Fix setup of the iconv input filter
[tig.git] / tig.c
blob1b5a0ac3a2024b8af9e58b229f1a43d3e9745f92
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);
232 * User requests
235 #define REQ_INFO \
236 /* XXX: Keep the view request first and in sync with views[]. */ \
237 REQ_GROUP("View switching") \
238 REQ_(VIEW_MAIN, "Show main view"), \
239 REQ_(VIEW_DIFF, "Show diff view"), \
240 REQ_(VIEW_LOG, "Show log view"), \
241 REQ_(VIEW_TREE, "Show tree view"), \
242 REQ_(VIEW_BLOB, "Show blob view"), \
243 REQ_(VIEW_BLAME, "Show blame view"), \
244 REQ_(VIEW_BRANCH, "Show branch view"), \
245 REQ_(VIEW_HELP, "Show help page"), \
246 REQ_(VIEW_PAGER, "Show pager view"), \
247 REQ_(VIEW_STATUS, "Show status view"), \
248 REQ_(VIEW_STAGE, "Show stage view"), \
250 REQ_GROUP("View manipulation") \
251 REQ_(ENTER, "Enter current line and scroll"), \
252 REQ_(NEXT, "Move to next"), \
253 REQ_(PREVIOUS, "Move to previous"), \
254 REQ_(PARENT, "Move to parent"), \
255 REQ_(VIEW_NEXT, "Move focus to next view"), \
256 REQ_(REFRESH, "Reload and refresh"), \
257 REQ_(MAXIMIZE, "Maximize the current view"), \
258 REQ_(VIEW_CLOSE, "Close the current view"), \
259 REQ_(QUIT, "Close all views and quit"), \
261 REQ_GROUP("View specific requests") \
262 REQ_(STATUS_UPDATE, "Update file status"), \
263 REQ_(STATUS_REVERT, "Revert file changes"), \
264 REQ_(STATUS_MERGE, "Merge file using external tool"), \
265 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
266 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
267 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
268 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
270 REQ_GROUP("Cursor navigation") \
271 REQ_(MOVE_UP, "Move cursor one line up"), \
272 REQ_(MOVE_DOWN, "Move cursor one line down"), \
273 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
274 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
275 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
276 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
278 REQ_GROUP("Scrolling") \
279 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
280 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
281 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
282 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
283 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
284 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
285 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
287 REQ_GROUP("Searching") \
288 REQ_(SEARCH, "Search the view"), \
289 REQ_(SEARCH_BACK, "Search backwards in the view"), \
290 REQ_(FIND_NEXT, "Find next search match"), \
291 REQ_(FIND_PREV, "Find previous search match"), \
293 REQ_GROUP("Option manipulation") \
294 REQ_(OPTIONS, "Open option menu"), \
295 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
296 REQ_(TOGGLE_DATE, "Toggle date display"), \
297 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
298 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
299 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
300 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
301 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
302 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
303 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
305 REQ_GROUP("Misc") \
306 REQ_(PROMPT, "Bring up the prompt"), \
307 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
308 REQ_(SHOW_VERSION, "Show version information"), \
309 REQ_(STOP_LOADING, "Stop all loading views"), \
310 REQ_(EDIT, "Open in editor"), \
311 REQ_(NONE, "Do nothing")
314 /* User action requests. */
315 enum request {
316 #define REQ_GROUP(help)
317 #define REQ_(req, help) REQ_##req
319 /* Offset all requests to avoid conflicts with ncurses getch values. */
320 REQ_UNKNOWN = KEY_MAX + 1,
321 REQ_OFFSET,
322 REQ_INFO,
324 /* Internal requests. */
325 REQ_JUMP_COMMIT,
327 #undef REQ_GROUP
328 #undef REQ_
331 struct request_info {
332 enum request request;
333 const char *name;
334 int namelen;
335 const char *help;
338 static const struct request_info req_info[] = {
339 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
340 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
341 REQ_INFO
342 #undef REQ_GROUP
343 #undef REQ_
346 static enum request
347 get_request(const char *name)
349 int namelen = strlen(name);
350 int i;
352 for (i = 0; i < ARRAY_SIZE(req_info); i++)
353 if (enum_equals(req_info[i], name, namelen))
354 return req_info[i].request;
356 return REQ_UNKNOWN;
361 * Options
364 /* Option and state variables. */
365 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
366 static enum date opt_date = DATE_DEFAULT;
367 static enum author opt_author = AUTHOR_FULL;
368 static enum filename opt_filename = FILENAME_AUTO;
369 static bool opt_rev_graph = TRUE;
370 static bool opt_line_number = FALSE;
371 static bool opt_show_refs = TRUE;
372 static bool opt_untracked_dirs_content = TRUE;
373 static int opt_diff_context = 3;
374 static char opt_diff_context_arg[9] = "";
375 static char opt_notes_arg[SIZEOF_STR] = "--no-notes";
376 static int opt_num_interval = 5;
377 static double opt_hscroll = 0.50;
378 static double opt_scale_split_view = 2.0 / 3.0;
379 static int opt_tab_size = 8;
380 static int opt_author_cols = AUTHOR_COLS;
381 static int opt_filename_cols = FILENAME_COLS;
382 static char opt_path[SIZEOF_STR] = "";
383 static char opt_file[SIZEOF_STR] = "";
384 static char opt_ref[SIZEOF_REF] = "";
385 static unsigned long opt_goto_line = 0;
386 static char opt_head[SIZEOF_REF] = "";
387 static char opt_remote[SIZEOF_REF] = "";
388 static char opt_encoding[20] = ENCODING_UTF8;
389 static iconv_t opt_iconv_in = ICONV_NONE;
390 static iconv_t opt_iconv_out = ICONV_NONE;
391 static char opt_search[SIZEOF_STR] = "";
392 static char opt_cdup[SIZEOF_STR] = "";
393 static char opt_prefix[SIZEOF_STR] = "";
394 static char opt_git_dir[SIZEOF_STR] = "";
395 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
396 static char opt_editor[SIZEOF_STR] = "";
397 static FILE *opt_tty = NULL;
398 static const char **opt_diff_argv = NULL;
399 static const char **opt_rev_argv = NULL;
400 static const char **opt_file_argv = NULL;
401 static const char **opt_blame_argv = NULL;
402 static int opt_lineno = 0;
404 #define is_initial_commit() (!get_ref_head())
405 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
407 static inline void
408 update_diff_context_arg(int diff_context)
410 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
411 string_ncopy(opt_diff_context_arg, "-U3", 3);
415 * Line-oriented content detection.
418 #define LINE_INFO \
419 LINE(DIFF_HEADER, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
420 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
421 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
422 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
423 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
424 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
425 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
426 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
427 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
428 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
429 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
430 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
431 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
432 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
433 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
434 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
435 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
436 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
437 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
438 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
439 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
440 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
441 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
442 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
443 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
444 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
445 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
446 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
447 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
448 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
449 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
450 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
451 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
452 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
453 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
454 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
455 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
456 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
457 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
458 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
459 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
460 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
461 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
462 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
463 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
464 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
465 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
466 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
467 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
468 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
469 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
470 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
471 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
472 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
473 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
474 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
475 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
476 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
477 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
478 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
479 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
480 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
481 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
482 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
483 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
484 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
485 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
486 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
487 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
488 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
489 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
490 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
492 enum line_type {
493 #define LINE(type, line, fg, bg, attr) \
494 LINE_##type
495 LINE_INFO,
496 LINE_NONE
497 #undef LINE
500 struct line_info {
501 const char *name; /* Option name. */
502 int namelen; /* Size of option name. */
503 const char *line; /* The start of line to match. */
504 int linelen; /* Size of string to match. */
505 int fg, bg, attr; /* Color and text attributes for the lines. */
508 static struct line_info line_info[] = {
509 #define LINE(type, line, fg, bg, attr) \
510 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
511 LINE_INFO
512 #undef LINE
515 static struct line_info *custom_color;
516 static size_t custom_colors;
518 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
520 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
521 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
523 /* Color IDs must be 1 or higher. [GH #15] */
524 #define COLOR_ID(line_type) ((line_type) + 1)
526 static enum line_type
527 get_line_type(const char *line)
529 int linelen = strlen(line);
530 enum line_type type;
532 for (type = 0; type < custom_colors; type++)
533 /* Case insensitive search matches Signed-off-by lines better. */
534 if (linelen >= custom_color[type].linelen &&
535 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
536 return TO_CUSTOM_COLOR_TYPE(type);
538 for (type = 0; type < ARRAY_SIZE(line_info); type++)
539 /* Case insensitive search matches Signed-off-by lines better. */
540 if (linelen >= line_info[type].linelen &&
541 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
542 return type;
544 return LINE_DEFAULT;
547 static enum line_type
548 get_line_type_from_ref(const struct ref *ref)
550 if (ref->head)
551 return LINE_MAIN_HEAD;
552 else if (ref->ltag)
553 return LINE_MAIN_LOCAL_TAG;
554 else if (ref->tag)
555 return LINE_MAIN_TAG;
556 else if (ref->tracked)
557 return LINE_MAIN_TRACKED;
558 else if (ref->remote)
559 return LINE_MAIN_REMOTE;
560 else if (ref->replace)
561 return LINE_MAIN_REPLACE;
563 return LINE_MAIN_REF;
566 static inline int
567 get_line_attr(enum line_type type)
569 if (type > LINE_NONE) {
570 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
571 return COLOR_PAIR(COLOR_ID(type)) | custom_color[TO_CUSTOM_COLOR_OFFSET(type)].attr;
573 assert(type < ARRAY_SIZE(line_info));
574 return COLOR_PAIR(COLOR_ID(type)) | line_info[type].attr;
577 static struct line_info *
578 get_line_info(const char *name)
580 size_t namelen = strlen(name);
581 enum line_type type;
583 for (type = 0; type < ARRAY_SIZE(line_info); type++)
584 if (enum_equals(line_info[type], name, namelen))
585 return &line_info[type];
587 return NULL;
590 static struct line_info *
591 add_custom_color(const char *quoted_line)
593 struct line_info *info;
594 char *line;
595 size_t linelen;
597 if (!realloc_custom_color(&custom_color, custom_colors, 1))
598 die("Failed to alloc custom line info");
600 linelen = strlen(quoted_line) - 1;
601 line = malloc(linelen);
602 if (!line)
603 return NULL;
605 strncpy(line, quoted_line + 1, linelen);
606 line[linelen - 1] = 0;
608 info = &custom_color[custom_colors++];
609 info->name = info->line = line;
610 info->namelen = info->linelen = strlen(line);
612 return info;
615 static void
616 init_line_info_color_pair(struct line_info *info, enum line_type type,
617 int default_bg, int default_fg)
619 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
620 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
622 init_pair(COLOR_ID(type), fg, bg);
625 static void
626 init_colors(void)
628 int default_bg = line_info[LINE_DEFAULT].bg;
629 int default_fg = line_info[LINE_DEFAULT].fg;
630 enum line_type type;
632 start_color();
634 if (assume_default_colors(default_fg, default_bg) == ERR) {
635 default_bg = COLOR_BLACK;
636 default_fg = COLOR_WHITE;
639 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
640 struct line_info *info = &line_info[type];
642 init_line_info_color_pair(info, type, default_bg, default_fg);
645 for (type = 0; type < custom_colors; type++) {
646 struct line_info *info = &custom_color[type];
648 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
649 default_bg, default_fg);
653 struct line {
654 enum line_type type;
656 /* State flags */
657 unsigned int selected:1;
658 unsigned int dirty:1;
659 unsigned int cleareol:1;
660 unsigned int other:16;
662 void *data; /* User data */
667 * Keys
670 struct keybinding {
671 int alias;
672 enum request request;
675 static struct keybinding default_keybindings[] = {
676 /* View switching */
677 { 'm', REQ_VIEW_MAIN },
678 { 'd', REQ_VIEW_DIFF },
679 { 'l', REQ_VIEW_LOG },
680 { 't', REQ_VIEW_TREE },
681 { 'f', REQ_VIEW_BLOB },
682 { 'B', REQ_VIEW_BLAME },
683 { 'H', REQ_VIEW_BRANCH },
684 { 'p', REQ_VIEW_PAGER },
685 { 'h', REQ_VIEW_HELP },
686 { 'S', REQ_VIEW_STATUS },
687 { 'c', REQ_VIEW_STAGE },
689 /* View manipulation */
690 { 'q', REQ_VIEW_CLOSE },
691 { KEY_TAB, REQ_VIEW_NEXT },
692 { KEY_RETURN, REQ_ENTER },
693 { KEY_UP, REQ_PREVIOUS },
694 { KEY_CTL('P'), REQ_PREVIOUS },
695 { KEY_DOWN, REQ_NEXT },
696 { KEY_CTL('N'), REQ_NEXT },
697 { 'R', REQ_REFRESH },
698 { KEY_F(5), REQ_REFRESH },
699 { 'O', REQ_MAXIMIZE },
700 { ',', REQ_PARENT },
702 /* View specific */
703 { 'u', REQ_STATUS_UPDATE },
704 { '!', REQ_STATUS_REVERT },
705 { 'M', REQ_STATUS_MERGE },
706 { KEY_CTL('u'), REQ_STAGE_UPDATE_LINE },
707 { '@', REQ_STAGE_NEXT },
708 { '[', REQ_DIFF_CONTEXT_DOWN },
709 { ']', REQ_DIFF_CONTEXT_UP },
711 /* Cursor navigation */
712 { 'k', REQ_MOVE_UP },
713 { 'j', REQ_MOVE_DOWN },
714 { KEY_HOME, REQ_MOVE_FIRST_LINE },
715 { KEY_END, REQ_MOVE_LAST_LINE },
716 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
717 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
718 { ' ', REQ_MOVE_PAGE_DOWN },
719 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
720 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
721 { 'b', REQ_MOVE_PAGE_UP },
722 { '-', REQ_MOVE_PAGE_UP },
724 /* Scrolling */
725 { '|', REQ_SCROLL_FIRST_COL },
726 { KEY_LEFT, REQ_SCROLL_LEFT },
727 { KEY_RIGHT, REQ_SCROLL_RIGHT },
728 { KEY_IC, REQ_SCROLL_LINE_UP },
729 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
730 { KEY_DC, REQ_SCROLL_LINE_DOWN },
731 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
732 { 'w', REQ_SCROLL_PAGE_UP },
733 { 's', REQ_SCROLL_PAGE_DOWN },
735 /* Searching */
736 { '/', REQ_SEARCH },
737 { '?', REQ_SEARCH_BACK },
738 { 'n', REQ_FIND_NEXT },
739 { 'N', REQ_FIND_PREV },
741 /* Misc */
742 { 'Q', REQ_QUIT },
743 { 'z', REQ_STOP_LOADING },
744 { 'v', REQ_SHOW_VERSION },
745 { 'r', REQ_SCREEN_REDRAW },
746 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
747 { 'o', REQ_OPTIONS },
748 { '.', REQ_TOGGLE_LINENO },
749 { 'D', REQ_TOGGLE_DATE },
750 { 'A', REQ_TOGGLE_AUTHOR },
751 { 'g', REQ_TOGGLE_REV_GRAPH },
752 { '~', REQ_TOGGLE_GRAPHIC },
753 { '#', REQ_TOGGLE_FILENAME },
754 { 'F', REQ_TOGGLE_REFS },
755 { 'I', REQ_TOGGLE_SORT_ORDER },
756 { 'i', REQ_TOGGLE_SORT_FIELD },
757 { ':', REQ_PROMPT },
758 { 'e', REQ_EDIT },
761 #define KEYMAP_ENUM(_) \
762 _(KEYMAP, GENERIC), \
763 _(KEYMAP, MAIN), \
764 _(KEYMAP, DIFF), \
765 _(KEYMAP, LOG), \
766 _(KEYMAP, TREE), \
767 _(KEYMAP, BLOB), \
768 _(KEYMAP, BLAME), \
769 _(KEYMAP, BRANCH), \
770 _(KEYMAP, PAGER), \
771 _(KEYMAP, HELP), \
772 _(KEYMAP, STATUS), \
773 _(KEYMAP, STAGE)
775 DEFINE_ENUM(keymap, KEYMAP_ENUM);
777 #define set_keymap(map, name) map_enum(map, keymap_map, name)
779 struct keybinding_table {
780 struct keybinding *data;
781 size_t size;
784 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_map)];
786 static void
787 add_keybinding(enum keymap keymap, enum request request, int key)
789 struct keybinding_table *table = &keybindings[keymap];
790 size_t i;
792 for (i = 0; i < keybindings[keymap].size; i++) {
793 if (keybindings[keymap].data[i].alias == key) {
794 keybindings[keymap].data[i].request = request;
795 return;
799 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
800 if (!table->data)
801 die("Failed to allocate keybinding");
802 table->data[table->size].alias = key;
803 table->data[table->size++].request = request;
805 if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
806 int i;
808 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
809 if (default_keybindings[i].alias == key)
810 default_keybindings[i].request = REQ_NONE;
814 /* Looks for a key binding first in the given map, then in the generic map, and
815 * lastly in the default keybindings. */
816 static enum request
817 get_keybinding(enum keymap keymap, int key)
819 size_t i;
821 for (i = 0; i < keybindings[keymap].size; i++)
822 if (keybindings[keymap].data[i].alias == key)
823 return keybindings[keymap].data[i].request;
825 for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
826 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
827 return keybindings[KEYMAP_GENERIC].data[i].request;
829 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
830 if (default_keybindings[i].alias == key)
831 return default_keybindings[i].request;
833 return (enum request) key;
837 struct key {
838 const char *name;
839 int value;
842 static const struct key key_table[] = {
843 { "Enter", KEY_RETURN },
844 { "Space", ' ' },
845 { "Backspace", KEY_BACKSPACE },
846 { "Tab", KEY_TAB },
847 { "Escape", KEY_ESC },
848 { "Left", KEY_LEFT },
849 { "Right", KEY_RIGHT },
850 { "Up", KEY_UP },
851 { "Down", KEY_DOWN },
852 { "Insert", KEY_IC },
853 { "Delete", KEY_DC },
854 { "Hash", '#' },
855 { "Home", KEY_HOME },
856 { "End", KEY_END },
857 { "PageUp", KEY_PPAGE },
858 { "PageDown", KEY_NPAGE },
859 { "F1", KEY_F(1) },
860 { "F2", KEY_F(2) },
861 { "F3", KEY_F(3) },
862 { "F4", KEY_F(4) },
863 { "F5", KEY_F(5) },
864 { "F6", KEY_F(6) },
865 { "F7", KEY_F(7) },
866 { "F8", KEY_F(8) },
867 { "F9", KEY_F(9) },
868 { "F10", KEY_F(10) },
869 { "F11", KEY_F(11) },
870 { "F12", KEY_F(12) },
873 static int
874 get_key_value(const char *name)
876 int i;
878 for (i = 0; i < ARRAY_SIZE(key_table); i++)
879 if (!strcasecmp(key_table[i].name, name))
880 return key_table[i].value;
882 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
883 return (int)name[1] & 0x1f;
884 if (strlen(name) == 1 && isprint(*name))
885 return (int) *name;
886 return ERR;
889 static const char *
890 get_key_name(int key_value)
892 static char key_char[] = "'X'\0";
893 const char *seq = NULL;
894 int key;
896 for (key = 0; key < ARRAY_SIZE(key_table); key++)
897 if (key_table[key].value == key_value)
898 seq = key_table[key].name;
900 if (seq == NULL && key_value < 0x7f) {
901 char *s = key_char + 1;
903 if (key_value >= 0x20) {
904 *s++ = key_value;
905 } else {
906 *s++ = '^';
907 *s++ = 0x40 | (key_value & 0x1f);
909 *s++ = '\'';
910 *s++ = '\0';
911 seq = key_char;
914 return seq ? seq : "(no key)";
917 static bool
918 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
920 const char *sep = *pos > 0 ? ", " : "";
921 const char *keyname = get_key_name(keybinding->alias);
923 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
926 static bool
927 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
928 enum keymap keymap, bool all)
930 int i;
932 for (i = 0; i < keybindings[keymap].size; i++) {
933 if (keybindings[keymap].data[i].request == request) {
934 if (!append_key(buf, pos, &keybindings[keymap].data[i]))
935 return FALSE;
936 if (!all)
937 break;
941 return TRUE;
944 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
946 static const char *
947 get_keys(enum keymap keymap, enum request request, bool all)
949 static char buf[BUFSIZ];
950 size_t pos = 0;
951 int i;
953 buf[pos] = 0;
955 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
956 return "Too many keybindings!";
957 if (pos > 0 && !all)
958 return buf;
960 if (keymap != KEYMAP_GENERIC) {
961 /* Only the generic keymap includes the default keybindings when
962 * listing all keys. */
963 if (all)
964 return buf;
966 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
967 return "Too many keybindings!";
968 if (pos)
969 return buf;
972 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
973 if (default_keybindings[i].request == request) {
974 if (!append_key(buf, &pos, &default_keybindings[i]))
975 return "Too many keybindings!";
976 if (!all)
977 return buf;
981 return buf;
984 struct run_request {
985 enum keymap keymap;
986 int key;
987 const char **argv;
990 static struct run_request *run_request;
991 static size_t run_requests;
993 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
995 static enum request
996 add_run_request(enum keymap keymap, int key, const char **argv)
998 struct run_request *req;
1000 if (!realloc_run_requests(&run_request, run_requests, 1))
1001 return REQ_NONE;
1003 req = &run_request[run_requests];
1004 req->keymap = keymap;
1005 req->key = key;
1006 req->argv = NULL;
1008 if (!argv_copy(&req->argv, argv))
1009 return REQ_NONE;
1011 return REQ_NONE + ++run_requests;
1014 static struct run_request *
1015 get_run_request(enum request request)
1017 if (request <= REQ_NONE)
1018 return NULL;
1019 return &run_request[request - REQ_NONE - 1];
1022 static void
1023 add_builtin_run_requests(void)
1025 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1026 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1027 const char *commit[] = { "git", "commit", NULL };
1028 const char *gc[] = { "git", "gc", NULL };
1029 struct run_request reqs[] = {
1030 { KEYMAP_MAIN, 'C', cherry_pick },
1031 { KEYMAP_STATUS, 'C', commit },
1032 { KEYMAP_BRANCH, 'C', checkout },
1033 { KEYMAP_GENERIC, 'G', gc },
1035 int i;
1037 for (i = 0; i < ARRAY_SIZE(reqs); i++) {
1038 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
1040 if (req != reqs[i].key)
1041 continue;
1042 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
1043 if (req != REQ_NONE)
1044 add_keybinding(reqs[i].keymap, req, reqs[i].key);
1049 * User config file handling.
1052 #define OPT_ERR_INFO \
1053 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1054 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1055 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1056 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1057 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1058 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1059 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1060 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1061 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1062 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1063 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1064 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1065 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1066 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1067 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1068 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1069 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1071 enum option_code {
1072 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1073 OPT_ERR_INFO
1074 #undef OPT_ERR_
1075 OPT_OK
1078 static const char *option_errors[] = {
1079 #define OPT_ERR_(name, msg) msg
1080 OPT_ERR_INFO
1081 #undef OPT_ERR_
1084 static const struct enum_map color_map[] = {
1085 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1086 COLOR_MAP(DEFAULT),
1087 COLOR_MAP(BLACK),
1088 COLOR_MAP(BLUE),
1089 COLOR_MAP(CYAN),
1090 COLOR_MAP(GREEN),
1091 COLOR_MAP(MAGENTA),
1092 COLOR_MAP(RED),
1093 COLOR_MAP(WHITE),
1094 COLOR_MAP(YELLOW),
1097 static const struct enum_map attr_map[] = {
1098 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1099 ATTR_MAP(NORMAL),
1100 ATTR_MAP(BLINK),
1101 ATTR_MAP(BOLD),
1102 ATTR_MAP(DIM),
1103 ATTR_MAP(REVERSE),
1104 ATTR_MAP(STANDOUT),
1105 ATTR_MAP(UNDERLINE),
1108 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1110 static enum option_code
1111 parse_step(double *opt, const char *arg)
1113 *opt = atoi(arg);
1114 if (!strchr(arg, '%'))
1115 return OPT_OK;
1117 /* "Shift down" so 100% and 1 does not conflict. */
1118 *opt = (*opt - 1) / 100;
1119 if (*opt >= 1.0) {
1120 *opt = 0.99;
1121 return OPT_ERR_INVALID_STEP_VALUE;
1123 if (*opt < 0.0) {
1124 *opt = 1;
1125 return OPT_ERR_INVALID_STEP_VALUE;
1127 return OPT_OK;
1130 static enum option_code
1131 parse_int(int *opt, const char *arg, int min, int max)
1133 int value = atoi(arg);
1135 if (min <= value && value <= max) {
1136 *opt = value;
1137 return OPT_OK;
1140 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1143 static bool
1144 set_color(int *color, const char *name)
1146 if (map_enum(color, color_map, name))
1147 return TRUE;
1148 if (!prefixcmp(name, "color"))
1149 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1150 return FALSE;
1153 /* Wants: object fgcolor bgcolor [attribute] */
1154 static enum option_code
1155 option_color_command(int argc, const char *argv[])
1157 struct line_info *info;
1159 if (argc < 3)
1160 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1162 if (*argv[0] == '"' || *argv[0] == '\'') {
1163 info = add_custom_color(argv[0]);
1164 } else {
1165 info = get_line_info(argv[0]);
1167 if (!info) {
1168 static const struct enum_map obsolete[] = {
1169 ENUM_MAP("main-delim", LINE_DELIMITER),
1170 ENUM_MAP("main-date", LINE_DATE),
1171 ENUM_MAP("main-author", LINE_AUTHOR),
1173 int index;
1175 if (!map_enum(&index, obsolete, argv[0]))
1176 return OPT_ERR_UNKNOWN_COLOR_NAME;
1177 info = &line_info[index];
1180 if (!set_color(&info->fg, argv[1]) ||
1181 !set_color(&info->bg, argv[2]))
1182 return OPT_ERR_UNKNOWN_COLOR;
1184 info->attr = 0;
1185 while (argc-- > 3) {
1186 int attr;
1188 if (!set_attribute(&attr, argv[argc]))
1189 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1190 info->attr |= attr;
1193 return OPT_OK;
1196 static enum option_code
1197 parse_bool(bool *opt, const char *arg)
1199 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1200 ? TRUE : FALSE;
1201 return OPT_OK;
1204 static enum option_code
1205 parse_enum_do(unsigned int *opt, const char *arg,
1206 const struct enum_map *map, size_t map_size)
1208 bool is_true;
1210 assert(map_size > 1);
1212 if (map_enum_do(map, map_size, (int *) opt, arg))
1213 return OPT_OK;
1215 parse_bool(&is_true, arg);
1216 *opt = is_true ? map[1].value : map[0].value;
1217 return OPT_OK;
1220 #define parse_enum(opt, arg, map) \
1221 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1223 static enum option_code
1224 parse_string(char *opt, const char *arg, size_t optsize)
1226 int arglen = strlen(arg);
1228 switch (arg[0]) {
1229 case '\"':
1230 case '\'':
1231 if (arglen == 1 || arg[arglen - 1] != arg[0])
1232 return OPT_ERR_UNMATCHED_QUOTATION;
1233 arg += 1; arglen -= 2;
1234 default:
1235 string_ncopy_do(opt, optsize, arg, arglen);
1236 return OPT_OK;
1240 static enum option_code
1241 parse_args(const char ***args, const char *argv[])
1243 if (*args == NULL && !argv_copy(args, argv))
1244 return OPT_ERR_OUT_OF_MEMORY;
1245 return OPT_OK;
1248 /* Wants: name = value */
1249 static enum option_code
1250 option_set_command(int argc, const char *argv[])
1252 if (argc < 3)
1253 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1255 if (strcmp(argv[1], "="))
1256 return OPT_ERR_NO_VALUE_ASSIGNED;
1258 if (!strcmp(argv[0], "blame-options"))
1259 return parse_args(&opt_blame_argv, argv + 2);
1261 if (argc != 3)
1262 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1264 if (!strcmp(argv[0], "show-author"))
1265 return parse_enum(&opt_author, argv[2], author_map);
1267 if (!strcmp(argv[0], "show-date"))
1268 return parse_enum(&opt_date, argv[2], date_map);
1270 if (!strcmp(argv[0], "show-rev-graph"))
1271 return parse_bool(&opt_rev_graph, argv[2]);
1273 if (!strcmp(argv[0], "show-refs"))
1274 return parse_bool(&opt_show_refs, argv[2]);
1276 if (!strcmp(argv[0], "show-notes")) {
1277 int res;
1279 strcpy(opt_notes_arg, "--notes=");
1280 res = parse_string(opt_notes_arg + 8, argv[2],
1281 sizeof(opt_notes_arg) - 8);
1282 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1283 opt_notes_arg[7] = '\0';
1284 return res;
1287 if (!strcmp(argv[0], "show-line-numbers"))
1288 return parse_bool(&opt_line_number, argv[2]);
1290 if (!strcmp(argv[0], "line-graphics"))
1291 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1293 if (!strcmp(argv[0], "line-number-interval"))
1294 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1296 if (!strcmp(argv[0], "author-width"))
1297 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1299 if (!strcmp(argv[0], "filename-width"))
1300 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1302 if (!strcmp(argv[0], "show-filename"))
1303 return parse_enum(&opt_filename, argv[2], filename_map);
1305 if (!strcmp(argv[0], "horizontal-scroll"))
1306 return parse_step(&opt_hscroll, argv[2]);
1308 if (!strcmp(argv[0], "split-view-height"))
1309 return parse_step(&opt_scale_split_view, argv[2]);
1311 if (!strcmp(argv[0], "tab-size"))
1312 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1314 if (!strcmp(argv[0], "diff-context")) {
1315 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1317 if (code == OPT_OK)
1318 update_diff_context_arg(opt_diff_context);
1319 return code;
1322 if (!strcmp(argv[0], "commit-encoding"))
1323 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1325 if (!strcmp(argv[0], "status-untracked-dirs"))
1326 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1328 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1331 /* Wants: mode request key */
1332 static enum option_code
1333 option_bind_command(int argc, const char *argv[])
1335 enum request request;
1336 int keymap = -1;
1337 int key;
1339 if (argc < 3)
1340 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1342 if (!set_keymap(&keymap, argv[0]))
1343 return OPT_ERR_UNKNOWN_KEY_MAP;
1345 key = get_key_value(argv[1]);
1346 if (key == ERR)
1347 return OPT_ERR_UNKNOWN_KEY;
1349 request = get_request(argv[2]);
1350 if (request == REQ_UNKNOWN) {
1351 static const struct enum_map obsolete[] = {
1352 ENUM_MAP("cherry-pick", REQ_NONE),
1353 ENUM_MAP("screen-resize", REQ_NONE),
1354 ENUM_MAP("tree-parent", REQ_PARENT),
1356 int alias;
1358 if (map_enum(&alias, obsolete, argv[2])) {
1359 if (alias != REQ_NONE)
1360 add_keybinding(keymap, alias, key);
1361 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1364 if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1365 request = add_run_request(keymap, key, argv + 2);
1366 if (request == REQ_UNKNOWN)
1367 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1369 add_keybinding(keymap, request, key);
1371 return OPT_OK;
1374 static enum option_code
1375 set_option(const char *opt, char *value)
1377 const char *argv[SIZEOF_ARG];
1378 int argc = 0;
1380 if (!argv_from_string(argv, &argc, value))
1381 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1383 if (!strcmp(opt, "color"))
1384 return option_color_command(argc, argv);
1386 if (!strcmp(opt, "set"))
1387 return option_set_command(argc, argv);
1389 if (!strcmp(opt, "bind"))
1390 return option_bind_command(argc, argv);
1392 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1395 struct config_state {
1396 int lineno;
1397 bool errors;
1400 static int
1401 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1403 struct config_state *config = data;
1404 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1406 config->lineno++;
1408 /* Check for comment markers, since read_properties() will
1409 * only ensure opt and value are split at first " \t". */
1410 optlen = strcspn(opt, "#");
1411 if (optlen == 0)
1412 return OK;
1414 if (opt[optlen] == 0) {
1415 /* Look for comment endings in the value. */
1416 size_t len = strcspn(value, "#");
1418 if (len < valuelen) {
1419 valuelen = len;
1420 value[valuelen] = 0;
1423 status = set_option(opt, value);
1426 if (status != OPT_OK) {
1427 warn("Error on line %d, near '%.*s': %s",
1428 config->lineno, (int) optlen, opt, option_errors[status]);
1429 config->errors = TRUE;
1432 /* Always keep going if errors are encountered. */
1433 return OK;
1436 static void
1437 load_option_file(const char *path)
1439 struct config_state config = { 0, FALSE };
1440 struct io io;
1442 /* Do not read configuration from stdin if set to "" */
1443 if (!path || !strlen(path))
1444 return;
1446 /* It's OK that the file doesn't exist. */
1447 if (!io_open(&io, "%s", path))
1448 return;
1450 if (io_load(&io, " \t", read_option, &config) == ERR ||
1451 config.errors == TRUE)
1452 warn("Errors while loading %s.", path);
1455 static int
1456 load_options(void)
1458 const char *home = getenv("HOME");
1459 const char *tigrc_user = getenv("TIGRC_USER");
1460 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1461 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1462 char buf[SIZEOF_STR];
1464 if (!tigrc_system)
1465 tigrc_system = SYSCONFDIR "/tigrc";
1466 load_option_file(tigrc_system);
1468 if (!tigrc_user) {
1469 if (!home || !string_format(buf, "%s/.tigrc", home))
1470 return ERR;
1471 tigrc_user = buf;
1473 load_option_file(tigrc_user);
1475 /* Add _after_ loading config files to avoid adding run requests
1476 * that conflict with keybindings. */
1477 add_builtin_run_requests();
1479 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1480 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1481 int argc = 0;
1483 if (!string_format(buf, "%s", tig_diff_opts) ||
1484 !argv_from_string(diff_opts, &argc, buf))
1485 die("TIG_DIFF_OPTS contains too many arguments");
1486 else if (!argv_copy(&opt_diff_argv, diff_opts))
1487 die("Failed to format TIG_DIFF_OPTS arguments");
1490 return OK;
1495 * The viewer
1498 struct view;
1499 struct view_ops;
1501 /* The display array of active views and the index of the current view. */
1502 static struct view *display[2];
1503 static WINDOW *display_win[2];
1504 static WINDOW *display_title[2];
1505 static unsigned int current_view;
1507 #define foreach_displayed_view(view, i) \
1508 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1510 #define displayed_views() (display[1] != NULL ? 2 : 1)
1512 /* Current head and commit ID */
1513 static char ref_blob[SIZEOF_REF] = "";
1514 static char ref_commit[SIZEOF_REF] = "HEAD";
1515 static char ref_head[SIZEOF_REF] = "HEAD";
1516 static char ref_branch[SIZEOF_REF] = "";
1518 enum view_type {
1519 VIEW_MAIN,
1520 VIEW_DIFF,
1521 VIEW_LOG,
1522 VIEW_TREE,
1523 VIEW_BLOB,
1524 VIEW_BLAME,
1525 VIEW_BRANCH,
1526 VIEW_HELP,
1527 VIEW_PAGER,
1528 VIEW_STATUS,
1529 VIEW_STAGE,
1532 struct view {
1533 enum view_type type; /* View type */
1534 const char *name; /* View name */
1535 const char *id; /* Points to either of ref_{head,commit,blob} */
1537 struct view_ops *ops; /* View operations */
1539 enum keymap keymap; /* What keymap does this view have */
1540 bool git_dir; /* Whether the view requires a git directory. */
1542 char ref[SIZEOF_REF]; /* Hovered commit reference */
1543 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1545 int height, width; /* The width and height of the main window */
1546 WINDOW *win; /* The main window */
1548 /* Navigation */
1549 unsigned long offset; /* Offset of the window top */
1550 unsigned long yoffset; /* Offset from the window side. */
1551 unsigned long lineno; /* Current line number */
1552 unsigned long p_offset; /* Previous offset of the window top */
1553 unsigned long p_yoffset;/* Previous offset from the window side */
1554 unsigned long p_lineno; /* Previous current line number */
1555 bool p_restore; /* Should the previous position be restored. */
1557 /* Searching */
1558 char grep[SIZEOF_STR]; /* Search string */
1559 regex_t *regex; /* Pre-compiled regexp */
1561 /* If non-NULL, points to the view that opened this view. If this view
1562 * is closed tig will switch back to the parent view. */
1563 struct view *parent;
1564 struct view *prev;
1566 /* Buffering */
1567 size_t lines; /* Total number of lines */
1568 struct line *line; /* Line index */
1569 unsigned int digits; /* Number of digits in the lines member. */
1571 /* Drawing */
1572 struct line *curline; /* Line currently being drawn. */
1573 enum line_type curtype; /* Attribute currently used for drawing. */
1574 unsigned long col; /* Column when drawing. */
1575 bool has_scrolled; /* View was scrolled. */
1577 /* Loading */
1578 const char **argv; /* Shell command arguments. */
1579 const char *dir; /* Directory from which to execute. */
1580 struct io io;
1581 struct io *pipe;
1582 time_t start_time;
1583 time_t update_secs;
1585 /* Private data */
1586 void *private;
1589 enum open_flags {
1590 OPEN_DEFAULT = 0, /* Use default view switching. */
1591 OPEN_SPLIT = 1, /* Split current view. */
1592 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1593 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1594 OPEN_PREPARED = 32, /* Open already prepared command. */
1595 OPEN_EXTRA = 64, /* Open extra data from command. */
1598 struct view_ops {
1599 /* What type of content being displayed. Used in the title bar. */
1600 const char *type;
1601 /* Size of private data. */
1602 size_t private_size;
1603 /* Open and reads in all view content. */
1604 bool (*open)(struct view *view, enum open_flags flags);
1605 /* Read one line; updates view->line. */
1606 bool (*read)(struct view *view, char *data);
1607 /* Draw one line; @lineno must be < view->height. */
1608 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1609 /* Depending on view handle a special requests. */
1610 enum request (*request)(struct view *view, enum request request, struct line *line);
1611 /* Search for regexp in a line. */
1612 bool (*grep)(struct view *view, struct line *line);
1613 /* Select line */
1614 void (*select)(struct view *view, struct line *line);
1617 static struct view_ops blame_ops;
1618 static struct view_ops blob_ops;
1619 static struct view_ops diff_ops;
1620 static struct view_ops help_ops;
1621 static struct view_ops log_ops;
1622 static struct view_ops main_ops;
1623 static struct view_ops pager_ops;
1624 static struct view_ops stage_ops;
1625 static struct view_ops status_ops;
1626 static struct view_ops tree_ops;
1627 static struct view_ops branch_ops;
1629 #define VIEW_STR(type, name, ref, ops, map, git) \
1630 { type, name, ref, ops, map, git }
1632 #define VIEW_(id, name, ops, git, ref) \
1633 VIEW_STR(VIEW_##id, name, ref, ops, KEYMAP_##id, git)
1635 static struct view views[] = {
1636 VIEW_(MAIN, "main", &main_ops, TRUE, ref_head),
1637 VIEW_(DIFF, "diff", &diff_ops, TRUE, ref_commit),
1638 VIEW_(LOG, "log", &log_ops, TRUE, ref_head),
1639 VIEW_(TREE, "tree", &tree_ops, TRUE, ref_commit),
1640 VIEW_(BLOB, "blob", &blob_ops, TRUE, ref_blob),
1641 VIEW_(BLAME, "blame", &blame_ops, TRUE, ref_commit),
1642 VIEW_(BRANCH, "branch", &branch_ops, TRUE, ref_head),
1643 VIEW_(HELP, "help", &help_ops, FALSE, ""),
1644 VIEW_(PAGER, "pager", &pager_ops, FALSE, ""),
1645 VIEW_(STATUS, "status", &status_ops, TRUE, "status"),
1646 VIEW_(STAGE, "stage", &stage_ops, TRUE, "stage"),
1649 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1651 #define foreach_view(view, i) \
1652 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1654 #define view_is_displayed(view) \
1655 (view == display[0] || view == display[1])
1657 static enum request
1658 view_request(struct view *view, enum request request)
1660 if (!view || !view->lines)
1661 return request;
1662 return view->ops->request(view, request, &view->line[view->lineno]);
1667 * View drawing.
1670 static inline void
1671 set_view_attr(struct view *view, enum line_type type)
1673 if (!view->curline->selected && view->curtype != type) {
1674 (void) wattrset(view->win, get_line_attr(type));
1675 wchgat(view->win, -1, 0, COLOR_ID(type), NULL);
1676 view->curtype = type;
1680 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1682 static bool
1683 draw_chars(struct view *view, enum line_type type, const char *string,
1684 int max_len, bool use_tilde)
1686 static char out_buffer[BUFSIZ * 2];
1687 int len = 0;
1688 int col = 0;
1689 int trimmed = FALSE;
1690 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1692 if (max_len <= 0)
1693 return VIEW_MAX_LEN(view) <= 0;
1695 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1697 set_view_attr(view, type);
1698 if (len > 0) {
1699 if (opt_iconv_out != ICONV_NONE) {
1700 size_t inlen = len + 1;
1701 char *instr = calloc(1, inlen);
1702 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1703 if (!instr)
1704 return VIEW_MAX_LEN(view) <= 0;
1706 strncpy(instr, string, len);
1708 char *outbuf = out_buffer;
1709 size_t outlen = sizeof(out_buffer);
1711 size_t ret;
1713 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1714 if (ret != (size_t) -1) {
1715 string = out_buffer;
1716 len = sizeof(out_buffer) - outlen;
1718 free(instr);
1721 waddnstr(view->win, string, len);
1723 if (trimmed && use_tilde) {
1724 set_view_attr(view, LINE_DELIMITER);
1725 waddch(view->win, '~');
1726 col++;
1730 view->col += col;
1731 return VIEW_MAX_LEN(view) <= 0;
1734 static bool
1735 draw_space(struct view *view, enum line_type type, int max, int spaces)
1737 static char space[] = " ";
1739 spaces = MIN(max, spaces);
1741 while (spaces > 0) {
1742 int len = MIN(spaces, sizeof(space) - 1);
1744 if (draw_chars(view, type, space, len, FALSE))
1745 return TRUE;
1746 spaces -= len;
1749 return VIEW_MAX_LEN(view) <= 0;
1752 static bool
1753 draw_text(struct view *view, enum line_type type, const char *string)
1755 char text[SIZEOF_STR];
1757 do {
1758 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1760 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1761 return TRUE;
1762 string += pos;
1763 } while (*string);
1765 return VIEW_MAX_LEN(view) <= 0;
1768 static bool
1769 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1771 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1772 int max = VIEW_MAX_LEN(view);
1773 int i;
1775 if (max < size)
1776 size = max;
1778 set_view_attr(view, type);
1779 /* Using waddch() instead of waddnstr() ensures that
1780 * they'll be rendered correctly for the cursor line. */
1781 for (i = skip; i < size; i++)
1782 waddch(view->win, graphic[i]);
1784 view->col += size;
1785 if (separator) {
1786 if (size < max && skip <= size)
1787 waddch(view->win, ' ');
1788 view->col++;
1791 return VIEW_MAX_LEN(view) <= 0;
1794 static bool
1795 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1797 int max = MIN(VIEW_MAX_LEN(view), len);
1798 int col = view->col;
1800 if (!text)
1801 return draw_space(view, type, max, max);
1803 return draw_chars(view, type, text, max - 1, trim)
1804 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1807 static bool
1808 draw_date(struct view *view, struct time *time)
1810 const char *date = mkdate(time, opt_date);
1811 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1813 if (opt_date == DATE_NO)
1814 return FALSE;
1816 return draw_field(view, LINE_DATE, date, cols, FALSE);
1819 static bool
1820 draw_author(struct view *view, const char *author)
1822 bool trim = author_trim(opt_author_cols);
1823 const char *text = mkauthor(author, opt_author_cols, opt_author);
1825 if (opt_author == AUTHOR_NO)
1826 return FALSE;
1828 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1831 static bool
1832 draw_filename(struct view *view, const char *filename, bool auto_enabled)
1834 bool trim = filename && strlen(filename) >= opt_filename_cols;
1836 if (opt_filename == FILENAME_NO)
1837 return FALSE;
1839 if (opt_filename == FILENAME_AUTO && !auto_enabled)
1840 return FALSE;
1842 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
1845 static bool
1846 draw_mode(struct view *view, mode_t mode)
1848 const char *str = mkmode(mode);
1850 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1853 static bool
1854 draw_lineno(struct view *view, unsigned int lineno)
1856 char number[10];
1857 int digits3 = view->digits < 3 ? 3 : view->digits;
1858 int max = MIN(VIEW_MAX_LEN(view), digits3);
1859 char *text = NULL;
1860 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1862 lineno += view->offset + 1;
1863 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1864 static char fmt[] = "%1ld";
1866 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1867 if (string_format(number, fmt, lineno))
1868 text = number;
1870 if (text)
1871 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1872 else
1873 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1874 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1877 static bool
1878 draw_refs(struct view *view, struct ref_list *refs)
1880 size_t i;
1882 if (!opt_show_refs || !refs)
1883 return FALSE;
1885 for (i = 0; i < refs->size; i++) {
1886 struct ref *ref = refs->refs[i];
1887 enum line_type type = get_line_type_from_ref(ref);
1889 if (draw_text(view, type, "[") ||
1890 draw_text(view, type, ref->name) ||
1891 draw_text(view, type, "]"))
1892 return TRUE;
1894 if (draw_text(view, LINE_DEFAULT, " "))
1895 return TRUE;
1898 return FALSE;
1901 static bool
1902 draw_view_line(struct view *view, unsigned int lineno)
1904 struct line *line;
1905 bool selected = (view->offset + lineno == view->lineno);
1907 assert(view_is_displayed(view));
1909 if (view->offset + lineno >= view->lines)
1910 return FALSE;
1912 line = &view->line[view->offset + lineno];
1914 wmove(view->win, lineno, 0);
1915 if (line->cleareol)
1916 wclrtoeol(view->win);
1917 view->col = 0;
1918 view->curline = line;
1919 view->curtype = LINE_NONE;
1920 line->selected = FALSE;
1921 line->dirty = line->cleareol = 0;
1923 if (selected) {
1924 set_view_attr(view, LINE_CURSOR);
1925 line->selected = TRUE;
1926 view->ops->select(view, line);
1929 return view->ops->draw(view, line, lineno);
1932 static void
1933 redraw_view_dirty(struct view *view)
1935 bool dirty = FALSE;
1936 int lineno;
1938 for (lineno = 0; lineno < view->height; lineno++) {
1939 if (view->offset + lineno >= view->lines)
1940 break;
1941 if (!view->line[view->offset + lineno].dirty)
1942 continue;
1943 dirty = TRUE;
1944 if (!draw_view_line(view, lineno))
1945 break;
1948 if (!dirty)
1949 return;
1950 wnoutrefresh(view->win);
1953 static void
1954 redraw_view_from(struct view *view, int lineno)
1956 assert(0 <= lineno && lineno < view->height);
1958 for (; lineno < view->height; lineno++) {
1959 if (!draw_view_line(view, lineno))
1960 break;
1963 wnoutrefresh(view->win);
1966 static void
1967 redraw_view(struct view *view)
1969 werase(view->win);
1970 redraw_view_from(view, 0);
1974 static void
1975 update_view_title(struct view *view)
1977 char buf[SIZEOF_STR];
1978 char state[SIZEOF_STR];
1979 size_t bufpos = 0, statelen = 0;
1980 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1982 assert(view_is_displayed(view));
1984 if (view->type != VIEW_STATUS && view->lines) {
1985 unsigned int view_lines = view->offset + view->height;
1986 unsigned int lines = view->lines
1987 ? MIN(view_lines, view->lines) * 100 / view->lines
1988 : 0;
1990 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
1991 view->ops->type,
1992 view->lineno + 1,
1993 view->lines,
1994 lines);
1998 if (view->pipe) {
1999 time_t secs = time(NULL) - view->start_time;
2001 /* Three git seconds are a long time ... */
2002 if (secs > 2)
2003 string_format_from(state, &statelen, " loading %lds", secs);
2006 string_format_from(buf, &bufpos, "[%s]", view->name);
2007 if (*view->ref && bufpos < view->width) {
2008 size_t refsize = strlen(view->ref);
2009 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2011 if (minsize < view->width)
2012 refsize = view->width - minsize + 7;
2013 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2016 if (statelen && bufpos < view->width) {
2017 string_format_from(buf, &bufpos, "%s", state);
2020 if (view == display[current_view])
2021 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2022 else
2023 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2025 mvwaddnstr(window, 0, 0, buf, bufpos);
2026 wclrtoeol(window);
2027 wnoutrefresh(window);
2030 static int
2031 apply_step(double step, int value)
2033 if (step >= 1)
2034 return (int) step;
2035 value *= step + 0.01;
2036 return value ? value : 1;
2039 static void
2040 resize_display(void)
2042 int offset, i;
2043 struct view *base = display[0];
2044 struct view *view = display[1] ? display[1] : display[0];
2046 /* Setup window dimensions */
2048 getmaxyx(stdscr, base->height, base->width);
2050 /* Make room for the status window. */
2051 base->height -= 1;
2053 if (view != base) {
2054 /* Horizontal split. */
2055 view->width = base->width;
2056 view->height = apply_step(opt_scale_split_view, base->height);
2057 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2058 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2059 base->height -= view->height;
2061 /* Make room for the title bar. */
2062 view->height -= 1;
2065 /* Make room for the title bar. */
2066 base->height -= 1;
2068 offset = 0;
2070 foreach_displayed_view (view, i) {
2071 if (!display_win[i]) {
2072 display_win[i] = newwin(view->height, view->width, offset, 0);
2073 if (!display_win[i])
2074 die("Failed to create %s view", view->name);
2076 scrollok(display_win[i], FALSE);
2078 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2079 if (!display_title[i])
2080 die("Failed to create title window");
2082 } else {
2083 wresize(display_win[i], view->height, view->width);
2084 mvwin(display_win[i], offset, 0);
2085 mvwin(display_title[i], offset + view->height, 0);
2088 view->win = display_win[i];
2090 offset += view->height + 1;
2094 static void
2095 redraw_display(bool clear)
2097 struct view *view;
2098 int i;
2100 foreach_displayed_view (view, i) {
2101 if (clear)
2102 wclear(view->win);
2103 redraw_view(view);
2104 update_view_title(view);
2110 * Option management
2113 #define TOGGLE_MENU \
2114 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2115 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2116 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2117 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2118 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2119 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2120 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL)
2122 static void
2123 toggle_option(enum request request)
2125 const struct {
2126 enum request request;
2127 const struct enum_map *map;
2128 size_t map_size;
2129 } data[] = {
2130 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2131 TOGGLE_MENU
2132 #undef TOGGLE_
2134 const struct menu_item menu[] = {
2135 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2136 TOGGLE_MENU
2137 #undef TOGGLE_
2138 { 0 }
2140 int i = 0;
2142 if (request == REQ_OPTIONS) {
2143 if (!prompt_menu("Toggle option", menu, &i))
2144 return;
2145 } else {
2146 while (i < ARRAY_SIZE(data) && data[i].request != request)
2147 i++;
2148 if (i >= ARRAY_SIZE(data))
2149 die("Invalid request (%d)", request);
2152 if (data[i].map != NULL) {
2153 unsigned int *opt = menu[i].data;
2155 *opt = (*opt + 1) % data[i].map_size;
2156 redraw_display(FALSE);
2157 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2159 } else {
2160 bool *option = menu[i].data;
2162 *option = !*option;
2163 redraw_display(FALSE);
2164 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2168 static void
2169 maximize_view(struct view *view, bool redraw)
2171 memset(display, 0, sizeof(display));
2172 current_view = 0;
2173 display[current_view] = view;
2174 resize_display();
2175 if (redraw) {
2176 redraw_display(FALSE);
2177 report("");
2183 * Navigation
2186 static bool
2187 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2189 if (lineno >= view->lines)
2190 lineno = view->lines > 0 ? view->lines - 1 : 0;
2192 if (offset > lineno || offset + view->height <= lineno) {
2193 unsigned long half = view->height / 2;
2195 if (lineno > half)
2196 offset = lineno - half;
2197 else
2198 offset = 0;
2201 if (offset != view->offset || lineno != view->lineno) {
2202 view->offset = offset;
2203 view->lineno = lineno;
2204 return TRUE;
2207 return FALSE;
2210 /* Scrolling backend */
2211 static void
2212 do_scroll_view(struct view *view, int lines)
2214 bool redraw_current_line = FALSE;
2216 /* The rendering expects the new offset. */
2217 view->offset += lines;
2219 assert(0 <= view->offset && view->offset < view->lines);
2220 assert(lines);
2222 /* Move current line into the view. */
2223 if (view->lineno < view->offset) {
2224 view->lineno = view->offset;
2225 redraw_current_line = TRUE;
2226 } else if (view->lineno >= view->offset + view->height) {
2227 view->lineno = view->offset + view->height - 1;
2228 redraw_current_line = TRUE;
2231 assert(view->offset <= view->lineno && view->lineno < view->lines);
2233 /* Redraw the whole screen if scrolling is pointless. */
2234 if (view->height < ABS(lines)) {
2235 redraw_view(view);
2237 } else {
2238 int line = lines > 0 ? view->height - lines : 0;
2239 int end = line + ABS(lines);
2241 scrollok(view->win, TRUE);
2242 wscrl(view->win, lines);
2243 scrollok(view->win, FALSE);
2245 while (line < end && draw_view_line(view, line))
2246 line++;
2248 if (redraw_current_line)
2249 draw_view_line(view, view->lineno - view->offset);
2250 wnoutrefresh(view->win);
2253 view->has_scrolled = TRUE;
2254 report("");
2257 /* Scroll frontend */
2258 static void
2259 scroll_view(struct view *view, enum request request)
2261 int lines = 1;
2263 assert(view_is_displayed(view));
2265 switch (request) {
2266 case REQ_SCROLL_FIRST_COL:
2267 view->yoffset = 0;
2268 redraw_view_from(view, 0);
2269 report("");
2270 return;
2271 case REQ_SCROLL_LEFT:
2272 if (view->yoffset == 0) {
2273 report("Cannot scroll beyond the first column");
2274 return;
2276 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2277 view->yoffset = 0;
2278 else
2279 view->yoffset -= apply_step(opt_hscroll, view->width);
2280 redraw_view_from(view, 0);
2281 report("");
2282 return;
2283 case REQ_SCROLL_RIGHT:
2284 view->yoffset += apply_step(opt_hscroll, view->width);
2285 redraw_view(view);
2286 report("");
2287 return;
2288 case REQ_SCROLL_PAGE_DOWN:
2289 lines = view->height;
2290 case REQ_SCROLL_LINE_DOWN:
2291 if (view->offset + lines > view->lines)
2292 lines = view->lines - view->offset;
2294 if (lines == 0 || view->offset + view->height >= view->lines) {
2295 report("Cannot scroll beyond the last line");
2296 return;
2298 break;
2300 case REQ_SCROLL_PAGE_UP:
2301 lines = view->height;
2302 case REQ_SCROLL_LINE_UP:
2303 if (lines > view->offset)
2304 lines = view->offset;
2306 if (lines == 0) {
2307 report("Cannot scroll beyond the first line");
2308 return;
2311 lines = -lines;
2312 break;
2314 default:
2315 die("request %d not handled in switch", request);
2318 do_scroll_view(view, lines);
2321 /* Cursor moving */
2322 static void
2323 move_view(struct view *view, enum request request)
2325 int scroll_steps = 0;
2326 int steps;
2328 switch (request) {
2329 case REQ_MOVE_FIRST_LINE:
2330 steps = -view->lineno;
2331 break;
2333 case REQ_MOVE_LAST_LINE:
2334 steps = view->lines - view->lineno - 1;
2335 break;
2337 case REQ_MOVE_PAGE_UP:
2338 steps = view->height > view->lineno
2339 ? -view->lineno : -view->height;
2340 break;
2342 case REQ_MOVE_PAGE_DOWN:
2343 steps = view->lineno + view->height >= view->lines
2344 ? view->lines - view->lineno - 1 : view->height;
2345 break;
2347 case REQ_MOVE_UP:
2348 steps = -1;
2349 break;
2351 case REQ_MOVE_DOWN:
2352 steps = 1;
2353 break;
2355 default:
2356 die("request %d not handled in switch", request);
2359 if (steps <= 0 && view->lineno == 0) {
2360 report("Cannot move beyond the first line");
2361 return;
2363 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2364 report("Cannot move beyond the last line");
2365 return;
2368 /* Move the current line */
2369 view->lineno += steps;
2370 assert(0 <= view->lineno && view->lineno < view->lines);
2372 /* Check whether the view needs to be scrolled */
2373 if (view->lineno < view->offset ||
2374 view->lineno >= view->offset + view->height) {
2375 scroll_steps = steps;
2376 if (steps < 0 && -steps > view->offset) {
2377 scroll_steps = -view->offset;
2379 } else if (steps > 0) {
2380 if (view->lineno == view->lines - 1 &&
2381 view->lines > view->height) {
2382 scroll_steps = view->lines - view->offset - 1;
2383 if (scroll_steps >= view->height)
2384 scroll_steps -= view->height - 1;
2389 if (!view_is_displayed(view)) {
2390 view->offset += scroll_steps;
2391 assert(0 <= view->offset && view->offset < view->lines);
2392 view->ops->select(view, &view->line[view->lineno]);
2393 return;
2396 /* Repaint the old "current" line if we be scrolling */
2397 if (ABS(steps) < view->height)
2398 draw_view_line(view, view->lineno - steps - view->offset);
2400 if (scroll_steps) {
2401 do_scroll_view(view, scroll_steps);
2402 return;
2405 /* Draw the current line */
2406 draw_view_line(view, view->lineno - view->offset);
2408 wnoutrefresh(view->win);
2409 report("");
2414 * Searching
2417 static void search_view(struct view *view, enum request request);
2419 static bool
2420 grep_text(struct view *view, const char *text[])
2422 regmatch_t pmatch;
2423 size_t i;
2425 for (i = 0; text[i]; i++)
2426 if (*text[i] &&
2427 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2428 return TRUE;
2429 return FALSE;
2432 static void
2433 select_view_line(struct view *view, unsigned long lineno)
2435 unsigned long old_lineno = view->lineno;
2436 unsigned long old_offset = view->offset;
2438 if (goto_view_line(view, view->offset, lineno)) {
2439 if (view_is_displayed(view)) {
2440 if (old_offset != view->offset) {
2441 redraw_view(view);
2442 } else {
2443 draw_view_line(view, old_lineno - view->offset);
2444 draw_view_line(view, view->lineno - view->offset);
2445 wnoutrefresh(view->win);
2447 } else {
2448 view->ops->select(view, &view->line[view->lineno]);
2453 static void
2454 find_next(struct view *view, enum request request)
2456 unsigned long lineno = view->lineno;
2457 int direction;
2459 if (!*view->grep) {
2460 if (!*opt_search)
2461 report("No previous search");
2462 else
2463 search_view(view, request);
2464 return;
2467 switch (request) {
2468 case REQ_SEARCH:
2469 case REQ_FIND_NEXT:
2470 direction = 1;
2471 break;
2473 case REQ_SEARCH_BACK:
2474 case REQ_FIND_PREV:
2475 direction = -1;
2476 break;
2478 default:
2479 return;
2482 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2483 lineno += direction;
2485 /* Note, lineno is unsigned long so will wrap around in which case it
2486 * will become bigger than view->lines. */
2487 for (; lineno < view->lines; lineno += direction) {
2488 if (view->ops->grep(view, &view->line[lineno])) {
2489 select_view_line(view, lineno);
2490 report("Line %ld matches '%s'", lineno + 1, view->grep);
2491 return;
2495 report("No match found for '%s'", view->grep);
2498 static void
2499 search_view(struct view *view, enum request request)
2501 int regex_err;
2503 if (view->regex) {
2504 regfree(view->regex);
2505 *view->grep = 0;
2506 } else {
2507 view->regex = calloc(1, sizeof(*view->regex));
2508 if (!view->regex)
2509 return;
2512 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2513 if (regex_err != 0) {
2514 char buf[SIZEOF_STR] = "unknown error";
2516 regerror(regex_err, view->regex, buf, sizeof(buf));
2517 report("Search failed: %s", buf);
2518 return;
2521 string_copy(view->grep, opt_search);
2523 find_next(view, request);
2527 * Incremental updating
2530 static void
2531 reset_view(struct view *view)
2533 int i;
2535 for (i = 0; i < view->lines; i++)
2536 free(view->line[i].data);
2537 free(view->line);
2539 view->p_offset = view->offset;
2540 view->p_yoffset = view->yoffset;
2541 view->p_lineno = view->lineno;
2543 view->line = NULL;
2544 view->offset = 0;
2545 view->yoffset = 0;
2546 view->lines = 0;
2547 view->lineno = 0;
2548 view->vid[0] = 0;
2549 view->update_secs = 0;
2552 static const char *
2553 format_arg(const char *name)
2555 static struct {
2556 const char *name;
2557 size_t namelen;
2558 const char *value;
2559 const char *value_if_empty;
2560 } vars[] = {
2561 #define FORMAT_VAR(name, value, value_if_empty) \
2562 { name, STRING_SIZE(name), value, value_if_empty }
2563 FORMAT_VAR("%(directory)", opt_path, "."),
2564 FORMAT_VAR("%(file)", opt_file, ""),
2565 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2566 FORMAT_VAR("%(head)", ref_head, ""),
2567 FORMAT_VAR("%(commit)", ref_commit, ""),
2568 FORMAT_VAR("%(blob)", ref_blob, ""),
2569 FORMAT_VAR("%(branch)", ref_branch, ""),
2571 int i;
2573 for (i = 0; i < ARRAY_SIZE(vars); i++)
2574 if (!strncmp(name, vars[i].name, vars[i].namelen))
2575 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2577 report("Unknown replacement: `%s`", name);
2578 return NULL;
2581 static bool
2582 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2584 char buf[SIZEOF_STR];
2585 int argc;
2587 argv_free(*dst_argv);
2589 for (argc = 0; src_argv[argc]; argc++) {
2590 const char *arg = src_argv[argc];
2591 size_t bufpos = 0;
2593 if (!strcmp(arg, "%(fileargs)")) {
2594 if (!argv_append_array(dst_argv, opt_file_argv))
2595 break;
2596 continue;
2598 } else if (!strcmp(arg, "%(diffargs)")) {
2599 if (!argv_append_array(dst_argv, opt_diff_argv))
2600 break;
2601 continue;
2603 } else if (!strcmp(arg, "%(blameargs)")) {
2604 if (!argv_append_array(dst_argv, opt_blame_argv))
2605 break;
2606 continue;
2608 } else if (!strcmp(arg, "%(revargs)") ||
2609 (first && !strcmp(arg, "%(commit)"))) {
2610 if (!argv_append_array(dst_argv, opt_rev_argv))
2611 break;
2612 continue;
2615 while (arg) {
2616 char *next = strstr(arg, "%(");
2617 int len = next - arg;
2618 const char *value;
2620 if (!next) {
2621 len = strlen(arg);
2622 value = "";
2624 } else {
2625 value = format_arg(next);
2627 if (!value) {
2628 return FALSE;
2632 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2633 return FALSE;
2635 arg = next ? strchr(next, ')') + 1 : NULL;
2638 if (!argv_append(dst_argv, buf))
2639 break;
2642 return src_argv[argc] == NULL;
2645 static bool
2646 restore_view_position(struct view *view)
2648 /* A view without a previous view is the first view */
2649 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2650 select_view_line(view, opt_lineno - 1);
2651 opt_lineno = 0;
2654 if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2655 return FALSE;
2657 /* Changing the view position cancels the restoring. */
2658 /* FIXME: Changing back to the first line is not detected. */
2659 if (view->offset != 0 || view->lineno != 0) {
2660 view->p_restore = FALSE;
2661 return FALSE;
2664 if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2665 view_is_displayed(view))
2666 werase(view->win);
2668 view->yoffset = view->p_yoffset;
2669 view->p_restore = FALSE;
2671 return TRUE;
2674 static void
2675 end_update(struct view *view, bool force)
2677 if (!view->pipe)
2678 return;
2679 while (!view->ops->read(view, NULL))
2680 if (!force)
2681 return;
2682 if (force)
2683 io_kill(view->pipe);
2684 io_done(view->pipe);
2685 view->pipe = NULL;
2688 static void
2689 setup_update(struct view *view, const char *vid)
2691 reset_view(view);
2692 string_copy_rev(view->vid, vid);
2693 view->pipe = &view->io;
2694 view->start_time = time(NULL);
2697 static bool
2698 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2700 bool extra = !!(flags & (OPEN_EXTRA));
2701 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2702 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2704 if (!reload && !strcmp(view->vid, view->id))
2705 return TRUE;
2707 if (view->pipe) {
2708 if (extra)
2709 io_done(view->pipe);
2710 else
2711 end_update(view, TRUE);
2714 if (!refresh && argv) {
2715 view->dir = dir;
2716 if (!format_argv(&view->argv, argv, !view->prev))
2717 return FALSE;
2719 /* Put the current ref_* value to the view title ref
2720 * member. This is needed by the blob view. Most other
2721 * views sets it automatically after loading because the
2722 * first line is a commit line. */
2723 string_copy_rev(view->ref, view->id);
2726 if (view->argv && view->argv[0] &&
2727 !io_run(&view->io, IO_RD, view->dir, view->argv))
2728 return FALSE;
2730 if (!extra)
2731 setup_update(view, view->id);
2733 return TRUE;
2736 static bool
2737 update_view(struct view *view)
2739 char out_buffer[BUFSIZ * 2];
2740 char *line;
2741 /* Clear the view and redraw everything since the tree sorting
2742 * might have rearranged things. */
2743 bool redraw = view->lines == 0;
2744 bool can_read = TRUE;
2746 if (!view->pipe)
2747 return TRUE;
2749 if (!io_can_read(view->pipe, FALSE)) {
2750 if (view->lines == 0 && view_is_displayed(view)) {
2751 time_t secs = time(NULL) - view->start_time;
2753 if (secs > 1 && secs > view->update_secs) {
2754 if (view->update_secs == 0)
2755 redraw_view(view);
2756 update_view_title(view);
2757 view->update_secs = secs;
2760 return TRUE;
2763 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2764 if (opt_iconv_in != ICONV_NONE) {
2765 ICONV_CONST char *inbuf = line;
2766 size_t inlen = strlen(line) + 1;
2768 char *outbuf = out_buffer;
2769 size_t outlen = sizeof(out_buffer);
2771 size_t ret;
2773 ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2774 if (ret != (size_t) -1)
2775 line = out_buffer;
2778 if (!view->ops->read(view, line)) {
2779 report("Allocation failure");
2780 end_update(view, TRUE);
2781 return FALSE;
2786 unsigned long lines = view->lines;
2787 int digits;
2789 for (digits = 0; lines; digits++)
2790 lines /= 10;
2792 /* Keep the displayed view in sync with line number scaling. */
2793 if (digits != view->digits) {
2794 view->digits = digits;
2795 if (opt_line_number || view->type == VIEW_BLAME)
2796 redraw = TRUE;
2800 if (io_error(view->pipe)) {
2801 report("Failed to read: %s", io_strerror(view->pipe));
2802 end_update(view, TRUE);
2804 } else if (io_eof(view->pipe)) {
2805 if (view_is_displayed(view))
2806 report("");
2807 end_update(view, FALSE);
2810 if (restore_view_position(view))
2811 redraw = TRUE;
2813 if (!view_is_displayed(view))
2814 return TRUE;
2816 if (redraw)
2817 redraw_view_from(view, 0);
2818 else
2819 redraw_view_dirty(view);
2821 /* Update the title _after_ the redraw so that if the redraw picks up a
2822 * commit reference in view->ref it'll be available here. */
2823 update_view_title(view);
2824 return TRUE;
2827 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2829 static struct line *
2830 add_line_data(struct view *view, void *data, enum line_type type)
2832 struct line *line;
2834 if (!realloc_lines(&view->line, view->lines, 1))
2835 return NULL;
2837 line = &view->line[view->lines++];
2838 memset(line, 0, sizeof(*line));
2839 line->type = type;
2840 line->data = data;
2841 line->dirty = 1;
2843 return line;
2846 static struct line *
2847 add_line_text(struct view *view, const char *text, enum line_type type)
2849 char *data = text ? strdup(text) : NULL;
2851 return data ? add_line_data(view, data, type) : NULL;
2854 static struct line *
2855 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2857 char buf[SIZEOF_STR];
2858 int retval;
2860 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval);
2861 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
2865 * View opening
2868 static void
2869 load_view(struct view *view, enum open_flags flags)
2871 if (view->pipe)
2872 end_update(view, TRUE);
2873 if (view->ops->private_size) {
2874 if (!view->private)
2875 view->private = calloc(1, view->ops->private_size);
2876 else
2877 memset(view->private, 0, view->ops->private_size);
2879 if (!view->ops->open(view, flags)) {
2880 report("Failed to load %s view", view->name);
2881 return;
2883 restore_view_position(view);
2885 if (view->pipe && view->lines == 0) {
2886 /* Clear the old view and let the incremental updating refill
2887 * the screen. */
2888 werase(view->win);
2889 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2890 report("");
2891 } else if (view_is_displayed(view)) {
2892 redraw_view(view);
2893 report("");
2897 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2898 #define reload_view(view) load_view(view, OPEN_RELOAD)
2900 static void
2901 split_view(struct view *prev, struct view *view)
2903 display[1] = view;
2904 current_view = 1;
2905 view->parent = prev;
2906 resize_display();
2908 if (prev->lineno - prev->offset >= prev->height) {
2909 /* Take the title line into account. */
2910 int lines = prev->lineno - prev->offset - prev->height + 1;
2912 /* Scroll the view that was split if the current line is
2913 * outside the new limited view. */
2914 do_scroll_view(prev, lines);
2917 if (view != prev && view_is_displayed(prev)) {
2918 /* "Blur" the previous view. */
2919 update_view_title(prev);
2923 static void
2924 open_view(struct view *prev, enum request request, enum open_flags flags)
2926 bool split = !!(flags & OPEN_SPLIT);
2927 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
2928 struct view *view = VIEW(request);
2929 int nviews = displayed_views();
2931 assert(flags ^ OPEN_REFRESH);
2933 if (view == prev && nviews == 1 && !reload) {
2934 report("Already in %s view", view->name);
2935 return;
2938 if (view->git_dir && !opt_git_dir[0]) {
2939 report("The %s view is disabled in pager view", view->name);
2940 return;
2943 if (split) {
2944 split_view(prev, view);
2945 } else {
2946 maximize_view(view, FALSE);
2949 /* No prev signals that this is the first loaded view. */
2950 if (prev && view != prev) {
2951 view->prev = prev;
2954 load_view(view, flags);
2957 static void
2958 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
2960 enum request request = view - views + REQ_OFFSET + 1;
2962 if (view->pipe)
2963 end_update(view, TRUE);
2964 view->dir = dir;
2966 if (!argv_copy(&view->argv, argv)) {
2967 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
2968 } else {
2969 open_view(prev, request, flags | OPEN_PREPARED);
2973 static void
2974 open_external_viewer(const char *argv[], const char *dir)
2976 def_prog_mode(); /* save current tty modes */
2977 endwin(); /* restore original tty modes */
2978 io_run_fg(argv, dir);
2979 fprintf(stderr, "Press Enter to continue");
2980 getc(opt_tty);
2981 reset_prog_mode();
2982 redraw_display(TRUE);
2985 static void
2986 open_mergetool(const char *file)
2988 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2990 open_external_viewer(mergetool_argv, opt_cdup);
2993 static void
2994 open_editor(const char *file)
2996 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
2997 char editor_cmd[SIZEOF_STR];
2998 const char *editor;
2999 int argc = 0;
3001 editor = getenv("GIT_EDITOR");
3002 if (!editor && *opt_editor)
3003 editor = opt_editor;
3004 if (!editor)
3005 editor = getenv("VISUAL");
3006 if (!editor)
3007 editor = getenv("EDITOR");
3008 if (!editor)
3009 editor = "vi";
3011 string_ncopy(editor_cmd, editor, strlen(editor));
3012 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3013 report("Failed to read editor command");
3014 return;
3017 editor_argv[argc] = file;
3018 open_external_viewer(editor_argv, opt_cdup);
3021 static void
3022 open_run_request(enum request request)
3024 struct run_request *req = get_run_request(request);
3025 const char **argv = NULL;
3027 if (!req) {
3028 report("Unknown run request");
3029 return;
3032 if (format_argv(&argv, req->argv, FALSE))
3033 open_external_viewer(argv, NULL);
3034 if (argv)
3035 argv_free(argv);
3036 free(argv);
3040 * User request switch noodle
3043 static int
3044 view_driver(struct view *view, enum request request)
3046 int i;
3048 if (request == REQ_NONE)
3049 return TRUE;
3051 if (request > REQ_NONE) {
3052 open_run_request(request);
3053 view_request(view, REQ_REFRESH);
3054 return TRUE;
3057 request = view_request(view, request);
3058 if (request == REQ_NONE)
3059 return TRUE;
3061 switch (request) {
3062 case REQ_MOVE_UP:
3063 case REQ_MOVE_DOWN:
3064 case REQ_MOVE_PAGE_UP:
3065 case REQ_MOVE_PAGE_DOWN:
3066 case REQ_MOVE_FIRST_LINE:
3067 case REQ_MOVE_LAST_LINE:
3068 move_view(view, request);
3069 break;
3071 case REQ_SCROLL_FIRST_COL:
3072 case REQ_SCROLL_LEFT:
3073 case REQ_SCROLL_RIGHT:
3074 case REQ_SCROLL_LINE_DOWN:
3075 case REQ_SCROLL_LINE_UP:
3076 case REQ_SCROLL_PAGE_DOWN:
3077 case REQ_SCROLL_PAGE_UP:
3078 scroll_view(view, request);
3079 break;
3081 case REQ_VIEW_BLAME:
3082 if (!opt_file[0]) {
3083 report("No file chosen, press %s to open tree view",
3084 get_key(view->keymap, REQ_VIEW_TREE));
3085 break;
3087 open_view(view, request, OPEN_DEFAULT);
3088 break;
3090 case REQ_VIEW_BLOB:
3091 if (!ref_blob[0]) {
3092 report("No file chosen, press %s to open tree view",
3093 get_key(view->keymap, REQ_VIEW_TREE));
3094 break;
3096 open_view(view, request, OPEN_DEFAULT);
3097 break;
3099 case REQ_VIEW_PAGER:
3100 if (view == NULL) {
3101 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
3102 die("Failed to open stdin");
3103 open_view(view, request, OPEN_PREPARED);
3104 break;
3107 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
3108 report("No pager content, press %s to run command from prompt",
3109 get_key(view->keymap, REQ_PROMPT));
3110 break;
3112 open_view(view, request, OPEN_DEFAULT);
3113 break;
3115 case REQ_VIEW_STAGE:
3116 if (!VIEW(REQ_VIEW_STAGE)->lines) {
3117 report("No stage content, press %s to open the status view and choose file",
3118 get_key(view->keymap, REQ_VIEW_STATUS));
3119 break;
3121 open_view(view, request, OPEN_DEFAULT);
3122 break;
3124 case REQ_VIEW_STATUS:
3125 if (opt_is_inside_work_tree == FALSE) {
3126 report("The status view requires a working tree");
3127 break;
3129 open_view(view, request, OPEN_DEFAULT);
3130 break;
3132 case REQ_VIEW_MAIN:
3133 case REQ_VIEW_DIFF:
3134 case REQ_VIEW_LOG:
3135 case REQ_VIEW_TREE:
3136 case REQ_VIEW_HELP:
3137 case REQ_VIEW_BRANCH:
3138 open_view(view, request, OPEN_DEFAULT);
3139 break;
3141 case REQ_NEXT:
3142 case REQ_PREVIOUS:
3143 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
3145 if (view->parent) {
3146 int line;
3148 view = view->parent;
3149 line = view->lineno;
3150 move_view(view, request);
3151 if (view_is_displayed(view))
3152 update_view_title(view);
3153 if (line != view->lineno)
3154 view_request(view, REQ_ENTER);
3155 } else {
3156 move_view(view, request);
3158 break;
3160 case REQ_VIEW_NEXT:
3162 int nviews = displayed_views();
3163 int next_view = (current_view + 1) % nviews;
3165 if (next_view == current_view) {
3166 report("Only one view is displayed");
3167 break;
3170 current_view = next_view;
3171 /* Blur out the title of the previous view. */
3172 update_view_title(view);
3173 report("");
3174 break;
3176 case REQ_REFRESH:
3177 report("Refreshing is not yet supported for the %s view", view->name);
3178 break;
3180 case REQ_MAXIMIZE:
3181 if (displayed_views() == 2)
3182 maximize_view(view, TRUE);
3183 break;
3185 case REQ_OPTIONS:
3186 case REQ_TOGGLE_LINENO:
3187 case REQ_TOGGLE_DATE:
3188 case REQ_TOGGLE_AUTHOR:
3189 case REQ_TOGGLE_FILENAME:
3190 case REQ_TOGGLE_GRAPHIC:
3191 case REQ_TOGGLE_REV_GRAPH:
3192 case REQ_TOGGLE_REFS:
3193 toggle_option(request);
3194 break;
3196 case REQ_TOGGLE_SORT_FIELD:
3197 case REQ_TOGGLE_SORT_ORDER:
3198 report("Sorting is not yet supported for the %s view", view->name);
3199 break;
3201 case REQ_DIFF_CONTEXT_UP:
3202 case REQ_DIFF_CONTEXT_DOWN:
3203 report("Changing the diff context is not yet supported for the %s view", view->name);
3204 break;
3206 case REQ_SEARCH:
3207 case REQ_SEARCH_BACK:
3208 search_view(view, request);
3209 break;
3211 case REQ_FIND_NEXT:
3212 case REQ_FIND_PREV:
3213 find_next(view, request);
3214 break;
3216 case REQ_STOP_LOADING:
3217 foreach_view(view, i) {
3218 if (view->pipe)
3219 report("Stopped loading the %s view", view->name),
3220 end_update(view, TRUE);
3222 break;
3224 case REQ_SHOW_VERSION:
3225 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3226 return TRUE;
3228 case REQ_SCREEN_REDRAW:
3229 redraw_display(TRUE);
3230 break;
3232 case REQ_EDIT:
3233 report("Nothing to edit");
3234 break;
3236 case REQ_ENTER:
3237 report("Nothing to enter");
3238 break;
3240 case REQ_VIEW_CLOSE:
3241 /* XXX: Mark closed views by letting view->prev point to the
3242 * view itself. Parents to closed view should never be
3243 * followed. */
3244 if (view->prev && view->prev != view) {
3245 maximize_view(view->prev, TRUE);
3246 view->prev = view;
3247 break;
3249 /* Fall-through */
3250 case REQ_QUIT:
3251 return FALSE;
3253 default:
3254 report("Unknown key, press %s for help",
3255 get_key(view->keymap, REQ_VIEW_HELP));
3256 return TRUE;
3259 return TRUE;
3264 * View backend utilities
3267 enum sort_field {
3268 ORDERBY_NAME,
3269 ORDERBY_DATE,
3270 ORDERBY_AUTHOR,
3273 struct sort_state {
3274 const enum sort_field *fields;
3275 size_t size, current;
3276 bool reverse;
3279 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3280 #define get_sort_field(state) ((state).fields[(state).current])
3281 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3283 static void
3284 sort_view(struct view *view, enum request request, struct sort_state *state,
3285 int (*compare)(const void *, const void *))
3287 switch (request) {
3288 case REQ_TOGGLE_SORT_FIELD:
3289 state->current = (state->current + 1) % state->size;
3290 break;
3292 case REQ_TOGGLE_SORT_ORDER:
3293 state->reverse = !state->reverse;
3294 break;
3295 default:
3296 die("Not a sort request");
3299 qsort(view->line, view->lines, sizeof(*view->line), compare);
3300 redraw_view(view);
3303 static bool
3304 update_diff_context(enum request request)
3306 int diff_context = opt_diff_context;
3308 switch (request) {
3309 case REQ_DIFF_CONTEXT_UP:
3310 opt_diff_context += 1;
3311 update_diff_context_arg(opt_diff_context);
3312 break;
3314 case REQ_DIFF_CONTEXT_DOWN:
3315 if (opt_diff_context == 0) {
3316 report("Diff context cannot be less than zero");
3317 break;
3319 opt_diff_context -= 1;
3320 update_diff_context_arg(opt_diff_context);
3321 break;
3323 default:
3324 die("Not a diff context request");
3327 return diff_context != opt_diff_context;
3330 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3332 /* Small author cache to reduce memory consumption. It uses binary
3333 * search to lookup or find place to position new entries. No entries
3334 * are ever freed. */
3335 static const char *
3336 get_author(const char *name)
3338 static const char **authors;
3339 static size_t authors_size;
3340 int from = 0, to = authors_size - 1;
3342 while (from <= to) {
3343 size_t pos = (to + from) / 2;
3344 int cmp = strcmp(name, authors[pos]);
3346 if (!cmp)
3347 return authors[pos];
3349 if (cmp < 0)
3350 to = pos - 1;
3351 else
3352 from = pos + 1;
3355 if (!realloc_authors(&authors, authors_size, 1))
3356 return NULL;
3357 name = strdup(name);
3358 if (!name)
3359 return NULL;
3361 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3362 authors[from] = name;
3363 authors_size++;
3365 return name;
3368 static void
3369 parse_timesec(struct time *time, const char *sec)
3371 time->sec = (time_t) atol(sec);
3374 static void
3375 parse_timezone(struct time *time, const char *zone)
3377 long tz;
3379 tz = ('0' - zone[1]) * 60 * 60 * 10;
3380 tz += ('0' - zone[2]) * 60 * 60;
3381 tz += ('0' - zone[3]) * 60 * 10;
3382 tz += ('0' - zone[4]) * 60;
3384 if (zone[0] == '-')
3385 tz = -tz;
3387 time->tz = tz;
3388 time->sec -= tz;
3391 /* Parse author lines where the name may be empty:
3392 * author <email@address.tld> 1138474660 +0100
3394 static void
3395 parse_author_line(char *ident, const char **author, struct time *time)
3397 char *nameend = strchr(ident, '<');
3398 char *emailend = strchr(ident, '>');
3400 if (nameend && emailend)
3401 *nameend = *emailend = 0;
3402 ident = chomp_string(ident);
3403 if (!*ident) {
3404 if (nameend)
3405 ident = chomp_string(nameend + 1);
3406 if (!*ident)
3407 ident = "Unknown";
3410 *author = get_author(ident);
3412 /* Parse epoch and timezone */
3413 if (emailend && emailend[1] == ' ') {
3414 char *secs = emailend + 2;
3415 char *zone = strchr(secs, ' ');
3417 parse_timesec(time, secs);
3419 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3420 parse_timezone(time, zone + 1);
3424 static struct line *
3425 find_prev_line_by_type(struct view *view, struct line *line, enum line_type type)
3427 for (; view->line < line; line--)
3428 if (line->type == type)
3429 return line;
3431 return NULL;
3435 * Blame
3438 struct blame_commit {
3439 char id[SIZEOF_REV]; /* SHA1 ID. */
3440 char title[128]; /* First line of the commit message. */
3441 const char *author; /* Author of the commit. */
3442 struct time time; /* Date from the author ident. */
3443 char filename[128]; /* Name of file. */
3444 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3445 char parent_filename[128]; /* Parent/previous name of file. */
3448 struct blame_header {
3449 char id[SIZEOF_REV]; /* SHA1 ID. */
3450 size_t orig_lineno;
3451 size_t lineno;
3452 size_t group;
3455 static bool
3456 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3458 const char *pos = *posref;
3460 *posref = NULL;
3461 pos = strchr(pos + 1, ' ');
3462 if (!pos || !isdigit(pos[1]))
3463 return FALSE;
3464 *number = atoi(pos + 1);
3465 if (*number < min || *number > max)
3466 return FALSE;
3468 *posref = pos;
3469 return TRUE;
3472 static bool
3473 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3475 const char *pos = text + SIZEOF_REV - 2;
3477 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3478 return FALSE;
3480 string_ncopy(header->id, text, SIZEOF_REV);
3482 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3483 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3484 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3485 return FALSE;
3487 return TRUE;
3490 static bool
3491 match_blame_header(const char *name, char **line)
3493 size_t namelen = strlen(name);
3494 bool matched = !strncmp(name, *line, namelen);
3496 if (matched)
3497 *line += namelen;
3499 return matched;
3502 static bool
3503 parse_blame_info(struct blame_commit *commit, char *line)
3505 if (match_blame_header("author ", &line)) {
3506 commit->author = get_author(line);
3508 } else if (match_blame_header("author-time ", &line)) {
3509 parse_timesec(&commit->time, line);
3511 } else if (match_blame_header("author-tz ", &line)) {
3512 parse_timezone(&commit->time, line);
3514 } else if (match_blame_header("summary ", &line)) {
3515 string_ncopy(commit->title, line, strlen(line));
3517 } else if (match_blame_header("previous ", &line)) {
3518 if (strlen(line) <= SIZEOF_REV)
3519 return FALSE;
3520 string_copy_rev(commit->parent_id, line);
3521 line += SIZEOF_REV;
3522 string_ncopy(commit->parent_filename, line, strlen(line));
3524 } else if (match_blame_header("filename ", &line)) {
3525 string_ncopy(commit->filename, line, strlen(line));
3526 return TRUE;
3529 return FALSE;
3533 * Pager backend
3536 static bool
3537 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3539 if (opt_line_number && draw_lineno(view, lineno))
3540 return TRUE;
3542 draw_text(view, line->type, line->data);
3543 return TRUE;
3546 static bool
3547 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3549 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3550 char ref[SIZEOF_STR];
3552 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3553 return TRUE;
3555 /* This is the only fatal call, since it can "corrupt" the buffer. */
3556 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3557 return FALSE;
3559 return TRUE;
3562 static void
3563 add_pager_refs(struct view *view, struct line *line)
3565 char buf[SIZEOF_STR];
3566 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3567 struct ref_list *list;
3568 size_t bufpos = 0, i;
3569 const char *sep = "Refs: ";
3570 bool is_tag = FALSE;
3572 assert(line->type == LINE_COMMIT);
3574 list = get_ref_list(commit_id);
3575 if (!list) {
3576 if (view->type == VIEW_DIFF)
3577 goto try_add_describe_ref;
3578 return;
3581 for (i = 0; i < list->size; i++) {
3582 struct ref *ref = list->refs[i];
3583 const char *fmt = ref->tag ? "%s[%s]" :
3584 ref->remote ? "%s<%s>" : "%s%s";
3586 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3587 return;
3588 sep = ", ";
3589 if (ref->tag)
3590 is_tag = TRUE;
3593 if (!is_tag && view->type == VIEW_DIFF) {
3594 try_add_describe_ref:
3595 /* Add <tag>-g<commit_id> "fake" reference. */
3596 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3597 return;
3600 if (bufpos == 0)
3601 return;
3603 add_line_text(view, buf, LINE_PP_REFS);
3606 static bool
3607 pager_read(struct view *view, char *data)
3609 struct line *line;
3611 if (!data)
3612 return TRUE;
3614 line = add_line_text(view, data, get_line_type(data));
3615 if (!line)
3616 return FALSE;
3618 if (line->type == LINE_COMMIT &&
3619 (view->type == VIEW_DIFF ||
3620 view->type == VIEW_LOG))
3621 add_pager_refs(view, line);
3623 return TRUE;
3626 static enum request
3627 pager_request(struct view *view, enum request request, struct line *line)
3629 int split = 0;
3631 if (request != REQ_ENTER)
3632 return request;
3634 if (line->type == LINE_COMMIT &&
3635 (view->type == VIEW_LOG ||
3636 view->type == VIEW_PAGER)) {
3637 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3638 split = 1;
3641 /* Always scroll the view even if it was split. That way
3642 * you can use Enter to scroll through the log view and
3643 * split open each commit diff. */
3644 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3646 /* FIXME: A minor workaround. Scrolling the view will call report("")
3647 * but if we are scrolling a non-current view this won't properly
3648 * update the view title. */
3649 if (split)
3650 update_view_title(view);
3652 return REQ_NONE;
3655 static bool
3656 pager_grep(struct view *view, struct line *line)
3658 const char *text[] = { line->data, NULL };
3660 return grep_text(view, text);
3663 static void
3664 pager_select(struct view *view, struct line *line)
3666 if (line->type == LINE_COMMIT) {
3667 char *text = (char *)line->data + STRING_SIZE("commit ");
3669 if (view->type != VIEW_PAGER)
3670 string_copy_rev(view->ref, text);
3671 string_copy_rev(ref_commit, text);
3675 static bool
3676 pager_open(struct view *view, enum open_flags flags)
3678 return begin_update(view, NULL, NULL, flags);
3681 static struct view_ops pager_ops = {
3682 "line",
3684 pager_open,
3685 pager_read,
3686 pager_draw,
3687 pager_request,
3688 pager_grep,
3689 pager_select,
3692 static bool
3693 log_open(struct view *view, enum open_flags flags)
3695 static const char *log_argv[] = {
3696 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3699 return begin_update(view, NULL, log_argv, flags);
3702 static enum request
3703 log_request(struct view *view, enum request request, struct line *line)
3705 switch (request) {
3706 case REQ_REFRESH:
3707 load_refs();
3708 refresh_view(view);
3709 return REQ_NONE;
3710 default:
3711 return pager_request(view, request, line);
3715 static struct view_ops log_ops = {
3716 "line",
3718 log_open,
3719 pager_read,
3720 pager_draw,
3721 log_request,
3722 pager_grep,
3723 pager_select,
3726 struct diff_state {
3727 bool reading_diff_stat;
3730 static bool
3731 diff_open(struct view *view, enum open_flags flags)
3733 static const char *diff_argv[] = {
3734 "git", "show", "--pretty=fuller", "--no-color", "--root",
3735 "--patch-with-stat", "--find-copies-harder", "-C",
3736 opt_notes_arg, opt_diff_context_arg, "%(diffargs)",
3737 "%(commit)", "--", "%(fileargs)", NULL
3740 return begin_update(view, NULL, diff_argv, flags);
3743 static bool
3744 diff_common_read(struct view *view, char *data, struct diff_state *state)
3746 if (state->reading_diff_stat) {
3747 size_t len = strlen(data);
3748 char *pipe = strchr(data, '|');
3749 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3750 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3752 if (pipe && (has_histogram || has_bin_diff)) {
3753 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3754 } else {
3755 state->reading_diff_stat = FALSE;
3758 } else if (!strcmp(data, "---")) {
3759 state->reading_diff_stat = TRUE;
3762 return pager_read(view, data);
3765 static enum request
3766 diff_common_enter(struct view *view, enum request request, struct line *line)
3768 if (line->type == LINE_DIFF_STAT) {
3769 int file_number = 0;
3771 while (line >= view->line && line->type == LINE_DIFF_STAT) {
3772 file_number++;
3773 line--;
3776 while (line < view->line + view->lines) {
3777 if (line->type == LINE_DIFF_HEADER) {
3778 if (file_number == 1) {
3779 break;
3781 file_number--;
3783 line++;
3787 select_view_line(view, line - view->line);
3788 report("");
3789 return REQ_NONE;
3791 } else {
3792 return pager_request(view, request, line);
3796 static bool
3797 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
3799 char *sep = strchr(*text, c);
3801 if (sep != NULL) {
3802 *sep = 0;
3803 draw_text(view, *type, *text);
3804 *sep = c;
3805 *text = sep;
3806 *type = next_type;
3809 return sep != NULL;
3812 static bool
3813 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
3815 char *text = line->data;
3816 enum line_type type = line->type;
3818 if (opt_line_number && draw_lineno(view, lineno))
3819 return TRUE;
3821 if (type == LINE_DIFF_STAT) {
3822 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
3823 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
3824 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
3825 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
3826 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
3827 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
3828 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
3830 } else {
3831 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
3832 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
3836 draw_text(view, type, text);
3837 return TRUE;
3840 static bool
3841 diff_read(struct view *view, char *data)
3843 struct diff_state *state = view->private;
3845 if (!data) {
3846 /* Fall back to retry if no diff will be shown. */
3847 if (view->lines == 0 && opt_file_argv) {
3848 int pos = argv_size(view->argv)
3849 - argv_size(opt_file_argv) - 1;
3851 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3852 for (; view->argv[pos]; pos++) {
3853 free((void *) view->argv[pos]);
3854 view->argv[pos] = NULL;
3857 if (view->pipe)
3858 io_done(view->pipe);
3859 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3860 return FALSE;
3863 return TRUE;
3866 return diff_common_read(view, data, state);
3869 static bool
3870 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
3871 struct blame_header *header, struct blame_commit *commit)
3873 char line_arg[SIZEOF_STR];
3874 const char *blame_argv[] = {
3875 "git", "blame", "-p", line_arg, ref, "--", file, NULL
3877 struct io io;
3878 bool ok = FALSE;
3879 char *buf;
3881 if (!string_format(line_arg, "-L%d,+1", lineno))
3882 return FALSE;
3884 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
3885 return FALSE;
3887 while ((buf = io_get(&io, '\n', TRUE))) {
3888 if (header) {
3889 if (!parse_blame_header(header, buf, 9999999))
3890 break;
3891 header = NULL;
3893 } else if (parse_blame_info(commit, buf)) {
3894 ok = TRUE;
3895 break;
3899 if (io_error(&io))
3900 ok = FALSE;
3902 io_done(&io);
3903 return ok;
3906 static bool
3907 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
3909 return prefixcmp(chunk, "@@ -") ||
3910 !(chunk = strchr(chunk, marker)) ||
3911 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
3914 static enum request
3915 diff_trace_origin(struct view *view, struct line *line)
3917 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
3918 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
3919 const char *chunk_data;
3920 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
3921 int lineno = 0;
3922 const char *file = NULL;
3923 char ref[SIZEOF_REF];
3924 struct blame_header header;
3925 struct blame_commit commit;
3927 if (!diff || !chunk || chunk == line) {
3928 report("The line to trace must be inside a diff chunk");
3929 return REQ_NONE;
3932 for (; diff < line && !file; diff++) {
3933 const char *data = diff->data;
3935 if (!prefixcmp(data, "--- a/")) {
3936 file = data + STRING_SIZE("--- a/");
3937 break;
3941 if (diff == line || !file) {
3942 report("Failed to read the file name");
3943 return REQ_NONE;
3946 chunk_data = chunk->data;
3948 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
3949 report("Failed to read the line number");
3950 return REQ_NONE;
3953 if (lineno == 0) {
3954 report("This is the origin of the line");
3955 return REQ_NONE;
3958 for (chunk += 1; chunk < line; chunk++) {
3959 if (chunk->type == LINE_DIFF_ADD) {
3960 lineno += chunk_marker == '+';
3961 } else if (chunk->type == LINE_DIFF_DEL) {
3962 lineno += chunk_marker == '-';
3963 } else {
3964 lineno++;
3968 if (chunk_marker == '+')
3969 string_copy(ref, view->vid);
3970 else
3971 string_format(ref, "%s^", view->vid);
3973 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
3974 report("Failed to read blame data");
3975 return REQ_NONE;
3978 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
3979 string_copy(opt_ref, header.id);
3980 opt_goto_line = header.orig_lineno - 1;
3982 return REQ_VIEW_BLAME;
3985 static enum request
3986 diff_request(struct view *view, enum request request, struct line *line)
3988 switch (request) {
3989 case REQ_VIEW_BLAME:
3990 return diff_trace_origin(view, line);
3992 case REQ_DIFF_CONTEXT_UP:
3993 case REQ_DIFF_CONTEXT_DOWN:
3994 if (!update_diff_context(request))
3995 return REQ_NONE;
3996 reload_view(view);
3997 return REQ_NONE;
3999 case REQ_ENTER:
4000 return diff_common_enter(view, request, line);
4002 default:
4003 return pager_request(view, request, line);
4007 static void
4008 diff_select(struct view *view, struct line *line)
4010 if (line->type == LINE_DIFF_STAT) {
4011 const char *key = get_key(KEYMAP_DIFF, REQ_ENTER);
4013 string_format(view->ref, "Press '%s' to jump to file diff", key);
4014 } else {
4015 string_ncopy(view->ref, view->id, strlen(view->id));
4016 return pager_select(view, line);
4020 static struct view_ops diff_ops = {
4021 "line",
4022 sizeof(struct diff_state),
4023 diff_open,
4024 diff_read,
4025 diff_common_draw,
4026 diff_request,
4027 pager_grep,
4028 diff_select,
4032 * Help backend
4035 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
4037 static bool
4038 help_open_keymap_title(struct view *view, enum keymap keymap)
4040 struct line *line;
4042 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
4043 help_keymap_hidden[keymap] ? '+' : '-',
4044 enum_name(keymap_map[keymap]));
4045 if (line)
4046 line->other = keymap;
4048 return help_keymap_hidden[keymap];
4051 static void
4052 help_open_keymap(struct view *view, enum keymap keymap)
4054 const char *group = NULL;
4055 char buf[SIZEOF_STR];
4056 size_t bufpos;
4057 bool add_title = TRUE;
4058 int i;
4060 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4061 const char *key = NULL;
4063 if (req_info[i].request == REQ_NONE)
4064 continue;
4066 if (!req_info[i].request) {
4067 group = req_info[i].help;
4068 continue;
4071 key = get_keys(keymap, req_info[i].request, TRUE);
4072 if (!key || !*key)
4073 continue;
4075 if (add_title && help_open_keymap_title(view, keymap))
4076 return;
4077 add_title = FALSE;
4079 if (group) {
4080 add_line_text(view, group, LINE_HELP_GROUP);
4081 group = NULL;
4084 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4085 enum_name(req_info[i]), req_info[i].help);
4088 group = "External commands:";
4090 for (i = 0; i < run_requests; i++) {
4091 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4092 const char *key;
4093 int argc;
4095 if (!req || req->keymap != keymap)
4096 continue;
4098 key = get_key_name(req->key);
4099 if (!*key)
4100 key = "(no key defined)";
4102 if (add_title && help_open_keymap_title(view, keymap))
4103 return;
4104 if (group) {
4105 add_line_text(view, group, LINE_HELP_GROUP);
4106 group = NULL;
4109 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
4110 if (!string_format_from(buf, &bufpos, "%s%s",
4111 argc ? " " : "", req->argv[argc]))
4112 return;
4114 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4118 static bool
4119 help_open(struct view *view, enum open_flags flags)
4121 enum keymap keymap;
4123 reset_view(view);
4124 view->p_restore = TRUE;
4125 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4126 add_line_text(view, "", LINE_DEFAULT);
4128 for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
4129 help_open_keymap(view, keymap);
4131 return TRUE;
4134 static enum request
4135 help_request(struct view *view, enum request request, struct line *line)
4137 switch (request) {
4138 case REQ_ENTER:
4139 if (line->type == LINE_HELP_KEYMAP) {
4140 help_keymap_hidden[line->other] =
4141 !help_keymap_hidden[line->other];
4142 refresh_view(view);
4145 return REQ_NONE;
4146 default:
4147 return pager_request(view, request, line);
4151 static struct view_ops help_ops = {
4152 "line",
4154 help_open,
4155 NULL,
4156 pager_draw,
4157 help_request,
4158 pager_grep,
4159 pager_select,
4164 * Tree backend
4167 struct tree_stack_entry {
4168 struct tree_stack_entry *prev; /* Entry below this in the stack */
4169 unsigned long lineno; /* Line number to restore */
4170 char *name; /* Position of name in opt_path */
4173 /* The top of the path stack. */
4174 static struct tree_stack_entry *tree_stack = NULL;
4175 unsigned long tree_lineno = 0;
4177 static void
4178 pop_tree_stack_entry(void)
4180 struct tree_stack_entry *entry = tree_stack;
4182 tree_lineno = entry->lineno;
4183 entry->name[0] = 0;
4184 tree_stack = entry->prev;
4185 free(entry);
4188 static void
4189 push_tree_stack_entry(const char *name, unsigned long lineno)
4191 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4192 size_t pathlen = strlen(opt_path);
4194 if (!entry)
4195 return;
4197 entry->prev = tree_stack;
4198 entry->name = opt_path + pathlen;
4199 tree_stack = entry;
4201 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4202 pop_tree_stack_entry();
4203 return;
4206 /* Move the current line to the first tree entry. */
4207 tree_lineno = 1;
4208 entry->lineno = lineno;
4211 /* Parse output from git-ls-tree(1):
4213 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4216 #define SIZEOF_TREE_ATTR \
4217 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4219 #define SIZEOF_TREE_MODE \
4220 STRING_SIZE("100644 ")
4222 #define TREE_ID_OFFSET \
4223 STRING_SIZE("100644 blob ")
4225 struct tree_entry {
4226 char id[SIZEOF_REV];
4227 mode_t mode;
4228 struct time time; /* Date from the author ident. */
4229 const char *author; /* Author of the commit. */
4230 char name[1];
4233 struct tree_state {
4234 const char *author_name;
4235 struct time author_time;
4236 bool read_date;
4239 static const char *
4240 tree_path(const struct line *line)
4242 return ((struct tree_entry *) line->data)->name;
4245 static int
4246 tree_compare_entry(const struct line *line1, const struct line *line2)
4248 if (line1->type != line2->type)
4249 return line1->type == LINE_TREE_DIR ? -1 : 1;
4250 return strcmp(tree_path(line1), tree_path(line2));
4253 static const enum sort_field tree_sort_fields[] = {
4254 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4256 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4258 static int
4259 tree_compare(const void *l1, const void *l2)
4261 const struct line *line1 = (const struct line *) l1;
4262 const struct line *line2 = (const struct line *) l2;
4263 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4264 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4266 if (line1->type == LINE_TREE_HEAD)
4267 return -1;
4268 if (line2->type == LINE_TREE_HEAD)
4269 return 1;
4271 switch (get_sort_field(tree_sort_state)) {
4272 case ORDERBY_DATE:
4273 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4275 case ORDERBY_AUTHOR:
4276 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4278 case ORDERBY_NAME:
4279 default:
4280 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4285 static struct line *
4286 tree_entry(struct view *view, enum line_type type, const char *path,
4287 const char *mode, const char *id)
4289 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4290 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4292 if (!entry || !line) {
4293 free(entry);
4294 return NULL;
4297 strncpy(entry->name, path, strlen(path));
4298 if (mode)
4299 entry->mode = strtoul(mode, NULL, 8);
4300 if (id)
4301 string_copy_rev(entry->id, id);
4303 return line;
4306 static bool
4307 tree_read_date(struct view *view, char *text, struct tree_state *state)
4309 if (!text && state->read_date) {
4310 state->read_date = FALSE;
4311 return TRUE;
4313 } else if (!text) {
4314 /* Find next entry to process */
4315 const char *log_file[] = {
4316 "git", "log", "--no-color", "--pretty=raw",
4317 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4320 if (!view->lines) {
4321 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4322 report("Tree is empty");
4323 return TRUE;
4326 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4327 report("Failed to load tree data");
4328 return TRUE;
4331 state->read_date = TRUE;
4332 return FALSE;
4334 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4335 parse_author_line(text + STRING_SIZE("author "),
4336 &state->author_name, &state->author_time);
4338 } else if (*text == ':') {
4339 char *pos;
4340 size_t annotated = 1;
4341 size_t i;
4343 pos = strchr(text, '\t');
4344 if (!pos)
4345 return TRUE;
4346 text = pos + 1;
4347 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4348 text += strlen(opt_path);
4349 pos = strchr(text, '/');
4350 if (pos)
4351 *pos = 0;
4353 for (i = 1; i < view->lines; i++) {
4354 struct line *line = &view->line[i];
4355 struct tree_entry *entry = line->data;
4357 annotated += !!entry->author;
4358 if (entry->author || strcmp(entry->name, text))
4359 continue;
4361 entry->author = state->author_name;
4362 entry->time = state->author_time;
4363 line->dirty = 1;
4364 break;
4367 if (annotated == view->lines)
4368 io_kill(view->pipe);
4370 return TRUE;
4373 static bool
4374 tree_read(struct view *view, char *text)
4376 struct tree_state *state = view->private;
4377 struct tree_entry *data;
4378 struct line *entry, *line;
4379 enum line_type type;
4380 size_t textlen = text ? strlen(text) : 0;
4381 char *path = text + SIZEOF_TREE_ATTR;
4383 if (state->read_date || !text)
4384 return tree_read_date(view, text, state);
4386 if (textlen <= SIZEOF_TREE_ATTR)
4387 return FALSE;
4388 if (view->lines == 0 &&
4389 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4390 return FALSE;
4392 /* Strip the path part ... */
4393 if (*opt_path) {
4394 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4395 size_t striplen = strlen(opt_path);
4397 if (pathlen > striplen)
4398 memmove(path, path + striplen,
4399 pathlen - striplen + 1);
4401 /* Insert "link" to parent directory. */
4402 if (view->lines == 1 &&
4403 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4404 return FALSE;
4407 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4408 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4409 if (!entry)
4410 return FALSE;
4411 data = entry->data;
4413 /* Skip "Directory ..." and ".." line. */
4414 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4415 if (tree_compare_entry(line, entry) <= 0)
4416 continue;
4418 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4420 line->data = data;
4421 line->type = type;
4422 for (; line <= entry; line++)
4423 line->dirty = line->cleareol = 1;
4424 return TRUE;
4427 if (tree_lineno > view->lineno) {
4428 view->lineno = tree_lineno;
4429 tree_lineno = 0;
4432 return TRUE;
4435 static bool
4436 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4438 struct tree_entry *entry = line->data;
4440 if (line->type == LINE_TREE_HEAD) {
4441 if (draw_text(view, line->type, "Directory path /"))
4442 return TRUE;
4443 } else {
4444 if (draw_mode(view, entry->mode))
4445 return TRUE;
4447 if (draw_author(view, entry->author))
4448 return TRUE;
4450 if (draw_date(view, &entry->time))
4451 return TRUE;
4454 draw_text(view, line->type, entry->name);
4455 return TRUE;
4458 static void
4459 open_blob_editor(const char *id)
4461 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4462 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4463 int fd = mkstemp(file);
4465 if (fd == -1)
4466 report("Failed to create temporary file");
4467 else if (!io_run_append(blob_argv, fd))
4468 report("Failed to save blob data to file");
4469 else
4470 open_editor(file);
4471 if (fd != -1)
4472 unlink(file);
4475 static enum request
4476 tree_request(struct view *view, enum request request, struct line *line)
4478 enum open_flags flags;
4479 struct tree_entry *entry = line->data;
4481 switch (request) {
4482 case REQ_VIEW_BLAME:
4483 if (line->type != LINE_TREE_FILE) {
4484 report("Blame only supported for files");
4485 return REQ_NONE;
4488 string_copy(opt_ref, view->vid);
4489 return request;
4491 case REQ_EDIT:
4492 if (line->type != LINE_TREE_FILE) {
4493 report("Edit only supported for files");
4494 } else if (!is_head_commit(view->vid)) {
4495 open_blob_editor(entry->id);
4496 } else {
4497 open_editor(opt_file);
4499 return REQ_NONE;
4501 case REQ_TOGGLE_SORT_FIELD:
4502 case REQ_TOGGLE_SORT_ORDER:
4503 sort_view(view, request, &tree_sort_state, tree_compare);
4504 return REQ_NONE;
4506 case REQ_PARENT:
4507 if (!*opt_path) {
4508 /* quit view if at top of tree */
4509 return REQ_VIEW_CLOSE;
4511 /* fake 'cd ..' */
4512 line = &view->line[1];
4513 break;
4515 case REQ_ENTER:
4516 break;
4518 default:
4519 return request;
4522 /* Cleanup the stack if the tree view is at a different tree. */
4523 while (!*opt_path && tree_stack)
4524 pop_tree_stack_entry();
4526 switch (line->type) {
4527 case LINE_TREE_DIR:
4528 /* Depending on whether it is a subdirectory or parent link
4529 * mangle the path buffer. */
4530 if (line == &view->line[1] && *opt_path) {
4531 pop_tree_stack_entry();
4533 } else {
4534 const char *basename = tree_path(line);
4536 push_tree_stack_entry(basename, view->lineno);
4539 /* Trees and subtrees share the same ID, so they are not not
4540 * unique like blobs. */
4541 flags = OPEN_RELOAD;
4542 request = REQ_VIEW_TREE;
4543 break;
4545 case LINE_TREE_FILE:
4546 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4547 request = REQ_VIEW_BLOB;
4548 break;
4550 default:
4551 return REQ_NONE;
4554 open_view(view, request, flags);
4555 if (request == REQ_VIEW_TREE)
4556 view->lineno = tree_lineno;
4558 return REQ_NONE;
4561 static bool
4562 tree_grep(struct view *view, struct line *line)
4564 struct tree_entry *entry = line->data;
4565 const char *text[] = {
4566 entry->name,
4567 mkauthor(entry->author, opt_author_cols, opt_author),
4568 mkdate(&entry->time, opt_date),
4569 NULL
4572 return grep_text(view, text);
4575 static void
4576 tree_select(struct view *view, struct line *line)
4578 struct tree_entry *entry = line->data;
4580 if (line->type == LINE_TREE_FILE) {
4581 string_copy_rev(ref_blob, entry->id);
4582 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4584 } else if (line->type != LINE_TREE_DIR) {
4585 return;
4588 string_copy_rev(view->ref, entry->id);
4591 static bool
4592 tree_open(struct view *view, enum open_flags flags)
4594 static const char *tree_argv[] = {
4595 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4598 if (view->lines == 0 && opt_prefix[0]) {
4599 char *pos = opt_prefix;
4601 while (pos && *pos) {
4602 char *end = strchr(pos, '/');
4604 if (end)
4605 *end = 0;
4606 push_tree_stack_entry(pos, 0);
4607 pos = end;
4608 if (end) {
4609 *end = '/';
4610 pos++;
4614 } else if (strcmp(view->vid, view->id)) {
4615 opt_path[0] = 0;
4618 return begin_update(view, opt_cdup, tree_argv, flags);
4621 static struct view_ops tree_ops = {
4622 "file",
4623 sizeof(struct tree_state),
4624 tree_open,
4625 tree_read,
4626 tree_draw,
4627 tree_request,
4628 tree_grep,
4629 tree_select,
4632 static bool
4633 blob_open(struct view *view, enum open_flags flags)
4635 static const char *blob_argv[] = {
4636 "git", "cat-file", "blob", "%(blob)", NULL
4639 return begin_update(view, NULL, blob_argv, flags);
4642 static bool
4643 blob_read(struct view *view, char *line)
4645 if (!line)
4646 return TRUE;
4647 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4650 static enum request
4651 blob_request(struct view *view, enum request request, struct line *line)
4653 switch (request) {
4654 case REQ_EDIT:
4655 open_blob_editor(view->vid);
4656 return REQ_NONE;
4657 default:
4658 return pager_request(view, request, line);
4662 static struct view_ops blob_ops = {
4663 "line",
4665 blob_open,
4666 blob_read,
4667 pager_draw,
4668 blob_request,
4669 pager_grep,
4670 pager_select,
4674 * Blame backend
4676 * Loading the blame view is a two phase job:
4678 * 1. File content is read either using opt_file from the
4679 * filesystem or using git-cat-file.
4680 * 2. Then blame information is incrementally added by
4681 * reading output from git-blame.
4684 struct blame {
4685 struct blame_commit *commit;
4686 unsigned long lineno;
4687 char text[1];
4690 struct blame_state {
4691 struct blame_commit *commit;
4692 int blamed;
4693 bool done_reading;
4694 bool auto_filename_display;
4697 static bool
4698 blame_detect_filename_display(struct view *view)
4700 bool show_filenames = FALSE;
4701 const char *filename = NULL;
4702 int i;
4704 if (opt_blame_argv) {
4705 for (i = 0; opt_blame_argv[i]; i++) {
4706 if (prefixcmp(opt_blame_argv[i], "-C"))
4707 continue;
4709 show_filenames = TRUE;
4713 for (i = 0; i < view->lines; i++) {
4714 struct blame *blame = view->line[i].data;
4716 if (blame->commit && blame->commit->id[0]) {
4717 if (!filename)
4718 filename = blame->commit->filename;
4719 else if (strcmp(filename, blame->commit->filename))
4720 show_filenames = TRUE;
4724 return show_filenames;
4727 static bool
4728 blame_open(struct view *view, enum open_flags flags)
4730 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4731 char path[SIZEOF_STR];
4732 size_t i;
4734 if (!view->prev && *opt_prefix) {
4735 string_copy(path, opt_file);
4736 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4737 return FALSE;
4740 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4741 const char *blame_cat_file_argv[] = {
4742 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4745 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4746 return FALSE;
4749 /* First pass: remove multiple references to the same commit. */
4750 for (i = 0; i < view->lines; i++) {
4751 struct blame *blame = view->line[i].data;
4753 if (blame->commit && blame->commit->id[0])
4754 blame->commit->id[0] = 0;
4755 else
4756 blame->commit = NULL;
4759 /* Second pass: free existing references. */
4760 for (i = 0; i < view->lines; i++) {
4761 struct blame *blame = view->line[i].data;
4763 if (blame->commit)
4764 free(blame->commit);
4767 string_format(view->vid, "%s", opt_file);
4768 string_format(view->ref, "%s ...", opt_file);
4770 return TRUE;
4773 static struct blame_commit *
4774 get_blame_commit(struct view *view, const char *id)
4776 size_t i;
4778 for (i = 0; i < view->lines; i++) {
4779 struct blame *blame = view->line[i].data;
4781 if (!blame->commit)
4782 continue;
4784 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4785 return blame->commit;
4789 struct blame_commit *commit = calloc(1, sizeof(*commit));
4791 if (commit)
4792 string_ncopy(commit->id, id, SIZEOF_REV);
4793 return commit;
4797 static struct blame_commit *
4798 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
4800 struct blame_header header;
4801 struct blame_commit *commit;
4802 struct blame *blame;
4804 if (!parse_blame_header(&header, text, view->lines))
4805 return NULL;
4807 commit = get_blame_commit(view, text);
4808 if (!commit)
4809 return NULL;
4811 state->blamed += header.group;
4812 while (header.group--) {
4813 struct line *line = &view->line[header.lineno + header.group - 1];
4815 blame = line->data;
4816 blame->commit = commit;
4817 blame->lineno = header.orig_lineno + header.group - 1;
4818 line->dirty = 1;
4821 return commit;
4824 static bool
4825 blame_read_file(struct view *view, const char *line, struct blame_state *state)
4827 if (!line) {
4828 const char *blame_argv[] = {
4829 "git", "blame", "%(blameargs)", "--incremental",
4830 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4833 if (view->lines == 0 && !view->prev)
4834 die("No blame exist for %s", view->vid);
4836 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
4837 report("Failed to load blame data");
4838 return TRUE;
4841 if (opt_goto_line > 0) {
4842 select_view_line(view, opt_goto_line);
4843 opt_goto_line = 0;
4846 state->done_reading = TRUE;
4847 return FALSE;
4849 } else {
4850 size_t linelen = strlen(line);
4851 struct blame *blame = malloc(sizeof(*blame) + linelen);
4853 if (!blame)
4854 return FALSE;
4856 blame->commit = NULL;
4857 strncpy(blame->text, line, linelen);
4858 blame->text[linelen] = 0;
4859 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4863 static bool
4864 blame_read(struct view *view, char *line)
4866 struct blame_state *state = view->private;
4868 if (!state->done_reading)
4869 return blame_read_file(view, line, state);
4871 if (!line) {
4872 state->auto_filename_display = blame_detect_filename_display(view);
4873 string_format(view->ref, "%s", view->vid);
4874 if (view_is_displayed(view)) {
4875 update_view_title(view);
4876 redraw_view_from(view, 0);
4878 return TRUE;
4881 if (!state->commit) {
4882 state->commit = read_blame_commit(view, line, state);
4883 string_format(view->ref, "%s %2d%%", view->vid,
4884 view->lines ? state->blamed * 100 / view->lines : 0);
4886 } else if (parse_blame_info(state->commit, line)) {
4887 state->commit = NULL;
4890 return TRUE;
4893 static bool
4894 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4896 struct blame_state *state = view->private;
4897 struct blame *blame = line->data;
4898 struct time *time = NULL;
4899 const char *id = NULL, *author = NULL, *filename = NULL;
4900 enum line_type id_type = LINE_BLAME_ID;
4901 static const enum line_type blame_colors[] = {
4902 LINE_PALETTE_0,
4903 LINE_PALETTE_1,
4904 LINE_PALETTE_2,
4905 LINE_PALETTE_3,
4906 LINE_PALETTE_4,
4907 LINE_PALETTE_5,
4908 LINE_PALETTE_6,
4911 #define BLAME_COLOR(i) \
4912 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
4914 if (blame->commit && *blame->commit->filename) {
4915 id = blame->commit->id;
4916 author = blame->commit->author;
4917 filename = blame->commit->filename;
4918 time = &blame->commit->time;
4919 id_type = BLAME_COLOR((long) blame->commit);
4922 if (draw_date(view, time))
4923 return TRUE;
4925 if (draw_author(view, author))
4926 return TRUE;
4928 if (draw_filename(view, filename, state->auto_filename_display))
4929 return TRUE;
4931 if (draw_field(view, id_type, id, ID_COLS, FALSE))
4932 return TRUE;
4934 if (draw_lineno(view, lineno))
4935 return TRUE;
4937 draw_text(view, LINE_DEFAULT, blame->text);
4938 return TRUE;
4941 static bool
4942 check_blame_commit(struct blame *blame, bool check_null_id)
4944 if (!blame->commit)
4945 report("Commit data not loaded yet");
4946 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4947 report("No commit exist for the selected line");
4948 else
4949 return TRUE;
4950 return FALSE;
4953 static void
4954 setup_blame_parent_line(struct view *view, struct blame *blame)
4956 char from[SIZEOF_REF + SIZEOF_STR];
4957 char to[SIZEOF_REF + SIZEOF_STR];
4958 const char *diff_tree_argv[] = {
4959 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4960 "-U0", from, to, "--", NULL
4962 struct io io;
4963 int parent_lineno = -1;
4964 int blamed_lineno = -1;
4965 char *line;
4967 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4968 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4969 !io_run(&io, IO_RD, NULL, diff_tree_argv))
4970 return;
4972 while ((line = io_get(&io, '\n', TRUE))) {
4973 if (*line == '@') {
4974 char *pos = strchr(line, '+');
4976 parent_lineno = atoi(line + 4);
4977 if (pos)
4978 blamed_lineno = atoi(pos + 1);
4980 } else if (*line == '+' && parent_lineno != -1) {
4981 if (blame->lineno == blamed_lineno - 1 &&
4982 !strcmp(blame->text, line + 1)) {
4983 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4984 break;
4986 blamed_lineno++;
4990 io_done(&io);
4993 static enum request
4994 blame_request(struct view *view, enum request request, struct line *line)
4996 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4997 struct blame *blame = line->data;
4999 switch (request) {
5000 case REQ_VIEW_BLAME:
5001 if (check_blame_commit(blame, TRUE)) {
5002 string_copy(opt_ref, blame->commit->id);
5003 string_copy(opt_file, blame->commit->filename);
5004 if (blame->lineno)
5005 view->lineno = blame->lineno;
5006 reload_view(view);
5008 break;
5010 case REQ_PARENT:
5011 if (!check_blame_commit(blame, TRUE))
5012 break;
5013 if (!*blame->commit->parent_id) {
5014 report("The selected commit has no parents");
5015 } else {
5016 string_copy_rev(opt_ref, blame->commit->parent_id);
5017 string_copy(opt_file, blame->commit->parent_filename);
5018 setup_blame_parent_line(view, blame);
5019 opt_goto_line = blame->lineno;
5020 reload_view(view);
5022 break;
5024 case REQ_ENTER:
5025 if (!check_blame_commit(blame, FALSE))
5026 break;
5028 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5029 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5030 break;
5032 if (!strcmp(blame->commit->id, NULL_ID)) {
5033 struct view *diff = VIEW(REQ_VIEW_DIFF);
5034 const char *diff_index_argv[] = {
5035 "git", "diff-index", "--root", "--patch-with-stat",
5036 "-C", "-M", opt_diff_context_arg,
5037 "HEAD", "--", view->vid, NULL
5040 if (!*blame->commit->parent_id) {
5041 diff_index_argv[1] = "diff";
5042 diff_index_argv[2] = "--no-color";
5043 diff_index_argv[7] = "--";
5044 diff_index_argv[8] = "/dev/null";
5047 open_argv(view, diff, diff_index_argv, NULL, flags);
5048 if (diff->pipe)
5049 string_copy_rev(diff->ref, NULL_ID);
5050 } else {
5051 open_view(view, REQ_VIEW_DIFF, flags);
5053 break;
5055 default:
5056 return request;
5059 return REQ_NONE;
5062 static bool
5063 blame_grep(struct view *view, struct line *line)
5065 struct blame *blame = line->data;
5066 struct blame_commit *commit = blame->commit;
5067 const char *text[] = {
5068 blame->text,
5069 commit ? commit->title : "",
5070 commit ? commit->id : "",
5071 commit && opt_author ? commit->author : "",
5072 commit ? mkdate(&commit->time, opt_date) : "",
5073 NULL
5076 return grep_text(view, text);
5079 static void
5080 blame_select(struct view *view, struct line *line)
5082 struct blame *blame = line->data;
5083 struct blame_commit *commit = blame->commit;
5085 if (!commit)
5086 return;
5088 if (!strcmp(commit->id, NULL_ID))
5089 string_ncopy(ref_commit, "HEAD", 4);
5090 else
5091 string_copy_rev(ref_commit, commit->id);
5094 static struct view_ops blame_ops = {
5095 "line",
5096 sizeof(struct blame_state),
5097 blame_open,
5098 blame_read,
5099 blame_draw,
5100 blame_request,
5101 blame_grep,
5102 blame_select,
5106 * Branch backend
5109 struct branch {
5110 const char *author; /* Author of the last commit. */
5111 struct time time; /* Date of the last activity. */
5112 const struct ref *ref; /* Name and commit ID information. */
5115 static const struct ref branch_all;
5117 static const enum sort_field branch_sort_fields[] = {
5118 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5120 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5122 struct branch_state {
5123 char id[SIZEOF_REV];
5126 static int
5127 branch_compare(const void *l1, const void *l2)
5129 const struct branch *branch1 = ((const struct line *) l1)->data;
5130 const struct branch *branch2 = ((const struct line *) l2)->data;
5132 if (branch1->ref == &branch_all)
5133 return -1;
5134 else if (branch2->ref == &branch_all)
5135 return 1;
5137 switch (get_sort_field(branch_sort_state)) {
5138 case ORDERBY_DATE:
5139 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5141 case ORDERBY_AUTHOR:
5142 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5144 case ORDERBY_NAME:
5145 default:
5146 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5150 static bool
5151 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5153 struct branch *branch = line->data;
5154 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5156 if (draw_date(view, &branch->time))
5157 return TRUE;
5159 if (draw_author(view, branch->author))
5160 return TRUE;
5162 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
5163 return TRUE;
5166 static enum request
5167 branch_request(struct view *view, enum request request, struct line *line)
5169 struct branch *branch = line->data;
5171 switch (request) {
5172 case REQ_REFRESH:
5173 load_refs();
5174 refresh_view(view);
5175 return REQ_NONE;
5177 case REQ_TOGGLE_SORT_FIELD:
5178 case REQ_TOGGLE_SORT_ORDER:
5179 sort_view(view, request, &branch_sort_state, branch_compare);
5180 return REQ_NONE;
5182 case REQ_ENTER:
5184 const struct ref *ref = branch->ref;
5185 const char *all_branches_argv[] = {
5186 "git", "log", "--no-color", "--pretty=raw", "--parents",
5187 "--topo-order",
5188 ref == &branch_all ? "--all" : ref->name, NULL
5190 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5192 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5193 return REQ_NONE;
5195 case REQ_JUMP_COMMIT:
5197 int lineno;
5199 for (lineno = 0; lineno < view->lines; lineno++) {
5200 struct branch *branch = view->line[lineno].data;
5202 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5203 select_view_line(view, lineno);
5204 report("");
5205 return REQ_NONE;
5209 default:
5210 return request;
5214 static bool
5215 branch_read(struct view *view, char *line)
5217 struct branch_state *state = view->private;
5218 struct branch *reference;
5219 size_t i;
5221 if (!line)
5222 return TRUE;
5224 switch (get_line_type(line)) {
5225 case LINE_COMMIT:
5226 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5227 return TRUE;
5229 case LINE_AUTHOR:
5230 for (i = 0, reference = NULL; i < view->lines; i++) {
5231 struct branch *branch = view->line[i].data;
5233 if (strcmp(branch->ref->id, state->id))
5234 continue;
5236 view->line[i].dirty = TRUE;
5237 if (reference) {
5238 branch->author = reference->author;
5239 branch->time = reference->time;
5240 continue;
5243 parse_author_line(line + STRING_SIZE("author "),
5244 &branch->author, &branch->time);
5245 reference = branch;
5247 return TRUE;
5249 default:
5250 return TRUE;
5255 static bool
5256 branch_open_visitor(void *data, const struct ref *ref)
5258 struct view *view = data;
5259 struct branch *branch;
5261 if (ref->tag || ref->ltag)
5262 return TRUE;
5264 branch = calloc(1, sizeof(*branch));
5265 if (!branch)
5266 return FALSE;
5268 branch->ref = ref;
5269 return !!add_line_data(view, branch, LINE_DEFAULT);
5272 static bool
5273 branch_open(struct view *view, enum open_flags flags)
5275 const char *branch_log[] = {
5276 "git", "log", "--no-color", "--pretty=raw",
5277 "--simplify-by-decoration", "--all", NULL
5280 if (!begin_update(view, NULL, branch_log, flags)) {
5281 report("Failed to load branch data");
5282 return TRUE;
5285 branch_open_visitor(view, &branch_all);
5286 foreach_ref(branch_open_visitor, view);
5287 view->p_restore = TRUE;
5289 return TRUE;
5292 static bool
5293 branch_grep(struct view *view, struct line *line)
5295 struct branch *branch = line->data;
5296 const char *text[] = {
5297 branch->ref->name,
5298 mkauthor(branch->author, opt_author_cols, opt_author),
5299 NULL
5302 return grep_text(view, text);
5305 static void
5306 branch_select(struct view *view, struct line *line)
5308 struct branch *branch = line->data;
5310 string_copy_rev(view->ref, branch->ref->id);
5311 string_copy_rev(ref_commit, branch->ref->id);
5312 string_copy_rev(ref_head, branch->ref->id);
5313 string_copy_rev(ref_branch, branch->ref->name);
5316 static struct view_ops branch_ops = {
5317 "branch",
5318 sizeof(struct branch_state),
5319 branch_open,
5320 branch_read,
5321 branch_draw,
5322 branch_request,
5323 branch_grep,
5324 branch_select,
5328 * Status backend
5331 struct status {
5332 char status;
5333 struct {
5334 mode_t mode;
5335 char rev[SIZEOF_REV];
5336 char name[SIZEOF_STR];
5337 } old;
5338 struct {
5339 mode_t mode;
5340 char rev[SIZEOF_REV];
5341 char name[SIZEOF_STR];
5342 } new;
5345 static char status_onbranch[SIZEOF_STR];
5346 static struct status stage_status;
5347 static enum line_type stage_line_type;
5349 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5351 /* This should work even for the "On branch" line. */
5352 static inline bool
5353 status_has_none(struct view *view, struct line *line)
5355 return line < view->line + view->lines && !line[1].data;
5358 /* Get fields from the diff line:
5359 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5361 static inline bool
5362 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5364 const char *old_mode = buf + 1;
5365 const char *new_mode = buf + 8;
5366 const char *old_rev = buf + 15;
5367 const char *new_rev = buf + 56;
5368 const char *status = buf + 97;
5370 if (bufsize < 98 ||
5371 old_mode[-1] != ':' ||
5372 new_mode[-1] != ' ' ||
5373 old_rev[-1] != ' ' ||
5374 new_rev[-1] != ' ' ||
5375 status[-1] != ' ')
5376 return FALSE;
5378 file->status = *status;
5380 string_copy_rev(file->old.rev, old_rev);
5381 string_copy_rev(file->new.rev, new_rev);
5383 file->old.mode = strtoul(old_mode, NULL, 8);
5384 file->new.mode = strtoul(new_mode, NULL, 8);
5386 file->old.name[0] = file->new.name[0] = 0;
5388 return TRUE;
5391 static bool
5392 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5394 struct status *unmerged = NULL;
5395 char *buf;
5396 struct io io;
5398 if (!io_run(&io, IO_RD, opt_cdup, argv))
5399 return FALSE;
5401 add_line_data(view, NULL, type);
5403 while ((buf = io_get(&io, 0, TRUE))) {
5404 struct status *file = unmerged;
5406 if (!file) {
5407 file = calloc(1, sizeof(*file));
5408 if (!file || !add_line_data(view, file, type))
5409 goto error_out;
5412 /* Parse diff info part. */
5413 if (status) {
5414 file->status = status;
5415 if (status == 'A')
5416 string_copy(file->old.rev, NULL_ID);
5418 } else if (!file->status || file == unmerged) {
5419 if (!status_get_diff(file, buf, strlen(buf)))
5420 goto error_out;
5422 buf = io_get(&io, 0, TRUE);
5423 if (!buf)
5424 break;
5426 /* Collapse all modified entries that follow an
5427 * associated unmerged entry. */
5428 if (unmerged == file) {
5429 unmerged->status = 'U';
5430 unmerged = NULL;
5431 } else if (file->status == 'U') {
5432 unmerged = file;
5436 /* Grab the old name for rename/copy. */
5437 if (!*file->old.name &&
5438 (file->status == 'R' || file->status == 'C')) {
5439 string_ncopy(file->old.name, buf, strlen(buf));
5441 buf = io_get(&io, 0, TRUE);
5442 if (!buf)
5443 break;
5446 /* git-ls-files just delivers a NUL separated list of
5447 * file names similar to the second half of the
5448 * git-diff-* output. */
5449 string_ncopy(file->new.name, buf, strlen(buf));
5450 if (!*file->old.name)
5451 string_copy(file->old.name, file->new.name);
5452 file = NULL;
5455 if (io_error(&io)) {
5456 error_out:
5457 io_done(&io);
5458 return FALSE;
5461 if (!view->line[view->lines - 1].data)
5462 add_line_data(view, NULL, LINE_STAT_NONE);
5464 io_done(&io);
5465 return TRUE;
5468 /* Don't show unmerged entries in the staged section. */
5469 static const char *status_diff_index_argv[] = {
5470 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
5471 "--cached", "-M", "HEAD", NULL
5474 static const char *status_diff_files_argv[] = {
5475 "git", "diff-files", "-z", NULL
5478 static const char *status_list_other_argv[] = {
5479 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5482 static const char *status_list_no_head_argv[] = {
5483 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5486 static const char *update_index_argv[] = {
5487 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5490 /* Restore the previous line number to stay in the context or select a
5491 * line with something that can be updated. */
5492 static void
5493 status_restore(struct view *view)
5495 if (view->p_lineno >= view->lines)
5496 view->p_lineno = view->lines - 1;
5497 while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
5498 view->p_lineno++;
5499 while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
5500 view->p_lineno--;
5502 /* If the above fails, always skip the "On branch" line. */
5503 if (view->p_lineno < view->lines)
5504 view->lineno = view->p_lineno;
5505 else
5506 view->lineno = 1;
5508 if (view->lineno < view->offset)
5509 view->offset = view->lineno;
5510 else if (view->offset + view->height <= view->lineno)
5511 view->offset = view->lineno - view->height + 1;
5513 view->p_restore = FALSE;
5516 static void
5517 status_update_onbranch(void)
5519 static const char *paths[][2] = {
5520 { "rebase-apply/rebasing", "Rebasing" },
5521 { "rebase-apply/applying", "Applying mailbox" },
5522 { "rebase-apply/", "Rebasing mailbox" },
5523 { "rebase-merge/interactive", "Interactive rebase" },
5524 { "rebase-merge/", "Rebase merge" },
5525 { "MERGE_HEAD", "Merging" },
5526 { "BISECT_LOG", "Bisecting" },
5527 { "HEAD", "On branch" },
5529 char buf[SIZEOF_STR];
5530 struct stat stat;
5531 int i;
5533 if (is_initial_commit()) {
5534 string_copy(status_onbranch, "Initial commit");
5535 return;
5538 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5539 char *head = opt_head;
5541 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5542 lstat(buf, &stat) < 0)
5543 continue;
5545 if (!*opt_head) {
5546 struct io io;
5548 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5549 io_read_buf(&io, buf, sizeof(buf))) {
5550 head = buf;
5551 if (!prefixcmp(head, "refs/heads/"))
5552 head += STRING_SIZE("refs/heads/");
5556 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5557 string_copy(status_onbranch, opt_head);
5558 return;
5561 string_copy(status_onbranch, "Not currently on any branch");
5564 /* First parse staged info using git-diff-index(1), then parse unstaged
5565 * info using git-diff-files(1), and finally untracked files using
5566 * git-ls-files(1). */
5567 static bool
5568 status_open(struct view *view, enum open_flags flags)
5570 reset_view(view);
5572 add_line_data(view, NULL, LINE_STAT_HEAD);
5573 status_update_onbranch();
5575 io_run_bg(update_index_argv);
5577 if (is_initial_commit()) {
5578 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5579 return FALSE;
5580 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5581 return FALSE;
5584 if (!opt_untracked_dirs_content)
5585 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5587 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5588 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5589 return FALSE;
5591 /* Restore the exact position or use the specialized restore
5592 * mode? */
5593 if (!view->p_restore)
5594 status_restore(view);
5595 return TRUE;
5598 static bool
5599 status_draw(struct view *view, struct line *line, unsigned int lineno)
5601 struct status *status = line->data;
5602 enum line_type type;
5603 const char *text;
5605 if (!status) {
5606 switch (line->type) {
5607 case LINE_STAT_STAGED:
5608 type = LINE_STAT_SECTION;
5609 text = "Changes to be committed:";
5610 break;
5612 case LINE_STAT_UNSTAGED:
5613 type = LINE_STAT_SECTION;
5614 text = "Changed but not updated:";
5615 break;
5617 case LINE_STAT_UNTRACKED:
5618 type = LINE_STAT_SECTION;
5619 text = "Untracked files:";
5620 break;
5622 case LINE_STAT_NONE:
5623 type = LINE_DEFAULT;
5624 text = " (no files)";
5625 break;
5627 case LINE_STAT_HEAD:
5628 type = LINE_STAT_HEAD;
5629 text = status_onbranch;
5630 break;
5632 default:
5633 return FALSE;
5635 } else {
5636 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5638 buf[0] = status->status;
5639 if (draw_text(view, line->type, buf))
5640 return TRUE;
5641 type = LINE_DEFAULT;
5642 text = status->new.name;
5645 draw_text(view, type, text);
5646 return TRUE;
5649 static enum request
5650 status_enter(struct view *view, struct line *line)
5652 struct status *status = line->data;
5653 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5655 if (line->type == LINE_STAT_NONE ||
5656 (!status && line[1].type == LINE_STAT_NONE)) {
5657 report("No file to diff");
5658 return REQ_NONE;
5661 switch (line->type) {
5662 case LINE_STAT_STAGED:
5663 case LINE_STAT_UNSTAGED:
5664 break;
5666 case LINE_STAT_UNTRACKED:
5667 if (!status) {
5668 report("No file to show");
5669 return REQ_NONE;
5672 if (!suffixcmp(status->new.name, -1, "/")) {
5673 report("Cannot display a directory");
5674 return REQ_NONE;
5676 break;
5678 case LINE_STAT_HEAD:
5679 return REQ_NONE;
5681 default:
5682 die("line type %d not handled in switch", line->type);
5685 if (status) {
5686 stage_status = *status;
5687 } else {
5688 memset(&stage_status, 0, sizeof(stage_status));
5691 stage_line_type = line->type;
5693 open_view(view, REQ_VIEW_STAGE, flags);
5694 return REQ_NONE;
5697 static bool
5698 status_exists(struct view *view, struct status *status, enum line_type type)
5700 unsigned long lineno;
5702 for (lineno = 0; lineno < view->lines; lineno++) {
5703 struct line *line = &view->line[lineno];
5704 struct status *pos = line->data;
5706 if (line->type != type)
5707 continue;
5708 if (!pos && (!status || !status->status) && line[1].data) {
5709 select_view_line(view, lineno);
5710 return TRUE;
5712 if (pos && !strcmp(status->new.name, pos->new.name)) {
5713 select_view_line(view, lineno);
5714 return TRUE;
5718 return FALSE;
5722 static bool
5723 status_update_prepare(struct io *io, enum line_type type)
5725 const char *staged_argv[] = {
5726 "git", "update-index", "-z", "--index-info", NULL
5728 const char *others_argv[] = {
5729 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5732 switch (type) {
5733 case LINE_STAT_STAGED:
5734 return io_run(io, IO_WR, opt_cdup, staged_argv);
5736 case LINE_STAT_UNSTAGED:
5737 case LINE_STAT_UNTRACKED:
5738 return io_run(io, IO_WR, opt_cdup, others_argv);
5740 default:
5741 die("line type %d not handled in switch", type);
5742 return FALSE;
5746 static bool
5747 status_update_write(struct io *io, struct status *status, enum line_type type)
5749 switch (type) {
5750 case LINE_STAT_STAGED:
5751 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
5752 status->old.rev, status->old.name, 0);
5754 case LINE_STAT_UNSTAGED:
5755 case LINE_STAT_UNTRACKED:
5756 return io_printf(io, "%s%c", status->new.name, 0);
5758 default:
5759 die("line type %d not handled in switch", type);
5760 return FALSE;
5764 static bool
5765 status_update_file(struct status *status, enum line_type type)
5767 struct io io;
5768 bool result;
5770 if (!status_update_prepare(&io, type))
5771 return FALSE;
5773 result = status_update_write(&io, status, type);
5774 return io_done(&io) && result;
5777 static bool
5778 status_update_files(struct view *view, struct line *line)
5780 char buf[sizeof(view->ref)];
5781 struct io io;
5782 bool result = TRUE;
5783 struct line *pos = view->line + view->lines;
5784 int files = 0;
5785 int file, done;
5786 int cursor_y = -1, cursor_x = -1;
5788 if (!status_update_prepare(&io, line->type))
5789 return FALSE;
5791 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5792 files++;
5794 string_copy(buf, view->ref);
5795 getsyx(cursor_y, cursor_x);
5796 for (file = 0, done = 5; result && file < files; line++, file++) {
5797 int almost_done = file * 100 / files;
5799 if (almost_done > done) {
5800 done = almost_done;
5801 string_format(view->ref, "updating file %u of %u (%d%% done)",
5802 file, files, done);
5803 update_view_title(view);
5804 setsyx(cursor_y, cursor_x);
5805 doupdate();
5807 result = status_update_write(&io, line->data, line->type);
5809 string_copy(view->ref, buf);
5811 return io_done(&io) && result;
5814 static bool
5815 status_update(struct view *view)
5817 struct line *line = &view->line[view->lineno];
5819 assert(view->lines);
5821 if (!line->data) {
5822 /* This should work even for the "On branch" line. */
5823 if (line < view->line + view->lines && !line[1].data) {
5824 report("Nothing to update");
5825 return FALSE;
5828 if (!status_update_files(view, line + 1)) {
5829 report("Failed to update file status");
5830 return FALSE;
5833 } else if (!status_update_file(line->data, line->type)) {
5834 report("Failed to update file status");
5835 return FALSE;
5838 return TRUE;
5841 static bool
5842 status_revert(struct status *status, enum line_type type, bool has_none)
5844 if (!status || type != LINE_STAT_UNSTAGED) {
5845 if (type == LINE_STAT_STAGED) {
5846 report("Cannot revert changes to staged files");
5847 } else if (type == LINE_STAT_UNTRACKED) {
5848 report("Cannot revert changes to untracked files");
5849 } else if (has_none) {
5850 report("Nothing to revert");
5851 } else {
5852 report("Cannot revert changes to multiple files");
5855 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5856 char mode[10] = "100644";
5857 const char *reset_argv[] = {
5858 "git", "update-index", "--cacheinfo", mode,
5859 status->old.rev, status->old.name, NULL
5861 const char *checkout_argv[] = {
5862 "git", "checkout", "--", status->old.name, NULL
5865 if (status->status == 'U') {
5866 string_format(mode, "%5o", status->old.mode);
5868 if (status->old.mode == 0 && status->new.mode == 0) {
5869 reset_argv[2] = "--force-remove";
5870 reset_argv[3] = status->old.name;
5871 reset_argv[4] = NULL;
5874 if (!io_run_fg(reset_argv, opt_cdup))
5875 return FALSE;
5876 if (status->old.mode == 0 && status->new.mode == 0)
5877 return TRUE;
5880 return io_run_fg(checkout_argv, opt_cdup);
5883 return FALSE;
5886 static enum request
5887 status_request(struct view *view, enum request request, struct line *line)
5889 struct status *status = line->data;
5891 switch (request) {
5892 case REQ_STATUS_UPDATE:
5893 if (!status_update(view))
5894 return REQ_NONE;
5895 break;
5897 case REQ_STATUS_REVERT:
5898 if (!status_revert(status, line->type, status_has_none(view, line)))
5899 return REQ_NONE;
5900 break;
5902 case REQ_STATUS_MERGE:
5903 if (!status || status->status != 'U') {
5904 report("Merging only possible for files with unmerged status ('U').");
5905 return REQ_NONE;
5907 open_mergetool(status->new.name);
5908 break;
5910 case REQ_EDIT:
5911 if (!status)
5912 return request;
5913 if (status->status == 'D') {
5914 report("File has been deleted.");
5915 return REQ_NONE;
5918 open_editor(status->new.name);
5919 break;
5921 case REQ_VIEW_BLAME:
5922 if (status)
5923 opt_ref[0] = 0;
5924 return request;
5926 case REQ_ENTER:
5927 /* After returning the status view has been split to
5928 * show the stage view. No further reloading is
5929 * necessary. */
5930 return status_enter(view, line);
5932 case REQ_REFRESH:
5933 /* Simply reload the view. */
5934 break;
5936 default:
5937 return request;
5940 refresh_view(view);
5942 return REQ_NONE;
5945 static void
5946 status_select(struct view *view, struct line *line)
5948 struct status *status = line->data;
5949 char file[SIZEOF_STR] = "all files";
5950 const char *text;
5951 const char *key;
5953 if (status && !string_format(file, "'%s'", status->new.name))
5954 return;
5956 if (!status && line[1].type == LINE_STAT_NONE)
5957 line++;
5959 switch (line->type) {
5960 case LINE_STAT_STAGED:
5961 text = "Press %s to unstage %s for commit";
5962 break;
5964 case LINE_STAT_UNSTAGED:
5965 text = "Press %s to stage %s for commit";
5966 break;
5968 case LINE_STAT_UNTRACKED:
5969 text = "Press %s to stage %s for addition";
5970 break;
5972 case LINE_STAT_HEAD:
5973 case LINE_STAT_NONE:
5974 text = "Nothing to update";
5975 break;
5977 default:
5978 die("line type %d not handled in switch", line->type);
5981 if (status && status->status == 'U') {
5982 text = "Press %s to resolve conflict in %s";
5983 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5985 } else {
5986 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5989 string_format(view->ref, text, key, file);
5990 if (status)
5991 string_copy(opt_file, status->new.name);
5994 static bool
5995 status_grep(struct view *view, struct line *line)
5997 struct status *status = line->data;
5999 if (status) {
6000 const char buf[2] = { status->status, 0 };
6001 const char *text[] = { status->new.name, buf, NULL };
6003 return grep_text(view, text);
6006 return FALSE;
6009 static struct view_ops status_ops = {
6010 "file",
6012 status_open,
6013 NULL,
6014 status_draw,
6015 status_request,
6016 status_grep,
6017 status_select,
6021 struct stage_state {
6022 struct diff_state diff;
6023 size_t chunks;
6024 int *chunk;
6027 static bool
6028 stage_diff_write(struct io *io, struct line *line, struct line *end)
6030 while (line < end) {
6031 if (!io_write(io, line->data, strlen(line->data)) ||
6032 !io_write(io, "\n", 1))
6033 return FALSE;
6034 line++;
6035 if (line->type == LINE_DIFF_CHUNK ||
6036 line->type == LINE_DIFF_HEADER)
6037 break;
6040 return TRUE;
6043 static bool
6044 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6046 const char *apply_argv[SIZEOF_ARG] = {
6047 "git", "apply", "--whitespace=nowarn", NULL
6049 struct line *diff_hdr;
6050 struct io io;
6051 int argc = 3;
6053 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6054 if (!diff_hdr)
6055 return FALSE;
6057 if (!revert)
6058 apply_argv[argc++] = "--cached";
6059 if (line != NULL)
6060 apply_argv[argc++] = "--unidiff-zero";
6061 if (revert || stage_line_type == LINE_STAT_STAGED)
6062 apply_argv[argc++] = "-R";
6063 apply_argv[argc++] = "-";
6064 apply_argv[argc++] = NULL;
6065 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6066 return FALSE;
6068 if (line != NULL) {
6069 int lineno = 0;
6070 struct line *context = chunk + 1;
6071 const char *markers[] = {
6072 line->type == LINE_DIFF_DEL ? "" : ",0",
6073 line->type == LINE_DIFF_DEL ? ",0" : "",
6076 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6078 while (context < line) {
6079 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6080 break;
6081 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6082 lineno++;
6084 context++;
6087 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6088 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6089 lineno, markers[0], lineno, markers[1]) ||
6090 !stage_diff_write(&io, line, line + 1)) {
6091 chunk = NULL;
6093 } else {
6094 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6095 !stage_diff_write(&io, chunk, view->line + view->lines))
6096 chunk = NULL;
6099 io_done(&io);
6100 io_run_bg(update_index_argv);
6102 return chunk ? TRUE : FALSE;
6105 static bool
6106 stage_update(struct view *view, struct line *line, bool single)
6108 struct line *chunk = NULL;
6110 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6111 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6113 if (chunk) {
6114 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6115 report("Failed to apply chunk");
6116 return FALSE;
6119 } else if (!stage_status.status) {
6120 view = view->parent;
6122 for (line = view->line; line < view->line + view->lines; line++)
6123 if (line->type == stage_line_type)
6124 break;
6126 if (!status_update_files(view, line + 1)) {
6127 report("Failed to update files");
6128 return FALSE;
6131 } else if (!status_update_file(&stage_status, stage_line_type)) {
6132 report("Failed to update file");
6133 return FALSE;
6136 return TRUE;
6139 static bool
6140 stage_revert(struct view *view, struct line *line)
6142 struct line *chunk = NULL;
6144 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6145 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6147 if (chunk) {
6148 if (!prompt_yesno("Are you sure you want to revert changes?"))
6149 return FALSE;
6151 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6152 report("Failed to revert chunk");
6153 return FALSE;
6155 return TRUE;
6157 } else {
6158 return status_revert(stage_status.status ? &stage_status : NULL,
6159 stage_line_type, FALSE);
6164 static void
6165 stage_next(struct view *view, struct line *line)
6167 struct stage_state *state = view->private;
6168 int i;
6170 if (!state->chunks) {
6171 for (line = view->line; line < view->line + view->lines; line++) {
6172 if (line->type != LINE_DIFF_CHUNK)
6173 continue;
6175 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6176 report("Allocation failure");
6177 return;
6180 state->chunk[state->chunks++] = line - view->line;
6184 for (i = 0; i < state->chunks; i++) {
6185 if (state->chunk[i] > view->lineno) {
6186 do_scroll_view(view, state->chunk[i] - view->lineno);
6187 report("Chunk %d of %d", i + 1, state->chunks);
6188 return;
6192 report("No next chunk found");
6195 static enum request
6196 stage_request(struct view *view, enum request request, struct line *line)
6198 switch (request) {
6199 case REQ_STATUS_UPDATE:
6200 if (!stage_update(view, line, FALSE))
6201 return REQ_NONE;
6202 break;
6204 case REQ_STATUS_REVERT:
6205 if (!stage_revert(view, line))
6206 return REQ_NONE;
6207 break;
6209 case REQ_STAGE_UPDATE_LINE:
6210 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6211 report("Please select a change to stage");
6212 return REQ_NONE;
6214 if (!stage_update(view, line, TRUE))
6215 return REQ_NONE;
6216 break;
6218 case REQ_STAGE_NEXT:
6219 if (stage_line_type == LINE_STAT_UNTRACKED) {
6220 report("File is untracked; press %s to add",
6221 get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
6222 return REQ_NONE;
6224 stage_next(view, line);
6225 return REQ_NONE;
6227 case REQ_EDIT:
6228 if (!stage_status.new.name[0])
6229 return request;
6230 if (stage_status.status == 'D') {
6231 report("File has been deleted.");
6232 return REQ_NONE;
6235 open_editor(stage_status.new.name);
6236 break;
6238 case REQ_REFRESH:
6239 /* Reload everything ... */
6240 break;
6242 case REQ_VIEW_BLAME:
6243 if (stage_status.new.name[0]) {
6244 string_copy(opt_file, stage_status.new.name);
6245 opt_ref[0] = 0;
6247 return request;
6249 case REQ_ENTER:
6250 return diff_common_enter(view, request, line);
6252 case REQ_DIFF_CONTEXT_UP:
6253 case REQ_DIFF_CONTEXT_DOWN:
6254 if (!update_diff_context(request))
6255 return REQ_NONE;
6256 break;
6258 default:
6259 return request;
6262 refresh_view(view->parent);
6264 /* Check whether the staged entry still exists, and close the
6265 * stage view if it doesn't. */
6266 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6267 status_restore(view->parent);
6268 return REQ_VIEW_CLOSE;
6271 refresh_view(view);
6273 return REQ_NONE;
6276 static bool
6277 stage_open(struct view *view, enum open_flags flags)
6279 static const char *no_head_diff_argv[] = {
6280 "git", "diff", "--no-color", "--patch-with-stat",
6281 opt_diff_context_arg,
6282 "--", "/dev/null", stage_status.new.name, NULL
6284 static const char *index_show_argv[] = {
6285 "git", "diff-index", "--root", "--patch-with-stat", "-C", "-M",
6286 "--cached", opt_diff_context_arg, "HEAD", "--",
6287 stage_status.old.name, stage_status.new.name, NULL
6289 static const char *files_show_argv[] = {
6290 "git", "diff-files", "--root", "--patch-with-stat",
6291 "-C", "-M", opt_diff_context_arg, "--",
6292 stage_status.old.name, stage_status.new.name, NULL
6294 /* Diffs for unmerged entries are empty when passing the new
6295 * path, so leave out the new path. */
6296 static const char *files_unmerged_argv[] = {
6297 "git", "diff-files", "--root", "--patch-with-stat",
6298 "-C", "-M", opt_diff_context_arg, "--",
6299 stage_status.old.name, NULL
6301 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6302 const char **argv = NULL;
6303 const char *info;
6305 switch (stage_line_type) {
6306 case LINE_STAT_STAGED:
6307 if (is_initial_commit()) {
6308 argv = no_head_diff_argv;
6309 } else {
6310 argv = index_show_argv;
6312 if (stage_status.status)
6313 info = "Staged changes to %s";
6314 else
6315 info = "Staged changes";
6316 break;
6318 case LINE_STAT_UNSTAGED:
6319 if (stage_status.status != 'U')
6320 argv = files_show_argv;
6321 else
6322 argv = files_unmerged_argv;
6323 if (stage_status.status)
6324 info = "Unstaged changes to %s";
6325 else
6326 info = "Unstaged changes";
6327 break;
6329 case LINE_STAT_UNTRACKED:
6330 info = "Untracked file %s";
6331 argv = file_argv;
6332 break;
6334 case LINE_STAT_HEAD:
6335 default:
6336 die("line type %d not handled in switch", stage_line_type);
6339 string_format(view->ref, info, stage_status.new.name);
6340 view->vid[0] = 0;
6341 view->dir = opt_cdup;
6342 return argv_copy(&view->argv, argv)
6343 && begin_update(view, NULL, NULL, flags);
6346 static bool
6347 stage_read(struct view *view, char *data)
6349 struct stage_state *state = view->private;
6351 if (data && diff_common_read(view, data, &state->diff))
6352 return TRUE;
6354 return pager_read(view, data);
6357 static struct view_ops stage_ops = {
6358 "line",
6359 sizeof(struct stage_state),
6360 stage_open,
6361 stage_read,
6362 diff_common_draw,
6363 stage_request,
6364 pager_grep,
6365 pager_select,
6370 * Revision graph
6373 static const enum line_type graph_colors[] = {
6374 LINE_PALETTE_0,
6375 LINE_PALETTE_1,
6376 LINE_PALETTE_2,
6377 LINE_PALETTE_3,
6378 LINE_PALETTE_4,
6379 LINE_PALETTE_5,
6380 LINE_PALETTE_6,
6383 static enum line_type get_graph_color(struct graph_symbol *symbol)
6385 if (symbol->commit)
6386 return LINE_GRAPH_COMMIT;
6387 assert(symbol->color < ARRAY_SIZE(graph_colors));
6388 return graph_colors[symbol->color];
6391 static bool
6392 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6394 const char *chars = graph_symbol_to_utf8(symbol);
6396 return draw_text(view, color, chars + !!first);
6399 static bool
6400 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6402 const char *chars = graph_symbol_to_ascii(symbol);
6404 return draw_text(view, color, chars + !!first);
6407 static bool
6408 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6410 const chtype *chars = graph_symbol_to_chtype(symbol);
6412 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6415 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6417 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6419 static const draw_graph_fn fns[] = {
6420 draw_graph_ascii,
6421 draw_graph_chtype,
6422 draw_graph_utf8
6424 draw_graph_fn fn = fns[opt_line_graphics];
6425 int i;
6427 for (i = 0; i < canvas->size; i++) {
6428 struct graph_symbol *symbol = &canvas->symbols[i];
6429 enum line_type color = get_graph_color(symbol);
6431 if (fn(view, symbol, color, i == 0))
6432 return TRUE;
6435 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6439 * Main view backend
6442 struct commit {
6443 char id[SIZEOF_REV]; /* SHA1 ID. */
6444 char title[128]; /* First line of the commit message. */
6445 const char *author; /* Author of the commit. */
6446 struct time time; /* Date from the author ident. */
6447 struct ref_list *refs; /* Repository references. */
6448 struct graph_canvas graph; /* Ancestry chain graphics. */
6451 static bool
6452 main_open(struct view *view, enum open_flags flags)
6454 static const char *main_argv[] = {
6455 "git", "log", "--no-color", "--pretty=raw", "--parents",
6456 "--topo-order", "%(diffargs)", "%(revargs)",
6457 "--", "%(fileargs)", NULL
6460 return begin_update(view, NULL, main_argv, flags);
6463 static bool
6464 main_draw(struct view *view, struct line *line, unsigned int lineno)
6466 struct commit *commit = line->data;
6468 if (!commit->author)
6469 return FALSE;
6471 if (opt_line_number && draw_lineno(view, lineno))
6472 return TRUE;
6474 if (draw_date(view, &commit->time))
6475 return TRUE;
6477 if (draw_author(view, commit->author))
6478 return TRUE;
6480 if (opt_rev_graph && draw_graph(view, &commit->graph))
6481 return TRUE;
6483 if (draw_refs(view, commit->refs))
6484 return TRUE;
6486 draw_text(view, LINE_DEFAULT, commit->title);
6487 return TRUE;
6490 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6491 static bool
6492 main_read(struct view *view, char *line)
6494 struct graph *graph = view->private;
6495 enum line_type type;
6496 struct commit *commit;
6498 if (!line) {
6499 if (!view->lines && !view->prev)
6500 die("No revisions match the given arguments.");
6501 if (view->lines > 0) {
6502 commit = view->line[view->lines - 1].data;
6503 view->line[view->lines - 1].dirty = 1;
6504 if (!commit->author) {
6505 view->lines--;
6506 free(commit);
6510 done_graph(graph);
6511 return TRUE;
6514 type = get_line_type(line);
6515 if (type == LINE_COMMIT) {
6516 bool is_boundary;
6518 commit = calloc(1, sizeof(struct commit));
6519 if (!commit)
6520 return FALSE;
6522 line += STRING_SIZE("commit ");
6523 is_boundary = *line == '-';
6524 if (is_boundary)
6525 line++;
6527 string_copy_rev(commit->id, line);
6528 commit->refs = get_ref_list(commit->id);
6529 add_line_data(view, commit, LINE_MAIN_COMMIT);
6530 graph_add_commit(graph, &commit->graph, commit->id, line, is_boundary);
6531 return TRUE;
6534 if (!view->lines)
6535 return TRUE;
6536 commit = view->line[view->lines - 1].data;
6538 switch (type) {
6539 case LINE_PARENT:
6540 if (!graph->has_parents)
6541 graph_add_parent(graph, line + STRING_SIZE("parent "));
6542 break;
6544 case LINE_AUTHOR:
6545 parse_author_line(line + STRING_SIZE("author "),
6546 &commit->author, &commit->time);
6547 graph_render_parents(graph);
6548 break;
6550 default:
6551 /* Fill in the commit title if it has not already been set. */
6552 if (commit->title[0])
6553 break;
6555 /* Require titles to start with a non-space character at the
6556 * offset used by git log. */
6557 if (strncmp(line, " ", 4))
6558 break;
6559 line += 4;
6560 /* Well, if the title starts with a whitespace character,
6561 * try to be forgiving. Otherwise we end up with no title. */
6562 while (isspace(*line))
6563 line++;
6564 if (*line == '\0')
6565 break;
6566 /* FIXME: More graceful handling of titles; append "..." to
6567 * shortened titles, etc. */
6569 string_expand(commit->title, sizeof(commit->title), line, 1);
6570 view->line[view->lines - 1].dirty = 1;
6573 return TRUE;
6576 static enum request
6577 main_request(struct view *view, enum request request, struct line *line)
6579 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6581 switch (request) {
6582 case REQ_ENTER:
6583 if (view_is_displayed(view) && display[0] != view)
6584 maximize_view(view, TRUE);
6585 open_view(view, REQ_VIEW_DIFF, flags);
6586 break;
6587 case REQ_REFRESH:
6588 load_refs();
6589 refresh_view(view);
6590 break;
6592 case REQ_JUMP_COMMIT:
6594 int lineno;
6596 for (lineno = 0; lineno < view->lines; lineno++) {
6597 struct commit *commit = view->line[lineno].data;
6599 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
6600 select_view_line(view, lineno);
6601 report("");
6602 return REQ_NONE;
6606 report("Unable to find commit '%s'", opt_search);
6607 break;
6609 default:
6610 return request;
6613 return REQ_NONE;
6616 static bool
6617 grep_refs(struct ref_list *list, regex_t *regex)
6619 regmatch_t pmatch;
6620 size_t i;
6622 if (!opt_show_refs || !list)
6623 return FALSE;
6625 for (i = 0; i < list->size; i++) {
6626 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
6627 return TRUE;
6630 return FALSE;
6633 static bool
6634 main_grep(struct view *view, struct line *line)
6636 struct commit *commit = line->data;
6637 const char *text[] = {
6638 commit->title,
6639 mkauthor(commit->author, opt_author_cols, opt_author),
6640 mkdate(&commit->time, opt_date),
6641 NULL
6644 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
6647 static void
6648 main_select(struct view *view, struct line *line)
6650 struct commit *commit = line->data;
6652 string_copy_rev(view->ref, commit->id);
6653 string_copy_rev(ref_commit, view->ref);
6656 static struct view_ops main_ops = {
6657 "commit",
6658 sizeof(struct graph),
6659 main_open,
6660 main_read,
6661 main_draw,
6662 main_request,
6663 main_grep,
6664 main_select,
6669 * Status management
6672 /* Whether or not the curses interface has been initialized. */
6673 static bool cursed = FALSE;
6675 /* Terminal hacks and workarounds. */
6676 static bool use_scroll_redrawwin;
6677 static bool use_scroll_status_wclear;
6679 /* The status window is used for polling keystrokes. */
6680 static WINDOW *status_win;
6682 /* Reading from the prompt? */
6683 static bool input_mode = FALSE;
6685 static bool status_empty = FALSE;
6687 /* Update status and title window. */
6688 static void
6689 report(const char *msg, ...)
6691 struct view *view = display[current_view];
6693 if (input_mode)
6694 return;
6696 if (!view) {
6697 char buf[SIZEOF_STR];
6698 int retval;
6700 FORMAT_BUFFER(buf, sizeof(buf), msg, retval);
6701 if (retval >= sizeof(buf)) {
6702 buf[sizeof(buf) - 1] = 0;
6703 buf[sizeof(buf) - 2] = '.';
6704 buf[sizeof(buf) - 3] = '.';
6705 buf[sizeof(buf) - 4] = '.';
6707 die("%s", buf);
6710 if (!status_empty || *msg) {
6711 va_list args;
6713 va_start(args, msg);
6715 wmove(status_win, 0, 0);
6716 if (view->has_scrolled && use_scroll_status_wclear)
6717 wclear(status_win);
6718 if (*msg) {
6719 vwprintw(status_win, msg, args);
6720 status_empty = FALSE;
6721 } else {
6722 status_empty = TRUE;
6724 wclrtoeol(status_win);
6725 wnoutrefresh(status_win);
6727 va_end(args);
6730 update_view_title(view);
6733 static void
6734 init_display(void)
6736 const char *term;
6737 int x, y;
6739 /* Initialize the curses library */
6740 if (isatty(STDIN_FILENO)) {
6741 cursed = !!initscr();
6742 opt_tty = stdin;
6743 } else {
6744 /* Leave stdin and stdout alone when acting as a pager. */
6745 opt_tty = fopen("/dev/tty", "r+");
6746 if (!opt_tty)
6747 die("Failed to open /dev/tty");
6748 cursed = !!newterm(NULL, opt_tty, opt_tty);
6751 if (!cursed)
6752 die("Failed to initialize curses");
6754 nonl(); /* Disable conversion and detect newlines from input. */
6755 cbreak(); /* Take input chars one at a time, no wait for \n */
6756 noecho(); /* Don't echo input */
6757 leaveok(stdscr, FALSE);
6759 if (has_colors())
6760 init_colors();
6762 getmaxyx(stdscr, y, x);
6763 status_win = newwin(1, x, y - 1, 0);
6764 if (!status_win)
6765 die("Failed to create status window");
6767 /* Enable keyboard mapping */
6768 keypad(status_win, TRUE);
6769 wbkgdset(status_win, get_line_attr(LINE_STATUS));
6771 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6772 set_tabsize(opt_tab_size);
6773 #else
6774 TABSIZE = opt_tab_size;
6775 #endif
6777 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6778 if (term && !strcmp(term, "gnome-terminal")) {
6779 /* In the gnome-terminal-emulator, the message from
6780 * scrolling up one line when impossible followed by
6781 * scrolling down one line causes corruption of the
6782 * status line. This is fixed by calling wclear. */
6783 use_scroll_status_wclear = TRUE;
6784 use_scroll_redrawwin = FALSE;
6786 } else if (term && !strcmp(term, "xrvt-xpm")) {
6787 /* No problems with full optimizations in xrvt-(unicode)
6788 * and aterm. */
6789 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6791 } else {
6792 /* When scrolling in (u)xterm the last line in the
6793 * scrolling direction will update slowly. */
6794 use_scroll_redrawwin = TRUE;
6795 use_scroll_status_wclear = FALSE;
6799 static int
6800 get_input(int prompt_position)
6802 struct view *view;
6803 int i, key, cursor_y, cursor_x;
6805 if (prompt_position)
6806 input_mode = TRUE;
6808 while (TRUE) {
6809 bool loading = FALSE;
6811 foreach_view (view, i) {
6812 update_view(view);
6813 if (view_is_displayed(view) && view->has_scrolled &&
6814 use_scroll_redrawwin)
6815 redrawwin(view->win);
6816 view->has_scrolled = FALSE;
6817 if (view->pipe)
6818 loading = TRUE;
6821 /* Update the cursor position. */
6822 if (prompt_position) {
6823 getbegyx(status_win, cursor_y, cursor_x);
6824 cursor_x = prompt_position;
6825 } else {
6826 view = display[current_view];
6827 getbegyx(view->win, cursor_y, cursor_x);
6828 cursor_x = view->width - 1;
6829 cursor_y += view->lineno - view->offset;
6831 setsyx(cursor_y, cursor_x);
6833 /* Refresh, accept single keystroke of input */
6834 doupdate();
6835 nodelay(status_win, loading);
6836 key = wgetch(status_win);
6838 /* wgetch() with nodelay() enabled returns ERR when
6839 * there's no input. */
6840 if (key == ERR) {
6842 } else if (key == KEY_RESIZE) {
6843 int height, width;
6845 getmaxyx(stdscr, height, width);
6847 wresize(status_win, 1, width);
6848 mvwin(status_win, height - 1, 0);
6849 wnoutrefresh(status_win);
6850 resize_display();
6851 redraw_display(TRUE);
6853 } else {
6854 input_mode = FALSE;
6855 if (key == erasechar())
6856 key = KEY_BACKSPACE;
6857 return key;
6862 static char *
6863 prompt_input(const char *prompt, input_handler handler, void *data)
6865 enum input_status status = INPUT_OK;
6866 static char buf[SIZEOF_STR];
6867 size_t pos = 0;
6869 buf[pos] = 0;
6871 while (status == INPUT_OK || status == INPUT_SKIP) {
6872 int key;
6874 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6875 wclrtoeol(status_win);
6877 key = get_input(pos + 1);
6878 switch (key) {
6879 case KEY_RETURN:
6880 case KEY_ENTER:
6881 case '\n':
6882 status = pos ? INPUT_STOP : INPUT_CANCEL;
6883 break;
6885 case KEY_BACKSPACE:
6886 if (pos > 0)
6887 buf[--pos] = 0;
6888 else
6889 status = INPUT_CANCEL;
6890 break;
6892 case KEY_ESC:
6893 status = INPUT_CANCEL;
6894 break;
6896 default:
6897 if (pos >= sizeof(buf)) {
6898 report("Input string too long");
6899 return NULL;
6902 status = handler(data, buf, key);
6903 if (status == INPUT_OK)
6904 buf[pos++] = (char) key;
6908 /* Clear the status window */
6909 status_empty = FALSE;
6910 report("");
6912 if (status == INPUT_CANCEL)
6913 return NULL;
6915 buf[pos++] = 0;
6917 return buf;
6920 static enum input_status
6921 prompt_yesno_handler(void *data, char *buf, int c)
6923 if (c == 'y' || c == 'Y')
6924 return INPUT_STOP;
6925 if (c == 'n' || c == 'N')
6926 return INPUT_CANCEL;
6927 return INPUT_SKIP;
6930 static bool
6931 prompt_yesno(const char *prompt)
6933 char prompt2[SIZEOF_STR];
6935 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6936 return FALSE;
6938 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6941 static enum input_status
6942 read_prompt_handler(void *data, char *buf, int c)
6944 return isprint(c) ? INPUT_OK : INPUT_SKIP;
6947 static char *
6948 read_prompt(const char *prompt)
6950 return prompt_input(prompt, read_prompt_handler, NULL);
6953 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6955 enum input_status status = INPUT_OK;
6956 int size = 0;
6958 while (items[size].text)
6959 size++;
6961 while (status == INPUT_OK) {
6962 const struct menu_item *item = &items[*selected];
6963 int key;
6964 int i;
6966 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6967 prompt, *selected + 1, size);
6968 if (item->hotkey)
6969 wprintw(status_win, "[%c] ", (char) item->hotkey);
6970 wprintw(status_win, "%s", item->text);
6971 wclrtoeol(status_win);
6973 key = get_input(COLS - 1);
6974 switch (key) {
6975 case KEY_RETURN:
6976 case KEY_ENTER:
6977 case '\n':
6978 status = INPUT_STOP;
6979 break;
6981 case KEY_LEFT:
6982 case KEY_UP:
6983 *selected = *selected - 1;
6984 if (*selected < 0)
6985 *selected = size - 1;
6986 break;
6988 case KEY_RIGHT:
6989 case KEY_DOWN:
6990 *selected = (*selected + 1) % size;
6991 break;
6993 case KEY_ESC:
6994 status = INPUT_CANCEL;
6995 break;
6997 default:
6998 for (i = 0; items[i].text; i++)
6999 if (items[i].hotkey == key) {
7000 *selected = i;
7001 status = INPUT_STOP;
7002 break;
7007 /* Clear the status window */
7008 status_empty = FALSE;
7009 report("");
7011 return status != INPUT_CANCEL;
7015 * Repository properties
7018 static struct ref **refs = NULL;
7019 static size_t refs_size = 0;
7020 static struct ref *refs_head = NULL;
7022 static struct ref_list **ref_lists = NULL;
7023 static size_t ref_lists_size = 0;
7025 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
7026 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
7027 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
7029 static int
7030 compare_refs(const void *ref1_, const void *ref2_)
7032 const struct ref *ref1 = *(const struct ref **)ref1_;
7033 const struct ref *ref2 = *(const struct ref **)ref2_;
7035 if (ref1->tag != ref2->tag)
7036 return ref2->tag - ref1->tag;
7037 if (ref1->ltag != ref2->ltag)
7038 return ref2->ltag - ref1->ltag;
7039 if (ref1->head != ref2->head)
7040 return ref2->head - ref1->head;
7041 if (ref1->tracked != ref2->tracked)
7042 return ref2->tracked - ref1->tracked;
7043 if (ref1->replace != ref2->replace)
7044 return ref2->replace - ref1->replace;
7045 /* Order remotes last. */
7046 if (ref1->remote != ref2->remote)
7047 return ref1->remote - ref2->remote;
7048 return strcmp(ref1->name, ref2->name);
7051 static void
7052 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
7054 size_t i;
7056 for (i = 0; i < refs_size; i++)
7057 if (!visitor(data, refs[i]))
7058 break;
7061 static struct ref *
7062 get_ref_head()
7064 return refs_head;
7067 static struct ref_list *
7068 get_ref_list(const char *id)
7070 struct ref_list *list;
7071 size_t i;
7073 for (i = 0; i < ref_lists_size; i++)
7074 if (!strcmp(id, ref_lists[i]->id))
7075 return ref_lists[i];
7077 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
7078 return NULL;
7079 list = calloc(1, sizeof(*list));
7080 if (!list)
7081 return NULL;
7083 for (i = 0; i < refs_size; i++) {
7084 if (!strcmp(id, refs[i]->id) &&
7085 realloc_refs_list(&list->refs, list->size, 1))
7086 list->refs[list->size++] = refs[i];
7089 if (!list->refs) {
7090 free(list);
7091 return NULL;
7094 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
7095 ref_lists[ref_lists_size++] = list;
7096 return list;
7099 static int
7100 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
7102 struct ref *ref = NULL;
7103 bool tag = FALSE;
7104 bool ltag = FALSE;
7105 bool remote = FALSE;
7106 bool replace = FALSE;
7107 bool tracked = FALSE;
7108 bool head = FALSE;
7109 int from = 0, to = refs_size - 1;
7111 if (!prefixcmp(name, "refs/tags/")) {
7112 if (!suffixcmp(name, namelen, "^{}")) {
7113 namelen -= 3;
7114 name[namelen] = 0;
7115 } else {
7116 ltag = TRUE;
7119 tag = TRUE;
7120 namelen -= STRING_SIZE("refs/tags/");
7121 name += STRING_SIZE("refs/tags/");
7123 } else if (!prefixcmp(name, "refs/remotes/")) {
7124 remote = TRUE;
7125 namelen -= STRING_SIZE("refs/remotes/");
7126 name += STRING_SIZE("refs/remotes/");
7127 tracked = !strcmp(opt_remote, name);
7129 } else if (!prefixcmp(name, "refs/replace/")) {
7130 replace = TRUE;
7131 id = name + strlen("refs/replace/");
7132 idlen = namelen - strlen("refs/replace/");
7133 name = "replaced";
7134 namelen = strlen(name);
7136 } else if (!prefixcmp(name, "refs/heads/")) {
7137 namelen -= STRING_SIZE("refs/heads/");
7138 name += STRING_SIZE("refs/heads/");
7139 if (strlen(opt_head) == namelen
7140 && !strncmp(opt_head, name, namelen))
7141 return OK;
7143 } else if (!strcmp(name, "HEAD")) {
7144 head = TRUE;
7145 if (*opt_head) {
7146 namelen = strlen(opt_head);
7147 name = opt_head;
7151 /* If we are reloading or it's an annotated tag, replace the
7152 * previous SHA1 with the resolved commit id; relies on the fact
7153 * git-ls-remote lists the commit id of an annotated tag right
7154 * before the commit id it points to. */
7155 while ((from <= to) && !replace) {
7156 size_t pos = (to + from) / 2;
7157 int cmp = strcmp(name, refs[pos]->name);
7159 if (!cmp) {
7160 ref = refs[pos];
7161 break;
7164 if (cmp < 0)
7165 to = pos - 1;
7166 else
7167 from = pos + 1;
7170 if (!ref) {
7171 if (!realloc_refs(&refs, refs_size, 1))
7172 return ERR;
7173 ref = calloc(1, sizeof(*ref) + namelen);
7174 if (!ref)
7175 return ERR;
7176 memmove(refs + from + 1, refs + from,
7177 (refs_size - from) * sizeof(*refs));
7178 refs[from] = ref;
7179 strncpy(ref->name, name, namelen);
7180 refs_size++;
7183 ref->head = head;
7184 ref->tag = tag;
7185 ref->ltag = ltag;
7186 ref->remote = remote;
7187 ref->replace = replace;
7188 ref->tracked = tracked;
7189 string_copy_rev(ref->id, id);
7191 if (head)
7192 refs_head = ref;
7193 return OK;
7196 static int
7197 load_refs(void)
7199 const char *head_argv[] = {
7200 "git", "symbolic-ref", "HEAD", NULL
7202 static const char *ls_remote_argv[SIZEOF_ARG] = {
7203 "git", "ls-remote", opt_git_dir, NULL
7205 static bool init = FALSE;
7206 size_t i;
7208 if (!init) {
7209 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
7210 die("TIG_LS_REMOTE contains too many arguments");
7211 init = TRUE;
7214 if (!*opt_git_dir)
7215 return OK;
7217 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
7218 !prefixcmp(opt_head, "refs/heads/")) {
7219 char *offset = opt_head + STRING_SIZE("refs/heads/");
7221 memmove(opt_head, offset, strlen(offset) + 1);
7224 refs_head = NULL;
7225 for (i = 0; i < refs_size; i++)
7226 refs[i]->id[0] = 0;
7228 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
7229 return ERR;
7231 /* Update the ref lists to reflect changes. */
7232 for (i = 0; i < ref_lists_size; i++) {
7233 struct ref_list *list = ref_lists[i];
7234 size_t old, new;
7236 for (old = new = 0; old < list->size; old++)
7237 if (!strcmp(list->id, list->refs[old]->id))
7238 list->refs[new++] = list->refs[old];
7239 list->size = new;
7242 qsort(refs, refs_size, sizeof(*refs), compare_refs);
7244 return OK;
7247 static void
7248 set_remote_branch(const char *name, const char *value, size_t valuelen)
7250 if (!strcmp(name, ".remote")) {
7251 string_ncopy(opt_remote, value, valuelen);
7253 } else if (*opt_remote && !strcmp(name, ".merge")) {
7254 size_t from = strlen(opt_remote);
7256 if (!prefixcmp(value, "refs/heads/"))
7257 value += STRING_SIZE("refs/heads/");
7259 if (!string_format_from(opt_remote, &from, "/%s", value))
7260 opt_remote[0] = 0;
7264 static void
7265 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7267 const char *argv[SIZEOF_ARG] = { name, "=" };
7268 int argc = 1 + (cmd == option_set_command);
7269 enum option_code error;
7271 if (!argv_from_string(argv, &argc, value))
7272 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7273 else
7274 error = cmd(argc, argv);
7276 if (error != OPT_OK)
7277 warn("Option 'tig.%s': %s", name, option_errors[error]);
7280 static bool
7281 set_environment_variable(const char *name, const char *value)
7283 size_t len = strlen(name) + 1 + strlen(value) + 1;
7284 char *env = malloc(len);
7286 if (env &&
7287 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7288 putenv(env) == 0)
7289 return TRUE;
7290 free(env);
7291 return FALSE;
7294 static void
7295 set_work_tree(const char *value)
7297 char cwd[SIZEOF_STR];
7299 if (!getcwd(cwd, sizeof(cwd)))
7300 die("Failed to get cwd path: %s", strerror(errno));
7301 if (chdir(opt_git_dir) < 0)
7302 die("Failed to chdir(%s): %s", strerror(errno));
7303 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7304 die("Failed to get git path: %s", strerror(errno));
7305 if (chdir(cwd) < 0)
7306 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7307 if (chdir(value) < 0)
7308 die("Failed to chdir(%s): %s", value, strerror(errno));
7309 if (!getcwd(cwd, sizeof(cwd)))
7310 die("Failed to get cwd path: %s", strerror(errno));
7311 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7312 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7313 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7314 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7315 opt_is_inside_work_tree = TRUE;
7318 static int
7319 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7321 if (!strcmp(name, "i18n.commitencoding"))
7322 string_ncopy(opt_encoding, value, valuelen);
7324 else if (!strcmp(name, "core.editor"))
7325 string_ncopy(opt_editor, value, valuelen);
7327 else if (!strcmp(name, "core.worktree"))
7328 set_work_tree(value);
7330 else if (!prefixcmp(name, "tig.color."))
7331 set_repo_config_option(name + 10, value, option_color_command);
7333 else if (!prefixcmp(name, "tig.bind."))
7334 set_repo_config_option(name + 9, value, option_bind_command);
7336 else if (!prefixcmp(name, "tig."))
7337 set_repo_config_option(name + 4, value, option_set_command);
7339 else if (*opt_head && !prefixcmp(name, "branch.") &&
7340 !strncmp(name + 7, opt_head, strlen(opt_head)))
7341 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7343 return OK;
7346 static int
7347 load_git_config(void)
7349 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7351 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7354 static int
7355 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7357 if (!opt_git_dir[0]) {
7358 string_ncopy(opt_git_dir, name, namelen);
7360 } else if (opt_is_inside_work_tree == -1) {
7361 /* This can be 3 different values depending on the
7362 * version of git being used. If git-rev-parse does not
7363 * understand --is-inside-work-tree it will simply echo
7364 * the option else either "true" or "false" is printed.
7365 * Default to true for the unknown case. */
7366 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7368 } else if (*name == '.') {
7369 string_ncopy(opt_cdup, name, namelen);
7371 } else {
7372 string_ncopy(opt_prefix, name, namelen);
7375 return OK;
7378 static int
7379 load_repo_info(void)
7381 const char *rev_parse_argv[] = {
7382 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7383 "--show-cdup", "--show-prefix", NULL
7386 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7391 * Main
7394 static const char usage[] =
7395 "tig " TIG_VERSION " (" __DATE__ ")\n"
7396 "\n"
7397 "Usage: tig [options] [revs] [--] [paths]\n"
7398 " or: tig show [options] [revs] [--] [paths]\n"
7399 " or: tig blame [options] [rev] [--] path\n"
7400 " or: tig status\n"
7401 " or: tig < [git command output]\n"
7402 "\n"
7403 "Options:\n"
7404 " +<number> Select line <number> in the first view\n"
7405 " -v, --version Show version and exit\n"
7406 " -h, --help Show help message and exit";
7408 static void __NORETURN
7409 quit(int sig)
7411 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7412 if (cursed)
7413 endwin();
7414 exit(0);
7417 static void __NORETURN
7418 die(const char *err, ...)
7420 va_list args;
7422 endwin();
7424 va_start(args, err);
7425 fputs("tig: ", stderr);
7426 vfprintf(stderr, err, args);
7427 fputs("\n", stderr);
7428 va_end(args);
7430 exit(1);
7433 static void
7434 warn(const char *msg, ...)
7436 va_list args;
7438 va_start(args, msg);
7439 fputs("tig warning: ", stderr);
7440 vfprintf(stderr, msg, args);
7441 fputs("\n", stderr);
7442 va_end(args);
7445 static int
7446 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7448 const char ***filter_args = data;
7450 return argv_append(filter_args, name) ? OK : ERR;
7453 static void
7454 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7456 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7457 const char **all_argv = NULL;
7459 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7460 !argv_append_array(&all_argv, argv) ||
7461 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7462 die("Failed to split arguments");
7463 argv_free(all_argv);
7464 free(all_argv);
7467 static void
7468 filter_options(const char *argv[], bool blame)
7470 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7472 if (blame)
7473 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7474 else
7475 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7477 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7480 static enum request
7481 parse_options(int argc, const char *argv[])
7483 enum request request = REQ_VIEW_MAIN;
7484 const char *subcommand;
7485 bool seen_dashdash = FALSE;
7486 const char **filter_argv = NULL;
7487 int i;
7489 if (!isatty(STDIN_FILENO))
7490 return REQ_VIEW_PAGER;
7492 if (argc <= 1)
7493 return REQ_VIEW_MAIN;
7495 subcommand = argv[1];
7496 if (!strcmp(subcommand, "status")) {
7497 if (argc > 2)
7498 warn("ignoring arguments after `%s'", subcommand);
7499 return REQ_VIEW_STATUS;
7501 } else if (!strcmp(subcommand, "blame")) {
7502 request = REQ_VIEW_BLAME;
7504 } else if (!strcmp(subcommand, "show")) {
7505 request = REQ_VIEW_DIFF;
7507 } else {
7508 subcommand = NULL;
7511 for (i = 1 + !!subcommand; i < argc; i++) {
7512 const char *opt = argv[i];
7514 // stop parsing our options after -- and let rev-parse handle the rest
7515 if (!seen_dashdash) {
7516 if (!strcmp(opt, "--")) {
7517 seen_dashdash = TRUE;
7518 continue;
7520 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7521 printf("tig version %s\n", TIG_VERSION);
7522 quit(0);
7524 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7525 printf("%s\n", usage);
7526 quit(0);
7528 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7529 opt_lineno = atoi(opt + 1);
7530 continue;
7535 if (!argv_append(&filter_argv, opt))
7536 die("command too long");
7539 if (filter_argv)
7540 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7542 /* Finish validating and setting up blame options */
7543 if (request == REQ_VIEW_BLAME) {
7544 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7545 die("invalid number of options to blame\n\n%s", usage);
7547 if (opt_rev_argv) {
7548 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7551 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7554 return request;
7558 main(int argc, const char *argv[])
7560 const char *codeset = ENCODING_UTF8;
7561 enum request request = parse_options(argc, argv);
7562 struct view *view;
7564 signal(SIGINT, quit);
7565 signal(SIGPIPE, SIG_IGN);
7567 if (setlocale(LC_ALL, "")) {
7568 codeset = nl_langinfo(CODESET);
7571 if (load_repo_info() == ERR)
7572 die("Failed to load repo info.");
7574 if (load_options() == ERR)
7575 die("Failed to load user config.");
7577 if (load_git_config() == ERR)
7578 die("Failed to load repo config.");
7580 /* Require a git repository unless when running in pager mode. */
7581 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7582 die("Not a git repository");
7584 if (*opt_encoding && strcmp(opt_encoding, ENCODING_UTF8)) {
7585 opt_iconv_in = iconv_open(ENCODING_UTF8, opt_encoding);
7586 if (opt_iconv_in == ICONV_NONE)
7587 die("Failed to initialize character set conversion");
7590 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
7591 char translit[SIZEOF_STR];
7593 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
7594 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
7595 else
7596 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
7597 if (opt_iconv_out == ICONV_NONE)
7598 die("Failed to initialize character set conversion");
7601 if (load_refs() == ERR)
7602 die("Failed to load refs.");
7604 init_display();
7606 while (view_driver(display[current_view], request)) {
7607 int key = get_input(0);
7609 view = display[current_view];
7610 request = get_keybinding(view->keymap, key);
7612 /* Some low-level request handling. This keeps access to
7613 * status_win restricted. */
7614 switch (request) {
7615 case REQ_NONE:
7616 report("Unknown key, press %s for help",
7617 get_key(view->keymap, REQ_VIEW_HELP));
7618 break;
7619 case REQ_PROMPT:
7621 char *cmd = read_prompt(":");
7623 if (cmd && string_isnumber(cmd)) {
7624 int lineno = view->lineno + 1;
7626 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
7627 select_view_line(view, lineno - 1);
7628 report("");
7629 } else {
7630 report("Unable to parse '%s' as a line number", cmd);
7632 } else if (cmd && iscommit(cmd)) {
7633 string_ncopy(opt_search, cmd, strlen(cmd));
7635 request = view_request(view, REQ_JUMP_COMMIT);
7636 if (request == REQ_JUMP_COMMIT) {
7637 report("Jumping to commits is not supported by the '%s' view", view->name);
7640 } else if (cmd) {
7641 struct view *next = VIEW(REQ_VIEW_PAGER);
7642 const char *argv[SIZEOF_ARG] = { "git" };
7643 int argc = 1;
7645 /* When running random commands, initially show the
7646 * command in the title. However, it maybe later be
7647 * overwritten if a commit line is selected. */
7648 string_ncopy(next->ref, cmd, strlen(cmd));
7650 if (!argv_from_string(argv, &argc, cmd)) {
7651 report("Too many arguments");
7652 } else if (!format_argv(&next->argv, argv, FALSE)) {
7653 report("Argument formatting failed");
7654 } else {
7655 next->dir = NULL;
7656 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7660 request = REQ_NONE;
7661 break;
7663 case REQ_SEARCH:
7664 case REQ_SEARCH_BACK:
7666 const char *prompt = request == REQ_SEARCH ? "/" : "?";
7667 char *search = read_prompt(prompt);
7669 if (search)
7670 string_ncopy(opt_search, search, strlen(search));
7671 else if (*opt_search)
7672 request = request == REQ_SEARCH ?
7673 REQ_FIND_NEXT :
7674 REQ_FIND_PREV;
7675 else
7676 request = REQ_NONE;
7677 break;
7679 default:
7680 break;
7684 quit(0);
7686 return 0;