Toggle to ignore all whitespace changes in diffs; bound to W
[tig.git] / tig.c
blobc7a3c3aca4f0a98d53e3926d4c51a07721626a89
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, "");
430 static inline void
431 toggle_ignore_space()
433 opt_ignore_space = !opt_ignore_space;
434 update_ignore_space_arg();
438 * Line-oriented content detection.
441 #define LINE_INFO \
442 LINE(DIFF_HEADER, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
443 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
444 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
445 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
446 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
447 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
448 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
449 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
450 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
451 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
452 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
453 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
454 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
455 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
456 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
457 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
458 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
459 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
460 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
461 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
462 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
463 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
464 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
465 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
466 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
467 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
468 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
469 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
470 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
471 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
472 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
473 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
474 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
475 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
476 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
477 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
478 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
479 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
480 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
481 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
482 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
483 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
484 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
485 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
486 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
487 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
488 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
489 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
490 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
491 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
492 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
493 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
494 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
495 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
496 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
497 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
498 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
499 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
500 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
501 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
502 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
503 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
504 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
505 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
506 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
507 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
508 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
509 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
510 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
511 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
512 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
513 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
515 enum line_type {
516 #define LINE(type, line, fg, bg, attr) \
517 LINE_##type
518 LINE_INFO,
519 LINE_NONE
520 #undef LINE
523 struct line_info {
524 const char *name; /* Option name. */
525 int namelen; /* Size of option name. */
526 const char *line; /* The start of line to match. */
527 int linelen; /* Size of string to match. */
528 int fg, bg, attr; /* Color and text attributes for the lines. */
531 static struct line_info line_info[] = {
532 #define LINE(type, line, fg, bg, attr) \
533 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
534 LINE_INFO
535 #undef LINE
538 static struct line_info *custom_color;
539 static size_t custom_colors;
541 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
543 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
544 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
546 /* Color IDs must be 1 or higher. [GH #15] */
547 #define COLOR_ID(line_type) ((line_type) + 1)
549 static enum line_type
550 get_line_type(const char *line)
552 int linelen = strlen(line);
553 enum line_type type;
555 for (type = 0; type < custom_colors; type++)
556 /* Case insensitive search matches Signed-off-by lines better. */
557 if (linelen >= custom_color[type].linelen &&
558 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
559 return TO_CUSTOM_COLOR_TYPE(type);
561 for (type = 0; type < ARRAY_SIZE(line_info); type++)
562 /* Case insensitive search matches Signed-off-by lines better. */
563 if (linelen >= line_info[type].linelen &&
564 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
565 return type;
567 return LINE_DEFAULT;
570 static enum line_type
571 get_line_type_from_ref(const struct ref *ref)
573 if (ref->head)
574 return LINE_MAIN_HEAD;
575 else if (ref->ltag)
576 return LINE_MAIN_LOCAL_TAG;
577 else if (ref->tag)
578 return LINE_MAIN_TAG;
579 else if (ref->tracked)
580 return LINE_MAIN_TRACKED;
581 else if (ref->remote)
582 return LINE_MAIN_REMOTE;
583 else if (ref->replace)
584 return LINE_MAIN_REPLACE;
586 return LINE_MAIN_REF;
589 static inline int
590 get_line_attr(enum line_type type)
592 if (type > LINE_NONE) {
593 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
594 return COLOR_PAIR(COLOR_ID(type)) | custom_color[TO_CUSTOM_COLOR_OFFSET(type)].attr;
596 assert(type < ARRAY_SIZE(line_info));
597 return COLOR_PAIR(COLOR_ID(type)) | line_info[type].attr;
600 static struct line_info *
601 get_line_info(const char *name)
603 size_t namelen = strlen(name);
604 enum line_type type;
606 for (type = 0; type < ARRAY_SIZE(line_info); type++)
607 if (enum_equals(line_info[type], name, namelen))
608 return &line_info[type];
610 return NULL;
613 static struct line_info *
614 add_custom_color(const char *quoted_line)
616 struct line_info *info;
617 char *line;
618 size_t linelen;
620 if (!realloc_custom_color(&custom_color, custom_colors, 1))
621 die("Failed to alloc custom line info");
623 linelen = strlen(quoted_line) - 1;
624 line = malloc(linelen);
625 if (!line)
626 return NULL;
628 strncpy(line, quoted_line + 1, linelen);
629 line[linelen - 1] = 0;
631 info = &custom_color[custom_colors++];
632 info->name = info->line = line;
633 info->namelen = info->linelen = strlen(line);
635 return info;
638 static void
639 init_line_info_color_pair(struct line_info *info, enum line_type type,
640 int default_bg, int default_fg)
642 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
643 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
645 init_pair(COLOR_ID(type), fg, bg);
648 static void
649 init_colors(void)
651 int default_bg = line_info[LINE_DEFAULT].bg;
652 int default_fg = line_info[LINE_DEFAULT].fg;
653 enum line_type type;
655 start_color();
657 if (assume_default_colors(default_fg, default_bg) == ERR) {
658 default_bg = COLOR_BLACK;
659 default_fg = COLOR_WHITE;
662 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
663 struct line_info *info = &line_info[type];
665 init_line_info_color_pair(info, type, default_bg, default_fg);
668 for (type = 0; type < custom_colors; type++) {
669 struct line_info *info = &custom_color[type];
671 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
672 default_bg, default_fg);
676 struct line {
677 enum line_type type;
679 /* State flags */
680 unsigned int selected:1;
681 unsigned int dirty:1;
682 unsigned int cleareol:1;
683 unsigned int other:16;
685 void *data; /* User data */
690 * Keys
693 struct keybinding {
694 int alias;
695 enum request request;
698 static struct keybinding default_keybindings[] = {
699 /* View switching */
700 { 'm', REQ_VIEW_MAIN },
701 { 'd', REQ_VIEW_DIFF },
702 { 'l', REQ_VIEW_LOG },
703 { 't', REQ_VIEW_TREE },
704 { 'f', REQ_VIEW_BLOB },
705 { 'B', REQ_VIEW_BLAME },
706 { 'H', REQ_VIEW_BRANCH },
707 { 'p', REQ_VIEW_PAGER },
708 { 'h', REQ_VIEW_HELP },
709 { 'S', REQ_VIEW_STATUS },
710 { 'c', REQ_VIEW_STAGE },
712 /* View manipulation */
713 { 'q', REQ_VIEW_CLOSE },
714 { KEY_TAB, REQ_VIEW_NEXT },
715 { KEY_RETURN, REQ_ENTER },
716 { KEY_UP, REQ_PREVIOUS },
717 { KEY_CTL('P'), REQ_PREVIOUS },
718 { KEY_DOWN, REQ_NEXT },
719 { KEY_CTL('N'), REQ_NEXT },
720 { 'R', REQ_REFRESH },
721 { KEY_F(5), REQ_REFRESH },
722 { 'O', REQ_MAXIMIZE },
723 { ',', REQ_PARENT },
725 /* View specific */
726 { 'u', REQ_STATUS_UPDATE },
727 { '!', REQ_STATUS_REVERT },
728 { 'M', REQ_STATUS_MERGE },
729 { '1', REQ_STAGE_UPDATE_LINE },
730 { '@', REQ_STAGE_NEXT },
731 { '[', REQ_DIFF_CONTEXT_DOWN },
732 { ']', REQ_DIFF_CONTEXT_UP },
734 /* Cursor navigation */
735 { 'k', REQ_MOVE_UP },
736 { 'j', REQ_MOVE_DOWN },
737 { KEY_HOME, REQ_MOVE_FIRST_LINE },
738 { KEY_END, REQ_MOVE_LAST_LINE },
739 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
740 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
741 { ' ', REQ_MOVE_PAGE_DOWN },
742 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
743 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
744 { 'b', REQ_MOVE_PAGE_UP },
745 { '-', REQ_MOVE_PAGE_UP },
747 /* Scrolling */
748 { '|', REQ_SCROLL_FIRST_COL },
749 { KEY_LEFT, REQ_SCROLL_LEFT },
750 { KEY_RIGHT, REQ_SCROLL_RIGHT },
751 { KEY_IC, REQ_SCROLL_LINE_UP },
752 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
753 { KEY_DC, REQ_SCROLL_LINE_DOWN },
754 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
755 { 'w', REQ_SCROLL_PAGE_UP },
756 { 's', REQ_SCROLL_PAGE_DOWN },
758 /* Searching */
759 { '/', REQ_SEARCH },
760 { '?', REQ_SEARCH_BACK },
761 { 'n', REQ_FIND_NEXT },
762 { 'N', REQ_FIND_PREV },
764 /* Misc */
765 { 'Q', REQ_QUIT },
766 { 'z', REQ_STOP_LOADING },
767 { 'v', REQ_SHOW_VERSION },
768 { 'r', REQ_SCREEN_REDRAW },
769 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
770 { 'o', REQ_OPTIONS },
771 { '.', REQ_TOGGLE_LINENO },
772 { 'D', REQ_TOGGLE_DATE },
773 { 'A', REQ_TOGGLE_AUTHOR },
774 { 'g', REQ_TOGGLE_REV_GRAPH },
775 { '~', REQ_TOGGLE_GRAPHIC },
776 { '#', REQ_TOGGLE_FILENAME },
777 { 'F', REQ_TOGGLE_REFS },
778 { 'I', REQ_TOGGLE_SORT_ORDER },
779 { 'i', REQ_TOGGLE_SORT_FIELD },
780 { 'W', REQ_TOGGLE_IGNORE_SPACE },
781 { ':', REQ_PROMPT },
782 { 'e', REQ_EDIT },
785 #define KEYMAP_ENUM(_) \
786 _(KEYMAP, GENERIC), \
787 _(KEYMAP, MAIN), \
788 _(KEYMAP, DIFF), \
789 _(KEYMAP, LOG), \
790 _(KEYMAP, TREE), \
791 _(KEYMAP, BLOB), \
792 _(KEYMAP, BLAME), \
793 _(KEYMAP, BRANCH), \
794 _(KEYMAP, PAGER), \
795 _(KEYMAP, HELP), \
796 _(KEYMAP, STATUS), \
797 _(KEYMAP, STAGE)
799 DEFINE_ENUM(keymap, KEYMAP_ENUM);
801 #define set_keymap(map, name) map_enum(map, keymap_map, name)
803 struct keybinding_table {
804 struct keybinding *data;
805 size_t size;
808 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_map)];
810 static void
811 add_keybinding(enum keymap keymap, enum request request, int key)
813 struct keybinding_table *table = &keybindings[keymap];
814 size_t i;
816 for (i = 0; i < table->size; i++) {
817 if (table->data[i].alias == key) {
818 table->data[i].request = request;
819 return;
823 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
824 if (!table->data)
825 die("Failed to allocate keybinding");
826 table->data[table->size].alias = key;
827 table->data[table->size++].request = request;
829 if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
830 int i;
832 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
833 if (default_keybindings[i].alias == key)
834 default_keybindings[i].request = REQ_NONE;
838 /* Looks for a key binding first in the given map, then in the generic map, and
839 * lastly in the default keybindings. */
840 static enum request
841 get_keybinding(enum keymap keymap, int key)
843 size_t i;
845 for (i = 0; i < keybindings[keymap].size; i++)
846 if (keybindings[keymap].data[i].alias == key)
847 return keybindings[keymap].data[i].request;
849 for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
850 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
851 return keybindings[KEYMAP_GENERIC].data[i].request;
853 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
854 if (default_keybindings[i].alias == key)
855 return default_keybindings[i].request;
857 return (enum request) key;
861 struct key {
862 const char *name;
863 int value;
866 static const struct key key_table[] = {
867 { "Enter", KEY_RETURN },
868 { "Space", ' ' },
869 { "Backspace", KEY_BACKSPACE },
870 { "Tab", KEY_TAB },
871 { "Escape", KEY_ESC },
872 { "Left", KEY_LEFT },
873 { "Right", KEY_RIGHT },
874 { "Up", KEY_UP },
875 { "Down", KEY_DOWN },
876 { "Insert", KEY_IC },
877 { "Delete", KEY_DC },
878 { "Hash", '#' },
879 { "Home", KEY_HOME },
880 { "End", KEY_END },
881 { "PageUp", KEY_PPAGE },
882 { "PageDown", KEY_NPAGE },
883 { "F1", KEY_F(1) },
884 { "F2", KEY_F(2) },
885 { "F3", KEY_F(3) },
886 { "F4", KEY_F(4) },
887 { "F5", KEY_F(5) },
888 { "F6", KEY_F(6) },
889 { "F7", KEY_F(7) },
890 { "F8", KEY_F(8) },
891 { "F9", KEY_F(9) },
892 { "F10", KEY_F(10) },
893 { "F11", KEY_F(11) },
894 { "F12", KEY_F(12) },
897 static int
898 get_key_value(const char *name)
900 int i;
902 for (i = 0; i < ARRAY_SIZE(key_table); i++)
903 if (!strcasecmp(key_table[i].name, name))
904 return key_table[i].value;
906 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
907 return (int)name[1] & 0x1f;
908 if (strlen(name) == 1 && isprint(*name))
909 return (int) *name;
910 return ERR;
913 static const char *
914 get_key_name(int key_value)
916 static char key_char[] = "'X'\0";
917 const char *seq = NULL;
918 int key;
920 for (key = 0; key < ARRAY_SIZE(key_table); key++)
921 if (key_table[key].value == key_value)
922 seq = key_table[key].name;
924 if (seq == NULL && key_value < 0x7f) {
925 char *s = key_char + 1;
927 if (key_value >= 0x20) {
928 *s++ = key_value;
929 } else {
930 *s++ = '^';
931 *s++ = 0x40 | (key_value & 0x1f);
933 *s++ = '\'';
934 *s++ = '\0';
935 seq = key_char;
938 return seq ? seq : "(no key)";
941 static bool
942 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
944 const char *sep = *pos > 0 ? ", " : "";
945 const char *keyname = get_key_name(keybinding->alias);
947 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
950 static bool
951 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
952 enum keymap keymap, bool all)
954 int i;
956 for (i = 0; i < keybindings[keymap].size; i++) {
957 if (keybindings[keymap].data[i].request == request) {
958 if (!append_key(buf, pos, &keybindings[keymap].data[i]))
959 return FALSE;
960 if (!all)
961 break;
965 return TRUE;
968 #define get_view_key(view, request) get_keys((view)->keymap, request, FALSE)
970 static const char *
971 get_keys(enum keymap keymap, enum request request, bool all)
973 static char buf[BUFSIZ];
974 size_t pos = 0;
975 int i;
977 buf[pos] = 0;
979 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
980 return "Too many keybindings!";
981 if (pos > 0 && !all)
982 return buf;
984 if (keymap != KEYMAP_GENERIC) {
985 /* Only the generic keymap includes the default keybindings when
986 * listing all keys. */
987 if (all)
988 return buf;
990 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
991 return "Too many keybindings!";
992 if (pos)
993 return buf;
996 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
997 if (default_keybindings[i].request == request) {
998 if (!append_key(buf, &pos, &default_keybindings[i]))
999 return "Too many keybindings!";
1000 if (!all)
1001 return buf;
1005 return buf;
1008 struct run_request {
1009 enum keymap keymap;
1010 int key;
1011 const char **argv;
1014 static struct run_request *run_request;
1015 static size_t run_requests;
1017 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1019 static enum request
1020 add_run_request(enum keymap keymap, int key, const char **argv)
1022 struct run_request *req;
1024 if (!realloc_run_requests(&run_request, run_requests, 1))
1025 return REQ_NONE;
1027 req = &run_request[run_requests];
1028 req->keymap = keymap;
1029 req->key = key;
1030 req->argv = NULL;
1032 if (!argv_copy(&req->argv, argv))
1033 return REQ_NONE;
1035 return REQ_NONE + ++run_requests;
1038 static struct run_request *
1039 get_run_request(enum request request)
1041 if (request <= REQ_NONE)
1042 return NULL;
1043 return &run_request[request - REQ_NONE - 1];
1046 static void
1047 add_builtin_run_requests(void)
1049 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1050 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1051 const char *commit[] = { "git", "commit", NULL };
1052 const char *gc[] = { "git", "gc", NULL };
1053 struct run_request reqs[] = {
1054 { KEYMAP_MAIN, 'C', cherry_pick },
1055 { KEYMAP_STATUS, 'C', commit },
1056 { KEYMAP_BRANCH, 'C', checkout },
1057 { KEYMAP_GENERIC, 'G', gc },
1059 int i;
1061 for (i = 0; i < ARRAY_SIZE(reqs); i++) {
1062 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
1064 if (req != reqs[i].key)
1065 continue;
1066 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
1067 if (req != REQ_NONE)
1068 add_keybinding(reqs[i].keymap, req, reqs[i].key);
1073 * User config file handling.
1076 #define OPT_ERR_INFO \
1077 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1078 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1079 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1080 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1081 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1082 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1083 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1084 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1085 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1086 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1087 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1088 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1089 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1090 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1091 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1092 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1093 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1094 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1096 enum option_code {
1097 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1098 OPT_ERR_INFO
1099 #undef OPT_ERR_
1100 OPT_OK
1103 static const char *option_errors[] = {
1104 #define OPT_ERR_(name, msg) msg
1105 OPT_ERR_INFO
1106 #undef OPT_ERR_
1109 static const struct enum_map color_map[] = {
1110 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1111 COLOR_MAP(DEFAULT),
1112 COLOR_MAP(BLACK),
1113 COLOR_MAP(BLUE),
1114 COLOR_MAP(CYAN),
1115 COLOR_MAP(GREEN),
1116 COLOR_MAP(MAGENTA),
1117 COLOR_MAP(RED),
1118 COLOR_MAP(WHITE),
1119 COLOR_MAP(YELLOW),
1122 static const struct enum_map attr_map[] = {
1123 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1124 ATTR_MAP(NORMAL),
1125 ATTR_MAP(BLINK),
1126 ATTR_MAP(BOLD),
1127 ATTR_MAP(DIM),
1128 ATTR_MAP(REVERSE),
1129 ATTR_MAP(STANDOUT),
1130 ATTR_MAP(UNDERLINE),
1133 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1135 static enum option_code
1136 parse_step(double *opt, const char *arg)
1138 *opt = atoi(arg);
1139 if (!strchr(arg, '%'))
1140 return OPT_OK;
1142 /* "Shift down" so 100% and 1 does not conflict. */
1143 *opt = (*opt - 1) / 100;
1144 if (*opt >= 1.0) {
1145 *opt = 0.99;
1146 return OPT_ERR_INVALID_STEP_VALUE;
1148 if (*opt < 0.0) {
1149 *opt = 1;
1150 return OPT_ERR_INVALID_STEP_VALUE;
1152 return OPT_OK;
1155 static enum option_code
1156 parse_int(int *opt, const char *arg, int min, int max)
1158 int value = atoi(arg);
1160 if (min <= value && value <= max) {
1161 *opt = value;
1162 return OPT_OK;
1165 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1168 static bool
1169 set_color(int *color, const char *name)
1171 if (map_enum(color, color_map, name))
1172 return TRUE;
1173 if (!prefixcmp(name, "color"))
1174 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1175 return FALSE;
1178 /* Wants: object fgcolor bgcolor [attribute] */
1179 static enum option_code
1180 option_color_command(int argc, const char *argv[])
1182 struct line_info *info;
1184 if (argc < 3)
1185 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1187 if (*argv[0] == '"' || *argv[0] == '\'') {
1188 info = add_custom_color(argv[0]);
1189 } else {
1190 info = get_line_info(argv[0]);
1192 if (!info) {
1193 static const struct enum_map obsolete[] = {
1194 ENUM_MAP("main-delim", LINE_DELIMITER),
1195 ENUM_MAP("main-date", LINE_DATE),
1196 ENUM_MAP("main-author", LINE_AUTHOR),
1198 int index;
1200 if (!map_enum(&index, obsolete, argv[0]))
1201 return OPT_ERR_UNKNOWN_COLOR_NAME;
1202 info = &line_info[index];
1205 if (!set_color(&info->fg, argv[1]) ||
1206 !set_color(&info->bg, argv[2]))
1207 return OPT_ERR_UNKNOWN_COLOR;
1209 info->attr = 0;
1210 while (argc-- > 3) {
1211 int attr;
1213 if (!set_attribute(&attr, argv[argc]))
1214 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1215 info->attr |= attr;
1218 return OPT_OK;
1221 static enum option_code
1222 parse_bool(bool *opt, const char *arg)
1224 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1225 ? TRUE : FALSE;
1226 return OPT_OK;
1229 static enum option_code
1230 parse_enum_do(unsigned int *opt, const char *arg,
1231 const struct enum_map *map, size_t map_size)
1233 bool is_true;
1235 assert(map_size > 1);
1237 if (map_enum_do(map, map_size, (int *) opt, arg))
1238 return OPT_OK;
1240 parse_bool(&is_true, arg);
1241 *opt = is_true ? map[1].value : map[0].value;
1242 return OPT_OK;
1245 #define parse_enum(opt, arg, map) \
1246 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1248 static enum option_code
1249 parse_string(char *opt, const char *arg, size_t optsize)
1251 int arglen = strlen(arg);
1253 switch (arg[0]) {
1254 case '\"':
1255 case '\'':
1256 if (arglen == 1 || arg[arglen - 1] != arg[0])
1257 return OPT_ERR_UNMATCHED_QUOTATION;
1258 arg += 1; arglen -= 2;
1259 default:
1260 string_ncopy_do(opt, optsize, arg, arglen);
1261 return OPT_OK;
1265 static enum option_code
1266 parse_args(const char ***args, const char *argv[])
1268 if (*args == NULL && !argv_copy(args, argv))
1269 return OPT_ERR_OUT_OF_MEMORY;
1270 return OPT_OK;
1273 /* Wants: name = value */
1274 static enum option_code
1275 option_set_command(int argc, const char *argv[])
1277 if (argc < 3)
1278 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1280 if (strcmp(argv[1], "="))
1281 return OPT_ERR_NO_VALUE_ASSIGNED;
1283 if (!strcmp(argv[0], "blame-options"))
1284 return parse_args(&opt_blame_argv, argv + 2);
1286 if (argc != 3)
1287 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1289 if (!strcmp(argv[0], "show-author"))
1290 return parse_enum(&opt_author, argv[2], author_map);
1292 if (!strcmp(argv[0], "show-date"))
1293 return parse_enum(&opt_date, argv[2], date_map);
1295 if (!strcmp(argv[0], "show-rev-graph"))
1296 return parse_bool(&opt_rev_graph, argv[2]);
1298 if (!strcmp(argv[0], "show-refs"))
1299 return parse_bool(&opt_show_refs, argv[2]);
1301 if (!strcmp(argv[0], "show-notes")) {
1302 int res;
1304 strcpy(opt_notes_arg, "--notes=");
1305 res = parse_string(opt_notes_arg + 8, argv[2],
1306 sizeof(opt_notes_arg) - 8);
1307 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1308 opt_notes_arg[7] = '\0';
1309 return res;
1312 if (!strcmp(argv[0], "show-line-numbers"))
1313 return parse_bool(&opt_line_number, argv[2]);
1315 if (!strcmp(argv[0], "line-graphics"))
1316 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1318 if (!strcmp(argv[0], "line-number-interval"))
1319 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1321 if (!strcmp(argv[0], "author-width"))
1322 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1324 if (!strcmp(argv[0], "filename-width"))
1325 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1327 if (!strcmp(argv[0], "show-filename"))
1328 return parse_enum(&opt_filename, argv[2], filename_map);
1330 if (!strcmp(argv[0], "horizontal-scroll"))
1331 return parse_step(&opt_hscroll, argv[2]);
1333 if (!strcmp(argv[0], "split-view-height"))
1334 return parse_step(&opt_scale_split_view, argv[2]);
1336 if (!strcmp(argv[0], "tab-size"))
1337 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1339 if (!strcmp(argv[0], "diff-context")) {
1340 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1342 if (code == OPT_OK)
1343 update_diff_context_arg(opt_diff_context);
1344 return code;
1347 if (!strcmp(argv[0], "ignore-space")) {
1348 enum option_code code = parse_bool(&opt_ignore_space, argv[2]);
1350 if (code == OPT_OK)
1351 update_ignore_space_arg();
1352 return code;
1355 if (!strcmp(argv[0], "commit-encoding"))
1356 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1358 if (!strcmp(argv[0], "status-untracked-dirs"))
1359 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1361 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1364 /* Wants: mode request key */
1365 static enum option_code
1366 option_bind_command(int argc, const char *argv[])
1368 enum request request;
1369 int keymap = -1;
1370 int key;
1372 if (argc < 3)
1373 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1375 if (!set_keymap(&keymap, argv[0]))
1376 return OPT_ERR_UNKNOWN_KEY_MAP;
1378 key = get_key_value(argv[1]);
1379 if (key == ERR)
1380 return OPT_ERR_UNKNOWN_KEY;
1382 request = get_request(argv[2]);
1383 if (request == REQ_UNKNOWN) {
1384 static const struct enum_map obsolete[] = {
1385 ENUM_MAP("cherry-pick", REQ_NONE),
1386 ENUM_MAP("screen-resize", REQ_NONE),
1387 ENUM_MAP("tree-parent", REQ_PARENT),
1389 int alias;
1391 if (map_enum(&alias, obsolete, argv[2])) {
1392 if (alias != REQ_NONE)
1393 add_keybinding(keymap, alias, key);
1394 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1397 if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1398 request = add_run_request(keymap, key, argv + 2);
1399 if (request == REQ_UNKNOWN)
1400 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1402 add_keybinding(keymap, request, key);
1404 return OPT_OK;
1408 static enum option_code load_option_file(const char *path);
1410 static enum option_code
1411 option_source_command(int argc, const char *argv[])
1413 if (argc < 1)
1414 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1416 return load_option_file(argv[0]);
1419 static enum option_code
1420 set_option(const char *opt, char *value)
1422 const char *argv[SIZEOF_ARG];
1423 int argc = 0;
1425 if (!argv_from_string(argv, &argc, value))
1426 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1428 if (!strcmp(opt, "color"))
1429 return option_color_command(argc, argv);
1431 if (!strcmp(opt, "set"))
1432 return option_set_command(argc, argv);
1434 if (!strcmp(opt, "bind"))
1435 return option_bind_command(argc, argv);
1437 if (!strcmp(opt, "source"))
1438 return option_source_command(argc, argv);
1440 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1443 struct config_state {
1444 const char *path;
1445 int lineno;
1446 bool errors;
1449 static int
1450 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1452 struct config_state *config = data;
1453 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1455 config->lineno++;
1457 /* Check for comment markers, since read_properties() will
1458 * only ensure opt and value are split at first " \t". */
1459 optlen = strcspn(opt, "#");
1460 if (optlen == 0)
1461 return OK;
1463 if (opt[optlen] == 0) {
1464 /* Look for comment endings in the value. */
1465 size_t len = strcspn(value, "#");
1467 if (len < valuelen) {
1468 valuelen = len;
1469 value[valuelen] = 0;
1472 status = set_option(opt, value);
1475 if (status != OPT_OK) {
1476 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1477 option_errors[status], (int) optlen, opt);
1478 config->errors = TRUE;
1481 /* Always keep going if errors are encountered. */
1482 return OK;
1485 static enum option_code
1486 load_option_file(const char *path)
1488 struct config_state config = { path, 0, FALSE };
1489 struct io io;
1491 /* Do not read configuration from stdin if set to "" */
1492 if (!path || !strlen(path))
1493 return OPT_OK;
1495 /* It's OK that the file doesn't exist. */
1496 if (!io_open(&io, "%s", path))
1497 return OPT_ERR_FILE_DOES_NOT_EXIST;
1499 if (io_load(&io, " \t", read_option, &config) == ERR ||
1500 config.errors == TRUE)
1501 warn("Errors while loading %s.", path);
1502 return OPT_OK;
1505 static int
1506 load_options(void)
1508 const char *home = getenv("HOME");
1509 const char *tigrc_user = getenv("TIGRC_USER");
1510 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1511 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1512 char buf[SIZEOF_STR];
1514 if (!tigrc_system)
1515 tigrc_system = SYSCONFDIR "/tigrc";
1516 load_option_file(tigrc_system);
1518 if (!tigrc_user) {
1519 if (!home || !string_format(buf, "%s/.tigrc", home))
1520 return ERR;
1521 tigrc_user = buf;
1523 load_option_file(tigrc_user);
1525 /* Add _after_ loading config files to avoid adding run requests
1526 * that conflict with keybindings. */
1527 add_builtin_run_requests();
1529 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1530 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1531 int argc = 0;
1533 if (!string_format(buf, "%s", tig_diff_opts) ||
1534 !argv_from_string(diff_opts, &argc, buf))
1535 die("TIG_DIFF_OPTS contains too many arguments");
1536 else if (!argv_copy(&opt_diff_argv, diff_opts))
1537 die("Failed to format TIG_DIFF_OPTS arguments");
1540 return OK;
1545 * The viewer
1548 struct view;
1549 struct view_ops;
1551 /* The display array of active views and the index of the current view. */
1552 static struct view *display[2];
1553 static WINDOW *display_win[2];
1554 static WINDOW *display_title[2];
1555 static unsigned int current_view;
1557 #define foreach_displayed_view(view, i) \
1558 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1560 #define displayed_views() (display[1] != NULL ? 2 : 1)
1562 /* Current head and commit ID */
1563 static char ref_blob[SIZEOF_REF] = "";
1564 static char ref_commit[SIZEOF_REF] = "HEAD";
1565 static char ref_head[SIZEOF_REF] = "HEAD";
1566 static char ref_branch[SIZEOF_REF] = "";
1568 enum view_flag {
1569 VIEW_NO_FLAGS = 0,
1570 VIEW_ALWAYS_LINENO = 1 << 0,
1571 VIEW_CUSTOM_STATUS = 1 << 1,
1572 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1573 VIEW_ADD_PAGER_REFS = 1 << 3,
1574 VIEW_OPEN_DIFF = 1 << 4,
1575 VIEW_NO_REF = 1 << 5,
1576 VIEW_NO_GIT_DIR = 1 << 6,
1579 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1581 struct view {
1582 const char *name; /* View name */
1583 const char *id; /* Points to either of ref_{head,commit,blob} */
1585 struct view_ops *ops; /* View operations */
1587 enum keymap keymap; /* What keymap does this view have */
1589 char ref[SIZEOF_REF]; /* Hovered commit reference */
1590 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1592 int height, width; /* The width and height of the main window */
1593 WINDOW *win; /* The main window */
1595 /* Navigation */
1596 unsigned long offset; /* Offset of the window top */
1597 unsigned long yoffset; /* Offset from the window side. */
1598 unsigned long lineno; /* Current line number */
1599 unsigned long p_offset; /* Previous offset of the window top */
1600 unsigned long p_yoffset;/* Previous offset from the window side */
1601 unsigned long p_lineno; /* Previous current line number */
1602 bool p_restore; /* Should the previous position be restored. */
1604 /* Searching */
1605 char grep[SIZEOF_STR]; /* Search string */
1606 regex_t *regex; /* Pre-compiled regexp */
1608 /* If non-NULL, points to the view that opened this view. If this view
1609 * is closed tig will switch back to the parent view. */
1610 struct view *parent;
1611 struct view *prev;
1613 /* Buffering */
1614 size_t lines; /* Total number of lines */
1615 struct line *line; /* Line index */
1616 unsigned int digits; /* Number of digits in the lines member. */
1618 /* Drawing */
1619 struct line *curline; /* Line currently being drawn. */
1620 enum line_type curtype; /* Attribute currently used for drawing. */
1621 unsigned long col; /* Column when drawing. */
1622 bool has_scrolled; /* View was scrolled. */
1624 /* Loading */
1625 const char **argv; /* Shell command arguments. */
1626 const char *dir; /* Directory from which to execute. */
1627 struct io io;
1628 struct io *pipe;
1629 time_t start_time;
1630 time_t update_secs;
1632 /* Private data */
1633 void *private;
1636 enum open_flags {
1637 OPEN_DEFAULT = 0, /* Use default view switching. */
1638 OPEN_SPLIT = 1, /* Split current view. */
1639 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1640 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1641 OPEN_PREPARED = 32, /* Open already prepared command. */
1642 OPEN_EXTRA = 64, /* Open extra data from command. */
1645 struct view_ops {
1646 /* What type of content being displayed. Used in the title bar. */
1647 const char *type;
1648 /* Flags to control the view behavior. */
1649 enum view_flag flags;
1650 /* Size of private data. */
1651 size_t private_size;
1652 /* Open and reads in all view content. */
1653 bool (*open)(struct view *view, enum open_flags flags);
1654 /* Read one line; updates view->line. */
1655 bool (*read)(struct view *view, char *data);
1656 /* Draw one line; @lineno must be < view->height. */
1657 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1658 /* Depending on view handle a special requests. */
1659 enum request (*request)(struct view *view, enum request request, struct line *line);
1660 /* Search for regexp in a line. */
1661 bool (*grep)(struct view *view, struct line *line);
1662 /* Select line */
1663 void (*select)(struct view *view, struct line *line);
1666 #define VIEW_OPS(id, name, ref) name##_ops
1667 static struct view_ops VIEW_INFO(VIEW_OPS);
1669 static struct view views[] = {
1670 #define VIEW_DATA(id, name, ref) \
1671 { #name, ref, &name##_ops, KEYMAP_##id }
1672 VIEW_INFO(VIEW_DATA)
1675 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1677 #define foreach_view(view, i) \
1678 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1680 #define view_is_displayed(view) \
1681 (view == display[0] || view == display[1])
1683 static enum request
1684 view_request(struct view *view, enum request request)
1686 if (!view || !view->lines)
1687 return request;
1688 return view->ops->request(view, request, &view->line[view->lineno]);
1693 * View drawing.
1696 static inline void
1697 set_view_attr(struct view *view, enum line_type type)
1699 if (!view->curline->selected && view->curtype != type) {
1700 (void) wattrset(view->win, get_line_attr(type));
1701 wchgat(view->win, -1, 0, COLOR_ID(type), NULL);
1702 view->curtype = type;
1706 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1708 static bool
1709 draw_chars(struct view *view, enum line_type type, const char *string,
1710 int max_len, bool use_tilde)
1712 static char out_buffer[BUFSIZ * 2];
1713 int len = 0;
1714 int col = 0;
1715 int trimmed = FALSE;
1716 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1718 if (max_len <= 0)
1719 return VIEW_MAX_LEN(view) <= 0;
1721 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1723 set_view_attr(view, type);
1724 if (len > 0) {
1725 if (opt_iconv_out != ICONV_NONE) {
1726 size_t inlen = len + 1;
1727 char *instr = calloc(1, inlen);
1728 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1729 if (!instr)
1730 return VIEW_MAX_LEN(view) <= 0;
1732 strncpy(instr, string, len);
1734 char *outbuf = out_buffer;
1735 size_t outlen = sizeof(out_buffer);
1737 size_t ret;
1739 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1740 if (ret != (size_t) -1) {
1741 string = out_buffer;
1742 len = sizeof(out_buffer) - outlen;
1744 free(instr);
1747 waddnstr(view->win, string, len);
1749 if (trimmed && use_tilde) {
1750 set_view_attr(view, LINE_DELIMITER);
1751 waddch(view->win, '~');
1752 col++;
1756 view->col += col;
1757 return VIEW_MAX_LEN(view) <= 0;
1760 static bool
1761 draw_space(struct view *view, enum line_type type, int max, int spaces)
1763 static char space[] = " ";
1765 spaces = MIN(max, spaces);
1767 while (spaces > 0) {
1768 int len = MIN(spaces, sizeof(space) - 1);
1770 if (draw_chars(view, type, space, len, FALSE))
1771 return TRUE;
1772 spaces -= len;
1775 return VIEW_MAX_LEN(view) <= 0;
1778 static bool
1779 draw_text(struct view *view, enum line_type type, const char *string)
1781 char text[SIZEOF_STR];
1783 do {
1784 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1786 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1787 return TRUE;
1788 string += pos;
1789 } while (*string);
1791 return VIEW_MAX_LEN(view) <= 0;
1794 static bool
1795 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
1797 char text[SIZEOF_STR];
1798 int retval;
1800 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
1801 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
1804 static bool
1805 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1807 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1808 int max = VIEW_MAX_LEN(view);
1809 int i;
1811 if (max < size)
1812 size = max;
1814 set_view_attr(view, type);
1815 /* Using waddch() instead of waddnstr() ensures that
1816 * they'll be rendered correctly for the cursor line. */
1817 for (i = skip; i < size; i++)
1818 waddch(view->win, graphic[i]);
1820 view->col += size;
1821 if (separator) {
1822 if (size < max && skip <= size)
1823 waddch(view->win, ' ');
1824 view->col++;
1827 return VIEW_MAX_LEN(view) <= 0;
1830 static bool
1831 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1833 int max = MIN(VIEW_MAX_LEN(view), len);
1834 int col = view->col;
1836 if (!text)
1837 return draw_space(view, type, max, max);
1839 return draw_chars(view, type, text, max - 1, trim)
1840 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1843 static bool
1844 draw_date(struct view *view, struct time *time)
1846 const char *date = mkdate(time, opt_date);
1847 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1849 if (opt_date == DATE_NO)
1850 return FALSE;
1852 return draw_field(view, LINE_DATE, date, cols, FALSE);
1855 static bool
1856 draw_author(struct view *view, const char *author)
1858 bool trim = author_trim(opt_author_cols);
1859 const char *text = mkauthor(author, opt_author_cols, opt_author);
1861 if (opt_author == AUTHOR_NO)
1862 return FALSE;
1864 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1867 static bool
1868 draw_filename(struct view *view, const char *filename, bool auto_enabled)
1870 bool trim = filename && strlen(filename) >= opt_filename_cols;
1872 if (opt_filename == FILENAME_NO)
1873 return FALSE;
1875 if (opt_filename == FILENAME_AUTO && !auto_enabled)
1876 return FALSE;
1878 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
1881 static bool
1882 draw_mode(struct view *view, mode_t mode)
1884 const char *str = mkmode(mode);
1886 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1889 static bool
1890 draw_lineno(struct view *view, unsigned int lineno)
1892 char number[10];
1893 int digits3 = view->digits < 3 ? 3 : view->digits;
1894 int max = MIN(VIEW_MAX_LEN(view), digits3);
1895 char *text = NULL;
1896 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1898 lineno += view->offset + 1;
1899 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1900 static char fmt[] = "%1ld";
1902 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1903 if (string_format(number, fmt, lineno))
1904 text = number;
1906 if (text)
1907 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1908 else
1909 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1910 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1913 static bool
1914 draw_refs(struct view *view, struct ref_list *refs)
1916 size_t i;
1918 if (!opt_show_refs || !refs)
1919 return FALSE;
1921 for (i = 0; i < refs->size; i++) {
1922 struct ref *ref = refs->refs[i];
1923 enum line_type type = get_line_type_from_ref(ref);
1925 if (draw_formatted(view, type, "[%s]", ref->name))
1926 return TRUE;
1928 if (draw_text(view, LINE_DEFAULT, " "))
1929 return TRUE;
1932 return FALSE;
1935 static bool
1936 draw_view_line(struct view *view, unsigned int lineno)
1938 struct line *line;
1939 bool selected = (view->offset + lineno == view->lineno);
1941 assert(view_is_displayed(view));
1943 if (view->offset + lineno >= view->lines)
1944 return FALSE;
1946 line = &view->line[view->offset + lineno];
1948 wmove(view->win, lineno, 0);
1949 if (line->cleareol)
1950 wclrtoeol(view->win);
1951 view->col = 0;
1952 view->curline = line;
1953 view->curtype = LINE_NONE;
1954 line->selected = FALSE;
1955 line->dirty = line->cleareol = 0;
1957 if (selected) {
1958 set_view_attr(view, LINE_CURSOR);
1959 line->selected = TRUE;
1960 view->ops->select(view, line);
1963 return view->ops->draw(view, line, lineno);
1966 static void
1967 redraw_view_dirty(struct view *view)
1969 bool dirty = FALSE;
1970 int lineno;
1972 for (lineno = 0; lineno < view->height; lineno++) {
1973 if (view->offset + lineno >= view->lines)
1974 break;
1975 if (!view->line[view->offset + lineno].dirty)
1976 continue;
1977 dirty = TRUE;
1978 if (!draw_view_line(view, lineno))
1979 break;
1982 if (!dirty)
1983 return;
1984 wnoutrefresh(view->win);
1987 static void
1988 redraw_view_from(struct view *view, int lineno)
1990 assert(0 <= lineno && lineno < view->height);
1992 for (; lineno < view->height; lineno++) {
1993 if (!draw_view_line(view, lineno))
1994 break;
1997 wnoutrefresh(view->win);
2000 static void
2001 redraw_view(struct view *view)
2003 werase(view->win);
2004 redraw_view_from(view, 0);
2008 static void
2009 update_view_title(struct view *view)
2011 char buf[SIZEOF_STR];
2012 char state[SIZEOF_STR];
2013 size_t bufpos = 0, statelen = 0;
2014 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2016 assert(view_is_displayed(view));
2018 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view->lines) {
2019 unsigned int view_lines = view->offset + view->height;
2020 unsigned int lines = view->lines
2021 ? MIN(view_lines, view->lines) * 100 / view->lines
2022 : 0;
2024 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
2025 view->ops->type,
2026 view->lineno + 1,
2027 view->lines,
2028 lines);
2032 if (view->pipe) {
2033 time_t secs = time(NULL) - view->start_time;
2035 /* Three git seconds are a long time ... */
2036 if (secs > 2)
2037 string_format_from(state, &statelen, " loading %lds", secs);
2040 string_format_from(buf, &bufpos, "[%s]", view->name);
2041 if (*view->ref && bufpos < view->width) {
2042 size_t refsize = strlen(view->ref);
2043 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2045 if (minsize < view->width)
2046 refsize = view->width - minsize + 7;
2047 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2050 if (statelen && bufpos < view->width) {
2051 string_format_from(buf, &bufpos, "%s", state);
2054 if (view == display[current_view])
2055 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2056 else
2057 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2059 mvwaddnstr(window, 0, 0, buf, bufpos);
2060 wclrtoeol(window);
2061 wnoutrefresh(window);
2064 static int
2065 apply_step(double step, int value)
2067 if (step >= 1)
2068 return (int) step;
2069 value *= step + 0.01;
2070 return value ? value : 1;
2073 static void
2074 resize_display(void)
2076 int offset, i;
2077 struct view *base = display[0];
2078 struct view *view = display[1] ? display[1] : display[0];
2080 /* Setup window dimensions */
2082 getmaxyx(stdscr, base->height, base->width);
2084 /* Make room for the status window. */
2085 base->height -= 1;
2087 if (view != base) {
2088 /* Horizontal split. */
2089 view->width = base->width;
2090 view->height = apply_step(opt_scale_split_view, base->height);
2091 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2092 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2093 base->height -= view->height;
2095 /* Make room for the title bar. */
2096 view->height -= 1;
2099 /* Make room for the title bar. */
2100 base->height -= 1;
2102 offset = 0;
2104 foreach_displayed_view (view, i) {
2105 if (!display_win[i]) {
2106 display_win[i] = newwin(view->height, view->width, offset, 0);
2107 if (!display_win[i])
2108 die("Failed to create %s view", view->name);
2110 scrollok(display_win[i], FALSE);
2112 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2113 if (!display_title[i])
2114 die("Failed to create title window");
2116 } else {
2117 wresize(display_win[i], view->height, view->width);
2118 mvwin(display_win[i], offset, 0);
2119 mvwin(display_title[i], offset + view->height, 0);
2122 view->win = display_win[i];
2124 offset += view->height + 1;
2128 static void
2129 redraw_display(bool clear)
2131 struct view *view;
2132 int i;
2134 foreach_displayed_view (view, i) {
2135 if (clear)
2136 wclear(view->win);
2137 redraw_view(view);
2138 update_view_title(view);
2144 * Option management
2147 #define TOGGLE_MENU \
2148 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2149 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2150 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2151 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2152 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2153 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2154 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL)
2156 static void
2157 toggle_option(enum request request)
2159 const struct {
2160 enum request request;
2161 const struct enum_map *map;
2162 size_t map_size;
2163 } data[] = {
2164 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2165 TOGGLE_MENU
2166 #undef TOGGLE_
2168 const struct menu_item menu[] = {
2169 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2170 TOGGLE_MENU
2171 #undef TOGGLE_
2172 { 0 }
2174 int i = 0;
2176 if (request == REQ_OPTIONS) {
2177 if (!prompt_menu("Toggle option", menu, &i))
2178 return;
2179 } else {
2180 while (i < ARRAY_SIZE(data) && data[i].request != request)
2181 i++;
2182 if (i >= ARRAY_SIZE(data))
2183 die("Invalid request (%d)", request);
2186 if (data[i].map != NULL) {
2187 unsigned int *opt = menu[i].data;
2189 *opt = (*opt + 1) % data[i].map_size;
2190 redraw_display(FALSE);
2191 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2193 } else {
2194 bool *option = menu[i].data;
2196 *option = !*option;
2197 redraw_display(FALSE);
2198 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2202 static void
2203 maximize_view(struct view *view, bool redraw)
2205 memset(display, 0, sizeof(display));
2206 current_view = 0;
2207 display[current_view] = view;
2208 resize_display();
2209 if (redraw) {
2210 redraw_display(FALSE);
2211 report("");
2217 * Navigation
2220 static bool
2221 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2223 if (lineno >= view->lines)
2224 lineno = view->lines > 0 ? view->lines - 1 : 0;
2226 if (offset > lineno || offset + view->height <= lineno) {
2227 unsigned long half = view->height / 2;
2229 if (lineno > half)
2230 offset = lineno - half;
2231 else
2232 offset = 0;
2235 if (offset != view->offset || lineno != view->lineno) {
2236 view->offset = offset;
2237 view->lineno = lineno;
2238 return TRUE;
2241 return FALSE;
2244 /* Scrolling backend */
2245 static void
2246 do_scroll_view(struct view *view, int lines)
2248 bool redraw_current_line = FALSE;
2250 /* The rendering expects the new offset. */
2251 view->offset += lines;
2253 assert(0 <= view->offset && view->offset < view->lines);
2254 assert(lines);
2256 /* Move current line into the view. */
2257 if (view->lineno < view->offset) {
2258 view->lineno = view->offset;
2259 redraw_current_line = TRUE;
2260 } else if (view->lineno >= view->offset + view->height) {
2261 view->lineno = view->offset + view->height - 1;
2262 redraw_current_line = TRUE;
2265 assert(view->offset <= view->lineno && view->lineno < view->lines);
2267 /* Redraw the whole screen if scrolling is pointless. */
2268 if (view->height < ABS(lines)) {
2269 redraw_view(view);
2271 } else {
2272 int line = lines > 0 ? view->height - lines : 0;
2273 int end = line + ABS(lines);
2275 scrollok(view->win, TRUE);
2276 wscrl(view->win, lines);
2277 scrollok(view->win, FALSE);
2279 while (line < end && draw_view_line(view, line))
2280 line++;
2282 if (redraw_current_line)
2283 draw_view_line(view, view->lineno - view->offset);
2284 wnoutrefresh(view->win);
2287 view->has_scrolled = TRUE;
2288 report("");
2291 /* Scroll frontend */
2292 static void
2293 scroll_view(struct view *view, enum request request)
2295 int lines = 1;
2297 assert(view_is_displayed(view));
2299 switch (request) {
2300 case REQ_SCROLL_FIRST_COL:
2301 view->yoffset = 0;
2302 redraw_view_from(view, 0);
2303 report("");
2304 return;
2305 case REQ_SCROLL_LEFT:
2306 if (view->yoffset == 0) {
2307 report("Cannot scroll beyond the first column");
2308 return;
2310 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2311 view->yoffset = 0;
2312 else
2313 view->yoffset -= apply_step(opt_hscroll, view->width);
2314 redraw_view_from(view, 0);
2315 report("");
2316 return;
2317 case REQ_SCROLL_RIGHT:
2318 view->yoffset += apply_step(opt_hscroll, view->width);
2319 redraw_view(view);
2320 report("");
2321 return;
2322 case REQ_SCROLL_PAGE_DOWN:
2323 lines = view->height;
2324 case REQ_SCROLL_LINE_DOWN:
2325 if (view->offset + lines > view->lines)
2326 lines = view->lines - view->offset;
2328 if (lines == 0 || view->offset + view->height >= view->lines) {
2329 report("Cannot scroll beyond the last line");
2330 return;
2332 break;
2334 case REQ_SCROLL_PAGE_UP:
2335 lines = view->height;
2336 case REQ_SCROLL_LINE_UP:
2337 if (lines > view->offset)
2338 lines = view->offset;
2340 if (lines == 0) {
2341 report("Cannot scroll beyond the first line");
2342 return;
2345 lines = -lines;
2346 break;
2348 default:
2349 die("request %d not handled in switch", request);
2352 do_scroll_view(view, lines);
2355 /* Cursor moving */
2356 static void
2357 move_view(struct view *view, enum request request)
2359 int scroll_steps = 0;
2360 int steps;
2362 switch (request) {
2363 case REQ_MOVE_FIRST_LINE:
2364 steps = -view->lineno;
2365 break;
2367 case REQ_MOVE_LAST_LINE:
2368 steps = view->lines - view->lineno - 1;
2369 break;
2371 case REQ_MOVE_PAGE_UP:
2372 steps = view->height > view->lineno
2373 ? -view->lineno : -view->height;
2374 break;
2376 case REQ_MOVE_PAGE_DOWN:
2377 steps = view->lineno + view->height >= view->lines
2378 ? view->lines - view->lineno - 1 : view->height;
2379 break;
2381 case REQ_MOVE_UP:
2382 steps = -1;
2383 break;
2385 case REQ_MOVE_DOWN:
2386 steps = 1;
2387 break;
2389 default:
2390 die("request %d not handled in switch", request);
2393 if (steps <= 0 && view->lineno == 0) {
2394 report("Cannot move beyond the first line");
2395 return;
2397 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2398 report("Cannot move beyond the last line");
2399 return;
2402 /* Move the current line */
2403 view->lineno += steps;
2404 assert(0 <= view->lineno && view->lineno < view->lines);
2406 /* Check whether the view needs to be scrolled */
2407 if (view->lineno < view->offset ||
2408 view->lineno >= view->offset + view->height) {
2409 scroll_steps = steps;
2410 if (steps < 0 && -steps > view->offset) {
2411 scroll_steps = -view->offset;
2413 } else if (steps > 0) {
2414 if (view->lineno == view->lines - 1 &&
2415 view->lines > view->height) {
2416 scroll_steps = view->lines - view->offset - 1;
2417 if (scroll_steps >= view->height)
2418 scroll_steps -= view->height - 1;
2423 if (!view_is_displayed(view)) {
2424 view->offset += scroll_steps;
2425 assert(0 <= view->offset && view->offset < view->lines);
2426 view->ops->select(view, &view->line[view->lineno]);
2427 return;
2430 /* Repaint the old "current" line if we be scrolling */
2431 if (ABS(steps) < view->height)
2432 draw_view_line(view, view->lineno - steps - view->offset);
2434 if (scroll_steps) {
2435 do_scroll_view(view, scroll_steps);
2436 return;
2439 /* Draw the current line */
2440 draw_view_line(view, view->lineno - view->offset);
2442 wnoutrefresh(view->win);
2443 report("");
2448 * Searching
2451 static void search_view(struct view *view, enum request request);
2453 static bool
2454 grep_text(struct view *view, const char *text[])
2456 regmatch_t pmatch;
2457 size_t i;
2459 for (i = 0; text[i]; i++)
2460 if (*text[i] &&
2461 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2462 return TRUE;
2463 return FALSE;
2466 static void
2467 select_view_line(struct view *view, unsigned long lineno)
2469 unsigned long old_lineno = view->lineno;
2470 unsigned long old_offset = view->offset;
2472 if (goto_view_line(view, view->offset, lineno)) {
2473 if (view_is_displayed(view)) {
2474 if (old_offset != view->offset) {
2475 redraw_view(view);
2476 } else {
2477 draw_view_line(view, old_lineno - view->offset);
2478 draw_view_line(view, view->lineno - view->offset);
2479 wnoutrefresh(view->win);
2481 } else {
2482 view->ops->select(view, &view->line[view->lineno]);
2487 static void
2488 find_next(struct view *view, enum request request)
2490 unsigned long lineno = view->lineno;
2491 int direction;
2493 if (!*view->grep) {
2494 if (!*opt_search)
2495 report("No previous search");
2496 else
2497 search_view(view, request);
2498 return;
2501 switch (request) {
2502 case REQ_SEARCH:
2503 case REQ_FIND_NEXT:
2504 direction = 1;
2505 break;
2507 case REQ_SEARCH_BACK:
2508 case REQ_FIND_PREV:
2509 direction = -1;
2510 break;
2512 default:
2513 return;
2516 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2517 lineno += direction;
2519 /* Note, lineno is unsigned long so will wrap around in which case it
2520 * will become bigger than view->lines. */
2521 for (; lineno < view->lines; lineno += direction) {
2522 if (view->ops->grep(view, &view->line[lineno])) {
2523 select_view_line(view, lineno);
2524 report("Line %ld matches '%s'", lineno + 1, view->grep);
2525 return;
2529 report("No match found for '%s'", view->grep);
2532 static void
2533 search_view(struct view *view, enum request request)
2535 int regex_err;
2537 if (view->regex) {
2538 regfree(view->regex);
2539 *view->grep = 0;
2540 } else {
2541 view->regex = calloc(1, sizeof(*view->regex));
2542 if (!view->regex)
2543 return;
2546 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2547 if (regex_err != 0) {
2548 char buf[SIZEOF_STR] = "unknown error";
2550 regerror(regex_err, view->regex, buf, sizeof(buf));
2551 report("Search failed: %s", buf);
2552 return;
2555 string_copy(view->grep, opt_search);
2557 find_next(view, request);
2561 * Incremental updating
2564 static void
2565 reset_view(struct view *view)
2567 int i;
2569 for (i = 0; i < view->lines; i++)
2570 free(view->line[i].data);
2571 free(view->line);
2573 view->p_offset = view->offset;
2574 view->p_yoffset = view->yoffset;
2575 view->p_lineno = view->lineno;
2577 view->line = NULL;
2578 view->offset = 0;
2579 view->yoffset = 0;
2580 view->lines = 0;
2581 view->lineno = 0;
2582 view->vid[0] = 0;
2583 view->update_secs = 0;
2586 static const char *
2587 format_arg(const char *name)
2589 static struct {
2590 const char *name;
2591 size_t namelen;
2592 const char *value;
2593 const char *value_if_empty;
2594 } vars[] = {
2595 #define FORMAT_VAR(name, value, value_if_empty) \
2596 { name, STRING_SIZE(name), value, value_if_empty }
2597 FORMAT_VAR("%(directory)", opt_path, "."),
2598 FORMAT_VAR("%(file)", opt_file, ""),
2599 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2600 FORMAT_VAR("%(head)", ref_head, ""),
2601 FORMAT_VAR("%(commit)", ref_commit, ""),
2602 FORMAT_VAR("%(blob)", ref_blob, ""),
2603 FORMAT_VAR("%(branch)", ref_branch, ""),
2605 int i;
2607 for (i = 0; i < ARRAY_SIZE(vars); i++)
2608 if (!strncmp(name, vars[i].name, vars[i].namelen))
2609 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2611 report("Unknown replacement: `%s`", name);
2612 return NULL;
2615 static bool
2616 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2618 char buf[SIZEOF_STR];
2619 int argc;
2621 argv_free(*dst_argv);
2623 for (argc = 0; src_argv[argc]; argc++) {
2624 const char *arg = src_argv[argc];
2625 size_t bufpos = 0;
2627 if (!strcmp(arg, "%(fileargs)")) {
2628 if (!argv_append_array(dst_argv, opt_file_argv))
2629 break;
2630 continue;
2632 } else if (!strcmp(arg, "%(diffargs)")) {
2633 if (!argv_append_array(dst_argv, opt_diff_argv))
2634 break;
2635 continue;
2637 } else if (!strcmp(arg, "%(blameargs)")) {
2638 if (!argv_append_array(dst_argv, opt_blame_argv))
2639 break;
2640 continue;
2642 } else if (!strcmp(arg, "%(revargs)") ||
2643 (first && !strcmp(arg, "%(commit)"))) {
2644 if (!argv_append_array(dst_argv, opt_rev_argv))
2645 break;
2646 continue;
2649 while (arg) {
2650 char *next = strstr(arg, "%(");
2651 int len = next - arg;
2652 const char *value;
2654 if (!next) {
2655 len = strlen(arg);
2656 value = "";
2658 } else {
2659 value = format_arg(next);
2661 if (!value) {
2662 return FALSE;
2666 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2667 return FALSE;
2669 arg = next ? strchr(next, ')') + 1 : NULL;
2672 if (!argv_append(dst_argv, buf))
2673 break;
2676 return src_argv[argc] == NULL;
2679 static bool
2680 restore_view_position(struct view *view)
2682 /* A view without a previous view is the first view */
2683 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2684 select_view_line(view, opt_lineno - 1);
2685 opt_lineno = 0;
2688 if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2689 return FALSE;
2691 /* Changing the view position cancels the restoring. */
2692 /* FIXME: Changing back to the first line is not detected. */
2693 if (view->offset != 0 || view->lineno != 0) {
2694 view->p_restore = FALSE;
2695 return FALSE;
2698 if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2699 view_is_displayed(view))
2700 werase(view->win);
2702 view->yoffset = view->p_yoffset;
2703 view->p_restore = FALSE;
2705 return TRUE;
2708 static void
2709 end_update(struct view *view, bool force)
2711 if (!view->pipe)
2712 return;
2713 while (!view->ops->read(view, NULL))
2714 if (!force)
2715 return;
2716 if (force)
2717 io_kill(view->pipe);
2718 io_done(view->pipe);
2719 view->pipe = NULL;
2722 static void
2723 setup_update(struct view *view, const char *vid)
2725 reset_view(view);
2726 string_copy_rev(view->vid, vid);
2727 view->pipe = &view->io;
2728 view->start_time = time(NULL);
2731 static bool
2732 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2734 bool extra = !!(flags & (OPEN_EXTRA));
2735 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2736 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2738 if (!reload && !strcmp(view->vid, view->id))
2739 return TRUE;
2741 if (view->pipe) {
2742 if (extra)
2743 io_done(view->pipe);
2744 else
2745 end_update(view, TRUE);
2748 if (!refresh && argv) {
2749 view->dir = dir;
2750 if (!format_argv(&view->argv, argv, !view->prev))
2751 return FALSE;
2753 /* Put the current ref_* value to the view title ref
2754 * member. This is needed by the blob view. Most other
2755 * views sets it automatically after loading because the
2756 * first line is a commit line. */
2757 string_copy_rev(view->ref, view->id);
2760 if (view->argv && view->argv[0] &&
2761 !io_run(&view->io, IO_RD, view->dir, view->argv))
2762 return FALSE;
2764 if (!extra)
2765 setup_update(view, view->id);
2767 return TRUE;
2770 static bool
2771 update_view(struct view *view)
2773 char out_buffer[BUFSIZ * 2];
2774 char *line;
2775 /* Clear the view and redraw everything since the tree sorting
2776 * might have rearranged things. */
2777 bool redraw = view->lines == 0;
2778 bool can_read = TRUE;
2780 if (!view->pipe)
2781 return TRUE;
2783 if (!io_can_read(view->pipe, FALSE)) {
2784 if (view->lines == 0 && view_is_displayed(view)) {
2785 time_t secs = time(NULL) - view->start_time;
2787 if (secs > 1 && secs > view->update_secs) {
2788 if (view->update_secs == 0)
2789 redraw_view(view);
2790 update_view_title(view);
2791 view->update_secs = secs;
2794 return TRUE;
2797 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2798 if (opt_iconv_in != ICONV_NONE) {
2799 ICONV_CONST char *inbuf = line;
2800 size_t inlen = strlen(line) + 1;
2802 char *outbuf = out_buffer;
2803 size_t outlen = sizeof(out_buffer);
2805 size_t ret;
2807 ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2808 if (ret != (size_t) -1)
2809 line = out_buffer;
2812 if (!view->ops->read(view, line)) {
2813 report("Allocation failure");
2814 end_update(view, TRUE);
2815 return FALSE;
2820 unsigned long lines = view->lines;
2821 int digits;
2823 for (digits = 0; lines; digits++)
2824 lines /= 10;
2826 /* Keep the displayed view in sync with line number scaling. */
2827 if (digits != view->digits) {
2828 view->digits = digits;
2829 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
2830 redraw = TRUE;
2834 if (io_error(view->pipe)) {
2835 report("Failed to read: %s", io_strerror(view->pipe));
2836 end_update(view, TRUE);
2838 } else if (io_eof(view->pipe)) {
2839 if (view_is_displayed(view))
2840 report("");
2841 end_update(view, FALSE);
2844 if (restore_view_position(view))
2845 redraw = TRUE;
2847 if (!view_is_displayed(view))
2848 return TRUE;
2850 if (redraw)
2851 redraw_view_from(view, 0);
2852 else
2853 redraw_view_dirty(view);
2855 /* Update the title _after_ the redraw so that if the redraw picks up a
2856 * commit reference in view->ref it'll be available here. */
2857 update_view_title(view);
2858 return TRUE;
2861 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2863 static struct line *
2864 add_line_data(struct view *view, void *data, enum line_type type)
2866 struct line *line;
2868 if (!realloc_lines(&view->line, view->lines, 1))
2869 return NULL;
2871 line = &view->line[view->lines++];
2872 memset(line, 0, sizeof(*line));
2873 line->type = type;
2874 line->data = data;
2875 line->dirty = 1;
2877 return line;
2880 static struct line *
2881 add_line_text(struct view *view, const char *text, enum line_type type)
2883 char *data = text ? strdup(text) : NULL;
2885 return data ? add_line_data(view, data, type) : NULL;
2888 static struct line *
2889 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2891 char buf[SIZEOF_STR];
2892 int retval;
2894 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
2895 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
2899 * View opening
2902 static void
2903 load_view(struct view *view, enum open_flags flags)
2905 if (view->pipe)
2906 end_update(view, TRUE);
2907 if (view->ops->private_size) {
2908 if (!view->private)
2909 view->private = calloc(1, view->ops->private_size);
2910 else
2911 memset(view->private, 0, view->ops->private_size);
2913 if (!view->ops->open(view, flags)) {
2914 report("Failed to load %s view", view->name);
2915 return;
2917 restore_view_position(view);
2919 if (view->pipe && view->lines == 0) {
2920 /* Clear the old view and let the incremental updating refill
2921 * the screen. */
2922 werase(view->win);
2923 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2924 report("");
2925 } else if (view_is_displayed(view)) {
2926 redraw_view(view);
2927 report("");
2931 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2932 #define reload_view(view) load_view(view, OPEN_RELOAD)
2934 static void
2935 split_view(struct view *prev, struct view *view)
2937 display[1] = view;
2938 current_view = 1;
2939 view->parent = prev;
2940 resize_display();
2942 if (prev->lineno - prev->offset >= prev->height) {
2943 /* Take the title line into account. */
2944 int lines = prev->lineno - prev->offset - prev->height + 1;
2946 /* Scroll the view that was split if the current line is
2947 * outside the new limited view. */
2948 do_scroll_view(prev, lines);
2951 if (view != prev && view_is_displayed(prev)) {
2952 /* "Blur" the previous view. */
2953 update_view_title(prev);
2957 static void
2958 open_view(struct view *prev, enum request request, enum open_flags flags)
2960 bool split = !!(flags & OPEN_SPLIT);
2961 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
2962 struct view *view = VIEW(request);
2963 int nviews = displayed_views();
2965 assert(flags ^ OPEN_REFRESH);
2967 if (view == prev && nviews == 1 && !reload) {
2968 report("Already in %s view", view->name);
2969 return;
2972 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
2973 report("The %s view is disabled in pager view", view->name);
2974 return;
2977 if (split) {
2978 split_view(prev, view);
2979 } else {
2980 maximize_view(view, FALSE);
2983 /* No prev signals that this is the first loaded view. */
2984 if (prev && view != prev) {
2985 view->prev = prev;
2988 load_view(view, flags);
2991 static void
2992 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
2994 enum request request = view - views + REQ_OFFSET + 1;
2996 if (view->pipe)
2997 end_update(view, TRUE);
2998 view->dir = dir;
3000 if (!argv_copy(&view->argv, argv)) {
3001 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3002 } else {
3003 open_view(prev, request, flags | OPEN_PREPARED);
3007 static void
3008 open_external_viewer(const char *argv[], const char *dir)
3010 def_prog_mode(); /* save current tty modes */
3011 endwin(); /* restore original tty modes */
3012 io_run_fg(argv, dir);
3013 fprintf(stderr, "Press Enter to continue");
3014 getc(opt_tty);
3015 reset_prog_mode();
3016 redraw_display(TRUE);
3019 static void
3020 open_mergetool(const char *file)
3022 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3024 open_external_viewer(mergetool_argv, opt_cdup);
3027 static void
3028 open_editor(const char *file)
3030 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3031 char editor_cmd[SIZEOF_STR];
3032 const char *editor;
3033 int argc = 0;
3035 editor = getenv("GIT_EDITOR");
3036 if (!editor && *opt_editor)
3037 editor = opt_editor;
3038 if (!editor)
3039 editor = getenv("VISUAL");
3040 if (!editor)
3041 editor = getenv("EDITOR");
3042 if (!editor)
3043 editor = "vi";
3045 string_ncopy(editor_cmd, editor, strlen(editor));
3046 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3047 report("Failed to read editor command");
3048 return;
3051 editor_argv[argc] = file;
3052 open_external_viewer(editor_argv, opt_cdup);
3055 static void
3056 open_run_request(enum request request)
3058 struct run_request *req = get_run_request(request);
3059 const char **argv = NULL;
3061 if (!req) {
3062 report("Unknown run request");
3063 return;
3066 if (format_argv(&argv, req->argv, FALSE))
3067 open_external_viewer(argv, NULL);
3068 if (argv)
3069 argv_free(argv);
3070 free(argv);
3074 * User request switch noodle
3077 static int
3078 view_driver(struct view *view, enum request request)
3080 int i;
3082 if (request == REQ_NONE)
3083 return TRUE;
3085 if (request > REQ_NONE) {
3086 open_run_request(request);
3087 view_request(view, REQ_REFRESH);
3088 return TRUE;
3091 request = view_request(view, request);
3092 if (request == REQ_NONE)
3093 return TRUE;
3095 switch (request) {
3096 case REQ_MOVE_UP:
3097 case REQ_MOVE_DOWN:
3098 case REQ_MOVE_PAGE_UP:
3099 case REQ_MOVE_PAGE_DOWN:
3100 case REQ_MOVE_FIRST_LINE:
3101 case REQ_MOVE_LAST_LINE:
3102 move_view(view, request);
3103 break;
3105 case REQ_SCROLL_FIRST_COL:
3106 case REQ_SCROLL_LEFT:
3107 case REQ_SCROLL_RIGHT:
3108 case REQ_SCROLL_LINE_DOWN:
3109 case REQ_SCROLL_LINE_UP:
3110 case REQ_SCROLL_PAGE_DOWN:
3111 case REQ_SCROLL_PAGE_UP:
3112 scroll_view(view, request);
3113 break;
3115 case REQ_VIEW_BLAME:
3116 if (!opt_file[0]) {
3117 report("No file chosen, press %s to open tree view",
3118 get_view_key(view, REQ_VIEW_TREE));
3119 break;
3121 open_view(view, request, OPEN_DEFAULT);
3122 break;
3124 case REQ_VIEW_BLOB:
3125 if (!ref_blob[0]) {
3126 report("No file chosen, press %s to open tree view",
3127 get_view_key(view, REQ_VIEW_TREE));
3128 break;
3130 open_view(view, request, OPEN_DEFAULT);
3131 break;
3133 case REQ_VIEW_PAGER:
3134 if (view == NULL) {
3135 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
3136 die("Failed to open stdin");
3137 open_view(view, request, OPEN_PREPARED);
3138 break;
3141 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
3142 report("No pager content, press %s to run command from prompt",
3143 get_view_key(view, REQ_PROMPT));
3144 break;
3146 open_view(view, request, OPEN_DEFAULT);
3147 break;
3149 case REQ_VIEW_STAGE:
3150 if (!VIEW(REQ_VIEW_STAGE)->lines) {
3151 report("No stage content, press %s to open the status view and choose file",
3152 get_view_key(view, REQ_VIEW_STATUS));
3153 break;
3155 open_view(view, request, OPEN_DEFAULT);
3156 break;
3158 case REQ_VIEW_STATUS:
3159 if (opt_is_inside_work_tree == FALSE) {
3160 report("The status view requires a working tree");
3161 break;
3163 open_view(view, request, OPEN_DEFAULT);
3164 break;
3166 case REQ_VIEW_MAIN:
3167 case REQ_VIEW_DIFF:
3168 case REQ_VIEW_LOG:
3169 case REQ_VIEW_TREE:
3170 case REQ_VIEW_HELP:
3171 case REQ_VIEW_BRANCH:
3172 open_view(view, request, OPEN_DEFAULT);
3173 break;
3175 case REQ_NEXT:
3176 case REQ_PREVIOUS:
3177 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
3179 if (view->parent) {
3180 int line;
3182 view = view->parent;
3183 line = view->lineno;
3184 move_view(view, request);
3185 if (view_is_displayed(view))
3186 update_view_title(view);
3187 if (line != view->lineno)
3188 view_request(view, REQ_ENTER);
3189 } else {
3190 move_view(view, request);
3192 break;
3194 case REQ_VIEW_NEXT:
3196 int nviews = displayed_views();
3197 int next_view = (current_view + 1) % nviews;
3199 if (next_view == current_view) {
3200 report("Only one view is displayed");
3201 break;
3204 current_view = next_view;
3205 /* Blur out the title of the previous view. */
3206 update_view_title(view);
3207 report("");
3208 break;
3210 case REQ_REFRESH:
3211 report("Refreshing is not yet supported for the %s view", view->name);
3212 break;
3214 case REQ_MAXIMIZE:
3215 if (displayed_views() == 2)
3216 maximize_view(view, TRUE);
3217 break;
3219 case REQ_OPTIONS:
3220 case REQ_TOGGLE_LINENO:
3221 case REQ_TOGGLE_DATE:
3222 case REQ_TOGGLE_AUTHOR:
3223 case REQ_TOGGLE_FILENAME:
3224 case REQ_TOGGLE_GRAPHIC:
3225 case REQ_TOGGLE_REV_GRAPH:
3226 case REQ_TOGGLE_REFS:
3227 toggle_option(request);
3228 break;
3230 case REQ_TOGGLE_SORT_FIELD:
3231 case REQ_TOGGLE_SORT_ORDER:
3232 report("Sorting is not yet supported for the %s view", view->name);
3233 break;
3235 case REQ_TOGGLE_IGNORE_SPACE:
3236 report("Toggling ignored whitespace is not yet supported for the %s view", view->name);
3237 break;
3239 case REQ_DIFF_CONTEXT_UP:
3240 case REQ_DIFF_CONTEXT_DOWN:
3241 report("Changing the diff context is not yet supported for the %s view", view->name);
3242 break;
3244 case REQ_SEARCH:
3245 case REQ_SEARCH_BACK:
3246 search_view(view, request);
3247 break;
3249 case REQ_FIND_NEXT:
3250 case REQ_FIND_PREV:
3251 find_next(view, request);
3252 break;
3254 case REQ_STOP_LOADING:
3255 foreach_view(view, i) {
3256 if (view->pipe)
3257 report("Stopped loading the %s view", view->name),
3258 end_update(view, TRUE);
3260 break;
3262 case REQ_SHOW_VERSION:
3263 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3264 return TRUE;
3266 case REQ_SCREEN_REDRAW:
3267 redraw_display(TRUE);
3268 break;
3270 case REQ_EDIT:
3271 report("Nothing to edit");
3272 break;
3274 case REQ_ENTER:
3275 report("Nothing to enter");
3276 break;
3278 case REQ_VIEW_CLOSE:
3279 /* XXX: Mark closed views by letting view->prev point to the
3280 * view itself. Parents to closed view should never be
3281 * followed. */
3282 if (view->prev && view->prev != view) {
3283 maximize_view(view->prev, TRUE);
3284 view->prev = view;
3285 break;
3287 /* Fall-through */
3288 case REQ_QUIT:
3289 return FALSE;
3291 default:
3292 report("Unknown key, press %s for help",
3293 get_view_key(view, REQ_VIEW_HELP));
3294 return TRUE;
3297 return TRUE;
3302 * View backend utilities
3305 enum sort_field {
3306 ORDERBY_NAME,
3307 ORDERBY_DATE,
3308 ORDERBY_AUTHOR,
3311 struct sort_state {
3312 const enum sort_field *fields;
3313 size_t size, current;
3314 bool reverse;
3317 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3318 #define get_sort_field(state) ((state).fields[(state).current])
3319 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3321 static void
3322 sort_view(struct view *view, enum request request, struct sort_state *state,
3323 int (*compare)(const void *, const void *))
3325 switch (request) {
3326 case REQ_TOGGLE_SORT_FIELD:
3327 state->current = (state->current + 1) % state->size;
3328 break;
3330 case REQ_TOGGLE_SORT_ORDER:
3331 state->reverse = !state->reverse;
3332 break;
3333 default:
3334 die("Not a sort request");
3337 qsort(view->line, view->lines, sizeof(*view->line), compare);
3338 redraw_view(view);
3341 static bool
3342 update_diff_context(enum request request)
3344 int diff_context = opt_diff_context;
3346 switch (request) {
3347 case REQ_DIFF_CONTEXT_UP:
3348 opt_diff_context += 1;
3349 update_diff_context_arg(opt_diff_context);
3350 break;
3352 case REQ_DIFF_CONTEXT_DOWN:
3353 if (opt_diff_context == 0) {
3354 report("Diff context cannot be less than zero");
3355 break;
3357 opt_diff_context -= 1;
3358 update_diff_context_arg(opt_diff_context);
3359 break;
3361 default:
3362 die("Not a diff context request");
3365 return diff_context != opt_diff_context;
3368 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3370 /* Small author cache to reduce memory consumption. It uses binary
3371 * search to lookup or find place to position new entries. No entries
3372 * are ever freed. */
3373 static const char *
3374 get_author(const char *name)
3376 static const char **authors;
3377 static size_t authors_size;
3378 int from = 0, to = authors_size - 1;
3380 while (from <= to) {
3381 size_t pos = (to + from) / 2;
3382 int cmp = strcmp(name, authors[pos]);
3384 if (!cmp)
3385 return authors[pos];
3387 if (cmp < 0)
3388 to = pos - 1;
3389 else
3390 from = pos + 1;
3393 if (!realloc_authors(&authors, authors_size, 1))
3394 return NULL;
3395 name = strdup(name);
3396 if (!name)
3397 return NULL;
3399 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3400 authors[from] = name;
3401 authors_size++;
3403 return name;
3406 static void
3407 parse_timesec(struct time *time, const char *sec)
3409 time->sec = (time_t) atol(sec);
3412 static void
3413 parse_timezone(struct time *time, const char *zone)
3415 long tz;
3417 tz = ('0' - zone[1]) * 60 * 60 * 10;
3418 tz += ('0' - zone[2]) * 60 * 60;
3419 tz += ('0' - zone[3]) * 60 * 10;
3420 tz += ('0' - zone[4]) * 60;
3422 if (zone[0] == '-')
3423 tz = -tz;
3425 time->tz = tz;
3426 time->sec -= tz;
3429 /* Parse author lines where the name may be empty:
3430 * author <email@address.tld> 1138474660 +0100
3432 static void
3433 parse_author_line(char *ident, const char **author, struct time *time)
3435 char *nameend = strchr(ident, '<');
3436 char *emailend = strchr(ident, '>');
3438 if (nameend && emailend)
3439 *nameend = *emailend = 0;
3440 ident = chomp_string(ident);
3441 if (!*ident) {
3442 if (nameend)
3443 ident = chomp_string(nameend + 1);
3444 if (!*ident)
3445 ident = "Unknown";
3448 *author = get_author(ident);
3450 /* Parse epoch and timezone */
3451 if (emailend && emailend[1] == ' ') {
3452 char *secs = emailend + 2;
3453 char *zone = strchr(secs, ' ');
3455 parse_timesec(time, secs);
3457 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3458 parse_timezone(time, zone + 1);
3462 static struct line *
3463 find_prev_line_by_type(struct view *view, struct line *line, enum line_type type)
3465 for (; view->line < line; line--)
3466 if (line->type == type)
3467 return line;
3469 return NULL;
3473 * Blame
3476 struct blame_commit {
3477 char id[SIZEOF_REV]; /* SHA1 ID. */
3478 char title[128]; /* First line of the commit message. */
3479 const char *author; /* Author of the commit. */
3480 struct time time; /* Date from the author ident. */
3481 char filename[128]; /* Name of file. */
3482 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3483 char parent_filename[128]; /* Parent/previous name of file. */
3486 struct blame_header {
3487 char id[SIZEOF_REV]; /* SHA1 ID. */
3488 size_t orig_lineno;
3489 size_t lineno;
3490 size_t group;
3493 static bool
3494 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3496 const char *pos = *posref;
3498 *posref = NULL;
3499 pos = strchr(pos + 1, ' ');
3500 if (!pos || !isdigit(pos[1]))
3501 return FALSE;
3502 *number = atoi(pos + 1);
3503 if (*number < min || *number > max)
3504 return FALSE;
3506 *posref = pos;
3507 return TRUE;
3510 static bool
3511 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3513 const char *pos = text + SIZEOF_REV - 2;
3515 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3516 return FALSE;
3518 string_ncopy(header->id, text, SIZEOF_REV);
3520 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3521 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3522 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3523 return FALSE;
3525 return TRUE;
3528 static bool
3529 match_blame_header(const char *name, char **line)
3531 size_t namelen = strlen(name);
3532 bool matched = !strncmp(name, *line, namelen);
3534 if (matched)
3535 *line += namelen;
3537 return matched;
3540 static bool
3541 parse_blame_info(struct blame_commit *commit, char *line)
3543 if (match_blame_header("author ", &line)) {
3544 commit->author = get_author(line);
3546 } else if (match_blame_header("author-time ", &line)) {
3547 parse_timesec(&commit->time, line);
3549 } else if (match_blame_header("author-tz ", &line)) {
3550 parse_timezone(&commit->time, line);
3552 } else if (match_blame_header("summary ", &line)) {
3553 string_ncopy(commit->title, line, strlen(line));
3555 } else if (match_blame_header("previous ", &line)) {
3556 if (strlen(line) <= SIZEOF_REV)
3557 return FALSE;
3558 string_copy_rev(commit->parent_id, line);
3559 line += SIZEOF_REV;
3560 string_ncopy(commit->parent_filename, line, strlen(line));
3562 } else if (match_blame_header("filename ", &line)) {
3563 string_ncopy(commit->filename, line, strlen(line));
3564 return TRUE;
3567 return FALSE;
3571 * Pager backend
3574 static bool
3575 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3577 if (opt_line_number && draw_lineno(view, lineno))
3578 return TRUE;
3580 draw_text(view, line->type, line->data);
3581 return TRUE;
3584 static bool
3585 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3587 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3588 char ref[SIZEOF_STR];
3590 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3591 return TRUE;
3593 /* This is the only fatal call, since it can "corrupt" the buffer. */
3594 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3595 return FALSE;
3597 return TRUE;
3600 static void
3601 add_pager_refs(struct view *view, struct line *line)
3603 char buf[SIZEOF_STR];
3604 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3605 struct ref_list *list;
3606 size_t bufpos = 0, i;
3607 const char *sep = "Refs: ";
3608 bool is_tag = FALSE;
3610 assert(line->type == LINE_COMMIT);
3612 list = get_ref_list(commit_id);
3613 if (!list) {
3614 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3615 goto try_add_describe_ref;
3616 return;
3619 for (i = 0; i < list->size; i++) {
3620 struct ref *ref = list->refs[i];
3621 const char *fmt = ref->tag ? "%s[%s]" :
3622 ref->remote ? "%s<%s>" : "%s%s";
3624 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3625 return;
3626 sep = ", ";
3627 if (ref->tag)
3628 is_tag = TRUE;
3631 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3632 try_add_describe_ref:
3633 /* Add <tag>-g<commit_id> "fake" reference. */
3634 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3635 return;
3638 if (bufpos == 0)
3639 return;
3641 add_line_text(view, buf, LINE_PP_REFS);
3644 static bool
3645 pager_read(struct view *view, char *data)
3647 struct line *line;
3649 if (!data)
3650 return TRUE;
3652 line = add_line_text(view, data, get_line_type(data));
3653 if (!line)
3654 return FALSE;
3656 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
3657 add_pager_refs(view, line);
3659 return TRUE;
3662 static enum request
3663 pager_request(struct view *view, enum request request, struct line *line)
3665 int split = 0;
3667 if (request != REQ_ENTER)
3668 return request;
3670 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
3671 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3672 split = 1;
3675 /* Always scroll the view even if it was split. That way
3676 * you can use Enter to scroll through the log view and
3677 * split open each commit diff. */
3678 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3680 /* FIXME: A minor workaround. Scrolling the view will call report("")
3681 * but if we are scrolling a non-current view this won't properly
3682 * update the view title. */
3683 if (split)
3684 update_view_title(view);
3686 return REQ_NONE;
3689 static bool
3690 pager_grep(struct view *view, struct line *line)
3692 const char *text[] = { line->data, NULL };
3694 return grep_text(view, text);
3697 static void
3698 pager_select(struct view *view, struct line *line)
3700 if (line->type == LINE_COMMIT) {
3701 char *text = (char *)line->data + STRING_SIZE("commit ");
3703 if (!view_has_flags(view, VIEW_NO_REF))
3704 string_copy_rev(view->ref, text);
3705 string_copy_rev(ref_commit, text);
3709 static bool
3710 pager_open(struct view *view, enum open_flags flags)
3712 return begin_update(view, NULL, NULL, flags);
3715 static struct view_ops pager_ops = {
3716 "line",
3717 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
3719 pager_open,
3720 pager_read,
3721 pager_draw,
3722 pager_request,
3723 pager_grep,
3724 pager_select,
3727 static bool
3728 log_open(struct view *view, enum open_flags flags)
3730 static const char *log_argv[] = {
3731 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3734 return begin_update(view, NULL, log_argv, flags);
3737 static enum request
3738 log_request(struct view *view, enum request request, struct line *line)
3740 switch (request) {
3741 case REQ_REFRESH:
3742 load_refs();
3743 refresh_view(view);
3744 return REQ_NONE;
3745 default:
3746 return pager_request(view, request, line);
3750 static struct view_ops log_ops = {
3751 "line",
3752 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
3754 log_open,
3755 pager_read,
3756 pager_draw,
3757 log_request,
3758 pager_grep,
3759 pager_select,
3762 struct diff_state {
3763 bool reading_diff_stat;
3766 static bool
3767 diff_open(struct view *view, enum open_flags flags)
3769 static const char *diff_argv[] = {
3770 "git", "show", "--pretty=fuller", "--no-color", "--root",
3771 "--patch-with-stat", "--find-copies-harder", "-C",
3772 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
3773 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3776 return begin_update(view, NULL, diff_argv, flags);
3779 static bool
3780 diff_common_read(struct view *view, char *data, struct diff_state *state)
3782 if (state->reading_diff_stat) {
3783 size_t len = strlen(data);
3784 char *pipe = strchr(data, '|');
3785 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3786 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3788 if (pipe && (has_histogram || has_bin_diff)) {
3789 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3790 } else {
3791 state->reading_diff_stat = FALSE;
3794 } else if (!strcmp(data, "---")) {
3795 state->reading_diff_stat = TRUE;
3798 return pager_read(view, data);
3801 static enum request
3802 diff_common_enter(struct view *view, enum request request, struct line *line)
3804 if (line->type == LINE_DIFF_STAT) {
3805 int file_number = 0;
3807 while (line >= view->line && line->type == LINE_DIFF_STAT) {
3808 file_number++;
3809 line--;
3812 while (line < view->line + view->lines) {
3813 if (line->type == LINE_DIFF_HEADER) {
3814 if (file_number == 1) {
3815 break;
3817 file_number--;
3819 line++;
3823 select_view_line(view, line - view->line);
3824 report("");
3825 return REQ_NONE;
3827 } else {
3828 return pager_request(view, request, line);
3832 static bool
3833 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
3835 char *sep = strchr(*text, c);
3837 if (sep != NULL) {
3838 *sep = 0;
3839 draw_text(view, *type, *text);
3840 *sep = c;
3841 *text = sep;
3842 *type = next_type;
3845 return sep != NULL;
3848 static bool
3849 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
3851 char *text = line->data;
3852 enum line_type type = line->type;
3854 if (opt_line_number && draw_lineno(view, lineno))
3855 return TRUE;
3857 if (type == LINE_DIFF_STAT) {
3858 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
3859 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
3860 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
3861 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
3862 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
3863 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
3864 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
3866 } else {
3867 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
3868 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
3872 draw_text(view, type, text);
3873 return TRUE;
3876 static bool
3877 diff_read(struct view *view, char *data)
3879 struct diff_state *state = view->private;
3881 if (!data) {
3882 /* Fall back to retry if no diff will be shown. */
3883 if (view->lines == 0 && opt_file_argv) {
3884 int pos = argv_size(view->argv)
3885 - argv_size(opt_file_argv) - 1;
3887 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3888 for (; view->argv[pos]; pos++) {
3889 free((void *) view->argv[pos]);
3890 view->argv[pos] = NULL;
3893 if (view->pipe)
3894 io_done(view->pipe);
3895 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3896 return FALSE;
3899 return TRUE;
3902 return diff_common_read(view, data, state);
3905 static bool
3906 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
3907 struct blame_header *header, struct blame_commit *commit)
3909 char line_arg[SIZEOF_STR];
3910 const char *blame_argv[] = {
3911 "git", "blame", "-p", line_arg, ref, "--", file, NULL
3913 struct io io;
3914 bool ok = FALSE;
3915 char *buf;
3917 if (!string_format(line_arg, "-L%d,+1", lineno))
3918 return FALSE;
3920 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
3921 return FALSE;
3923 while ((buf = io_get(&io, '\n', TRUE))) {
3924 if (header) {
3925 if (!parse_blame_header(header, buf, 9999999))
3926 break;
3927 header = NULL;
3929 } else if (parse_blame_info(commit, buf)) {
3930 ok = TRUE;
3931 break;
3935 if (io_error(&io))
3936 ok = FALSE;
3938 io_done(&io);
3939 return ok;
3942 static bool
3943 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
3945 return prefixcmp(chunk, "@@ -") ||
3946 !(chunk = strchr(chunk, marker)) ||
3947 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
3950 static enum request
3951 diff_trace_origin(struct view *view, struct line *line)
3953 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
3954 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
3955 const char *chunk_data;
3956 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
3957 int lineno = 0;
3958 const char *file = NULL;
3959 char ref[SIZEOF_REF];
3960 struct blame_header header;
3961 struct blame_commit commit;
3963 if (!diff || !chunk || chunk == line) {
3964 report("The line to trace must be inside a diff chunk");
3965 return REQ_NONE;
3968 for (; diff < line && !file; diff++) {
3969 const char *data = diff->data;
3971 if (!prefixcmp(data, "--- a/")) {
3972 file = data + STRING_SIZE("--- a/");
3973 break;
3977 if (diff == line || !file) {
3978 report("Failed to read the file name");
3979 return REQ_NONE;
3982 chunk_data = chunk->data;
3984 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
3985 report("Failed to read the line number");
3986 return REQ_NONE;
3989 if (lineno == 0) {
3990 report("This is the origin of the line");
3991 return REQ_NONE;
3994 for (chunk += 1; chunk < line; chunk++) {
3995 if (chunk->type == LINE_DIFF_ADD) {
3996 lineno += chunk_marker == '+';
3997 } else if (chunk->type == LINE_DIFF_DEL) {
3998 lineno += chunk_marker == '-';
3999 } else {
4000 lineno++;
4004 if (chunk_marker == '+')
4005 string_copy(ref, view->vid);
4006 else
4007 string_format(ref, "%s^", view->vid);
4009 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4010 report("Failed to read blame data");
4011 return REQ_NONE;
4014 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4015 string_copy(opt_ref, header.id);
4016 opt_goto_line = header.orig_lineno - 1;
4018 return REQ_VIEW_BLAME;
4021 static enum request
4022 diff_request(struct view *view, enum request request, struct line *line)
4024 switch (request) {
4025 case REQ_VIEW_BLAME:
4026 return diff_trace_origin(view, line);
4028 case REQ_DIFF_CONTEXT_UP:
4029 case REQ_DIFF_CONTEXT_DOWN:
4030 if (!update_diff_context(request))
4031 return REQ_NONE;
4032 reload_view(view);
4033 return REQ_NONE;
4035 case REQ_TOGGLE_IGNORE_SPACE:
4036 toggle_ignore_space();
4037 reload_view(view);
4038 return REQ_NONE;
4040 case REQ_ENTER:
4041 return diff_common_enter(view, request, line);
4043 default:
4044 return pager_request(view, request, line);
4048 static void
4049 diff_select(struct view *view, struct line *line)
4051 if (line->type == LINE_DIFF_STAT) {
4052 const char *key = get_view_key(view, REQ_ENTER);
4054 string_format(view->ref, "Press '%s' to jump to file diff", key);
4055 } else {
4056 string_ncopy(view->ref, view->id, strlen(view->id));
4057 return pager_select(view, line);
4061 static struct view_ops diff_ops = {
4062 "line",
4063 VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS,
4064 sizeof(struct diff_state),
4065 diff_open,
4066 diff_read,
4067 diff_common_draw,
4068 diff_request,
4069 pager_grep,
4070 diff_select,
4074 * Help backend
4077 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
4079 static bool
4080 help_open_keymap_title(struct view *view, enum keymap keymap)
4082 struct line *line;
4084 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
4085 help_keymap_hidden[keymap] ? '+' : '-',
4086 enum_name(keymap_map[keymap]));
4087 if (line)
4088 line->other = keymap;
4090 return help_keymap_hidden[keymap];
4093 static void
4094 help_open_keymap(struct view *view, enum keymap keymap)
4096 const char *group = NULL;
4097 char buf[SIZEOF_STR];
4098 size_t bufpos;
4099 bool add_title = TRUE;
4100 int i;
4102 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4103 const char *key = NULL;
4105 if (req_info[i].request == REQ_NONE)
4106 continue;
4108 if (!req_info[i].request) {
4109 group = req_info[i].help;
4110 continue;
4113 key = get_keys(keymap, req_info[i].request, TRUE);
4114 if (!key || !*key)
4115 continue;
4117 if (add_title && help_open_keymap_title(view, keymap))
4118 return;
4119 add_title = FALSE;
4121 if (group) {
4122 add_line_text(view, group, LINE_HELP_GROUP);
4123 group = NULL;
4126 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4127 enum_name(req_info[i]), req_info[i].help);
4130 group = "External commands:";
4132 for (i = 0; i < run_requests; i++) {
4133 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4134 const char *key;
4135 int argc;
4137 if (!req || req->keymap != keymap)
4138 continue;
4140 key = get_key_name(req->key);
4141 if (!*key)
4142 key = "(no key defined)";
4144 if (add_title && help_open_keymap_title(view, keymap))
4145 return;
4146 if (group) {
4147 add_line_text(view, group, LINE_HELP_GROUP);
4148 group = NULL;
4151 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
4152 if (!string_format_from(buf, &bufpos, "%s%s",
4153 argc ? " " : "", req->argv[argc]))
4154 return;
4156 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4160 static bool
4161 help_open(struct view *view, enum open_flags flags)
4163 enum keymap keymap;
4165 reset_view(view);
4166 view->p_restore = TRUE;
4167 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4168 add_line_text(view, "", LINE_DEFAULT);
4170 for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
4171 help_open_keymap(view, keymap);
4173 return TRUE;
4176 static enum request
4177 help_request(struct view *view, enum request request, struct line *line)
4179 switch (request) {
4180 case REQ_ENTER:
4181 if (line->type == LINE_HELP_KEYMAP) {
4182 help_keymap_hidden[line->other] =
4183 !help_keymap_hidden[line->other];
4184 refresh_view(view);
4187 return REQ_NONE;
4188 default:
4189 return pager_request(view, request, line);
4193 static struct view_ops help_ops = {
4194 "line",
4195 VIEW_NO_GIT_DIR,
4197 help_open,
4198 NULL,
4199 pager_draw,
4200 help_request,
4201 pager_grep,
4202 pager_select,
4207 * Tree backend
4210 struct tree_stack_entry {
4211 struct tree_stack_entry *prev; /* Entry below this in the stack */
4212 unsigned long lineno; /* Line number to restore */
4213 char *name; /* Position of name in opt_path */
4216 /* The top of the path stack. */
4217 static struct tree_stack_entry *tree_stack = NULL;
4218 unsigned long tree_lineno = 0;
4220 static void
4221 pop_tree_stack_entry(void)
4223 struct tree_stack_entry *entry = tree_stack;
4225 tree_lineno = entry->lineno;
4226 entry->name[0] = 0;
4227 tree_stack = entry->prev;
4228 free(entry);
4231 static void
4232 push_tree_stack_entry(const char *name, unsigned long lineno)
4234 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4235 size_t pathlen = strlen(opt_path);
4237 if (!entry)
4238 return;
4240 entry->prev = tree_stack;
4241 entry->name = opt_path + pathlen;
4242 tree_stack = entry;
4244 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4245 pop_tree_stack_entry();
4246 return;
4249 /* Move the current line to the first tree entry. */
4250 tree_lineno = 1;
4251 entry->lineno = lineno;
4254 /* Parse output from git-ls-tree(1):
4256 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4259 #define SIZEOF_TREE_ATTR \
4260 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4262 #define SIZEOF_TREE_MODE \
4263 STRING_SIZE("100644 ")
4265 #define TREE_ID_OFFSET \
4266 STRING_SIZE("100644 blob ")
4268 struct tree_entry {
4269 char id[SIZEOF_REV];
4270 mode_t mode;
4271 struct time time; /* Date from the author ident. */
4272 const char *author; /* Author of the commit. */
4273 char name[1];
4276 struct tree_state {
4277 const char *author_name;
4278 struct time author_time;
4279 bool read_date;
4282 static const char *
4283 tree_path(const struct line *line)
4285 return ((struct tree_entry *) line->data)->name;
4288 static int
4289 tree_compare_entry(const struct line *line1, const struct line *line2)
4291 if (line1->type != line2->type)
4292 return line1->type == LINE_TREE_DIR ? -1 : 1;
4293 return strcmp(tree_path(line1), tree_path(line2));
4296 static const enum sort_field tree_sort_fields[] = {
4297 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4299 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4301 static int
4302 tree_compare(const void *l1, const void *l2)
4304 const struct line *line1 = (const struct line *) l1;
4305 const struct line *line2 = (const struct line *) l2;
4306 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4307 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4309 if (line1->type == LINE_TREE_HEAD)
4310 return -1;
4311 if (line2->type == LINE_TREE_HEAD)
4312 return 1;
4314 switch (get_sort_field(tree_sort_state)) {
4315 case ORDERBY_DATE:
4316 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4318 case ORDERBY_AUTHOR:
4319 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4321 case ORDERBY_NAME:
4322 default:
4323 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4328 static struct line *
4329 tree_entry(struct view *view, enum line_type type, const char *path,
4330 const char *mode, const char *id)
4332 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4333 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4335 if (!entry || !line) {
4336 free(entry);
4337 return NULL;
4340 strncpy(entry->name, path, strlen(path));
4341 if (mode)
4342 entry->mode = strtoul(mode, NULL, 8);
4343 if (id)
4344 string_copy_rev(entry->id, id);
4346 return line;
4349 static bool
4350 tree_read_date(struct view *view, char *text, struct tree_state *state)
4352 if (!text && state->read_date) {
4353 state->read_date = FALSE;
4354 return TRUE;
4356 } else if (!text) {
4357 /* Find next entry to process */
4358 const char *log_file[] = {
4359 "git", "log", "--no-color", "--pretty=raw",
4360 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4363 if (!view->lines) {
4364 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4365 report("Tree is empty");
4366 return TRUE;
4369 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4370 report("Failed to load tree data");
4371 return TRUE;
4374 state->read_date = TRUE;
4375 return FALSE;
4377 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4378 parse_author_line(text + STRING_SIZE("author "),
4379 &state->author_name, &state->author_time);
4381 } else if (*text == ':') {
4382 char *pos;
4383 size_t annotated = 1;
4384 size_t i;
4386 pos = strchr(text, '\t');
4387 if (!pos)
4388 return TRUE;
4389 text = pos + 1;
4390 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4391 text += strlen(opt_path);
4392 pos = strchr(text, '/');
4393 if (pos)
4394 *pos = 0;
4396 for (i = 1; i < view->lines; i++) {
4397 struct line *line = &view->line[i];
4398 struct tree_entry *entry = line->data;
4400 annotated += !!entry->author;
4401 if (entry->author || strcmp(entry->name, text))
4402 continue;
4404 entry->author = state->author_name;
4405 entry->time = state->author_time;
4406 line->dirty = 1;
4407 break;
4410 if (annotated == view->lines)
4411 io_kill(view->pipe);
4413 return TRUE;
4416 static bool
4417 tree_read(struct view *view, char *text)
4419 struct tree_state *state = view->private;
4420 struct tree_entry *data;
4421 struct line *entry, *line;
4422 enum line_type type;
4423 size_t textlen = text ? strlen(text) : 0;
4424 char *path = text + SIZEOF_TREE_ATTR;
4426 if (state->read_date || !text)
4427 return tree_read_date(view, text, state);
4429 if (textlen <= SIZEOF_TREE_ATTR)
4430 return FALSE;
4431 if (view->lines == 0 &&
4432 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4433 return FALSE;
4435 /* Strip the path part ... */
4436 if (*opt_path) {
4437 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4438 size_t striplen = strlen(opt_path);
4440 if (pathlen > striplen)
4441 memmove(path, path + striplen,
4442 pathlen - striplen + 1);
4444 /* Insert "link" to parent directory. */
4445 if (view->lines == 1 &&
4446 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4447 return FALSE;
4450 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4451 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4452 if (!entry)
4453 return FALSE;
4454 data = entry->data;
4456 /* Skip "Directory ..." and ".." line. */
4457 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4458 if (tree_compare_entry(line, entry) <= 0)
4459 continue;
4461 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4463 line->data = data;
4464 line->type = type;
4465 for (; line <= entry; line++)
4466 line->dirty = line->cleareol = 1;
4467 return TRUE;
4470 if (tree_lineno > view->lineno) {
4471 view->lineno = tree_lineno;
4472 tree_lineno = 0;
4475 return TRUE;
4478 static bool
4479 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4481 struct tree_entry *entry = line->data;
4483 if (line->type == LINE_TREE_HEAD) {
4484 if (draw_text(view, line->type, "Directory path /"))
4485 return TRUE;
4486 } else {
4487 if (draw_mode(view, entry->mode))
4488 return TRUE;
4490 if (draw_author(view, entry->author))
4491 return TRUE;
4493 if (draw_date(view, &entry->time))
4494 return TRUE;
4497 draw_text(view, line->type, entry->name);
4498 return TRUE;
4501 static void
4502 open_blob_editor(const char *id)
4504 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4505 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4506 int fd = mkstemp(file);
4508 if (fd == -1)
4509 report("Failed to create temporary file");
4510 else if (!io_run_append(blob_argv, fd))
4511 report("Failed to save blob data to file");
4512 else
4513 open_editor(file);
4514 if (fd != -1)
4515 unlink(file);
4518 static enum request
4519 tree_request(struct view *view, enum request request, struct line *line)
4521 enum open_flags flags;
4522 struct tree_entry *entry = line->data;
4524 switch (request) {
4525 case REQ_VIEW_BLAME:
4526 if (line->type != LINE_TREE_FILE) {
4527 report("Blame only supported for files");
4528 return REQ_NONE;
4531 string_copy(opt_ref, view->vid);
4532 return request;
4534 case REQ_EDIT:
4535 if (line->type != LINE_TREE_FILE) {
4536 report("Edit only supported for files");
4537 } else if (!is_head_commit(view->vid)) {
4538 open_blob_editor(entry->id);
4539 } else {
4540 open_editor(opt_file);
4542 return REQ_NONE;
4544 case REQ_TOGGLE_SORT_FIELD:
4545 case REQ_TOGGLE_SORT_ORDER:
4546 sort_view(view, request, &tree_sort_state, tree_compare);
4547 return REQ_NONE;
4549 case REQ_PARENT:
4550 if (!*opt_path) {
4551 /* quit view if at top of tree */
4552 return REQ_VIEW_CLOSE;
4554 /* fake 'cd ..' */
4555 line = &view->line[1];
4556 break;
4558 case REQ_ENTER:
4559 break;
4561 default:
4562 return request;
4565 /* Cleanup the stack if the tree view is at a different tree. */
4566 while (!*opt_path && tree_stack)
4567 pop_tree_stack_entry();
4569 switch (line->type) {
4570 case LINE_TREE_DIR:
4571 /* Depending on whether it is a subdirectory or parent link
4572 * mangle the path buffer. */
4573 if (line == &view->line[1] && *opt_path) {
4574 pop_tree_stack_entry();
4576 } else {
4577 const char *basename = tree_path(line);
4579 push_tree_stack_entry(basename, view->lineno);
4582 /* Trees and subtrees share the same ID, so they are not not
4583 * unique like blobs. */
4584 flags = OPEN_RELOAD;
4585 request = REQ_VIEW_TREE;
4586 break;
4588 case LINE_TREE_FILE:
4589 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4590 request = REQ_VIEW_BLOB;
4591 break;
4593 default:
4594 return REQ_NONE;
4597 open_view(view, request, flags);
4598 if (request == REQ_VIEW_TREE)
4599 view->lineno = tree_lineno;
4601 return REQ_NONE;
4604 static bool
4605 tree_grep(struct view *view, struct line *line)
4607 struct tree_entry *entry = line->data;
4608 const char *text[] = {
4609 entry->name,
4610 mkauthor(entry->author, opt_author_cols, opt_author),
4611 mkdate(&entry->time, opt_date),
4612 NULL
4615 return grep_text(view, text);
4618 static void
4619 tree_select(struct view *view, struct line *line)
4621 struct tree_entry *entry = line->data;
4623 if (line->type == LINE_TREE_FILE) {
4624 string_copy_rev(ref_blob, entry->id);
4625 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4627 } else if (line->type != LINE_TREE_DIR) {
4628 return;
4631 string_copy_rev(view->ref, entry->id);
4634 static bool
4635 tree_open(struct view *view, enum open_flags flags)
4637 static const char *tree_argv[] = {
4638 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4641 if (view->lines == 0 && opt_prefix[0]) {
4642 char *pos = opt_prefix;
4644 while (pos && *pos) {
4645 char *end = strchr(pos, '/');
4647 if (end)
4648 *end = 0;
4649 push_tree_stack_entry(pos, 0);
4650 pos = end;
4651 if (end) {
4652 *end = '/';
4653 pos++;
4657 } else if (strcmp(view->vid, view->id)) {
4658 opt_path[0] = 0;
4661 return begin_update(view, opt_cdup, tree_argv, flags);
4664 static struct view_ops tree_ops = {
4665 "file",
4666 VIEW_NO_FLAGS,
4667 sizeof(struct tree_state),
4668 tree_open,
4669 tree_read,
4670 tree_draw,
4671 tree_request,
4672 tree_grep,
4673 tree_select,
4676 static bool
4677 blob_open(struct view *view, enum open_flags flags)
4679 static const char *blob_argv[] = {
4680 "git", "cat-file", "blob", "%(blob)", NULL
4683 return begin_update(view, NULL, blob_argv, flags);
4686 static bool
4687 blob_read(struct view *view, char *line)
4689 if (!line)
4690 return TRUE;
4691 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4694 static enum request
4695 blob_request(struct view *view, enum request request, struct line *line)
4697 switch (request) {
4698 case REQ_EDIT:
4699 open_blob_editor(view->vid);
4700 return REQ_NONE;
4701 default:
4702 return pager_request(view, request, line);
4706 static struct view_ops blob_ops = {
4707 "line",
4708 VIEW_NO_FLAGS,
4710 blob_open,
4711 blob_read,
4712 pager_draw,
4713 blob_request,
4714 pager_grep,
4715 pager_select,
4719 * Blame backend
4721 * Loading the blame view is a two phase job:
4723 * 1. File content is read either using opt_file from the
4724 * filesystem or using git-cat-file.
4725 * 2. Then blame information is incrementally added by
4726 * reading output from git-blame.
4729 struct blame {
4730 struct blame_commit *commit;
4731 unsigned long lineno;
4732 char text[1];
4735 struct blame_state {
4736 struct blame_commit *commit;
4737 int blamed;
4738 bool done_reading;
4739 bool auto_filename_display;
4742 static bool
4743 blame_detect_filename_display(struct view *view)
4745 bool show_filenames = FALSE;
4746 const char *filename = NULL;
4747 int i;
4749 if (opt_blame_argv) {
4750 for (i = 0; opt_blame_argv[i]; i++) {
4751 if (prefixcmp(opt_blame_argv[i], "-C"))
4752 continue;
4754 show_filenames = TRUE;
4758 for (i = 0; i < view->lines; i++) {
4759 struct blame *blame = view->line[i].data;
4761 if (blame->commit && blame->commit->id[0]) {
4762 if (!filename)
4763 filename = blame->commit->filename;
4764 else if (strcmp(filename, blame->commit->filename))
4765 show_filenames = TRUE;
4769 return show_filenames;
4772 static bool
4773 blame_open(struct view *view, enum open_flags flags)
4775 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4776 char path[SIZEOF_STR];
4777 size_t i;
4779 if (!view->prev && *opt_prefix) {
4780 string_copy(path, opt_file);
4781 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4782 return FALSE;
4785 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4786 const char *blame_cat_file_argv[] = {
4787 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4790 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4791 return FALSE;
4794 /* First pass: remove multiple references to the same commit. */
4795 for (i = 0; i < view->lines; i++) {
4796 struct blame *blame = view->line[i].data;
4798 if (blame->commit && blame->commit->id[0])
4799 blame->commit->id[0] = 0;
4800 else
4801 blame->commit = NULL;
4804 /* Second pass: free existing references. */
4805 for (i = 0; i < view->lines; i++) {
4806 struct blame *blame = view->line[i].data;
4808 if (blame->commit)
4809 free(blame->commit);
4812 string_format(view->vid, "%s", opt_file);
4813 string_format(view->ref, "%s ...", opt_file);
4815 return TRUE;
4818 static struct blame_commit *
4819 get_blame_commit(struct view *view, const char *id)
4821 size_t i;
4823 for (i = 0; i < view->lines; i++) {
4824 struct blame *blame = view->line[i].data;
4826 if (!blame->commit)
4827 continue;
4829 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4830 return blame->commit;
4834 struct blame_commit *commit = calloc(1, sizeof(*commit));
4836 if (commit)
4837 string_ncopy(commit->id, id, SIZEOF_REV);
4838 return commit;
4842 static struct blame_commit *
4843 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
4845 struct blame_header header;
4846 struct blame_commit *commit;
4847 struct blame *blame;
4849 if (!parse_blame_header(&header, text, view->lines))
4850 return NULL;
4852 commit = get_blame_commit(view, text);
4853 if (!commit)
4854 return NULL;
4856 state->blamed += header.group;
4857 while (header.group--) {
4858 struct line *line = &view->line[header.lineno + header.group - 1];
4860 blame = line->data;
4861 blame->commit = commit;
4862 blame->lineno = header.orig_lineno + header.group - 1;
4863 line->dirty = 1;
4866 return commit;
4869 static bool
4870 blame_read_file(struct view *view, const char *line, struct blame_state *state)
4872 if (!line) {
4873 const char *blame_argv[] = {
4874 "git", "blame", "%(blameargs)", "--incremental",
4875 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4878 if (view->lines == 0 && !view->prev)
4879 die("No blame exist for %s", view->vid);
4881 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
4882 report("Failed to load blame data");
4883 return TRUE;
4886 if (opt_goto_line > 0) {
4887 select_view_line(view, opt_goto_line);
4888 opt_goto_line = 0;
4891 state->done_reading = TRUE;
4892 return FALSE;
4894 } else {
4895 size_t linelen = strlen(line);
4896 struct blame *blame = malloc(sizeof(*blame) + linelen);
4898 if (!blame)
4899 return FALSE;
4901 blame->commit = NULL;
4902 strncpy(blame->text, line, linelen);
4903 blame->text[linelen] = 0;
4904 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4908 static bool
4909 blame_read(struct view *view, char *line)
4911 struct blame_state *state = view->private;
4913 if (!state->done_reading)
4914 return blame_read_file(view, line, state);
4916 if (!line) {
4917 state->auto_filename_display = blame_detect_filename_display(view);
4918 string_format(view->ref, "%s", view->vid);
4919 if (view_is_displayed(view)) {
4920 update_view_title(view);
4921 redraw_view_from(view, 0);
4923 return TRUE;
4926 if (!state->commit) {
4927 state->commit = read_blame_commit(view, line, state);
4928 string_format(view->ref, "%s %2d%%", view->vid,
4929 view->lines ? state->blamed * 100 / view->lines : 0);
4931 } else if (parse_blame_info(state->commit, line)) {
4932 state->commit = NULL;
4935 return TRUE;
4938 static bool
4939 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4941 struct blame_state *state = view->private;
4942 struct blame *blame = line->data;
4943 struct time *time = NULL;
4944 const char *id = NULL, *author = NULL, *filename = NULL;
4945 enum line_type id_type = LINE_BLAME_ID;
4946 static const enum line_type blame_colors[] = {
4947 LINE_PALETTE_0,
4948 LINE_PALETTE_1,
4949 LINE_PALETTE_2,
4950 LINE_PALETTE_3,
4951 LINE_PALETTE_4,
4952 LINE_PALETTE_5,
4953 LINE_PALETTE_6,
4956 #define BLAME_COLOR(i) \
4957 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
4959 if (blame->commit && *blame->commit->filename) {
4960 id = blame->commit->id;
4961 author = blame->commit->author;
4962 filename = blame->commit->filename;
4963 time = &blame->commit->time;
4964 id_type = BLAME_COLOR((long) blame->commit);
4967 if (draw_date(view, time))
4968 return TRUE;
4970 if (draw_author(view, author))
4971 return TRUE;
4973 if (draw_filename(view, filename, state->auto_filename_display))
4974 return TRUE;
4976 if (draw_field(view, id_type, id, ID_COLS, FALSE))
4977 return TRUE;
4979 if (draw_lineno(view, lineno))
4980 return TRUE;
4982 draw_text(view, LINE_DEFAULT, blame->text);
4983 return TRUE;
4986 static bool
4987 check_blame_commit(struct blame *blame, bool check_null_id)
4989 if (!blame->commit)
4990 report("Commit data not loaded yet");
4991 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4992 report("No commit exist for the selected line");
4993 else
4994 return TRUE;
4995 return FALSE;
4998 static void
4999 setup_blame_parent_line(struct view *view, struct blame *blame)
5001 char from[SIZEOF_REF + SIZEOF_STR];
5002 char to[SIZEOF_REF + SIZEOF_STR];
5003 const char *diff_tree_argv[] = {
5004 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
5005 "-U0", from, to, "--", NULL
5007 struct io io;
5008 int parent_lineno = -1;
5009 int blamed_lineno = -1;
5010 char *line;
5012 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5013 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5014 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5015 return;
5017 while ((line = io_get(&io, '\n', TRUE))) {
5018 if (*line == '@') {
5019 char *pos = strchr(line, '+');
5021 parent_lineno = atoi(line + 4);
5022 if (pos)
5023 blamed_lineno = atoi(pos + 1);
5025 } else if (*line == '+' && parent_lineno != -1) {
5026 if (blame->lineno == blamed_lineno - 1 &&
5027 !strcmp(blame->text, line + 1)) {
5028 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
5029 break;
5031 blamed_lineno++;
5035 io_done(&io);
5038 static enum request
5039 blame_request(struct view *view, enum request request, struct line *line)
5041 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5042 struct blame *blame = line->data;
5044 switch (request) {
5045 case REQ_VIEW_BLAME:
5046 if (check_blame_commit(blame, TRUE)) {
5047 string_copy(opt_ref, blame->commit->id);
5048 string_copy(opt_file, blame->commit->filename);
5049 if (blame->lineno)
5050 view->lineno = blame->lineno;
5051 reload_view(view);
5053 break;
5055 case REQ_PARENT:
5056 if (!check_blame_commit(blame, TRUE))
5057 break;
5058 if (!*blame->commit->parent_id) {
5059 report("The selected commit has no parents");
5060 } else {
5061 string_copy_rev(opt_ref, blame->commit->parent_id);
5062 string_copy(opt_file, blame->commit->parent_filename);
5063 setup_blame_parent_line(view, blame);
5064 opt_goto_line = blame->lineno;
5065 reload_view(view);
5067 break;
5069 case REQ_ENTER:
5070 if (!check_blame_commit(blame, FALSE))
5071 break;
5073 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5074 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5075 break;
5077 if (!strcmp(blame->commit->id, NULL_ID)) {
5078 struct view *diff = VIEW(REQ_VIEW_DIFF);
5079 const char *diff_index_argv[] = {
5080 "git", "diff-index", "--root", "--patch-with-stat",
5081 "-C", "-M", opt_diff_context_arg,
5082 "HEAD", "--", view->vid, NULL
5085 if (!*blame->commit->parent_id) {
5086 diff_index_argv[1] = "diff";
5087 diff_index_argv[2] = "--no-color";
5088 diff_index_argv[7] = "--";
5089 diff_index_argv[8] = "/dev/null";
5092 open_argv(view, diff, diff_index_argv, NULL, flags);
5093 if (diff->pipe)
5094 string_copy_rev(diff->ref, NULL_ID);
5095 } else {
5096 open_view(view, REQ_VIEW_DIFF, flags);
5098 break;
5100 default:
5101 return request;
5104 return REQ_NONE;
5107 static bool
5108 blame_grep(struct view *view, struct line *line)
5110 struct blame *blame = line->data;
5111 struct blame_commit *commit = blame->commit;
5112 const char *text[] = {
5113 blame->text,
5114 commit ? commit->title : "",
5115 commit ? commit->id : "",
5116 commit && opt_author ? commit->author : "",
5117 commit ? mkdate(&commit->time, opt_date) : "",
5118 NULL
5121 return grep_text(view, text);
5124 static void
5125 blame_select(struct view *view, struct line *line)
5127 struct blame *blame = line->data;
5128 struct blame_commit *commit = blame->commit;
5130 if (!commit)
5131 return;
5133 if (!strcmp(commit->id, NULL_ID))
5134 string_ncopy(ref_commit, "HEAD", 4);
5135 else
5136 string_copy_rev(ref_commit, commit->id);
5139 static struct view_ops blame_ops = {
5140 "line",
5141 VIEW_ALWAYS_LINENO,
5142 sizeof(struct blame_state),
5143 blame_open,
5144 blame_read,
5145 blame_draw,
5146 blame_request,
5147 blame_grep,
5148 blame_select,
5152 * Branch backend
5155 struct branch {
5156 const char *author; /* Author of the last commit. */
5157 struct time time; /* Date of the last activity. */
5158 const struct ref *ref; /* Name and commit ID information. */
5161 static const struct ref branch_all;
5163 static const enum sort_field branch_sort_fields[] = {
5164 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5166 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5168 struct branch_state {
5169 char id[SIZEOF_REV];
5172 static int
5173 branch_compare(const void *l1, const void *l2)
5175 const struct branch *branch1 = ((const struct line *) l1)->data;
5176 const struct branch *branch2 = ((const struct line *) l2)->data;
5178 if (branch1->ref == &branch_all)
5179 return -1;
5180 else if (branch2->ref == &branch_all)
5181 return 1;
5183 switch (get_sort_field(branch_sort_state)) {
5184 case ORDERBY_DATE:
5185 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5187 case ORDERBY_AUTHOR:
5188 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5190 case ORDERBY_NAME:
5191 default:
5192 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5196 static bool
5197 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5199 struct branch *branch = line->data;
5200 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5202 if (draw_date(view, &branch->time))
5203 return TRUE;
5205 if (draw_author(view, branch->author))
5206 return TRUE;
5208 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
5209 return TRUE;
5212 static enum request
5213 branch_request(struct view *view, enum request request, struct line *line)
5215 struct branch *branch = line->data;
5217 switch (request) {
5218 case REQ_REFRESH:
5219 load_refs();
5220 refresh_view(view);
5221 return REQ_NONE;
5223 case REQ_TOGGLE_SORT_FIELD:
5224 case REQ_TOGGLE_SORT_ORDER:
5225 sort_view(view, request, &branch_sort_state, branch_compare);
5226 return REQ_NONE;
5228 case REQ_ENTER:
5230 const struct ref *ref = branch->ref;
5231 const char *all_branches_argv[] = {
5232 "git", "log", "--no-color", "--pretty=raw", "--parents",
5233 "--topo-order",
5234 ref == &branch_all ? "--all" : ref->name, NULL
5236 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5238 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5239 return REQ_NONE;
5241 case REQ_JUMP_COMMIT:
5243 int lineno;
5245 for (lineno = 0; lineno < view->lines; lineno++) {
5246 struct branch *branch = view->line[lineno].data;
5248 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5249 select_view_line(view, lineno);
5250 report("");
5251 return REQ_NONE;
5255 default:
5256 return request;
5260 static bool
5261 branch_read(struct view *view, char *line)
5263 struct branch_state *state = view->private;
5264 struct branch *reference;
5265 size_t i;
5267 if (!line)
5268 return TRUE;
5270 switch (get_line_type(line)) {
5271 case LINE_COMMIT:
5272 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5273 return TRUE;
5275 case LINE_AUTHOR:
5276 for (i = 0, reference = NULL; i < view->lines; i++) {
5277 struct branch *branch = view->line[i].data;
5279 if (strcmp(branch->ref->id, state->id))
5280 continue;
5282 view->line[i].dirty = TRUE;
5283 if (reference) {
5284 branch->author = reference->author;
5285 branch->time = reference->time;
5286 continue;
5289 parse_author_line(line + STRING_SIZE("author "),
5290 &branch->author, &branch->time);
5291 reference = branch;
5293 return TRUE;
5295 default:
5296 return TRUE;
5301 static bool
5302 branch_open_visitor(void *data, const struct ref *ref)
5304 struct view *view = data;
5305 struct branch *branch;
5307 if (ref->tag || ref->ltag)
5308 return TRUE;
5310 branch = calloc(1, sizeof(*branch));
5311 if (!branch)
5312 return FALSE;
5314 branch->ref = ref;
5315 return !!add_line_data(view, branch, LINE_DEFAULT);
5318 static bool
5319 branch_open(struct view *view, enum open_flags flags)
5321 const char *branch_log[] = {
5322 "git", "log", "--no-color", "--pretty=raw",
5323 "--simplify-by-decoration", "--all", NULL
5326 if (!begin_update(view, NULL, branch_log, flags)) {
5327 report("Failed to load branch data");
5328 return TRUE;
5331 branch_open_visitor(view, &branch_all);
5332 foreach_ref(branch_open_visitor, view);
5333 view->p_restore = TRUE;
5335 return TRUE;
5338 static bool
5339 branch_grep(struct view *view, struct line *line)
5341 struct branch *branch = line->data;
5342 const char *text[] = {
5343 branch->ref->name,
5344 mkauthor(branch->author, opt_author_cols, opt_author),
5345 NULL
5348 return grep_text(view, text);
5351 static void
5352 branch_select(struct view *view, struct line *line)
5354 struct branch *branch = line->data;
5356 string_copy_rev(view->ref, branch->ref->id);
5357 string_copy_rev(ref_commit, branch->ref->id);
5358 string_copy_rev(ref_head, branch->ref->id);
5359 string_copy_rev(ref_branch, branch->ref->name);
5362 static struct view_ops branch_ops = {
5363 "branch",
5364 VIEW_NO_FLAGS,
5365 sizeof(struct branch_state),
5366 branch_open,
5367 branch_read,
5368 branch_draw,
5369 branch_request,
5370 branch_grep,
5371 branch_select,
5375 * Status backend
5378 struct status {
5379 char status;
5380 struct {
5381 mode_t mode;
5382 char rev[SIZEOF_REV];
5383 char name[SIZEOF_STR];
5384 } old;
5385 struct {
5386 mode_t mode;
5387 char rev[SIZEOF_REV];
5388 char name[SIZEOF_STR];
5389 } new;
5392 static char status_onbranch[SIZEOF_STR];
5393 static struct status stage_status;
5394 static enum line_type stage_line_type;
5396 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5398 /* This should work even for the "On branch" line. */
5399 static inline bool
5400 status_has_none(struct view *view, struct line *line)
5402 return line < view->line + view->lines && !line[1].data;
5405 /* Get fields from the diff line:
5406 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5408 static inline bool
5409 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5411 const char *old_mode = buf + 1;
5412 const char *new_mode = buf + 8;
5413 const char *old_rev = buf + 15;
5414 const char *new_rev = buf + 56;
5415 const char *status = buf + 97;
5417 if (bufsize < 98 ||
5418 old_mode[-1] != ':' ||
5419 new_mode[-1] != ' ' ||
5420 old_rev[-1] != ' ' ||
5421 new_rev[-1] != ' ' ||
5422 status[-1] != ' ')
5423 return FALSE;
5425 file->status = *status;
5427 string_copy_rev(file->old.rev, old_rev);
5428 string_copy_rev(file->new.rev, new_rev);
5430 file->old.mode = strtoul(old_mode, NULL, 8);
5431 file->new.mode = strtoul(new_mode, NULL, 8);
5433 file->old.name[0] = file->new.name[0] = 0;
5435 return TRUE;
5438 static bool
5439 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5441 struct status *unmerged = NULL;
5442 char *buf;
5443 struct io io;
5445 if (!io_run(&io, IO_RD, opt_cdup, argv))
5446 return FALSE;
5448 add_line_data(view, NULL, type);
5450 while ((buf = io_get(&io, 0, TRUE))) {
5451 struct status *file = unmerged;
5453 if (!file) {
5454 file = calloc(1, sizeof(*file));
5455 if (!file || !add_line_data(view, file, type))
5456 goto error_out;
5459 /* Parse diff info part. */
5460 if (status) {
5461 file->status = status;
5462 if (status == 'A')
5463 string_copy(file->old.rev, NULL_ID);
5465 } else if (!file->status || file == unmerged) {
5466 if (!status_get_diff(file, buf, strlen(buf)))
5467 goto error_out;
5469 buf = io_get(&io, 0, TRUE);
5470 if (!buf)
5471 break;
5473 /* Collapse all modified entries that follow an
5474 * associated unmerged entry. */
5475 if (unmerged == file) {
5476 unmerged->status = 'U';
5477 unmerged = NULL;
5478 } else if (file->status == 'U') {
5479 unmerged = file;
5483 /* Grab the old name for rename/copy. */
5484 if (!*file->old.name &&
5485 (file->status == 'R' || file->status == 'C')) {
5486 string_ncopy(file->old.name, buf, strlen(buf));
5488 buf = io_get(&io, 0, TRUE);
5489 if (!buf)
5490 break;
5493 /* git-ls-files just delivers a NUL separated list of
5494 * file names similar to the second half of the
5495 * git-diff-* output. */
5496 string_ncopy(file->new.name, buf, strlen(buf));
5497 if (!*file->old.name)
5498 string_copy(file->old.name, file->new.name);
5499 file = NULL;
5502 if (io_error(&io)) {
5503 error_out:
5504 io_done(&io);
5505 return FALSE;
5508 if (!view->line[view->lines - 1].data)
5509 add_line_data(view, NULL, LINE_STAT_NONE);
5511 io_done(&io);
5512 return TRUE;
5515 /* Don't show unmerged entries in the staged section. */
5516 static const char *status_diff_index_argv[] = {
5517 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
5518 "--cached", "-M", "HEAD", NULL
5521 static const char *status_diff_files_argv[] = {
5522 "git", "diff-files", "-z", NULL
5525 static const char *status_list_other_argv[] = {
5526 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5529 static const char *status_list_no_head_argv[] = {
5530 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5533 static const char *update_index_argv[] = {
5534 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5537 /* Restore the previous line number to stay in the context or select a
5538 * line with something that can be updated. */
5539 static void
5540 status_restore(struct view *view)
5542 if (view->p_lineno >= view->lines)
5543 view->p_lineno = view->lines - 1;
5544 while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
5545 view->p_lineno++;
5546 while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
5547 view->p_lineno--;
5549 /* If the above fails, always skip the "On branch" line. */
5550 if (view->p_lineno < view->lines)
5551 view->lineno = view->p_lineno;
5552 else
5553 view->lineno = 1;
5555 if (view->lineno < view->offset)
5556 view->offset = view->lineno;
5557 else if (view->offset + view->height <= view->lineno)
5558 view->offset = view->lineno - view->height + 1;
5560 view->p_restore = FALSE;
5563 static void
5564 status_update_onbranch(void)
5566 static const char *paths[][2] = {
5567 { "rebase-apply/rebasing", "Rebasing" },
5568 { "rebase-apply/applying", "Applying mailbox" },
5569 { "rebase-apply/", "Rebasing mailbox" },
5570 { "rebase-merge/interactive", "Interactive rebase" },
5571 { "rebase-merge/", "Rebase merge" },
5572 { "MERGE_HEAD", "Merging" },
5573 { "BISECT_LOG", "Bisecting" },
5574 { "HEAD", "On branch" },
5576 char buf[SIZEOF_STR];
5577 struct stat stat;
5578 int i;
5580 if (is_initial_commit()) {
5581 string_copy(status_onbranch, "Initial commit");
5582 return;
5585 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5586 char *head = opt_head;
5588 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5589 lstat(buf, &stat) < 0)
5590 continue;
5592 if (!*opt_head) {
5593 struct io io;
5595 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5596 io_read_buf(&io, buf, sizeof(buf))) {
5597 head = buf;
5598 if (!prefixcmp(head, "refs/heads/"))
5599 head += STRING_SIZE("refs/heads/");
5603 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5604 string_copy(status_onbranch, opt_head);
5605 return;
5608 string_copy(status_onbranch, "Not currently on any branch");
5611 /* First parse staged info using git-diff-index(1), then parse unstaged
5612 * info using git-diff-files(1), and finally untracked files using
5613 * git-ls-files(1). */
5614 static bool
5615 status_open(struct view *view, enum open_flags flags)
5617 reset_view(view);
5619 add_line_data(view, NULL, LINE_STAT_HEAD);
5620 status_update_onbranch();
5622 io_run_bg(update_index_argv);
5624 if (is_initial_commit()) {
5625 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5626 return FALSE;
5627 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5628 return FALSE;
5631 if (!opt_untracked_dirs_content)
5632 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5634 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5635 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5636 return FALSE;
5638 /* Restore the exact position or use the specialized restore
5639 * mode? */
5640 if (!view->p_restore)
5641 status_restore(view);
5642 return TRUE;
5645 static bool
5646 status_draw(struct view *view, struct line *line, unsigned int lineno)
5648 struct status *status = line->data;
5649 enum line_type type;
5650 const char *text;
5652 if (!status) {
5653 switch (line->type) {
5654 case LINE_STAT_STAGED:
5655 type = LINE_STAT_SECTION;
5656 text = "Changes to be committed:";
5657 break;
5659 case LINE_STAT_UNSTAGED:
5660 type = LINE_STAT_SECTION;
5661 text = "Changed but not updated:";
5662 break;
5664 case LINE_STAT_UNTRACKED:
5665 type = LINE_STAT_SECTION;
5666 text = "Untracked files:";
5667 break;
5669 case LINE_STAT_NONE:
5670 type = LINE_DEFAULT;
5671 text = " (no files)";
5672 break;
5674 case LINE_STAT_HEAD:
5675 type = LINE_STAT_HEAD;
5676 text = status_onbranch;
5677 break;
5679 default:
5680 return FALSE;
5682 } else {
5683 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5685 buf[0] = status->status;
5686 if (draw_text(view, line->type, buf))
5687 return TRUE;
5688 type = LINE_DEFAULT;
5689 text = status->new.name;
5692 draw_text(view, type, text);
5693 return TRUE;
5696 static enum request
5697 status_enter(struct view *view, struct line *line)
5699 struct status *status = line->data;
5700 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5702 if (line->type == LINE_STAT_NONE ||
5703 (!status && line[1].type == LINE_STAT_NONE)) {
5704 report("No file to diff");
5705 return REQ_NONE;
5708 switch (line->type) {
5709 case LINE_STAT_STAGED:
5710 case LINE_STAT_UNSTAGED:
5711 break;
5713 case LINE_STAT_UNTRACKED:
5714 if (!status) {
5715 report("No file to show");
5716 return REQ_NONE;
5719 if (!suffixcmp(status->new.name, -1, "/")) {
5720 report("Cannot display a directory");
5721 return REQ_NONE;
5723 break;
5725 case LINE_STAT_HEAD:
5726 return REQ_NONE;
5728 default:
5729 die("line type %d not handled in switch", line->type);
5732 if (status) {
5733 stage_status = *status;
5734 } else {
5735 memset(&stage_status, 0, sizeof(stage_status));
5738 stage_line_type = line->type;
5740 open_view(view, REQ_VIEW_STAGE, flags);
5741 return REQ_NONE;
5744 static bool
5745 status_exists(struct view *view, struct status *status, enum line_type type)
5747 unsigned long lineno;
5749 for (lineno = 0; lineno < view->lines; lineno++) {
5750 struct line *line = &view->line[lineno];
5751 struct status *pos = line->data;
5753 if (line->type != type)
5754 continue;
5755 if (!pos && (!status || !status->status) && line[1].data) {
5756 select_view_line(view, lineno);
5757 return TRUE;
5759 if (pos && !strcmp(status->new.name, pos->new.name)) {
5760 select_view_line(view, lineno);
5761 return TRUE;
5765 return FALSE;
5769 static bool
5770 status_update_prepare(struct io *io, enum line_type type)
5772 const char *staged_argv[] = {
5773 "git", "update-index", "-z", "--index-info", NULL
5775 const char *others_argv[] = {
5776 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5779 switch (type) {
5780 case LINE_STAT_STAGED:
5781 return io_run(io, IO_WR, opt_cdup, staged_argv);
5783 case LINE_STAT_UNSTAGED:
5784 case LINE_STAT_UNTRACKED:
5785 return io_run(io, IO_WR, opt_cdup, others_argv);
5787 default:
5788 die("line type %d not handled in switch", type);
5789 return FALSE;
5793 static bool
5794 status_update_write(struct io *io, struct status *status, enum line_type type)
5796 switch (type) {
5797 case LINE_STAT_STAGED:
5798 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
5799 status->old.rev, status->old.name, 0);
5801 case LINE_STAT_UNSTAGED:
5802 case LINE_STAT_UNTRACKED:
5803 return io_printf(io, "%s%c", status->new.name, 0);
5805 default:
5806 die("line type %d not handled in switch", type);
5807 return FALSE;
5811 static bool
5812 status_update_file(struct status *status, enum line_type type)
5814 struct io io;
5815 bool result;
5817 if (!status_update_prepare(&io, type))
5818 return FALSE;
5820 result = status_update_write(&io, status, type);
5821 return io_done(&io) && result;
5824 static bool
5825 status_update_files(struct view *view, struct line *line)
5827 char buf[sizeof(view->ref)];
5828 struct io io;
5829 bool result = TRUE;
5830 struct line *pos = view->line + view->lines;
5831 int files = 0;
5832 int file, done;
5833 int cursor_y = -1, cursor_x = -1;
5835 if (!status_update_prepare(&io, line->type))
5836 return FALSE;
5838 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5839 files++;
5841 string_copy(buf, view->ref);
5842 getsyx(cursor_y, cursor_x);
5843 for (file = 0, done = 5; result && file < files; line++, file++) {
5844 int almost_done = file * 100 / files;
5846 if (almost_done > done) {
5847 done = almost_done;
5848 string_format(view->ref, "updating file %u of %u (%d%% done)",
5849 file, files, done);
5850 update_view_title(view);
5851 setsyx(cursor_y, cursor_x);
5852 doupdate();
5854 result = status_update_write(&io, line->data, line->type);
5856 string_copy(view->ref, buf);
5858 return io_done(&io) && result;
5861 static bool
5862 status_update(struct view *view)
5864 struct line *line = &view->line[view->lineno];
5866 assert(view->lines);
5868 if (!line->data) {
5869 /* This should work even for the "On branch" line. */
5870 if (line < view->line + view->lines && !line[1].data) {
5871 report("Nothing to update");
5872 return FALSE;
5875 if (!status_update_files(view, line + 1)) {
5876 report("Failed to update file status");
5877 return FALSE;
5880 } else if (!status_update_file(line->data, line->type)) {
5881 report("Failed to update file status");
5882 return FALSE;
5885 return TRUE;
5888 static bool
5889 status_revert(struct status *status, enum line_type type, bool has_none)
5891 if (!status || type != LINE_STAT_UNSTAGED) {
5892 if (type == LINE_STAT_STAGED) {
5893 report("Cannot revert changes to staged files");
5894 } else if (type == LINE_STAT_UNTRACKED) {
5895 report("Cannot revert changes to untracked files");
5896 } else if (has_none) {
5897 report("Nothing to revert");
5898 } else {
5899 report("Cannot revert changes to multiple files");
5902 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5903 char mode[10] = "100644";
5904 const char *reset_argv[] = {
5905 "git", "update-index", "--cacheinfo", mode,
5906 status->old.rev, status->old.name, NULL
5908 const char *checkout_argv[] = {
5909 "git", "checkout", "--", status->old.name, NULL
5912 if (status->status == 'U') {
5913 string_format(mode, "%5o", status->old.mode);
5915 if (status->old.mode == 0 && status->new.mode == 0) {
5916 reset_argv[2] = "--force-remove";
5917 reset_argv[3] = status->old.name;
5918 reset_argv[4] = NULL;
5921 if (!io_run_fg(reset_argv, opt_cdup))
5922 return FALSE;
5923 if (status->old.mode == 0 && status->new.mode == 0)
5924 return TRUE;
5927 return io_run_fg(checkout_argv, opt_cdup);
5930 return FALSE;
5933 static enum request
5934 status_request(struct view *view, enum request request, struct line *line)
5936 struct status *status = line->data;
5938 switch (request) {
5939 case REQ_STATUS_UPDATE:
5940 if (!status_update(view))
5941 return REQ_NONE;
5942 break;
5944 case REQ_STATUS_REVERT:
5945 if (!status_revert(status, line->type, status_has_none(view, line)))
5946 return REQ_NONE;
5947 break;
5949 case REQ_STATUS_MERGE:
5950 if (!status || status->status != 'U') {
5951 report("Merging only possible for files with unmerged status ('U').");
5952 return REQ_NONE;
5954 open_mergetool(status->new.name);
5955 break;
5957 case REQ_EDIT:
5958 if (!status)
5959 return request;
5960 if (status->status == 'D') {
5961 report("File has been deleted.");
5962 return REQ_NONE;
5965 open_editor(status->new.name);
5966 break;
5968 case REQ_VIEW_BLAME:
5969 if (status)
5970 opt_ref[0] = 0;
5971 return request;
5973 case REQ_ENTER:
5974 /* After returning the status view has been split to
5975 * show the stage view. No further reloading is
5976 * necessary. */
5977 return status_enter(view, line);
5979 case REQ_REFRESH:
5980 /* Simply reload the view. */
5981 break;
5983 default:
5984 return request;
5987 refresh_view(view);
5989 return REQ_NONE;
5992 static void
5993 status_select(struct view *view, struct line *line)
5995 struct status *status = line->data;
5996 char file[SIZEOF_STR] = "all files";
5997 const char *text;
5998 const char *key;
6000 if (status && !string_format(file, "'%s'", status->new.name))
6001 return;
6003 if (!status && line[1].type == LINE_STAT_NONE)
6004 line++;
6006 switch (line->type) {
6007 case LINE_STAT_STAGED:
6008 text = "Press %s to unstage %s for commit";
6009 break;
6011 case LINE_STAT_UNSTAGED:
6012 text = "Press %s to stage %s for commit";
6013 break;
6015 case LINE_STAT_UNTRACKED:
6016 text = "Press %s to stage %s for addition";
6017 break;
6019 case LINE_STAT_HEAD:
6020 case LINE_STAT_NONE:
6021 text = "Nothing to update";
6022 break;
6024 default:
6025 die("line type %d not handled in switch", line->type);
6028 if (status && status->status == 'U') {
6029 text = "Press %s to resolve conflict in %s";
6030 key = get_view_key(view, REQ_STATUS_MERGE);
6032 } else {
6033 key = get_view_key(view, REQ_STATUS_UPDATE);
6036 string_format(view->ref, text, key, file);
6037 if (status)
6038 string_copy(opt_file, status->new.name);
6041 static bool
6042 status_grep(struct view *view, struct line *line)
6044 struct status *status = line->data;
6046 if (status) {
6047 const char buf[2] = { status->status, 0 };
6048 const char *text[] = { status->new.name, buf, NULL };
6050 return grep_text(view, text);
6053 return FALSE;
6056 static struct view_ops status_ops = {
6057 "file",
6058 VIEW_CUSTOM_STATUS,
6060 status_open,
6061 NULL,
6062 status_draw,
6063 status_request,
6064 status_grep,
6065 status_select,
6069 struct stage_state {
6070 struct diff_state diff;
6071 size_t chunks;
6072 int *chunk;
6075 static bool
6076 stage_diff_write(struct io *io, struct line *line, struct line *end)
6078 while (line < end) {
6079 if (!io_write(io, line->data, strlen(line->data)) ||
6080 !io_write(io, "\n", 1))
6081 return FALSE;
6082 line++;
6083 if (line->type == LINE_DIFF_CHUNK ||
6084 line->type == LINE_DIFF_HEADER)
6085 break;
6088 return TRUE;
6091 static bool
6092 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6094 const char *apply_argv[SIZEOF_ARG] = {
6095 "git", "apply", "--whitespace=nowarn", NULL
6097 struct line *diff_hdr;
6098 struct io io;
6099 int argc = 3;
6101 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6102 if (!diff_hdr)
6103 return FALSE;
6105 if (!revert)
6106 apply_argv[argc++] = "--cached";
6107 if (line != NULL)
6108 apply_argv[argc++] = "--unidiff-zero";
6109 if (revert || stage_line_type == LINE_STAT_STAGED)
6110 apply_argv[argc++] = "-R";
6111 apply_argv[argc++] = "-";
6112 apply_argv[argc++] = NULL;
6113 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6114 return FALSE;
6116 if (line != NULL) {
6117 int lineno = 0;
6118 struct line *context = chunk + 1;
6119 const char *markers[] = {
6120 line->type == LINE_DIFF_DEL ? "" : ",0",
6121 line->type == LINE_DIFF_DEL ? ",0" : "",
6124 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6126 while (context < line) {
6127 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6128 break;
6129 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6130 lineno++;
6132 context++;
6135 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6136 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6137 lineno, markers[0], lineno, markers[1]) ||
6138 !stage_diff_write(&io, line, line + 1)) {
6139 chunk = NULL;
6141 } else {
6142 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6143 !stage_diff_write(&io, chunk, view->line + view->lines))
6144 chunk = NULL;
6147 io_done(&io);
6148 io_run_bg(update_index_argv);
6150 return chunk ? TRUE : FALSE;
6153 static bool
6154 stage_update(struct view *view, struct line *line, bool single)
6156 struct line *chunk = NULL;
6158 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6159 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6161 if (chunk) {
6162 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6163 report("Failed to apply chunk");
6164 return FALSE;
6167 } else if (!stage_status.status) {
6168 view = view->parent;
6170 for (line = view->line; line < view->line + view->lines; line++)
6171 if (line->type == stage_line_type)
6172 break;
6174 if (!status_update_files(view, line + 1)) {
6175 report("Failed to update files");
6176 return FALSE;
6179 } else if (!status_update_file(&stage_status, stage_line_type)) {
6180 report("Failed to update file");
6181 return FALSE;
6184 return TRUE;
6187 static bool
6188 stage_revert(struct view *view, struct line *line)
6190 struct line *chunk = NULL;
6192 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6193 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6195 if (chunk) {
6196 if (!prompt_yesno("Are you sure you want to revert changes?"))
6197 return FALSE;
6199 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6200 report("Failed to revert chunk");
6201 return FALSE;
6203 return TRUE;
6205 } else {
6206 return status_revert(stage_status.status ? &stage_status : NULL,
6207 stage_line_type, FALSE);
6212 static void
6213 stage_next(struct view *view, struct line *line)
6215 struct stage_state *state = view->private;
6216 int i;
6218 if (!state->chunks) {
6219 for (line = view->line; line < view->line + view->lines; line++) {
6220 if (line->type != LINE_DIFF_CHUNK)
6221 continue;
6223 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6224 report("Allocation failure");
6225 return;
6228 state->chunk[state->chunks++] = line - view->line;
6232 for (i = 0; i < state->chunks; i++) {
6233 if (state->chunk[i] > view->lineno) {
6234 do_scroll_view(view, state->chunk[i] - view->lineno);
6235 report("Chunk %d of %d", i + 1, state->chunks);
6236 return;
6240 report("No next chunk found");
6243 static enum request
6244 stage_request(struct view *view, enum request request, struct line *line)
6246 switch (request) {
6247 case REQ_STATUS_UPDATE:
6248 if (!stage_update(view, line, FALSE))
6249 return REQ_NONE;
6250 break;
6252 case REQ_STATUS_REVERT:
6253 if (!stage_revert(view, line))
6254 return REQ_NONE;
6255 break;
6257 case REQ_STAGE_UPDATE_LINE:
6258 if (stage_line_type == LINE_STAT_UNTRACKED ||
6259 stage_status.status == 'A') {
6260 report("Staging single lines is not supported for new files");
6261 return REQ_NONE;
6263 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6264 report("Please select a change to stage");
6265 return REQ_NONE;
6267 if (!stage_update(view, line, TRUE))
6268 return REQ_NONE;
6269 break;
6271 case REQ_STAGE_NEXT:
6272 if (stage_line_type == LINE_STAT_UNTRACKED) {
6273 report("File is untracked; press %s to add",
6274 get_view_key(view, REQ_STATUS_UPDATE));
6275 return REQ_NONE;
6277 stage_next(view, line);
6278 return REQ_NONE;
6280 case REQ_EDIT:
6281 if (!stage_status.new.name[0])
6282 return request;
6283 if (stage_status.status == 'D') {
6284 report("File has been deleted.");
6285 return REQ_NONE;
6288 open_editor(stage_status.new.name);
6289 break;
6291 case REQ_REFRESH:
6292 /* Reload everything ... */
6293 break;
6295 case REQ_VIEW_BLAME:
6296 if (stage_status.new.name[0]) {
6297 string_copy(opt_file, stage_status.new.name);
6298 opt_ref[0] = 0;
6300 return request;
6302 case REQ_ENTER:
6303 return diff_common_enter(view, request, line);
6305 case REQ_DIFF_CONTEXT_UP:
6306 case REQ_DIFF_CONTEXT_DOWN:
6307 if (!update_diff_context(request))
6308 return REQ_NONE;
6309 break;
6311 default:
6312 return request;
6315 refresh_view(view->parent);
6317 /* Check whether the staged entry still exists, and close the
6318 * stage view if it doesn't. */
6319 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6320 status_restore(view->parent);
6321 return REQ_VIEW_CLOSE;
6324 refresh_view(view);
6326 return REQ_NONE;
6329 static bool
6330 stage_open(struct view *view, enum open_flags flags)
6332 static const char *no_head_diff_argv[] = {
6333 "git", "diff", "--no-color", "--patch-with-stat",
6334 opt_diff_context_arg,
6335 "--", "/dev/null", stage_status.new.name, NULL
6337 static const char *index_show_argv[] = {
6338 "git", "diff-index", "--root", "--patch-with-stat", "-C", "-M",
6339 "--cached", opt_diff_context_arg, "HEAD", "--",
6340 stage_status.old.name, stage_status.new.name, NULL
6342 static const char *files_show_argv[] = {
6343 "git", "diff-files", "--root", "--patch-with-stat",
6344 "-C", "-M", opt_diff_context_arg, "--",
6345 stage_status.old.name, stage_status.new.name, NULL
6347 /* Diffs for unmerged entries are empty when passing the new
6348 * path, so leave out the new path. */
6349 static const char *files_unmerged_argv[] = {
6350 "git", "diff-files", "--root", "--patch-with-stat",
6351 "-C", "-M", opt_diff_context_arg, "--",
6352 stage_status.old.name, NULL
6354 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6355 const char **argv = NULL;
6356 const char *info;
6358 switch (stage_line_type) {
6359 case LINE_STAT_STAGED:
6360 if (is_initial_commit()) {
6361 argv = no_head_diff_argv;
6362 } else {
6363 argv = index_show_argv;
6365 if (stage_status.status)
6366 info = "Staged changes to %s";
6367 else
6368 info = "Staged changes";
6369 break;
6371 case LINE_STAT_UNSTAGED:
6372 if (stage_status.status != 'U')
6373 argv = files_show_argv;
6374 else
6375 argv = files_unmerged_argv;
6376 if (stage_status.status)
6377 info = "Unstaged changes to %s";
6378 else
6379 info = "Unstaged changes";
6380 break;
6382 case LINE_STAT_UNTRACKED:
6383 info = "Untracked file %s";
6384 argv = file_argv;
6385 break;
6387 case LINE_STAT_HEAD:
6388 default:
6389 die("line type %d not handled in switch", stage_line_type);
6392 string_format(view->ref, info, stage_status.new.name);
6393 view->vid[0] = 0;
6394 view->dir = opt_cdup;
6395 return argv_copy(&view->argv, argv)
6396 && begin_update(view, NULL, NULL, flags);
6399 static bool
6400 stage_read(struct view *view, char *data)
6402 struct stage_state *state = view->private;
6404 if (data && diff_common_read(view, data, &state->diff))
6405 return TRUE;
6407 return pager_read(view, data);
6410 static struct view_ops stage_ops = {
6411 "line",
6412 VIEW_NO_FLAGS,
6413 sizeof(struct stage_state),
6414 stage_open,
6415 stage_read,
6416 diff_common_draw,
6417 stage_request,
6418 pager_grep,
6419 pager_select,
6424 * Revision graph
6427 static const enum line_type graph_colors[] = {
6428 LINE_PALETTE_0,
6429 LINE_PALETTE_1,
6430 LINE_PALETTE_2,
6431 LINE_PALETTE_3,
6432 LINE_PALETTE_4,
6433 LINE_PALETTE_5,
6434 LINE_PALETTE_6,
6437 static enum line_type get_graph_color(struct graph_symbol *symbol)
6439 if (symbol->commit)
6440 return LINE_GRAPH_COMMIT;
6441 assert(symbol->color < ARRAY_SIZE(graph_colors));
6442 return graph_colors[symbol->color];
6445 static bool
6446 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6448 const char *chars = graph_symbol_to_utf8(symbol);
6450 return draw_text(view, color, chars + !!first);
6453 static bool
6454 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6456 const char *chars = graph_symbol_to_ascii(symbol);
6458 return draw_text(view, color, chars + !!first);
6461 static bool
6462 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6464 const chtype *chars = graph_symbol_to_chtype(symbol);
6466 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6469 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6471 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6473 static const draw_graph_fn fns[] = {
6474 draw_graph_ascii,
6475 draw_graph_chtype,
6476 draw_graph_utf8
6478 draw_graph_fn fn = fns[opt_line_graphics];
6479 int i;
6481 for (i = 0; i < canvas->size; i++) {
6482 struct graph_symbol *symbol = &canvas->symbols[i];
6483 enum line_type color = get_graph_color(symbol);
6485 if (fn(view, symbol, color, i == 0))
6486 return TRUE;
6489 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6493 * Main view backend
6496 struct commit {
6497 char id[SIZEOF_REV]; /* SHA1 ID. */
6498 char title[128]; /* First line of the commit message. */
6499 const char *author; /* Author of the commit. */
6500 struct time time; /* Date from the author ident. */
6501 struct ref_list *refs; /* Repository references. */
6502 struct graph_canvas graph; /* Ancestry chain graphics. */
6505 static bool
6506 main_open(struct view *view, enum open_flags flags)
6508 static const char *main_argv[] = {
6509 "git", "log", "--no-color", "--pretty=raw", "--parents",
6510 "--topo-order", "%(diffargs)", "%(revargs)",
6511 "--", "%(fileargs)", NULL
6514 return begin_update(view, NULL, main_argv, flags);
6517 static bool
6518 main_draw(struct view *view, struct line *line, unsigned int lineno)
6520 struct commit *commit = line->data;
6522 if (!commit->author)
6523 return FALSE;
6525 if (opt_line_number && draw_lineno(view, lineno))
6526 return TRUE;
6528 if (draw_date(view, &commit->time))
6529 return TRUE;
6531 if (draw_author(view, commit->author))
6532 return TRUE;
6534 if (opt_rev_graph && draw_graph(view, &commit->graph))
6535 return TRUE;
6537 if (draw_refs(view, commit->refs))
6538 return TRUE;
6540 draw_text(view, LINE_DEFAULT, commit->title);
6541 return TRUE;
6544 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6545 static bool
6546 main_read(struct view *view, char *line)
6548 struct graph *graph = view->private;
6549 enum line_type type;
6550 struct commit *commit;
6552 if (!line) {
6553 if (!view->lines && !view->prev)
6554 die("No revisions match the given arguments.");
6555 if (view->lines > 0) {
6556 commit = view->line[view->lines - 1].data;
6557 view->line[view->lines - 1].dirty = 1;
6558 if (!commit->author) {
6559 view->lines--;
6560 free(commit);
6564 done_graph(graph);
6565 return TRUE;
6568 type = get_line_type(line);
6569 if (type == LINE_COMMIT) {
6570 bool is_boundary;
6572 commit = calloc(1, sizeof(struct commit));
6573 if (!commit)
6574 return FALSE;
6576 line += STRING_SIZE("commit ");
6577 is_boundary = *line == '-';
6578 if (is_boundary)
6579 line++;
6581 string_copy_rev(commit->id, line);
6582 commit->refs = get_ref_list(commit->id);
6583 add_line_data(view, commit, LINE_MAIN_COMMIT);
6584 graph_add_commit(graph, &commit->graph, commit->id, line, is_boundary);
6585 return TRUE;
6588 if (!view->lines)
6589 return TRUE;
6590 commit = view->line[view->lines - 1].data;
6592 switch (type) {
6593 case LINE_PARENT:
6594 if (!graph->has_parents)
6595 graph_add_parent(graph, line + STRING_SIZE("parent "));
6596 break;
6598 case LINE_AUTHOR:
6599 parse_author_line(line + STRING_SIZE("author "),
6600 &commit->author, &commit->time);
6601 graph_render_parents(graph);
6602 break;
6604 default:
6605 /* Fill in the commit title if it has not already been set. */
6606 if (commit->title[0])
6607 break;
6609 /* Require titles to start with a non-space character at the
6610 * offset used by git log. */
6611 if (strncmp(line, " ", 4))
6612 break;
6613 line += 4;
6614 /* Well, if the title starts with a whitespace character,
6615 * try to be forgiving. Otherwise we end up with no title. */
6616 while (isspace(*line))
6617 line++;
6618 if (*line == '\0')
6619 break;
6620 /* FIXME: More graceful handling of titles; append "..." to
6621 * shortened titles, etc. */
6623 string_expand(commit->title, sizeof(commit->title), line, 1);
6624 view->line[view->lines - 1].dirty = 1;
6627 return TRUE;
6630 static enum request
6631 main_request(struct view *view, enum request request, struct line *line)
6633 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6635 switch (request) {
6636 case REQ_ENTER:
6637 if (view_is_displayed(view) && display[0] != view)
6638 maximize_view(view, TRUE);
6639 open_view(view, REQ_VIEW_DIFF, flags);
6640 break;
6641 case REQ_REFRESH:
6642 load_refs();
6643 refresh_view(view);
6644 break;
6646 case REQ_JUMP_COMMIT:
6648 int lineno;
6650 for (lineno = 0; lineno < view->lines; lineno++) {
6651 struct commit *commit = view->line[lineno].data;
6653 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
6654 select_view_line(view, lineno);
6655 report("");
6656 return REQ_NONE;
6660 report("Unable to find commit '%s'", opt_search);
6661 break;
6663 default:
6664 return request;
6667 return REQ_NONE;
6670 static bool
6671 grep_refs(struct ref_list *list, regex_t *regex)
6673 regmatch_t pmatch;
6674 size_t i;
6676 if (!opt_show_refs || !list)
6677 return FALSE;
6679 for (i = 0; i < list->size; i++) {
6680 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
6681 return TRUE;
6684 return FALSE;
6687 static bool
6688 main_grep(struct view *view, struct line *line)
6690 struct commit *commit = line->data;
6691 const char *text[] = {
6692 commit->title,
6693 mkauthor(commit->author, opt_author_cols, opt_author),
6694 mkdate(&commit->time, opt_date),
6695 NULL
6698 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
6701 static void
6702 main_select(struct view *view, struct line *line)
6704 struct commit *commit = line->data;
6706 string_copy_rev(view->ref, commit->id);
6707 string_copy_rev(ref_commit, view->ref);
6710 static struct view_ops main_ops = {
6711 "commit",
6712 VIEW_NO_FLAGS,
6713 sizeof(struct graph),
6714 main_open,
6715 main_read,
6716 main_draw,
6717 main_request,
6718 main_grep,
6719 main_select,
6724 * Status management
6727 /* Whether or not the curses interface has been initialized. */
6728 static bool cursed = FALSE;
6730 /* Terminal hacks and workarounds. */
6731 static bool use_scroll_redrawwin;
6732 static bool use_scroll_status_wclear;
6734 /* The status window is used for polling keystrokes. */
6735 static WINDOW *status_win;
6737 /* Reading from the prompt? */
6738 static bool input_mode = FALSE;
6740 static bool status_empty = FALSE;
6742 /* Update status and title window. */
6743 static void
6744 report(const char *msg, ...)
6746 struct view *view = display[current_view];
6748 if (input_mode)
6749 return;
6751 if (!view) {
6752 char buf[SIZEOF_STR];
6753 int retval;
6755 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
6756 die("%s", buf);
6759 if (!status_empty || *msg) {
6760 va_list args;
6762 va_start(args, msg);
6764 wmove(status_win, 0, 0);
6765 if (view->has_scrolled && use_scroll_status_wclear)
6766 wclear(status_win);
6767 if (*msg) {
6768 vwprintw(status_win, msg, args);
6769 status_empty = FALSE;
6770 } else {
6771 status_empty = TRUE;
6773 wclrtoeol(status_win);
6774 wnoutrefresh(status_win);
6776 va_end(args);
6779 update_view_title(view);
6782 static void
6783 init_display(void)
6785 const char *term;
6786 int x, y;
6788 /* Initialize the curses library */
6789 if (isatty(STDIN_FILENO)) {
6790 cursed = !!initscr();
6791 opt_tty = stdin;
6792 } else {
6793 /* Leave stdin and stdout alone when acting as a pager. */
6794 opt_tty = fopen("/dev/tty", "r+");
6795 if (!opt_tty)
6796 die("Failed to open /dev/tty");
6797 cursed = !!newterm(NULL, opt_tty, opt_tty);
6800 if (!cursed)
6801 die("Failed to initialize curses");
6803 nonl(); /* Disable conversion and detect newlines from input. */
6804 cbreak(); /* Take input chars one at a time, no wait for \n */
6805 noecho(); /* Don't echo input */
6806 leaveok(stdscr, FALSE);
6808 if (has_colors())
6809 init_colors();
6811 getmaxyx(stdscr, y, x);
6812 status_win = newwin(1, x, y - 1, 0);
6813 if (!status_win)
6814 die("Failed to create status window");
6816 /* Enable keyboard mapping */
6817 keypad(status_win, TRUE);
6818 wbkgdset(status_win, get_line_attr(LINE_STATUS));
6820 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6821 set_tabsize(opt_tab_size);
6822 #else
6823 TABSIZE = opt_tab_size;
6824 #endif
6826 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6827 if (term && !strcmp(term, "gnome-terminal")) {
6828 /* In the gnome-terminal-emulator, the message from
6829 * scrolling up one line when impossible followed by
6830 * scrolling down one line causes corruption of the
6831 * status line. This is fixed by calling wclear. */
6832 use_scroll_status_wclear = TRUE;
6833 use_scroll_redrawwin = FALSE;
6835 } else if (term && !strcmp(term, "xrvt-xpm")) {
6836 /* No problems with full optimizations in xrvt-(unicode)
6837 * and aterm. */
6838 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6840 } else {
6841 /* When scrolling in (u)xterm the last line in the
6842 * scrolling direction will update slowly. */
6843 use_scroll_redrawwin = TRUE;
6844 use_scroll_status_wclear = FALSE;
6848 static int
6849 get_input(int prompt_position)
6851 struct view *view;
6852 int i, key, cursor_y, cursor_x;
6854 if (prompt_position)
6855 input_mode = TRUE;
6857 while (TRUE) {
6858 bool loading = FALSE;
6860 foreach_view (view, i) {
6861 update_view(view);
6862 if (view_is_displayed(view) && view->has_scrolled &&
6863 use_scroll_redrawwin)
6864 redrawwin(view->win);
6865 view->has_scrolled = FALSE;
6866 if (view->pipe)
6867 loading = TRUE;
6870 /* Update the cursor position. */
6871 if (prompt_position) {
6872 getbegyx(status_win, cursor_y, cursor_x);
6873 cursor_x = prompt_position;
6874 } else {
6875 view = display[current_view];
6876 getbegyx(view->win, cursor_y, cursor_x);
6877 cursor_x = view->width - 1;
6878 cursor_y += view->lineno - view->offset;
6880 setsyx(cursor_y, cursor_x);
6882 /* Refresh, accept single keystroke of input */
6883 doupdate();
6884 nodelay(status_win, loading);
6885 key = wgetch(status_win);
6887 /* wgetch() with nodelay() enabled returns ERR when
6888 * there's no input. */
6889 if (key == ERR) {
6891 } else if (key == KEY_RESIZE) {
6892 int height, width;
6894 getmaxyx(stdscr, height, width);
6896 wresize(status_win, 1, width);
6897 mvwin(status_win, height - 1, 0);
6898 wnoutrefresh(status_win);
6899 resize_display();
6900 redraw_display(TRUE);
6902 } else {
6903 input_mode = FALSE;
6904 if (key == erasechar())
6905 key = KEY_BACKSPACE;
6906 return key;
6911 static char *
6912 prompt_input(const char *prompt, input_handler handler, void *data)
6914 enum input_status status = INPUT_OK;
6915 static char buf[SIZEOF_STR];
6916 size_t pos = 0;
6918 buf[pos] = 0;
6920 while (status == INPUT_OK || status == INPUT_SKIP) {
6921 int key;
6923 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6924 wclrtoeol(status_win);
6926 key = get_input(pos + 1);
6927 switch (key) {
6928 case KEY_RETURN:
6929 case KEY_ENTER:
6930 case '\n':
6931 status = pos ? INPUT_STOP : INPUT_CANCEL;
6932 break;
6934 case KEY_BACKSPACE:
6935 if (pos > 0)
6936 buf[--pos] = 0;
6937 else
6938 status = INPUT_CANCEL;
6939 break;
6941 case KEY_ESC:
6942 status = INPUT_CANCEL;
6943 break;
6945 default:
6946 if (pos >= sizeof(buf)) {
6947 report("Input string too long");
6948 return NULL;
6951 status = handler(data, buf, key);
6952 if (status == INPUT_OK)
6953 buf[pos++] = (char) key;
6957 /* Clear the status window */
6958 status_empty = FALSE;
6959 report("");
6961 if (status == INPUT_CANCEL)
6962 return NULL;
6964 buf[pos++] = 0;
6966 return buf;
6969 static enum input_status
6970 prompt_yesno_handler(void *data, char *buf, int c)
6972 if (c == 'y' || c == 'Y')
6973 return INPUT_STOP;
6974 if (c == 'n' || c == 'N')
6975 return INPUT_CANCEL;
6976 return INPUT_SKIP;
6979 static bool
6980 prompt_yesno(const char *prompt)
6982 char prompt2[SIZEOF_STR];
6984 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6985 return FALSE;
6987 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6990 static enum input_status
6991 read_prompt_handler(void *data, char *buf, int c)
6993 return isprint(c) ? INPUT_OK : INPUT_SKIP;
6996 static char *
6997 read_prompt(const char *prompt)
6999 return prompt_input(prompt, read_prompt_handler, NULL);
7002 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7004 enum input_status status = INPUT_OK;
7005 int size = 0;
7007 while (items[size].text)
7008 size++;
7010 while (status == INPUT_OK) {
7011 const struct menu_item *item = &items[*selected];
7012 int key;
7013 int i;
7015 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7016 prompt, *selected + 1, size);
7017 if (item->hotkey)
7018 wprintw(status_win, "[%c] ", (char) item->hotkey);
7019 wprintw(status_win, "%s", item->text);
7020 wclrtoeol(status_win);
7022 key = get_input(COLS - 1);
7023 switch (key) {
7024 case KEY_RETURN:
7025 case KEY_ENTER:
7026 case '\n':
7027 status = INPUT_STOP;
7028 break;
7030 case KEY_LEFT:
7031 case KEY_UP:
7032 *selected = *selected - 1;
7033 if (*selected < 0)
7034 *selected = size - 1;
7035 break;
7037 case KEY_RIGHT:
7038 case KEY_DOWN:
7039 *selected = (*selected + 1) % size;
7040 break;
7042 case KEY_ESC:
7043 status = INPUT_CANCEL;
7044 break;
7046 default:
7047 for (i = 0; items[i].text; i++)
7048 if (items[i].hotkey == key) {
7049 *selected = i;
7050 status = INPUT_STOP;
7051 break;
7056 /* Clear the status window */
7057 status_empty = FALSE;
7058 report("");
7060 return status != INPUT_CANCEL;
7064 * Repository properties
7067 static struct ref **refs = NULL;
7068 static size_t refs_size = 0;
7069 static struct ref *refs_head = NULL;
7071 static struct ref_list **ref_lists = NULL;
7072 static size_t ref_lists_size = 0;
7074 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
7075 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
7076 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
7078 static int
7079 compare_refs(const void *ref1_, const void *ref2_)
7081 const struct ref *ref1 = *(const struct ref **)ref1_;
7082 const struct ref *ref2 = *(const struct ref **)ref2_;
7084 if (ref1->tag != ref2->tag)
7085 return ref2->tag - ref1->tag;
7086 if (ref1->ltag != ref2->ltag)
7087 return ref2->ltag - ref1->ltag;
7088 if (ref1->head != ref2->head)
7089 return ref2->head - ref1->head;
7090 if (ref1->tracked != ref2->tracked)
7091 return ref2->tracked - ref1->tracked;
7092 if (ref1->replace != ref2->replace)
7093 return ref2->replace - ref1->replace;
7094 /* Order remotes last. */
7095 if (ref1->remote != ref2->remote)
7096 return ref1->remote - ref2->remote;
7097 return strcmp(ref1->name, ref2->name);
7100 static void
7101 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
7103 size_t i;
7105 for (i = 0; i < refs_size; i++)
7106 if (!visitor(data, refs[i]))
7107 break;
7110 static struct ref *
7111 get_ref_head()
7113 return refs_head;
7116 static struct ref_list *
7117 get_ref_list(const char *id)
7119 struct ref_list *list;
7120 size_t i;
7122 for (i = 0; i < ref_lists_size; i++)
7123 if (!strcmp(id, ref_lists[i]->id))
7124 return ref_lists[i];
7126 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
7127 return NULL;
7128 list = calloc(1, sizeof(*list));
7129 if (!list)
7130 return NULL;
7132 for (i = 0; i < refs_size; i++) {
7133 if (!strcmp(id, refs[i]->id) &&
7134 realloc_refs_list(&list->refs, list->size, 1))
7135 list->refs[list->size++] = refs[i];
7138 if (!list->refs) {
7139 free(list);
7140 return NULL;
7143 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
7144 ref_lists[ref_lists_size++] = list;
7145 return list;
7148 static int
7149 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
7151 struct ref *ref = NULL;
7152 bool tag = FALSE;
7153 bool ltag = FALSE;
7154 bool remote = FALSE;
7155 bool replace = FALSE;
7156 bool tracked = FALSE;
7157 bool head = FALSE;
7158 int from = 0, to = refs_size - 1;
7160 if (!prefixcmp(name, "refs/tags/")) {
7161 if (!suffixcmp(name, namelen, "^{}")) {
7162 namelen -= 3;
7163 name[namelen] = 0;
7164 } else {
7165 ltag = TRUE;
7168 tag = TRUE;
7169 namelen -= STRING_SIZE("refs/tags/");
7170 name += STRING_SIZE("refs/tags/");
7172 } else if (!prefixcmp(name, "refs/remotes/")) {
7173 remote = TRUE;
7174 namelen -= STRING_SIZE("refs/remotes/");
7175 name += STRING_SIZE("refs/remotes/");
7176 tracked = !strcmp(opt_remote, name);
7178 } else if (!prefixcmp(name, "refs/replace/")) {
7179 replace = TRUE;
7180 id = name + strlen("refs/replace/");
7181 idlen = namelen - strlen("refs/replace/");
7182 name = "replaced";
7183 namelen = strlen(name);
7185 } else if (!prefixcmp(name, "refs/heads/")) {
7186 namelen -= STRING_SIZE("refs/heads/");
7187 name += STRING_SIZE("refs/heads/");
7188 if (strlen(opt_head) == namelen
7189 && !strncmp(opt_head, name, namelen))
7190 return OK;
7192 } else if (!strcmp(name, "HEAD")) {
7193 head = TRUE;
7194 if (*opt_head) {
7195 namelen = strlen(opt_head);
7196 name = opt_head;
7200 /* If we are reloading or it's an annotated tag, replace the
7201 * previous SHA1 with the resolved commit id; relies on the fact
7202 * git-ls-remote lists the commit id of an annotated tag right
7203 * before the commit id it points to. */
7204 while ((from <= to) && !replace) {
7205 size_t pos = (to + from) / 2;
7206 int cmp = strcmp(name, refs[pos]->name);
7208 if (!cmp) {
7209 ref = refs[pos];
7210 break;
7213 if (cmp < 0)
7214 to = pos - 1;
7215 else
7216 from = pos + 1;
7219 if (!ref) {
7220 if (!realloc_refs(&refs, refs_size, 1))
7221 return ERR;
7222 ref = calloc(1, sizeof(*ref) + namelen);
7223 if (!ref)
7224 return ERR;
7225 memmove(refs + from + 1, refs + from,
7226 (refs_size - from) * sizeof(*refs));
7227 refs[from] = ref;
7228 strncpy(ref->name, name, namelen);
7229 refs_size++;
7232 ref->head = head;
7233 ref->tag = tag;
7234 ref->ltag = ltag;
7235 ref->remote = remote;
7236 ref->replace = replace;
7237 ref->tracked = tracked;
7238 string_copy_rev(ref->id, id);
7240 if (head)
7241 refs_head = ref;
7242 return OK;
7245 static int
7246 load_refs(void)
7248 const char *head_argv[] = {
7249 "git", "symbolic-ref", "HEAD", NULL
7251 static const char *ls_remote_argv[SIZEOF_ARG] = {
7252 "git", "ls-remote", opt_git_dir, NULL
7254 static bool init = FALSE;
7255 size_t i;
7257 if (!init) {
7258 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
7259 die("TIG_LS_REMOTE contains too many arguments");
7260 init = TRUE;
7263 if (!*opt_git_dir)
7264 return OK;
7266 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
7267 !prefixcmp(opt_head, "refs/heads/")) {
7268 char *offset = opt_head + STRING_SIZE("refs/heads/");
7270 memmove(opt_head, offset, strlen(offset) + 1);
7273 refs_head = NULL;
7274 for (i = 0; i < refs_size; i++)
7275 refs[i]->id[0] = 0;
7277 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
7278 return ERR;
7280 /* Update the ref lists to reflect changes. */
7281 for (i = 0; i < ref_lists_size; i++) {
7282 struct ref_list *list = ref_lists[i];
7283 size_t old, new;
7285 for (old = new = 0; old < list->size; old++)
7286 if (!strcmp(list->id, list->refs[old]->id))
7287 list->refs[new++] = list->refs[old];
7288 list->size = new;
7291 qsort(refs, refs_size, sizeof(*refs), compare_refs);
7293 return OK;
7296 static void
7297 set_remote_branch(const char *name, const char *value, size_t valuelen)
7299 if (!strcmp(name, ".remote")) {
7300 string_ncopy(opt_remote, value, valuelen);
7302 } else if (*opt_remote && !strcmp(name, ".merge")) {
7303 size_t from = strlen(opt_remote);
7305 if (!prefixcmp(value, "refs/heads/"))
7306 value += STRING_SIZE("refs/heads/");
7308 if (!string_format_from(opt_remote, &from, "/%s", value))
7309 opt_remote[0] = 0;
7313 static void
7314 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7316 const char *argv[SIZEOF_ARG] = { name, "=" };
7317 int argc = 1 + (cmd == option_set_command);
7318 enum option_code error;
7320 if (!argv_from_string(argv, &argc, value))
7321 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7322 else
7323 error = cmd(argc, argv);
7325 if (error != OPT_OK)
7326 warn("Option 'tig.%s': %s", name, option_errors[error]);
7329 static bool
7330 set_environment_variable(const char *name, const char *value)
7332 size_t len = strlen(name) + 1 + strlen(value) + 1;
7333 char *env = malloc(len);
7335 if (env &&
7336 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7337 putenv(env) == 0)
7338 return TRUE;
7339 free(env);
7340 return FALSE;
7343 static void
7344 set_work_tree(const char *value)
7346 char cwd[SIZEOF_STR];
7348 if (!getcwd(cwd, sizeof(cwd)))
7349 die("Failed to get cwd path: %s", strerror(errno));
7350 if (chdir(opt_git_dir) < 0)
7351 die("Failed to chdir(%s): %s", strerror(errno));
7352 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7353 die("Failed to get git path: %s", strerror(errno));
7354 if (chdir(cwd) < 0)
7355 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7356 if (chdir(value) < 0)
7357 die("Failed to chdir(%s): %s", value, strerror(errno));
7358 if (!getcwd(cwd, sizeof(cwd)))
7359 die("Failed to get cwd path: %s", strerror(errno));
7360 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7361 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7362 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7363 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7364 opt_is_inside_work_tree = TRUE;
7367 static int
7368 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7370 if (!strcmp(name, "i18n.commitencoding"))
7371 string_ncopy(opt_encoding, value, valuelen);
7373 else if (!strcmp(name, "core.editor"))
7374 string_ncopy(opt_editor, value, valuelen);
7376 else if (!strcmp(name, "core.worktree"))
7377 set_work_tree(value);
7379 else if (!prefixcmp(name, "tig.color."))
7380 set_repo_config_option(name + 10, value, option_color_command);
7382 else if (!prefixcmp(name, "tig.bind."))
7383 set_repo_config_option(name + 9, value, option_bind_command);
7385 else if (!prefixcmp(name, "tig."))
7386 set_repo_config_option(name + 4, value, option_set_command);
7388 else if (*opt_head && !prefixcmp(name, "branch.") &&
7389 !strncmp(name + 7, opt_head, strlen(opt_head)))
7390 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7392 return OK;
7395 static int
7396 load_git_config(void)
7398 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7400 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7403 static int
7404 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7406 if (!opt_git_dir[0]) {
7407 string_ncopy(opt_git_dir, name, namelen);
7409 } else if (opt_is_inside_work_tree == -1) {
7410 /* This can be 3 different values depending on the
7411 * version of git being used. If git-rev-parse does not
7412 * understand --is-inside-work-tree it will simply echo
7413 * the option else either "true" or "false" is printed.
7414 * Default to true for the unknown case. */
7415 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7417 } else if (*name == '.') {
7418 string_ncopy(opt_cdup, name, namelen);
7420 } else {
7421 string_ncopy(opt_prefix, name, namelen);
7424 return OK;
7427 static int
7428 load_repo_info(void)
7430 const char *rev_parse_argv[] = {
7431 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7432 "--show-cdup", "--show-prefix", NULL
7435 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7440 * Main
7443 static const char usage[] =
7444 "tig " TIG_VERSION " (" __DATE__ ")\n"
7445 "\n"
7446 "Usage: tig [options] [revs] [--] [paths]\n"
7447 " or: tig show [options] [revs] [--] [paths]\n"
7448 " or: tig blame [options] [rev] [--] path\n"
7449 " or: tig status\n"
7450 " or: tig < [git command output]\n"
7451 "\n"
7452 "Options:\n"
7453 " +<number> Select line <number> in the first view\n"
7454 " -v, --version Show version and exit\n"
7455 " -h, --help Show help message and exit";
7457 static void __NORETURN
7458 quit(int sig)
7460 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7461 if (cursed)
7462 endwin();
7463 exit(0);
7466 static void __NORETURN
7467 die(const char *err, ...)
7469 va_list args;
7471 endwin();
7473 va_start(args, err);
7474 fputs("tig: ", stderr);
7475 vfprintf(stderr, err, args);
7476 fputs("\n", stderr);
7477 va_end(args);
7479 exit(1);
7482 static void
7483 warn(const char *msg, ...)
7485 va_list args;
7487 va_start(args, msg);
7488 fputs("tig warning: ", stderr);
7489 vfprintf(stderr, msg, args);
7490 fputs("\n", stderr);
7491 va_end(args);
7494 static int
7495 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7497 const char ***filter_args = data;
7499 return argv_append(filter_args, name) ? OK : ERR;
7502 static void
7503 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7505 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7506 const char **all_argv = NULL;
7508 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7509 !argv_append_array(&all_argv, argv) ||
7510 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7511 die("Failed to split arguments");
7512 argv_free(all_argv);
7513 free(all_argv);
7516 static void
7517 filter_options(const char *argv[], bool blame)
7519 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7521 if (blame)
7522 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7523 else
7524 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7526 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7529 static enum request
7530 parse_options(int argc, const char *argv[])
7532 enum request request = REQ_VIEW_MAIN;
7533 const char *subcommand;
7534 bool seen_dashdash = FALSE;
7535 const char **filter_argv = NULL;
7536 int i;
7538 if (!isatty(STDIN_FILENO))
7539 return REQ_VIEW_PAGER;
7541 if (argc <= 1)
7542 return REQ_VIEW_MAIN;
7544 subcommand = argv[1];
7545 if (!strcmp(subcommand, "status")) {
7546 if (argc > 2)
7547 warn("ignoring arguments after `%s'", subcommand);
7548 return REQ_VIEW_STATUS;
7550 } else if (!strcmp(subcommand, "blame")) {
7551 request = REQ_VIEW_BLAME;
7553 } else if (!strcmp(subcommand, "show")) {
7554 request = REQ_VIEW_DIFF;
7556 } else {
7557 subcommand = NULL;
7560 for (i = 1 + !!subcommand; i < argc; i++) {
7561 const char *opt = argv[i];
7563 // stop parsing our options after -- and let rev-parse handle the rest
7564 if (!seen_dashdash) {
7565 if (!strcmp(opt, "--")) {
7566 seen_dashdash = TRUE;
7567 continue;
7569 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7570 printf("tig version %s\n", TIG_VERSION);
7571 quit(0);
7573 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7574 printf("%s\n", usage);
7575 quit(0);
7577 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7578 opt_lineno = atoi(opt + 1);
7579 continue;
7584 if (!argv_append(&filter_argv, opt))
7585 die("command too long");
7588 if (filter_argv)
7589 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7591 /* Finish validating and setting up blame options */
7592 if (request == REQ_VIEW_BLAME) {
7593 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7594 die("invalid number of options to blame\n\n%s", usage);
7596 if (opt_rev_argv) {
7597 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7600 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7603 return request;
7607 main(int argc, const char *argv[])
7609 const char *codeset = ENCODING_UTF8;
7610 enum request request = parse_options(argc, argv);
7611 struct view *view;
7613 signal(SIGINT, quit);
7614 signal(SIGPIPE, SIG_IGN);
7616 if (setlocale(LC_ALL, "")) {
7617 codeset = nl_langinfo(CODESET);
7620 if (load_repo_info() == ERR)
7621 die("Failed to load repo info.");
7623 if (load_options() == ERR)
7624 die("Failed to load user config.");
7626 if (load_git_config() == ERR)
7627 die("Failed to load repo config.");
7629 /* Require a git repository unless when running in pager mode. */
7630 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7631 die("Not a git repository");
7633 if (*opt_encoding && strcmp(opt_encoding, ENCODING_UTF8)) {
7634 opt_iconv_in = iconv_open(ENCODING_UTF8, opt_encoding);
7635 if (opt_iconv_in == ICONV_NONE)
7636 die("Failed to initialize character set conversion");
7639 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
7640 char translit[SIZEOF_STR];
7642 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
7643 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
7644 else
7645 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
7646 if (opt_iconv_out == ICONV_NONE)
7647 die("Failed to initialize character set conversion");
7650 if (load_refs() == ERR)
7651 die("Failed to load refs.");
7653 init_display();
7655 while (view_driver(display[current_view], request)) {
7656 int key = get_input(0);
7658 view = display[current_view];
7659 request = get_keybinding(view->keymap, key);
7661 /* Some low-level request handling. This keeps access to
7662 * status_win restricted. */
7663 switch (request) {
7664 case REQ_NONE:
7665 report("Unknown key, press %s for help",
7666 get_view_key(view, REQ_VIEW_HELP));
7667 break;
7668 case REQ_PROMPT:
7670 char *cmd = read_prompt(":");
7672 if (cmd && string_isnumber(cmd)) {
7673 int lineno = view->lineno + 1;
7675 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
7676 select_view_line(view, lineno - 1);
7677 report("");
7678 } else {
7679 report("Unable to parse '%s' as a line number", cmd);
7681 } else if (cmd && iscommit(cmd)) {
7682 string_ncopy(opt_search, cmd, strlen(cmd));
7684 request = view_request(view, REQ_JUMP_COMMIT);
7685 if (request == REQ_JUMP_COMMIT) {
7686 report("Jumping to commits is not supported by the '%s' view", view->name);
7689 } else if (cmd) {
7690 struct view *next = VIEW(REQ_VIEW_PAGER);
7691 const char *argv[SIZEOF_ARG] = { "git" };
7692 int argc = 1;
7694 /* When running random commands, initially show the
7695 * command in the title. However, it maybe later be
7696 * overwritten if a commit line is selected. */
7697 string_ncopy(next->ref, cmd, strlen(cmd));
7699 if (!argv_from_string(argv, &argc, cmd)) {
7700 report("Too many arguments");
7701 } else if (!format_argv(&next->argv, argv, FALSE)) {
7702 report("Argument formatting failed");
7703 } else {
7704 next->dir = NULL;
7705 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7709 request = REQ_NONE;
7710 break;
7712 case REQ_SEARCH:
7713 case REQ_SEARCH_BACK:
7715 const char *prompt = request == REQ_SEARCH ? "/" : "?";
7716 char *search = read_prompt(prompt);
7718 if (search)
7719 string_ncopy(opt_search, search, strlen(search));
7720 else if (*opt_search)
7721 request = request == REQ_SEARCH ?
7722 REQ_FIND_NEXT :
7723 REQ_FIND_PREV;
7724 else
7725 request = REQ_NONE;
7726 break;
7728 default:
7729 break;
7733 quit(0);
7735 return 0;