tig.c: compare_refs: fix comparing by ref->ltag
[tig.git] / tig.c
blob0d096616706dc6dfb32b8e2bc1f2b60003ccffad
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_NEXT, "Find next chunk to stage"), \
266 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
267 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
269 REQ_GROUP("Cursor navigation") \
270 REQ_(MOVE_UP, "Move cursor one line up"), \
271 REQ_(MOVE_DOWN, "Move cursor one line down"), \
272 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
273 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
274 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
275 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
277 REQ_GROUP("Scrolling") \
278 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
279 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
280 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
281 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
282 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
283 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
284 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
286 REQ_GROUP("Searching") \
287 REQ_(SEARCH, "Search the view"), \
288 REQ_(SEARCH_BACK, "Search backwards in the view"), \
289 REQ_(FIND_NEXT, "Find next search match"), \
290 REQ_(FIND_PREV, "Find previous search match"), \
292 REQ_GROUP("Option manipulation") \
293 REQ_(OPTIONS, "Open option menu"), \
294 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
295 REQ_(TOGGLE_DATE, "Toggle date display"), \
296 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
297 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
298 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
299 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
300 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
301 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
302 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
304 REQ_GROUP("Misc") \
305 REQ_(PROMPT, "Bring up the prompt"), \
306 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
307 REQ_(SHOW_VERSION, "Show version information"), \
308 REQ_(STOP_LOADING, "Stop all loading views"), \
309 REQ_(EDIT, "Open in editor"), \
310 REQ_(NONE, "Do nothing")
313 /* User action requests. */
314 enum request {
315 #define REQ_GROUP(help)
316 #define REQ_(req, help) REQ_##req
318 /* Offset all requests to avoid conflicts with ncurses getch values. */
319 REQ_UNKNOWN = KEY_MAX + 1,
320 REQ_OFFSET,
321 REQ_INFO,
323 /* Internal requests. */
324 REQ_JUMP_COMMIT,
326 #undef REQ_GROUP
327 #undef REQ_
330 struct request_info {
331 enum request request;
332 const char *name;
333 int namelen;
334 const char *help;
337 static const struct request_info req_info[] = {
338 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
339 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
340 REQ_INFO
341 #undef REQ_GROUP
342 #undef REQ_
345 static enum request
346 get_request(const char *name)
348 int namelen = strlen(name);
349 int i;
351 for (i = 0; i < ARRAY_SIZE(req_info); i++)
352 if (enum_equals(req_info[i], name, namelen))
353 return req_info[i].request;
355 return REQ_UNKNOWN;
360 * Options
363 /* Option and state variables. */
364 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
365 static enum date opt_date = DATE_DEFAULT;
366 static enum author opt_author = AUTHOR_FULL;
367 static enum filename opt_filename = FILENAME_AUTO;
368 static bool opt_rev_graph = TRUE;
369 static bool opt_line_number = FALSE;
370 static bool opt_show_refs = TRUE;
371 static bool opt_untracked_dirs_content = TRUE;
372 static int opt_diff_context = 3;
373 static char opt_diff_context_arg[9] = "";
374 static char opt_notes_arg[SIZEOF_STR] = "--no-notes";
375 static int opt_num_interval = 5;
376 static double opt_hscroll = 0.50;
377 static double opt_scale_split_view = 2.0 / 3.0;
378 static int opt_tab_size = 8;
379 static int opt_author_cols = AUTHOR_COLS;
380 static int opt_filename_cols = FILENAME_COLS;
381 static char opt_path[SIZEOF_STR] = "";
382 static char opt_file[SIZEOF_STR] = "";
383 static char opt_ref[SIZEOF_REF] = "";
384 static unsigned long opt_goto_line = 0;
385 static char opt_head[SIZEOF_REF] = "";
386 static char opt_remote[SIZEOF_REF] = "";
387 static char opt_encoding[20] = "UTF-8";
388 static iconv_t opt_iconv_in = ICONV_NONE;
389 static iconv_t opt_iconv_out = ICONV_NONE;
390 static char opt_search[SIZEOF_STR] = "";
391 static char opt_cdup[SIZEOF_STR] = "";
392 static char opt_prefix[SIZEOF_STR] = "";
393 static char opt_git_dir[SIZEOF_STR] = "";
394 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
395 static char opt_editor[SIZEOF_STR] = "";
396 static FILE *opt_tty = NULL;
397 static const char **opt_diff_argv = NULL;
398 static const char **opt_rev_argv = NULL;
399 static const char **opt_file_argv = NULL;
400 static const char **opt_blame_argv = NULL;
401 static int opt_lineno = 0;
403 #define is_initial_commit() (!get_ref_head())
404 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
406 static inline void
407 update_diff_context_arg(int diff_context)
409 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
410 string_ncopy(opt_diff_context_arg, "-U3", 3);
414 * Line-oriented content detection.
417 #define LINE_INFO \
418 LINE(DIFF_HEADER, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
419 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
420 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
421 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
422 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
423 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
424 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
425 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
426 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
427 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
428 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
429 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
430 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
431 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
432 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
433 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
434 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
435 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
436 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
437 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
438 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
439 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
440 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
441 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
442 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
443 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
444 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
445 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
446 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
447 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
448 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
449 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
450 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
451 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
452 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
453 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
454 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
455 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
456 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
457 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
458 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
459 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
460 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
461 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
462 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
463 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
464 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
465 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
466 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
467 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
468 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
469 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
470 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
471 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
472 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
473 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
474 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
475 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
476 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
477 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
478 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
479 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
480 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
481 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
482 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
483 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
484 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
485 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
486 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
487 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
488 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
489 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
491 enum line_type {
492 #define LINE(type, line, fg, bg, attr) \
493 LINE_##type
494 LINE_INFO,
495 LINE_NONE
496 #undef LINE
499 struct line_info {
500 const char *name; /* Option name. */
501 int namelen; /* Size of option name. */
502 const char *line; /* The start of line to match. */
503 int linelen; /* Size of string to match. */
504 int fg, bg, attr; /* Color and text attributes for the lines. */
507 static struct line_info line_info[] = {
508 #define LINE(type, line, fg, bg, attr) \
509 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
510 LINE_INFO
511 #undef LINE
514 static struct line_info *custom_color;
515 static size_t custom_colors;
517 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
519 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
520 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
522 /* Color IDs must be 1 or higher. [GH #15] */
523 #define COLOR_ID(line_type) ((line_type) + 1)
525 static enum line_type
526 get_line_type(const char *line)
528 int linelen = strlen(line);
529 enum line_type type;
531 for (type = 0; type < custom_colors; type++)
532 /* Case insensitive search matches Signed-off-by lines better. */
533 if (linelen >= custom_color[type].linelen &&
534 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
535 return TO_CUSTOM_COLOR_TYPE(type);
537 for (type = 0; type < ARRAY_SIZE(line_info); type++)
538 /* Case insensitive search matches Signed-off-by lines better. */
539 if (linelen >= line_info[type].linelen &&
540 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
541 return type;
543 return LINE_DEFAULT;
546 static enum line_type
547 get_line_type_from_ref(const struct ref *ref)
549 if (ref->head)
550 return LINE_MAIN_HEAD;
551 else if (ref->ltag)
552 return LINE_MAIN_LOCAL_TAG;
553 else if (ref->tag)
554 return LINE_MAIN_TAG;
555 else if (ref->tracked)
556 return LINE_MAIN_TRACKED;
557 else if (ref->remote)
558 return LINE_MAIN_REMOTE;
559 else if (ref->replace)
560 return LINE_MAIN_REPLACE;
562 return LINE_MAIN_REF;
565 static inline int
566 get_line_attr(enum line_type type)
568 if (type > LINE_NONE) {
569 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
570 return COLOR_PAIR(COLOR_ID(type)) | custom_color[TO_CUSTOM_COLOR_OFFSET(type)].attr;
572 assert(type < ARRAY_SIZE(line_info));
573 return COLOR_PAIR(COLOR_ID(type)) | line_info[type].attr;
576 static struct line_info *
577 get_line_info(const char *name)
579 size_t namelen = strlen(name);
580 enum line_type type;
582 for (type = 0; type < ARRAY_SIZE(line_info); type++)
583 if (enum_equals(line_info[type], name, namelen))
584 return &line_info[type];
586 return NULL;
589 static struct line_info *
590 add_custom_color(const char *quoted_line)
592 struct line_info *info;
593 char *line;
594 size_t linelen;
596 if (!realloc_custom_color(&custom_color, custom_colors, 1))
597 die("Failed to alloc custom line info");
599 linelen = strlen(quoted_line) - 1;
600 line = malloc(linelen);
601 if (!line)
602 return NULL;
604 strncpy(line, quoted_line + 1, linelen);
605 line[linelen - 1] = 0;
607 info = &custom_color[custom_colors++];
608 info->name = info->line = line;
609 info->namelen = info->linelen = strlen(line);
611 return info;
614 static void
615 init_line_info_color_pair(struct line_info *info, enum line_type type,
616 int default_bg, int default_fg)
618 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
619 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
621 init_pair(COLOR_ID(type), fg, bg);
624 static void
625 init_colors(void)
627 int default_bg = line_info[LINE_DEFAULT].bg;
628 int default_fg = line_info[LINE_DEFAULT].fg;
629 enum line_type type;
631 start_color();
633 if (assume_default_colors(default_fg, default_bg) == ERR) {
634 default_bg = COLOR_BLACK;
635 default_fg = COLOR_WHITE;
638 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
639 struct line_info *info = &line_info[type];
641 init_line_info_color_pair(info, type, default_bg, default_fg);
644 for (type = 0; type < custom_colors; type++) {
645 struct line_info *info = &custom_color[type];
647 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
648 default_bg, default_fg);
652 struct line {
653 enum line_type type;
655 /* State flags */
656 unsigned int selected:1;
657 unsigned int dirty:1;
658 unsigned int cleareol:1;
659 unsigned int other:16;
661 void *data; /* User data */
666 * Keys
669 struct keybinding {
670 int alias;
671 enum request request;
674 static struct keybinding default_keybindings[] = {
675 /* View switching */
676 { 'm', REQ_VIEW_MAIN },
677 { 'd', REQ_VIEW_DIFF },
678 { 'l', REQ_VIEW_LOG },
679 { 't', REQ_VIEW_TREE },
680 { 'f', REQ_VIEW_BLOB },
681 { 'B', REQ_VIEW_BLAME },
682 { 'H', REQ_VIEW_BRANCH },
683 { 'p', REQ_VIEW_PAGER },
684 { 'h', REQ_VIEW_HELP },
685 { 'S', REQ_VIEW_STATUS },
686 { 'c', REQ_VIEW_STAGE },
688 /* View manipulation */
689 { 'q', REQ_VIEW_CLOSE },
690 { KEY_TAB, REQ_VIEW_NEXT },
691 { KEY_RETURN, REQ_ENTER },
692 { KEY_UP, REQ_PREVIOUS },
693 { KEY_CTL('P'), REQ_PREVIOUS },
694 { KEY_DOWN, REQ_NEXT },
695 { KEY_CTL('N'), REQ_NEXT },
696 { 'R', REQ_REFRESH },
697 { KEY_F(5), REQ_REFRESH },
698 { 'O', REQ_MAXIMIZE },
699 { ',', REQ_PARENT },
701 /* View specific */
702 { 'u', REQ_STATUS_UPDATE },
703 { '!', REQ_STATUS_REVERT },
704 { 'M', REQ_STATUS_MERGE },
705 { '@', REQ_STAGE_NEXT },
706 { '[', REQ_DIFF_CONTEXT_DOWN },
707 { ']', REQ_DIFF_CONTEXT_UP },
709 /* Cursor navigation */
710 { 'k', REQ_MOVE_UP },
711 { 'j', REQ_MOVE_DOWN },
712 { KEY_HOME, REQ_MOVE_FIRST_LINE },
713 { KEY_END, REQ_MOVE_LAST_LINE },
714 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
715 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
716 { ' ', REQ_MOVE_PAGE_DOWN },
717 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
718 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
719 { 'b', REQ_MOVE_PAGE_UP },
720 { '-', REQ_MOVE_PAGE_UP },
722 /* Scrolling */
723 { '|', REQ_SCROLL_FIRST_COL },
724 { KEY_LEFT, REQ_SCROLL_LEFT },
725 { KEY_RIGHT, REQ_SCROLL_RIGHT },
726 { KEY_IC, REQ_SCROLL_LINE_UP },
727 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
728 { KEY_DC, REQ_SCROLL_LINE_DOWN },
729 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
730 { 'w', REQ_SCROLL_PAGE_UP },
731 { 's', REQ_SCROLL_PAGE_DOWN },
733 /* Searching */
734 { '/', REQ_SEARCH },
735 { '?', REQ_SEARCH_BACK },
736 { 'n', REQ_FIND_NEXT },
737 { 'N', REQ_FIND_PREV },
739 /* Misc */
740 { 'Q', REQ_QUIT },
741 { 'z', REQ_STOP_LOADING },
742 { 'v', REQ_SHOW_VERSION },
743 { 'r', REQ_SCREEN_REDRAW },
744 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
745 { 'o', REQ_OPTIONS },
746 { '.', REQ_TOGGLE_LINENO },
747 { 'D', REQ_TOGGLE_DATE },
748 { 'A', REQ_TOGGLE_AUTHOR },
749 { 'g', REQ_TOGGLE_REV_GRAPH },
750 { '~', REQ_TOGGLE_GRAPHIC },
751 { '#', REQ_TOGGLE_FILENAME },
752 { 'F', REQ_TOGGLE_REFS },
753 { 'I', REQ_TOGGLE_SORT_ORDER },
754 { 'i', REQ_TOGGLE_SORT_FIELD },
755 { ':', REQ_PROMPT },
756 { 'e', REQ_EDIT },
759 #define KEYMAP_ENUM(_) \
760 _(KEYMAP, GENERIC), \
761 _(KEYMAP, MAIN), \
762 _(KEYMAP, DIFF), \
763 _(KEYMAP, LOG), \
764 _(KEYMAP, TREE), \
765 _(KEYMAP, BLOB), \
766 _(KEYMAP, BLAME), \
767 _(KEYMAP, BRANCH), \
768 _(KEYMAP, PAGER), \
769 _(KEYMAP, HELP), \
770 _(KEYMAP, STATUS), \
771 _(KEYMAP, STAGE)
773 DEFINE_ENUM(keymap, KEYMAP_ENUM);
775 #define set_keymap(map, name) map_enum(map, keymap_map, name)
777 struct keybinding_table {
778 struct keybinding *data;
779 size_t size;
782 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_map)];
784 static void
785 add_keybinding(enum keymap keymap, enum request request, int key)
787 struct keybinding_table *table = &keybindings[keymap];
788 size_t i;
790 for (i = 0; i < keybindings[keymap].size; i++) {
791 if (keybindings[keymap].data[i].alias == key) {
792 keybindings[keymap].data[i].request = request;
793 return;
797 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
798 if (!table->data)
799 die("Failed to allocate keybinding");
800 table->data[table->size].alias = key;
801 table->data[table->size++].request = request;
803 if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
804 int i;
806 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
807 if (default_keybindings[i].alias == key)
808 default_keybindings[i].request = REQ_NONE;
812 /* Looks for a key binding first in the given map, then in the generic map, and
813 * lastly in the default keybindings. */
814 static enum request
815 get_keybinding(enum keymap keymap, int key)
817 size_t i;
819 for (i = 0; i < keybindings[keymap].size; i++)
820 if (keybindings[keymap].data[i].alias == key)
821 return keybindings[keymap].data[i].request;
823 for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
824 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
825 return keybindings[KEYMAP_GENERIC].data[i].request;
827 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
828 if (default_keybindings[i].alias == key)
829 return default_keybindings[i].request;
831 return (enum request) key;
835 struct key {
836 const char *name;
837 int value;
840 static const struct key key_table[] = {
841 { "Enter", KEY_RETURN },
842 { "Space", ' ' },
843 { "Backspace", KEY_BACKSPACE },
844 { "Tab", KEY_TAB },
845 { "Escape", KEY_ESC },
846 { "Left", KEY_LEFT },
847 { "Right", KEY_RIGHT },
848 { "Up", KEY_UP },
849 { "Down", KEY_DOWN },
850 { "Insert", KEY_IC },
851 { "Delete", KEY_DC },
852 { "Hash", '#' },
853 { "Home", KEY_HOME },
854 { "End", KEY_END },
855 { "PageUp", KEY_PPAGE },
856 { "PageDown", KEY_NPAGE },
857 { "F1", KEY_F(1) },
858 { "F2", KEY_F(2) },
859 { "F3", KEY_F(3) },
860 { "F4", KEY_F(4) },
861 { "F5", KEY_F(5) },
862 { "F6", KEY_F(6) },
863 { "F7", KEY_F(7) },
864 { "F8", KEY_F(8) },
865 { "F9", KEY_F(9) },
866 { "F10", KEY_F(10) },
867 { "F11", KEY_F(11) },
868 { "F12", KEY_F(12) },
871 static int
872 get_key_value(const char *name)
874 int i;
876 for (i = 0; i < ARRAY_SIZE(key_table); i++)
877 if (!strcasecmp(key_table[i].name, name))
878 return key_table[i].value;
880 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
881 return (int)name[1] & 0x1f;
882 if (strlen(name) == 1 && isprint(*name))
883 return (int) *name;
884 return ERR;
887 static const char *
888 get_key_name(int key_value)
890 static char key_char[] = "'X'\0";
891 const char *seq = NULL;
892 int key;
894 for (key = 0; key < ARRAY_SIZE(key_table); key++)
895 if (key_table[key].value == key_value)
896 seq = key_table[key].name;
898 if (seq == NULL && key_value < 0x7f) {
899 char *s = key_char + 1;
901 if (key_value >= 0x20) {
902 *s++ = key_value;
903 } else {
904 *s++ = '^';
905 *s++ = 0x40 | (key_value & 0x1f);
907 *s++ = '\'';
908 *s++ = '\0';
909 seq = key_char;
912 return seq ? seq : "(no key)";
915 static bool
916 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
918 const char *sep = *pos > 0 ? ", " : "";
919 const char *keyname = get_key_name(keybinding->alias);
921 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
924 static bool
925 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
926 enum keymap keymap, bool all)
928 int i;
930 for (i = 0; i < keybindings[keymap].size; i++) {
931 if (keybindings[keymap].data[i].request == request) {
932 if (!append_key(buf, pos, &keybindings[keymap].data[i]))
933 return FALSE;
934 if (!all)
935 break;
939 return TRUE;
942 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
944 static const char *
945 get_keys(enum keymap keymap, enum request request, bool all)
947 static char buf[BUFSIZ];
948 size_t pos = 0;
949 int i;
951 buf[pos] = 0;
953 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
954 return "Too many keybindings!";
955 if (pos > 0 && !all)
956 return buf;
958 if (keymap != KEYMAP_GENERIC) {
959 /* Only the generic keymap includes the default keybindings when
960 * listing all keys. */
961 if (all)
962 return buf;
964 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
965 return "Too many keybindings!";
966 if (pos)
967 return buf;
970 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
971 if (default_keybindings[i].request == request) {
972 if (!append_key(buf, &pos, &default_keybindings[i]))
973 return "Too many keybindings!";
974 if (!all)
975 return buf;
979 return buf;
982 struct run_request {
983 enum keymap keymap;
984 int key;
985 const char **argv;
988 static struct run_request *run_request;
989 static size_t run_requests;
991 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
993 static enum request
994 add_run_request(enum keymap keymap, int key, const char **argv)
996 struct run_request *req;
998 if (!realloc_run_requests(&run_request, run_requests, 1))
999 return REQ_NONE;
1001 req = &run_request[run_requests];
1002 req->keymap = keymap;
1003 req->key = key;
1004 req->argv = NULL;
1006 if (!argv_copy(&req->argv, argv))
1007 return REQ_NONE;
1009 return REQ_NONE + ++run_requests;
1012 static struct run_request *
1013 get_run_request(enum request request)
1015 if (request <= REQ_NONE)
1016 return NULL;
1017 return &run_request[request - REQ_NONE - 1];
1020 static void
1021 add_builtin_run_requests(void)
1023 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1024 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1025 const char *commit[] = { "git", "commit", NULL };
1026 const char *gc[] = { "git", "gc", NULL };
1027 struct run_request reqs[] = {
1028 { KEYMAP_MAIN, 'C', cherry_pick },
1029 { KEYMAP_STATUS, 'C', commit },
1030 { KEYMAP_BRANCH, 'C', checkout },
1031 { KEYMAP_GENERIC, 'G', gc },
1033 int i;
1035 for (i = 0; i < ARRAY_SIZE(reqs); i++) {
1036 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
1038 if (req != reqs[i].key)
1039 continue;
1040 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
1041 if (req != REQ_NONE)
1042 add_keybinding(reqs[i].keymap, req, reqs[i].key);
1047 * User config file handling.
1050 #define OPT_ERR_INFO \
1051 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1052 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1053 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1054 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1055 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1056 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1057 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1058 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1059 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1060 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1061 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1062 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1063 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1064 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1065 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1066 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1067 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1069 enum option_code {
1070 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1071 OPT_ERR_INFO
1072 #undef OPT_ERR_
1073 OPT_OK
1076 static const char *option_errors[] = {
1077 #define OPT_ERR_(name, msg) msg
1078 OPT_ERR_INFO
1079 #undef OPT_ERR_
1082 static const struct enum_map color_map[] = {
1083 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1084 COLOR_MAP(DEFAULT),
1085 COLOR_MAP(BLACK),
1086 COLOR_MAP(BLUE),
1087 COLOR_MAP(CYAN),
1088 COLOR_MAP(GREEN),
1089 COLOR_MAP(MAGENTA),
1090 COLOR_MAP(RED),
1091 COLOR_MAP(WHITE),
1092 COLOR_MAP(YELLOW),
1095 static const struct enum_map attr_map[] = {
1096 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1097 ATTR_MAP(NORMAL),
1098 ATTR_MAP(BLINK),
1099 ATTR_MAP(BOLD),
1100 ATTR_MAP(DIM),
1101 ATTR_MAP(REVERSE),
1102 ATTR_MAP(STANDOUT),
1103 ATTR_MAP(UNDERLINE),
1106 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1108 static enum option_code
1109 parse_step(double *opt, const char *arg)
1111 *opt = atoi(arg);
1112 if (!strchr(arg, '%'))
1113 return OPT_OK;
1115 /* "Shift down" so 100% and 1 does not conflict. */
1116 *opt = (*opt - 1) / 100;
1117 if (*opt >= 1.0) {
1118 *opt = 0.99;
1119 return OPT_ERR_INVALID_STEP_VALUE;
1121 if (*opt < 0.0) {
1122 *opt = 1;
1123 return OPT_ERR_INVALID_STEP_VALUE;
1125 return OPT_OK;
1128 static enum option_code
1129 parse_int(int *opt, const char *arg, int min, int max)
1131 int value = atoi(arg);
1133 if (min <= value && value <= max) {
1134 *opt = value;
1135 return OPT_OK;
1138 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1141 static bool
1142 set_color(int *color, const char *name)
1144 if (map_enum(color, color_map, name))
1145 return TRUE;
1146 if (!prefixcmp(name, "color"))
1147 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1148 return FALSE;
1151 /* Wants: object fgcolor bgcolor [attribute] */
1152 static enum option_code
1153 option_color_command(int argc, const char *argv[])
1155 struct line_info *info;
1157 if (argc < 3)
1158 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1160 if (*argv[0] == '"' || *argv[0] == '\'') {
1161 info = add_custom_color(argv[0]);
1162 } else {
1163 info = get_line_info(argv[0]);
1165 if (!info) {
1166 static const struct enum_map obsolete[] = {
1167 ENUM_MAP("main-delim", LINE_DELIMITER),
1168 ENUM_MAP("main-date", LINE_DATE),
1169 ENUM_MAP("main-author", LINE_AUTHOR),
1171 int index;
1173 if (!map_enum(&index, obsolete, argv[0]))
1174 return OPT_ERR_UNKNOWN_COLOR_NAME;
1175 info = &line_info[index];
1178 if (!set_color(&info->fg, argv[1]) ||
1179 !set_color(&info->bg, argv[2]))
1180 return OPT_ERR_UNKNOWN_COLOR;
1182 info->attr = 0;
1183 while (argc-- > 3) {
1184 int attr;
1186 if (!set_attribute(&attr, argv[argc]))
1187 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1188 info->attr |= attr;
1191 return OPT_OK;
1194 static enum option_code
1195 parse_bool(bool *opt, const char *arg)
1197 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1198 ? TRUE : FALSE;
1199 return OPT_OK;
1202 static enum option_code
1203 parse_enum_do(unsigned int *opt, const char *arg,
1204 const struct enum_map *map, size_t map_size)
1206 bool is_true;
1208 assert(map_size > 1);
1210 if (map_enum_do(map, map_size, (int *) opt, arg))
1211 return OPT_OK;
1213 parse_bool(&is_true, arg);
1214 *opt = is_true ? map[1].value : map[0].value;
1215 return OPT_OK;
1218 #define parse_enum(opt, arg, map) \
1219 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1221 static enum option_code
1222 parse_string(char *opt, const char *arg, size_t optsize)
1224 int arglen = strlen(arg);
1226 switch (arg[0]) {
1227 case '\"':
1228 case '\'':
1229 if (arglen == 1 || arg[arglen - 1] != arg[0])
1230 return OPT_ERR_UNMATCHED_QUOTATION;
1231 arg += 1; arglen -= 2;
1232 default:
1233 string_ncopy_do(opt, optsize, arg, arglen);
1234 return OPT_OK;
1238 static enum option_code
1239 parse_args(const char ***args, const char *argv[])
1241 if (*args == NULL && !argv_copy(args, argv))
1242 return OPT_ERR_OUT_OF_MEMORY;
1243 return OPT_OK;
1246 /* Wants: name = value */
1247 static enum option_code
1248 option_set_command(int argc, const char *argv[])
1250 if (argc < 3)
1251 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1253 if (strcmp(argv[1], "="))
1254 return OPT_ERR_NO_VALUE_ASSIGNED;
1256 if (!strcmp(argv[0], "blame-options"))
1257 return parse_args(&opt_blame_argv, argv + 2);
1259 if (argc != 3)
1260 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1262 if (!strcmp(argv[0], "show-author"))
1263 return parse_enum(&opt_author, argv[2], author_map);
1265 if (!strcmp(argv[0], "show-date"))
1266 return parse_enum(&opt_date, argv[2], date_map);
1268 if (!strcmp(argv[0], "show-rev-graph"))
1269 return parse_bool(&opt_rev_graph, argv[2]);
1271 if (!strcmp(argv[0], "show-refs"))
1272 return parse_bool(&opt_show_refs, argv[2]);
1274 if (!strcmp(argv[0], "show-notes")) {
1275 int res;
1277 strcpy(opt_notes_arg, "--notes=");
1278 res = parse_string(opt_notes_arg + 8, argv[2],
1279 sizeof(opt_notes_arg) - 8);
1280 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1281 opt_notes_arg[7] = '\0';
1282 return res;
1285 if (!strcmp(argv[0], "show-line-numbers"))
1286 return parse_bool(&opt_line_number, argv[2]);
1288 if (!strcmp(argv[0], "line-graphics"))
1289 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1291 if (!strcmp(argv[0], "line-number-interval"))
1292 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1294 if (!strcmp(argv[0], "author-width"))
1295 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1297 if (!strcmp(argv[0], "filename-width"))
1298 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1300 if (!strcmp(argv[0], "show-filename"))
1301 return parse_enum(&opt_filename, argv[2], filename_map);
1303 if (!strcmp(argv[0], "horizontal-scroll"))
1304 return parse_step(&opt_hscroll, argv[2]);
1306 if (!strcmp(argv[0], "split-view-height"))
1307 return parse_step(&opt_scale_split_view, argv[2]);
1309 if (!strcmp(argv[0], "tab-size"))
1310 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1312 if (!strcmp(argv[0], "diff-context")) {
1313 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1315 if (code == OPT_OK)
1316 update_diff_context_arg(opt_diff_context);
1317 return code;
1320 if (!strcmp(argv[0], "commit-encoding"))
1321 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1323 if (!strcmp(argv[0], "status-untracked-dirs"))
1324 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1326 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1329 /* Wants: mode request key */
1330 static enum option_code
1331 option_bind_command(int argc, const char *argv[])
1333 enum request request;
1334 int keymap = -1;
1335 int key;
1337 if (argc < 3)
1338 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1340 if (!set_keymap(&keymap, argv[0]))
1341 return OPT_ERR_UNKNOWN_KEY_MAP;
1343 key = get_key_value(argv[1]);
1344 if (key == ERR)
1345 return OPT_ERR_UNKNOWN_KEY;
1347 request = get_request(argv[2]);
1348 if (request == REQ_UNKNOWN) {
1349 static const struct enum_map obsolete[] = {
1350 ENUM_MAP("cherry-pick", REQ_NONE),
1351 ENUM_MAP("screen-resize", REQ_NONE),
1352 ENUM_MAP("tree-parent", REQ_PARENT),
1354 int alias;
1356 if (map_enum(&alias, obsolete, argv[2])) {
1357 if (alias != REQ_NONE)
1358 add_keybinding(keymap, alias, key);
1359 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1362 if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1363 request = add_run_request(keymap, key, argv + 2);
1364 if (request == REQ_UNKNOWN)
1365 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1367 add_keybinding(keymap, request, key);
1369 return OPT_OK;
1372 static enum option_code
1373 set_option(const char *opt, char *value)
1375 const char *argv[SIZEOF_ARG];
1376 int argc = 0;
1378 if (!argv_from_string(argv, &argc, value))
1379 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1381 if (!strcmp(opt, "color"))
1382 return option_color_command(argc, argv);
1384 if (!strcmp(opt, "set"))
1385 return option_set_command(argc, argv);
1387 if (!strcmp(opt, "bind"))
1388 return option_bind_command(argc, argv);
1390 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1393 struct config_state {
1394 int lineno;
1395 bool errors;
1398 static int
1399 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1401 struct config_state *config = data;
1402 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1404 config->lineno++;
1406 /* Check for comment markers, since read_properties() will
1407 * only ensure opt and value are split at first " \t". */
1408 optlen = strcspn(opt, "#");
1409 if (optlen == 0)
1410 return OK;
1412 if (opt[optlen] == 0) {
1413 /* Look for comment endings in the value. */
1414 size_t len = strcspn(value, "#");
1416 if (len < valuelen) {
1417 valuelen = len;
1418 value[valuelen] = 0;
1421 status = set_option(opt, value);
1424 if (status != OPT_OK) {
1425 warn("Error on line %d, near '%.*s': %s",
1426 config->lineno, (int) optlen, opt, option_errors[status]);
1427 config->errors = TRUE;
1430 /* Always keep going if errors are encountered. */
1431 return OK;
1434 static void
1435 load_option_file(const char *path)
1437 struct config_state config = { 0, FALSE };
1438 struct io io;
1440 /* It's OK that the file doesn't exist. */
1441 if (!io_open(&io, "%s", path))
1442 return;
1444 if (io_load(&io, " \t", read_option, &config) == ERR ||
1445 config.errors == TRUE)
1446 warn("Errors while loading %s.", path);
1449 static int
1450 load_options(void)
1452 const char *home = getenv("HOME");
1453 const char *tigrc_user = getenv("TIGRC_USER");
1454 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1455 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1456 char buf[SIZEOF_STR];
1458 if (!tigrc_system)
1459 tigrc_system = SYSCONFDIR "/tigrc";
1460 load_option_file(tigrc_system);
1462 if (!tigrc_user) {
1463 if (!home || !string_format(buf, "%s/.tigrc", home))
1464 return ERR;
1465 tigrc_user = buf;
1467 load_option_file(tigrc_user);
1469 /* Add _after_ loading config files to avoid adding run requests
1470 * that conflict with keybindings. */
1471 add_builtin_run_requests();
1473 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1474 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1475 int argc = 0;
1477 if (!string_format(buf, "%s", tig_diff_opts) ||
1478 !argv_from_string(diff_opts, &argc, buf))
1479 die("TIG_DIFF_OPTS contains too many arguments");
1480 else if (!argv_copy(&opt_diff_argv, diff_opts))
1481 die("Failed to format TIG_DIFF_OPTS arguments");
1484 return OK;
1489 * The viewer
1492 struct view;
1493 struct view_ops;
1495 /* The display array of active views and the index of the current view. */
1496 static struct view *display[2];
1497 static WINDOW *display_win[2];
1498 static WINDOW *display_title[2];
1499 static unsigned int current_view;
1501 #define foreach_displayed_view(view, i) \
1502 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1504 #define displayed_views() (display[1] != NULL ? 2 : 1)
1506 /* Current head and commit ID */
1507 static char ref_blob[SIZEOF_REF] = "";
1508 static char ref_commit[SIZEOF_REF] = "HEAD";
1509 static char ref_head[SIZEOF_REF] = "HEAD";
1510 static char ref_branch[SIZEOF_REF] = "";
1512 enum view_type {
1513 VIEW_MAIN,
1514 VIEW_DIFF,
1515 VIEW_LOG,
1516 VIEW_TREE,
1517 VIEW_BLOB,
1518 VIEW_BLAME,
1519 VIEW_BRANCH,
1520 VIEW_HELP,
1521 VIEW_PAGER,
1522 VIEW_STATUS,
1523 VIEW_STAGE,
1526 struct view {
1527 enum view_type type; /* View type */
1528 const char *name; /* View name */
1529 const char *id; /* Points to either of ref_{head,commit,blob} */
1531 struct view_ops *ops; /* View operations */
1533 enum keymap keymap; /* What keymap does this view have */
1534 bool git_dir; /* Whether the view requires a git directory. */
1536 char ref[SIZEOF_REF]; /* Hovered commit reference */
1537 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1539 int height, width; /* The width and height of the main window */
1540 WINDOW *win; /* The main window */
1542 /* Navigation */
1543 unsigned long offset; /* Offset of the window top */
1544 unsigned long yoffset; /* Offset from the window side. */
1545 unsigned long lineno; /* Current line number */
1546 unsigned long p_offset; /* Previous offset of the window top */
1547 unsigned long p_yoffset;/* Previous offset from the window side */
1548 unsigned long p_lineno; /* Previous current line number */
1549 bool p_restore; /* Should the previous position be restored. */
1551 /* Searching */
1552 char grep[SIZEOF_STR]; /* Search string */
1553 regex_t *regex; /* Pre-compiled regexp */
1555 /* If non-NULL, points to the view that opened this view. If this view
1556 * is closed tig will switch back to the parent view. */
1557 struct view *parent;
1558 struct view *prev;
1560 /* Buffering */
1561 size_t lines; /* Total number of lines */
1562 struct line *line; /* Line index */
1563 unsigned int digits; /* Number of digits in the lines member. */
1565 /* Drawing */
1566 struct line *curline; /* Line currently being drawn. */
1567 enum line_type curtype; /* Attribute currently used for drawing. */
1568 unsigned long col; /* Column when drawing. */
1569 bool has_scrolled; /* View was scrolled. */
1571 /* Loading */
1572 const char **argv; /* Shell command arguments. */
1573 const char *dir; /* Directory from which to execute. */
1574 struct io io;
1575 struct io *pipe;
1576 time_t start_time;
1577 time_t update_secs;
1579 /* Private data */
1580 void *private;
1583 enum open_flags {
1584 OPEN_DEFAULT = 0, /* Use default view switching. */
1585 OPEN_SPLIT = 1, /* Split current view. */
1586 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1587 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1588 OPEN_PREPARED = 32, /* Open already prepared command. */
1589 OPEN_EXTRA = 64, /* Open extra data from command. */
1592 struct view_ops {
1593 /* What type of content being displayed. Used in the title bar. */
1594 const char *type;
1595 /* Size of private data. */
1596 size_t private_size;
1597 /* Open and reads in all view content. */
1598 bool (*open)(struct view *view, enum open_flags flags);
1599 /* Read one line; updates view->line. */
1600 bool (*read)(struct view *view, char *data);
1601 /* Draw one line; @lineno must be < view->height. */
1602 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1603 /* Depending on view handle a special requests. */
1604 enum request (*request)(struct view *view, enum request request, struct line *line);
1605 /* Search for regexp in a line. */
1606 bool (*grep)(struct view *view, struct line *line);
1607 /* Select line */
1608 void (*select)(struct view *view, struct line *line);
1611 static struct view_ops blame_ops;
1612 static struct view_ops blob_ops;
1613 static struct view_ops diff_ops;
1614 static struct view_ops help_ops;
1615 static struct view_ops log_ops;
1616 static struct view_ops main_ops;
1617 static struct view_ops pager_ops;
1618 static struct view_ops stage_ops;
1619 static struct view_ops status_ops;
1620 static struct view_ops tree_ops;
1621 static struct view_ops branch_ops;
1623 #define VIEW_STR(type, name, ref, ops, map, git) \
1624 { type, name, ref, ops, map, git }
1626 #define VIEW_(id, name, ops, git, ref) \
1627 VIEW_STR(VIEW_##id, name, ref, ops, KEYMAP_##id, git)
1629 static struct view views[] = {
1630 VIEW_(MAIN, "main", &main_ops, TRUE, ref_head),
1631 VIEW_(DIFF, "diff", &diff_ops, TRUE, ref_commit),
1632 VIEW_(LOG, "log", &log_ops, TRUE, ref_head),
1633 VIEW_(TREE, "tree", &tree_ops, TRUE, ref_commit),
1634 VIEW_(BLOB, "blob", &blob_ops, TRUE, ref_blob),
1635 VIEW_(BLAME, "blame", &blame_ops, TRUE, ref_commit),
1636 VIEW_(BRANCH, "branch", &branch_ops, TRUE, ref_head),
1637 VIEW_(HELP, "help", &help_ops, FALSE, ""),
1638 VIEW_(PAGER, "pager", &pager_ops, FALSE, ""),
1639 VIEW_(STATUS, "status", &status_ops, TRUE, "status"),
1640 VIEW_(STAGE, "stage", &stage_ops, TRUE, "stage"),
1643 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1645 #define foreach_view(view, i) \
1646 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1648 #define view_is_displayed(view) \
1649 (view == display[0] || view == display[1])
1651 static enum request
1652 view_request(struct view *view, enum request request)
1654 if (!view || !view->lines)
1655 return request;
1656 return view->ops->request(view, request, &view->line[view->lineno]);
1661 * View drawing.
1664 static inline void
1665 set_view_attr(struct view *view, enum line_type type)
1667 if (!view->curline->selected && view->curtype != type) {
1668 (void) wattrset(view->win, get_line_attr(type));
1669 wchgat(view->win, -1, 0, COLOR_ID(type), NULL);
1670 view->curtype = type;
1674 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1676 static bool
1677 draw_chars(struct view *view, enum line_type type, const char *string,
1678 int max_len, bool use_tilde)
1680 static char out_buffer[BUFSIZ * 2];
1681 int len = 0;
1682 int col = 0;
1683 int trimmed = FALSE;
1684 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1686 if (max_len <= 0)
1687 return VIEW_MAX_LEN(view) <= 0;
1689 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1691 set_view_attr(view, type);
1692 if (len > 0) {
1693 if (opt_iconv_out != ICONV_NONE) {
1694 ICONV_CONST char *inbuf = (ICONV_CONST char *) string;
1695 size_t inlen = len + 1;
1697 char *outbuf = out_buffer;
1698 size_t outlen = sizeof(out_buffer);
1700 size_t ret;
1702 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1703 if (ret != (size_t) -1) {
1704 string = out_buffer;
1705 len = sizeof(out_buffer) - outlen;
1709 waddnstr(view->win, string, len);
1711 if (trimmed && use_tilde) {
1712 set_view_attr(view, LINE_DELIMITER);
1713 waddch(view->win, '~');
1714 col++;
1718 view->col += col;
1719 return VIEW_MAX_LEN(view) <= 0;
1722 static bool
1723 draw_space(struct view *view, enum line_type type, int max, int spaces)
1725 static char space[] = " ";
1727 spaces = MIN(max, spaces);
1729 while (spaces > 0) {
1730 int len = MIN(spaces, sizeof(space) - 1);
1732 if (draw_chars(view, type, space, len, FALSE))
1733 return TRUE;
1734 spaces -= len;
1737 return VIEW_MAX_LEN(view) <= 0;
1740 static bool
1741 draw_text(struct view *view, enum line_type type, const char *string)
1743 char text[SIZEOF_STR];
1745 do {
1746 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1748 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1749 return TRUE;
1750 string += pos;
1751 } while (*string);
1753 return VIEW_MAX_LEN(view) <= 0;
1756 static bool
1757 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1759 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1760 int max = VIEW_MAX_LEN(view);
1761 int i;
1763 if (max < size)
1764 size = max;
1766 set_view_attr(view, type);
1767 /* Using waddch() instead of waddnstr() ensures that
1768 * they'll be rendered correctly for the cursor line. */
1769 for (i = skip; i < size; i++)
1770 waddch(view->win, graphic[i]);
1772 view->col += size;
1773 if (separator) {
1774 if (size < max && skip <= size)
1775 waddch(view->win, ' ');
1776 view->col++;
1779 return VIEW_MAX_LEN(view) <= 0;
1782 static bool
1783 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1785 int max = MIN(VIEW_MAX_LEN(view), len);
1786 int col = view->col;
1788 if (!text)
1789 return draw_space(view, type, max, max);
1791 return draw_chars(view, type, text, max - 1, trim)
1792 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1795 static bool
1796 draw_date(struct view *view, struct time *time)
1798 const char *date = mkdate(time, opt_date);
1799 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1801 if (opt_date == DATE_NO)
1802 return FALSE;
1804 return draw_field(view, LINE_DATE, date, cols, FALSE);
1807 static bool
1808 draw_author(struct view *view, const char *author)
1810 bool trim = author_trim(opt_author_cols);
1811 const char *text = mkauthor(author, opt_author_cols, opt_author);
1813 if (opt_author == AUTHOR_NO)
1814 return FALSE;
1816 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1819 static bool
1820 draw_filename(struct view *view, const char *filename, bool auto_enabled)
1822 bool trim = filename && strlen(filename) >= opt_filename_cols;
1824 if (opt_filename == FILENAME_NO)
1825 return FALSE;
1827 if (opt_filename == FILENAME_AUTO && !auto_enabled)
1828 return FALSE;
1830 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
1833 static bool
1834 draw_mode(struct view *view, mode_t mode)
1836 const char *str = mkmode(mode);
1838 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1841 static bool
1842 draw_lineno(struct view *view, unsigned int lineno)
1844 char number[10];
1845 int digits3 = view->digits < 3 ? 3 : view->digits;
1846 int max = MIN(VIEW_MAX_LEN(view), digits3);
1847 char *text = NULL;
1848 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1850 lineno += view->offset + 1;
1851 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1852 static char fmt[] = "%1ld";
1854 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1855 if (string_format(number, fmt, lineno))
1856 text = number;
1858 if (text)
1859 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1860 else
1861 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1862 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1865 static bool
1866 draw_refs(struct view *view, struct ref_list *refs)
1868 size_t i;
1870 if (!opt_show_refs || !refs)
1871 return FALSE;
1873 for (i = 0; i < refs->size; i++) {
1874 struct ref *ref = refs->refs[i];
1875 enum line_type type = get_line_type_from_ref(ref);
1877 if (draw_text(view, type, "[") ||
1878 draw_text(view, type, ref->name) ||
1879 draw_text(view, type, "]"))
1880 return TRUE;
1882 if (draw_text(view, LINE_DEFAULT, " "))
1883 return TRUE;
1886 return FALSE;
1889 static bool
1890 draw_view_line(struct view *view, unsigned int lineno)
1892 struct line *line;
1893 bool selected = (view->offset + lineno == view->lineno);
1895 assert(view_is_displayed(view));
1897 if (view->offset + lineno >= view->lines)
1898 return FALSE;
1900 line = &view->line[view->offset + lineno];
1902 wmove(view->win, lineno, 0);
1903 if (line->cleareol)
1904 wclrtoeol(view->win);
1905 view->col = 0;
1906 view->curline = line;
1907 view->curtype = LINE_NONE;
1908 line->selected = FALSE;
1909 line->dirty = line->cleareol = 0;
1911 if (selected) {
1912 set_view_attr(view, LINE_CURSOR);
1913 line->selected = TRUE;
1914 view->ops->select(view, line);
1917 return view->ops->draw(view, line, lineno);
1920 static void
1921 redraw_view_dirty(struct view *view)
1923 bool dirty = FALSE;
1924 int lineno;
1926 for (lineno = 0; lineno < view->height; lineno++) {
1927 if (view->offset + lineno >= view->lines)
1928 break;
1929 if (!view->line[view->offset + lineno].dirty)
1930 continue;
1931 dirty = TRUE;
1932 if (!draw_view_line(view, lineno))
1933 break;
1936 if (!dirty)
1937 return;
1938 wnoutrefresh(view->win);
1941 static void
1942 redraw_view_from(struct view *view, int lineno)
1944 assert(0 <= lineno && lineno < view->height);
1946 for (; lineno < view->height; lineno++) {
1947 if (!draw_view_line(view, lineno))
1948 break;
1951 wnoutrefresh(view->win);
1954 static void
1955 redraw_view(struct view *view)
1957 werase(view->win);
1958 redraw_view_from(view, 0);
1962 static void
1963 update_view_title(struct view *view)
1965 char buf[SIZEOF_STR];
1966 char state[SIZEOF_STR];
1967 size_t bufpos = 0, statelen = 0;
1968 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1970 assert(view_is_displayed(view));
1972 if (view->type != VIEW_STATUS && view->lines) {
1973 unsigned int view_lines = view->offset + view->height;
1974 unsigned int lines = view->lines
1975 ? MIN(view_lines, view->lines) * 100 / view->lines
1976 : 0;
1978 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
1979 view->ops->type,
1980 view->lineno + 1,
1981 view->lines,
1982 lines);
1986 if (view->pipe) {
1987 time_t secs = time(NULL) - view->start_time;
1989 /* Three git seconds are a long time ... */
1990 if (secs > 2)
1991 string_format_from(state, &statelen, " loading %lds", secs);
1994 string_format_from(buf, &bufpos, "[%s]", view->name);
1995 if (*view->ref && bufpos < view->width) {
1996 size_t refsize = strlen(view->ref);
1997 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
1999 if (minsize < view->width)
2000 refsize = view->width - minsize + 7;
2001 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2004 if (statelen && bufpos < view->width) {
2005 string_format_from(buf, &bufpos, "%s", state);
2008 if (view == display[current_view])
2009 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2010 else
2011 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2013 mvwaddnstr(window, 0, 0, buf, bufpos);
2014 wclrtoeol(window);
2015 wnoutrefresh(window);
2018 static int
2019 apply_step(double step, int value)
2021 if (step >= 1)
2022 return (int) step;
2023 value *= step + 0.01;
2024 return value ? value : 1;
2027 static void
2028 resize_display(void)
2030 int offset, i;
2031 struct view *base = display[0];
2032 struct view *view = display[1] ? display[1] : display[0];
2034 /* Setup window dimensions */
2036 getmaxyx(stdscr, base->height, base->width);
2038 /* Make room for the status window. */
2039 base->height -= 1;
2041 if (view != base) {
2042 /* Horizontal split. */
2043 view->width = base->width;
2044 view->height = apply_step(opt_scale_split_view, base->height);
2045 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2046 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2047 base->height -= view->height;
2049 /* Make room for the title bar. */
2050 view->height -= 1;
2053 /* Make room for the title bar. */
2054 base->height -= 1;
2056 offset = 0;
2058 foreach_displayed_view (view, i) {
2059 if (!display_win[i]) {
2060 display_win[i] = newwin(view->height, view->width, offset, 0);
2061 if (!display_win[i])
2062 die("Failed to create %s view", view->name);
2064 scrollok(display_win[i], FALSE);
2066 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2067 if (!display_title[i])
2068 die("Failed to create title window");
2070 } else {
2071 wresize(display_win[i], view->height, view->width);
2072 mvwin(display_win[i], offset, 0);
2073 mvwin(display_title[i], offset + view->height, 0);
2076 view->win = display_win[i];
2078 offset += view->height + 1;
2082 static void
2083 redraw_display(bool clear)
2085 struct view *view;
2086 int i;
2088 foreach_displayed_view (view, i) {
2089 if (clear)
2090 wclear(view->win);
2091 redraw_view(view);
2092 update_view_title(view);
2098 * Option management
2101 #define TOGGLE_MENU \
2102 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2103 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2104 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2105 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2106 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2107 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2108 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL)
2110 static void
2111 toggle_option(enum request request)
2113 const struct {
2114 enum request request;
2115 const struct enum_map *map;
2116 size_t map_size;
2117 } data[] = {
2118 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2119 TOGGLE_MENU
2120 #undef TOGGLE_
2122 const struct menu_item menu[] = {
2123 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2124 TOGGLE_MENU
2125 #undef TOGGLE_
2126 { 0 }
2128 int i = 0;
2130 if (request == REQ_OPTIONS) {
2131 if (!prompt_menu("Toggle option", menu, &i))
2132 return;
2133 } else {
2134 while (i < ARRAY_SIZE(data) && data[i].request != request)
2135 i++;
2136 if (i >= ARRAY_SIZE(data))
2137 die("Invalid request (%d)", request);
2140 if (data[i].map != NULL) {
2141 unsigned int *opt = menu[i].data;
2143 *opt = (*opt + 1) % data[i].map_size;
2144 redraw_display(FALSE);
2145 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2147 } else {
2148 bool *option = menu[i].data;
2150 *option = !*option;
2151 redraw_display(FALSE);
2152 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2156 static void
2157 maximize_view(struct view *view, bool redraw)
2159 memset(display, 0, sizeof(display));
2160 current_view = 0;
2161 display[current_view] = view;
2162 resize_display();
2163 if (redraw) {
2164 redraw_display(FALSE);
2165 report("");
2171 * Navigation
2174 static bool
2175 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2177 if (lineno >= view->lines)
2178 lineno = view->lines > 0 ? view->lines - 1 : 0;
2180 if (offset > lineno || offset + view->height <= lineno) {
2181 unsigned long half = view->height / 2;
2183 if (lineno > half)
2184 offset = lineno - half;
2185 else
2186 offset = 0;
2189 if (offset != view->offset || lineno != view->lineno) {
2190 view->offset = offset;
2191 view->lineno = lineno;
2192 return TRUE;
2195 return FALSE;
2198 /* Scrolling backend */
2199 static void
2200 do_scroll_view(struct view *view, int lines)
2202 bool redraw_current_line = FALSE;
2204 /* The rendering expects the new offset. */
2205 view->offset += lines;
2207 assert(0 <= view->offset && view->offset < view->lines);
2208 assert(lines);
2210 /* Move current line into the view. */
2211 if (view->lineno < view->offset) {
2212 view->lineno = view->offset;
2213 redraw_current_line = TRUE;
2214 } else if (view->lineno >= view->offset + view->height) {
2215 view->lineno = view->offset + view->height - 1;
2216 redraw_current_line = TRUE;
2219 assert(view->offset <= view->lineno && view->lineno < view->lines);
2221 /* Redraw the whole screen if scrolling is pointless. */
2222 if (view->height < ABS(lines)) {
2223 redraw_view(view);
2225 } else {
2226 int line = lines > 0 ? view->height - lines : 0;
2227 int end = line + ABS(lines);
2229 scrollok(view->win, TRUE);
2230 wscrl(view->win, lines);
2231 scrollok(view->win, FALSE);
2233 while (line < end && draw_view_line(view, line))
2234 line++;
2236 if (redraw_current_line)
2237 draw_view_line(view, view->lineno - view->offset);
2238 wnoutrefresh(view->win);
2241 view->has_scrolled = TRUE;
2242 report("");
2245 /* Scroll frontend */
2246 static void
2247 scroll_view(struct view *view, enum request request)
2249 int lines = 1;
2251 assert(view_is_displayed(view));
2253 switch (request) {
2254 case REQ_SCROLL_FIRST_COL:
2255 view->yoffset = 0;
2256 redraw_view_from(view, 0);
2257 report("");
2258 return;
2259 case REQ_SCROLL_LEFT:
2260 if (view->yoffset == 0) {
2261 report("Cannot scroll beyond the first column");
2262 return;
2264 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2265 view->yoffset = 0;
2266 else
2267 view->yoffset -= apply_step(opt_hscroll, view->width);
2268 redraw_view_from(view, 0);
2269 report("");
2270 return;
2271 case REQ_SCROLL_RIGHT:
2272 view->yoffset += apply_step(opt_hscroll, view->width);
2273 redraw_view(view);
2274 report("");
2275 return;
2276 case REQ_SCROLL_PAGE_DOWN:
2277 lines = view->height;
2278 case REQ_SCROLL_LINE_DOWN:
2279 if (view->offset + lines > view->lines)
2280 lines = view->lines - view->offset;
2282 if (lines == 0 || view->offset + view->height >= view->lines) {
2283 report("Cannot scroll beyond the last line");
2284 return;
2286 break;
2288 case REQ_SCROLL_PAGE_UP:
2289 lines = view->height;
2290 case REQ_SCROLL_LINE_UP:
2291 if (lines > view->offset)
2292 lines = view->offset;
2294 if (lines == 0) {
2295 report("Cannot scroll beyond the first line");
2296 return;
2299 lines = -lines;
2300 break;
2302 default:
2303 die("request %d not handled in switch", request);
2306 do_scroll_view(view, lines);
2309 /* Cursor moving */
2310 static void
2311 move_view(struct view *view, enum request request)
2313 int scroll_steps = 0;
2314 int steps;
2316 switch (request) {
2317 case REQ_MOVE_FIRST_LINE:
2318 steps = -view->lineno;
2319 break;
2321 case REQ_MOVE_LAST_LINE:
2322 steps = view->lines - view->lineno - 1;
2323 break;
2325 case REQ_MOVE_PAGE_UP:
2326 steps = view->height > view->lineno
2327 ? -view->lineno : -view->height;
2328 break;
2330 case REQ_MOVE_PAGE_DOWN:
2331 steps = view->lineno + view->height >= view->lines
2332 ? view->lines - view->lineno - 1 : view->height;
2333 break;
2335 case REQ_MOVE_UP:
2336 steps = -1;
2337 break;
2339 case REQ_MOVE_DOWN:
2340 steps = 1;
2341 break;
2343 default:
2344 die("request %d not handled in switch", request);
2347 if (steps <= 0 && view->lineno == 0) {
2348 report("Cannot move beyond the first line");
2349 return;
2351 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2352 report("Cannot move beyond the last line");
2353 return;
2356 /* Move the current line */
2357 view->lineno += steps;
2358 assert(0 <= view->lineno && view->lineno < view->lines);
2360 /* Check whether the view needs to be scrolled */
2361 if (view->lineno < view->offset ||
2362 view->lineno >= view->offset + view->height) {
2363 scroll_steps = steps;
2364 if (steps < 0 && -steps > view->offset) {
2365 scroll_steps = -view->offset;
2367 } else if (steps > 0) {
2368 if (view->lineno == view->lines - 1 &&
2369 view->lines > view->height) {
2370 scroll_steps = view->lines - view->offset - 1;
2371 if (scroll_steps >= view->height)
2372 scroll_steps -= view->height - 1;
2377 if (!view_is_displayed(view)) {
2378 view->offset += scroll_steps;
2379 assert(0 <= view->offset && view->offset < view->lines);
2380 view->ops->select(view, &view->line[view->lineno]);
2381 return;
2384 /* Repaint the old "current" line if we be scrolling */
2385 if (ABS(steps) < view->height)
2386 draw_view_line(view, view->lineno - steps - view->offset);
2388 if (scroll_steps) {
2389 do_scroll_view(view, scroll_steps);
2390 return;
2393 /* Draw the current line */
2394 draw_view_line(view, view->lineno - view->offset);
2396 wnoutrefresh(view->win);
2397 report("");
2402 * Searching
2405 static void search_view(struct view *view, enum request request);
2407 static bool
2408 grep_text(struct view *view, const char *text[])
2410 regmatch_t pmatch;
2411 size_t i;
2413 for (i = 0; text[i]; i++)
2414 if (*text[i] &&
2415 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2416 return TRUE;
2417 return FALSE;
2420 static void
2421 select_view_line(struct view *view, unsigned long lineno)
2423 unsigned long old_lineno = view->lineno;
2424 unsigned long old_offset = view->offset;
2426 if (goto_view_line(view, view->offset, lineno)) {
2427 if (view_is_displayed(view)) {
2428 if (old_offset != view->offset) {
2429 redraw_view(view);
2430 } else {
2431 draw_view_line(view, old_lineno - view->offset);
2432 draw_view_line(view, view->lineno - view->offset);
2433 wnoutrefresh(view->win);
2435 } else {
2436 view->ops->select(view, &view->line[view->lineno]);
2441 static void
2442 find_next(struct view *view, enum request request)
2444 unsigned long lineno = view->lineno;
2445 int direction;
2447 if (!*view->grep) {
2448 if (!*opt_search)
2449 report("No previous search");
2450 else
2451 search_view(view, request);
2452 return;
2455 switch (request) {
2456 case REQ_SEARCH:
2457 case REQ_FIND_NEXT:
2458 direction = 1;
2459 break;
2461 case REQ_SEARCH_BACK:
2462 case REQ_FIND_PREV:
2463 direction = -1;
2464 break;
2466 default:
2467 return;
2470 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2471 lineno += direction;
2473 /* Note, lineno is unsigned long so will wrap around in which case it
2474 * will become bigger than view->lines. */
2475 for (; lineno < view->lines; lineno += direction) {
2476 if (view->ops->grep(view, &view->line[lineno])) {
2477 select_view_line(view, lineno);
2478 report("Line %ld matches '%s'", lineno + 1, view->grep);
2479 return;
2483 report("No match found for '%s'", view->grep);
2486 static void
2487 search_view(struct view *view, enum request request)
2489 int regex_err;
2491 if (view->regex) {
2492 regfree(view->regex);
2493 *view->grep = 0;
2494 } else {
2495 view->regex = calloc(1, sizeof(*view->regex));
2496 if (!view->regex)
2497 return;
2500 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2501 if (regex_err != 0) {
2502 char buf[SIZEOF_STR] = "unknown error";
2504 regerror(regex_err, view->regex, buf, sizeof(buf));
2505 report("Search failed: %s", buf);
2506 return;
2509 string_copy(view->grep, opt_search);
2511 find_next(view, request);
2515 * Incremental updating
2518 static void
2519 reset_view(struct view *view)
2521 int i;
2523 for (i = 0; i < view->lines; i++)
2524 free(view->line[i].data);
2525 free(view->line);
2527 view->p_offset = view->offset;
2528 view->p_yoffset = view->yoffset;
2529 view->p_lineno = view->lineno;
2531 view->line = NULL;
2532 view->offset = 0;
2533 view->yoffset = 0;
2534 view->lines = 0;
2535 view->lineno = 0;
2536 view->vid[0] = 0;
2537 view->update_secs = 0;
2540 static const char *
2541 format_arg(const char *name)
2543 static struct {
2544 const char *name;
2545 size_t namelen;
2546 const char *value;
2547 const char *value_if_empty;
2548 } vars[] = {
2549 #define FORMAT_VAR(name, value, value_if_empty) \
2550 { name, STRING_SIZE(name), value, value_if_empty }
2551 FORMAT_VAR("%(directory)", opt_path, "."),
2552 FORMAT_VAR("%(file)", opt_file, ""),
2553 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2554 FORMAT_VAR("%(head)", ref_head, ""),
2555 FORMAT_VAR("%(commit)", ref_commit, ""),
2556 FORMAT_VAR("%(blob)", ref_blob, ""),
2557 FORMAT_VAR("%(branch)", ref_branch, ""),
2559 int i;
2561 for (i = 0; i < ARRAY_SIZE(vars); i++)
2562 if (!strncmp(name, vars[i].name, vars[i].namelen))
2563 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2565 report("Unknown replacement: `%s`", name);
2566 return NULL;
2569 static bool
2570 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2572 char buf[SIZEOF_STR];
2573 int argc;
2575 argv_free(*dst_argv);
2577 for (argc = 0; src_argv[argc]; argc++) {
2578 const char *arg = src_argv[argc];
2579 size_t bufpos = 0;
2581 if (!strcmp(arg, "%(fileargs)")) {
2582 if (!argv_append_array(dst_argv, opt_file_argv))
2583 break;
2584 continue;
2586 } else if (!strcmp(arg, "%(diffargs)")) {
2587 if (!argv_append_array(dst_argv, opt_diff_argv))
2588 break;
2589 continue;
2591 } else if (!strcmp(arg, "%(blameargs)")) {
2592 if (!argv_append_array(dst_argv, opt_blame_argv))
2593 break;
2594 continue;
2596 } else if (!strcmp(arg, "%(revargs)") ||
2597 (first && !strcmp(arg, "%(commit)"))) {
2598 if (!argv_append_array(dst_argv, opt_rev_argv))
2599 break;
2600 continue;
2603 while (arg) {
2604 char *next = strstr(arg, "%(");
2605 int len = next - arg;
2606 const char *value;
2608 if (!next) {
2609 len = strlen(arg);
2610 value = "";
2612 } else {
2613 value = format_arg(next);
2615 if (!value) {
2616 return FALSE;
2620 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2621 return FALSE;
2623 arg = next ? strchr(next, ')') + 1 : NULL;
2626 if (!argv_append(dst_argv, buf))
2627 break;
2630 return src_argv[argc] == NULL;
2633 static bool
2634 restore_view_position(struct view *view)
2636 /* A view without a previous view is the first view */
2637 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2638 select_view_line(view, opt_lineno - 1);
2639 opt_lineno = 0;
2642 if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2643 return FALSE;
2645 /* Changing the view position cancels the restoring. */
2646 /* FIXME: Changing back to the first line is not detected. */
2647 if (view->offset != 0 || view->lineno != 0) {
2648 view->p_restore = FALSE;
2649 return FALSE;
2652 if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2653 view_is_displayed(view))
2654 werase(view->win);
2656 view->yoffset = view->p_yoffset;
2657 view->p_restore = FALSE;
2659 return TRUE;
2662 static void
2663 end_update(struct view *view, bool force)
2665 if (!view->pipe)
2666 return;
2667 while (!view->ops->read(view, NULL))
2668 if (!force)
2669 return;
2670 if (force)
2671 io_kill(view->pipe);
2672 io_done(view->pipe);
2673 view->pipe = NULL;
2676 static void
2677 setup_update(struct view *view, const char *vid)
2679 reset_view(view);
2680 string_copy_rev(view->vid, vid);
2681 view->pipe = &view->io;
2682 view->start_time = time(NULL);
2685 static bool
2686 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2688 bool extra = !!(flags & (OPEN_EXTRA));
2689 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2690 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2692 if (!reload && !strcmp(view->vid, view->id))
2693 return TRUE;
2695 if (view->pipe) {
2696 if (extra)
2697 io_done(view->pipe);
2698 else
2699 end_update(view, TRUE);
2702 if (!refresh && argv) {
2703 view->dir = dir;
2704 if (!format_argv(&view->argv, argv, !view->prev))
2705 return FALSE;
2707 /* Put the current ref_* value to the view title ref
2708 * member. This is needed by the blob view. Most other
2709 * views sets it automatically after loading because the
2710 * first line is a commit line. */
2711 string_copy_rev(view->ref, view->id);
2714 if (view->argv && view->argv[0] &&
2715 !io_run(&view->io, IO_RD, view->dir, view->argv))
2716 return FALSE;
2718 if (!extra)
2719 setup_update(view, view->id);
2721 return TRUE;
2724 static bool
2725 update_view(struct view *view)
2727 char out_buffer[BUFSIZ * 2];
2728 char *line;
2729 /* Clear the view and redraw everything since the tree sorting
2730 * might have rearranged things. */
2731 bool redraw = view->lines == 0;
2732 bool can_read = TRUE;
2734 if (!view->pipe)
2735 return TRUE;
2737 if (!io_can_read(view->pipe, FALSE)) {
2738 if (view->lines == 0 && view_is_displayed(view)) {
2739 time_t secs = time(NULL) - view->start_time;
2741 if (secs > 1 && secs > view->update_secs) {
2742 if (view->update_secs == 0)
2743 redraw_view(view);
2744 update_view_title(view);
2745 view->update_secs = secs;
2748 return TRUE;
2751 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2752 if (opt_iconv_in != ICONV_NONE) {
2753 ICONV_CONST char *inbuf = line;
2754 size_t inlen = strlen(line) + 1;
2756 char *outbuf = out_buffer;
2757 size_t outlen = sizeof(out_buffer);
2759 size_t ret;
2761 ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2762 if (ret != (size_t) -1)
2763 line = out_buffer;
2766 if (!view->ops->read(view, line)) {
2767 report("Allocation failure");
2768 end_update(view, TRUE);
2769 return FALSE;
2774 unsigned long lines = view->lines;
2775 int digits;
2777 for (digits = 0; lines; digits++)
2778 lines /= 10;
2780 /* Keep the displayed view in sync with line number scaling. */
2781 if (digits != view->digits) {
2782 view->digits = digits;
2783 if (opt_line_number || view->type == VIEW_BLAME)
2784 redraw = TRUE;
2788 if (io_error(view->pipe)) {
2789 report("Failed to read: %s", io_strerror(view->pipe));
2790 end_update(view, TRUE);
2792 } else if (io_eof(view->pipe)) {
2793 if (view_is_displayed(view))
2794 report("");
2795 end_update(view, FALSE);
2798 if (restore_view_position(view))
2799 redraw = TRUE;
2801 if (!view_is_displayed(view))
2802 return TRUE;
2804 if (redraw)
2805 redraw_view_from(view, 0);
2806 else
2807 redraw_view_dirty(view);
2809 /* Update the title _after_ the redraw so that if the redraw picks up a
2810 * commit reference in view->ref it'll be available here. */
2811 update_view_title(view);
2812 return TRUE;
2815 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2817 static struct line *
2818 add_line_data(struct view *view, void *data, enum line_type type)
2820 struct line *line;
2822 if (!realloc_lines(&view->line, view->lines, 1))
2823 return NULL;
2825 line = &view->line[view->lines++];
2826 memset(line, 0, sizeof(*line));
2827 line->type = type;
2828 line->data = data;
2829 line->dirty = 1;
2831 return line;
2834 static struct line *
2835 add_line_text(struct view *view, const char *text, enum line_type type)
2837 char *data = text ? strdup(text) : NULL;
2839 return data ? add_line_data(view, data, type) : NULL;
2842 static struct line *
2843 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2845 char buf[SIZEOF_STR];
2846 va_list args;
2848 va_start(args, fmt);
2849 if (vsnprintf(buf, sizeof(buf), fmt, args) >= sizeof(buf))
2850 buf[0] = 0;
2851 va_end(args);
2853 return buf[0] ? add_line_text(view, buf, type) : NULL;
2857 * View opening
2860 static void
2861 load_view(struct view *view, enum open_flags flags)
2863 if (view->pipe)
2864 end_update(view, TRUE);
2865 if (view->ops->private_size) {
2866 if (!view->private)
2867 view->private = calloc(1, view->ops->private_size);
2868 else
2869 memset(view->private, 0, view->ops->private_size);
2871 if (!view->ops->open(view, flags)) {
2872 report("Failed to load %s view", view->name);
2873 return;
2875 restore_view_position(view);
2877 if (view->pipe && view->lines == 0) {
2878 /* Clear the old view and let the incremental updating refill
2879 * the screen. */
2880 werase(view->win);
2881 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2882 report("");
2883 } else if (view_is_displayed(view)) {
2884 redraw_view(view);
2885 report("");
2889 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2890 #define reload_view(view) load_view(view, OPEN_RELOAD)
2892 static void
2893 split_view(struct view *prev, struct view *view)
2895 display[1] = view;
2896 current_view = 1;
2897 view->parent = prev;
2898 resize_display();
2900 if (prev->lineno - prev->offset >= prev->height) {
2901 /* Take the title line into account. */
2902 int lines = prev->lineno - prev->offset - prev->height + 1;
2904 /* Scroll the view that was split if the current line is
2905 * outside the new limited view. */
2906 do_scroll_view(prev, lines);
2909 if (view != prev && view_is_displayed(prev)) {
2910 /* "Blur" the previous view. */
2911 update_view_title(prev);
2915 static void
2916 open_view(struct view *prev, enum request request, enum open_flags flags)
2918 bool split = !!(flags & OPEN_SPLIT);
2919 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
2920 struct view *view = VIEW(request);
2921 int nviews = displayed_views();
2923 assert(flags ^ OPEN_REFRESH);
2925 if (view == prev && nviews == 1 && !reload) {
2926 report("Already in %s view", view->name);
2927 return;
2930 if (view->git_dir && !opt_git_dir[0]) {
2931 report("The %s view is disabled in pager view", view->name);
2932 return;
2935 if (split) {
2936 split_view(prev, view);
2937 } else {
2938 maximize_view(view, FALSE);
2941 /* No prev signals that this is the first loaded view. */
2942 if (prev && view != prev) {
2943 view->prev = prev;
2946 load_view(view, flags);
2949 static void
2950 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
2952 enum request request = view - views + REQ_OFFSET + 1;
2954 if (view->pipe)
2955 end_update(view, TRUE);
2956 view->dir = dir;
2958 if (!argv_copy(&view->argv, argv)) {
2959 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
2960 } else {
2961 open_view(prev, request, flags | OPEN_PREPARED);
2965 static void
2966 open_external_viewer(const char *argv[], const char *dir)
2968 def_prog_mode(); /* save current tty modes */
2969 endwin(); /* restore original tty modes */
2970 io_run_fg(argv, dir);
2971 fprintf(stderr, "Press Enter to continue");
2972 getc(opt_tty);
2973 reset_prog_mode();
2974 redraw_display(TRUE);
2977 static void
2978 open_mergetool(const char *file)
2980 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2982 open_external_viewer(mergetool_argv, opt_cdup);
2985 static void
2986 open_editor(const char *file)
2988 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
2989 char editor_cmd[SIZEOF_STR];
2990 const char *editor;
2991 int argc = 0;
2993 editor = getenv("GIT_EDITOR");
2994 if (!editor && *opt_editor)
2995 editor = opt_editor;
2996 if (!editor)
2997 editor = getenv("VISUAL");
2998 if (!editor)
2999 editor = getenv("EDITOR");
3000 if (!editor)
3001 editor = "vi";
3003 string_ncopy(editor_cmd, editor, strlen(editor));
3004 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3005 report("Failed to read editor command");
3006 return;
3009 editor_argv[argc] = file;
3010 open_external_viewer(editor_argv, opt_cdup);
3013 static void
3014 open_run_request(enum request request)
3016 struct run_request *req = get_run_request(request);
3017 const char **argv = NULL;
3019 if (!req) {
3020 report("Unknown run request");
3021 return;
3024 if (format_argv(&argv, req->argv, FALSE))
3025 open_external_viewer(argv, NULL);
3026 if (argv)
3027 argv_free(argv);
3028 free(argv);
3032 * User request switch noodle
3035 static int
3036 view_driver(struct view *view, enum request request)
3038 int i;
3040 if (request == REQ_NONE)
3041 return TRUE;
3043 if (request > REQ_NONE) {
3044 open_run_request(request);
3045 view_request(view, REQ_REFRESH);
3046 return TRUE;
3049 request = view_request(view, request);
3050 if (request == REQ_NONE)
3051 return TRUE;
3053 switch (request) {
3054 case REQ_MOVE_UP:
3055 case REQ_MOVE_DOWN:
3056 case REQ_MOVE_PAGE_UP:
3057 case REQ_MOVE_PAGE_DOWN:
3058 case REQ_MOVE_FIRST_LINE:
3059 case REQ_MOVE_LAST_LINE:
3060 move_view(view, request);
3061 break;
3063 case REQ_SCROLL_FIRST_COL:
3064 case REQ_SCROLL_LEFT:
3065 case REQ_SCROLL_RIGHT:
3066 case REQ_SCROLL_LINE_DOWN:
3067 case REQ_SCROLL_LINE_UP:
3068 case REQ_SCROLL_PAGE_DOWN:
3069 case REQ_SCROLL_PAGE_UP:
3070 scroll_view(view, request);
3071 break;
3073 case REQ_VIEW_BLAME:
3074 if (!opt_file[0]) {
3075 report("No file chosen, press %s to open tree view",
3076 get_key(view->keymap, REQ_VIEW_TREE));
3077 break;
3079 open_view(view, request, OPEN_DEFAULT);
3080 break;
3082 case REQ_VIEW_BLOB:
3083 if (!ref_blob[0]) {
3084 report("No file chosen, press %s to open tree view",
3085 get_key(view->keymap, REQ_VIEW_TREE));
3086 break;
3088 open_view(view, request, OPEN_DEFAULT);
3089 break;
3091 case REQ_VIEW_PAGER:
3092 if (view == NULL) {
3093 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
3094 die("Failed to open stdin");
3095 open_view(view, request, OPEN_PREPARED);
3096 break;
3099 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
3100 report("No pager content, press %s to run command from prompt",
3101 get_key(view->keymap, REQ_PROMPT));
3102 break;
3104 open_view(view, request, OPEN_DEFAULT);
3105 break;
3107 case REQ_VIEW_STAGE:
3108 if (!VIEW(REQ_VIEW_STAGE)->lines) {
3109 report("No stage content, press %s to open the status view and choose file",
3110 get_key(view->keymap, REQ_VIEW_STATUS));
3111 break;
3113 open_view(view, request, OPEN_DEFAULT);
3114 break;
3116 case REQ_VIEW_STATUS:
3117 if (opt_is_inside_work_tree == FALSE) {
3118 report("The status view requires a working tree");
3119 break;
3121 open_view(view, request, OPEN_DEFAULT);
3122 break;
3124 case REQ_VIEW_MAIN:
3125 case REQ_VIEW_DIFF:
3126 case REQ_VIEW_LOG:
3127 case REQ_VIEW_TREE:
3128 case REQ_VIEW_HELP:
3129 case REQ_VIEW_BRANCH:
3130 open_view(view, request, OPEN_DEFAULT);
3131 break;
3133 case REQ_NEXT:
3134 case REQ_PREVIOUS:
3135 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
3137 if (view->parent) {
3138 int line;
3140 view = view->parent;
3141 line = view->lineno;
3142 move_view(view, request);
3143 if (view_is_displayed(view))
3144 update_view_title(view);
3145 if (line != view->lineno)
3146 view_request(view, REQ_ENTER);
3147 } else {
3148 move_view(view, request);
3150 break;
3152 case REQ_VIEW_NEXT:
3154 int nviews = displayed_views();
3155 int next_view = (current_view + 1) % nviews;
3157 if (next_view == current_view) {
3158 report("Only one view is displayed");
3159 break;
3162 current_view = next_view;
3163 /* Blur out the title of the previous view. */
3164 update_view_title(view);
3165 report("");
3166 break;
3168 case REQ_REFRESH:
3169 report("Refreshing is not yet supported for the %s view", view->name);
3170 break;
3172 case REQ_MAXIMIZE:
3173 if (displayed_views() == 2)
3174 maximize_view(view, TRUE);
3175 break;
3177 case REQ_OPTIONS:
3178 case REQ_TOGGLE_LINENO:
3179 case REQ_TOGGLE_DATE:
3180 case REQ_TOGGLE_AUTHOR:
3181 case REQ_TOGGLE_FILENAME:
3182 case REQ_TOGGLE_GRAPHIC:
3183 case REQ_TOGGLE_REV_GRAPH:
3184 case REQ_TOGGLE_REFS:
3185 toggle_option(request);
3186 break;
3188 case REQ_TOGGLE_SORT_FIELD:
3189 case REQ_TOGGLE_SORT_ORDER:
3190 report("Sorting is not yet supported for the %s view", view->name);
3191 break;
3193 case REQ_DIFF_CONTEXT_UP:
3194 case REQ_DIFF_CONTEXT_DOWN:
3195 report("Changing the diff context is not yet supported for the %s view", view->name);
3196 break;
3198 case REQ_SEARCH:
3199 case REQ_SEARCH_BACK:
3200 search_view(view, request);
3201 break;
3203 case REQ_FIND_NEXT:
3204 case REQ_FIND_PREV:
3205 find_next(view, request);
3206 break;
3208 case REQ_STOP_LOADING:
3209 foreach_view(view, i) {
3210 if (view->pipe)
3211 report("Stopped loading the %s view", view->name),
3212 end_update(view, TRUE);
3214 break;
3216 case REQ_SHOW_VERSION:
3217 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3218 return TRUE;
3220 case REQ_SCREEN_REDRAW:
3221 redraw_display(TRUE);
3222 break;
3224 case REQ_EDIT:
3225 report("Nothing to edit");
3226 break;
3228 case REQ_ENTER:
3229 report("Nothing to enter");
3230 break;
3232 case REQ_VIEW_CLOSE:
3233 /* XXX: Mark closed views by letting view->prev point to the
3234 * view itself. Parents to closed view should never be
3235 * followed. */
3236 if (view->prev && view->prev != view) {
3237 maximize_view(view->prev, TRUE);
3238 view->prev = view;
3239 break;
3241 /* Fall-through */
3242 case REQ_QUIT:
3243 return FALSE;
3245 default:
3246 report("Unknown key, press %s for help",
3247 get_key(view->keymap, REQ_VIEW_HELP));
3248 return TRUE;
3251 return TRUE;
3256 * View backend utilities
3259 enum sort_field {
3260 ORDERBY_NAME,
3261 ORDERBY_DATE,
3262 ORDERBY_AUTHOR,
3265 struct sort_state {
3266 const enum sort_field *fields;
3267 size_t size, current;
3268 bool reverse;
3271 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3272 #define get_sort_field(state) ((state).fields[(state).current])
3273 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3275 static void
3276 sort_view(struct view *view, enum request request, struct sort_state *state,
3277 int (*compare)(const void *, const void *))
3279 switch (request) {
3280 case REQ_TOGGLE_SORT_FIELD:
3281 state->current = (state->current + 1) % state->size;
3282 break;
3284 case REQ_TOGGLE_SORT_ORDER:
3285 state->reverse = !state->reverse;
3286 break;
3287 default:
3288 die("Not a sort request");
3291 qsort(view->line, view->lines, sizeof(*view->line), compare);
3292 redraw_view(view);
3295 static bool
3296 update_diff_context(enum request request)
3298 int diff_context = opt_diff_context;
3300 switch (request) {
3301 case REQ_DIFF_CONTEXT_UP:
3302 opt_diff_context += 1;
3303 update_diff_context_arg(opt_diff_context);
3304 break;
3306 case REQ_DIFF_CONTEXT_DOWN:
3307 if (opt_diff_context == 0) {
3308 report("Diff context cannot be less than zero");
3309 break;
3311 opt_diff_context -= 1;
3312 update_diff_context_arg(opt_diff_context);
3313 break;
3315 default:
3316 die("Not a diff context request");
3319 return diff_context != opt_diff_context;
3322 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3324 /* Small author cache to reduce memory consumption. It uses binary
3325 * search to lookup or find place to position new entries. No entries
3326 * are ever freed. */
3327 static const char *
3328 get_author(const char *name)
3330 static const char **authors;
3331 static size_t authors_size;
3332 int from = 0, to = authors_size - 1;
3334 while (from <= to) {
3335 size_t pos = (to + from) / 2;
3336 int cmp = strcmp(name, authors[pos]);
3338 if (!cmp)
3339 return authors[pos];
3341 if (cmp < 0)
3342 to = pos - 1;
3343 else
3344 from = pos + 1;
3347 if (!realloc_authors(&authors, authors_size, 1))
3348 return NULL;
3349 name = strdup(name);
3350 if (!name)
3351 return NULL;
3353 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3354 authors[from] = name;
3355 authors_size++;
3357 return name;
3360 static void
3361 parse_timesec(struct time *time, const char *sec)
3363 time->sec = (time_t) atol(sec);
3366 static void
3367 parse_timezone(struct time *time, const char *zone)
3369 long tz;
3371 tz = ('0' - zone[1]) * 60 * 60 * 10;
3372 tz += ('0' - zone[2]) * 60 * 60;
3373 tz += ('0' - zone[3]) * 60 * 10;
3374 tz += ('0' - zone[4]) * 60;
3376 if (zone[0] == '-')
3377 tz = -tz;
3379 time->tz = tz;
3380 time->sec -= tz;
3383 /* Parse author lines where the name may be empty:
3384 * author <email@address.tld> 1138474660 +0100
3386 static void
3387 parse_author_line(char *ident, const char **author, struct time *time)
3389 char *nameend = strchr(ident, '<');
3390 char *emailend = strchr(ident, '>');
3392 if (nameend && emailend)
3393 *nameend = *emailend = 0;
3394 ident = chomp_string(ident);
3395 if (!*ident) {
3396 if (nameend)
3397 ident = chomp_string(nameend + 1);
3398 if (!*ident)
3399 ident = "Unknown";
3402 *author = get_author(ident);
3404 /* Parse epoch and timezone */
3405 if (emailend && emailend[1] == ' ') {
3406 char *secs = emailend + 2;
3407 char *zone = strchr(secs, ' ');
3409 parse_timesec(time, secs);
3411 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3412 parse_timezone(time, zone + 1);
3416 static struct line *
3417 find_prev_line_by_type(struct view *view, struct line *line, enum line_type type)
3419 for (; view->line < line; line--)
3420 if (line->type == type)
3421 return line;
3423 return NULL;
3427 * Blame
3430 struct blame_commit {
3431 char id[SIZEOF_REV]; /* SHA1 ID. */
3432 char title[128]; /* First line of the commit message. */
3433 const char *author; /* Author of the commit. */
3434 struct time time; /* Date from the author ident. */
3435 char filename[128]; /* Name of file. */
3436 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3437 char parent_filename[128]; /* Parent/previous name of file. */
3440 struct blame_header {
3441 char id[SIZEOF_REV]; /* SHA1 ID. */
3442 size_t orig_lineno;
3443 size_t lineno;
3444 size_t group;
3447 static bool
3448 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3450 const char *pos = *posref;
3452 *posref = NULL;
3453 pos = strchr(pos + 1, ' ');
3454 if (!pos || !isdigit(pos[1]))
3455 return FALSE;
3456 *number = atoi(pos + 1);
3457 if (*number < min || *number > max)
3458 return FALSE;
3460 *posref = pos;
3461 return TRUE;
3464 static bool
3465 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3467 const char *pos = text + SIZEOF_REV - 2;
3469 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3470 return FALSE;
3472 string_ncopy(header->id, text, SIZEOF_REV);
3474 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3475 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3476 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3477 return FALSE;
3479 return TRUE;
3482 static bool
3483 match_blame_header(const char *name, char **line)
3485 size_t namelen = strlen(name);
3486 bool matched = !strncmp(name, *line, namelen);
3488 if (matched)
3489 *line += namelen;
3491 return matched;
3494 static bool
3495 parse_blame_info(struct blame_commit *commit, char *line)
3497 if (match_blame_header("author ", &line)) {
3498 commit->author = get_author(line);
3500 } else if (match_blame_header("author-time ", &line)) {
3501 parse_timesec(&commit->time, line);
3503 } else if (match_blame_header("author-tz ", &line)) {
3504 parse_timezone(&commit->time, line);
3506 } else if (match_blame_header("summary ", &line)) {
3507 string_ncopy(commit->title, line, strlen(line));
3509 } else if (match_blame_header("previous ", &line)) {
3510 if (strlen(line) <= SIZEOF_REV)
3511 return FALSE;
3512 string_copy_rev(commit->parent_id, line);
3513 line += SIZEOF_REV;
3514 string_ncopy(commit->parent_filename, line, strlen(line));
3516 } else if (match_blame_header("filename ", &line)) {
3517 string_ncopy(commit->filename, line, strlen(line));
3518 return TRUE;
3521 return FALSE;
3525 * Pager backend
3528 static bool
3529 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3531 if (opt_line_number && draw_lineno(view, lineno))
3532 return TRUE;
3534 draw_text(view, line->type, line->data);
3535 return TRUE;
3538 static bool
3539 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3541 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3542 char ref[SIZEOF_STR];
3544 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3545 return TRUE;
3547 /* This is the only fatal call, since it can "corrupt" the buffer. */
3548 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3549 return FALSE;
3551 return TRUE;
3554 static void
3555 add_pager_refs(struct view *view, struct line *line)
3557 char buf[SIZEOF_STR];
3558 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3559 struct ref_list *list;
3560 size_t bufpos = 0, i;
3561 const char *sep = "Refs: ";
3562 bool is_tag = FALSE;
3564 assert(line->type == LINE_COMMIT);
3566 list = get_ref_list(commit_id);
3567 if (!list) {
3568 if (view->type == VIEW_DIFF)
3569 goto try_add_describe_ref;
3570 return;
3573 for (i = 0; i < list->size; i++) {
3574 struct ref *ref = list->refs[i];
3575 const char *fmt = ref->tag ? "%s[%s]" :
3576 ref->remote ? "%s<%s>" : "%s%s";
3578 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3579 return;
3580 sep = ", ";
3581 if (ref->tag)
3582 is_tag = TRUE;
3585 if (!is_tag && view->type == VIEW_DIFF) {
3586 try_add_describe_ref:
3587 /* Add <tag>-g<commit_id> "fake" reference. */
3588 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3589 return;
3592 if (bufpos == 0)
3593 return;
3595 add_line_text(view, buf, LINE_PP_REFS);
3598 static bool
3599 pager_read(struct view *view, char *data)
3601 struct line *line;
3603 if (!data)
3604 return TRUE;
3606 line = add_line_text(view, data, get_line_type(data));
3607 if (!line)
3608 return FALSE;
3610 if (line->type == LINE_COMMIT &&
3611 (view->type == VIEW_DIFF ||
3612 view->type == VIEW_LOG))
3613 add_pager_refs(view, line);
3615 return TRUE;
3618 static enum request
3619 pager_request(struct view *view, enum request request, struct line *line)
3621 int split = 0;
3623 if (request != REQ_ENTER)
3624 return request;
3626 if (line->type == LINE_COMMIT &&
3627 (view->type == VIEW_LOG ||
3628 view->type == VIEW_PAGER)) {
3629 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3630 split = 1;
3633 /* Always scroll the view even if it was split. That way
3634 * you can use Enter to scroll through the log view and
3635 * split open each commit diff. */
3636 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3638 /* FIXME: A minor workaround. Scrolling the view will call report("")
3639 * but if we are scrolling a non-current view this won't properly
3640 * update the view title. */
3641 if (split)
3642 update_view_title(view);
3644 return REQ_NONE;
3647 static bool
3648 pager_grep(struct view *view, struct line *line)
3650 const char *text[] = { line->data, NULL };
3652 return grep_text(view, text);
3655 static void
3656 pager_select(struct view *view, struct line *line)
3658 if (line->type == LINE_COMMIT) {
3659 char *text = (char *)line->data + STRING_SIZE("commit ");
3661 if (view->type != VIEW_PAGER)
3662 string_copy_rev(view->ref, text);
3663 string_copy_rev(ref_commit, text);
3667 static bool
3668 pager_open(struct view *view, enum open_flags flags)
3670 return begin_update(view, NULL, NULL, flags);
3673 static struct view_ops pager_ops = {
3674 "line",
3676 pager_open,
3677 pager_read,
3678 pager_draw,
3679 pager_request,
3680 pager_grep,
3681 pager_select,
3684 static bool
3685 log_open(struct view *view, enum open_flags flags)
3687 static const char *log_argv[] = {
3688 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3691 return begin_update(view, NULL, log_argv, flags);
3694 static enum request
3695 log_request(struct view *view, enum request request, struct line *line)
3697 switch (request) {
3698 case REQ_REFRESH:
3699 load_refs();
3700 refresh_view(view);
3701 return REQ_NONE;
3702 default:
3703 return pager_request(view, request, line);
3707 static struct view_ops log_ops = {
3708 "line",
3710 log_open,
3711 pager_read,
3712 pager_draw,
3713 log_request,
3714 pager_grep,
3715 pager_select,
3718 struct diff_state {
3719 bool reading_diff_stat;
3722 static bool
3723 diff_open(struct view *view, enum open_flags flags)
3725 static const char *diff_argv[] = {
3726 "git", "show", "--pretty=fuller", "--no-color", "--root",
3727 "--patch-with-stat", "--find-copies-harder", "-C",
3728 opt_notes_arg, opt_diff_context_arg, "%(diffargs)",
3729 "%(commit)", "--", "%(fileargs)", NULL
3732 return begin_update(view, NULL, diff_argv, flags);
3735 static bool
3736 diff_common_read(struct view *view, char *data, struct diff_state *state)
3738 if (state->reading_diff_stat) {
3739 size_t len = strlen(data);
3740 char *pipe = strchr(data, '|');
3741 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3742 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3744 if (pipe && (has_histogram || has_bin_diff)) {
3745 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3746 } else {
3747 state->reading_diff_stat = FALSE;
3750 } else if (!strcmp(data, "---")) {
3751 state->reading_diff_stat = TRUE;
3754 return pager_read(view, data);
3757 static enum request
3758 diff_common_enter(struct view *view, enum request request, struct line *line)
3760 if (line->type == LINE_DIFF_STAT) {
3761 int file_number = 0;
3763 while (line >= view->line && line->type == LINE_DIFF_STAT) {
3764 file_number++;
3765 line--;
3768 while (line < view->line + view->lines) {
3769 if (line->type == LINE_DIFF_HEADER) {
3770 if (file_number == 1) {
3771 break;
3773 file_number--;
3775 line++;
3779 select_view_line(view, line - view->line);
3780 report("");
3781 return REQ_NONE;
3783 } else {
3784 return pager_request(view, request, line);
3788 static bool
3789 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
3791 char *sep = strchr(*text, c);
3793 if (sep != NULL) {
3794 *sep = 0;
3795 draw_text(view, *type, *text);
3796 *sep = c;
3797 *text = sep;
3798 *type = next_type;
3801 return sep != NULL;
3804 static bool
3805 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
3807 char *text = line->data;
3808 enum line_type type = line->type;
3810 if (opt_line_number && draw_lineno(view, lineno))
3811 return TRUE;
3813 if (type == LINE_DIFF_STAT) {
3814 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
3815 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
3816 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
3817 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
3818 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
3819 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
3820 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
3822 } else {
3823 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
3824 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
3828 draw_text(view, type, text);
3829 return TRUE;
3832 static bool
3833 diff_read(struct view *view, char *data)
3835 struct diff_state *state = view->private;
3837 if (!data) {
3838 /* Fall back to retry if no diff will be shown. */
3839 if (view->lines == 0 && opt_file_argv) {
3840 int pos = argv_size(view->argv)
3841 - argv_size(opt_file_argv) - 1;
3843 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3844 for (; view->argv[pos]; pos++) {
3845 free((void *) view->argv[pos]);
3846 view->argv[pos] = NULL;
3849 if (view->pipe)
3850 io_done(view->pipe);
3851 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3852 return FALSE;
3855 return TRUE;
3858 return diff_common_read(view, data, state);
3861 static bool
3862 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
3863 struct blame_header *header, struct blame_commit *commit)
3865 char line_arg[SIZEOF_STR];
3866 const char *blame_argv[] = {
3867 "git", "blame", "-p", line_arg, ref, "--", file, NULL
3869 struct io io;
3870 bool ok = FALSE;
3871 char *buf;
3873 if (!string_format(line_arg, "-L%d,+1", lineno))
3874 return FALSE;
3876 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
3877 return FALSE;
3879 while ((buf = io_get(&io, '\n', TRUE))) {
3880 if (header) {
3881 if (!parse_blame_header(header, buf, 9999999))
3882 break;
3883 header = NULL;
3885 } else if (parse_blame_info(commit, buf)) {
3886 ok = TRUE;
3887 break;
3891 if (io_error(&io))
3892 ok = FALSE;
3894 io_done(&io);
3895 return ok;
3898 static enum request
3899 diff_trace_origin(struct view *view, struct line *line)
3901 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
3902 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
3903 const char *chunk_data;
3904 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
3905 int lineno = 0;
3906 const char *file = NULL;
3907 char ref[SIZEOF_REF];
3908 struct blame_header header;
3909 struct blame_commit commit;
3911 if (!diff || !chunk || chunk == line) {
3912 report("The line to trace must be inside a diff chunk");
3913 return REQ_NONE;
3916 for (; diff < line && !file; diff++) {
3917 const char *data = diff->data;
3919 if (!prefixcmp(data, "--- a/")) {
3920 file = data + STRING_SIZE("--- a/");
3921 break;
3925 if (diff == line || !file) {
3926 report("Failed to read the file name");
3927 return REQ_NONE;
3930 chunk_data = chunk->data;
3932 if (prefixcmp(chunk_data, "@@ -") ||
3933 !(chunk_data = strchr(chunk_data, chunk_marker)) ||
3934 parse_int(&lineno, chunk_data + 1, 0, 9999999) != OPT_OK) {
3935 report("Failed to read the line number");
3936 return REQ_NONE;
3939 if (lineno == 0) {
3940 report("This is the origin of the line");
3941 return REQ_NONE;
3944 for (chunk += 1; chunk < line; chunk++) {
3945 if (chunk->type == LINE_DIFF_ADD) {
3946 lineno += chunk_marker == '+';
3947 } else if (chunk->type == LINE_DIFF_DEL) {
3948 lineno += chunk_marker == '-';
3949 } else {
3950 lineno++;
3954 if (chunk_marker == '+')
3955 string_copy(ref, view->vid);
3956 else
3957 string_format(ref, "%s^", view->vid);
3959 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
3960 report("Failed to read blame data");
3961 return REQ_NONE;
3964 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
3965 string_copy(opt_ref, header.id);
3966 opt_goto_line = header.orig_lineno - 1;
3968 return REQ_VIEW_BLAME;
3971 static enum request
3972 diff_request(struct view *view, enum request request, struct line *line)
3974 switch (request) {
3975 case REQ_VIEW_BLAME:
3976 return diff_trace_origin(view, line);
3978 case REQ_DIFF_CONTEXT_UP:
3979 case REQ_DIFF_CONTEXT_DOWN:
3980 if (!update_diff_context(request))
3981 return REQ_NONE;
3982 reload_view(view);
3983 return REQ_NONE;
3985 case REQ_ENTER:
3986 return diff_common_enter(view, request, line);
3988 default:
3989 return pager_request(view, request, line);
3993 static void
3994 diff_select(struct view *view, struct line *line)
3996 if (line->type == LINE_DIFF_STAT) {
3997 const char *key = get_key(KEYMAP_DIFF, REQ_ENTER);
3999 string_format(view->ref, "Press '%s' to jump to file diff", key);
4000 } else {
4001 string_ncopy(view->ref, view->id, strlen(view->id));
4002 return pager_select(view, line);
4006 static struct view_ops diff_ops = {
4007 "line",
4008 sizeof(struct diff_state),
4009 diff_open,
4010 diff_read,
4011 diff_common_draw,
4012 diff_request,
4013 pager_grep,
4014 diff_select,
4018 * Help backend
4021 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
4023 static bool
4024 help_open_keymap_title(struct view *view, enum keymap keymap)
4026 struct line *line;
4028 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
4029 help_keymap_hidden[keymap] ? '+' : '-',
4030 enum_name(keymap_map[keymap]));
4031 if (line)
4032 line->other = keymap;
4034 return help_keymap_hidden[keymap];
4037 static void
4038 help_open_keymap(struct view *view, enum keymap keymap)
4040 const char *group = NULL;
4041 char buf[SIZEOF_STR];
4042 size_t bufpos;
4043 bool add_title = TRUE;
4044 int i;
4046 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4047 const char *key = NULL;
4049 if (req_info[i].request == REQ_NONE)
4050 continue;
4052 if (!req_info[i].request) {
4053 group = req_info[i].help;
4054 continue;
4057 key = get_keys(keymap, req_info[i].request, TRUE);
4058 if (!key || !*key)
4059 continue;
4061 if (add_title && help_open_keymap_title(view, keymap))
4062 return;
4063 add_title = FALSE;
4065 if (group) {
4066 add_line_text(view, group, LINE_HELP_GROUP);
4067 group = NULL;
4070 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4071 enum_name(req_info[i]), req_info[i].help);
4074 group = "External commands:";
4076 for (i = 0; i < run_requests; i++) {
4077 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4078 const char *key;
4079 int argc;
4081 if (!req || req->keymap != keymap)
4082 continue;
4084 key = get_key_name(req->key);
4085 if (!*key)
4086 key = "(no key defined)";
4088 if (add_title && help_open_keymap_title(view, keymap))
4089 return;
4090 if (group) {
4091 add_line_text(view, group, LINE_HELP_GROUP);
4092 group = NULL;
4095 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
4096 if (!string_format_from(buf, &bufpos, "%s%s",
4097 argc ? " " : "", req->argv[argc]))
4098 return;
4100 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4104 static bool
4105 help_open(struct view *view, enum open_flags flags)
4107 enum keymap keymap;
4109 reset_view(view);
4110 view->p_restore = TRUE;
4111 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4112 add_line_text(view, "", LINE_DEFAULT);
4114 for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
4115 help_open_keymap(view, keymap);
4117 return TRUE;
4120 static enum request
4121 help_request(struct view *view, enum request request, struct line *line)
4123 switch (request) {
4124 case REQ_ENTER:
4125 if (line->type == LINE_HELP_KEYMAP) {
4126 help_keymap_hidden[line->other] =
4127 !help_keymap_hidden[line->other];
4128 refresh_view(view);
4131 return REQ_NONE;
4132 default:
4133 return pager_request(view, request, line);
4137 static struct view_ops help_ops = {
4138 "line",
4140 help_open,
4141 NULL,
4142 pager_draw,
4143 help_request,
4144 pager_grep,
4145 pager_select,
4150 * Tree backend
4153 struct tree_stack_entry {
4154 struct tree_stack_entry *prev; /* Entry below this in the stack */
4155 unsigned long lineno; /* Line number to restore */
4156 char *name; /* Position of name in opt_path */
4159 /* The top of the path stack. */
4160 static struct tree_stack_entry *tree_stack = NULL;
4161 unsigned long tree_lineno = 0;
4163 static void
4164 pop_tree_stack_entry(void)
4166 struct tree_stack_entry *entry = tree_stack;
4168 tree_lineno = entry->lineno;
4169 entry->name[0] = 0;
4170 tree_stack = entry->prev;
4171 free(entry);
4174 static void
4175 push_tree_stack_entry(const char *name, unsigned long lineno)
4177 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4178 size_t pathlen = strlen(opt_path);
4180 if (!entry)
4181 return;
4183 entry->prev = tree_stack;
4184 entry->name = opt_path + pathlen;
4185 tree_stack = entry;
4187 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4188 pop_tree_stack_entry();
4189 return;
4192 /* Move the current line to the first tree entry. */
4193 tree_lineno = 1;
4194 entry->lineno = lineno;
4197 /* Parse output from git-ls-tree(1):
4199 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4202 #define SIZEOF_TREE_ATTR \
4203 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4205 #define SIZEOF_TREE_MODE \
4206 STRING_SIZE("100644 ")
4208 #define TREE_ID_OFFSET \
4209 STRING_SIZE("100644 blob ")
4211 struct tree_entry {
4212 char id[SIZEOF_REV];
4213 mode_t mode;
4214 struct time time; /* Date from the author ident. */
4215 const char *author; /* Author of the commit. */
4216 char name[1];
4219 struct tree_state {
4220 const char *author_name;
4221 struct time author_time;
4222 bool read_date;
4225 static const char *
4226 tree_path(const struct line *line)
4228 return ((struct tree_entry *) line->data)->name;
4231 static int
4232 tree_compare_entry(const struct line *line1, const struct line *line2)
4234 if (line1->type != line2->type)
4235 return line1->type == LINE_TREE_DIR ? -1 : 1;
4236 return strcmp(tree_path(line1), tree_path(line2));
4239 static const enum sort_field tree_sort_fields[] = {
4240 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4242 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4244 static int
4245 tree_compare(const void *l1, const void *l2)
4247 const struct line *line1 = (const struct line *) l1;
4248 const struct line *line2 = (const struct line *) l2;
4249 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4250 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4252 if (line1->type == LINE_TREE_HEAD)
4253 return -1;
4254 if (line2->type == LINE_TREE_HEAD)
4255 return 1;
4257 switch (get_sort_field(tree_sort_state)) {
4258 case ORDERBY_DATE:
4259 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4261 case ORDERBY_AUTHOR:
4262 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4264 case ORDERBY_NAME:
4265 default:
4266 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4271 static struct line *
4272 tree_entry(struct view *view, enum line_type type, const char *path,
4273 const char *mode, const char *id)
4275 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4276 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4278 if (!entry || !line) {
4279 free(entry);
4280 return NULL;
4283 strncpy(entry->name, path, strlen(path));
4284 if (mode)
4285 entry->mode = strtoul(mode, NULL, 8);
4286 if (id)
4287 string_copy_rev(entry->id, id);
4289 return line;
4292 static bool
4293 tree_read_date(struct view *view, char *text, struct tree_state *state)
4295 if (!text && state->read_date) {
4296 state->read_date = FALSE;
4297 return TRUE;
4299 } else if (!text) {
4300 /* Find next entry to process */
4301 const char *log_file[] = {
4302 "git", "log", "--no-color", "--pretty=raw",
4303 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4306 if (!view->lines) {
4307 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4308 report("Tree is empty");
4309 return TRUE;
4312 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4313 report("Failed to load tree data");
4314 return TRUE;
4317 state->read_date = TRUE;
4318 return FALSE;
4320 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4321 parse_author_line(text + STRING_SIZE("author "),
4322 &state->author_name, &state->author_time);
4324 } else if (*text == ':') {
4325 char *pos;
4326 size_t annotated = 1;
4327 size_t i;
4329 pos = strchr(text, '\t');
4330 if (!pos)
4331 return TRUE;
4332 text = pos + 1;
4333 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4334 text += strlen(opt_path);
4335 pos = strchr(text, '/');
4336 if (pos)
4337 *pos = 0;
4339 for (i = 1; i < view->lines; i++) {
4340 struct line *line = &view->line[i];
4341 struct tree_entry *entry = line->data;
4343 annotated += !!entry->author;
4344 if (entry->author || strcmp(entry->name, text))
4345 continue;
4347 entry->author = state->author_name;
4348 entry->time = state->author_time;
4349 line->dirty = 1;
4350 break;
4353 if (annotated == view->lines)
4354 io_kill(view->pipe);
4356 return TRUE;
4359 static bool
4360 tree_read(struct view *view, char *text)
4362 struct tree_state *state = view->private;
4363 struct tree_entry *data;
4364 struct line *entry, *line;
4365 enum line_type type;
4366 size_t textlen = text ? strlen(text) : 0;
4367 char *path = text + SIZEOF_TREE_ATTR;
4369 if (state->read_date || !text)
4370 return tree_read_date(view, text, state);
4372 if (textlen <= SIZEOF_TREE_ATTR)
4373 return FALSE;
4374 if (view->lines == 0 &&
4375 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4376 return FALSE;
4378 /* Strip the path part ... */
4379 if (*opt_path) {
4380 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4381 size_t striplen = strlen(opt_path);
4383 if (pathlen > striplen)
4384 memmove(path, path + striplen,
4385 pathlen - striplen + 1);
4387 /* Insert "link" to parent directory. */
4388 if (view->lines == 1 &&
4389 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4390 return FALSE;
4393 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4394 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4395 if (!entry)
4396 return FALSE;
4397 data = entry->data;
4399 /* Skip "Directory ..." and ".." line. */
4400 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4401 if (tree_compare_entry(line, entry) <= 0)
4402 continue;
4404 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4406 line->data = data;
4407 line->type = type;
4408 for (; line <= entry; line++)
4409 line->dirty = line->cleareol = 1;
4410 return TRUE;
4413 if (tree_lineno > view->lineno) {
4414 view->lineno = tree_lineno;
4415 tree_lineno = 0;
4418 return TRUE;
4421 static bool
4422 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4424 struct tree_entry *entry = line->data;
4426 if (line->type == LINE_TREE_HEAD) {
4427 if (draw_text(view, line->type, "Directory path /"))
4428 return TRUE;
4429 } else {
4430 if (draw_mode(view, entry->mode))
4431 return TRUE;
4433 if (draw_author(view, entry->author))
4434 return TRUE;
4436 if (draw_date(view, &entry->time))
4437 return TRUE;
4440 draw_text(view, line->type, entry->name);
4441 return TRUE;
4444 static void
4445 open_blob_editor(const char *id)
4447 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4448 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4449 int fd = mkstemp(file);
4451 if (fd == -1)
4452 report("Failed to create temporary file");
4453 else if (!io_run_append(blob_argv, fd))
4454 report("Failed to save blob data to file");
4455 else
4456 open_editor(file);
4457 if (fd != -1)
4458 unlink(file);
4461 static enum request
4462 tree_request(struct view *view, enum request request, struct line *line)
4464 enum open_flags flags;
4465 struct tree_entry *entry = line->data;
4467 switch (request) {
4468 case REQ_VIEW_BLAME:
4469 if (line->type != LINE_TREE_FILE) {
4470 report("Blame only supported for files");
4471 return REQ_NONE;
4474 string_copy(opt_ref, view->vid);
4475 return request;
4477 case REQ_EDIT:
4478 if (line->type != LINE_TREE_FILE) {
4479 report("Edit only supported for files");
4480 } else if (!is_head_commit(view->vid)) {
4481 open_blob_editor(entry->id);
4482 } else {
4483 open_editor(opt_file);
4485 return REQ_NONE;
4487 case REQ_TOGGLE_SORT_FIELD:
4488 case REQ_TOGGLE_SORT_ORDER:
4489 sort_view(view, request, &tree_sort_state, tree_compare);
4490 return REQ_NONE;
4492 case REQ_PARENT:
4493 if (!*opt_path) {
4494 /* quit view if at top of tree */
4495 return REQ_VIEW_CLOSE;
4497 /* fake 'cd ..' */
4498 line = &view->line[1];
4499 break;
4501 case REQ_ENTER:
4502 break;
4504 default:
4505 return request;
4508 /* Cleanup the stack if the tree view is at a different tree. */
4509 while (!*opt_path && tree_stack)
4510 pop_tree_stack_entry();
4512 switch (line->type) {
4513 case LINE_TREE_DIR:
4514 /* Depending on whether it is a subdirectory or parent link
4515 * mangle the path buffer. */
4516 if (line == &view->line[1] && *opt_path) {
4517 pop_tree_stack_entry();
4519 } else {
4520 const char *basename = tree_path(line);
4522 push_tree_stack_entry(basename, view->lineno);
4525 /* Trees and subtrees share the same ID, so they are not not
4526 * unique like blobs. */
4527 flags = OPEN_RELOAD;
4528 request = REQ_VIEW_TREE;
4529 break;
4531 case LINE_TREE_FILE:
4532 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4533 request = REQ_VIEW_BLOB;
4534 break;
4536 default:
4537 return REQ_NONE;
4540 open_view(view, request, flags);
4541 if (request == REQ_VIEW_TREE)
4542 view->lineno = tree_lineno;
4544 return REQ_NONE;
4547 static bool
4548 tree_grep(struct view *view, struct line *line)
4550 struct tree_entry *entry = line->data;
4551 const char *text[] = {
4552 entry->name,
4553 mkauthor(entry->author, opt_author_cols, opt_author),
4554 mkdate(&entry->time, opt_date),
4555 NULL
4558 return grep_text(view, text);
4561 static void
4562 tree_select(struct view *view, struct line *line)
4564 struct tree_entry *entry = line->data;
4566 if (line->type == LINE_TREE_FILE) {
4567 string_copy_rev(ref_blob, entry->id);
4568 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4570 } else if (line->type != LINE_TREE_DIR) {
4571 return;
4574 string_copy_rev(view->ref, entry->id);
4577 static bool
4578 tree_open(struct view *view, enum open_flags flags)
4580 static const char *tree_argv[] = {
4581 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4584 if (view->lines == 0 && opt_prefix[0]) {
4585 char *pos = opt_prefix;
4587 while (pos && *pos) {
4588 char *end = strchr(pos, '/');
4590 if (end)
4591 *end = 0;
4592 push_tree_stack_entry(pos, 0);
4593 pos = end;
4594 if (end) {
4595 *end = '/';
4596 pos++;
4600 } else if (strcmp(view->vid, view->id)) {
4601 opt_path[0] = 0;
4604 return begin_update(view, opt_cdup, tree_argv, flags);
4607 static struct view_ops tree_ops = {
4608 "file",
4609 sizeof(struct tree_state),
4610 tree_open,
4611 tree_read,
4612 tree_draw,
4613 tree_request,
4614 tree_grep,
4615 tree_select,
4618 static bool
4619 blob_open(struct view *view, enum open_flags flags)
4621 static const char *blob_argv[] = {
4622 "git", "cat-file", "blob", "%(blob)", NULL
4625 return begin_update(view, NULL, blob_argv, flags);
4628 static bool
4629 blob_read(struct view *view, char *line)
4631 if (!line)
4632 return TRUE;
4633 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4636 static enum request
4637 blob_request(struct view *view, enum request request, struct line *line)
4639 switch (request) {
4640 case REQ_EDIT:
4641 open_blob_editor(view->vid);
4642 return REQ_NONE;
4643 default:
4644 return pager_request(view, request, line);
4648 static struct view_ops blob_ops = {
4649 "line",
4651 blob_open,
4652 blob_read,
4653 pager_draw,
4654 blob_request,
4655 pager_grep,
4656 pager_select,
4660 * Blame backend
4662 * Loading the blame view is a two phase job:
4664 * 1. File content is read either using opt_file from the
4665 * filesystem or using git-cat-file.
4666 * 2. Then blame information is incrementally added by
4667 * reading output from git-blame.
4670 struct blame {
4671 struct blame_commit *commit;
4672 unsigned long lineno;
4673 char text[1];
4676 struct blame_state {
4677 struct blame_commit *commit;
4678 int blamed;
4679 bool done_reading;
4680 bool auto_filename_display;
4683 static bool
4684 blame_detect_filename_display(struct view *view)
4686 bool show_filenames = FALSE;
4687 const char *filename = NULL;
4688 int i;
4690 if (opt_blame_argv) {
4691 for (i = 0; opt_blame_argv[i]; i++) {
4692 if (prefixcmp(opt_blame_argv[i], "-C"))
4693 continue;
4695 show_filenames = TRUE;
4699 for (i = 0; i < view->lines; i++) {
4700 struct blame *blame = view->line[i].data;
4702 if (blame->commit && blame->commit->id[0]) {
4703 if (!filename)
4704 filename = blame->commit->filename;
4705 else if (strcmp(filename, blame->commit->filename))
4706 show_filenames = TRUE;
4710 return show_filenames;
4713 static bool
4714 blame_open(struct view *view, enum open_flags flags)
4716 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4717 char path[SIZEOF_STR];
4718 size_t i;
4720 if (!view->prev && *opt_prefix) {
4721 string_copy(path, opt_file);
4722 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4723 return FALSE;
4726 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4727 const char *blame_cat_file_argv[] = {
4728 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4731 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4732 return FALSE;
4735 /* First pass: remove multiple references to the same commit. */
4736 for (i = 0; i < view->lines; i++) {
4737 struct blame *blame = view->line[i].data;
4739 if (blame->commit && blame->commit->id[0])
4740 blame->commit->id[0] = 0;
4741 else
4742 blame->commit = NULL;
4745 /* Second pass: free existing references. */
4746 for (i = 0; i < view->lines; i++) {
4747 struct blame *blame = view->line[i].data;
4749 if (blame->commit)
4750 free(blame->commit);
4753 string_format(view->vid, "%s", opt_file);
4754 string_format(view->ref, "%s ...", opt_file);
4756 return TRUE;
4759 static struct blame_commit *
4760 get_blame_commit(struct view *view, const char *id)
4762 size_t i;
4764 for (i = 0; i < view->lines; i++) {
4765 struct blame *blame = view->line[i].data;
4767 if (!blame->commit)
4768 continue;
4770 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4771 return blame->commit;
4775 struct blame_commit *commit = calloc(1, sizeof(*commit));
4777 if (commit)
4778 string_ncopy(commit->id, id, SIZEOF_REV);
4779 return commit;
4783 static struct blame_commit *
4784 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
4786 struct blame_header header;
4787 struct blame_commit *commit;
4788 struct blame *blame;
4790 if (!parse_blame_header(&header, text, view->lines))
4791 return NULL;
4793 commit = get_blame_commit(view, text);
4794 if (!commit)
4795 return NULL;
4797 state->blamed += header.group;
4798 while (header.group--) {
4799 struct line *line = &view->line[header.lineno + header.group - 1];
4801 blame = line->data;
4802 blame->commit = commit;
4803 blame->lineno = header.orig_lineno + header.group - 1;
4804 line->dirty = 1;
4807 return commit;
4810 static bool
4811 blame_read_file(struct view *view, const char *line, struct blame_state *state)
4813 if (!line) {
4814 const char *blame_argv[] = {
4815 "git", "blame", "%(blameargs)", "--incremental",
4816 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4819 if (view->lines == 0 && !view->prev)
4820 die("No blame exist for %s", view->vid);
4822 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
4823 report("Failed to load blame data");
4824 return TRUE;
4827 if (opt_goto_line > 0) {
4828 select_view_line(view, opt_goto_line);
4829 opt_goto_line = 0;
4832 state->done_reading = TRUE;
4833 return FALSE;
4835 } else {
4836 size_t linelen = strlen(line);
4837 struct blame *blame = malloc(sizeof(*blame) + linelen);
4839 if (!blame)
4840 return FALSE;
4842 blame->commit = NULL;
4843 strncpy(blame->text, line, linelen);
4844 blame->text[linelen] = 0;
4845 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4849 static bool
4850 blame_read(struct view *view, char *line)
4852 struct blame_state *state = view->private;
4854 if (!state->done_reading)
4855 return blame_read_file(view, line, state);
4857 if (!line) {
4858 state->auto_filename_display = blame_detect_filename_display(view);
4859 string_format(view->ref, "%s", view->vid);
4860 if (view_is_displayed(view)) {
4861 update_view_title(view);
4862 redraw_view_from(view, 0);
4864 return TRUE;
4867 if (!state->commit) {
4868 state->commit = read_blame_commit(view, line, state);
4869 string_format(view->ref, "%s %2d%%", view->vid,
4870 view->lines ? state->blamed * 100 / view->lines : 0);
4872 } else if (parse_blame_info(state->commit, line)) {
4873 state->commit = NULL;
4876 return TRUE;
4879 static bool
4880 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4882 struct blame_state *state = view->private;
4883 struct blame *blame = line->data;
4884 struct time *time = NULL;
4885 const char *id = NULL, *author = NULL, *filename = NULL;
4886 enum line_type id_type = LINE_BLAME_ID;
4887 static const enum line_type blame_colors[] = {
4888 LINE_PALETTE_0,
4889 LINE_PALETTE_1,
4890 LINE_PALETTE_2,
4891 LINE_PALETTE_3,
4892 LINE_PALETTE_4,
4893 LINE_PALETTE_5,
4894 LINE_PALETTE_6,
4897 #define BLAME_COLOR(i) \
4898 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
4900 if (blame->commit && *blame->commit->filename) {
4901 id = blame->commit->id;
4902 author = blame->commit->author;
4903 filename = blame->commit->filename;
4904 time = &blame->commit->time;
4905 id_type = BLAME_COLOR((long) blame->commit);
4908 if (draw_date(view, time))
4909 return TRUE;
4911 if (draw_author(view, author))
4912 return TRUE;
4914 if (draw_filename(view, filename, state->auto_filename_display))
4915 return TRUE;
4917 if (draw_field(view, id_type, id, ID_COLS, FALSE))
4918 return TRUE;
4920 if (draw_lineno(view, lineno))
4921 return TRUE;
4923 draw_text(view, LINE_DEFAULT, blame->text);
4924 return TRUE;
4927 static bool
4928 check_blame_commit(struct blame *blame, bool check_null_id)
4930 if (!blame->commit)
4931 report("Commit data not loaded yet");
4932 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4933 report("No commit exist for the selected line");
4934 else
4935 return TRUE;
4936 return FALSE;
4939 static void
4940 setup_blame_parent_line(struct view *view, struct blame *blame)
4942 char from[SIZEOF_REF + SIZEOF_STR];
4943 char to[SIZEOF_REF + SIZEOF_STR];
4944 const char *diff_tree_argv[] = {
4945 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4946 "-U0", from, to, "--", NULL
4948 struct io io;
4949 int parent_lineno = -1;
4950 int blamed_lineno = -1;
4951 char *line;
4953 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4954 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4955 !io_run(&io, IO_RD, NULL, diff_tree_argv))
4956 return;
4958 while ((line = io_get(&io, '\n', TRUE))) {
4959 if (*line == '@') {
4960 char *pos = strchr(line, '+');
4962 parent_lineno = atoi(line + 4);
4963 if (pos)
4964 blamed_lineno = atoi(pos + 1);
4966 } else if (*line == '+' && parent_lineno != -1) {
4967 if (blame->lineno == blamed_lineno - 1 &&
4968 !strcmp(blame->text, line + 1)) {
4969 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4970 break;
4972 blamed_lineno++;
4976 io_done(&io);
4979 static enum request
4980 blame_request(struct view *view, enum request request, struct line *line)
4982 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4983 struct blame *blame = line->data;
4985 switch (request) {
4986 case REQ_VIEW_BLAME:
4987 if (check_blame_commit(blame, TRUE)) {
4988 string_copy(opt_ref, blame->commit->id);
4989 string_copy(opt_file, blame->commit->filename);
4990 if (blame->lineno)
4991 view->lineno = blame->lineno;
4992 reload_view(view);
4994 break;
4996 case REQ_PARENT:
4997 if (!check_blame_commit(blame, TRUE))
4998 break;
4999 if (!*blame->commit->parent_id) {
5000 report("The selected commit has no parents");
5001 } else {
5002 string_copy_rev(opt_ref, blame->commit->parent_id);
5003 string_copy(opt_file, blame->commit->parent_filename);
5004 setup_blame_parent_line(view, blame);
5005 opt_goto_line = blame->lineno;
5006 reload_view(view);
5008 break;
5010 case REQ_ENTER:
5011 if (!check_blame_commit(blame, FALSE))
5012 break;
5014 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5015 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5016 break;
5018 if (!strcmp(blame->commit->id, NULL_ID)) {
5019 struct view *diff = VIEW(REQ_VIEW_DIFF);
5020 const char *diff_index_argv[] = {
5021 "git", "diff-index", "--root", "--patch-with-stat",
5022 "-C", "-M", opt_diff_context_arg,
5023 "HEAD", "--", view->vid, NULL
5026 if (!*blame->commit->parent_id) {
5027 diff_index_argv[1] = "diff";
5028 diff_index_argv[2] = "--no-color";
5029 diff_index_argv[7] = "--";
5030 diff_index_argv[8] = "/dev/null";
5033 open_argv(view, diff, diff_index_argv, NULL, flags);
5034 if (diff->pipe)
5035 string_copy_rev(diff->ref, NULL_ID);
5036 } else {
5037 open_view(view, REQ_VIEW_DIFF, flags);
5039 break;
5041 default:
5042 return request;
5045 return REQ_NONE;
5048 static bool
5049 blame_grep(struct view *view, struct line *line)
5051 struct blame *blame = line->data;
5052 struct blame_commit *commit = blame->commit;
5053 const char *text[] = {
5054 blame->text,
5055 commit ? commit->title : "",
5056 commit ? commit->id : "",
5057 commit && opt_author ? commit->author : "",
5058 commit ? mkdate(&commit->time, opt_date) : "",
5059 NULL
5062 return grep_text(view, text);
5065 static void
5066 blame_select(struct view *view, struct line *line)
5068 struct blame *blame = line->data;
5069 struct blame_commit *commit = blame->commit;
5071 if (!commit)
5072 return;
5074 if (!strcmp(commit->id, NULL_ID))
5075 string_ncopy(ref_commit, "HEAD", 4);
5076 else
5077 string_copy_rev(ref_commit, commit->id);
5080 static struct view_ops blame_ops = {
5081 "line",
5082 sizeof(struct blame_state),
5083 blame_open,
5084 blame_read,
5085 blame_draw,
5086 blame_request,
5087 blame_grep,
5088 blame_select,
5092 * Branch backend
5095 struct branch {
5096 const char *author; /* Author of the last commit. */
5097 struct time time; /* Date of the last activity. */
5098 const struct ref *ref; /* Name and commit ID information. */
5101 static const struct ref branch_all;
5103 static const enum sort_field branch_sort_fields[] = {
5104 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5106 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5108 struct branch_state {
5109 char id[SIZEOF_REV];
5112 static int
5113 branch_compare(const void *l1, const void *l2)
5115 const struct branch *branch1 = ((const struct line *) l1)->data;
5116 const struct branch *branch2 = ((const struct line *) l2)->data;
5118 if (branch1->ref == &branch_all)
5119 return -1;
5120 else if (branch2->ref == &branch_all)
5121 return 1;
5123 switch (get_sort_field(branch_sort_state)) {
5124 case ORDERBY_DATE:
5125 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5127 case ORDERBY_AUTHOR:
5128 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5130 case ORDERBY_NAME:
5131 default:
5132 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5136 static bool
5137 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5139 struct branch *branch = line->data;
5140 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5142 if (draw_date(view, &branch->time))
5143 return TRUE;
5145 if (draw_author(view, branch->author))
5146 return TRUE;
5148 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
5149 return TRUE;
5152 static enum request
5153 branch_request(struct view *view, enum request request, struct line *line)
5155 struct branch *branch = line->data;
5157 switch (request) {
5158 case REQ_REFRESH:
5159 load_refs();
5160 refresh_view(view);
5161 return REQ_NONE;
5163 case REQ_TOGGLE_SORT_FIELD:
5164 case REQ_TOGGLE_SORT_ORDER:
5165 sort_view(view, request, &branch_sort_state, branch_compare);
5166 return REQ_NONE;
5168 case REQ_ENTER:
5170 const struct ref *ref = branch->ref;
5171 const char *all_branches_argv[] = {
5172 "git", "log", "--no-color", "--pretty=raw", "--parents",
5173 "--topo-order",
5174 ref == &branch_all ? "--all" : ref->name, NULL
5176 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5178 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5179 return REQ_NONE;
5181 case REQ_JUMP_COMMIT:
5183 int lineno;
5185 for (lineno = 0; lineno < view->lines; lineno++) {
5186 struct branch *branch = view->line[lineno].data;
5188 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5189 select_view_line(view, lineno);
5190 report("");
5191 return REQ_NONE;
5195 default:
5196 return request;
5200 static bool
5201 branch_read(struct view *view, char *line)
5203 struct branch_state *state = view->private;
5204 struct branch *reference;
5205 size_t i;
5207 if (!line)
5208 return TRUE;
5210 switch (get_line_type(line)) {
5211 case LINE_COMMIT:
5212 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5213 return TRUE;
5215 case LINE_AUTHOR:
5216 for (i = 0, reference = NULL; i < view->lines; i++) {
5217 struct branch *branch = view->line[i].data;
5219 if (strcmp(branch->ref->id, state->id))
5220 continue;
5222 view->line[i].dirty = TRUE;
5223 if (reference) {
5224 branch->author = reference->author;
5225 branch->time = reference->time;
5226 continue;
5229 parse_author_line(line + STRING_SIZE("author "),
5230 &branch->author, &branch->time);
5231 reference = branch;
5233 return TRUE;
5235 default:
5236 return TRUE;
5241 static bool
5242 branch_open_visitor(void *data, const struct ref *ref)
5244 struct view *view = data;
5245 struct branch *branch;
5247 if (ref->tag || ref->ltag)
5248 return TRUE;
5250 branch = calloc(1, sizeof(*branch));
5251 if (!branch)
5252 return FALSE;
5254 branch->ref = ref;
5255 return !!add_line_data(view, branch, LINE_DEFAULT);
5258 static bool
5259 branch_open(struct view *view, enum open_flags flags)
5261 const char *branch_log[] = {
5262 "git", "log", "--no-color", "--pretty=raw",
5263 "--simplify-by-decoration", "--all", NULL
5266 if (!begin_update(view, NULL, branch_log, flags)) {
5267 report("Failed to load branch data");
5268 return TRUE;
5271 branch_open_visitor(view, &branch_all);
5272 foreach_ref(branch_open_visitor, view);
5273 view->p_restore = TRUE;
5275 return TRUE;
5278 static bool
5279 branch_grep(struct view *view, struct line *line)
5281 struct branch *branch = line->data;
5282 const char *text[] = {
5283 branch->ref->name,
5284 mkauthor(branch->author, opt_author_cols, opt_author),
5285 NULL
5288 return grep_text(view, text);
5291 static void
5292 branch_select(struct view *view, struct line *line)
5294 struct branch *branch = line->data;
5296 string_copy_rev(view->ref, branch->ref->id);
5297 string_copy_rev(ref_commit, branch->ref->id);
5298 string_copy_rev(ref_head, branch->ref->id);
5299 string_copy_rev(ref_branch, branch->ref->name);
5302 static struct view_ops branch_ops = {
5303 "branch",
5304 sizeof(struct branch_state),
5305 branch_open,
5306 branch_read,
5307 branch_draw,
5308 branch_request,
5309 branch_grep,
5310 branch_select,
5314 * Status backend
5317 struct status {
5318 char status;
5319 struct {
5320 mode_t mode;
5321 char rev[SIZEOF_REV];
5322 char name[SIZEOF_STR];
5323 } old;
5324 struct {
5325 mode_t mode;
5326 char rev[SIZEOF_REV];
5327 char name[SIZEOF_STR];
5328 } new;
5331 static char status_onbranch[SIZEOF_STR];
5332 static struct status stage_status;
5333 static enum line_type stage_line_type;
5335 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5337 /* This should work even for the "On branch" line. */
5338 static inline bool
5339 status_has_none(struct view *view, struct line *line)
5341 return line < view->line + view->lines && !line[1].data;
5344 /* Get fields from the diff line:
5345 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5347 static inline bool
5348 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5350 const char *old_mode = buf + 1;
5351 const char *new_mode = buf + 8;
5352 const char *old_rev = buf + 15;
5353 const char *new_rev = buf + 56;
5354 const char *status = buf + 97;
5356 if (bufsize < 98 ||
5357 old_mode[-1] != ':' ||
5358 new_mode[-1] != ' ' ||
5359 old_rev[-1] != ' ' ||
5360 new_rev[-1] != ' ' ||
5361 status[-1] != ' ')
5362 return FALSE;
5364 file->status = *status;
5366 string_copy_rev(file->old.rev, old_rev);
5367 string_copy_rev(file->new.rev, new_rev);
5369 file->old.mode = strtoul(old_mode, NULL, 8);
5370 file->new.mode = strtoul(new_mode, NULL, 8);
5372 file->old.name[0] = file->new.name[0] = 0;
5374 return TRUE;
5377 static bool
5378 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5380 struct status *unmerged = NULL;
5381 char *buf;
5382 struct io io;
5384 if (!io_run(&io, IO_RD, opt_cdup, argv))
5385 return FALSE;
5387 add_line_data(view, NULL, type);
5389 while ((buf = io_get(&io, 0, TRUE))) {
5390 struct status *file = unmerged;
5392 if (!file) {
5393 file = calloc(1, sizeof(*file));
5394 if (!file || !add_line_data(view, file, type))
5395 goto error_out;
5398 /* Parse diff info part. */
5399 if (status) {
5400 file->status = status;
5401 if (status == 'A')
5402 string_copy(file->old.rev, NULL_ID);
5404 } else if (!file->status || file == unmerged) {
5405 if (!status_get_diff(file, buf, strlen(buf)))
5406 goto error_out;
5408 buf = io_get(&io, 0, TRUE);
5409 if (!buf)
5410 break;
5412 /* Collapse all modified entries that follow an
5413 * associated unmerged entry. */
5414 if (unmerged == file) {
5415 unmerged->status = 'U';
5416 unmerged = NULL;
5417 } else if (file->status == 'U') {
5418 unmerged = file;
5422 /* Grab the old name for rename/copy. */
5423 if (!*file->old.name &&
5424 (file->status == 'R' || file->status == 'C')) {
5425 string_ncopy(file->old.name, buf, strlen(buf));
5427 buf = io_get(&io, 0, TRUE);
5428 if (!buf)
5429 break;
5432 /* git-ls-files just delivers a NUL separated list of
5433 * file names similar to the second half of the
5434 * git-diff-* output. */
5435 string_ncopy(file->new.name, buf, strlen(buf));
5436 if (!*file->old.name)
5437 string_copy(file->old.name, file->new.name);
5438 file = NULL;
5441 if (io_error(&io)) {
5442 error_out:
5443 io_done(&io);
5444 return FALSE;
5447 if (!view->line[view->lines - 1].data)
5448 add_line_data(view, NULL, LINE_STAT_NONE);
5450 io_done(&io);
5451 return TRUE;
5454 /* Don't show unmerged entries in the staged section. */
5455 static const char *status_diff_index_argv[] = {
5456 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
5457 "--cached", "-M", "HEAD", NULL
5460 static const char *status_diff_files_argv[] = {
5461 "git", "diff-files", "-z", NULL
5464 static const char *status_list_other_argv[] = {
5465 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5468 static const char *status_list_no_head_argv[] = {
5469 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5472 static const char *update_index_argv[] = {
5473 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5476 /* Restore the previous line number to stay in the context or select a
5477 * line with something that can be updated. */
5478 static void
5479 status_restore(struct view *view)
5481 if (view->p_lineno >= view->lines)
5482 view->p_lineno = view->lines - 1;
5483 while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
5484 view->p_lineno++;
5485 while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
5486 view->p_lineno--;
5488 /* If the above fails, always skip the "On branch" line. */
5489 if (view->p_lineno < view->lines)
5490 view->lineno = view->p_lineno;
5491 else
5492 view->lineno = 1;
5494 if (view->lineno < view->offset)
5495 view->offset = view->lineno;
5496 else if (view->offset + view->height <= view->lineno)
5497 view->offset = view->lineno - view->height + 1;
5499 view->p_restore = FALSE;
5502 static void
5503 status_update_onbranch(void)
5505 static const char *paths[][2] = {
5506 { "rebase-apply/rebasing", "Rebasing" },
5507 { "rebase-apply/applying", "Applying mailbox" },
5508 { "rebase-apply/", "Rebasing mailbox" },
5509 { "rebase-merge/interactive", "Interactive rebase" },
5510 { "rebase-merge/", "Rebase merge" },
5511 { "MERGE_HEAD", "Merging" },
5512 { "BISECT_LOG", "Bisecting" },
5513 { "HEAD", "On branch" },
5515 char buf[SIZEOF_STR];
5516 struct stat stat;
5517 int i;
5519 if (is_initial_commit()) {
5520 string_copy(status_onbranch, "Initial commit");
5521 return;
5524 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5525 char *head = opt_head;
5527 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5528 lstat(buf, &stat) < 0)
5529 continue;
5531 if (!*opt_head) {
5532 struct io io;
5534 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5535 io_read_buf(&io, buf, sizeof(buf))) {
5536 head = buf;
5537 if (!prefixcmp(head, "refs/heads/"))
5538 head += STRING_SIZE("refs/heads/");
5542 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5543 string_copy(status_onbranch, opt_head);
5544 return;
5547 string_copy(status_onbranch, "Not currently on any branch");
5550 /* First parse staged info using git-diff-index(1), then parse unstaged
5551 * info using git-diff-files(1), and finally untracked files using
5552 * git-ls-files(1). */
5553 static bool
5554 status_open(struct view *view, enum open_flags flags)
5556 reset_view(view);
5558 add_line_data(view, NULL, LINE_STAT_HEAD);
5559 status_update_onbranch();
5561 io_run_bg(update_index_argv);
5563 if (is_initial_commit()) {
5564 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5565 return FALSE;
5566 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5567 return FALSE;
5570 if (!opt_untracked_dirs_content)
5571 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5573 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5574 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5575 return FALSE;
5577 /* Restore the exact position or use the specialized restore
5578 * mode? */
5579 if (!view->p_restore)
5580 status_restore(view);
5581 return TRUE;
5584 static bool
5585 status_draw(struct view *view, struct line *line, unsigned int lineno)
5587 struct status *status = line->data;
5588 enum line_type type;
5589 const char *text;
5591 if (!status) {
5592 switch (line->type) {
5593 case LINE_STAT_STAGED:
5594 type = LINE_STAT_SECTION;
5595 text = "Changes to be committed:";
5596 break;
5598 case LINE_STAT_UNSTAGED:
5599 type = LINE_STAT_SECTION;
5600 text = "Changed but not updated:";
5601 break;
5603 case LINE_STAT_UNTRACKED:
5604 type = LINE_STAT_SECTION;
5605 text = "Untracked files:";
5606 break;
5608 case LINE_STAT_NONE:
5609 type = LINE_DEFAULT;
5610 text = " (no files)";
5611 break;
5613 case LINE_STAT_HEAD:
5614 type = LINE_STAT_HEAD;
5615 text = status_onbranch;
5616 break;
5618 default:
5619 return FALSE;
5621 } else {
5622 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5624 buf[0] = status->status;
5625 if (draw_text(view, line->type, buf))
5626 return TRUE;
5627 type = LINE_DEFAULT;
5628 text = status->new.name;
5631 draw_text(view, type, text);
5632 return TRUE;
5635 static enum request
5636 status_enter(struct view *view, struct line *line)
5638 struct status *status = line->data;
5639 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5641 if (line->type == LINE_STAT_NONE ||
5642 (!status && line[1].type == LINE_STAT_NONE)) {
5643 report("No file to diff");
5644 return REQ_NONE;
5647 switch (line->type) {
5648 case LINE_STAT_STAGED:
5649 case LINE_STAT_UNSTAGED:
5650 break;
5652 case LINE_STAT_UNTRACKED:
5653 if (!status) {
5654 report("No file to show");
5655 return REQ_NONE;
5658 if (!suffixcmp(status->new.name, -1, "/")) {
5659 report("Cannot display a directory");
5660 return REQ_NONE;
5662 break;
5664 case LINE_STAT_HEAD:
5665 return REQ_NONE;
5667 default:
5668 die("line type %d not handled in switch", line->type);
5671 if (status) {
5672 stage_status = *status;
5673 } else {
5674 memset(&stage_status, 0, sizeof(stage_status));
5677 stage_line_type = line->type;
5679 open_view(view, REQ_VIEW_STAGE, flags);
5680 return REQ_NONE;
5683 static bool
5684 status_exists(struct view *view, struct status *status, enum line_type type)
5686 unsigned long lineno;
5688 for (lineno = 0; lineno < view->lines; lineno++) {
5689 struct line *line = &view->line[lineno];
5690 struct status *pos = line->data;
5692 if (line->type != type)
5693 continue;
5694 if (!pos && (!status || !status->status) && line[1].data) {
5695 select_view_line(view, lineno);
5696 return TRUE;
5698 if (pos && !strcmp(status->new.name, pos->new.name)) {
5699 select_view_line(view, lineno);
5700 return TRUE;
5704 return FALSE;
5708 static bool
5709 status_update_prepare(struct io *io, enum line_type type)
5711 const char *staged_argv[] = {
5712 "git", "update-index", "-z", "--index-info", NULL
5714 const char *others_argv[] = {
5715 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5718 switch (type) {
5719 case LINE_STAT_STAGED:
5720 return io_run(io, IO_WR, opt_cdup, staged_argv);
5722 case LINE_STAT_UNSTAGED:
5723 case LINE_STAT_UNTRACKED:
5724 return io_run(io, IO_WR, opt_cdup, others_argv);
5726 default:
5727 die("line type %d not handled in switch", type);
5728 return FALSE;
5732 static bool
5733 status_update_write(struct io *io, struct status *status, enum line_type type)
5735 char buf[SIZEOF_STR];
5736 size_t bufsize = 0;
5738 switch (type) {
5739 case LINE_STAT_STAGED:
5740 if (!string_format_from(buf, &bufsize, "%06o %s\t%s%c",
5741 status->old.mode,
5742 status->old.rev,
5743 status->old.name, 0))
5744 return FALSE;
5745 break;
5747 case LINE_STAT_UNSTAGED:
5748 case LINE_STAT_UNTRACKED:
5749 if (!string_format_from(buf, &bufsize, "%s%c", status->new.name, 0))
5750 return FALSE;
5751 break;
5753 default:
5754 die("line type %d not handled in switch", type);
5757 return io_write(io, buf, bufsize);
5760 static bool
5761 status_update_file(struct status *status, enum line_type type)
5763 struct io io;
5764 bool result;
5766 if (!status_update_prepare(&io, type))
5767 return FALSE;
5769 result = status_update_write(&io, status, type);
5770 return io_done(&io) && result;
5773 static bool
5774 status_update_files(struct view *view, struct line *line)
5776 char buf[sizeof(view->ref)];
5777 struct io io;
5778 bool result = TRUE;
5779 struct line *pos = view->line + view->lines;
5780 int files = 0;
5781 int file, done;
5782 int cursor_y = -1, cursor_x = -1;
5784 if (!status_update_prepare(&io, line->type))
5785 return FALSE;
5787 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5788 files++;
5790 string_copy(buf, view->ref);
5791 getsyx(cursor_y, cursor_x);
5792 for (file = 0, done = 5; result && file < files; line++, file++) {
5793 int almost_done = file * 100 / files;
5795 if (almost_done > done) {
5796 done = almost_done;
5797 string_format(view->ref, "updating file %u of %u (%d%% done)",
5798 file, files, done);
5799 update_view_title(view);
5800 setsyx(cursor_y, cursor_x);
5801 doupdate();
5803 result = status_update_write(&io, line->data, line->type);
5805 string_copy(view->ref, buf);
5807 return io_done(&io) && result;
5810 static bool
5811 status_update(struct view *view)
5813 struct line *line = &view->line[view->lineno];
5815 assert(view->lines);
5817 if (!line->data) {
5818 /* This should work even for the "On branch" line. */
5819 if (line < view->line + view->lines && !line[1].data) {
5820 report("Nothing to update");
5821 return FALSE;
5824 if (!status_update_files(view, line + 1)) {
5825 report("Failed to update file status");
5826 return FALSE;
5829 } else if (!status_update_file(line->data, line->type)) {
5830 report("Failed to update file status");
5831 return FALSE;
5834 return TRUE;
5837 static bool
5838 status_revert(struct status *status, enum line_type type, bool has_none)
5840 if (!status || type != LINE_STAT_UNSTAGED) {
5841 if (type == LINE_STAT_STAGED) {
5842 report("Cannot revert changes to staged files");
5843 } else if (type == LINE_STAT_UNTRACKED) {
5844 report("Cannot revert changes to untracked files");
5845 } else if (has_none) {
5846 report("Nothing to revert");
5847 } else {
5848 report("Cannot revert changes to multiple files");
5851 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5852 char mode[10] = "100644";
5853 const char *reset_argv[] = {
5854 "git", "update-index", "--cacheinfo", mode,
5855 status->old.rev, status->old.name, NULL
5857 const char *checkout_argv[] = {
5858 "git", "checkout", "--", status->old.name, NULL
5861 if (status->status == 'U') {
5862 string_format(mode, "%5o", status->old.mode);
5864 if (status->old.mode == 0 && status->new.mode == 0) {
5865 reset_argv[2] = "--force-remove";
5866 reset_argv[3] = status->old.name;
5867 reset_argv[4] = NULL;
5870 if (!io_run_fg(reset_argv, opt_cdup))
5871 return FALSE;
5872 if (status->old.mode == 0 && status->new.mode == 0)
5873 return TRUE;
5876 return io_run_fg(checkout_argv, opt_cdup);
5879 return FALSE;
5882 static enum request
5883 status_request(struct view *view, enum request request, struct line *line)
5885 struct status *status = line->data;
5887 switch (request) {
5888 case REQ_STATUS_UPDATE:
5889 if (!status_update(view))
5890 return REQ_NONE;
5891 break;
5893 case REQ_STATUS_REVERT:
5894 if (!status_revert(status, line->type, status_has_none(view, line)))
5895 return REQ_NONE;
5896 break;
5898 case REQ_STATUS_MERGE:
5899 if (!status || status->status != 'U') {
5900 report("Merging only possible for files with unmerged status ('U').");
5901 return REQ_NONE;
5903 open_mergetool(status->new.name);
5904 break;
5906 case REQ_EDIT:
5907 if (!status)
5908 return request;
5909 if (status->status == 'D') {
5910 report("File has been deleted.");
5911 return REQ_NONE;
5914 open_editor(status->new.name);
5915 break;
5917 case REQ_VIEW_BLAME:
5918 if (status)
5919 opt_ref[0] = 0;
5920 return request;
5922 case REQ_ENTER:
5923 /* After returning the status view has been split to
5924 * show the stage view. No further reloading is
5925 * necessary. */
5926 return status_enter(view, line);
5928 case REQ_REFRESH:
5929 /* Simply reload the view. */
5930 break;
5932 default:
5933 return request;
5936 refresh_view(view);
5938 return REQ_NONE;
5941 static void
5942 status_select(struct view *view, struct line *line)
5944 struct status *status = line->data;
5945 char file[SIZEOF_STR] = "all files";
5946 const char *text;
5947 const char *key;
5949 if (status && !string_format(file, "'%s'", status->new.name))
5950 return;
5952 if (!status && line[1].type == LINE_STAT_NONE)
5953 line++;
5955 switch (line->type) {
5956 case LINE_STAT_STAGED:
5957 text = "Press %s to unstage %s for commit";
5958 break;
5960 case LINE_STAT_UNSTAGED:
5961 text = "Press %s to stage %s for commit";
5962 break;
5964 case LINE_STAT_UNTRACKED:
5965 text = "Press %s to stage %s for addition";
5966 break;
5968 case LINE_STAT_HEAD:
5969 case LINE_STAT_NONE:
5970 text = "Nothing to update";
5971 break;
5973 default:
5974 die("line type %d not handled in switch", line->type);
5977 if (status && status->status == 'U') {
5978 text = "Press %s to resolve conflict in %s";
5979 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5981 } else {
5982 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5985 string_format(view->ref, text, key, file);
5986 if (status)
5987 string_copy(opt_file, status->new.name);
5990 static bool
5991 status_grep(struct view *view, struct line *line)
5993 struct status *status = line->data;
5995 if (status) {
5996 const char buf[2] = { status->status, 0 };
5997 const char *text[] = { status->new.name, buf, NULL };
5999 return grep_text(view, text);
6002 return FALSE;
6005 static struct view_ops status_ops = {
6006 "file",
6008 status_open,
6009 NULL,
6010 status_draw,
6011 status_request,
6012 status_grep,
6013 status_select,
6017 struct stage_state {
6018 struct diff_state diff;
6019 size_t chunks;
6020 int *chunk;
6023 static bool
6024 stage_diff_write(struct io *io, struct line *line, struct line *end)
6026 while (line < end) {
6027 if (!io_write(io, line->data, strlen(line->data)) ||
6028 !io_write(io, "\n", 1))
6029 return FALSE;
6030 line++;
6031 if (line->type == LINE_DIFF_CHUNK ||
6032 line->type == LINE_DIFF_HEADER)
6033 break;
6036 return TRUE;
6039 static bool
6040 stage_apply_chunk(struct view *view, struct line *chunk, bool revert)
6042 const char *apply_argv[SIZEOF_ARG] = {
6043 "git", "apply", "--whitespace=nowarn", NULL
6045 struct line *diff_hdr;
6046 struct io io;
6047 int argc = 3;
6049 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6050 if (!diff_hdr)
6051 return FALSE;
6053 if (!revert)
6054 apply_argv[argc++] = "--cached";
6055 if (revert || stage_line_type == LINE_STAT_STAGED)
6056 apply_argv[argc++] = "-R";
6057 apply_argv[argc++] = "-";
6058 apply_argv[argc++] = NULL;
6059 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6060 return FALSE;
6062 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6063 !stage_diff_write(&io, chunk, view->line + view->lines))
6064 chunk = NULL;
6066 io_done(&io);
6067 io_run_bg(update_index_argv);
6069 return chunk ? TRUE : FALSE;
6072 static bool
6073 stage_update(struct view *view, struct line *line)
6075 struct line *chunk = NULL;
6077 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6078 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6080 if (chunk) {
6081 if (!stage_apply_chunk(view, chunk, FALSE)) {
6082 report("Failed to apply chunk");
6083 return FALSE;
6086 } else if (!stage_status.status) {
6087 view = view->parent;
6089 for (line = view->line; line < view->line + view->lines; line++)
6090 if (line->type == stage_line_type)
6091 break;
6093 if (!status_update_files(view, line + 1)) {
6094 report("Failed to update files");
6095 return FALSE;
6098 } else if (!status_update_file(&stage_status, stage_line_type)) {
6099 report("Failed to update file");
6100 return FALSE;
6103 return TRUE;
6106 static bool
6107 stage_revert(struct view *view, struct line *line)
6109 struct line *chunk = NULL;
6111 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6112 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6114 if (chunk) {
6115 if (!prompt_yesno("Are you sure you want to revert changes?"))
6116 return FALSE;
6118 if (!stage_apply_chunk(view, chunk, TRUE)) {
6119 report("Failed to revert chunk");
6120 return FALSE;
6122 return TRUE;
6124 } else {
6125 return status_revert(stage_status.status ? &stage_status : NULL,
6126 stage_line_type, FALSE);
6131 static void
6132 stage_next(struct view *view, struct line *line)
6134 struct stage_state *state = view->private;
6135 int i;
6137 if (!state->chunks) {
6138 for (line = view->line; line < view->line + view->lines; line++) {
6139 if (line->type != LINE_DIFF_CHUNK)
6140 continue;
6142 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6143 report("Allocation failure");
6144 return;
6147 state->chunk[state->chunks++] = line - view->line;
6151 for (i = 0; i < state->chunks; i++) {
6152 if (state->chunk[i] > view->lineno) {
6153 do_scroll_view(view, state->chunk[i] - view->lineno);
6154 report("Chunk %d of %d", i + 1, state->chunks);
6155 return;
6159 report("No next chunk found");
6162 static enum request
6163 stage_request(struct view *view, enum request request, struct line *line)
6165 switch (request) {
6166 case REQ_STATUS_UPDATE:
6167 if (!stage_update(view, line))
6168 return REQ_NONE;
6169 break;
6171 case REQ_STATUS_REVERT:
6172 if (!stage_revert(view, line))
6173 return REQ_NONE;
6174 break;
6176 case REQ_STAGE_NEXT:
6177 if (stage_line_type == LINE_STAT_UNTRACKED) {
6178 report("File is untracked; press %s to add",
6179 get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
6180 return REQ_NONE;
6182 stage_next(view, line);
6183 return REQ_NONE;
6185 case REQ_EDIT:
6186 if (!stage_status.new.name[0])
6187 return request;
6188 if (stage_status.status == 'D') {
6189 report("File has been deleted.");
6190 return REQ_NONE;
6193 open_editor(stage_status.new.name);
6194 break;
6196 case REQ_REFRESH:
6197 /* Reload everything ... */
6198 break;
6200 case REQ_VIEW_BLAME:
6201 if (stage_status.new.name[0]) {
6202 string_copy(opt_file, stage_status.new.name);
6203 opt_ref[0] = 0;
6205 return request;
6207 case REQ_ENTER:
6208 return diff_common_enter(view, request, line);
6210 case REQ_DIFF_CONTEXT_UP:
6211 case REQ_DIFF_CONTEXT_DOWN:
6212 if (!update_diff_context(request))
6213 return REQ_NONE;
6214 break;
6216 default:
6217 return request;
6220 refresh_view(view->parent);
6222 /* Check whether the staged entry still exists, and close the
6223 * stage view if it doesn't. */
6224 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6225 status_restore(view->parent);
6226 return REQ_VIEW_CLOSE;
6229 refresh_view(view);
6231 return REQ_NONE;
6234 static bool
6235 stage_open(struct view *view, enum open_flags flags)
6237 static const char *no_head_diff_argv[] = {
6238 "git", "diff", "--no-color", "--patch-with-stat",
6239 opt_diff_context_arg,
6240 "--", "/dev/null", stage_status.new.name, NULL
6242 static const char *index_show_argv[] = {
6243 "git", "diff-index", "--root", "--patch-with-stat", "-C", "-M",
6244 "--cached", opt_diff_context_arg, "HEAD", "--",
6245 stage_status.old.name, stage_status.new.name, NULL
6247 static const char *files_show_argv[] = {
6248 "git", "diff-files", "--root", "--patch-with-stat",
6249 "-C", "-M", opt_diff_context_arg, "--",
6250 stage_status.old.name, stage_status.new.name, NULL
6252 /* Diffs for unmerged entries are empty when passing the new
6253 * path, so leave out the new path. */
6254 static const char *files_unmerged_argv[] = {
6255 "git", "diff-files", "--root", "--patch-with-stat",
6256 "-C", "-M", opt_diff_context_arg, "--",
6257 stage_status.old.name, NULL
6259 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6260 const char **argv = NULL;
6261 const char *info;
6263 switch (stage_line_type) {
6264 case LINE_STAT_STAGED:
6265 if (is_initial_commit()) {
6266 argv = no_head_diff_argv;
6267 } else {
6268 argv = index_show_argv;
6270 if (stage_status.status)
6271 info = "Staged changes to %s";
6272 else
6273 info = "Staged changes";
6274 break;
6276 case LINE_STAT_UNSTAGED:
6277 if (stage_status.status != 'U')
6278 argv = files_show_argv;
6279 else
6280 argv = files_unmerged_argv;
6281 if (stage_status.status)
6282 info = "Unstaged changes to %s";
6283 else
6284 info = "Unstaged changes";
6285 break;
6287 case LINE_STAT_UNTRACKED:
6288 info = "Untracked file %s";
6289 argv = file_argv;
6290 break;
6292 case LINE_STAT_HEAD:
6293 default:
6294 die("line type %d not handled in switch", stage_line_type);
6297 string_format(view->ref, info, stage_status.new.name);
6298 view->vid[0] = 0;
6299 view->dir = opt_cdup;
6300 return argv_copy(&view->argv, argv)
6301 && begin_update(view, NULL, NULL, flags);
6304 static bool
6305 stage_read(struct view *view, char *data)
6307 struct stage_state *state = view->private;
6309 if (data && diff_common_read(view, data, &state->diff))
6310 return TRUE;
6312 return pager_read(view, data);
6315 static struct view_ops stage_ops = {
6316 "line",
6317 sizeof(struct stage_state),
6318 stage_open,
6319 stage_read,
6320 diff_common_draw,
6321 stage_request,
6322 pager_grep,
6323 pager_select,
6328 * Revision graph
6331 static const enum line_type graph_colors[] = {
6332 LINE_PALETTE_0,
6333 LINE_PALETTE_1,
6334 LINE_PALETTE_2,
6335 LINE_PALETTE_3,
6336 LINE_PALETTE_4,
6337 LINE_PALETTE_5,
6338 LINE_PALETTE_6,
6341 static enum line_type get_graph_color(struct graph_symbol *symbol)
6343 if (symbol->commit)
6344 return LINE_GRAPH_COMMIT;
6345 assert(symbol->color < ARRAY_SIZE(graph_colors));
6346 return graph_colors[symbol->color];
6349 static bool
6350 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6352 const char *chars = graph_symbol_to_utf8(symbol);
6354 return draw_text(view, color, chars + !!first);
6357 static bool
6358 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6360 const char *chars = graph_symbol_to_ascii(symbol);
6362 return draw_text(view, color, chars + !!first);
6365 static bool
6366 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6368 const chtype *chars = graph_symbol_to_chtype(symbol);
6370 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6373 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6375 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6377 static const draw_graph_fn fns[] = {
6378 draw_graph_ascii,
6379 draw_graph_chtype,
6380 draw_graph_utf8
6382 draw_graph_fn fn = fns[opt_line_graphics];
6383 int i;
6385 for (i = 0; i < canvas->size; i++) {
6386 struct graph_symbol *symbol = &canvas->symbols[i];
6387 enum line_type color = get_graph_color(symbol);
6389 if (fn(view, symbol, color, i == 0))
6390 return TRUE;
6393 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6397 * Main view backend
6400 struct commit {
6401 char id[SIZEOF_REV]; /* SHA1 ID. */
6402 char title[128]; /* First line of the commit message. */
6403 const char *author; /* Author of the commit. */
6404 struct time time; /* Date from the author ident. */
6405 struct ref_list *refs; /* Repository references. */
6406 struct graph_canvas graph; /* Ancestry chain graphics. */
6409 static bool
6410 main_open(struct view *view, enum open_flags flags)
6412 static const char *main_argv[] = {
6413 "git", "log", "--no-color", "--pretty=raw", "--parents",
6414 "--topo-order", "%(diffargs)", "%(revargs)",
6415 "--", "%(fileargs)", NULL
6418 return begin_update(view, NULL, main_argv, flags);
6421 static bool
6422 main_draw(struct view *view, struct line *line, unsigned int lineno)
6424 struct commit *commit = line->data;
6426 if (!commit->author)
6427 return FALSE;
6429 if (opt_line_number && draw_lineno(view, lineno))
6430 return TRUE;
6432 if (draw_date(view, &commit->time))
6433 return TRUE;
6435 if (draw_author(view, commit->author))
6436 return TRUE;
6438 if (opt_rev_graph && draw_graph(view, &commit->graph))
6439 return TRUE;
6441 if (draw_refs(view, commit->refs))
6442 return TRUE;
6444 draw_text(view, LINE_DEFAULT, commit->title);
6445 return TRUE;
6448 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6449 static bool
6450 main_read(struct view *view, char *line)
6452 struct graph *graph = view->private;
6453 enum line_type type;
6454 struct commit *commit;
6456 if (!line) {
6457 if (!view->lines && !view->prev)
6458 die("No revisions match the given arguments.");
6459 if (view->lines > 0) {
6460 commit = view->line[view->lines - 1].data;
6461 view->line[view->lines - 1].dirty = 1;
6462 if (!commit->author) {
6463 view->lines--;
6464 free(commit);
6468 done_graph(graph);
6469 return TRUE;
6472 type = get_line_type(line);
6473 if (type == LINE_COMMIT) {
6474 bool is_boundary;
6476 commit = calloc(1, sizeof(struct commit));
6477 if (!commit)
6478 return FALSE;
6480 line += STRING_SIZE("commit ");
6481 is_boundary = *line == '-';
6482 if (is_boundary)
6483 line++;
6485 string_copy_rev(commit->id, line);
6486 commit->refs = get_ref_list(commit->id);
6487 add_line_data(view, commit, LINE_MAIN_COMMIT);
6488 graph_add_commit(graph, &commit->graph, commit->id, line, is_boundary);
6489 return TRUE;
6492 if (!view->lines)
6493 return TRUE;
6494 commit = view->line[view->lines - 1].data;
6496 switch (type) {
6497 case LINE_PARENT:
6498 if (!graph->has_parents)
6499 graph_add_parent(graph, line + STRING_SIZE("parent "));
6500 break;
6502 case LINE_AUTHOR:
6503 parse_author_line(line + STRING_SIZE("author "),
6504 &commit->author, &commit->time);
6505 graph_render_parents(graph);
6506 break;
6508 default:
6509 /* Fill in the commit title if it has not already been set. */
6510 if (commit->title[0])
6511 break;
6513 /* Require titles to start with a non-space character at the
6514 * offset used by git log. */
6515 if (strncmp(line, " ", 4))
6516 break;
6517 line += 4;
6518 /* Well, if the title starts with a whitespace character,
6519 * try to be forgiving. Otherwise we end up with no title. */
6520 while (isspace(*line))
6521 line++;
6522 if (*line == '\0')
6523 break;
6524 /* FIXME: More graceful handling of titles; append "..." to
6525 * shortened titles, etc. */
6527 string_expand(commit->title, sizeof(commit->title), line, 1);
6528 view->line[view->lines - 1].dirty = 1;
6531 return TRUE;
6534 static enum request
6535 main_request(struct view *view, enum request request, struct line *line)
6537 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6539 switch (request) {
6540 case REQ_ENTER:
6541 if (view_is_displayed(view) && display[0] != view)
6542 maximize_view(view, TRUE);
6543 open_view(view, REQ_VIEW_DIFF, flags);
6544 break;
6545 case REQ_REFRESH:
6546 load_refs();
6547 refresh_view(view);
6548 break;
6550 case REQ_JUMP_COMMIT:
6552 int lineno;
6554 for (lineno = 0; lineno < view->lines; lineno++) {
6555 struct commit *commit = view->line[lineno].data;
6557 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
6558 select_view_line(view, lineno);
6559 report("");
6560 return REQ_NONE;
6564 report("Unable to find commit '%s'", opt_search);
6565 break;
6567 default:
6568 return request;
6571 return REQ_NONE;
6574 static bool
6575 grep_refs(struct ref_list *list, regex_t *regex)
6577 regmatch_t pmatch;
6578 size_t i;
6580 if (!opt_show_refs || !list)
6581 return FALSE;
6583 for (i = 0; i < list->size; i++) {
6584 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
6585 return TRUE;
6588 return FALSE;
6591 static bool
6592 main_grep(struct view *view, struct line *line)
6594 struct commit *commit = line->data;
6595 const char *text[] = {
6596 commit->title,
6597 mkauthor(commit->author, opt_author_cols, opt_author),
6598 mkdate(&commit->time, opt_date),
6599 NULL
6602 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
6605 static void
6606 main_select(struct view *view, struct line *line)
6608 struct commit *commit = line->data;
6610 string_copy_rev(view->ref, commit->id);
6611 string_copy_rev(ref_commit, view->ref);
6614 static struct view_ops main_ops = {
6615 "commit",
6616 sizeof(struct graph),
6617 main_open,
6618 main_read,
6619 main_draw,
6620 main_request,
6621 main_grep,
6622 main_select,
6627 * Status management
6630 /* Whether or not the curses interface has been initialized. */
6631 static bool cursed = FALSE;
6633 /* Terminal hacks and workarounds. */
6634 static bool use_scroll_redrawwin;
6635 static bool use_scroll_status_wclear;
6637 /* The status window is used for polling keystrokes. */
6638 static WINDOW *status_win;
6640 /* Reading from the prompt? */
6641 static bool input_mode = FALSE;
6643 static bool status_empty = FALSE;
6645 /* Update status and title window. */
6646 static void
6647 report(const char *msg, ...)
6649 struct view *view = display[current_view];
6651 if (input_mode)
6652 return;
6654 if (!view) {
6655 char buf[SIZEOF_STR];
6656 va_list args;
6658 va_start(args, msg);
6659 if (vsnprintf(buf, sizeof(buf), msg, args) >= sizeof(buf)) {
6660 buf[sizeof(buf) - 1] = 0;
6661 buf[sizeof(buf) - 2] = '.';
6662 buf[sizeof(buf) - 3] = '.';
6663 buf[sizeof(buf) - 4] = '.';
6665 va_end(args);
6666 die("%s", buf);
6669 if (!status_empty || *msg) {
6670 va_list args;
6672 va_start(args, msg);
6674 wmove(status_win, 0, 0);
6675 if (view->has_scrolled && use_scroll_status_wclear)
6676 wclear(status_win);
6677 if (*msg) {
6678 vwprintw(status_win, msg, args);
6679 status_empty = FALSE;
6680 } else {
6681 status_empty = TRUE;
6683 wclrtoeol(status_win);
6684 wnoutrefresh(status_win);
6686 va_end(args);
6689 update_view_title(view);
6692 static void
6693 init_display(void)
6695 const char *term;
6696 int x, y;
6698 /* Initialize the curses library */
6699 if (isatty(STDIN_FILENO)) {
6700 cursed = !!initscr();
6701 opt_tty = stdin;
6702 } else {
6703 /* Leave stdin and stdout alone when acting as a pager. */
6704 opt_tty = fopen("/dev/tty", "r+");
6705 if (!opt_tty)
6706 die("Failed to open /dev/tty");
6707 cursed = !!newterm(NULL, opt_tty, opt_tty);
6710 if (!cursed)
6711 die("Failed to initialize curses");
6713 nonl(); /* Disable conversion and detect newlines from input. */
6714 cbreak(); /* Take input chars one at a time, no wait for \n */
6715 noecho(); /* Don't echo input */
6716 leaveok(stdscr, FALSE);
6718 if (has_colors())
6719 init_colors();
6721 getmaxyx(stdscr, y, x);
6722 status_win = newwin(1, x, y - 1, 0);
6723 if (!status_win)
6724 die("Failed to create status window");
6726 /* Enable keyboard mapping */
6727 keypad(status_win, TRUE);
6728 wbkgdset(status_win, get_line_attr(LINE_STATUS));
6730 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6731 set_tabsize(opt_tab_size);
6732 #else
6733 TABSIZE = opt_tab_size;
6734 #endif
6736 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6737 if (term && !strcmp(term, "gnome-terminal")) {
6738 /* In the gnome-terminal-emulator, the message from
6739 * scrolling up one line when impossible followed by
6740 * scrolling down one line causes corruption of the
6741 * status line. This is fixed by calling wclear. */
6742 use_scroll_status_wclear = TRUE;
6743 use_scroll_redrawwin = FALSE;
6745 } else if (term && !strcmp(term, "xrvt-xpm")) {
6746 /* No problems with full optimizations in xrvt-(unicode)
6747 * and aterm. */
6748 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6750 } else {
6751 /* When scrolling in (u)xterm the last line in the
6752 * scrolling direction will update slowly. */
6753 use_scroll_redrawwin = TRUE;
6754 use_scroll_status_wclear = FALSE;
6758 static int
6759 get_input(int prompt_position)
6761 struct view *view;
6762 int i, key, cursor_y, cursor_x;
6764 if (prompt_position)
6765 input_mode = TRUE;
6767 while (TRUE) {
6768 bool loading = FALSE;
6770 foreach_view (view, i) {
6771 update_view(view);
6772 if (view_is_displayed(view) && view->has_scrolled &&
6773 use_scroll_redrawwin)
6774 redrawwin(view->win);
6775 view->has_scrolled = FALSE;
6776 if (view->pipe)
6777 loading = TRUE;
6780 /* Update the cursor position. */
6781 if (prompt_position) {
6782 getbegyx(status_win, cursor_y, cursor_x);
6783 cursor_x = prompt_position;
6784 } else {
6785 view = display[current_view];
6786 getbegyx(view->win, cursor_y, cursor_x);
6787 cursor_x = view->width - 1;
6788 cursor_y += view->lineno - view->offset;
6790 setsyx(cursor_y, cursor_x);
6792 /* Refresh, accept single keystroke of input */
6793 doupdate();
6794 nodelay(status_win, loading);
6795 key = wgetch(status_win);
6797 /* wgetch() with nodelay() enabled returns ERR when
6798 * there's no input. */
6799 if (key == ERR) {
6801 } else if (key == KEY_RESIZE) {
6802 int height, width;
6804 getmaxyx(stdscr, height, width);
6806 wresize(status_win, 1, width);
6807 mvwin(status_win, height - 1, 0);
6808 wnoutrefresh(status_win);
6809 resize_display();
6810 redraw_display(TRUE);
6812 } else {
6813 input_mode = FALSE;
6814 if (key == erasechar())
6815 key = KEY_BACKSPACE;
6816 return key;
6821 static char *
6822 prompt_input(const char *prompt, input_handler handler, void *data)
6824 enum input_status status = INPUT_OK;
6825 static char buf[SIZEOF_STR];
6826 size_t pos = 0;
6828 buf[pos] = 0;
6830 while (status == INPUT_OK || status == INPUT_SKIP) {
6831 int key;
6833 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6834 wclrtoeol(status_win);
6836 key = get_input(pos + 1);
6837 switch (key) {
6838 case KEY_RETURN:
6839 case KEY_ENTER:
6840 case '\n':
6841 status = pos ? INPUT_STOP : INPUT_CANCEL;
6842 break;
6844 case KEY_BACKSPACE:
6845 if (pos > 0)
6846 buf[--pos] = 0;
6847 else
6848 status = INPUT_CANCEL;
6849 break;
6851 case KEY_ESC:
6852 status = INPUT_CANCEL;
6853 break;
6855 default:
6856 if (pos >= sizeof(buf)) {
6857 report("Input string too long");
6858 return NULL;
6861 status = handler(data, buf, key);
6862 if (status == INPUT_OK)
6863 buf[pos++] = (char) key;
6867 /* Clear the status window */
6868 status_empty = FALSE;
6869 report("");
6871 if (status == INPUT_CANCEL)
6872 return NULL;
6874 buf[pos++] = 0;
6876 return buf;
6879 static enum input_status
6880 prompt_yesno_handler(void *data, char *buf, int c)
6882 if (c == 'y' || c == 'Y')
6883 return INPUT_STOP;
6884 if (c == 'n' || c == 'N')
6885 return INPUT_CANCEL;
6886 return INPUT_SKIP;
6889 static bool
6890 prompt_yesno(const char *prompt)
6892 char prompt2[SIZEOF_STR];
6894 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6895 return FALSE;
6897 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6900 static enum input_status
6901 read_prompt_handler(void *data, char *buf, int c)
6903 return isprint(c) ? INPUT_OK : INPUT_SKIP;
6906 static char *
6907 read_prompt(const char *prompt)
6909 return prompt_input(prompt, read_prompt_handler, NULL);
6912 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6914 enum input_status status = INPUT_OK;
6915 int size = 0;
6917 while (items[size].text)
6918 size++;
6920 while (status == INPUT_OK) {
6921 const struct menu_item *item = &items[*selected];
6922 int key;
6923 int i;
6925 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6926 prompt, *selected + 1, size);
6927 if (item->hotkey)
6928 wprintw(status_win, "[%c] ", (char) item->hotkey);
6929 wprintw(status_win, "%s", item->text);
6930 wclrtoeol(status_win);
6932 key = get_input(COLS - 1);
6933 switch (key) {
6934 case KEY_RETURN:
6935 case KEY_ENTER:
6936 case '\n':
6937 status = INPUT_STOP;
6938 break;
6940 case KEY_LEFT:
6941 case KEY_UP:
6942 *selected = *selected - 1;
6943 if (*selected < 0)
6944 *selected = size - 1;
6945 break;
6947 case KEY_RIGHT:
6948 case KEY_DOWN:
6949 *selected = (*selected + 1) % size;
6950 break;
6952 case KEY_ESC:
6953 status = INPUT_CANCEL;
6954 break;
6956 default:
6957 for (i = 0; items[i].text; i++)
6958 if (items[i].hotkey == key) {
6959 *selected = i;
6960 status = INPUT_STOP;
6961 break;
6966 /* Clear the status window */
6967 status_empty = FALSE;
6968 report("");
6970 return status != INPUT_CANCEL;
6974 * Repository properties
6977 static struct ref **refs = NULL;
6978 static size_t refs_size = 0;
6979 static struct ref *refs_head = NULL;
6981 static struct ref_list **ref_lists = NULL;
6982 static size_t ref_lists_size = 0;
6984 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
6985 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
6986 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
6988 static int
6989 compare_refs(const void *ref1_, const void *ref2_)
6991 const struct ref *ref1 = *(const struct ref **)ref1_;
6992 const struct ref *ref2 = *(const struct ref **)ref2_;
6994 if (ref1->tag != ref2->tag)
6995 return ref2->tag - ref1->tag;
6996 if (ref1->ltag != ref2->ltag)
6997 return ref2->ltag - ref1->ltag;
6998 if (ref1->head != ref2->head)
6999 return ref2->head - ref1->head;
7000 if (ref1->tracked != ref2->tracked)
7001 return ref2->tracked - ref1->tracked;
7002 if (ref1->replace != ref2->replace)
7003 return ref2->replace - ref1->replace;
7004 /* Order remotes last. */
7005 if (ref1->remote != ref2->remote)
7006 return ref1->remote - ref2->remote;
7007 return strcmp(ref1->name, ref2->name);
7010 static void
7011 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
7013 size_t i;
7015 for (i = 0; i < refs_size; i++)
7016 if (!visitor(data, refs[i]))
7017 break;
7020 static struct ref *
7021 get_ref_head()
7023 return refs_head;
7026 static struct ref_list *
7027 get_ref_list(const char *id)
7029 struct ref_list *list;
7030 size_t i;
7032 for (i = 0; i < ref_lists_size; i++)
7033 if (!strcmp(id, ref_lists[i]->id))
7034 return ref_lists[i];
7036 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
7037 return NULL;
7038 list = calloc(1, sizeof(*list));
7039 if (!list)
7040 return NULL;
7042 for (i = 0; i < refs_size; i++) {
7043 if (!strcmp(id, refs[i]->id) &&
7044 realloc_refs_list(&list->refs, list->size, 1))
7045 list->refs[list->size++] = refs[i];
7048 if (!list->refs) {
7049 free(list);
7050 return NULL;
7053 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
7054 ref_lists[ref_lists_size++] = list;
7055 return list;
7058 static int
7059 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
7061 struct ref *ref = NULL;
7062 bool tag = FALSE;
7063 bool ltag = FALSE;
7064 bool remote = FALSE;
7065 bool replace = FALSE;
7066 bool tracked = FALSE;
7067 bool head = FALSE;
7068 int from = 0, to = refs_size - 1;
7070 if (!prefixcmp(name, "refs/tags/")) {
7071 if (!suffixcmp(name, namelen, "^{}")) {
7072 namelen -= 3;
7073 name[namelen] = 0;
7074 } else {
7075 ltag = TRUE;
7078 tag = TRUE;
7079 namelen -= STRING_SIZE("refs/tags/");
7080 name += STRING_SIZE("refs/tags/");
7082 } else if (!prefixcmp(name, "refs/remotes/")) {
7083 remote = TRUE;
7084 namelen -= STRING_SIZE("refs/remotes/");
7085 name += STRING_SIZE("refs/remotes/");
7086 tracked = !strcmp(opt_remote, name);
7088 } else if (!prefixcmp(name, "refs/replace/")) {
7089 replace = TRUE;
7090 id = name + strlen("refs/replace/");
7091 idlen = namelen - strlen("refs/replace/");
7092 name = "replaced";
7093 namelen = strlen(name);
7095 } else if (!prefixcmp(name, "refs/heads/")) {
7096 namelen -= STRING_SIZE("refs/heads/");
7097 name += STRING_SIZE("refs/heads/");
7098 if (strlen(opt_head) == namelen
7099 && !strncmp(opt_head, name, namelen))
7100 return OK;
7102 } else if (!strcmp(name, "HEAD")) {
7103 head = TRUE;
7104 if (*opt_head) {
7105 namelen = strlen(opt_head);
7106 name = opt_head;
7110 /* If we are reloading or it's an annotated tag, replace the
7111 * previous SHA1 with the resolved commit id; relies on the fact
7112 * git-ls-remote lists the commit id of an annotated tag right
7113 * before the commit id it points to. */
7114 while ((from <= to) && !replace) {
7115 size_t pos = (to + from) / 2;
7116 int cmp = strcmp(name, refs[pos]->name);
7118 if (!cmp) {
7119 ref = refs[pos];
7120 break;
7123 if (cmp < 0)
7124 to = pos - 1;
7125 else
7126 from = pos + 1;
7129 if (!ref) {
7130 if (!realloc_refs(&refs, refs_size, 1))
7131 return ERR;
7132 ref = calloc(1, sizeof(*ref) + namelen);
7133 if (!ref)
7134 return ERR;
7135 memmove(refs + from + 1, refs + from,
7136 (refs_size - from) * sizeof(*refs));
7137 refs[from] = ref;
7138 strncpy(ref->name, name, namelen);
7139 refs_size++;
7142 ref->head = head;
7143 ref->tag = tag;
7144 ref->ltag = ltag;
7145 ref->remote = remote;
7146 ref->replace = replace;
7147 ref->tracked = tracked;
7148 string_copy_rev(ref->id, id);
7150 if (head)
7151 refs_head = ref;
7152 return OK;
7155 static int
7156 load_refs(void)
7158 const char *head_argv[] = {
7159 "git", "symbolic-ref", "HEAD", NULL
7161 static const char *ls_remote_argv[SIZEOF_ARG] = {
7162 "git", "ls-remote", opt_git_dir, NULL
7164 static bool init = FALSE;
7165 size_t i;
7167 if (!init) {
7168 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
7169 die("TIG_LS_REMOTE contains too many arguments");
7170 init = TRUE;
7173 if (!*opt_git_dir)
7174 return OK;
7176 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
7177 !prefixcmp(opt_head, "refs/heads/")) {
7178 char *offset = opt_head + STRING_SIZE("refs/heads/");
7180 memmove(opt_head, offset, strlen(offset) + 1);
7183 refs_head = NULL;
7184 for (i = 0; i < refs_size; i++)
7185 refs[i]->id[0] = 0;
7187 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
7188 return ERR;
7190 /* Update the ref lists to reflect changes. */
7191 for (i = 0; i < ref_lists_size; i++) {
7192 struct ref_list *list = ref_lists[i];
7193 size_t old, new;
7195 for (old = new = 0; old < list->size; old++)
7196 if (!strcmp(list->id, list->refs[old]->id))
7197 list->refs[new++] = list->refs[old];
7198 list->size = new;
7201 qsort(refs, refs_size, sizeof(*refs), compare_refs);
7203 return OK;
7206 static void
7207 set_remote_branch(const char *name, const char *value, size_t valuelen)
7209 if (!strcmp(name, ".remote")) {
7210 string_ncopy(opt_remote, value, valuelen);
7212 } else if (*opt_remote && !strcmp(name, ".merge")) {
7213 size_t from = strlen(opt_remote);
7215 if (!prefixcmp(value, "refs/heads/"))
7216 value += STRING_SIZE("refs/heads/");
7218 if (!string_format_from(opt_remote, &from, "/%s", value))
7219 opt_remote[0] = 0;
7223 static void
7224 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7226 const char *argv[SIZEOF_ARG] = { name, "=" };
7227 int argc = 1 + (cmd == option_set_command);
7228 enum option_code error;
7230 if (!argv_from_string(argv, &argc, value))
7231 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7232 else
7233 error = cmd(argc, argv);
7235 if (error != OPT_OK)
7236 warn("Option 'tig.%s': %s", name, option_errors[error]);
7239 static bool
7240 set_environment_variable(const char *name, const char *value)
7242 size_t len = strlen(name) + 1 + strlen(value) + 1;
7243 char *env = malloc(len);
7245 if (env &&
7246 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7247 putenv(env) == 0)
7248 return TRUE;
7249 free(env);
7250 return FALSE;
7253 static void
7254 set_work_tree(const char *value)
7256 char cwd[SIZEOF_STR];
7258 if (!getcwd(cwd, sizeof(cwd)))
7259 die("Failed to get cwd path: %s", strerror(errno));
7260 if (chdir(opt_git_dir) < 0)
7261 die("Failed to chdir(%s): %s", strerror(errno));
7262 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7263 die("Failed to get git path: %s", strerror(errno));
7264 if (chdir(cwd) < 0)
7265 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7266 if (chdir(value) < 0)
7267 die("Failed to chdir(%s): %s", value, strerror(errno));
7268 if (!getcwd(cwd, sizeof(cwd)))
7269 die("Failed to get cwd path: %s", strerror(errno));
7270 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7271 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7272 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7273 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7274 opt_is_inside_work_tree = TRUE;
7277 static int
7278 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7280 if (!strcmp(name, "i18n.commitencoding"))
7281 string_ncopy(opt_encoding, value, valuelen);
7283 else if (!strcmp(name, "core.editor"))
7284 string_ncopy(opt_editor, value, valuelen);
7286 else if (!strcmp(name, "core.worktree"))
7287 set_work_tree(value);
7289 else if (!prefixcmp(name, "tig.color."))
7290 set_repo_config_option(name + 10, value, option_color_command);
7292 else if (!prefixcmp(name, "tig.bind."))
7293 set_repo_config_option(name + 9, value, option_bind_command);
7295 else if (!prefixcmp(name, "tig."))
7296 set_repo_config_option(name + 4, value, option_set_command);
7298 else if (*opt_head && !prefixcmp(name, "branch.") &&
7299 !strncmp(name + 7, opt_head, strlen(opt_head)))
7300 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7302 return OK;
7305 static int
7306 load_git_config(void)
7308 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7310 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7313 static int
7314 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7316 if (!opt_git_dir[0]) {
7317 string_ncopy(opt_git_dir, name, namelen);
7319 } else if (opt_is_inside_work_tree == -1) {
7320 /* This can be 3 different values depending on the
7321 * version of git being used. If git-rev-parse does not
7322 * understand --is-inside-work-tree it will simply echo
7323 * the option else either "true" or "false" is printed.
7324 * Default to true for the unknown case. */
7325 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7327 } else if (*name == '.') {
7328 string_ncopy(opt_cdup, name, namelen);
7330 } else {
7331 string_ncopy(opt_prefix, name, namelen);
7334 return OK;
7337 static int
7338 load_repo_info(void)
7340 const char *rev_parse_argv[] = {
7341 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7342 "--show-cdup", "--show-prefix", NULL
7345 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7350 * Main
7353 static const char usage[] =
7354 "tig " TIG_VERSION " (" __DATE__ ")\n"
7355 "\n"
7356 "Usage: tig [options] [revs] [--] [paths]\n"
7357 " or: tig show [options] [revs] [--] [paths]\n"
7358 " or: tig blame [options] [rev] [--] path\n"
7359 " or: tig status\n"
7360 " or: tig < [git command output]\n"
7361 "\n"
7362 "Options:\n"
7363 " +<number> Select line <number> in the first view\n"
7364 " -v, --version Show version and exit\n"
7365 " -h, --help Show help message and exit";
7367 static void __NORETURN
7368 quit(int sig)
7370 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7371 if (cursed)
7372 endwin();
7373 exit(0);
7376 static void __NORETURN
7377 die(const char *err, ...)
7379 va_list args;
7381 endwin();
7383 va_start(args, err);
7384 fputs("tig: ", stderr);
7385 vfprintf(stderr, err, args);
7386 fputs("\n", stderr);
7387 va_end(args);
7389 exit(1);
7392 static void
7393 warn(const char *msg, ...)
7395 va_list args;
7397 va_start(args, msg);
7398 fputs("tig warning: ", stderr);
7399 vfprintf(stderr, msg, args);
7400 fputs("\n", stderr);
7401 va_end(args);
7404 static int
7405 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7407 const char ***filter_args = data;
7409 return argv_append(filter_args, name) ? OK : ERR;
7412 static void
7413 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7415 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7416 const char **all_argv = NULL;
7418 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7419 !argv_append_array(&all_argv, argv) ||
7420 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7421 die("Failed to split arguments");
7422 argv_free(all_argv);
7423 free(all_argv);
7426 static void
7427 filter_options(const char *argv[], bool blame)
7429 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7431 if (blame)
7432 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7433 else
7434 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7436 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7439 static enum request
7440 parse_options(int argc, const char *argv[])
7442 enum request request = REQ_VIEW_MAIN;
7443 const char *subcommand;
7444 bool seen_dashdash = FALSE;
7445 const char **filter_argv = NULL;
7446 int i;
7448 if (!isatty(STDIN_FILENO))
7449 return REQ_VIEW_PAGER;
7451 if (argc <= 1)
7452 return REQ_VIEW_MAIN;
7454 subcommand = argv[1];
7455 if (!strcmp(subcommand, "status")) {
7456 if (argc > 2)
7457 warn("ignoring arguments after `%s'", subcommand);
7458 return REQ_VIEW_STATUS;
7460 } else if (!strcmp(subcommand, "blame")) {
7461 request = REQ_VIEW_BLAME;
7463 } else if (!strcmp(subcommand, "show")) {
7464 request = REQ_VIEW_DIFF;
7466 } else {
7467 subcommand = NULL;
7470 for (i = 1 + !!subcommand; i < argc; i++) {
7471 const char *opt = argv[i];
7473 // stop parsing our options after -- and let rev-parse handle the rest
7474 if (!seen_dashdash) {
7475 if (!strcmp(opt, "--")) {
7476 seen_dashdash = TRUE;
7477 continue;
7479 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7480 printf("tig version %s\n", TIG_VERSION);
7481 quit(0);
7483 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7484 printf("%s\n", usage);
7485 quit(0);
7487 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7488 opt_lineno = atoi(opt + 1);
7489 continue;
7494 if (!argv_append(&filter_argv, opt))
7495 die("command too long");
7498 if (filter_argv)
7499 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7501 /* Finish validating and setting up blame options */
7502 if (request == REQ_VIEW_BLAME) {
7503 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7504 die("invalid number of options to blame\n\n%s", usage);
7506 if (opt_rev_argv) {
7507 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7510 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7513 return request;
7517 main(int argc, const char *argv[])
7519 const char *codeset = "UTF-8";
7520 enum request request = parse_options(argc, argv);
7521 struct view *view;
7523 signal(SIGINT, quit);
7524 signal(SIGPIPE, SIG_IGN);
7526 if (setlocale(LC_ALL, "")) {
7527 codeset = nl_langinfo(CODESET);
7530 if (load_repo_info() == ERR)
7531 die("Failed to load repo info.");
7533 if (load_options() == ERR)
7534 die("Failed to load user config.");
7536 if (load_git_config() == ERR)
7537 die("Failed to load repo config.");
7539 /* Require a git repository unless when running in pager mode. */
7540 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7541 die("Not a git repository");
7543 if (*opt_encoding && strcmp(codeset, "UTF-8")) {
7544 opt_iconv_in = iconv_open("UTF-8", opt_encoding);
7545 if (opt_iconv_in == ICONV_NONE)
7546 die("Failed to initialize character set conversion");
7549 if (codeset && strcmp(codeset, "UTF-8")) {
7550 opt_iconv_out = iconv_open(codeset, "UTF-8");
7551 if (opt_iconv_out == ICONV_NONE)
7552 die("Failed to initialize character set conversion");
7555 if (load_refs() == ERR)
7556 die("Failed to load refs.");
7558 init_display();
7560 while (view_driver(display[current_view], request)) {
7561 int key = get_input(0);
7563 view = display[current_view];
7564 request = get_keybinding(view->keymap, key);
7566 /* Some low-level request handling. This keeps access to
7567 * status_win restricted. */
7568 switch (request) {
7569 case REQ_NONE:
7570 report("Unknown key, press %s for help",
7571 get_key(view->keymap, REQ_VIEW_HELP));
7572 break;
7573 case REQ_PROMPT:
7575 char *cmd = read_prompt(":");
7577 if (cmd && string_isnumber(cmd)) {
7578 int lineno = view->lineno + 1;
7580 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
7581 select_view_line(view, lineno - 1);
7582 report("");
7583 } else {
7584 report("Unable to parse '%s' as a line number", cmd);
7586 } else if (cmd && iscommit(cmd)) {
7587 string_ncopy(opt_search, cmd, strlen(cmd));
7589 request = view_request(view, REQ_JUMP_COMMIT);
7590 if (request == REQ_JUMP_COMMIT) {
7591 report("Jumping to commits is not supported by the '%s' view", view->name);
7594 } else if (cmd) {
7595 struct view *next = VIEW(REQ_VIEW_PAGER);
7596 const char *argv[SIZEOF_ARG] = { "git" };
7597 int argc = 1;
7599 /* When running random commands, initially show the
7600 * command in the title. However, it maybe later be
7601 * overwritten if a commit line is selected. */
7602 string_ncopy(next->ref, cmd, strlen(cmd));
7604 if (!argv_from_string(argv, &argc, cmd)) {
7605 report("Too many arguments");
7606 } else if (!format_argv(&next->argv, argv, FALSE)) {
7607 report("Argument formatting failed");
7608 } else {
7609 next->dir = NULL;
7610 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7614 request = REQ_NONE;
7615 break;
7617 case REQ_SEARCH:
7618 case REQ_SEARCH_BACK:
7620 const char *prompt = request == REQ_SEARCH ? "/" : "?";
7621 char *search = read_prompt(prompt);
7623 if (search)
7624 string_ncopy(opt_search, search, strlen(search));
7625 else if (*opt_search)
7626 request = request == REQ_SEARCH ?
7627 REQ_FIND_NEXT :
7628 REQ_FIND_PREV;
7629 else
7630 request = REQ_NONE;
7631 break;
7633 default:
7634 break;
7638 quit(0);
7640 return 0;