Add "//TRANSLIT" for iconv encoding
[tig.git] / tig.c
blobe5637bff606139da30441bc8ef21a75a800cf7dc
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 /* It's OK that the file doesn't exist. */
1443 if (!io_open(&io, "%s", path))
1444 return;
1446 if (io_load(&io, " \t", read_option, &config) == ERR ||
1447 config.errors == TRUE)
1448 warn("Errors while loading %s.", path);
1451 static int
1452 load_options(void)
1454 const char *home = getenv("HOME");
1455 const char *tigrc_user = getenv("TIGRC_USER");
1456 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1457 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1458 char buf[SIZEOF_STR];
1460 if (!tigrc_system)
1461 tigrc_system = SYSCONFDIR "/tigrc";
1462 load_option_file(tigrc_system);
1464 if (!tigrc_user) {
1465 if (!home || !string_format(buf, "%s/.tigrc", home))
1466 return ERR;
1467 tigrc_user = buf;
1469 load_option_file(tigrc_user);
1471 /* Add _after_ loading config files to avoid adding run requests
1472 * that conflict with keybindings. */
1473 add_builtin_run_requests();
1475 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1476 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1477 int argc = 0;
1479 if (!string_format(buf, "%s", tig_diff_opts) ||
1480 !argv_from_string(diff_opts, &argc, buf))
1481 die("TIG_DIFF_OPTS contains too many arguments");
1482 else if (!argv_copy(&opt_diff_argv, diff_opts))
1483 die("Failed to format TIG_DIFF_OPTS arguments");
1486 return OK;
1491 * The viewer
1494 struct view;
1495 struct view_ops;
1497 /* The display array of active views and the index of the current view. */
1498 static struct view *display[2];
1499 static WINDOW *display_win[2];
1500 static WINDOW *display_title[2];
1501 static unsigned int current_view;
1503 #define foreach_displayed_view(view, i) \
1504 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1506 #define displayed_views() (display[1] != NULL ? 2 : 1)
1508 /* Current head and commit ID */
1509 static char ref_blob[SIZEOF_REF] = "";
1510 static char ref_commit[SIZEOF_REF] = "HEAD";
1511 static char ref_head[SIZEOF_REF] = "HEAD";
1512 static char ref_branch[SIZEOF_REF] = "";
1514 enum view_type {
1515 VIEW_MAIN,
1516 VIEW_DIFF,
1517 VIEW_LOG,
1518 VIEW_TREE,
1519 VIEW_BLOB,
1520 VIEW_BLAME,
1521 VIEW_BRANCH,
1522 VIEW_HELP,
1523 VIEW_PAGER,
1524 VIEW_STATUS,
1525 VIEW_STAGE,
1528 struct view {
1529 enum view_type type; /* View type */
1530 const char *name; /* View name */
1531 const char *id; /* Points to either of ref_{head,commit,blob} */
1533 struct view_ops *ops; /* View operations */
1535 enum keymap keymap; /* What keymap does this view have */
1536 bool git_dir; /* Whether the view requires a git directory. */
1538 char ref[SIZEOF_REF]; /* Hovered commit reference */
1539 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1541 int height, width; /* The width and height of the main window */
1542 WINDOW *win; /* The main window */
1544 /* Navigation */
1545 unsigned long offset; /* Offset of the window top */
1546 unsigned long yoffset; /* Offset from the window side. */
1547 unsigned long lineno; /* Current line number */
1548 unsigned long p_offset; /* Previous offset of the window top */
1549 unsigned long p_yoffset;/* Previous offset from the window side */
1550 unsigned long p_lineno; /* Previous current line number */
1551 bool p_restore; /* Should the previous position be restored. */
1553 /* Searching */
1554 char grep[SIZEOF_STR]; /* Search string */
1555 regex_t *regex; /* Pre-compiled regexp */
1557 /* If non-NULL, points to the view that opened this view. If this view
1558 * is closed tig will switch back to the parent view. */
1559 struct view *parent;
1560 struct view *prev;
1562 /* Buffering */
1563 size_t lines; /* Total number of lines */
1564 struct line *line; /* Line index */
1565 unsigned int digits; /* Number of digits in the lines member. */
1567 /* Drawing */
1568 struct line *curline; /* Line currently being drawn. */
1569 enum line_type curtype; /* Attribute currently used for drawing. */
1570 unsigned long col; /* Column when drawing. */
1571 bool has_scrolled; /* View was scrolled. */
1573 /* Loading */
1574 const char **argv; /* Shell command arguments. */
1575 const char *dir; /* Directory from which to execute. */
1576 struct io io;
1577 struct io *pipe;
1578 time_t start_time;
1579 time_t update_secs;
1581 /* Private data */
1582 void *private;
1585 enum open_flags {
1586 OPEN_DEFAULT = 0, /* Use default view switching. */
1587 OPEN_SPLIT = 1, /* Split current view. */
1588 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1589 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1590 OPEN_PREPARED = 32, /* Open already prepared command. */
1591 OPEN_EXTRA = 64, /* Open extra data from command. */
1594 struct view_ops {
1595 /* What type of content being displayed. Used in the title bar. */
1596 const char *type;
1597 /* Size of private data. */
1598 size_t private_size;
1599 /* Open and reads in all view content. */
1600 bool (*open)(struct view *view, enum open_flags flags);
1601 /* Read one line; updates view->line. */
1602 bool (*read)(struct view *view, char *data);
1603 /* Draw one line; @lineno must be < view->height. */
1604 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1605 /* Depending on view handle a special requests. */
1606 enum request (*request)(struct view *view, enum request request, struct line *line);
1607 /* Search for regexp in a line. */
1608 bool (*grep)(struct view *view, struct line *line);
1609 /* Select line */
1610 void (*select)(struct view *view, struct line *line);
1613 static struct view_ops blame_ops;
1614 static struct view_ops blob_ops;
1615 static struct view_ops diff_ops;
1616 static struct view_ops help_ops;
1617 static struct view_ops log_ops;
1618 static struct view_ops main_ops;
1619 static struct view_ops pager_ops;
1620 static struct view_ops stage_ops;
1621 static struct view_ops status_ops;
1622 static struct view_ops tree_ops;
1623 static struct view_ops branch_ops;
1625 #define VIEW_STR(type, name, ref, ops, map, git) \
1626 { type, name, ref, ops, map, git }
1628 #define VIEW_(id, name, ops, git, ref) \
1629 VIEW_STR(VIEW_##id, name, ref, ops, KEYMAP_##id, git)
1631 static struct view views[] = {
1632 VIEW_(MAIN, "main", &main_ops, TRUE, ref_head),
1633 VIEW_(DIFF, "diff", &diff_ops, TRUE, ref_commit),
1634 VIEW_(LOG, "log", &log_ops, TRUE, ref_head),
1635 VIEW_(TREE, "tree", &tree_ops, TRUE, ref_commit),
1636 VIEW_(BLOB, "blob", &blob_ops, TRUE, ref_blob),
1637 VIEW_(BLAME, "blame", &blame_ops, TRUE, ref_commit),
1638 VIEW_(BRANCH, "branch", &branch_ops, TRUE, ref_head),
1639 VIEW_(HELP, "help", &help_ops, FALSE, ""),
1640 VIEW_(PAGER, "pager", &pager_ops, FALSE, ""),
1641 VIEW_(STATUS, "status", &status_ops, TRUE, "status"),
1642 VIEW_(STAGE, "stage", &stage_ops, TRUE, "stage"),
1645 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1647 #define foreach_view(view, i) \
1648 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1650 #define view_is_displayed(view) \
1651 (view == display[0] || view == display[1])
1653 static enum request
1654 view_request(struct view *view, enum request request)
1656 if (!view || !view->lines)
1657 return request;
1658 return view->ops->request(view, request, &view->line[view->lineno]);
1663 * View drawing.
1666 static inline void
1667 set_view_attr(struct view *view, enum line_type type)
1669 if (!view->curline->selected && view->curtype != type) {
1670 (void) wattrset(view->win, get_line_attr(type));
1671 wchgat(view->win, -1, 0, COLOR_ID(type), NULL);
1672 view->curtype = type;
1676 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1678 static bool
1679 draw_chars(struct view *view, enum line_type type, const char *string,
1680 int max_len, bool use_tilde)
1682 static char out_buffer[BUFSIZ * 2];
1683 int len = 0;
1684 int col = 0;
1685 int trimmed = FALSE;
1686 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1688 if (max_len <= 0)
1689 return VIEW_MAX_LEN(view) <= 0;
1691 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1693 set_view_attr(view, type);
1694 if (len > 0) {
1695 if (opt_iconv_out != ICONV_NONE) {
1696 ICONV_CONST char *inbuf = (ICONV_CONST char *) string;
1697 size_t inlen = len + 1;
1699 char *outbuf = out_buffer;
1700 size_t outlen = sizeof(out_buffer);
1702 size_t ret;
1704 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1705 if (ret != (size_t) -1) {
1706 string = out_buffer;
1707 len = sizeof(out_buffer) - outlen;
1711 waddnstr(view->win, string, len);
1713 if (trimmed && use_tilde) {
1714 set_view_attr(view, LINE_DELIMITER);
1715 waddch(view->win, '~');
1716 col++;
1720 view->col += col;
1721 return VIEW_MAX_LEN(view) <= 0;
1724 static bool
1725 draw_space(struct view *view, enum line_type type, int max, int spaces)
1727 static char space[] = " ";
1729 spaces = MIN(max, spaces);
1731 while (spaces > 0) {
1732 int len = MIN(spaces, sizeof(space) - 1);
1734 if (draw_chars(view, type, space, len, FALSE))
1735 return TRUE;
1736 spaces -= len;
1739 return VIEW_MAX_LEN(view) <= 0;
1742 static bool
1743 draw_text(struct view *view, enum line_type type, const char *string)
1745 char text[SIZEOF_STR];
1747 do {
1748 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1750 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1751 return TRUE;
1752 string += pos;
1753 } while (*string);
1755 return VIEW_MAX_LEN(view) <= 0;
1758 static bool
1759 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1761 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1762 int max = VIEW_MAX_LEN(view);
1763 int i;
1765 if (max < size)
1766 size = max;
1768 set_view_attr(view, type);
1769 /* Using waddch() instead of waddnstr() ensures that
1770 * they'll be rendered correctly for the cursor line. */
1771 for (i = skip; i < size; i++)
1772 waddch(view->win, graphic[i]);
1774 view->col += size;
1775 if (separator) {
1776 if (size < max && skip <= size)
1777 waddch(view->win, ' ');
1778 view->col++;
1781 return VIEW_MAX_LEN(view) <= 0;
1784 static bool
1785 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1787 int max = MIN(VIEW_MAX_LEN(view), len);
1788 int col = view->col;
1790 if (!text)
1791 return draw_space(view, type, max, max);
1793 return draw_chars(view, type, text, max - 1, trim)
1794 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1797 static bool
1798 draw_date(struct view *view, struct time *time)
1800 const char *date = mkdate(time, opt_date);
1801 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1803 if (opt_date == DATE_NO)
1804 return FALSE;
1806 return draw_field(view, LINE_DATE, date, cols, FALSE);
1809 static bool
1810 draw_author(struct view *view, const char *author)
1812 bool trim = author_trim(opt_author_cols);
1813 const char *text = mkauthor(author, opt_author_cols, opt_author);
1815 if (opt_author == AUTHOR_NO)
1816 return FALSE;
1818 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1821 static bool
1822 draw_filename(struct view *view, const char *filename, bool auto_enabled)
1824 bool trim = filename && strlen(filename) >= opt_filename_cols;
1826 if (opt_filename == FILENAME_NO)
1827 return FALSE;
1829 if (opt_filename == FILENAME_AUTO && !auto_enabled)
1830 return FALSE;
1832 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
1835 static bool
1836 draw_mode(struct view *view, mode_t mode)
1838 const char *str = mkmode(mode);
1840 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1843 static bool
1844 draw_lineno(struct view *view, unsigned int lineno)
1846 char number[10];
1847 int digits3 = view->digits < 3 ? 3 : view->digits;
1848 int max = MIN(VIEW_MAX_LEN(view), digits3);
1849 char *text = NULL;
1850 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1852 lineno += view->offset + 1;
1853 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1854 static char fmt[] = "%1ld";
1856 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1857 if (string_format(number, fmt, lineno))
1858 text = number;
1860 if (text)
1861 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1862 else
1863 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1864 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1867 static bool
1868 draw_refs(struct view *view, struct ref_list *refs)
1870 size_t i;
1872 if (!opt_show_refs || !refs)
1873 return FALSE;
1875 for (i = 0; i < refs->size; i++) {
1876 struct ref *ref = refs->refs[i];
1877 enum line_type type = get_line_type_from_ref(ref);
1879 if (draw_text(view, type, "[") ||
1880 draw_text(view, type, ref->name) ||
1881 draw_text(view, type, "]"))
1882 return TRUE;
1884 if (draw_text(view, LINE_DEFAULT, " "))
1885 return TRUE;
1888 return FALSE;
1891 static bool
1892 draw_view_line(struct view *view, unsigned int lineno)
1894 struct line *line;
1895 bool selected = (view->offset + lineno == view->lineno);
1897 assert(view_is_displayed(view));
1899 if (view->offset + lineno >= view->lines)
1900 return FALSE;
1902 line = &view->line[view->offset + lineno];
1904 wmove(view->win, lineno, 0);
1905 if (line->cleareol)
1906 wclrtoeol(view->win);
1907 view->col = 0;
1908 view->curline = line;
1909 view->curtype = LINE_NONE;
1910 line->selected = FALSE;
1911 line->dirty = line->cleareol = 0;
1913 if (selected) {
1914 set_view_attr(view, LINE_CURSOR);
1915 line->selected = TRUE;
1916 view->ops->select(view, line);
1919 return view->ops->draw(view, line, lineno);
1922 static void
1923 redraw_view_dirty(struct view *view)
1925 bool dirty = FALSE;
1926 int lineno;
1928 for (lineno = 0; lineno < view->height; lineno++) {
1929 if (view->offset + lineno >= view->lines)
1930 break;
1931 if (!view->line[view->offset + lineno].dirty)
1932 continue;
1933 dirty = TRUE;
1934 if (!draw_view_line(view, lineno))
1935 break;
1938 if (!dirty)
1939 return;
1940 wnoutrefresh(view->win);
1943 static void
1944 redraw_view_from(struct view *view, int lineno)
1946 assert(0 <= lineno && lineno < view->height);
1948 for (; lineno < view->height; lineno++) {
1949 if (!draw_view_line(view, lineno))
1950 break;
1953 wnoutrefresh(view->win);
1956 static void
1957 redraw_view(struct view *view)
1959 werase(view->win);
1960 redraw_view_from(view, 0);
1964 static void
1965 update_view_title(struct view *view)
1967 char buf[SIZEOF_STR];
1968 char state[SIZEOF_STR];
1969 size_t bufpos = 0, statelen = 0;
1970 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1972 assert(view_is_displayed(view));
1974 if (view->type != VIEW_STATUS && view->lines) {
1975 unsigned int view_lines = view->offset + view->height;
1976 unsigned int lines = view->lines
1977 ? MIN(view_lines, view->lines) * 100 / view->lines
1978 : 0;
1980 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
1981 view->ops->type,
1982 view->lineno + 1,
1983 view->lines,
1984 lines);
1988 if (view->pipe) {
1989 time_t secs = time(NULL) - view->start_time;
1991 /* Three git seconds are a long time ... */
1992 if (secs > 2)
1993 string_format_from(state, &statelen, " loading %lds", secs);
1996 string_format_from(buf, &bufpos, "[%s]", view->name);
1997 if (*view->ref && bufpos < view->width) {
1998 size_t refsize = strlen(view->ref);
1999 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2001 if (minsize < view->width)
2002 refsize = view->width - minsize + 7;
2003 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2006 if (statelen && bufpos < view->width) {
2007 string_format_from(buf, &bufpos, "%s", state);
2010 if (view == display[current_view])
2011 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2012 else
2013 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2015 mvwaddnstr(window, 0, 0, buf, bufpos);
2016 wclrtoeol(window);
2017 wnoutrefresh(window);
2020 static int
2021 apply_step(double step, int value)
2023 if (step >= 1)
2024 return (int) step;
2025 value *= step + 0.01;
2026 return value ? value : 1;
2029 static void
2030 resize_display(void)
2032 int offset, i;
2033 struct view *base = display[0];
2034 struct view *view = display[1] ? display[1] : display[0];
2036 /* Setup window dimensions */
2038 getmaxyx(stdscr, base->height, base->width);
2040 /* Make room for the status window. */
2041 base->height -= 1;
2043 if (view != base) {
2044 /* Horizontal split. */
2045 view->width = base->width;
2046 view->height = apply_step(opt_scale_split_view, base->height);
2047 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2048 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2049 base->height -= view->height;
2051 /* Make room for the title bar. */
2052 view->height -= 1;
2055 /* Make room for the title bar. */
2056 base->height -= 1;
2058 offset = 0;
2060 foreach_displayed_view (view, i) {
2061 if (!display_win[i]) {
2062 display_win[i] = newwin(view->height, view->width, offset, 0);
2063 if (!display_win[i])
2064 die("Failed to create %s view", view->name);
2066 scrollok(display_win[i], FALSE);
2068 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2069 if (!display_title[i])
2070 die("Failed to create title window");
2072 } else {
2073 wresize(display_win[i], view->height, view->width);
2074 mvwin(display_win[i], offset, 0);
2075 mvwin(display_title[i], offset + view->height, 0);
2078 view->win = display_win[i];
2080 offset += view->height + 1;
2084 static void
2085 redraw_display(bool clear)
2087 struct view *view;
2088 int i;
2090 foreach_displayed_view (view, i) {
2091 if (clear)
2092 wclear(view->win);
2093 redraw_view(view);
2094 update_view_title(view);
2100 * Option management
2103 #define TOGGLE_MENU \
2104 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2105 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2106 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2107 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2108 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2109 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2110 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL)
2112 static void
2113 toggle_option(enum request request)
2115 const struct {
2116 enum request request;
2117 const struct enum_map *map;
2118 size_t map_size;
2119 } data[] = {
2120 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2121 TOGGLE_MENU
2122 #undef TOGGLE_
2124 const struct menu_item menu[] = {
2125 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2126 TOGGLE_MENU
2127 #undef TOGGLE_
2128 { 0 }
2130 int i = 0;
2132 if (request == REQ_OPTIONS) {
2133 if (!prompt_menu("Toggle option", menu, &i))
2134 return;
2135 } else {
2136 while (i < ARRAY_SIZE(data) && data[i].request != request)
2137 i++;
2138 if (i >= ARRAY_SIZE(data))
2139 die("Invalid request (%d)", request);
2142 if (data[i].map != NULL) {
2143 unsigned int *opt = menu[i].data;
2145 *opt = (*opt + 1) % data[i].map_size;
2146 redraw_display(FALSE);
2147 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2149 } else {
2150 bool *option = menu[i].data;
2152 *option = !*option;
2153 redraw_display(FALSE);
2154 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2158 static void
2159 maximize_view(struct view *view, bool redraw)
2161 memset(display, 0, sizeof(display));
2162 current_view = 0;
2163 display[current_view] = view;
2164 resize_display();
2165 if (redraw) {
2166 redraw_display(FALSE);
2167 report("");
2173 * Navigation
2176 static bool
2177 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2179 if (lineno >= view->lines)
2180 lineno = view->lines > 0 ? view->lines - 1 : 0;
2182 if (offset > lineno || offset + view->height <= lineno) {
2183 unsigned long half = view->height / 2;
2185 if (lineno > half)
2186 offset = lineno - half;
2187 else
2188 offset = 0;
2191 if (offset != view->offset || lineno != view->lineno) {
2192 view->offset = offset;
2193 view->lineno = lineno;
2194 return TRUE;
2197 return FALSE;
2200 /* Scrolling backend */
2201 static void
2202 do_scroll_view(struct view *view, int lines)
2204 bool redraw_current_line = FALSE;
2206 /* The rendering expects the new offset. */
2207 view->offset += lines;
2209 assert(0 <= view->offset && view->offset < view->lines);
2210 assert(lines);
2212 /* Move current line into the view. */
2213 if (view->lineno < view->offset) {
2214 view->lineno = view->offset;
2215 redraw_current_line = TRUE;
2216 } else if (view->lineno >= view->offset + view->height) {
2217 view->lineno = view->offset + view->height - 1;
2218 redraw_current_line = TRUE;
2221 assert(view->offset <= view->lineno && view->lineno < view->lines);
2223 /* Redraw the whole screen if scrolling is pointless. */
2224 if (view->height < ABS(lines)) {
2225 redraw_view(view);
2227 } else {
2228 int line = lines > 0 ? view->height - lines : 0;
2229 int end = line + ABS(lines);
2231 scrollok(view->win, TRUE);
2232 wscrl(view->win, lines);
2233 scrollok(view->win, FALSE);
2235 while (line < end && draw_view_line(view, line))
2236 line++;
2238 if (redraw_current_line)
2239 draw_view_line(view, view->lineno - view->offset);
2240 wnoutrefresh(view->win);
2243 view->has_scrolled = TRUE;
2244 report("");
2247 /* Scroll frontend */
2248 static void
2249 scroll_view(struct view *view, enum request request)
2251 int lines = 1;
2253 assert(view_is_displayed(view));
2255 switch (request) {
2256 case REQ_SCROLL_FIRST_COL:
2257 view->yoffset = 0;
2258 redraw_view_from(view, 0);
2259 report("");
2260 return;
2261 case REQ_SCROLL_LEFT:
2262 if (view->yoffset == 0) {
2263 report("Cannot scroll beyond the first column");
2264 return;
2266 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2267 view->yoffset = 0;
2268 else
2269 view->yoffset -= apply_step(opt_hscroll, view->width);
2270 redraw_view_from(view, 0);
2271 report("");
2272 return;
2273 case REQ_SCROLL_RIGHT:
2274 view->yoffset += apply_step(opt_hscroll, view->width);
2275 redraw_view(view);
2276 report("");
2277 return;
2278 case REQ_SCROLL_PAGE_DOWN:
2279 lines = view->height;
2280 case REQ_SCROLL_LINE_DOWN:
2281 if (view->offset + lines > view->lines)
2282 lines = view->lines - view->offset;
2284 if (lines == 0 || view->offset + view->height >= view->lines) {
2285 report("Cannot scroll beyond the last line");
2286 return;
2288 break;
2290 case REQ_SCROLL_PAGE_UP:
2291 lines = view->height;
2292 case REQ_SCROLL_LINE_UP:
2293 if (lines > view->offset)
2294 lines = view->offset;
2296 if (lines == 0) {
2297 report("Cannot scroll beyond the first line");
2298 return;
2301 lines = -lines;
2302 break;
2304 default:
2305 die("request %d not handled in switch", request);
2308 do_scroll_view(view, lines);
2311 /* Cursor moving */
2312 static void
2313 move_view(struct view *view, enum request request)
2315 int scroll_steps = 0;
2316 int steps;
2318 switch (request) {
2319 case REQ_MOVE_FIRST_LINE:
2320 steps = -view->lineno;
2321 break;
2323 case REQ_MOVE_LAST_LINE:
2324 steps = view->lines - view->lineno - 1;
2325 break;
2327 case REQ_MOVE_PAGE_UP:
2328 steps = view->height > view->lineno
2329 ? -view->lineno : -view->height;
2330 break;
2332 case REQ_MOVE_PAGE_DOWN:
2333 steps = view->lineno + view->height >= view->lines
2334 ? view->lines - view->lineno - 1 : view->height;
2335 break;
2337 case REQ_MOVE_UP:
2338 steps = -1;
2339 break;
2341 case REQ_MOVE_DOWN:
2342 steps = 1;
2343 break;
2345 default:
2346 die("request %d not handled in switch", request);
2349 if (steps <= 0 && view->lineno == 0) {
2350 report("Cannot move beyond the first line");
2351 return;
2353 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2354 report("Cannot move beyond the last line");
2355 return;
2358 /* Move the current line */
2359 view->lineno += steps;
2360 assert(0 <= view->lineno && view->lineno < view->lines);
2362 /* Check whether the view needs to be scrolled */
2363 if (view->lineno < view->offset ||
2364 view->lineno >= view->offset + view->height) {
2365 scroll_steps = steps;
2366 if (steps < 0 && -steps > view->offset) {
2367 scroll_steps = -view->offset;
2369 } else if (steps > 0) {
2370 if (view->lineno == view->lines - 1 &&
2371 view->lines > view->height) {
2372 scroll_steps = view->lines - view->offset - 1;
2373 if (scroll_steps >= view->height)
2374 scroll_steps -= view->height - 1;
2379 if (!view_is_displayed(view)) {
2380 view->offset += scroll_steps;
2381 assert(0 <= view->offset && view->offset < view->lines);
2382 view->ops->select(view, &view->line[view->lineno]);
2383 return;
2386 /* Repaint the old "current" line if we be scrolling */
2387 if (ABS(steps) < view->height)
2388 draw_view_line(view, view->lineno - steps - view->offset);
2390 if (scroll_steps) {
2391 do_scroll_view(view, scroll_steps);
2392 return;
2395 /* Draw the current line */
2396 draw_view_line(view, view->lineno - view->offset);
2398 wnoutrefresh(view->win);
2399 report("");
2404 * Searching
2407 static void search_view(struct view *view, enum request request);
2409 static bool
2410 grep_text(struct view *view, const char *text[])
2412 regmatch_t pmatch;
2413 size_t i;
2415 for (i = 0; text[i]; i++)
2416 if (*text[i] &&
2417 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2418 return TRUE;
2419 return FALSE;
2422 static void
2423 select_view_line(struct view *view, unsigned long lineno)
2425 unsigned long old_lineno = view->lineno;
2426 unsigned long old_offset = view->offset;
2428 if (goto_view_line(view, view->offset, lineno)) {
2429 if (view_is_displayed(view)) {
2430 if (old_offset != view->offset) {
2431 redraw_view(view);
2432 } else {
2433 draw_view_line(view, old_lineno - view->offset);
2434 draw_view_line(view, view->lineno - view->offset);
2435 wnoutrefresh(view->win);
2437 } else {
2438 view->ops->select(view, &view->line[view->lineno]);
2443 static void
2444 find_next(struct view *view, enum request request)
2446 unsigned long lineno = view->lineno;
2447 int direction;
2449 if (!*view->grep) {
2450 if (!*opt_search)
2451 report("No previous search");
2452 else
2453 search_view(view, request);
2454 return;
2457 switch (request) {
2458 case REQ_SEARCH:
2459 case REQ_FIND_NEXT:
2460 direction = 1;
2461 break;
2463 case REQ_SEARCH_BACK:
2464 case REQ_FIND_PREV:
2465 direction = -1;
2466 break;
2468 default:
2469 return;
2472 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2473 lineno += direction;
2475 /* Note, lineno is unsigned long so will wrap around in which case it
2476 * will become bigger than view->lines. */
2477 for (; lineno < view->lines; lineno += direction) {
2478 if (view->ops->grep(view, &view->line[lineno])) {
2479 select_view_line(view, lineno);
2480 report("Line %ld matches '%s'", lineno + 1, view->grep);
2481 return;
2485 report("No match found for '%s'", view->grep);
2488 static void
2489 search_view(struct view *view, enum request request)
2491 int regex_err;
2493 if (view->regex) {
2494 regfree(view->regex);
2495 *view->grep = 0;
2496 } else {
2497 view->regex = calloc(1, sizeof(*view->regex));
2498 if (!view->regex)
2499 return;
2502 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2503 if (regex_err != 0) {
2504 char buf[SIZEOF_STR] = "unknown error";
2506 regerror(regex_err, view->regex, buf, sizeof(buf));
2507 report("Search failed: %s", buf);
2508 return;
2511 string_copy(view->grep, opt_search);
2513 find_next(view, request);
2517 * Incremental updating
2520 static void
2521 reset_view(struct view *view)
2523 int i;
2525 for (i = 0; i < view->lines; i++)
2526 free(view->line[i].data);
2527 free(view->line);
2529 view->p_offset = view->offset;
2530 view->p_yoffset = view->yoffset;
2531 view->p_lineno = view->lineno;
2533 view->line = NULL;
2534 view->offset = 0;
2535 view->yoffset = 0;
2536 view->lines = 0;
2537 view->lineno = 0;
2538 view->vid[0] = 0;
2539 view->update_secs = 0;
2542 static const char *
2543 format_arg(const char *name)
2545 static struct {
2546 const char *name;
2547 size_t namelen;
2548 const char *value;
2549 const char *value_if_empty;
2550 } vars[] = {
2551 #define FORMAT_VAR(name, value, value_if_empty) \
2552 { name, STRING_SIZE(name), value, value_if_empty }
2553 FORMAT_VAR("%(directory)", opt_path, "."),
2554 FORMAT_VAR("%(file)", opt_file, ""),
2555 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2556 FORMAT_VAR("%(head)", ref_head, ""),
2557 FORMAT_VAR("%(commit)", ref_commit, ""),
2558 FORMAT_VAR("%(blob)", ref_blob, ""),
2559 FORMAT_VAR("%(branch)", ref_branch, ""),
2561 int i;
2563 for (i = 0; i < ARRAY_SIZE(vars); i++)
2564 if (!strncmp(name, vars[i].name, vars[i].namelen))
2565 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2567 report("Unknown replacement: `%s`", name);
2568 return NULL;
2571 static bool
2572 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2574 char buf[SIZEOF_STR];
2575 int argc;
2577 argv_free(*dst_argv);
2579 for (argc = 0; src_argv[argc]; argc++) {
2580 const char *arg = src_argv[argc];
2581 size_t bufpos = 0;
2583 if (!strcmp(arg, "%(fileargs)")) {
2584 if (!argv_append_array(dst_argv, opt_file_argv))
2585 break;
2586 continue;
2588 } else if (!strcmp(arg, "%(diffargs)")) {
2589 if (!argv_append_array(dst_argv, opt_diff_argv))
2590 break;
2591 continue;
2593 } else if (!strcmp(arg, "%(blameargs)")) {
2594 if (!argv_append_array(dst_argv, opt_blame_argv))
2595 break;
2596 continue;
2598 } else if (!strcmp(arg, "%(revargs)") ||
2599 (first && !strcmp(arg, "%(commit)"))) {
2600 if (!argv_append_array(dst_argv, opt_rev_argv))
2601 break;
2602 continue;
2605 while (arg) {
2606 char *next = strstr(arg, "%(");
2607 int len = next - arg;
2608 const char *value;
2610 if (!next) {
2611 len = strlen(arg);
2612 value = "";
2614 } else {
2615 value = format_arg(next);
2617 if (!value) {
2618 return FALSE;
2622 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2623 return FALSE;
2625 arg = next ? strchr(next, ')') + 1 : NULL;
2628 if (!argv_append(dst_argv, buf))
2629 break;
2632 return src_argv[argc] == NULL;
2635 static bool
2636 restore_view_position(struct view *view)
2638 /* A view without a previous view is the first view */
2639 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2640 select_view_line(view, opt_lineno - 1);
2641 opt_lineno = 0;
2644 if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2645 return FALSE;
2647 /* Changing the view position cancels the restoring. */
2648 /* FIXME: Changing back to the first line is not detected. */
2649 if (view->offset != 0 || view->lineno != 0) {
2650 view->p_restore = FALSE;
2651 return FALSE;
2654 if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2655 view_is_displayed(view))
2656 werase(view->win);
2658 view->yoffset = view->p_yoffset;
2659 view->p_restore = FALSE;
2661 return TRUE;
2664 static void
2665 end_update(struct view *view, bool force)
2667 if (!view->pipe)
2668 return;
2669 while (!view->ops->read(view, NULL))
2670 if (!force)
2671 return;
2672 if (force)
2673 io_kill(view->pipe);
2674 io_done(view->pipe);
2675 view->pipe = NULL;
2678 static void
2679 setup_update(struct view *view, const char *vid)
2681 reset_view(view);
2682 string_copy_rev(view->vid, vid);
2683 view->pipe = &view->io;
2684 view->start_time = time(NULL);
2687 static bool
2688 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2690 bool extra = !!(flags & (OPEN_EXTRA));
2691 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2692 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2694 if (!reload && !strcmp(view->vid, view->id))
2695 return TRUE;
2697 if (view->pipe) {
2698 if (extra)
2699 io_done(view->pipe);
2700 else
2701 end_update(view, TRUE);
2704 if (!refresh && argv) {
2705 view->dir = dir;
2706 if (!format_argv(&view->argv, argv, !view->prev))
2707 return FALSE;
2709 /* Put the current ref_* value to the view title ref
2710 * member. This is needed by the blob view. Most other
2711 * views sets it automatically after loading because the
2712 * first line is a commit line. */
2713 string_copy_rev(view->ref, view->id);
2716 if (view->argv && view->argv[0] &&
2717 !io_run(&view->io, IO_RD, view->dir, view->argv))
2718 return FALSE;
2720 if (!extra)
2721 setup_update(view, view->id);
2723 return TRUE;
2726 static bool
2727 update_view(struct view *view)
2729 char out_buffer[BUFSIZ * 2];
2730 char *line;
2731 /* Clear the view and redraw everything since the tree sorting
2732 * might have rearranged things. */
2733 bool redraw = view->lines == 0;
2734 bool can_read = TRUE;
2736 if (!view->pipe)
2737 return TRUE;
2739 if (!io_can_read(view->pipe, FALSE)) {
2740 if (view->lines == 0 && view_is_displayed(view)) {
2741 time_t secs = time(NULL) - view->start_time;
2743 if (secs > 1 && secs > view->update_secs) {
2744 if (view->update_secs == 0)
2745 redraw_view(view);
2746 update_view_title(view);
2747 view->update_secs = secs;
2750 return TRUE;
2753 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2754 if (opt_iconv_in != ICONV_NONE) {
2755 ICONV_CONST char *inbuf = line;
2756 size_t inlen = strlen(line) + 1;
2758 char *outbuf = out_buffer;
2759 size_t outlen = sizeof(out_buffer);
2761 size_t ret;
2763 ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2764 if (ret != (size_t) -1)
2765 line = out_buffer;
2768 if (!view->ops->read(view, line)) {
2769 report("Allocation failure");
2770 end_update(view, TRUE);
2771 return FALSE;
2776 unsigned long lines = view->lines;
2777 int digits;
2779 for (digits = 0; lines; digits++)
2780 lines /= 10;
2782 /* Keep the displayed view in sync with line number scaling. */
2783 if (digits != view->digits) {
2784 view->digits = digits;
2785 if (opt_line_number || view->type == VIEW_BLAME)
2786 redraw = TRUE;
2790 if (io_error(view->pipe)) {
2791 report("Failed to read: %s", io_strerror(view->pipe));
2792 end_update(view, TRUE);
2794 } else if (io_eof(view->pipe)) {
2795 if (view_is_displayed(view))
2796 report("");
2797 end_update(view, FALSE);
2800 if (restore_view_position(view))
2801 redraw = TRUE;
2803 if (!view_is_displayed(view))
2804 return TRUE;
2806 if (redraw)
2807 redraw_view_from(view, 0);
2808 else
2809 redraw_view_dirty(view);
2811 /* Update the title _after_ the redraw so that if the redraw picks up a
2812 * commit reference in view->ref it'll be available here. */
2813 update_view_title(view);
2814 return TRUE;
2817 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2819 static struct line *
2820 add_line_data(struct view *view, void *data, enum line_type type)
2822 struct line *line;
2824 if (!realloc_lines(&view->line, view->lines, 1))
2825 return NULL;
2827 line = &view->line[view->lines++];
2828 memset(line, 0, sizeof(*line));
2829 line->type = type;
2830 line->data = data;
2831 line->dirty = 1;
2833 return line;
2836 static struct line *
2837 add_line_text(struct view *view, const char *text, enum line_type type)
2839 char *data = text ? strdup(text) : NULL;
2841 return data ? add_line_data(view, data, type) : NULL;
2844 static struct line *
2845 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2847 char buf[SIZEOF_STR];
2848 int retval;
2850 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval);
2851 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
2855 * View opening
2858 static void
2859 load_view(struct view *view, enum open_flags flags)
2861 if (view->pipe)
2862 end_update(view, TRUE);
2863 if (view->ops->private_size) {
2864 if (!view->private)
2865 view->private = calloc(1, view->ops->private_size);
2866 else
2867 memset(view->private, 0, view->ops->private_size);
2869 if (!view->ops->open(view, flags)) {
2870 report("Failed to load %s view", view->name);
2871 return;
2873 restore_view_position(view);
2875 if (view->pipe && view->lines == 0) {
2876 /* Clear the old view and let the incremental updating refill
2877 * the screen. */
2878 werase(view->win);
2879 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2880 report("");
2881 } else if (view_is_displayed(view)) {
2882 redraw_view(view);
2883 report("");
2887 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2888 #define reload_view(view) load_view(view, OPEN_RELOAD)
2890 static void
2891 split_view(struct view *prev, struct view *view)
2893 display[1] = view;
2894 current_view = 1;
2895 view->parent = prev;
2896 resize_display();
2898 if (prev->lineno - prev->offset >= prev->height) {
2899 /* Take the title line into account. */
2900 int lines = prev->lineno - prev->offset - prev->height + 1;
2902 /* Scroll the view that was split if the current line is
2903 * outside the new limited view. */
2904 do_scroll_view(prev, lines);
2907 if (view != prev && view_is_displayed(prev)) {
2908 /* "Blur" the previous view. */
2909 update_view_title(prev);
2913 static void
2914 open_view(struct view *prev, enum request request, enum open_flags flags)
2916 bool split = !!(flags & OPEN_SPLIT);
2917 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
2918 struct view *view = VIEW(request);
2919 int nviews = displayed_views();
2921 assert(flags ^ OPEN_REFRESH);
2923 if (view == prev && nviews == 1 && !reload) {
2924 report("Already in %s view", view->name);
2925 return;
2928 if (view->git_dir && !opt_git_dir[0]) {
2929 report("The %s view is disabled in pager view", view->name);
2930 return;
2933 if (split) {
2934 split_view(prev, view);
2935 } else {
2936 maximize_view(view, FALSE);
2939 /* No prev signals that this is the first loaded view. */
2940 if (prev && view != prev) {
2941 view->prev = prev;
2944 load_view(view, flags);
2947 static void
2948 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
2950 enum request request = view - views + REQ_OFFSET + 1;
2952 if (view->pipe)
2953 end_update(view, TRUE);
2954 view->dir = dir;
2956 if (!argv_copy(&view->argv, argv)) {
2957 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
2958 } else {
2959 open_view(prev, request, flags | OPEN_PREPARED);
2963 static void
2964 open_external_viewer(const char *argv[], const char *dir)
2966 def_prog_mode(); /* save current tty modes */
2967 endwin(); /* restore original tty modes */
2968 io_run_fg(argv, dir);
2969 fprintf(stderr, "Press Enter to continue");
2970 getc(opt_tty);
2971 reset_prog_mode();
2972 redraw_display(TRUE);
2975 static void
2976 open_mergetool(const char *file)
2978 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2980 open_external_viewer(mergetool_argv, opt_cdup);
2983 static void
2984 open_editor(const char *file)
2986 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
2987 char editor_cmd[SIZEOF_STR];
2988 const char *editor;
2989 int argc = 0;
2991 editor = getenv("GIT_EDITOR");
2992 if (!editor && *opt_editor)
2993 editor = opt_editor;
2994 if (!editor)
2995 editor = getenv("VISUAL");
2996 if (!editor)
2997 editor = getenv("EDITOR");
2998 if (!editor)
2999 editor = "vi";
3001 string_ncopy(editor_cmd, editor, strlen(editor));
3002 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3003 report("Failed to read editor command");
3004 return;
3007 editor_argv[argc] = file;
3008 open_external_viewer(editor_argv, opt_cdup);
3011 static void
3012 open_run_request(enum request request)
3014 struct run_request *req = get_run_request(request);
3015 const char **argv = NULL;
3017 if (!req) {
3018 report("Unknown run request");
3019 return;
3022 if (format_argv(&argv, req->argv, FALSE))
3023 open_external_viewer(argv, NULL);
3024 if (argv)
3025 argv_free(argv);
3026 free(argv);
3030 * User request switch noodle
3033 static int
3034 view_driver(struct view *view, enum request request)
3036 int i;
3038 if (request == REQ_NONE)
3039 return TRUE;
3041 if (request > REQ_NONE) {
3042 open_run_request(request);
3043 view_request(view, REQ_REFRESH);
3044 return TRUE;
3047 request = view_request(view, request);
3048 if (request == REQ_NONE)
3049 return TRUE;
3051 switch (request) {
3052 case REQ_MOVE_UP:
3053 case REQ_MOVE_DOWN:
3054 case REQ_MOVE_PAGE_UP:
3055 case REQ_MOVE_PAGE_DOWN:
3056 case REQ_MOVE_FIRST_LINE:
3057 case REQ_MOVE_LAST_LINE:
3058 move_view(view, request);
3059 break;
3061 case REQ_SCROLL_FIRST_COL:
3062 case REQ_SCROLL_LEFT:
3063 case REQ_SCROLL_RIGHT:
3064 case REQ_SCROLL_LINE_DOWN:
3065 case REQ_SCROLL_LINE_UP:
3066 case REQ_SCROLL_PAGE_DOWN:
3067 case REQ_SCROLL_PAGE_UP:
3068 scroll_view(view, request);
3069 break;
3071 case REQ_VIEW_BLAME:
3072 if (!opt_file[0]) {
3073 report("No file chosen, press %s to open tree view",
3074 get_key(view->keymap, REQ_VIEW_TREE));
3075 break;
3077 open_view(view, request, OPEN_DEFAULT);
3078 break;
3080 case REQ_VIEW_BLOB:
3081 if (!ref_blob[0]) {
3082 report("No file chosen, press %s to open tree view",
3083 get_key(view->keymap, REQ_VIEW_TREE));
3084 break;
3086 open_view(view, request, OPEN_DEFAULT);
3087 break;
3089 case REQ_VIEW_PAGER:
3090 if (view == NULL) {
3091 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
3092 die("Failed to open stdin");
3093 open_view(view, request, OPEN_PREPARED);
3094 break;
3097 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
3098 report("No pager content, press %s to run command from prompt",
3099 get_key(view->keymap, REQ_PROMPT));
3100 break;
3102 open_view(view, request, OPEN_DEFAULT);
3103 break;
3105 case REQ_VIEW_STAGE:
3106 if (!VIEW(REQ_VIEW_STAGE)->lines) {
3107 report("No stage content, press %s to open the status view and choose file",
3108 get_key(view->keymap, REQ_VIEW_STATUS));
3109 break;
3111 open_view(view, request, OPEN_DEFAULT);
3112 break;
3114 case REQ_VIEW_STATUS:
3115 if (opt_is_inside_work_tree == FALSE) {
3116 report("The status view requires a working tree");
3117 break;
3119 open_view(view, request, OPEN_DEFAULT);
3120 break;
3122 case REQ_VIEW_MAIN:
3123 case REQ_VIEW_DIFF:
3124 case REQ_VIEW_LOG:
3125 case REQ_VIEW_TREE:
3126 case REQ_VIEW_HELP:
3127 case REQ_VIEW_BRANCH:
3128 open_view(view, request, OPEN_DEFAULT);
3129 break;
3131 case REQ_NEXT:
3132 case REQ_PREVIOUS:
3133 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
3135 if (view->parent) {
3136 int line;
3138 view = view->parent;
3139 line = view->lineno;
3140 move_view(view, request);
3141 if (view_is_displayed(view))
3142 update_view_title(view);
3143 if (line != view->lineno)
3144 view_request(view, REQ_ENTER);
3145 } else {
3146 move_view(view, request);
3148 break;
3150 case REQ_VIEW_NEXT:
3152 int nviews = displayed_views();
3153 int next_view = (current_view + 1) % nviews;
3155 if (next_view == current_view) {
3156 report("Only one view is displayed");
3157 break;
3160 current_view = next_view;
3161 /* Blur out the title of the previous view. */
3162 update_view_title(view);
3163 report("");
3164 break;
3166 case REQ_REFRESH:
3167 report("Refreshing is not yet supported for the %s view", view->name);
3168 break;
3170 case REQ_MAXIMIZE:
3171 if (displayed_views() == 2)
3172 maximize_view(view, TRUE);
3173 break;
3175 case REQ_OPTIONS:
3176 case REQ_TOGGLE_LINENO:
3177 case REQ_TOGGLE_DATE:
3178 case REQ_TOGGLE_AUTHOR:
3179 case REQ_TOGGLE_FILENAME:
3180 case REQ_TOGGLE_GRAPHIC:
3181 case REQ_TOGGLE_REV_GRAPH:
3182 case REQ_TOGGLE_REFS:
3183 toggle_option(request);
3184 break;
3186 case REQ_TOGGLE_SORT_FIELD:
3187 case REQ_TOGGLE_SORT_ORDER:
3188 report("Sorting is not yet supported for the %s view", view->name);
3189 break;
3191 case REQ_DIFF_CONTEXT_UP:
3192 case REQ_DIFF_CONTEXT_DOWN:
3193 report("Changing the diff context is not yet supported for the %s view", view->name);
3194 break;
3196 case REQ_SEARCH:
3197 case REQ_SEARCH_BACK:
3198 search_view(view, request);
3199 break;
3201 case REQ_FIND_NEXT:
3202 case REQ_FIND_PREV:
3203 find_next(view, request);
3204 break;
3206 case REQ_STOP_LOADING:
3207 foreach_view(view, i) {
3208 if (view->pipe)
3209 report("Stopped loading the %s view", view->name),
3210 end_update(view, TRUE);
3212 break;
3214 case REQ_SHOW_VERSION:
3215 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3216 return TRUE;
3218 case REQ_SCREEN_REDRAW:
3219 redraw_display(TRUE);
3220 break;
3222 case REQ_EDIT:
3223 report("Nothing to edit");
3224 break;
3226 case REQ_ENTER:
3227 report("Nothing to enter");
3228 break;
3230 case REQ_VIEW_CLOSE:
3231 /* XXX: Mark closed views by letting view->prev point to the
3232 * view itself. Parents to closed view should never be
3233 * followed. */
3234 if (view->prev && view->prev != view) {
3235 maximize_view(view->prev, TRUE);
3236 view->prev = view;
3237 break;
3239 /* Fall-through */
3240 case REQ_QUIT:
3241 return FALSE;
3243 default:
3244 report("Unknown key, press %s for help",
3245 get_key(view->keymap, REQ_VIEW_HELP));
3246 return TRUE;
3249 return TRUE;
3254 * View backend utilities
3257 enum sort_field {
3258 ORDERBY_NAME,
3259 ORDERBY_DATE,
3260 ORDERBY_AUTHOR,
3263 struct sort_state {
3264 const enum sort_field *fields;
3265 size_t size, current;
3266 bool reverse;
3269 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3270 #define get_sort_field(state) ((state).fields[(state).current])
3271 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3273 static void
3274 sort_view(struct view *view, enum request request, struct sort_state *state,
3275 int (*compare)(const void *, const void *))
3277 switch (request) {
3278 case REQ_TOGGLE_SORT_FIELD:
3279 state->current = (state->current + 1) % state->size;
3280 break;
3282 case REQ_TOGGLE_SORT_ORDER:
3283 state->reverse = !state->reverse;
3284 break;
3285 default:
3286 die("Not a sort request");
3289 qsort(view->line, view->lines, sizeof(*view->line), compare);
3290 redraw_view(view);
3293 static bool
3294 update_diff_context(enum request request)
3296 int diff_context = opt_diff_context;
3298 switch (request) {
3299 case REQ_DIFF_CONTEXT_UP:
3300 opt_diff_context += 1;
3301 update_diff_context_arg(opt_diff_context);
3302 break;
3304 case REQ_DIFF_CONTEXT_DOWN:
3305 if (opt_diff_context == 0) {
3306 report("Diff context cannot be less than zero");
3307 break;
3309 opt_diff_context -= 1;
3310 update_diff_context_arg(opt_diff_context);
3311 break;
3313 default:
3314 die("Not a diff context request");
3317 return diff_context != opt_diff_context;
3320 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3322 /* Small author cache to reduce memory consumption. It uses binary
3323 * search to lookup or find place to position new entries. No entries
3324 * are ever freed. */
3325 static const char *
3326 get_author(const char *name)
3328 static const char **authors;
3329 static size_t authors_size;
3330 int from = 0, to = authors_size - 1;
3332 while (from <= to) {
3333 size_t pos = (to + from) / 2;
3334 int cmp = strcmp(name, authors[pos]);
3336 if (!cmp)
3337 return authors[pos];
3339 if (cmp < 0)
3340 to = pos - 1;
3341 else
3342 from = pos + 1;
3345 if (!realloc_authors(&authors, authors_size, 1))
3346 return NULL;
3347 name = strdup(name);
3348 if (!name)
3349 return NULL;
3351 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3352 authors[from] = name;
3353 authors_size++;
3355 return name;
3358 static void
3359 parse_timesec(struct time *time, const char *sec)
3361 time->sec = (time_t) atol(sec);
3364 static void
3365 parse_timezone(struct time *time, const char *zone)
3367 long tz;
3369 tz = ('0' - zone[1]) * 60 * 60 * 10;
3370 tz += ('0' - zone[2]) * 60 * 60;
3371 tz += ('0' - zone[3]) * 60 * 10;
3372 tz += ('0' - zone[4]) * 60;
3374 if (zone[0] == '-')
3375 tz = -tz;
3377 time->tz = tz;
3378 time->sec -= tz;
3381 /* Parse author lines where the name may be empty:
3382 * author <email@address.tld> 1138474660 +0100
3384 static void
3385 parse_author_line(char *ident, const char **author, struct time *time)
3387 char *nameend = strchr(ident, '<');
3388 char *emailend = strchr(ident, '>');
3390 if (nameend && emailend)
3391 *nameend = *emailend = 0;
3392 ident = chomp_string(ident);
3393 if (!*ident) {
3394 if (nameend)
3395 ident = chomp_string(nameend + 1);
3396 if (!*ident)
3397 ident = "Unknown";
3400 *author = get_author(ident);
3402 /* Parse epoch and timezone */
3403 if (emailend && emailend[1] == ' ') {
3404 char *secs = emailend + 2;
3405 char *zone = strchr(secs, ' ');
3407 parse_timesec(time, secs);
3409 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3410 parse_timezone(time, zone + 1);
3414 static struct line *
3415 find_prev_line_by_type(struct view *view, struct line *line, enum line_type type)
3417 for (; view->line < line; line--)
3418 if (line->type == type)
3419 return line;
3421 return NULL;
3425 * Blame
3428 struct blame_commit {
3429 char id[SIZEOF_REV]; /* SHA1 ID. */
3430 char title[128]; /* First line of the commit message. */
3431 const char *author; /* Author of the commit. */
3432 struct time time; /* Date from the author ident. */
3433 char filename[128]; /* Name of file. */
3434 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3435 char parent_filename[128]; /* Parent/previous name of file. */
3438 struct blame_header {
3439 char id[SIZEOF_REV]; /* SHA1 ID. */
3440 size_t orig_lineno;
3441 size_t lineno;
3442 size_t group;
3445 static bool
3446 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3448 const char *pos = *posref;
3450 *posref = NULL;
3451 pos = strchr(pos + 1, ' ');
3452 if (!pos || !isdigit(pos[1]))
3453 return FALSE;
3454 *number = atoi(pos + 1);
3455 if (*number < min || *number > max)
3456 return FALSE;
3458 *posref = pos;
3459 return TRUE;
3462 static bool
3463 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3465 const char *pos = text + SIZEOF_REV - 2;
3467 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3468 return FALSE;
3470 string_ncopy(header->id, text, SIZEOF_REV);
3472 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3473 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3474 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3475 return FALSE;
3477 return TRUE;
3480 static bool
3481 match_blame_header(const char *name, char **line)
3483 size_t namelen = strlen(name);
3484 bool matched = !strncmp(name, *line, namelen);
3486 if (matched)
3487 *line += namelen;
3489 return matched;
3492 static bool
3493 parse_blame_info(struct blame_commit *commit, char *line)
3495 if (match_blame_header("author ", &line)) {
3496 commit->author = get_author(line);
3498 } else if (match_blame_header("author-time ", &line)) {
3499 parse_timesec(&commit->time, line);
3501 } else if (match_blame_header("author-tz ", &line)) {
3502 parse_timezone(&commit->time, line);
3504 } else if (match_blame_header("summary ", &line)) {
3505 string_ncopy(commit->title, line, strlen(line));
3507 } else if (match_blame_header("previous ", &line)) {
3508 if (strlen(line) <= SIZEOF_REV)
3509 return FALSE;
3510 string_copy_rev(commit->parent_id, line);
3511 line += SIZEOF_REV;
3512 string_ncopy(commit->parent_filename, line, strlen(line));
3514 } else if (match_blame_header("filename ", &line)) {
3515 string_ncopy(commit->filename, line, strlen(line));
3516 return TRUE;
3519 return FALSE;
3523 * Pager backend
3526 static bool
3527 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3529 if (opt_line_number && draw_lineno(view, lineno))
3530 return TRUE;
3532 draw_text(view, line->type, line->data);
3533 return TRUE;
3536 static bool
3537 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3539 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3540 char ref[SIZEOF_STR];
3542 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3543 return TRUE;
3545 /* This is the only fatal call, since it can "corrupt" the buffer. */
3546 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3547 return FALSE;
3549 return TRUE;
3552 static void
3553 add_pager_refs(struct view *view, struct line *line)
3555 char buf[SIZEOF_STR];
3556 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3557 struct ref_list *list;
3558 size_t bufpos = 0, i;
3559 const char *sep = "Refs: ";
3560 bool is_tag = FALSE;
3562 assert(line->type == LINE_COMMIT);
3564 list = get_ref_list(commit_id);
3565 if (!list) {
3566 if (view->type == VIEW_DIFF)
3567 goto try_add_describe_ref;
3568 return;
3571 for (i = 0; i < list->size; i++) {
3572 struct ref *ref = list->refs[i];
3573 const char *fmt = ref->tag ? "%s[%s]" :
3574 ref->remote ? "%s<%s>" : "%s%s";
3576 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3577 return;
3578 sep = ", ";
3579 if (ref->tag)
3580 is_tag = TRUE;
3583 if (!is_tag && view->type == VIEW_DIFF) {
3584 try_add_describe_ref:
3585 /* Add <tag>-g<commit_id> "fake" reference. */
3586 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3587 return;
3590 if (bufpos == 0)
3591 return;
3593 add_line_text(view, buf, LINE_PP_REFS);
3596 static bool
3597 pager_read(struct view *view, char *data)
3599 struct line *line;
3601 if (!data)
3602 return TRUE;
3604 line = add_line_text(view, data, get_line_type(data));
3605 if (!line)
3606 return FALSE;
3608 if (line->type == LINE_COMMIT &&
3609 (view->type == VIEW_DIFF ||
3610 view->type == VIEW_LOG))
3611 add_pager_refs(view, line);
3613 return TRUE;
3616 static enum request
3617 pager_request(struct view *view, enum request request, struct line *line)
3619 int split = 0;
3621 if (request != REQ_ENTER)
3622 return request;
3624 if (line->type == LINE_COMMIT &&
3625 (view->type == VIEW_LOG ||
3626 view->type == VIEW_PAGER)) {
3627 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3628 split = 1;
3631 /* Always scroll the view even if it was split. That way
3632 * you can use Enter to scroll through the log view and
3633 * split open each commit diff. */
3634 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3636 /* FIXME: A minor workaround. Scrolling the view will call report("")
3637 * but if we are scrolling a non-current view this won't properly
3638 * update the view title. */
3639 if (split)
3640 update_view_title(view);
3642 return REQ_NONE;
3645 static bool
3646 pager_grep(struct view *view, struct line *line)
3648 const char *text[] = { line->data, NULL };
3650 return grep_text(view, text);
3653 static void
3654 pager_select(struct view *view, struct line *line)
3656 if (line->type == LINE_COMMIT) {
3657 char *text = (char *)line->data + STRING_SIZE("commit ");
3659 if (view->type != VIEW_PAGER)
3660 string_copy_rev(view->ref, text);
3661 string_copy_rev(ref_commit, text);
3665 static bool
3666 pager_open(struct view *view, enum open_flags flags)
3668 return begin_update(view, NULL, NULL, flags);
3671 static struct view_ops pager_ops = {
3672 "line",
3674 pager_open,
3675 pager_read,
3676 pager_draw,
3677 pager_request,
3678 pager_grep,
3679 pager_select,
3682 static bool
3683 log_open(struct view *view, enum open_flags flags)
3685 static const char *log_argv[] = {
3686 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3689 return begin_update(view, NULL, log_argv, flags);
3692 static enum request
3693 log_request(struct view *view, enum request request, struct line *line)
3695 switch (request) {
3696 case REQ_REFRESH:
3697 load_refs();
3698 refresh_view(view);
3699 return REQ_NONE;
3700 default:
3701 return pager_request(view, request, line);
3705 static struct view_ops log_ops = {
3706 "line",
3708 log_open,
3709 pager_read,
3710 pager_draw,
3711 log_request,
3712 pager_grep,
3713 pager_select,
3716 struct diff_state {
3717 bool reading_diff_stat;
3720 static bool
3721 diff_open(struct view *view, enum open_flags flags)
3723 static const char *diff_argv[] = {
3724 "git", "show", "--pretty=fuller", "--no-color", "--root",
3725 "--patch-with-stat", "--find-copies-harder", "-C",
3726 opt_notes_arg, opt_diff_context_arg, "%(diffargs)",
3727 "%(commit)", "--", "%(fileargs)", NULL
3730 return begin_update(view, NULL, diff_argv, flags);
3733 static bool
3734 diff_common_read(struct view *view, char *data, struct diff_state *state)
3736 if (state->reading_diff_stat) {
3737 size_t len = strlen(data);
3738 char *pipe = strchr(data, '|');
3739 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3740 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3742 if (pipe && (has_histogram || has_bin_diff)) {
3743 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3744 } else {
3745 state->reading_diff_stat = FALSE;
3748 } else if (!strcmp(data, "---")) {
3749 state->reading_diff_stat = TRUE;
3752 return pager_read(view, data);
3755 static enum request
3756 diff_common_enter(struct view *view, enum request request, struct line *line)
3758 if (line->type == LINE_DIFF_STAT) {
3759 int file_number = 0;
3761 while (line >= view->line && line->type == LINE_DIFF_STAT) {
3762 file_number++;
3763 line--;
3766 while (line < view->line + view->lines) {
3767 if (line->type == LINE_DIFF_HEADER) {
3768 if (file_number == 1) {
3769 break;
3771 file_number--;
3773 line++;
3777 select_view_line(view, line - view->line);
3778 report("");
3779 return REQ_NONE;
3781 } else {
3782 return pager_request(view, request, line);
3786 static bool
3787 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
3789 char *sep = strchr(*text, c);
3791 if (sep != NULL) {
3792 *sep = 0;
3793 draw_text(view, *type, *text);
3794 *sep = c;
3795 *text = sep;
3796 *type = next_type;
3799 return sep != NULL;
3802 static bool
3803 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
3805 char *text = line->data;
3806 enum line_type type = line->type;
3808 if (opt_line_number && draw_lineno(view, lineno))
3809 return TRUE;
3811 if (type == LINE_DIFF_STAT) {
3812 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
3813 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
3814 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
3815 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
3816 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
3817 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
3818 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
3820 } else {
3821 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
3822 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
3826 draw_text(view, type, text);
3827 return TRUE;
3830 static bool
3831 diff_read(struct view *view, char *data)
3833 struct diff_state *state = view->private;
3835 if (!data) {
3836 /* Fall back to retry if no diff will be shown. */
3837 if (view->lines == 0 && opt_file_argv) {
3838 int pos = argv_size(view->argv)
3839 - argv_size(opt_file_argv) - 1;
3841 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3842 for (; view->argv[pos]; pos++) {
3843 free((void *) view->argv[pos]);
3844 view->argv[pos] = NULL;
3847 if (view->pipe)
3848 io_done(view->pipe);
3849 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3850 return FALSE;
3853 return TRUE;
3856 return diff_common_read(view, data, state);
3859 static bool
3860 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
3861 struct blame_header *header, struct blame_commit *commit)
3863 char line_arg[SIZEOF_STR];
3864 const char *blame_argv[] = {
3865 "git", "blame", "-p", line_arg, ref, "--", file, NULL
3867 struct io io;
3868 bool ok = FALSE;
3869 char *buf;
3871 if (!string_format(line_arg, "-L%d,+1", lineno))
3872 return FALSE;
3874 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
3875 return FALSE;
3877 while ((buf = io_get(&io, '\n', TRUE))) {
3878 if (header) {
3879 if (!parse_blame_header(header, buf, 9999999))
3880 break;
3881 header = NULL;
3883 } else if (parse_blame_info(commit, buf)) {
3884 ok = TRUE;
3885 break;
3889 if (io_error(&io))
3890 ok = FALSE;
3892 io_done(&io);
3893 return ok;
3896 static bool
3897 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
3899 return prefixcmp(chunk, "@@ -") ||
3900 !(chunk = strchr(chunk, marker)) ||
3901 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
3904 static enum request
3905 diff_trace_origin(struct view *view, struct line *line)
3907 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
3908 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
3909 const char *chunk_data;
3910 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
3911 int lineno = 0;
3912 const char *file = NULL;
3913 char ref[SIZEOF_REF];
3914 struct blame_header header;
3915 struct blame_commit commit;
3917 if (!diff || !chunk || chunk == line) {
3918 report("The line to trace must be inside a diff chunk");
3919 return REQ_NONE;
3922 for (; diff < line && !file; diff++) {
3923 const char *data = diff->data;
3925 if (!prefixcmp(data, "--- a/")) {
3926 file = data + STRING_SIZE("--- a/");
3927 break;
3931 if (diff == line || !file) {
3932 report("Failed to read the file name");
3933 return REQ_NONE;
3936 chunk_data = chunk->data;
3938 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
3939 report("Failed to read the line number");
3940 return REQ_NONE;
3943 if (lineno == 0) {
3944 report("This is the origin of the line");
3945 return REQ_NONE;
3948 for (chunk += 1; chunk < line; chunk++) {
3949 if (chunk->type == LINE_DIFF_ADD) {
3950 lineno += chunk_marker == '+';
3951 } else if (chunk->type == LINE_DIFF_DEL) {
3952 lineno += chunk_marker == '-';
3953 } else {
3954 lineno++;
3958 if (chunk_marker == '+')
3959 string_copy(ref, view->vid);
3960 else
3961 string_format(ref, "%s^", view->vid);
3963 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
3964 report("Failed to read blame data");
3965 return REQ_NONE;
3968 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
3969 string_copy(opt_ref, header.id);
3970 opt_goto_line = header.orig_lineno - 1;
3972 return REQ_VIEW_BLAME;
3975 static enum request
3976 diff_request(struct view *view, enum request request, struct line *line)
3978 switch (request) {
3979 case REQ_VIEW_BLAME:
3980 return diff_trace_origin(view, line);
3982 case REQ_DIFF_CONTEXT_UP:
3983 case REQ_DIFF_CONTEXT_DOWN:
3984 if (!update_diff_context(request))
3985 return REQ_NONE;
3986 reload_view(view);
3987 return REQ_NONE;
3989 case REQ_ENTER:
3990 return diff_common_enter(view, request, line);
3992 default:
3993 return pager_request(view, request, line);
3997 static void
3998 diff_select(struct view *view, struct line *line)
4000 if (line->type == LINE_DIFF_STAT) {
4001 const char *key = get_key(KEYMAP_DIFF, REQ_ENTER);
4003 string_format(view->ref, "Press '%s' to jump to file diff", key);
4004 } else {
4005 string_ncopy(view->ref, view->id, strlen(view->id));
4006 return pager_select(view, line);
4010 static struct view_ops diff_ops = {
4011 "line",
4012 sizeof(struct diff_state),
4013 diff_open,
4014 diff_read,
4015 diff_common_draw,
4016 diff_request,
4017 pager_grep,
4018 diff_select,
4022 * Help backend
4025 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
4027 static bool
4028 help_open_keymap_title(struct view *view, enum keymap keymap)
4030 struct line *line;
4032 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
4033 help_keymap_hidden[keymap] ? '+' : '-',
4034 enum_name(keymap_map[keymap]));
4035 if (line)
4036 line->other = keymap;
4038 return help_keymap_hidden[keymap];
4041 static void
4042 help_open_keymap(struct view *view, enum keymap keymap)
4044 const char *group = NULL;
4045 char buf[SIZEOF_STR];
4046 size_t bufpos;
4047 bool add_title = TRUE;
4048 int i;
4050 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4051 const char *key = NULL;
4053 if (req_info[i].request == REQ_NONE)
4054 continue;
4056 if (!req_info[i].request) {
4057 group = req_info[i].help;
4058 continue;
4061 key = get_keys(keymap, req_info[i].request, TRUE);
4062 if (!key || !*key)
4063 continue;
4065 if (add_title && help_open_keymap_title(view, keymap))
4066 return;
4067 add_title = FALSE;
4069 if (group) {
4070 add_line_text(view, group, LINE_HELP_GROUP);
4071 group = NULL;
4074 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4075 enum_name(req_info[i]), req_info[i].help);
4078 group = "External commands:";
4080 for (i = 0; i < run_requests; i++) {
4081 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4082 const char *key;
4083 int argc;
4085 if (!req || req->keymap != keymap)
4086 continue;
4088 key = get_key_name(req->key);
4089 if (!*key)
4090 key = "(no key defined)";
4092 if (add_title && help_open_keymap_title(view, keymap))
4093 return;
4094 if (group) {
4095 add_line_text(view, group, LINE_HELP_GROUP);
4096 group = NULL;
4099 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
4100 if (!string_format_from(buf, &bufpos, "%s%s",
4101 argc ? " " : "", req->argv[argc]))
4102 return;
4104 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4108 static bool
4109 help_open(struct view *view, enum open_flags flags)
4111 enum keymap keymap;
4113 reset_view(view);
4114 view->p_restore = TRUE;
4115 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4116 add_line_text(view, "", LINE_DEFAULT);
4118 for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
4119 help_open_keymap(view, keymap);
4121 return TRUE;
4124 static enum request
4125 help_request(struct view *view, enum request request, struct line *line)
4127 switch (request) {
4128 case REQ_ENTER:
4129 if (line->type == LINE_HELP_KEYMAP) {
4130 help_keymap_hidden[line->other] =
4131 !help_keymap_hidden[line->other];
4132 refresh_view(view);
4135 return REQ_NONE;
4136 default:
4137 return pager_request(view, request, line);
4141 static struct view_ops help_ops = {
4142 "line",
4144 help_open,
4145 NULL,
4146 pager_draw,
4147 help_request,
4148 pager_grep,
4149 pager_select,
4154 * Tree backend
4157 struct tree_stack_entry {
4158 struct tree_stack_entry *prev; /* Entry below this in the stack */
4159 unsigned long lineno; /* Line number to restore */
4160 char *name; /* Position of name in opt_path */
4163 /* The top of the path stack. */
4164 static struct tree_stack_entry *tree_stack = NULL;
4165 unsigned long tree_lineno = 0;
4167 static void
4168 pop_tree_stack_entry(void)
4170 struct tree_stack_entry *entry = tree_stack;
4172 tree_lineno = entry->lineno;
4173 entry->name[0] = 0;
4174 tree_stack = entry->prev;
4175 free(entry);
4178 static void
4179 push_tree_stack_entry(const char *name, unsigned long lineno)
4181 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4182 size_t pathlen = strlen(opt_path);
4184 if (!entry)
4185 return;
4187 entry->prev = tree_stack;
4188 entry->name = opt_path + pathlen;
4189 tree_stack = entry;
4191 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4192 pop_tree_stack_entry();
4193 return;
4196 /* Move the current line to the first tree entry. */
4197 tree_lineno = 1;
4198 entry->lineno = lineno;
4201 /* Parse output from git-ls-tree(1):
4203 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4206 #define SIZEOF_TREE_ATTR \
4207 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4209 #define SIZEOF_TREE_MODE \
4210 STRING_SIZE("100644 ")
4212 #define TREE_ID_OFFSET \
4213 STRING_SIZE("100644 blob ")
4215 struct tree_entry {
4216 char id[SIZEOF_REV];
4217 mode_t mode;
4218 struct time time; /* Date from the author ident. */
4219 const char *author; /* Author of the commit. */
4220 char name[1];
4223 struct tree_state {
4224 const char *author_name;
4225 struct time author_time;
4226 bool read_date;
4229 static const char *
4230 tree_path(const struct line *line)
4232 return ((struct tree_entry *) line->data)->name;
4235 static int
4236 tree_compare_entry(const struct line *line1, const struct line *line2)
4238 if (line1->type != line2->type)
4239 return line1->type == LINE_TREE_DIR ? -1 : 1;
4240 return strcmp(tree_path(line1), tree_path(line2));
4243 static const enum sort_field tree_sort_fields[] = {
4244 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4246 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4248 static int
4249 tree_compare(const void *l1, const void *l2)
4251 const struct line *line1 = (const struct line *) l1;
4252 const struct line *line2 = (const struct line *) l2;
4253 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4254 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4256 if (line1->type == LINE_TREE_HEAD)
4257 return -1;
4258 if (line2->type == LINE_TREE_HEAD)
4259 return 1;
4261 switch (get_sort_field(tree_sort_state)) {
4262 case ORDERBY_DATE:
4263 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4265 case ORDERBY_AUTHOR:
4266 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4268 case ORDERBY_NAME:
4269 default:
4270 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4275 static struct line *
4276 tree_entry(struct view *view, enum line_type type, const char *path,
4277 const char *mode, const char *id)
4279 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4280 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4282 if (!entry || !line) {
4283 free(entry);
4284 return NULL;
4287 strncpy(entry->name, path, strlen(path));
4288 if (mode)
4289 entry->mode = strtoul(mode, NULL, 8);
4290 if (id)
4291 string_copy_rev(entry->id, id);
4293 return line;
4296 static bool
4297 tree_read_date(struct view *view, char *text, struct tree_state *state)
4299 if (!text && state->read_date) {
4300 state->read_date = FALSE;
4301 return TRUE;
4303 } else if (!text) {
4304 /* Find next entry to process */
4305 const char *log_file[] = {
4306 "git", "log", "--no-color", "--pretty=raw",
4307 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4310 if (!view->lines) {
4311 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4312 report("Tree is empty");
4313 return TRUE;
4316 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4317 report("Failed to load tree data");
4318 return TRUE;
4321 state->read_date = TRUE;
4322 return FALSE;
4324 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4325 parse_author_line(text + STRING_SIZE("author "),
4326 &state->author_name, &state->author_time);
4328 } else if (*text == ':') {
4329 char *pos;
4330 size_t annotated = 1;
4331 size_t i;
4333 pos = strchr(text, '\t');
4334 if (!pos)
4335 return TRUE;
4336 text = pos + 1;
4337 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4338 text += strlen(opt_path);
4339 pos = strchr(text, '/');
4340 if (pos)
4341 *pos = 0;
4343 for (i = 1; i < view->lines; i++) {
4344 struct line *line = &view->line[i];
4345 struct tree_entry *entry = line->data;
4347 annotated += !!entry->author;
4348 if (entry->author || strcmp(entry->name, text))
4349 continue;
4351 entry->author = state->author_name;
4352 entry->time = state->author_time;
4353 line->dirty = 1;
4354 break;
4357 if (annotated == view->lines)
4358 io_kill(view->pipe);
4360 return TRUE;
4363 static bool
4364 tree_read(struct view *view, char *text)
4366 struct tree_state *state = view->private;
4367 struct tree_entry *data;
4368 struct line *entry, *line;
4369 enum line_type type;
4370 size_t textlen = text ? strlen(text) : 0;
4371 char *path = text + SIZEOF_TREE_ATTR;
4373 if (state->read_date || !text)
4374 return tree_read_date(view, text, state);
4376 if (textlen <= SIZEOF_TREE_ATTR)
4377 return FALSE;
4378 if (view->lines == 0 &&
4379 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4380 return FALSE;
4382 /* Strip the path part ... */
4383 if (*opt_path) {
4384 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4385 size_t striplen = strlen(opt_path);
4387 if (pathlen > striplen)
4388 memmove(path, path + striplen,
4389 pathlen - striplen + 1);
4391 /* Insert "link" to parent directory. */
4392 if (view->lines == 1 &&
4393 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4394 return FALSE;
4397 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4398 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4399 if (!entry)
4400 return FALSE;
4401 data = entry->data;
4403 /* Skip "Directory ..." and ".." line. */
4404 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4405 if (tree_compare_entry(line, entry) <= 0)
4406 continue;
4408 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4410 line->data = data;
4411 line->type = type;
4412 for (; line <= entry; line++)
4413 line->dirty = line->cleareol = 1;
4414 return TRUE;
4417 if (tree_lineno > view->lineno) {
4418 view->lineno = tree_lineno;
4419 tree_lineno = 0;
4422 return TRUE;
4425 static bool
4426 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4428 struct tree_entry *entry = line->data;
4430 if (line->type == LINE_TREE_HEAD) {
4431 if (draw_text(view, line->type, "Directory path /"))
4432 return TRUE;
4433 } else {
4434 if (draw_mode(view, entry->mode))
4435 return TRUE;
4437 if (draw_author(view, entry->author))
4438 return TRUE;
4440 if (draw_date(view, &entry->time))
4441 return TRUE;
4444 draw_text(view, line->type, entry->name);
4445 return TRUE;
4448 static void
4449 open_blob_editor(const char *id)
4451 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4452 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4453 int fd = mkstemp(file);
4455 if (fd == -1)
4456 report("Failed to create temporary file");
4457 else if (!io_run_append(blob_argv, fd))
4458 report("Failed to save blob data to file");
4459 else
4460 open_editor(file);
4461 if (fd != -1)
4462 unlink(file);
4465 static enum request
4466 tree_request(struct view *view, enum request request, struct line *line)
4468 enum open_flags flags;
4469 struct tree_entry *entry = line->data;
4471 switch (request) {
4472 case REQ_VIEW_BLAME:
4473 if (line->type != LINE_TREE_FILE) {
4474 report("Blame only supported for files");
4475 return REQ_NONE;
4478 string_copy(opt_ref, view->vid);
4479 return request;
4481 case REQ_EDIT:
4482 if (line->type != LINE_TREE_FILE) {
4483 report("Edit only supported for files");
4484 } else if (!is_head_commit(view->vid)) {
4485 open_blob_editor(entry->id);
4486 } else {
4487 open_editor(opt_file);
4489 return REQ_NONE;
4491 case REQ_TOGGLE_SORT_FIELD:
4492 case REQ_TOGGLE_SORT_ORDER:
4493 sort_view(view, request, &tree_sort_state, tree_compare);
4494 return REQ_NONE;
4496 case REQ_PARENT:
4497 if (!*opt_path) {
4498 /* quit view if at top of tree */
4499 return REQ_VIEW_CLOSE;
4501 /* fake 'cd ..' */
4502 line = &view->line[1];
4503 break;
4505 case REQ_ENTER:
4506 break;
4508 default:
4509 return request;
4512 /* Cleanup the stack if the tree view is at a different tree. */
4513 while (!*opt_path && tree_stack)
4514 pop_tree_stack_entry();
4516 switch (line->type) {
4517 case LINE_TREE_DIR:
4518 /* Depending on whether it is a subdirectory or parent link
4519 * mangle the path buffer. */
4520 if (line == &view->line[1] && *opt_path) {
4521 pop_tree_stack_entry();
4523 } else {
4524 const char *basename = tree_path(line);
4526 push_tree_stack_entry(basename, view->lineno);
4529 /* Trees and subtrees share the same ID, so they are not not
4530 * unique like blobs. */
4531 flags = OPEN_RELOAD;
4532 request = REQ_VIEW_TREE;
4533 break;
4535 case LINE_TREE_FILE:
4536 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4537 request = REQ_VIEW_BLOB;
4538 break;
4540 default:
4541 return REQ_NONE;
4544 open_view(view, request, flags);
4545 if (request == REQ_VIEW_TREE)
4546 view->lineno = tree_lineno;
4548 return REQ_NONE;
4551 static bool
4552 tree_grep(struct view *view, struct line *line)
4554 struct tree_entry *entry = line->data;
4555 const char *text[] = {
4556 entry->name,
4557 mkauthor(entry->author, opt_author_cols, opt_author),
4558 mkdate(&entry->time, opt_date),
4559 NULL
4562 return grep_text(view, text);
4565 static void
4566 tree_select(struct view *view, struct line *line)
4568 struct tree_entry *entry = line->data;
4570 if (line->type == LINE_TREE_FILE) {
4571 string_copy_rev(ref_blob, entry->id);
4572 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4574 } else if (line->type != LINE_TREE_DIR) {
4575 return;
4578 string_copy_rev(view->ref, entry->id);
4581 static bool
4582 tree_open(struct view *view, enum open_flags flags)
4584 static const char *tree_argv[] = {
4585 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4588 if (view->lines == 0 && opt_prefix[0]) {
4589 char *pos = opt_prefix;
4591 while (pos && *pos) {
4592 char *end = strchr(pos, '/');
4594 if (end)
4595 *end = 0;
4596 push_tree_stack_entry(pos, 0);
4597 pos = end;
4598 if (end) {
4599 *end = '/';
4600 pos++;
4604 } else if (strcmp(view->vid, view->id)) {
4605 opt_path[0] = 0;
4608 return begin_update(view, opt_cdup, tree_argv, flags);
4611 static struct view_ops tree_ops = {
4612 "file",
4613 sizeof(struct tree_state),
4614 tree_open,
4615 tree_read,
4616 tree_draw,
4617 tree_request,
4618 tree_grep,
4619 tree_select,
4622 static bool
4623 blob_open(struct view *view, enum open_flags flags)
4625 static const char *blob_argv[] = {
4626 "git", "cat-file", "blob", "%(blob)", NULL
4629 return begin_update(view, NULL, blob_argv, flags);
4632 static bool
4633 blob_read(struct view *view, char *line)
4635 if (!line)
4636 return TRUE;
4637 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4640 static enum request
4641 blob_request(struct view *view, enum request request, struct line *line)
4643 switch (request) {
4644 case REQ_EDIT:
4645 open_blob_editor(view->vid);
4646 return REQ_NONE;
4647 default:
4648 return pager_request(view, request, line);
4652 static struct view_ops blob_ops = {
4653 "line",
4655 blob_open,
4656 blob_read,
4657 pager_draw,
4658 blob_request,
4659 pager_grep,
4660 pager_select,
4664 * Blame backend
4666 * Loading the blame view is a two phase job:
4668 * 1. File content is read either using opt_file from the
4669 * filesystem or using git-cat-file.
4670 * 2. Then blame information is incrementally added by
4671 * reading output from git-blame.
4674 struct blame {
4675 struct blame_commit *commit;
4676 unsigned long lineno;
4677 char text[1];
4680 struct blame_state {
4681 struct blame_commit *commit;
4682 int blamed;
4683 bool done_reading;
4684 bool auto_filename_display;
4687 static bool
4688 blame_detect_filename_display(struct view *view)
4690 bool show_filenames = FALSE;
4691 const char *filename = NULL;
4692 int i;
4694 if (opt_blame_argv) {
4695 for (i = 0; opt_blame_argv[i]; i++) {
4696 if (prefixcmp(opt_blame_argv[i], "-C"))
4697 continue;
4699 show_filenames = TRUE;
4703 for (i = 0; i < view->lines; i++) {
4704 struct blame *blame = view->line[i].data;
4706 if (blame->commit && blame->commit->id[0]) {
4707 if (!filename)
4708 filename = blame->commit->filename;
4709 else if (strcmp(filename, blame->commit->filename))
4710 show_filenames = TRUE;
4714 return show_filenames;
4717 static bool
4718 blame_open(struct view *view, enum open_flags flags)
4720 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4721 char path[SIZEOF_STR];
4722 size_t i;
4724 if (!view->prev && *opt_prefix) {
4725 string_copy(path, opt_file);
4726 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4727 return FALSE;
4730 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4731 const char *blame_cat_file_argv[] = {
4732 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4735 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4736 return FALSE;
4739 /* First pass: remove multiple references to the same commit. */
4740 for (i = 0; i < view->lines; i++) {
4741 struct blame *blame = view->line[i].data;
4743 if (blame->commit && blame->commit->id[0])
4744 blame->commit->id[0] = 0;
4745 else
4746 blame->commit = NULL;
4749 /* Second pass: free existing references. */
4750 for (i = 0; i < view->lines; i++) {
4751 struct blame *blame = view->line[i].data;
4753 if (blame->commit)
4754 free(blame->commit);
4757 string_format(view->vid, "%s", opt_file);
4758 string_format(view->ref, "%s ...", opt_file);
4760 return TRUE;
4763 static struct blame_commit *
4764 get_blame_commit(struct view *view, const char *id)
4766 size_t i;
4768 for (i = 0; i < view->lines; i++) {
4769 struct blame *blame = view->line[i].data;
4771 if (!blame->commit)
4772 continue;
4774 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4775 return blame->commit;
4779 struct blame_commit *commit = calloc(1, sizeof(*commit));
4781 if (commit)
4782 string_ncopy(commit->id, id, SIZEOF_REV);
4783 return commit;
4787 static struct blame_commit *
4788 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
4790 struct blame_header header;
4791 struct blame_commit *commit;
4792 struct blame *blame;
4794 if (!parse_blame_header(&header, text, view->lines))
4795 return NULL;
4797 commit = get_blame_commit(view, text);
4798 if (!commit)
4799 return NULL;
4801 state->blamed += header.group;
4802 while (header.group--) {
4803 struct line *line = &view->line[header.lineno + header.group - 1];
4805 blame = line->data;
4806 blame->commit = commit;
4807 blame->lineno = header.orig_lineno + header.group - 1;
4808 line->dirty = 1;
4811 return commit;
4814 static bool
4815 blame_read_file(struct view *view, const char *line, struct blame_state *state)
4817 if (!line) {
4818 const char *blame_argv[] = {
4819 "git", "blame", "%(blameargs)", "--incremental",
4820 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4823 if (view->lines == 0 && !view->prev)
4824 die("No blame exist for %s", view->vid);
4826 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
4827 report("Failed to load blame data");
4828 return TRUE;
4831 if (opt_goto_line > 0) {
4832 select_view_line(view, opt_goto_line);
4833 opt_goto_line = 0;
4836 state->done_reading = TRUE;
4837 return FALSE;
4839 } else {
4840 size_t linelen = strlen(line);
4841 struct blame *blame = malloc(sizeof(*blame) + linelen);
4843 if (!blame)
4844 return FALSE;
4846 blame->commit = NULL;
4847 strncpy(blame->text, line, linelen);
4848 blame->text[linelen] = 0;
4849 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4853 static bool
4854 blame_read(struct view *view, char *line)
4856 struct blame_state *state = view->private;
4858 if (!state->done_reading)
4859 return blame_read_file(view, line, state);
4861 if (!line) {
4862 state->auto_filename_display = blame_detect_filename_display(view);
4863 string_format(view->ref, "%s", view->vid);
4864 if (view_is_displayed(view)) {
4865 update_view_title(view);
4866 redraw_view_from(view, 0);
4868 return TRUE;
4871 if (!state->commit) {
4872 state->commit = read_blame_commit(view, line, state);
4873 string_format(view->ref, "%s %2d%%", view->vid,
4874 view->lines ? state->blamed * 100 / view->lines : 0);
4876 } else if (parse_blame_info(state->commit, line)) {
4877 state->commit = NULL;
4880 return TRUE;
4883 static bool
4884 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4886 struct blame_state *state = view->private;
4887 struct blame *blame = line->data;
4888 struct time *time = NULL;
4889 const char *id = NULL, *author = NULL, *filename = NULL;
4890 enum line_type id_type = LINE_BLAME_ID;
4891 static const enum line_type blame_colors[] = {
4892 LINE_PALETTE_0,
4893 LINE_PALETTE_1,
4894 LINE_PALETTE_2,
4895 LINE_PALETTE_3,
4896 LINE_PALETTE_4,
4897 LINE_PALETTE_5,
4898 LINE_PALETTE_6,
4901 #define BLAME_COLOR(i) \
4902 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
4904 if (blame->commit && *blame->commit->filename) {
4905 id = blame->commit->id;
4906 author = blame->commit->author;
4907 filename = blame->commit->filename;
4908 time = &blame->commit->time;
4909 id_type = BLAME_COLOR((long) blame->commit);
4912 if (draw_date(view, time))
4913 return TRUE;
4915 if (draw_author(view, author))
4916 return TRUE;
4918 if (draw_filename(view, filename, state->auto_filename_display))
4919 return TRUE;
4921 if (draw_field(view, id_type, id, ID_COLS, FALSE))
4922 return TRUE;
4924 if (draw_lineno(view, lineno))
4925 return TRUE;
4927 draw_text(view, LINE_DEFAULT, blame->text);
4928 return TRUE;
4931 static bool
4932 check_blame_commit(struct blame *blame, bool check_null_id)
4934 if (!blame->commit)
4935 report("Commit data not loaded yet");
4936 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4937 report("No commit exist for the selected line");
4938 else
4939 return TRUE;
4940 return FALSE;
4943 static void
4944 setup_blame_parent_line(struct view *view, struct blame *blame)
4946 char from[SIZEOF_REF + SIZEOF_STR];
4947 char to[SIZEOF_REF + SIZEOF_STR];
4948 const char *diff_tree_argv[] = {
4949 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4950 "-U0", from, to, "--", NULL
4952 struct io io;
4953 int parent_lineno = -1;
4954 int blamed_lineno = -1;
4955 char *line;
4957 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4958 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4959 !io_run(&io, IO_RD, NULL, diff_tree_argv))
4960 return;
4962 while ((line = io_get(&io, '\n', TRUE))) {
4963 if (*line == '@') {
4964 char *pos = strchr(line, '+');
4966 parent_lineno = atoi(line + 4);
4967 if (pos)
4968 blamed_lineno = atoi(pos + 1);
4970 } else if (*line == '+' && parent_lineno != -1) {
4971 if (blame->lineno == blamed_lineno - 1 &&
4972 !strcmp(blame->text, line + 1)) {
4973 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4974 break;
4976 blamed_lineno++;
4980 io_done(&io);
4983 static enum request
4984 blame_request(struct view *view, enum request request, struct line *line)
4986 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4987 struct blame *blame = line->data;
4989 switch (request) {
4990 case REQ_VIEW_BLAME:
4991 if (check_blame_commit(blame, TRUE)) {
4992 string_copy(opt_ref, blame->commit->id);
4993 string_copy(opt_file, blame->commit->filename);
4994 if (blame->lineno)
4995 view->lineno = blame->lineno;
4996 reload_view(view);
4998 break;
5000 case REQ_PARENT:
5001 if (!check_blame_commit(blame, TRUE))
5002 break;
5003 if (!*blame->commit->parent_id) {
5004 report("The selected commit has no parents");
5005 } else {
5006 string_copy_rev(opt_ref, blame->commit->parent_id);
5007 string_copy(opt_file, blame->commit->parent_filename);
5008 setup_blame_parent_line(view, blame);
5009 opt_goto_line = blame->lineno;
5010 reload_view(view);
5012 break;
5014 case REQ_ENTER:
5015 if (!check_blame_commit(blame, FALSE))
5016 break;
5018 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5019 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5020 break;
5022 if (!strcmp(blame->commit->id, NULL_ID)) {
5023 struct view *diff = VIEW(REQ_VIEW_DIFF);
5024 const char *diff_index_argv[] = {
5025 "git", "diff-index", "--root", "--patch-with-stat",
5026 "-C", "-M", opt_diff_context_arg,
5027 "HEAD", "--", view->vid, NULL
5030 if (!*blame->commit->parent_id) {
5031 diff_index_argv[1] = "diff";
5032 diff_index_argv[2] = "--no-color";
5033 diff_index_argv[7] = "--";
5034 diff_index_argv[8] = "/dev/null";
5037 open_argv(view, diff, diff_index_argv, NULL, flags);
5038 if (diff->pipe)
5039 string_copy_rev(diff->ref, NULL_ID);
5040 } else {
5041 open_view(view, REQ_VIEW_DIFF, flags);
5043 break;
5045 default:
5046 return request;
5049 return REQ_NONE;
5052 static bool
5053 blame_grep(struct view *view, struct line *line)
5055 struct blame *blame = line->data;
5056 struct blame_commit *commit = blame->commit;
5057 const char *text[] = {
5058 blame->text,
5059 commit ? commit->title : "",
5060 commit ? commit->id : "",
5061 commit && opt_author ? commit->author : "",
5062 commit ? mkdate(&commit->time, opt_date) : "",
5063 NULL
5066 return grep_text(view, text);
5069 static void
5070 blame_select(struct view *view, struct line *line)
5072 struct blame *blame = line->data;
5073 struct blame_commit *commit = blame->commit;
5075 if (!commit)
5076 return;
5078 if (!strcmp(commit->id, NULL_ID))
5079 string_ncopy(ref_commit, "HEAD", 4);
5080 else
5081 string_copy_rev(ref_commit, commit->id);
5084 static struct view_ops blame_ops = {
5085 "line",
5086 sizeof(struct blame_state),
5087 blame_open,
5088 blame_read,
5089 blame_draw,
5090 blame_request,
5091 blame_grep,
5092 blame_select,
5096 * Branch backend
5099 struct branch {
5100 const char *author; /* Author of the last commit. */
5101 struct time time; /* Date of the last activity. */
5102 const struct ref *ref; /* Name and commit ID information. */
5105 static const struct ref branch_all;
5107 static const enum sort_field branch_sort_fields[] = {
5108 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5110 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5112 struct branch_state {
5113 char id[SIZEOF_REV];
5116 static int
5117 branch_compare(const void *l1, const void *l2)
5119 const struct branch *branch1 = ((const struct line *) l1)->data;
5120 const struct branch *branch2 = ((const struct line *) l2)->data;
5122 if (branch1->ref == &branch_all)
5123 return -1;
5124 else if (branch2->ref == &branch_all)
5125 return 1;
5127 switch (get_sort_field(branch_sort_state)) {
5128 case ORDERBY_DATE:
5129 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5131 case ORDERBY_AUTHOR:
5132 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5134 case ORDERBY_NAME:
5135 default:
5136 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5140 static bool
5141 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5143 struct branch *branch = line->data;
5144 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5146 if (draw_date(view, &branch->time))
5147 return TRUE;
5149 if (draw_author(view, branch->author))
5150 return TRUE;
5152 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
5153 return TRUE;
5156 static enum request
5157 branch_request(struct view *view, enum request request, struct line *line)
5159 struct branch *branch = line->data;
5161 switch (request) {
5162 case REQ_REFRESH:
5163 load_refs();
5164 refresh_view(view);
5165 return REQ_NONE;
5167 case REQ_TOGGLE_SORT_FIELD:
5168 case REQ_TOGGLE_SORT_ORDER:
5169 sort_view(view, request, &branch_sort_state, branch_compare);
5170 return REQ_NONE;
5172 case REQ_ENTER:
5174 const struct ref *ref = branch->ref;
5175 const char *all_branches_argv[] = {
5176 "git", "log", "--no-color", "--pretty=raw", "--parents",
5177 "--topo-order",
5178 ref == &branch_all ? "--all" : ref->name, NULL
5180 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5182 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5183 return REQ_NONE;
5185 case REQ_JUMP_COMMIT:
5187 int lineno;
5189 for (lineno = 0; lineno < view->lines; lineno++) {
5190 struct branch *branch = view->line[lineno].data;
5192 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5193 select_view_line(view, lineno);
5194 report("");
5195 return REQ_NONE;
5199 default:
5200 return request;
5204 static bool
5205 branch_read(struct view *view, char *line)
5207 struct branch_state *state = view->private;
5208 struct branch *reference;
5209 size_t i;
5211 if (!line)
5212 return TRUE;
5214 switch (get_line_type(line)) {
5215 case LINE_COMMIT:
5216 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5217 return TRUE;
5219 case LINE_AUTHOR:
5220 for (i = 0, reference = NULL; i < view->lines; i++) {
5221 struct branch *branch = view->line[i].data;
5223 if (strcmp(branch->ref->id, state->id))
5224 continue;
5226 view->line[i].dirty = TRUE;
5227 if (reference) {
5228 branch->author = reference->author;
5229 branch->time = reference->time;
5230 continue;
5233 parse_author_line(line + STRING_SIZE("author "),
5234 &branch->author, &branch->time);
5235 reference = branch;
5237 return TRUE;
5239 default:
5240 return TRUE;
5245 static bool
5246 branch_open_visitor(void *data, const struct ref *ref)
5248 struct view *view = data;
5249 struct branch *branch;
5251 if (ref->tag || ref->ltag)
5252 return TRUE;
5254 branch = calloc(1, sizeof(*branch));
5255 if (!branch)
5256 return FALSE;
5258 branch->ref = ref;
5259 return !!add_line_data(view, branch, LINE_DEFAULT);
5262 static bool
5263 branch_open(struct view *view, enum open_flags flags)
5265 const char *branch_log[] = {
5266 "git", "log", "--no-color", "--pretty=raw",
5267 "--simplify-by-decoration", "--all", NULL
5270 if (!begin_update(view, NULL, branch_log, flags)) {
5271 report("Failed to load branch data");
5272 return TRUE;
5275 branch_open_visitor(view, &branch_all);
5276 foreach_ref(branch_open_visitor, view);
5277 view->p_restore = TRUE;
5279 return TRUE;
5282 static bool
5283 branch_grep(struct view *view, struct line *line)
5285 struct branch *branch = line->data;
5286 const char *text[] = {
5287 branch->ref->name,
5288 mkauthor(branch->author, opt_author_cols, opt_author),
5289 NULL
5292 return grep_text(view, text);
5295 static void
5296 branch_select(struct view *view, struct line *line)
5298 struct branch *branch = line->data;
5300 string_copy_rev(view->ref, branch->ref->id);
5301 string_copy_rev(ref_commit, branch->ref->id);
5302 string_copy_rev(ref_head, branch->ref->id);
5303 string_copy_rev(ref_branch, branch->ref->name);
5306 static struct view_ops branch_ops = {
5307 "branch",
5308 sizeof(struct branch_state),
5309 branch_open,
5310 branch_read,
5311 branch_draw,
5312 branch_request,
5313 branch_grep,
5314 branch_select,
5318 * Status backend
5321 struct status {
5322 char status;
5323 struct {
5324 mode_t mode;
5325 char rev[SIZEOF_REV];
5326 char name[SIZEOF_STR];
5327 } old;
5328 struct {
5329 mode_t mode;
5330 char rev[SIZEOF_REV];
5331 char name[SIZEOF_STR];
5332 } new;
5335 static char status_onbranch[SIZEOF_STR];
5336 static struct status stage_status;
5337 static enum line_type stage_line_type;
5339 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5341 /* This should work even for the "On branch" line. */
5342 static inline bool
5343 status_has_none(struct view *view, struct line *line)
5345 return line < view->line + view->lines && !line[1].data;
5348 /* Get fields from the diff line:
5349 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5351 static inline bool
5352 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5354 const char *old_mode = buf + 1;
5355 const char *new_mode = buf + 8;
5356 const char *old_rev = buf + 15;
5357 const char *new_rev = buf + 56;
5358 const char *status = buf + 97;
5360 if (bufsize < 98 ||
5361 old_mode[-1] != ':' ||
5362 new_mode[-1] != ' ' ||
5363 old_rev[-1] != ' ' ||
5364 new_rev[-1] != ' ' ||
5365 status[-1] != ' ')
5366 return FALSE;
5368 file->status = *status;
5370 string_copy_rev(file->old.rev, old_rev);
5371 string_copy_rev(file->new.rev, new_rev);
5373 file->old.mode = strtoul(old_mode, NULL, 8);
5374 file->new.mode = strtoul(new_mode, NULL, 8);
5376 file->old.name[0] = file->new.name[0] = 0;
5378 return TRUE;
5381 static bool
5382 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5384 struct status *unmerged = NULL;
5385 char *buf;
5386 struct io io;
5388 if (!io_run(&io, IO_RD, opt_cdup, argv))
5389 return FALSE;
5391 add_line_data(view, NULL, type);
5393 while ((buf = io_get(&io, 0, TRUE))) {
5394 struct status *file = unmerged;
5396 if (!file) {
5397 file = calloc(1, sizeof(*file));
5398 if (!file || !add_line_data(view, file, type))
5399 goto error_out;
5402 /* Parse diff info part. */
5403 if (status) {
5404 file->status = status;
5405 if (status == 'A')
5406 string_copy(file->old.rev, NULL_ID);
5408 } else if (!file->status || file == unmerged) {
5409 if (!status_get_diff(file, buf, strlen(buf)))
5410 goto error_out;
5412 buf = io_get(&io, 0, TRUE);
5413 if (!buf)
5414 break;
5416 /* Collapse all modified entries that follow an
5417 * associated unmerged entry. */
5418 if (unmerged == file) {
5419 unmerged->status = 'U';
5420 unmerged = NULL;
5421 } else if (file->status == 'U') {
5422 unmerged = file;
5426 /* Grab the old name for rename/copy. */
5427 if (!*file->old.name &&
5428 (file->status == 'R' || file->status == 'C')) {
5429 string_ncopy(file->old.name, buf, strlen(buf));
5431 buf = io_get(&io, 0, TRUE);
5432 if (!buf)
5433 break;
5436 /* git-ls-files just delivers a NUL separated list of
5437 * file names similar to the second half of the
5438 * git-diff-* output. */
5439 string_ncopy(file->new.name, buf, strlen(buf));
5440 if (!*file->old.name)
5441 string_copy(file->old.name, file->new.name);
5442 file = NULL;
5445 if (io_error(&io)) {
5446 error_out:
5447 io_done(&io);
5448 return FALSE;
5451 if (!view->line[view->lines - 1].data)
5452 add_line_data(view, NULL, LINE_STAT_NONE);
5454 io_done(&io);
5455 return TRUE;
5458 /* Don't show unmerged entries in the staged section. */
5459 static const char *status_diff_index_argv[] = {
5460 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
5461 "--cached", "-M", "HEAD", NULL
5464 static const char *status_diff_files_argv[] = {
5465 "git", "diff-files", "-z", NULL
5468 static const char *status_list_other_argv[] = {
5469 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5472 static const char *status_list_no_head_argv[] = {
5473 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5476 static const char *update_index_argv[] = {
5477 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5480 /* Restore the previous line number to stay in the context or select a
5481 * line with something that can be updated. */
5482 static void
5483 status_restore(struct view *view)
5485 if (view->p_lineno >= view->lines)
5486 view->p_lineno = view->lines - 1;
5487 while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
5488 view->p_lineno++;
5489 while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
5490 view->p_lineno--;
5492 /* If the above fails, always skip the "On branch" line. */
5493 if (view->p_lineno < view->lines)
5494 view->lineno = view->p_lineno;
5495 else
5496 view->lineno = 1;
5498 if (view->lineno < view->offset)
5499 view->offset = view->lineno;
5500 else if (view->offset + view->height <= view->lineno)
5501 view->offset = view->lineno - view->height + 1;
5503 view->p_restore = FALSE;
5506 static void
5507 status_update_onbranch(void)
5509 static const char *paths[][2] = {
5510 { "rebase-apply/rebasing", "Rebasing" },
5511 { "rebase-apply/applying", "Applying mailbox" },
5512 { "rebase-apply/", "Rebasing mailbox" },
5513 { "rebase-merge/interactive", "Interactive rebase" },
5514 { "rebase-merge/", "Rebase merge" },
5515 { "MERGE_HEAD", "Merging" },
5516 { "BISECT_LOG", "Bisecting" },
5517 { "HEAD", "On branch" },
5519 char buf[SIZEOF_STR];
5520 struct stat stat;
5521 int i;
5523 if (is_initial_commit()) {
5524 string_copy(status_onbranch, "Initial commit");
5525 return;
5528 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5529 char *head = opt_head;
5531 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5532 lstat(buf, &stat) < 0)
5533 continue;
5535 if (!*opt_head) {
5536 struct io io;
5538 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5539 io_read_buf(&io, buf, sizeof(buf))) {
5540 head = buf;
5541 if (!prefixcmp(head, "refs/heads/"))
5542 head += STRING_SIZE("refs/heads/");
5546 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5547 string_copy(status_onbranch, opt_head);
5548 return;
5551 string_copy(status_onbranch, "Not currently on any branch");
5554 /* First parse staged info using git-diff-index(1), then parse unstaged
5555 * info using git-diff-files(1), and finally untracked files using
5556 * git-ls-files(1). */
5557 static bool
5558 status_open(struct view *view, enum open_flags flags)
5560 reset_view(view);
5562 add_line_data(view, NULL, LINE_STAT_HEAD);
5563 status_update_onbranch();
5565 io_run_bg(update_index_argv);
5567 if (is_initial_commit()) {
5568 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5569 return FALSE;
5570 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5571 return FALSE;
5574 if (!opt_untracked_dirs_content)
5575 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5577 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5578 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5579 return FALSE;
5581 /* Restore the exact position or use the specialized restore
5582 * mode? */
5583 if (!view->p_restore)
5584 status_restore(view);
5585 return TRUE;
5588 static bool
5589 status_draw(struct view *view, struct line *line, unsigned int lineno)
5591 struct status *status = line->data;
5592 enum line_type type;
5593 const char *text;
5595 if (!status) {
5596 switch (line->type) {
5597 case LINE_STAT_STAGED:
5598 type = LINE_STAT_SECTION;
5599 text = "Changes to be committed:";
5600 break;
5602 case LINE_STAT_UNSTAGED:
5603 type = LINE_STAT_SECTION;
5604 text = "Changed but not updated:";
5605 break;
5607 case LINE_STAT_UNTRACKED:
5608 type = LINE_STAT_SECTION;
5609 text = "Untracked files:";
5610 break;
5612 case LINE_STAT_NONE:
5613 type = LINE_DEFAULT;
5614 text = " (no files)";
5615 break;
5617 case LINE_STAT_HEAD:
5618 type = LINE_STAT_HEAD;
5619 text = status_onbranch;
5620 break;
5622 default:
5623 return FALSE;
5625 } else {
5626 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5628 buf[0] = status->status;
5629 if (draw_text(view, line->type, buf))
5630 return TRUE;
5631 type = LINE_DEFAULT;
5632 text = status->new.name;
5635 draw_text(view, type, text);
5636 return TRUE;
5639 static enum request
5640 status_enter(struct view *view, struct line *line)
5642 struct status *status = line->data;
5643 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5645 if (line->type == LINE_STAT_NONE ||
5646 (!status && line[1].type == LINE_STAT_NONE)) {
5647 report("No file to diff");
5648 return REQ_NONE;
5651 switch (line->type) {
5652 case LINE_STAT_STAGED:
5653 case LINE_STAT_UNSTAGED:
5654 break;
5656 case LINE_STAT_UNTRACKED:
5657 if (!status) {
5658 report("No file to show");
5659 return REQ_NONE;
5662 if (!suffixcmp(status->new.name, -1, "/")) {
5663 report("Cannot display a directory");
5664 return REQ_NONE;
5666 break;
5668 case LINE_STAT_HEAD:
5669 return REQ_NONE;
5671 default:
5672 die("line type %d not handled in switch", line->type);
5675 if (status) {
5676 stage_status = *status;
5677 } else {
5678 memset(&stage_status, 0, sizeof(stage_status));
5681 stage_line_type = line->type;
5683 open_view(view, REQ_VIEW_STAGE, flags);
5684 return REQ_NONE;
5687 static bool
5688 status_exists(struct view *view, struct status *status, enum line_type type)
5690 unsigned long lineno;
5692 for (lineno = 0; lineno < view->lines; lineno++) {
5693 struct line *line = &view->line[lineno];
5694 struct status *pos = line->data;
5696 if (line->type != type)
5697 continue;
5698 if (!pos && (!status || !status->status) && line[1].data) {
5699 select_view_line(view, lineno);
5700 return TRUE;
5702 if (pos && !strcmp(status->new.name, pos->new.name)) {
5703 select_view_line(view, lineno);
5704 return TRUE;
5708 return FALSE;
5712 static bool
5713 status_update_prepare(struct io *io, enum line_type type)
5715 const char *staged_argv[] = {
5716 "git", "update-index", "-z", "--index-info", NULL
5718 const char *others_argv[] = {
5719 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5722 switch (type) {
5723 case LINE_STAT_STAGED:
5724 return io_run(io, IO_WR, opt_cdup, staged_argv);
5726 case LINE_STAT_UNSTAGED:
5727 case LINE_STAT_UNTRACKED:
5728 return io_run(io, IO_WR, opt_cdup, others_argv);
5730 default:
5731 die("line type %d not handled in switch", type);
5732 return FALSE;
5736 static bool
5737 status_update_write(struct io *io, struct status *status, enum line_type type)
5739 switch (type) {
5740 case LINE_STAT_STAGED:
5741 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
5742 status->old.rev, status->old.name, 0);
5744 case LINE_STAT_UNSTAGED:
5745 case LINE_STAT_UNTRACKED:
5746 return io_printf(io, "%s%c", status->new.name, 0);
5748 default:
5749 die("line type %d not handled in switch", type);
5750 return FALSE;
5754 static bool
5755 status_update_file(struct status *status, enum line_type type)
5757 struct io io;
5758 bool result;
5760 if (!status_update_prepare(&io, type))
5761 return FALSE;
5763 result = status_update_write(&io, status, type);
5764 return io_done(&io) && result;
5767 static bool
5768 status_update_files(struct view *view, struct line *line)
5770 char buf[sizeof(view->ref)];
5771 struct io io;
5772 bool result = TRUE;
5773 struct line *pos = view->line + view->lines;
5774 int files = 0;
5775 int file, done;
5776 int cursor_y = -1, cursor_x = -1;
5778 if (!status_update_prepare(&io, line->type))
5779 return FALSE;
5781 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5782 files++;
5784 string_copy(buf, view->ref);
5785 getsyx(cursor_y, cursor_x);
5786 for (file = 0, done = 5; result && file < files; line++, file++) {
5787 int almost_done = file * 100 / files;
5789 if (almost_done > done) {
5790 done = almost_done;
5791 string_format(view->ref, "updating file %u of %u (%d%% done)",
5792 file, files, done);
5793 update_view_title(view);
5794 setsyx(cursor_y, cursor_x);
5795 doupdate();
5797 result = status_update_write(&io, line->data, line->type);
5799 string_copy(view->ref, buf);
5801 return io_done(&io) && result;
5804 static bool
5805 status_update(struct view *view)
5807 struct line *line = &view->line[view->lineno];
5809 assert(view->lines);
5811 if (!line->data) {
5812 /* This should work even for the "On branch" line. */
5813 if (line < view->line + view->lines && !line[1].data) {
5814 report("Nothing to update");
5815 return FALSE;
5818 if (!status_update_files(view, line + 1)) {
5819 report("Failed to update file status");
5820 return FALSE;
5823 } else if (!status_update_file(line->data, line->type)) {
5824 report("Failed to update file status");
5825 return FALSE;
5828 return TRUE;
5831 static bool
5832 status_revert(struct status *status, enum line_type type, bool has_none)
5834 if (!status || type != LINE_STAT_UNSTAGED) {
5835 if (type == LINE_STAT_STAGED) {
5836 report("Cannot revert changes to staged files");
5837 } else if (type == LINE_STAT_UNTRACKED) {
5838 report("Cannot revert changes to untracked files");
5839 } else if (has_none) {
5840 report("Nothing to revert");
5841 } else {
5842 report("Cannot revert changes to multiple files");
5845 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5846 char mode[10] = "100644";
5847 const char *reset_argv[] = {
5848 "git", "update-index", "--cacheinfo", mode,
5849 status->old.rev, status->old.name, NULL
5851 const char *checkout_argv[] = {
5852 "git", "checkout", "--", status->old.name, NULL
5855 if (status->status == 'U') {
5856 string_format(mode, "%5o", status->old.mode);
5858 if (status->old.mode == 0 && status->new.mode == 0) {
5859 reset_argv[2] = "--force-remove";
5860 reset_argv[3] = status->old.name;
5861 reset_argv[4] = NULL;
5864 if (!io_run_fg(reset_argv, opt_cdup))
5865 return FALSE;
5866 if (status->old.mode == 0 && status->new.mode == 0)
5867 return TRUE;
5870 return io_run_fg(checkout_argv, opt_cdup);
5873 return FALSE;
5876 static enum request
5877 status_request(struct view *view, enum request request, struct line *line)
5879 struct status *status = line->data;
5881 switch (request) {
5882 case REQ_STATUS_UPDATE:
5883 if (!status_update(view))
5884 return REQ_NONE;
5885 break;
5887 case REQ_STATUS_REVERT:
5888 if (!status_revert(status, line->type, status_has_none(view, line)))
5889 return REQ_NONE;
5890 break;
5892 case REQ_STATUS_MERGE:
5893 if (!status || status->status != 'U') {
5894 report("Merging only possible for files with unmerged status ('U').");
5895 return REQ_NONE;
5897 open_mergetool(status->new.name);
5898 break;
5900 case REQ_EDIT:
5901 if (!status)
5902 return request;
5903 if (status->status == 'D') {
5904 report("File has been deleted.");
5905 return REQ_NONE;
5908 open_editor(status->new.name);
5909 break;
5911 case REQ_VIEW_BLAME:
5912 if (status)
5913 opt_ref[0] = 0;
5914 return request;
5916 case REQ_ENTER:
5917 /* After returning the status view has been split to
5918 * show the stage view. No further reloading is
5919 * necessary. */
5920 return status_enter(view, line);
5922 case REQ_REFRESH:
5923 /* Simply reload the view. */
5924 break;
5926 default:
5927 return request;
5930 refresh_view(view);
5932 return REQ_NONE;
5935 static void
5936 status_select(struct view *view, struct line *line)
5938 struct status *status = line->data;
5939 char file[SIZEOF_STR] = "all files";
5940 const char *text;
5941 const char *key;
5943 if (status && !string_format(file, "'%s'", status->new.name))
5944 return;
5946 if (!status && line[1].type == LINE_STAT_NONE)
5947 line++;
5949 switch (line->type) {
5950 case LINE_STAT_STAGED:
5951 text = "Press %s to unstage %s for commit";
5952 break;
5954 case LINE_STAT_UNSTAGED:
5955 text = "Press %s to stage %s for commit";
5956 break;
5958 case LINE_STAT_UNTRACKED:
5959 text = "Press %s to stage %s for addition";
5960 break;
5962 case LINE_STAT_HEAD:
5963 case LINE_STAT_NONE:
5964 text = "Nothing to update";
5965 break;
5967 default:
5968 die("line type %d not handled in switch", line->type);
5971 if (status && status->status == 'U') {
5972 text = "Press %s to resolve conflict in %s";
5973 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5975 } else {
5976 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5979 string_format(view->ref, text, key, file);
5980 if (status)
5981 string_copy(opt_file, status->new.name);
5984 static bool
5985 status_grep(struct view *view, struct line *line)
5987 struct status *status = line->data;
5989 if (status) {
5990 const char buf[2] = { status->status, 0 };
5991 const char *text[] = { status->new.name, buf, NULL };
5993 return grep_text(view, text);
5996 return FALSE;
5999 static struct view_ops status_ops = {
6000 "file",
6002 status_open,
6003 NULL,
6004 status_draw,
6005 status_request,
6006 status_grep,
6007 status_select,
6011 struct stage_state {
6012 struct diff_state diff;
6013 size_t chunks;
6014 int *chunk;
6017 static bool
6018 stage_diff_write(struct io *io, struct line *line, struct line *end)
6020 while (line < end) {
6021 if (!io_write(io, line->data, strlen(line->data)) ||
6022 !io_write(io, "\n", 1))
6023 return FALSE;
6024 line++;
6025 if (line->type == LINE_DIFF_CHUNK ||
6026 line->type == LINE_DIFF_HEADER)
6027 break;
6030 return TRUE;
6033 static bool
6034 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6036 const char *apply_argv[SIZEOF_ARG] = {
6037 "git", "apply", "--whitespace=nowarn", NULL
6039 struct line *diff_hdr;
6040 struct io io;
6041 int argc = 3;
6043 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6044 if (!diff_hdr)
6045 return FALSE;
6047 if (!revert)
6048 apply_argv[argc++] = "--cached";
6049 if (line != NULL)
6050 apply_argv[argc++] = "--unidiff-zero";
6051 if (revert || stage_line_type == LINE_STAT_STAGED)
6052 apply_argv[argc++] = "-R";
6053 apply_argv[argc++] = "-";
6054 apply_argv[argc++] = NULL;
6055 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6056 return FALSE;
6058 if (line != NULL) {
6059 int lineno = 0;
6060 struct line *context = chunk + 1;
6061 const char *markers[] = {
6062 line->type == LINE_DIFF_DEL ? "" : ",0",
6063 line->type == LINE_DIFF_DEL ? ",0" : "",
6066 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6068 while (context < line) {
6069 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6070 break;
6071 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6072 lineno++;
6074 context++;
6077 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6078 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6079 lineno, markers[0], lineno, markers[1]) ||
6080 !stage_diff_write(&io, line, line + 1)) {
6081 chunk = NULL;
6083 } else {
6084 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6085 !stage_diff_write(&io, chunk, view->line + view->lines))
6086 chunk = NULL;
6089 io_done(&io);
6090 io_run_bg(update_index_argv);
6092 return chunk ? TRUE : FALSE;
6095 static bool
6096 stage_update(struct view *view, struct line *line, bool single)
6098 struct line *chunk = NULL;
6100 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6101 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6103 if (chunk) {
6104 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6105 report("Failed to apply chunk");
6106 return FALSE;
6109 } else if (!stage_status.status) {
6110 view = view->parent;
6112 for (line = view->line; line < view->line + view->lines; line++)
6113 if (line->type == stage_line_type)
6114 break;
6116 if (!status_update_files(view, line + 1)) {
6117 report("Failed to update files");
6118 return FALSE;
6121 } else if (!status_update_file(&stage_status, stage_line_type)) {
6122 report("Failed to update file");
6123 return FALSE;
6126 return TRUE;
6129 static bool
6130 stage_revert(struct view *view, struct line *line)
6132 struct line *chunk = NULL;
6134 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6135 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6137 if (chunk) {
6138 if (!prompt_yesno("Are you sure you want to revert changes?"))
6139 return FALSE;
6141 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6142 report("Failed to revert chunk");
6143 return FALSE;
6145 return TRUE;
6147 } else {
6148 return status_revert(stage_status.status ? &stage_status : NULL,
6149 stage_line_type, FALSE);
6154 static void
6155 stage_next(struct view *view, struct line *line)
6157 struct stage_state *state = view->private;
6158 int i;
6160 if (!state->chunks) {
6161 for (line = view->line; line < view->line + view->lines; line++) {
6162 if (line->type != LINE_DIFF_CHUNK)
6163 continue;
6165 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6166 report("Allocation failure");
6167 return;
6170 state->chunk[state->chunks++] = line - view->line;
6174 for (i = 0; i < state->chunks; i++) {
6175 if (state->chunk[i] > view->lineno) {
6176 do_scroll_view(view, state->chunk[i] - view->lineno);
6177 report("Chunk %d of %d", i + 1, state->chunks);
6178 return;
6182 report("No next chunk found");
6185 static enum request
6186 stage_request(struct view *view, enum request request, struct line *line)
6188 switch (request) {
6189 case REQ_STATUS_UPDATE:
6190 if (!stage_update(view, line, FALSE))
6191 return REQ_NONE;
6192 break;
6194 case REQ_STATUS_REVERT:
6195 if (!stage_revert(view, line))
6196 return REQ_NONE;
6197 break;
6199 case REQ_STAGE_UPDATE_LINE:
6200 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6201 report("Please select a change to stage");
6202 return REQ_NONE;
6204 if (!stage_update(view, line, TRUE))
6205 return REQ_NONE;
6206 break;
6208 case REQ_STAGE_NEXT:
6209 if (stage_line_type == LINE_STAT_UNTRACKED) {
6210 report("File is untracked; press %s to add",
6211 get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
6212 return REQ_NONE;
6214 stage_next(view, line);
6215 return REQ_NONE;
6217 case REQ_EDIT:
6218 if (!stage_status.new.name[0])
6219 return request;
6220 if (stage_status.status == 'D') {
6221 report("File has been deleted.");
6222 return REQ_NONE;
6225 open_editor(stage_status.new.name);
6226 break;
6228 case REQ_REFRESH:
6229 /* Reload everything ... */
6230 break;
6232 case REQ_VIEW_BLAME:
6233 if (stage_status.new.name[0]) {
6234 string_copy(opt_file, stage_status.new.name);
6235 opt_ref[0] = 0;
6237 return request;
6239 case REQ_ENTER:
6240 return diff_common_enter(view, request, line);
6242 case REQ_DIFF_CONTEXT_UP:
6243 case REQ_DIFF_CONTEXT_DOWN:
6244 if (!update_diff_context(request))
6245 return REQ_NONE;
6246 break;
6248 default:
6249 return request;
6252 refresh_view(view->parent);
6254 /* Check whether the staged entry still exists, and close the
6255 * stage view if it doesn't. */
6256 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6257 status_restore(view->parent);
6258 return REQ_VIEW_CLOSE;
6261 refresh_view(view);
6263 return REQ_NONE;
6266 static bool
6267 stage_open(struct view *view, enum open_flags flags)
6269 static const char *no_head_diff_argv[] = {
6270 "git", "diff", "--no-color", "--patch-with-stat",
6271 opt_diff_context_arg,
6272 "--", "/dev/null", stage_status.new.name, NULL
6274 static const char *index_show_argv[] = {
6275 "git", "diff-index", "--root", "--patch-with-stat", "-C", "-M",
6276 "--cached", opt_diff_context_arg, "HEAD", "--",
6277 stage_status.old.name, stage_status.new.name, NULL
6279 static const char *files_show_argv[] = {
6280 "git", "diff-files", "--root", "--patch-with-stat",
6281 "-C", "-M", opt_diff_context_arg, "--",
6282 stage_status.old.name, stage_status.new.name, NULL
6284 /* Diffs for unmerged entries are empty when passing the new
6285 * path, so leave out the new path. */
6286 static const char *files_unmerged_argv[] = {
6287 "git", "diff-files", "--root", "--patch-with-stat",
6288 "-C", "-M", opt_diff_context_arg, "--",
6289 stage_status.old.name, NULL
6291 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6292 const char **argv = NULL;
6293 const char *info;
6295 switch (stage_line_type) {
6296 case LINE_STAT_STAGED:
6297 if (is_initial_commit()) {
6298 argv = no_head_diff_argv;
6299 } else {
6300 argv = index_show_argv;
6302 if (stage_status.status)
6303 info = "Staged changes to %s";
6304 else
6305 info = "Staged changes";
6306 break;
6308 case LINE_STAT_UNSTAGED:
6309 if (stage_status.status != 'U')
6310 argv = files_show_argv;
6311 else
6312 argv = files_unmerged_argv;
6313 if (stage_status.status)
6314 info = "Unstaged changes to %s";
6315 else
6316 info = "Unstaged changes";
6317 break;
6319 case LINE_STAT_UNTRACKED:
6320 info = "Untracked file %s";
6321 argv = file_argv;
6322 break;
6324 case LINE_STAT_HEAD:
6325 default:
6326 die("line type %d not handled in switch", stage_line_type);
6329 string_format(view->ref, info, stage_status.new.name);
6330 view->vid[0] = 0;
6331 view->dir = opt_cdup;
6332 return argv_copy(&view->argv, argv)
6333 && begin_update(view, NULL, NULL, flags);
6336 static bool
6337 stage_read(struct view *view, char *data)
6339 struct stage_state *state = view->private;
6341 if (data && diff_common_read(view, data, &state->diff))
6342 return TRUE;
6344 return pager_read(view, data);
6347 static struct view_ops stage_ops = {
6348 "line",
6349 sizeof(struct stage_state),
6350 stage_open,
6351 stage_read,
6352 diff_common_draw,
6353 stage_request,
6354 pager_grep,
6355 pager_select,
6360 * Revision graph
6363 static const enum line_type graph_colors[] = {
6364 LINE_PALETTE_0,
6365 LINE_PALETTE_1,
6366 LINE_PALETTE_2,
6367 LINE_PALETTE_3,
6368 LINE_PALETTE_4,
6369 LINE_PALETTE_5,
6370 LINE_PALETTE_6,
6373 static enum line_type get_graph_color(struct graph_symbol *symbol)
6375 if (symbol->commit)
6376 return LINE_GRAPH_COMMIT;
6377 assert(symbol->color < ARRAY_SIZE(graph_colors));
6378 return graph_colors[symbol->color];
6381 static bool
6382 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6384 const char *chars = graph_symbol_to_utf8(symbol);
6386 return draw_text(view, color, chars + !!first);
6389 static bool
6390 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6392 const char *chars = graph_symbol_to_ascii(symbol);
6394 return draw_text(view, color, chars + !!first);
6397 static bool
6398 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6400 const chtype *chars = graph_symbol_to_chtype(symbol);
6402 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6405 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6407 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6409 static const draw_graph_fn fns[] = {
6410 draw_graph_ascii,
6411 draw_graph_chtype,
6412 draw_graph_utf8
6414 draw_graph_fn fn = fns[opt_line_graphics];
6415 int i;
6417 for (i = 0; i < canvas->size; i++) {
6418 struct graph_symbol *symbol = &canvas->symbols[i];
6419 enum line_type color = get_graph_color(symbol);
6421 if (fn(view, symbol, color, i == 0))
6422 return TRUE;
6425 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6429 * Main view backend
6432 struct commit {
6433 char id[SIZEOF_REV]; /* SHA1 ID. */
6434 char title[128]; /* First line of the commit message. */
6435 const char *author; /* Author of the commit. */
6436 struct time time; /* Date from the author ident. */
6437 struct ref_list *refs; /* Repository references. */
6438 struct graph_canvas graph; /* Ancestry chain graphics. */
6441 static bool
6442 main_open(struct view *view, enum open_flags flags)
6444 static const char *main_argv[] = {
6445 "git", "log", "--no-color", "--pretty=raw", "--parents",
6446 "--topo-order", "%(diffargs)", "%(revargs)",
6447 "--", "%(fileargs)", NULL
6450 return begin_update(view, NULL, main_argv, flags);
6453 static bool
6454 main_draw(struct view *view, struct line *line, unsigned int lineno)
6456 struct commit *commit = line->data;
6458 if (!commit->author)
6459 return FALSE;
6461 if (opt_line_number && draw_lineno(view, lineno))
6462 return TRUE;
6464 if (draw_date(view, &commit->time))
6465 return TRUE;
6467 if (draw_author(view, commit->author))
6468 return TRUE;
6470 if (opt_rev_graph && draw_graph(view, &commit->graph))
6471 return TRUE;
6473 if (draw_refs(view, commit->refs))
6474 return TRUE;
6476 draw_text(view, LINE_DEFAULT, commit->title);
6477 return TRUE;
6480 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6481 static bool
6482 main_read(struct view *view, char *line)
6484 struct graph *graph = view->private;
6485 enum line_type type;
6486 struct commit *commit;
6488 if (!line) {
6489 if (!view->lines && !view->prev)
6490 die("No revisions match the given arguments.");
6491 if (view->lines > 0) {
6492 commit = view->line[view->lines - 1].data;
6493 view->line[view->lines - 1].dirty = 1;
6494 if (!commit->author) {
6495 view->lines--;
6496 free(commit);
6500 done_graph(graph);
6501 return TRUE;
6504 type = get_line_type(line);
6505 if (type == LINE_COMMIT) {
6506 bool is_boundary;
6508 commit = calloc(1, sizeof(struct commit));
6509 if (!commit)
6510 return FALSE;
6512 line += STRING_SIZE("commit ");
6513 is_boundary = *line == '-';
6514 if (is_boundary)
6515 line++;
6517 string_copy_rev(commit->id, line);
6518 commit->refs = get_ref_list(commit->id);
6519 add_line_data(view, commit, LINE_MAIN_COMMIT);
6520 graph_add_commit(graph, &commit->graph, commit->id, line, is_boundary);
6521 return TRUE;
6524 if (!view->lines)
6525 return TRUE;
6526 commit = view->line[view->lines - 1].data;
6528 switch (type) {
6529 case LINE_PARENT:
6530 if (!graph->has_parents)
6531 graph_add_parent(graph, line + STRING_SIZE("parent "));
6532 break;
6534 case LINE_AUTHOR:
6535 parse_author_line(line + STRING_SIZE("author "),
6536 &commit->author, &commit->time);
6537 graph_render_parents(graph);
6538 break;
6540 default:
6541 /* Fill in the commit title if it has not already been set. */
6542 if (commit->title[0])
6543 break;
6545 /* Require titles to start with a non-space character at the
6546 * offset used by git log. */
6547 if (strncmp(line, " ", 4))
6548 break;
6549 line += 4;
6550 /* Well, if the title starts with a whitespace character,
6551 * try to be forgiving. Otherwise we end up with no title. */
6552 while (isspace(*line))
6553 line++;
6554 if (*line == '\0')
6555 break;
6556 /* FIXME: More graceful handling of titles; append "..." to
6557 * shortened titles, etc. */
6559 string_expand(commit->title, sizeof(commit->title), line, 1);
6560 view->line[view->lines - 1].dirty = 1;
6563 return TRUE;
6566 static enum request
6567 main_request(struct view *view, enum request request, struct line *line)
6569 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6571 switch (request) {
6572 case REQ_ENTER:
6573 if (view_is_displayed(view) && display[0] != view)
6574 maximize_view(view, TRUE);
6575 open_view(view, REQ_VIEW_DIFF, flags);
6576 break;
6577 case REQ_REFRESH:
6578 load_refs();
6579 refresh_view(view);
6580 break;
6582 case REQ_JUMP_COMMIT:
6584 int lineno;
6586 for (lineno = 0; lineno < view->lines; lineno++) {
6587 struct commit *commit = view->line[lineno].data;
6589 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
6590 select_view_line(view, lineno);
6591 report("");
6592 return REQ_NONE;
6596 report("Unable to find commit '%s'", opt_search);
6597 break;
6599 default:
6600 return request;
6603 return REQ_NONE;
6606 static bool
6607 grep_refs(struct ref_list *list, regex_t *regex)
6609 regmatch_t pmatch;
6610 size_t i;
6612 if (!opt_show_refs || !list)
6613 return FALSE;
6615 for (i = 0; i < list->size; i++) {
6616 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
6617 return TRUE;
6620 return FALSE;
6623 static bool
6624 main_grep(struct view *view, struct line *line)
6626 struct commit *commit = line->data;
6627 const char *text[] = {
6628 commit->title,
6629 mkauthor(commit->author, opt_author_cols, opt_author),
6630 mkdate(&commit->time, opt_date),
6631 NULL
6634 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
6637 static void
6638 main_select(struct view *view, struct line *line)
6640 struct commit *commit = line->data;
6642 string_copy_rev(view->ref, commit->id);
6643 string_copy_rev(ref_commit, view->ref);
6646 static struct view_ops main_ops = {
6647 "commit",
6648 sizeof(struct graph),
6649 main_open,
6650 main_read,
6651 main_draw,
6652 main_request,
6653 main_grep,
6654 main_select,
6659 * Status management
6662 /* Whether or not the curses interface has been initialized. */
6663 static bool cursed = FALSE;
6665 /* Terminal hacks and workarounds. */
6666 static bool use_scroll_redrawwin;
6667 static bool use_scroll_status_wclear;
6669 /* The status window is used for polling keystrokes. */
6670 static WINDOW *status_win;
6672 /* Reading from the prompt? */
6673 static bool input_mode = FALSE;
6675 static bool status_empty = FALSE;
6677 /* Update status and title window. */
6678 static void
6679 report(const char *msg, ...)
6681 struct view *view = display[current_view];
6683 if (input_mode)
6684 return;
6686 if (!view) {
6687 char buf[SIZEOF_STR];
6688 int retval;
6690 FORMAT_BUFFER(buf, sizeof(buf), msg, retval);
6691 if (retval >= sizeof(buf)) {
6692 buf[sizeof(buf) - 1] = 0;
6693 buf[sizeof(buf) - 2] = '.';
6694 buf[sizeof(buf) - 3] = '.';
6695 buf[sizeof(buf) - 4] = '.';
6697 die("%s", buf);
6700 if (!status_empty || *msg) {
6701 va_list args;
6703 va_start(args, msg);
6705 wmove(status_win, 0, 0);
6706 if (view->has_scrolled && use_scroll_status_wclear)
6707 wclear(status_win);
6708 if (*msg) {
6709 vwprintw(status_win, msg, args);
6710 status_empty = FALSE;
6711 } else {
6712 status_empty = TRUE;
6714 wclrtoeol(status_win);
6715 wnoutrefresh(status_win);
6717 va_end(args);
6720 update_view_title(view);
6723 static void
6724 init_display(void)
6726 const char *term;
6727 int x, y;
6729 /* Initialize the curses library */
6730 if (isatty(STDIN_FILENO)) {
6731 cursed = !!initscr();
6732 opt_tty = stdin;
6733 } else {
6734 /* Leave stdin and stdout alone when acting as a pager. */
6735 opt_tty = fopen("/dev/tty", "r+");
6736 if (!opt_tty)
6737 die("Failed to open /dev/tty");
6738 cursed = !!newterm(NULL, opt_tty, opt_tty);
6741 if (!cursed)
6742 die("Failed to initialize curses");
6744 nonl(); /* Disable conversion and detect newlines from input. */
6745 cbreak(); /* Take input chars one at a time, no wait for \n */
6746 noecho(); /* Don't echo input */
6747 leaveok(stdscr, FALSE);
6749 if (has_colors())
6750 init_colors();
6752 getmaxyx(stdscr, y, x);
6753 status_win = newwin(1, x, y - 1, 0);
6754 if (!status_win)
6755 die("Failed to create status window");
6757 /* Enable keyboard mapping */
6758 keypad(status_win, TRUE);
6759 wbkgdset(status_win, get_line_attr(LINE_STATUS));
6761 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6762 set_tabsize(opt_tab_size);
6763 #else
6764 TABSIZE = opt_tab_size;
6765 #endif
6767 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6768 if (term && !strcmp(term, "gnome-terminal")) {
6769 /* In the gnome-terminal-emulator, the message from
6770 * scrolling up one line when impossible followed by
6771 * scrolling down one line causes corruption of the
6772 * status line. This is fixed by calling wclear. */
6773 use_scroll_status_wclear = TRUE;
6774 use_scroll_redrawwin = FALSE;
6776 } else if (term && !strcmp(term, "xrvt-xpm")) {
6777 /* No problems with full optimizations in xrvt-(unicode)
6778 * and aterm. */
6779 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6781 } else {
6782 /* When scrolling in (u)xterm the last line in the
6783 * scrolling direction will update slowly. */
6784 use_scroll_redrawwin = TRUE;
6785 use_scroll_status_wclear = FALSE;
6789 static int
6790 get_input(int prompt_position)
6792 struct view *view;
6793 int i, key, cursor_y, cursor_x;
6795 if (prompt_position)
6796 input_mode = TRUE;
6798 while (TRUE) {
6799 bool loading = FALSE;
6801 foreach_view (view, i) {
6802 update_view(view);
6803 if (view_is_displayed(view) && view->has_scrolled &&
6804 use_scroll_redrawwin)
6805 redrawwin(view->win);
6806 view->has_scrolled = FALSE;
6807 if (view->pipe)
6808 loading = TRUE;
6811 /* Update the cursor position. */
6812 if (prompt_position) {
6813 getbegyx(status_win, cursor_y, cursor_x);
6814 cursor_x = prompt_position;
6815 } else {
6816 view = display[current_view];
6817 getbegyx(view->win, cursor_y, cursor_x);
6818 cursor_x = view->width - 1;
6819 cursor_y += view->lineno - view->offset;
6821 setsyx(cursor_y, cursor_x);
6823 /* Refresh, accept single keystroke of input */
6824 doupdate();
6825 nodelay(status_win, loading);
6826 key = wgetch(status_win);
6828 /* wgetch() with nodelay() enabled returns ERR when
6829 * there's no input. */
6830 if (key == ERR) {
6832 } else if (key == KEY_RESIZE) {
6833 int height, width;
6835 getmaxyx(stdscr, height, width);
6837 wresize(status_win, 1, width);
6838 mvwin(status_win, height - 1, 0);
6839 wnoutrefresh(status_win);
6840 resize_display();
6841 redraw_display(TRUE);
6843 } else {
6844 input_mode = FALSE;
6845 if (key == erasechar())
6846 key = KEY_BACKSPACE;
6847 return key;
6852 static char *
6853 prompt_input(const char *prompt, input_handler handler, void *data)
6855 enum input_status status = INPUT_OK;
6856 static char buf[SIZEOF_STR];
6857 size_t pos = 0;
6859 buf[pos] = 0;
6861 while (status == INPUT_OK || status == INPUT_SKIP) {
6862 int key;
6864 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6865 wclrtoeol(status_win);
6867 key = get_input(pos + 1);
6868 switch (key) {
6869 case KEY_RETURN:
6870 case KEY_ENTER:
6871 case '\n':
6872 status = pos ? INPUT_STOP : INPUT_CANCEL;
6873 break;
6875 case KEY_BACKSPACE:
6876 if (pos > 0)
6877 buf[--pos] = 0;
6878 else
6879 status = INPUT_CANCEL;
6880 break;
6882 case KEY_ESC:
6883 status = INPUT_CANCEL;
6884 break;
6886 default:
6887 if (pos >= sizeof(buf)) {
6888 report("Input string too long");
6889 return NULL;
6892 status = handler(data, buf, key);
6893 if (status == INPUT_OK)
6894 buf[pos++] = (char) key;
6898 /* Clear the status window */
6899 status_empty = FALSE;
6900 report("");
6902 if (status == INPUT_CANCEL)
6903 return NULL;
6905 buf[pos++] = 0;
6907 return buf;
6910 static enum input_status
6911 prompt_yesno_handler(void *data, char *buf, int c)
6913 if (c == 'y' || c == 'Y')
6914 return INPUT_STOP;
6915 if (c == 'n' || c == 'N')
6916 return INPUT_CANCEL;
6917 return INPUT_SKIP;
6920 static bool
6921 prompt_yesno(const char *prompt)
6923 char prompt2[SIZEOF_STR];
6925 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6926 return FALSE;
6928 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6931 static enum input_status
6932 read_prompt_handler(void *data, char *buf, int c)
6934 return isprint(c) ? INPUT_OK : INPUT_SKIP;
6937 static char *
6938 read_prompt(const char *prompt)
6940 return prompt_input(prompt, read_prompt_handler, NULL);
6943 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6945 enum input_status status = INPUT_OK;
6946 int size = 0;
6948 while (items[size].text)
6949 size++;
6951 while (status == INPUT_OK) {
6952 const struct menu_item *item = &items[*selected];
6953 int key;
6954 int i;
6956 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6957 prompt, *selected + 1, size);
6958 if (item->hotkey)
6959 wprintw(status_win, "[%c] ", (char) item->hotkey);
6960 wprintw(status_win, "%s", item->text);
6961 wclrtoeol(status_win);
6963 key = get_input(COLS - 1);
6964 switch (key) {
6965 case KEY_RETURN:
6966 case KEY_ENTER:
6967 case '\n':
6968 status = INPUT_STOP;
6969 break;
6971 case KEY_LEFT:
6972 case KEY_UP:
6973 *selected = *selected - 1;
6974 if (*selected < 0)
6975 *selected = size - 1;
6976 break;
6978 case KEY_RIGHT:
6979 case KEY_DOWN:
6980 *selected = (*selected + 1) % size;
6981 break;
6983 case KEY_ESC:
6984 status = INPUT_CANCEL;
6985 break;
6987 default:
6988 for (i = 0; items[i].text; i++)
6989 if (items[i].hotkey == key) {
6990 *selected = i;
6991 status = INPUT_STOP;
6992 break;
6997 /* Clear the status window */
6998 status_empty = FALSE;
6999 report("");
7001 return status != INPUT_CANCEL;
7005 * Repository properties
7008 static struct ref **refs = NULL;
7009 static size_t refs_size = 0;
7010 static struct ref *refs_head = NULL;
7012 static struct ref_list **ref_lists = NULL;
7013 static size_t ref_lists_size = 0;
7015 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
7016 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
7017 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
7019 static int
7020 compare_refs(const void *ref1_, const void *ref2_)
7022 const struct ref *ref1 = *(const struct ref **)ref1_;
7023 const struct ref *ref2 = *(const struct ref **)ref2_;
7025 if (ref1->tag != ref2->tag)
7026 return ref2->tag - ref1->tag;
7027 if (ref1->ltag != ref2->ltag)
7028 return ref2->ltag - ref1->ltag;
7029 if (ref1->head != ref2->head)
7030 return ref2->head - ref1->head;
7031 if (ref1->tracked != ref2->tracked)
7032 return ref2->tracked - ref1->tracked;
7033 if (ref1->replace != ref2->replace)
7034 return ref2->replace - ref1->replace;
7035 /* Order remotes last. */
7036 if (ref1->remote != ref2->remote)
7037 return ref1->remote - ref2->remote;
7038 return strcmp(ref1->name, ref2->name);
7041 static void
7042 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
7044 size_t i;
7046 for (i = 0; i < refs_size; i++)
7047 if (!visitor(data, refs[i]))
7048 break;
7051 static struct ref *
7052 get_ref_head()
7054 return refs_head;
7057 static struct ref_list *
7058 get_ref_list(const char *id)
7060 struct ref_list *list;
7061 size_t i;
7063 for (i = 0; i < ref_lists_size; i++)
7064 if (!strcmp(id, ref_lists[i]->id))
7065 return ref_lists[i];
7067 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
7068 return NULL;
7069 list = calloc(1, sizeof(*list));
7070 if (!list)
7071 return NULL;
7073 for (i = 0; i < refs_size; i++) {
7074 if (!strcmp(id, refs[i]->id) &&
7075 realloc_refs_list(&list->refs, list->size, 1))
7076 list->refs[list->size++] = refs[i];
7079 if (!list->refs) {
7080 free(list);
7081 return NULL;
7084 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
7085 ref_lists[ref_lists_size++] = list;
7086 return list;
7089 static int
7090 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
7092 struct ref *ref = NULL;
7093 bool tag = FALSE;
7094 bool ltag = FALSE;
7095 bool remote = FALSE;
7096 bool replace = FALSE;
7097 bool tracked = FALSE;
7098 bool head = FALSE;
7099 int from = 0, to = refs_size - 1;
7101 if (!prefixcmp(name, "refs/tags/")) {
7102 if (!suffixcmp(name, namelen, "^{}")) {
7103 namelen -= 3;
7104 name[namelen] = 0;
7105 } else {
7106 ltag = TRUE;
7109 tag = TRUE;
7110 namelen -= STRING_SIZE("refs/tags/");
7111 name += STRING_SIZE("refs/tags/");
7113 } else if (!prefixcmp(name, "refs/remotes/")) {
7114 remote = TRUE;
7115 namelen -= STRING_SIZE("refs/remotes/");
7116 name += STRING_SIZE("refs/remotes/");
7117 tracked = !strcmp(opt_remote, name);
7119 } else if (!prefixcmp(name, "refs/replace/")) {
7120 replace = TRUE;
7121 id = name + strlen("refs/replace/");
7122 idlen = namelen - strlen("refs/replace/");
7123 name = "replaced";
7124 namelen = strlen(name);
7126 } else if (!prefixcmp(name, "refs/heads/")) {
7127 namelen -= STRING_SIZE("refs/heads/");
7128 name += STRING_SIZE("refs/heads/");
7129 if (strlen(opt_head) == namelen
7130 && !strncmp(opt_head, name, namelen))
7131 return OK;
7133 } else if (!strcmp(name, "HEAD")) {
7134 head = TRUE;
7135 if (*opt_head) {
7136 namelen = strlen(opt_head);
7137 name = opt_head;
7141 /* If we are reloading or it's an annotated tag, replace the
7142 * previous SHA1 with the resolved commit id; relies on the fact
7143 * git-ls-remote lists the commit id of an annotated tag right
7144 * before the commit id it points to. */
7145 while ((from <= to) && !replace) {
7146 size_t pos = (to + from) / 2;
7147 int cmp = strcmp(name, refs[pos]->name);
7149 if (!cmp) {
7150 ref = refs[pos];
7151 break;
7154 if (cmp < 0)
7155 to = pos - 1;
7156 else
7157 from = pos + 1;
7160 if (!ref) {
7161 if (!realloc_refs(&refs, refs_size, 1))
7162 return ERR;
7163 ref = calloc(1, sizeof(*ref) + namelen);
7164 if (!ref)
7165 return ERR;
7166 memmove(refs + from + 1, refs + from,
7167 (refs_size - from) * sizeof(*refs));
7168 refs[from] = ref;
7169 strncpy(ref->name, name, namelen);
7170 refs_size++;
7173 ref->head = head;
7174 ref->tag = tag;
7175 ref->ltag = ltag;
7176 ref->remote = remote;
7177 ref->replace = replace;
7178 ref->tracked = tracked;
7179 string_copy_rev(ref->id, id);
7181 if (head)
7182 refs_head = ref;
7183 return OK;
7186 static int
7187 load_refs(void)
7189 const char *head_argv[] = {
7190 "git", "symbolic-ref", "HEAD", NULL
7192 static const char *ls_remote_argv[SIZEOF_ARG] = {
7193 "git", "ls-remote", opt_git_dir, NULL
7195 static bool init = FALSE;
7196 size_t i;
7198 if (!init) {
7199 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
7200 die("TIG_LS_REMOTE contains too many arguments");
7201 init = TRUE;
7204 if (!*opt_git_dir)
7205 return OK;
7207 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
7208 !prefixcmp(opt_head, "refs/heads/")) {
7209 char *offset = opt_head + STRING_SIZE("refs/heads/");
7211 memmove(opt_head, offset, strlen(offset) + 1);
7214 refs_head = NULL;
7215 for (i = 0; i < refs_size; i++)
7216 refs[i]->id[0] = 0;
7218 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
7219 return ERR;
7221 /* Update the ref lists to reflect changes. */
7222 for (i = 0; i < ref_lists_size; i++) {
7223 struct ref_list *list = ref_lists[i];
7224 size_t old, new;
7226 for (old = new = 0; old < list->size; old++)
7227 if (!strcmp(list->id, list->refs[old]->id))
7228 list->refs[new++] = list->refs[old];
7229 list->size = new;
7232 qsort(refs, refs_size, sizeof(*refs), compare_refs);
7234 return OK;
7237 static void
7238 set_remote_branch(const char *name, const char *value, size_t valuelen)
7240 if (!strcmp(name, ".remote")) {
7241 string_ncopy(opt_remote, value, valuelen);
7243 } else if (*opt_remote && !strcmp(name, ".merge")) {
7244 size_t from = strlen(opt_remote);
7246 if (!prefixcmp(value, "refs/heads/"))
7247 value += STRING_SIZE("refs/heads/");
7249 if (!string_format_from(opt_remote, &from, "/%s", value))
7250 opt_remote[0] = 0;
7254 static void
7255 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7257 const char *argv[SIZEOF_ARG] = { name, "=" };
7258 int argc = 1 + (cmd == option_set_command);
7259 enum option_code error;
7261 if (!argv_from_string(argv, &argc, value))
7262 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7263 else
7264 error = cmd(argc, argv);
7266 if (error != OPT_OK)
7267 warn("Option 'tig.%s': %s", name, option_errors[error]);
7270 static bool
7271 set_environment_variable(const char *name, const char *value)
7273 size_t len = strlen(name) + 1 + strlen(value) + 1;
7274 char *env = malloc(len);
7276 if (env &&
7277 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7278 putenv(env) == 0)
7279 return TRUE;
7280 free(env);
7281 return FALSE;
7284 static void
7285 set_work_tree(const char *value)
7287 char cwd[SIZEOF_STR];
7289 if (!getcwd(cwd, sizeof(cwd)))
7290 die("Failed to get cwd path: %s", strerror(errno));
7291 if (chdir(opt_git_dir) < 0)
7292 die("Failed to chdir(%s): %s", strerror(errno));
7293 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7294 die("Failed to get git path: %s", strerror(errno));
7295 if (chdir(cwd) < 0)
7296 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7297 if (chdir(value) < 0)
7298 die("Failed to chdir(%s): %s", value, strerror(errno));
7299 if (!getcwd(cwd, sizeof(cwd)))
7300 die("Failed to get cwd path: %s", strerror(errno));
7301 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7302 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7303 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7304 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7305 opt_is_inside_work_tree = TRUE;
7308 static int
7309 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7311 if (!strcmp(name, "i18n.commitencoding"))
7312 string_ncopy(opt_encoding, value, valuelen);
7314 else if (!strcmp(name, "core.editor"))
7315 string_ncopy(opt_editor, value, valuelen);
7317 else if (!strcmp(name, "core.worktree"))
7318 set_work_tree(value);
7320 else if (!prefixcmp(name, "tig.color."))
7321 set_repo_config_option(name + 10, value, option_color_command);
7323 else if (!prefixcmp(name, "tig.bind."))
7324 set_repo_config_option(name + 9, value, option_bind_command);
7326 else if (!prefixcmp(name, "tig."))
7327 set_repo_config_option(name + 4, value, option_set_command);
7329 else if (*opt_head && !prefixcmp(name, "branch.") &&
7330 !strncmp(name + 7, opt_head, strlen(opt_head)))
7331 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7333 return OK;
7336 static int
7337 load_git_config(void)
7339 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7341 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7344 static int
7345 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7347 if (!opt_git_dir[0]) {
7348 string_ncopy(opt_git_dir, name, namelen);
7350 } else if (opt_is_inside_work_tree == -1) {
7351 /* This can be 3 different values depending on the
7352 * version of git being used. If git-rev-parse does not
7353 * understand --is-inside-work-tree it will simply echo
7354 * the option else either "true" or "false" is printed.
7355 * Default to true for the unknown case. */
7356 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7358 } else if (*name == '.') {
7359 string_ncopy(opt_cdup, name, namelen);
7361 } else {
7362 string_ncopy(opt_prefix, name, namelen);
7365 return OK;
7368 static int
7369 load_repo_info(void)
7371 const char *rev_parse_argv[] = {
7372 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7373 "--show-cdup", "--show-prefix", NULL
7376 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7381 * Main
7384 static const char usage[] =
7385 "tig " TIG_VERSION " (" __DATE__ ")\n"
7386 "\n"
7387 "Usage: tig [options] [revs] [--] [paths]\n"
7388 " or: tig show [options] [revs] [--] [paths]\n"
7389 " or: tig blame [options] [rev] [--] path\n"
7390 " or: tig status\n"
7391 " or: tig < [git command output]\n"
7392 "\n"
7393 "Options:\n"
7394 " +<number> Select line <number> in the first view\n"
7395 " -v, --version Show version and exit\n"
7396 " -h, --help Show help message and exit";
7398 static void __NORETURN
7399 quit(int sig)
7401 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7402 if (cursed)
7403 endwin();
7404 exit(0);
7407 static void __NORETURN
7408 die(const char *err, ...)
7410 va_list args;
7412 endwin();
7414 va_start(args, err);
7415 fputs("tig: ", stderr);
7416 vfprintf(stderr, err, args);
7417 fputs("\n", stderr);
7418 va_end(args);
7420 exit(1);
7423 static void
7424 warn(const char *msg, ...)
7426 va_list args;
7428 va_start(args, msg);
7429 fputs("tig warning: ", stderr);
7430 vfprintf(stderr, msg, args);
7431 fputs("\n", stderr);
7432 va_end(args);
7435 static int
7436 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7438 const char ***filter_args = data;
7440 return argv_append(filter_args, name) ? OK : ERR;
7443 static void
7444 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7446 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7447 const char **all_argv = NULL;
7449 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7450 !argv_append_array(&all_argv, argv) ||
7451 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7452 die("Failed to split arguments");
7453 argv_free(all_argv);
7454 free(all_argv);
7457 static void
7458 filter_options(const char *argv[], bool blame)
7460 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7462 if (blame)
7463 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7464 else
7465 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7467 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7470 static enum request
7471 parse_options(int argc, const char *argv[])
7473 enum request request = REQ_VIEW_MAIN;
7474 const char *subcommand;
7475 bool seen_dashdash = FALSE;
7476 const char **filter_argv = NULL;
7477 int i;
7479 if (!isatty(STDIN_FILENO))
7480 return REQ_VIEW_PAGER;
7482 if (argc <= 1)
7483 return REQ_VIEW_MAIN;
7485 subcommand = argv[1];
7486 if (!strcmp(subcommand, "status")) {
7487 if (argc > 2)
7488 warn("ignoring arguments after `%s'", subcommand);
7489 return REQ_VIEW_STATUS;
7491 } else if (!strcmp(subcommand, "blame")) {
7492 request = REQ_VIEW_BLAME;
7494 } else if (!strcmp(subcommand, "show")) {
7495 request = REQ_VIEW_DIFF;
7497 } else {
7498 subcommand = NULL;
7501 for (i = 1 + !!subcommand; i < argc; i++) {
7502 const char *opt = argv[i];
7504 // stop parsing our options after -- and let rev-parse handle the rest
7505 if (!seen_dashdash) {
7506 if (!strcmp(opt, "--")) {
7507 seen_dashdash = TRUE;
7508 continue;
7510 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7511 printf("tig version %s\n", TIG_VERSION);
7512 quit(0);
7514 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7515 printf("%s\n", usage);
7516 quit(0);
7518 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7519 opt_lineno = atoi(opt + 1);
7520 continue;
7525 if (!argv_append(&filter_argv, opt))
7526 die("command too long");
7529 if (filter_argv)
7530 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7532 /* Finish validating and setting up blame options */
7533 if (request == REQ_VIEW_BLAME) {
7534 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7535 die("invalid number of options to blame\n\n%s", usage);
7537 if (opt_rev_argv) {
7538 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7541 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7544 return request;
7548 main(int argc, const char *argv[])
7550 const char *codeset = ENCODING_UTF8;
7551 enum request request = parse_options(argc, argv);
7552 struct view *view;
7554 signal(SIGINT, quit);
7555 signal(SIGPIPE, SIG_IGN);
7557 if (setlocale(LC_ALL, "")) {
7558 codeset = nl_langinfo(CODESET);
7561 if (load_repo_info() == ERR)
7562 die("Failed to load repo info.");
7564 if (load_options() == ERR)
7565 die("Failed to load user config.");
7567 if (load_git_config() == ERR)
7568 die("Failed to load repo config.");
7570 /* Require a git repository unless when running in pager mode. */
7571 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7572 die("Not a git repository");
7574 if (*opt_encoding && strcmp(codeset, ENCODING_UTF8)) {
7575 opt_iconv_in = iconv_open(ENCODING_UTF8, opt_encoding);
7576 if (opt_iconv_in == ICONV_NONE)
7577 die("Failed to initialize character set conversion");
7580 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
7581 char translit[SIZEOF_STR];
7583 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
7584 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
7585 else
7586 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
7587 if (opt_iconv_out == ICONV_NONE)
7588 die("Failed to initialize character set conversion");
7591 if (load_refs() == ERR)
7592 die("Failed to load refs.");
7594 init_display();
7596 while (view_driver(display[current_view], request)) {
7597 int key = get_input(0);
7599 view = display[current_view];
7600 request = get_keybinding(view->keymap, key);
7602 /* Some low-level request handling. This keeps access to
7603 * status_win restricted. */
7604 switch (request) {
7605 case REQ_NONE:
7606 report("Unknown key, press %s for help",
7607 get_key(view->keymap, REQ_VIEW_HELP));
7608 break;
7609 case REQ_PROMPT:
7611 char *cmd = read_prompt(":");
7613 if (cmd && string_isnumber(cmd)) {
7614 int lineno = view->lineno + 1;
7616 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
7617 select_view_line(view, lineno - 1);
7618 report("");
7619 } else {
7620 report("Unable to parse '%s' as a line number", cmd);
7622 } else if (cmd && iscommit(cmd)) {
7623 string_ncopy(opt_search, cmd, strlen(cmd));
7625 request = view_request(view, REQ_JUMP_COMMIT);
7626 if (request == REQ_JUMP_COMMIT) {
7627 report("Jumping to commits is not supported by the '%s' view", view->name);
7630 } else if (cmd) {
7631 struct view *next = VIEW(REQ_VIEW_PAGER);
7632 const char *argv[SIZEOF_ARG] = { "git" };
7633 int argc = 1;
7635 /* When running random commands, initially show the
7636 * command in the title. However, it maybe later be
7637 * overwritten if a commit line is selected. */
7638 string_ncopy(next->ref, cmd, strlen(cmd));
7640 if (!argv_from_string(argv, &argc, cmd)) {
7641 report("Too many arguments");
7642 } else if (!format_argv(&next->argv, argv, FALSE)) {
7643 report("Argument formatting failed");
7644 } else {
7645 next->dir = NULL;
7646 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7650 request = REQ_NONE;
7651 break;
7653 case REQ_SEARCH:
7654 case REQ_SEARCH_BACK:
7656 const char *prompt = request == REQ_SEARCH ? "/" : "?";
7657 char *search = read_prompt(prompt);
7659 if (search)
7660 string_ncopy(opt_search, search, strlen(search));
7661 else if (*opt_search)
7662 request = request == REQ_SEARCH ?
7663 REQ_FIND_NEXT :
7664 REQ_FIND_PREV;
7665 else
7666 request = REQ_NONE;
7667 break;
7669 default:
7670 break;
7674 quit(0);
7676 return 0;