Add support for using path encoding from git attributes
[tig.git] / tig.c
blob2229279d66bfb08468c838da849974fd6fe0e482
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);
230 #define IGNORE_SPACE_ENUM(_) \
231 _(IGNORE_SPACE, NO), \
232 _(IGNORE_SPACE, ALL), \
233 _(IGNORE_SPACE, SOME), \
234 _(IGNORE_SPACE, AT_EOL)
236 DEFINE_ENUM(ignore_space, IGNORE_SPACE_ENUM);
238 #define VIEW_INFO(_) \
239 _(MAIN, main, ref_head), \
240 _(DIFF, diff, ref_commit), \
241 _(LOG, log, ref_head), \
242 _(TREE, tree, ref_commit), \
243 _(BLOB, blob, ref_blob), \
244 _(BLAME, blame, ref_commit), \
245 _(BRANCH, branch, ref_head), \
246 _(HELP, help, ""), \
247 _(PAGER, pager, ""), \
248 _(STATUS, status, "status"), \
249 _(STAGE, stage, "stage")
251 static struct encoding *
252 get_path_encoding(const char *path, struct encoding *default_encoding)
254 const char *check_attr_argv[] = {
255 "git", "check-attr", "encoding", "--", path, NULL
257 char buf[SIZEOF_STR];
258 char *encoding;
260 /* <path>: encoding: <encoding> */
262 if (!*path || !io_run_buf(check_attr_argv, buf, sizeof(buf))
263 || !(encoding = strstr(buf, ENCODING_SEP)))
264 return default_encoding;
266 encoding += STRING_SIZE(ENCODING_SEP);
267 if (!strcmp(encoding, ENCODING_UTF8)
268 || !strcmp(encoding, "unspecified")
269 || !strcmp(encoding, "set"))
270 return default_encoding;
272 return encoding_open(encoding);
276 * User requests
279 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
281 #define REQ_INFO \
282 REQ_GROUP("View switching") \
283 VIEW_INFO(VIEW_REQ), \
285 REQ_GROUP("View manipulation") \
286 REQ_(ENTER, "Enter current line and scroll"), \
287 REQ_(NEXT, "Move to next"), \
288 REQ_(PREVIOUS, "Move to previous"), \
289 REQ_(PARENT, "Move to parent"), \
290 REQ_(VIEW_NEXT, "Move focus to next view"), \
291 REQ_(REFRESH, "Reload and refresh"), \
292 REQ_(MAXIMIZE, "Maximize the current view"), \
293 REQ_(VIEW_CLOSE, "Close the current view"), \
294 REQ_(QUIT, "Close all views and quit"), \
296 REQ_GROUP("View specific requests") \
297 REQ_(STATUS_UPDATE, "Update file status"), \
298 REQ_(STATUS_REVERT, "Revert file changes"), \
299 REQ_(STATUS_MERGE, "Merge file using external tool"), \
300 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
301 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
302 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
303 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
305 REQ_GROUP("Cursor navigation") \
306 REQ_(MOVE_UP, "Move cursor one line up"), \
307 REQ_(MOVE_DOWN, "Move cursor one line down"), \
308 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
309 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
310 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
311 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
313 REQ_GROUP("Scrolling") \
314 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
315 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
316 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
317 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
318 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
319 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
320 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
322 REQ_GROUP("Searching") \
323 REQ_(SEARCH, "Search the view"), \
324 REQ_(SEARCH_BACK, "Search backwards in the view"), \
325 REQ_(FIND_NEXT, "Find next search match"), \
326 REQ_(FIND_PREV, "Find previous search match"), \
328 REQ_GROUP("Option manipulation") \
329 REQ_(OPTIONS, "Open option menu"), \
330 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
331 REQ_(TOGGLE_DATE, "Toggle date display"), \
332 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
333 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
334 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
335 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
336 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
337 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
338 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
339 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
341 REQ_GROUP("Misc") \
342 REQ_(PROMPT, "Bring up the prompt"), \
343 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
344 REQ_(SHOW_VERSION, "Show version information"), \
345 REQ_(STOP_LOADING, "Stop all loading views"), \
346 REQ_(EDIT, "Open in editor"), \
347 REQ_(NONE, "Do nothing")
350 /* User action requests. */
351 enum request {
352 #define REQ_GROUP(help)
353 #define REQ_(req, help) REQ_##req
355 /* Offset all requests to avoid conflicts with ncurses getch values. */
356 REQ_UNKNOWN = KEY_MAX + 1,
357 REQ_OFFSET,
358 REQ_INFO,
360 /* Internal requests. */
361 REQ_JUMP_COMMIT,
363 #undef REQ_GROUP
364 #undef REQ_
367 struct request_info {
368 enum request request;
369 const char *name;
370 int namelen;
371 const char *help;
374 static const struct request_info req_info[] = {
375 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
376 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
377 REQ_INFO
378 #undef REQ_GROUP
379 #undef REQ_
382 static enum request
383 get_request(const char *name)
385 int namelen = strlen(name);
386 int i;
388 for (i = 0; i < ARRAY_SIZE(req_info); i++)
389 if (enum_equals(req_info[i], name, namelen))
390 return req_info[i].request;
392 return REQ_UNKNOWN;
397 * Options
400 /* Option and state variables. */
401 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
402 static enum date opt_date = DATE_DEFAULT;
403 static enum author opt_author = AUTHOR_FULL;
404 static enum filename opt_filename = FILENAME_AUTO;
405 static bool opt_rev_graph = TRUE;
406 static bool opt_line_number = FALSE;
407 static bool opt_show_refs = TRUE;
408 static bool opt_untracked_dirs_content = TRUE;
409 static int opt_diff_context = 3;
410 static char opt_diff_context_arg[9] = "";
411 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
412 static char opt_ignore_space_arg[22] = "";
413 static char opt_notes_arg[SIZEOF_STR] = "--no-notes";
414 static int opt_num_interval = 5;
415 static double opt_hscroll = 0.50;
416 static double opt_scale_split_view = 2.0 / 3.0;
417 static int opt_tab_size = 8;
418 static int opt_author_cols = AUTHOR_COLS;
419 static int opt_filename_cols = FILENAME_COLS;
420 static char opt_path[SIZEOF_STR] = "";
421 static char opt_file[SIZEOF_STR] = "";
422 static char opt_ref[SIZEOF_REF] = "";
423 static unsigned long opt_goto_line = 0;
424 static char opt_head[SIZEOF_REF] = "";
425 static char opt_remote[SIZEOF_REF] = "";
426 static struct encoding *opt_encoding = NULL;
427 static iconv_t opt_iconv_out = ICONV_NONE;
428 static char opt_search[SIZEOF_STR] = "";
429 static char opt_cdup[SIZEOF_STR] = "";
430 static char opt_prefix[SIZEOF_STR] = "";
431 static char opt_git_dir[SIZEOF_STR] = "";
432 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
433 static char opt_editor[SIZEOF_STR] = "";
434 static FILE *opt_tty = NULL;
435 static const char **opt_diff_argv = NULL;
436 static const char **opt_rev_argv = NULL;
437 static const char **opt_file_argv = NULL;
438 static const char **opt_blame_argv = NULL;
439 static int opt_lineno = 0;
441 #define is_initial_commit() (!get_ref_head())
442 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
444 static inline void
445 update_diff_context_arg(int diff_context)
447 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
448 string_ncopy(opt_diff_context_arg, "-U3", 3);
451 static inline void
452 update_ignore_space_arg()
454 if (opt_ignore_space == IGNORE_SPACE_ALL) {
455 string_copy(opt_ignore_space_arg, "--ignore-all-space");
456 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
457 string_copy(opt_ignore_space_arg, "--ignore-space-change");
458 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
459 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
460 } else {
461 string_copy(opt_ignore_space_arg, "");
466 * Line-oriented content detection.
469 #define LINE_INFO \
470 LINE(DIFF_HEADER, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
471 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
472 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
473 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
474 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
475 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
476 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
477 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
478 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
479 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
480 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
481 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
482 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
483 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
484 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
485 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
486 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
487 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
488 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
489 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
490 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
491 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
492 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
493 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
494 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
495 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
496 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
497 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
498 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
499 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
500 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
501 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
502 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
503 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
504 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
505 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
506 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
507 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
508 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
509 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
510 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
511 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
512 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
513 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
514 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
515 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
516 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
517 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
518 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
519 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
520 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
521 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
522 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
523 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
524 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
525 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
526 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
527 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
528 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
529 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
530 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
531 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
532 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
533 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
534 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
535 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
536 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
537 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
538 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
539 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
540 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
541 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
543 enum line_type {
544 #define LINE(type, line, fg, bg, attr) \
545 LINE_##type
546 LINE_INFO,
547 LINE_NONE
548 #undef LINE
551 struct line_info {
552 const char *name; /* Option name. */
553 int namelen; /* Size of option name. */
554 const char *line; /* The start of line to match. */
555 int linelen; /* Size of string to match. */
556 int fg, bg, attr; /* Color and text attributes for the lines. */
559 static struct line_info line_info[] = {
560 #define LINE(type, line, fg, bg, attr) \
561 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
562 LINE_INFO
563 #undef LINE
566 static struct line_info *custom_color;
567 static size_t custom_colors;
569 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
571 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
572 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
574 /* Color IDs must be 1 or higher. [GH #15] */
575 #define COLOR_ID(line_type) ((line_type) + 1)
577 static enum line_type
578 get_line_type(const char *line)
580 int linelen = strlen(line);
581 enum line_type type;
583 for (type = 0; type < custom_colors; type++)
584 /* Case insensitive search matches Signed-off-by lines better. */
585 if (linelen >= custom_color[type].linelen &&
586 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
587 return TO_CUSTOM_COLOR_TYPE(type);
589 for (type = 0; type < ARRAY_SIZE(line_info); type++)
590 /* Case insensitive search matches Signed-off-by lines better. */
591 if (linelen >= line_info[type].linelen &&
592 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
593 return type;
595 return LINE_DEFAULT;
598 static enum line_type
599 get_line_type_from_ref(const struct ref *ref)
601 if (ref->head)
602 return LINE_MAIN_HEAD;
603 else if (ref->ltag)
604 return LINE_MAIN_LOCAL_TAG;
605 else if (ref->tag)
606 return LINE_MAIN_TAG;
607 else if (ref->tracked)
608 return LINE_MAIN_TRACKED;
609 else if (ref->remote)
610 return LINE_MAIN_REMOTE;
611 else if (ref->replace)
612 return LINE_MAIN_REPLACE;
614 return LINE_MAIN_REF;
617 static inline int
618 get_line_attr(enum line_type type)
620 if (type > LINE_NONE) {
621 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
622 return COLOR_PAIR(COLOR_ID(type)) | custom_color[TO_CUSTOM_COLOR_OFFSET(type)].attr;
624 assert(type < ARRAY_SIZE(line_info));
625 return COLOR_PAIR(COLOR_ID(type)) | line_info[type].attr;
628 static struct line_info *
629 get_line_info(const char *name)
631 size_t namelen = strlen(name);
632 enum line_type type;
634 for (type = 0; type < ARRAY_SIZE(line_info); type++)
635 if (enum_equals(line_info[type], name, namelen))
636 return &line_info[type];
638 return NULL;
641 static struct line_info *
642 add_custom_color(const char *quoted_line)
644 struct line_info *info;
645 char *line;
646 size_t linelen;
648 if (!realloc_custom_color(&custom_color, custom_colors, 1))
649 die("Failed to alloc custom line info");
651 linelen = strlen(quoted_line) - 1;
652 line = malloc(linelen);
653 if (!line)
654 return NULL;
656 strncpy(line, quoted_line + 1, linelen);
657 line[linelen - 1] = 0;
659 info = &custom_color[custom_colors++];
660 info->name = info->line = line;
661 info->namelen = info->linelen = strlen(line);
663 return info;
666 static void
667 init_line_info_color_pair(struct line_info *info, enum line_type type,
668 int default_bg, int default_fg)
670 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
671 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
673 init_pair(COLOR_ID(type), fg, bg);
676 static void
677 init_colors(void)
679 int default_bg = line_info[LINE_DEFAULT].bg;
680 int default_fg = line_info[LINE_DEFAULT].fg;
681 enum line_type type;
683 start_color();
685 if (assume_default_colors(default_fg, default_bg) == ERR) {
686 default_bg = COLOR_BLACK;
687 default_fg = COLOR_WHITE;
690 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
691 struct line_info *info = &line_info[type];
693 init_line_info_color_pair(info, type, default_bg, default_fg);
696 for (type = 0; type < custom_colors; type++) {
697 struct line_info *info = &custom_color[type];
699 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
700 default_bg, default_fg);
704 struct line {
705 enum line_type type;
707 /* State flags */
708 unsigned int selected:1;
709 unsigned int dirty:1;
710 unsigned int cleareol:1;
711 unsigned int other:16;
713 void *data; /* User data */
718 * Keys
721 struct keybinding {
722 int alias;
723 enum request request;
726 static struct keybinding default_keybindings[] = {
727 /* View switching */
728 { 'm', REQ_VIEW_MAIN },
729 { 'd', REQ_VIEW_DIFF },
730 { 'l', REQ_VIEW_LOG },
731 { 't', REQ_VIEW_TREE },
732 { 'f', REQ_VIEW_BLOB },
733 { 'B', REQ_VIEW_BLAME },
734 { 'H', REQ_VIEW_BRANCH },
735 { 'p', REQ_VIEW_PAGER },
736 { 'h', REQ_VIEW_HELP },
737 { 'S', REQ_VIEW_STATUS },
738 { 'c', REQ_VIEW_STAGE },
740 /* View manipulation */
741 { 'q', REQ_VIEW_CLOSE },
742 { KEY_TAB, REQ_VIEW_NEXT },
743 { KEY_RETURN, REQ_ENTER },
744 { KEY_UP, REQ_PREVIOUS },
745 { KEY_CTL('P'), REQ_PREVIOUS },
746 { KEY_DOWN, REQ_NEXT },
747 { KEY_CTL('N'), REQ_NEXT },
748 { 'R', REQ_REFRESH },
749 { KEY_F(5), REQ_REFRESH },
750 { 'O', REQ_MAXIMIZE },
751 { ',', REQ_PARENT },
753 /* View specific */
754 { 'u', REQ_STATUS_UPDATE },
755 { '!', REQ_STATUS_REVERT },
756 { 'M', REQ_STATUS_MERGE },
757 { '1', REQ_STAGE_UPDATE_LINE },
758 { '@', REQ_STAGE_NEXT },
759 { '[', REQ_DIFF_CONTEXT_DOWN },
760 { ']', REQ_DIFF_CONTEXT_UP },
762 /* Cursor navigation */
763 { 'k', REQ_MOVE_UP },
764 { 'j', REQ_MOVE_DOWN },
765 { KEY_HOME, REQ_MOVE_FIRST_LINE },
766 { KEY_END, REQ_MOVE_LAST_LINE },
767 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
768 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
769 { ' ', REQ_MOVE_PAGE_DOWN },
770 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
771 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
772 { 'b', REQ_MOVE_PAGE_UP },
773 { '-', REQ_MOVE_PAGE_UP },
775 /* Scrolling */
776 { '|', REQ_SCROLL_FIRST_COL },
777 { KEY_LEFT, REQ_SCROLL_LEFT },
778 { KEY_RIGHT, REQ_SCROLL_RIGHT },
779 { KEY_IC, REQ_SCROLL_LINE_UP },
780 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
781 { KEY_DC, REQ_SCROLL_LINE_DOWN },
782 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
783 { 'w', REQ_SCROLL_PAGE_UP },
784 { 's', REQ_SCROLL_PAGE_DOWN },
786 /* Searching */
787 { '/', REQ_SEARCH },
788 { '?', REQ_SEARCH_BACK },
789 { 'n', REQ_FIND_NEXT },
790 { 'N', REQ_FIND_PREV },
792 /* Misc */
793 { 'Q', REQ_QUIT },
794 { 'z', REQ_STOP_LOADING },
795 { 'v', REQ_SHOW_VERSION },
796 { 'r', REQ_SCREEN_REDRAW },
797 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
798 { 'o', REQ_OPTIONS },
799 { '.', REQ_TOGGLE_LINENO },
800 { 'D', REQ_TOGGLE_DATE },
801 { 'A', REQ_TOGGLE_AUTHOR },
802 { 'g', REQ_TOGGLE_REV_GRAPH },
803 { '~', REQ_TOGGLE_GRAPHIC },
804 { '#', REQ_TOGGLE_FILENAME },
805 { 'F', REQ_TOGGLE_REFS },
806 { 'I', REQ_TOGGLE_SORT_ORDER },
807 { 'i', REQ_TOGGLE_SORT_FIELD },
808 { 'W', REQ_TOGGLE_IGNORE_SPACE },
809 { ':', REQ_PROMPT },
810 { 'e', REQ_EDIT },
813 #define KEYMAP_ENUM(_) \
814 _(KEYMAP, GENERIC), \
815 _(KEYMAP, MAIN), \
816 _(KEYMAP, DIFF), \
817 _(KEYMAP, LOG), \
818 _(KEYMAP, TREE), \
819 _(KEYMAP, BLOB), \
820 _(KEYMAP, BLAME), \
821 _(KEYMAP, BRANCH), \
822 _(KEYMAP, PAGER), \
823 _(KEYMAP, HELP), \
824 _(KEYMAP, STATUS), \
825 _(KEYMAP, STAGE)
827 DEFINE_ENUM(keymap, KEYMAP_ENUM);
829 #define set_keymap(map, name) map_enum(map, keymap_map, name)
831 struct keybinding_table {
832 struct keybinding *data;
833 size_t size;
836 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_map)];
838 static void
839 add_keybinding(enum keymap keymap, enum request request, int key)
841 struct keybinding_table *table = &keybindings[keymap];
842 size_t i;
844 for (i = 0; i < table->size; i++) {
845 if (table->data[i].alias == key) {
846 table->data[i].request = request;
847 return;
851 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
852 if (!table->data)
853 die("Failed to allocate keybinding");
854 table->data[table->size].alias = key;
855 table->data[table->size++].request = request;
857 if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
858 int i;
860 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
861 if (default_keybindings[i].alias == key)
862 default_keybindings[i].request = REQ_NONE;
866 /* Looks for a key binding first in the given map, then in the generic map, and
867 * lastly in the default keybindings. */
868 static enum request
869 get_keybinding(enum keymap keymap, int key)
871 size_t i;
873 for (i = 0; i < keybindings[keymap].size; i++)
874 if (keybindings[keymap].data[i].alias == key)
875 return keybindings[keymap].data[i].request;
877 for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
878 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
879 return keybindings[KEYMAP_GENERIC].data[i].request;
881 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
882 if (default_keybindings[i].alias == key)
883 return default_keybindings[i].request;
885 return (enum request) key;
889 struct key {
890 const char *name;
891 int value;
894 static const struct key key_table[] = {
895 { "Enter", KEY_RETURN },
896 { "Space", ' ' },
897 { "Backspace", KEY_BACKSPACE },
898 { "Tab", KEY_TAB },
899 { "Escape", KEY_ESC },
900 { "Left", KEY_LEFT },
901 { "Right", KEY_RIGHT },
902 { "Up", KEY_UP },
903 { "Down", KEY_DOWN },
904 { "Insert", KEY_IC },
905 { "Delete", KEY_DC },
906 { "Hash", '#' },
907 { "Home", KEY_HOME },
908 { "End", KEY_END },
909 { "PageUp", KEY_PPAGE },
910 { "PageDown", KEY_NPAGE },
911 { "F1", KEY_F(1) },
912 { "F2", KEY_F(2) },
913 { "F3", KEY_F(3) },
914 { "F4", KEY_F(4) },
915 { "F5", KEY_F(5) },
916 { "F6", KEY_F(6) },
917 { "F7", KEY_F(7) },
918 { "F8", KEY_F(8) },
919 { "F9", KEY_F(9) },
920 { "F10", KEY_F(10) },
921 { "F11", KEY_F(11) },
922 { "F12", KEY_F(12) },
925 static int
926 get_key_value(const char *name)
928 int i;
930 for (i = 0; i < ARRAY_SIZE(key_table); i++)
931 if (!strcasecmp(key_table[i].name, name))
932 return key_table[i].value;
934 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
935 return (int)name[1] & 0x1f;
936 if (strlen(name) == 1 && isprint(*name))
937 return (int) *name;
938 return ERR;
941 static const char *
942 get_key_name(int key_value)
944 static char key_char[] = "'X'\0";
945 const char *seq = NULL;
946 int key;
948 for (key = 0; key < ARRAY_SIZE(key_table); key++)
949 if (key_table[key].value == key_value)
950 seq = key_table[key].name;
952 if (seq == NULL && key_value < 0x7f) {
953 char *s = key_char + 1;
955 if (key_value >= 0x20) {
956 *s++ = key_value;
957 } else {
958 *s++ = '^';
959 *s++ = 0x40 | (key_value & 0x1f);
961 *s++ = '\'';
962 *s++ = '\0';
963 seq = key_char;
966 return seq ? seq : "(no key)";
969 static bool
970 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
972 const char *sep = *pos > 0 ? ", " : "";
973 const char *keyname = get_key_name(keybinding->alias);
975 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
978 static bool
979 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
980 enum keymap keymap, bool all)
982 int i;
984 for (i = 0; i < keybindings[keymap].size; i++) {
985 if (keybindings[keymap].data[i].request == request) {
986 if (!append_key(buf, pos, &keybindings[keymap].data[i]))
987 return FALSE;
988 if (!all)
989 break;
993 return TRUE;
996 #define get_view_key(view, request) get_keys((view)->keymap, request, FALSE)
998 static const char *
999 get_keys(enum keymap keymap, enum request request, bool all)
1001 static char buf[BUFSIZ];
1002 size_t pos = 0;
1003 int i;
1005 buf[pos] = 0;
1007 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1008 return "Too many keybindings!";
1009 if (pos > 0 && !all)
1010 return buf;
1012 if (keymap != KEYMAP_GENERIC) {
1013 /* Only the generic keymap includes the default keybindings when
1014 * listing all keys. */
1015 if (all)
1016 return buf;
1018 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
1019 return "Too many keybindings!";
1020 if (pos)
1021 return buf;
1024 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1025 if (default_keybindings[i].request == request) {
1026 if (!append_key(buf, &pos, &default_keybindings[i]))
1027 return "Too many keybindings!";
1028 if (!all)
1029 return buf;
1033 return buf;
1036 struct run_request {
1037 enum keymap keymap;
1038 int key;
1039 const char **argv;
1042 static struct run_request *run_request;
1043 static size_t run_requests;
1045 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1047 static enum request
1048 add_run_request(enum keymap keymap, int key, const char **argv)
1050 struct run_request *req;
1052 if (!realloc_run_requests(&run_request, run_requests, 1))
1053 return REQ_NONE;
1055 req = &run_request[run_requests];
1056 req->keymap = keymap;
1057 req->key = key;
1058 req->argv = NULL;
1060 if (!argv_copy(&req->argv, argv))
1061 return REQ_NONE;
1063 return REQ_NONE + ++run_requests;
1066 static struct run_request *
1067 get_run_request(enum request request)
1069 if (request <= REQ_NONE)
1070 return NULL;
1071 return &run_request[request - REQ_NONE - 1];
1074 static void
1075 add_builtin_run_requests(void)
1077 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1078 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1079 const char *commit[] = { "git", "commit", NULL };
1080 const char *gc[] = { "git", "gc", NULL };
1081 struct run_request reqs[] = {
1082 { KEYMAP_MAIN, 'C', cherry_pick },
1083 { KEYMAP_STATUS, 'C', commit },
1084 { KEYMAP_BRANCH, 'C', checkout },
1085 { KEYMAP_GENERIC, 'G', gc },
1087 int i;
1089 for (i = 0; i < ARRAY_SIZE(reqs); i++) {
1090 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
1092 if (req != reqs[i].key)
1093 continue;
1094 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
1095 if (req != REQ_NONE)
1096 add_keybinding(reqs[i].keymap, req, reqs[i].key);
1101 * User config file handling.
1104 #define OPT_ERR_INFO \
1105 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1106 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1107 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1108 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1109 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1110 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1111 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1112 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1113 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1114 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1115 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1116 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1117 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1118 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1119 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1120 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1121 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1122 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1124 enum option_code {
1125 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1126 OPT_ERR_INFO
1127 #undef OPT_ERR_
1128 OPT_OK
1131 static const char *option_errors[] = {
1132 #define OPT_ERR_(name, msg) msg
1133 OPT_ERR_INFO
1134 #undef OPT_ERR_
1137 static const struct enum_map color_map[] = {
1138 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1139 COLOR_MAP(DEFAULT),
1140 COLOR_MAP(BLACK),
1141 COLOR_MAP(BLUE),
1142 COLOR_MAP(CYAN),
1143 COLOR_MAP(GREEN),
1144 COLOR_MAP(MAGENTA),
1145 COLOR_MAP(RED),
1146 COLOR_MAP(WHITE),
1147 COLOR_MAP(YELLOW),
1150 static const struct enum_map attr_map[] = {
1151 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1152 ATTR_MAP(NORMAL),
1153 ATTR_MAP(BLINK),
1154 ATTR_MAP(BOLD),
1155 ATTR_MAP(DIM),
1156 ATTR_MAP(REVERSE),
1157 ATTR_MAP(STANDOUT),
1158 ATTR_MAP(UNDERLINE),
1161 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1163 static enum option_code
1164 parse_step(double *opt, const char *arg)
1166 *opt = atoi(arg);
1167 if (!strchr(arg, '%'))
1168 return OPT_OK;
1170 /* "Shift down" so 100% and 1 does not conflict. */
1171 *opt = (*opt - 1) / 100;
1172 if (*opt >= 1.0) {
1173 *opt = 0.99;
1174 return OPT_ERR_INVALID_STEP_VALUE;
1176 if (*opt < 0.0) {
1177 *opt = 1;
1178 return OPT_ERR_INVALID_STEP_VALUE;
1180 return OPT_OK;
1183 static enum option_code
1184 parse_int(int *opt, const char *arg, int min, int max)
1186 int value = atoi(arg);
1188 if (min <= value && value <= max) {
1189 *opt = value;
1190 return OPT_OK;
1193 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1196 static bool
1197 set_color(int *color, const char *name)
1199 if (map_enum(color, color_map, name))
1200 return TRUE;
1201 if (!prefixcmp(name, "color"))
1202 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1203 return FALSE;
1206 /* Wants: object fgcolor bgcolor [attribute] */
1207 static enum option_code
1208 option_color_command(int argc, const char *argv[])
1210 struct line_info *info;
1212 if (argc < 3)
1213 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1215 if (*argv[0] == '"' || *argv[0] == '\'') {
1216 info = add_custom_color(argv[0]);
1217 } else {
1218 info = get_line_info(argv[0]);
1220 if (!info) {
1221 static const struct enum_map obsolete[] = {
1222 ENUM_MAP("main-delim", LINE_DELIMITER),
1223 ENUM_MAP("main-date", LINE_DATE),
1224 ENUM_MAP("main-author", LINE_AUTHOR),
1226 int index;
1228 if (!map_enum(&index, obsolete, argv[0]))
1229 return OPT_ERR_UNKNOWN_COLOR_NAME;
1230 info = &line_info[index];
1233 if (!set_color(&info->fg, argv[1]) ||
1234 !set_color(&info->bg, argv[2]))
1235 return OPT_ERR_UNKNOWN_COLOR;
1237 info->attr = 0;
1238 while (argc-- > 3) {
1239 int attr;
1241 if (!set_attribute(&attr, argv[argc]))
1242 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1243 info->attr |= attr;
1246 return OPT_OK;
1249 static enum option_code
1250 parse_bool(bool *opt, const char *arg)
1252 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1253 ? TRUE : FALSE;
1254 return OPT_OK;
1257 static enum option_code
1258 parse_enum_do(unsigned int *opt, const char *arg,
1259 const struct enum_map *map, size_t map_size)
1261 bool is_true;
1263 assert(map_size > 1);
1265 if (map_enum_do(map, map_size, (int *) opt, arg))
1266 return OPT_OK;
1268 parse_bool(&is_true, arg);
1269 *opt = is_true ? map[1].value : map[0].value;
1270 return OPT_OK;
1273 #define parse_enum(opt, arg, map) \
1274 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1276 static enum option_code
1277 parse_string(char *opt, const char *arg, size_t optsize)
1279 int arglen = strlen(arg);
1281 switch (arg[0]) {
1282 case '\"':
1283 case '\'':
1284 if (arglen == 1 || arg[arglen - 1] != arg[0])
1285 return OPT_ERR_UNMATCHED_QUOTATION;
1286 arg += 1; arglen -= 2;
1287 default:
1288 string_ncopy_do(opt, optsize, arg, arglen);
1289 return OPT_OK;
1293 static enum option_code
1294 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1296 char buf[SIZEOF_STR];
1297 enum option_code code = parse_string(buf, arg, sizeof(buf));
1299 if (code == OPT_OK) {
1300 struct encoding *encoding = *encoding_ref;
1302 if (encoding && !priority)
1303 return code;
1304 encoding = encoding_open(buf);
1305 if (encoding)
1306 *encoding_ref = encoding;
1309 return code;
1312 static enum option_code
1313 parse_args(const char ***args, const char *argv[])
1315 if (*args == NULL && !argv_copy(args, argv))
1316 return OPT_ERR_OUT_OF_MEMORY;
1317 return OPT_OK;
1320 /* Wants: name = value */
1321 static enum option_code
1322 option_set_command(int argc, const char *argv[])
1324 if (argc < 3)
1325 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1327 if (strcmp(argv[1], "="))
1328 return OPT_ERR_NO_VALUE_ASSIGNED;
1330 if (!strcmp(argv[0], "blame-options"))
1331 return parse_args(&opt_blame_argv, argv + 2);
1333 if (argc != 3)
1334 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1336 if (!strcmp(argv[0], "show-author"))
1337 return parse_enum(&opt_author, argv[2], author_map);
1339 if (!strcmp(argv[0], "show-date"))
1340 return parse_enum(&opt_date, argv[2], date_map);
1342 if (!strcmp(argv[0], "show-rev-graph"))
1343 return parse_bool(&opt_rev_graph, argv[2]);
1345 if (!strcmp(argv[0], "show-refs"))
1346 return parse_bool(&opt_show_refs, argv[2]);
1348 if (!strcmp(argv[0], "show-notes")) {
1349 int res;
1351 strcpy(opt_notes_arg, "--notes=");
1352 res = parse_string(opt_notes_arg + 8, argv[2],
1353 sizeof(opt_notes_arg) - 8);
1354 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1355 opt_notes_arg[7] = '\0';
1356 return res;
1359 if (!strcmp(argv[0], "show-line-numbers"))
1360 return parse_bool(&opt_line_number, argv[2]);
1362 if (!strcmp(argv[0], "line-graphics"))
1363 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1365 if (!strcmp(argv[0], "line-number-interval"))
1366 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1368 if (!strcmp(argv[0], "author-width"))
1369 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1371 if (!strcmp(argv[0], "filename-width"))
1372 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1374 if (!strcmp(argv[0], "show-filename"))
1375 return parse_enum(&opt_filename, argv[2], filename_map);
1377 if (!strcmp(argv[0], "horizontal-scroll"))
1378 return parse_step(&opt_hscroll, argv[2]);
1380 if (!strcmp(argv[0], "split-view-height"))
1381 return parse_step(&opt_scale_split_view, argv[2]);
1383 if (!strcmp(argv[0], "tab-size"))
1384 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1386 if (!strcmp(argv[0], "diff-context")) {
1387 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1389 if (code == OPT_OK)
1390 update_diff_context_arg(opt_diff_context);
1391 return code;
1394 if (!strcmp(argv[0], "ignore-space")) {
1395 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1397 if (code == OPT_OK)
1398 update_ignore_space_arg();
1399 return code;
1402 if (!strcmp(argv[0], "commit-encoding"))
1403 return parse_encoding(&opt_encoding, argv[2], FALSE);
1405 if (!strcmp(argv[0], "status-untracked-dirs"))
1406 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1408 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1411 /* Wants: mode request key */
1412 static enum option_code
1413 option_bind_command(int argc, const char *argv[])
1415 enum request request;
1416 int keymap = -1;
1417 int key;
1419 if (argc < 3)
1420 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1422 if (!set_keymap(&keymap, argv[0]))
1423 return OPT_ERR_UNKNOWN_KEY_MAP;
1425 key = get_key_value(argv[1]);
1426 if (key == ERR)
1427 return OPT_ERR_UNKNOWN_KEY;
1429 request = get_request(argv[2]);
1430 if (request == REQ_UNKNOWN) {
1431 static const struct enum_map obsolete[] = {
1432 ENUM_MAP("cherry-pick", REQ_NONE),
1433 ENUM_MAP("screen-resize", REQ_NONE),
1434 ENUM_MAP("tree-parent", REQ_PARENT),
1436 int alias;
1438 if (map_enum(&alias, obsolete, argv[2])) {
1439 if (alias != REQ_NONE)
1440 add_keybinding(keymap, alias, key);
1441 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1444 if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1445 request = add_run_request(keymap, key, argv + 2);
1446 if (request == REQ_UNKNOWN)
1447 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1449 add_keybinding(keymap, request, key);
1451 return OPT_OK;
1455 static enum option_code load_option_file(const char *path);
1457 static enum option_code
1458 option_source_command(int argc, const char *argv[])
1460 if (argc < 1)
1461 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1463 return load_option_file(argv[0]);
1466 static enum option_code
1467 set_option(const char *opt, char *value)
1469 const char *argv[SIZEOF_ARG];
1470 int argc = 0;
1472 if (!argv_from_string(argv, &argc, value))
1473 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1475 if (!strcmp(opt, "color"))
1476 return option_color_command(argc, argv);
1478 if (!strcmp(opt, "set"))
1479 return option_set_command(argc, argv);
1481 if (!strcmp(opt, "bind"))
1482 return option_bind_command(argc, argv);
1484 if (!strcmp(opt, "source"))
1485 return option_source_command(argc, argv);
1487 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1490 struct config_state {
1491 const char *path;
1492 int lineno;
1493 bool errors;
1496 static int
1497 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1499 struct config_state *config = data;
1500 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1502 config->lineno++;
1504 /* Check for comment markers, since read_properties() will
1505 * only ensure opt and value are split at first " \t". */
1506 optlen = strcspn(opt, "#");
1507 if (optlen == 0)
1508 return OK;
1510 if (opt[optlen] == 0) {
1511 /* Look for comment endings in the value. */
1512 size_t len = strcspn(value, "#");
1514 if (len < valuelen) {
1515 valuelen = len;
1516 value[valuelen] = 0;
1519 status = set_option(opt, value);
1522 if (status != OPT_OK) {
1523 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1524 option_errors[status], (int) optlen, opt);
1525 config->errors = TRUE;
1528 /* Always keep going if errors are encountered. */
1529 return OK;
1532 static enum option_code
1533 load_option_file(const char *path)
1535 struct config_state config = { path, 0, FALSE };
1536 struct io io;
1538 /* Do not read configuration from stdin if set to "" */
1539 if (!path || !strlen(path))
1540 return OPT_OK;
1542 /* It's OK that the file doesn't exist. */
1543 if (!io_open(&io, "%s", path))
1544 return OPT_ERR_FILE_DOES_NOT_EXIST;
1546 if (io_load(&io, " \t", read_option, &config) == ERR ||
1547 config.errors == TRUE)
1548 warn("Errors while loading %s.", path);
1549 return OPT_OK;
1552 static int
1553 load_options(void)
1555 const char *home = getenv("HOME");
1556 const char *tigrc_user = getenv("TIGRC_USER");
1557 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1558 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1559 char buf[SIZEOF_STR];
1561 if (!tigrc_system)
1562 tigrc_system = SYSCONFDIR "/tigrc";
1563 load_option_file(tigrc_system);
1565 if (!tigrc_user) {
1566 if (!home || !string_format(buf, "%s/.tigrc", home))
1567 return ERR;
1568 tigrc_user = buf;
1570 load_option_file(tigrc_user);
1572 /* Add _after_ loading config files to avoid adding run requests
1573 * that conflict with keybindings. */
1574 add_builtin_run_requests();
1576 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1577 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1578 int argc = 0;
1580 if (!string_format(buf, "%s", tig_diff_opts) ||
1581 !argv_from_string(diff_opts, &argc, buf))
1582 die("TIG_DIFF_OPTS contains too many arguments");
1583 else if (!argv_copy(&opt_diff_argv, diff_opts))
1584 die("Failed to format TIG_DIFF_OPTS arguments");
1587 return OK;
1592 * The viewer
1595 struct view;
1596 struct view_ops;
1598 /* The display array of active views and the index of the current view. */
1599 static struct view *display[2];
1600 static WINDOW *display_win[2];
1601 static WINDOW *display_title[2];
1602 static unsigned int current_view;
1604 #define foreach_displayed_view(view, i) \
1605 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1607 #define displayed_views() (display[1] != NULL ? 2 : 1)
1609 /* Current head and commit ID */
1610 static char ref_blob[SIZEOF_REF] = "";
1611 static char ref_commit[SIZEOF_REF] = "HEAD";
1612 static char ref_head[SIZEOF_REF] = "HEAD";
1613 static char ref_branch[SIZEOF_REF] = "";
1615 enum view_flag {
1616 VIEW_NO_FLAGS = 0,
1617 VIEW_ALWAYS_LINENO = 1 << 0,
1618 VIEW_CUSTOM_STATUS = 1 << 1,
1619 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1620 VIEW_ADD_PAGER_REFS = 1 << 3,
1621 VIEW_OPEN_DIFF = 1 << 4,
1622 VIEW_NO_REF = 1 << 5,
1623 VIEW_NO_GIT_DIR = 1 << 6,
1626 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1628 struct view {
1629 const char *name; /* View name */
1630 const char *id; /* Points to either of ref_{head,commit,blob} */
1632 struct view_ops *ops; /* View operations */
1634 enum keymap keymap; /* What keymap does this view have */
1636 char ref[SIZEOF_REF]; /* Hovered commit reference */
1637 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1639 int height, width; /* The width and height of the main window */
1640 WINDOW *win; /* The main window */
1642 /* Navigation */
1643 unsigned long offset; /* Offset of the window top */
1644 unsigned long yoffset; /* Offset from the window side. */
1645 unsigned long lineno; /* Current line number */
1646 unsigned long p_offset; /* Previous offset of the window top */
1647 unsigned long p_yoffset;/* Previous offset from the window side */
1648 unsigned long p_lineno; /* Previous current line number */
1649 bool p_restore; /* Should the previous position be restored. */
1651 /* Searching */
1652 char grep[SIZEOF_STR]; /* Search string */
1653 regex_t *regex; /* Pre-compiled regexp */
1655 /* If non-NULL, points to the view that opened this view. If this view
1656 * is closed tig will switch back to the parent view. */
1657 struct view *parent;
1658 struct view *prev;
1660 /* Buffering */
1661 size_t lines; /* Total number of lines */
1662 struct line *line; /* Line index */
1663 unsigned int digits; /* Number of digits in the lines member. */
1665 /* Drawing */
1666 struct line *curline; /* Line currently being drawn. */
1667 enum line_type curtype; /* Attribute currently used for drawing. */
1668 unsigned long col; /* Column when drawing. */
1669 bool has_scrolled; /* View was scrolled. */
1671 /* Loading */
1672 const char **argv; /* Shell command arguments. */
1673 const char *dir; /* Directory from which to execute. */
1674 struct io io;
1675 struct io *pipe;
1676 time_t start_time;
1677 time_t update_secs;
1678 struct encoding *encoding;
1680 /* Private data */
1681 void *private;
1684 enum open_flags {
1685 OPEN_DEFAULT = 0, /* Use default view switching. */
1686 OPEN_SPLIT = 1, /* Split current view. */
1687 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1688 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1689 OPEN_PREPARED = 32, /* Open already prepared command. */
1690 OPEN_EXTRA = 64, /* Open extra data from command. */
1693 struct view_ops {
1694 /* What type of content being displayed. Used in the title bar. */
1695 const char *type;
1696 /* Flags to control the view behavior. */
1697 enum view_flag flags;
1698 /* Size of private data. */
1699 size_t private_size;
1700 /* Open and reads in all view content. */
1701 bool (*open)(struct view *view, enum open_flags flags);
1702 /* Read one line; updates view->line. */
1703 bool (*read)(struct view *view, char *data);
1704 /* Draw one line; @lineno must be < view->height. */
1705 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1706 /* Depending on view handle a special requests. */
1707 enum request (*request)(struct view *view, enum request request, struct line *line);
1708 /* Search for regexp in a line. */
1709 bool (*grep)(struct view *view, struct line *line);
1710 /* Select line */
1711 void (*select)(struct view *view, struct line *line);
1714 #define VIEW_OPS(id, name, ref) name##_ops
1715 static struct view_ops VIEW_INFO(VIEW_OPS);
1717 static struct view views[] = {
1718 #define VIEW_DATA(id, name, ref) \
1719 { #name, ref, &name##_ops, KEYMAP_##id }
1720 VIEW_INFO(VIEW_DATA)
1723 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1725 #define foreach_view(view, i) \
1726 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1728 #define view_is_displayed(view) \
1729 (view == display[0] || view == display[1])
1731 static enum request
1732 view_request(struct view *view, enum request request)
1734 if (!view || !view->lines)
1735 return request;
1736 return view->ops->request(view, request, &view->line[view->lineno]);
1741 * View drawing.
1744 static inline void
1745 set_view_attr(struct view *view, enum line_type type)
1747 if (!view->curline->selected && view->curtype != type) {
1748 (void) wattrset(view->win, get_line_attr(type));
1749 wchgat(view->win, -1, 0, COLOR_ID(type), NULL);
1750 view->curtype = type;
1754 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1756 static bool
1757 draw_chars(struct view *view, enum line_type type, const char *string,
1758 int max_len, bool use_tilde)
1760 static char out_buffer[BUFSIZ * 2];
1761 int len = 0;
1762 int col = 0;
1763 int trimmed = FALSE;
1764 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1766 if (max_len <= 0)
1767 return VIEW_MAX_LEN(view) <= 0;
1769 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1771 set_view_attr(view, type);
1772 if (len > 0) {
1773 if (opt_iconv_out != ICONV_NONE) {
1774 size_t inlen = len + 1;
1775 char *instr = calloc(1, inlen);
1776 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1777 if (!instr)
1778 return VIEW_MAX_LEN(view) <= 0;
1780 strncpy(instr, string, len);
1782 char *outbuf = out_buffer;
1783 size_t outlen = sizeof(out_buffer);
1785 size_t ret;
1787 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1788 if (ret != (size_t) -1) {
1789 string = out_buffer;
1790 len = sizeof(out_buffer) - outlen;
1792 free(instr);
1795 waddnstr(view->win, string, len);
1797 if (trimmed && use_tilde) {
1798 set_view_attr(view, LINE_DELIMITER);
1799 waddch(view->win, '~');
1800 col++;
1804 view->col += col;
1805 return VIEW_MAX_LEN(view) <= 0;
1808 static bool
1809 draw_space(struct view *view, enum line_type type, int max, int spaces)
1811 static char space[] = " ";
1813 spaces = MIN(max, spaces);
1815 while (spaces > 0) {
1816 int len = MIN(spaces, sizeof(space) - 1);
1818 if (draw_chars(view, type, space, len, FALSE))
1819 return TRUE;
1820 spaces -= len;
1823 return VIEW_MAX_LEN(view) <= 0;
1826 static bool
1827 draw_text(struct view *view, enum line_type type, const char *string)
1829 char text[SIZEOF_STR];
1831 do {
1832 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1834 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1835 return TRUE;
1836 string += pos;
1837 } while (*string);
1839 return VIEW_MAX_LEN(view) <= 0;
1842 static bool
1843 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
1845 char text[SIZEOF_STR];
1846 int retval;
1848 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
1849 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
1852 static bool
1853 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1855 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1856 int max = VIEW_MAX_LEN(view);
1857 int i;
1859 if (max < size)
1860 size = max;
1862 set_view_attr(view, type);
1863 /* Using waddch() instead of waddnstr() ensures that
1864 * they'll be rendered correctly for the cursor line. */
1865 for (i = skip; i < size; i++)
1866 waddch(view->win, graphic[i]);
1868 view->col += size;
1869 if (separator) {
1870 if (size < max && skip <= size)
1871 waddch(view->win, ' ');
1872 view->col++;
1875 return VIEW_MAX_LEN(view) <= 0;
1878 static bool
1879 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1881 int max = MIN(VIEW_MAX_LEN(view), len);
1882 int col = view->col;
1884 if (!text)
1885 return draw_space(view, type, max, max);
1887 return draw_chars(view, type, text, max - 1, trim)
1888 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1891 static bool
1892 draw_date(struct view *view, struct time *time)
1894 const char *date = mkdate(time, opt_date);
1895 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1897 if (opt_date == DATE_NO)
1898 return FALSE;
1900 return draw_field(view, LINE_DATE, date, cols, FALSE);
1903 static bool
1904 draw_author(struct view *view, const char *author)
1906 bool trim = author_trim(opt_author_cols);
1907 const char *text = mkauthor(author, opt_author_cols, opt_author);
1909 if (opt_author == AUTHOR_NO)
1910 return FALSE;
1912 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1915 static bool
1916 draw_filename(struct view *view, const char *filename, bool auto_enabled)
1918 bool trim = filename && strlen(filename) >= opt_filename_cols;
1920 if (opt_filename == FILENAME_NO)
1921 return FALSE;
1923 if (opt_filename == FILENAME_AUTO && !auto_enabled)
1924 return FALSE;
1926 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
1929 static bool
1930 draw_mode(struct view *view, mode_t mode)
1932 const char *str = mkmode(mode);
1934 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1937 static bool
1938 draw_lineno(struct view *view, unsigned int lineno)
1940 char number[10];
1941 int digits3 = view->digits < 3 ? 3 : view->digits;
1942 int max = MIN(VIEW_MAX_LEN(view), digits3);
1943 char *text = NULL;
1944 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1946 lineno += view->offset + 1;
1947 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1948 static char fmt[] = "%1ld";
1950 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1951 if (string_format(number, fmt, lineno))
1952 text = number;
1954 if (text)
1955 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1956 else
1957 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1958 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1961 static bool
1962 draw_refs(struct view *view, struct ref_list *refs)
1964 size_t i;
1966 if (!opt_show_refs || !refs)
1967 return FALSE;
1969 for (i = 0; i < refs->size; i++) {
1970 struct ref *ref = refs->refs[i];
1971 enum line_type type = get_line_type_from_ref(ref);
1973 if (draw_formatted(view, type, "[%s]", ref->name))
1974 return TRUE;
1976 if (draw_text(view, LINE_DEFAULT, " "))
1977 return TRUE;
1980 return FALSE;
1983 static bool
1984 draw_view_line(struct view *view, unsigned int lineno)
1986 struct line *line;
1987 bool selected = (view->offset + lineno == view->lineno);
1989 assert(view_is_displayed(view));
1991 if (view->offset + lineno >= view->lines)
1992 return FALSE;
1994 line = &view->line[view->offset + lineno];
1996 wmove(view->win, lineno, 0);
1997 if (line->cleareol)
1998 wclrtoeol(view->win);
1999 view->col = 0;
2000 view->curline = line;
2001 view->curtype = LINE_NONE;
2002 line->selected = FALSE;
2003 line->dirty = line->cleareol = 0;
2005 if (selected) {
2006 set_view_attr(view, LINE_CURSOR);
2007 line->selected = TRUE;
2008 view->ops->select(view, line);
2011 return view->ops->draw(view, line, lineno);
2014 static void
2015 redraw_view_dirty(struct view *view)
2017 bool dirty = FALSE;
2018 int lineno;
2020 for (lineno = 0; lineno < view->height; lineno++) {
2021 if (view->offset + lineno >= view->lines)
2022 break;
2023 if (!view->line[view->offset + lineno].dirty)
2024 continue;
2025 dirty = TRUE;
2026 if (!draw_view_line(view, lineno))
2027 break;
2030 if (!dirty)
2031 return;
2032 wnoutrefresh(view->win);
2035 static void
2036 redraw_view_from(struct view *view, int lineno)
2038 assert(0 <= lineno && lineno < view->height);
2040 for (; lineno < view->height; lineno++) {
2041 if (!draw_view_line(view, lineno))
2042 break;
2045 wnoutrefresh(view->win);
2048 static void
2049 redraw_view(struct view *view)
2051 werase(view->win);
2052 redraw_view_from(view, 0);
2056 static void
2057 update_view_title(struct view *view)
2059 char buf[SIZEOF_STR];
2060 char state[SIZEOF_STR];
2061 size_t bufpos = 0, statelen = 0;
2062 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2064 assert(view_is_displayed(view));
2066 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view->lines) {
2067 unsigned int view_lines = view->offset + view->height;
2068 unsigned int lines = view->lines
2069 ? MIN(view_lines, view->lines) * 100 / view->lines
2070 : 0;
2072 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
2073 view->ops->type,
2074 view->lineno + 1,
2075 view->lines,
2076 lines);
2080 if (view->pipe) {
2081 time_t secs = time(NULL) - view->start_time;
2083 /* Three git seconds are a long time ... */
2084 if (secs > 2)
2085 string_format_from(state, &statelen, " loading %lds", secs);
2088 string_format_from(buf, &bufpos, "[%s]", view->name);
2089 if (*view->ref && bufpos < view->width) {
2090 size_t refsize = strlen(view->ref);
2091 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2093 if (minsize < view->width)
2094 refsize = view->width - minsize + 7;
2095 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2098 if (statelen && bufpos < view->width) {
2099 string_format_from(buf, &bufpos, "%s", state);
2102 if (view == display[current_view])
2103 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2104 else
2105 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2107 mvwaddnstr(window, 0, 0, buf, bufpos);
2108 wclrtoeol(window);
2109 wnoutrefresh(window);
2112 static int
2113 apply_step(double step, int value)
2115 if (step >= 1)
2116 return (int) step;
2117 value *= step + 0.01;
2118 return value ? value : 1;
2121 static void
2122 resize_display(void)
2124 int offset, i;
2125 struct view *base = display[0];
2126 struct view *view = display[1] ? display[1] : display[0];
2128 /* Setup window dimensions */
2130 getmaxyx(stdscr, base->height, base->width);
2132 /* Make room for the status window. */
2133 base->height -= 1;
2135 if (view != base) {
2136 /* Horizontal split. */
2137 view->width = base->width;
2138 view->height = apply_step(opt_scale_split_view, base->height);
2139 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2140 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2141 base->height -= view->height;
2143 /* Make room for the title bar. */
2144 view->height -= 1;
2147 /* Make room for the title bar. */
2148 base->height -= 1;
2150 offset = 0;
2152 foreach_displayed_view (view, i) {
2153 if (!display_win[i]) {
2154 display_win[i] = newwin(view->height, view->width, offset, 0);
2155 if (!display_win[i])
2156 die("Failed to create %s view", view->name);
2158 scrollok(display_win[i], FALSE);
2160 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2161 if (!display_title[i])
2162 die("Failed to create title window");
2164 } else {
2165 wresize(display_win[i], view->height, view->width);
2166 mvwin(display_win[i], offset, 0);
2167 mvwin(display_title[i], offset + view->height, 0);
2170 view->win = display_win[i];
2172 offset += view->height + 1;
2176 static void
2177 redraw_display(bool clear)
2179 struct view *view;
2180 int i;
2182 foreach_displayed_view (view, i) {
2183 if (clear)
2184 wclear(view->win);
2185 redraw_view(view);
2186 update_view_title(view);
2192 * Option management
2195 #define TOGGLE_MENU \
2196 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2197 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2198 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2199 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2200 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2201 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2202 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2203 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL)
2205 static bool
2206 toggle_option(enum request request)
2208 const struct {
2209 enum request request;
2210 const struct enum_map *map;
2211 size_t map_size;
2212 } data[] = {
2213 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2214 TOGGLE_MENU
2215 #undef TOGGLE_
2217 const struct menu_item menu[] = {
2218 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2219 TOGGLE_MENU
2220 #undef TOGGLE_
2221 { 0 }
2223 int i = 0;
2225 if (request == REQ_OPTIONS) {
2226 if (!prompt_menu("Toggle option", menu, &i))
2227 return FALSE;
2228 } else {
2229 while (i < ARRAY_SIZE(data) && data[i].request != request)
2230 i++;
2231 if (i >= ARRAY_SIZE(data))
2232 die("Invalid request (%d)", request);
2235 if (data[i].map != NULL) {
2236 unsigned int *opt = menu[i].data;
2238 *opt = (*opt + 1) % data[i].map_size;
2239 if (data[i].map == ignore_space_map) {
2240 update_ignore_space_arg();
2241 report("Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2242 return TRUE;
2245 redraw_display(FALSE);
2246 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2248 } else {
2249 bool *option = menu[i].data;
2251 *option = !*option;
2252 redraw_display(FALSE);
2253 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2256 return FALSE;
2259 static void
2260 maximize_view(struct view *view, bool redraw)
2262 memset(display, 0, sizeof(display));
2263 current_view = 0;
2264 display[current_view] = view;
2265 resize_display();
2266 if (redraw) {
2267 redraw_display(FALSE);
2268 report("");
2274 * Navigation
2277 static bool
2278 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2280 if (lineno >= view->lines)
2281 lineno = view->lines > 0 ? view->lines - 1 : 0;
2283 if (offset > lineno || offset + view->height <= lineno) {
2284 unsigned long half = view->height / 2;
2286 if (lineno > half)
2287 offset = lineno - half;
2288 else
2289 offset = 0;
2292 if (offset != view->offset || lineno != view->lineno) {
2293 view->offset = offset;
2294 view->lineno = lineno;
2295 return TRUE;
2298 return FALSE;
2301 /* Scrolling backend */
2302 static void
2303 do_scroll_view(struct view *view, int lines)
2305 bool redraw_current_line = FALSE;
2307 /* The rendering expects the new offset. */
2308 view->offset += lines;
2310 assert(0 <= view->offset && view->offset < view->lines);
2311 assert(lines);
2313 /* Move current line into the view. */
2314 if (view->lineno < view->offset) {
2315 view->lineno = view->offset;
2316 redraw_current_line = TRUE;
2317 } else if (view->lineno >= view->offset + view->height) {
2318 view->lineno = view->offset + view->height - 1;
2319 redraw_current_line = TRUE;
2322 assert(view->offset <= view->lineno && view->lineno < view->lines);
2324 /* Redraw the whole screen if scrolling is pointless. */
2325 if (view->height < ABS(lines)) {
2326 redraw_view(view);
2328 } else {
2329 int line = lines > 0 ? view->height - lines : 0;
2330 int end = line + ABS(lines);
2332 scrollok(view->win, TRUE);
2333 wscrl(view->win, lines);
2334 scrollok(view->win, FALSE);
2336 while (line < end && draw_view_line(view, line))
2337 line++;
2339 if (redraw_current_line)
2340 draw_view_line(view, view->lineno - view->offset);
2341 wnoutrefresh(view->win);
2344 view->has_scrolled = TRUE;
2345 report("");
2348 /* Scroll frontend */
2349 static void
2350 scroll_view(struct view *view, enum request request)
2352 int lines = 1;
2354 assert(view_is_displayed(view));
2356 switch (request) {
2357 case REQ_SCROLL_FIRST_COL:
2358 view->yoffset = 0;
2359 redraw_view_from(view, 0);
2360 report("");
2361 return;
2362 case REQ_SCROLL_LEFT:
2363 if (view->yoffset == 0) {
2364 report("Cannot scroll beyond the first column");
2365 return;
2367 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2368 view->yoffset = 0;
2369 else
2370 view->yoffset -= apply_step(opt_hscroll, view->width);
2371 redraw_view_from(view, 0);
2372 report("");
2373 return;
2374 case REQ_SCROLL_RIGHT:
2375 view->yoffset += apply_step(opt_hscroll, view->width);
2376 redraw_view(view);
2377 report("");
2378 return;
2379 case REQ_SCROLL_PAGE_DOWN:
2380 lines = view->height;
2381 case REQ_SCROLL_LINE_DOWN:
2382 if (view->offset + lines > view->lines)
2383 lines = view->lines - view->offset;
2385 if (lines == 0 || view->offset + view->height >= view->lines) {
2386 report("Cannot scroll beyond the last line");
2387 return;
2389 break;
2391 case REQ_SCROLL_PAGE_UP:
2392 lines = view->height;
2393 case REQ_SCROLL_LINE_UP:
2394 if (lines > view->offset)
2395 lines = view->offset;
2397 if (lines == 0) {
2398 report("Cannot scroll beyond the first line");
2399 return;
2402 lines = -lines;
2403 break;
2405 default:
2406 die("request %d not handled in switch", request);
2409 do_scroll_view(view, lines);
2412 /* Cursor moving */
2413 static void
2414 move_view(struct view *view, enum request request)
2416 int scroll_steps = 0;
2417 int steps;
2419 switch (request) {
2420 case REQ_MOVE_FIRST_LINE:
2421 steps = -view->lineno;
2422 break;
2424 case REQ_MOVE_LAST_LINE:
2425 steps = view->lines - view->lineno - 1;
2426 break;
2428 case REQ_MOVE_PAGE_UP:
2429 steps = view->height > view->lineno
2430 ? -view->lineno : -view->height;
2431 break;
2433 case REQ_MOVE_PAGE_DOWN:
2434 steps = view->lineno + view->height >= view->lines
2435 ? view->lines - view->lineno - 1 : view->height;
2436 break;
2438 case REQ_MOVE_UP:
2439 steps = -1;
2440 break;
2442 case REQ_MOVE_DOWN:
2443 steps = 1;
2444 break;
2446 default:
2447 die("request %d not handled in switch", request);
2450 if (steps <= 0 && view->lineno == 0) {
2451 report("Cannot move beyond the first line");
2452 return;
2454 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2455 report("Cannot move beyond the last line");
2456 return;
2459 /* Move the current line */
2460 view->lineno += steps;
2461 assert(0 <= view->lineno && view->lineno < view->lines);
2463 /* Check whether the view needs to be scrolled */
2464 if (view->lineno < view->offset ||
2465 view->lineno >= view->offset + view->height) {
2466 scroll_steps = steps;
2467 if (steps < 0 && -steps > view->offset) {
2468 scroll_steps = -view->offset;
2470 } else if (steps > 0) {
2471 if (view->lineno == view->lines - 1 &&
2472 view->lines > view->height) {
2473 scroll_steps = view->lines - view->offset - 1;
2474 if (scroll_steps >= view->height)
2475 scroll_steps -= view->height - 1;
2480 if (!view_is_displayed(view)) {
2481 view->offset += scroll_steps;
2482 assert(0 <= view->offset && view->offset < view->lines);
2483 view->ops->select(view, &view->line[view->lineno]);
2484 return;
2487 /* Repaint the old "current" line if we be scrolling */
2488 if (ABS(steps) < view->height)
2489 draw_view_line(view, view->lineno - steps - view->offset);
2491 if (scroll_steps) {
2492 do_scroll_view(view, scroll_steps);
2493 return;
2496 /* Draw the current line */
2497 draw_view_line(view, view->lineno - view->offset);
2499 wnoutrefresh(view->win);
2500 report("");
2505 * Searching
2508 static void search_view(struct view *view, enum request request);
2510 static bool
2511 grep_text(struct view *view, const char *text[])
2513 regmatch_t pmatch;
2514 size_t i;
2516 for (i = 0; text[i]; i++)
2517 if (*text[i] &&
2518 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2519 return TRUE;
2520 return FALSE;
2523 static void
2524 select_view_line(struct view *view, unsigned long lineno)
2526 unsigned long old_lineno = view->lineno;
2527 unsigned long old_offset = view->offset;
2529 if (goto_view_line(view, view->offset, lineno)) {
2530 if (view_is_displayed(view)) {
2531 if (old_offset != view->offset) {
2532 redraw_view(view);
2533 } else {
2534 draw_view_line(view, old_lineno - view->offset);
2535 draw_view_line(view, view->lineno - view->offset);
2536 wnoutrefresh(view->win);
2538 } else {
2539 view->ops->select(view, &view->line[view->lineno]);
2544 static void
2545 find_next(struct view *view, enum request request)
2547 unsigned long lineno = view->lineno;
2548 int direction;
2550 if (!*view->grep) {
2551 if (!*opt_search)
2552 report("No previous search");
2553 else
2554 search_view(view, request);
2555 return;
2558 switch (request) {
2559 case REQ_SEARCH:
2560 case REQ_FIND_NEXT:
2561 direction = 1;
2562 break;
2564 case REQ_SEARCH_BACK:
2565 case REQ_FIND_PREV:
2566 direction = -1;
2567 break;
2569 default:
2570 return;
2573 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2574 lineno += direction;
2576 /* Note, lineno is unsigned long so will wrap around in which case it
2577 * will become bigger than view->lines. */
2578 for (; lineno < view->lines; lineno += direction) {
2579 if (view->ops->grep(view, &view->line[lineno])) {
2580 select_view_line(view, lineno);
2581 report("Line %ld matches '%s'", lineno + 1, view->grep);
2582 return;
2586 report("No match found for '%s'", view->grep);
2589 static void
2590 search_view(struct view *view, enum request request)
2592 int regex_err;
2594 if (view->regex) {
2595 regfree(view->regex);
2596 *view->grep = 0;
2597 } else {
2598 view->regex = calloc(1, sizeof(*view->regex));
2599 if (!view->regex)
2600 return;
2603 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2604 if (regex_err != 0) {
2605 char buf[SIZEOF_STR] = "unknown error";
2607 regerror(regex_err, view->regex, buf, sizeof(buf));
2608 report("Search failed: %s", buf);
2609 return;
2612 string_copy(view->grep, opt_search);
2614 find_next(view, request);
2618 * Incremental updating
2621 static void
2622 reset_view(struct view *view)
2624 int i;
2626 for (i = 0; i < view->lines; i++)
2627 free(view->line[i].data);
2628 free(view->line);
2630 view->p_offset = view->offset;
2631 view->p_yoffset = view->yoffset;
2632 view->p_lineno = view->lineno;
2634 view->line = NULL;
2635 view->offset = 0;
2636 view->yoffset = 0;
2637 view->lines = 0;
2638 view->lineno = 0;
2639 view->vid[0] = 0;
2640 view->update_secs = 0;
2643 static const char *
2644 format_arg(const char *name)
2646 static struct {
2647 const char *name;
2648 size_t namelen;
2649 const char *value;
2650 const char *value_if_empty;
2651 } vars[] = {
2652 #define FORMAT_VAR(name, value, value_if_empty) \
2653 { name, STRING_SIZE(name), value, value_if_empty }
2654 FORMAT_VAR("%(directory)", opt_path, "."),
2655 FORMAT_VAR("%(file)", opt_file, ""),
2656 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2657 FORMAT_VAR("%(head)", ref_head, ""),
2658 FORMAT_VAR("%(commit)", ref_commit, ""),
2659 FORMAT_VAR("%(blob)", ref_blob, ""),
2660 FORMAT_VAR("%(branch)", ref_branch, ""),
2662 int i;
2664 for (i = 0; i < ARRAY_SIZE(vars); i++)
2665 if (!strncmp(name, vars[i].name, vars[i].namelen))
2666 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2668 report("Unknown replacement: `%s`", name);
2669 return NULL;
2672 static bool
2673 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2675 char buf[SIZEOF_STR];
2676 int argc;
2678 argv_free(*dst_argv);
2680 for (argc = 0; src_argv[argc]; argc++) {
2681 const char *arg = src_argv[argc];
2682 size_t bufpos = 0;
2684 if (!strcmp(arg, "%(fileargs)")) {
2685 if (!argv_append_array(dst_argv, opt_file_argv))
2686 break;
2687 continue;
2689 } else if (!strcmp(arg, "%(diffargs)")) {
2690 if (!argv_append_array(dst_argv, opt_diff_argv))
2691 break;
2692 continue;
2694 } else if (!strcmp(arg, "%(blameargs)")) {
2695 if (!argv_append_array(dst_argv, opt_blame_argv))
2696 break;
2697 continue;
2699 } else if (!strcmp(arg, "%(revargs)") ||
2700 (first && !strcmp(arg, "%(commit)"))) {
2701 if (!argv_append_array(dst_argv, opt_rev_argv))
2702 break;
2703 continue;
2706 while (arg) {
2707 char *next = strstr(arg, "%(");
2708 int len = next - arg;
2709 const char *value;
2711 if (!next) {
2712 len = strlen(arg);
2713 value = "";
2715 } else {
2716 value = format_arg(next);
2718 if (!value) {
2719 return FALSE;
2723 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2724 return FALSE;
2726 arg = next ? strchr(next, ')') + 1 : NULL;
2729 if (!argv_append(dst_argv, buf))
2730 break;
2733 return src_argv[argc] == NULL;
2736 static bool
2737 restore_view_position(struct view *view)
2739 /* A view without a previous view is the first view */
2740 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2741 select_view_line(view, opt_lineno - 1);
2742 opt_lineno = 0;
2745 if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2746 return FALSE;
2748 /* Changing the view position cancels the restoring. */
2749 /* FIXME: Changing back to the first line is not detected. */
2750 if (view->offset != 0 || view->lineno != 0) {
2751 view->p_restore = FALSE;
2752 return FALSE;
2755 if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2756 view_is_displayed(view))
2757 werase(view->win);
2759 view->yoffset = view->p_yoffset;
2760 view->p_restore = FALSE;
2762 return TRUE;
2765 static void
2766 end_update(struct view *view, bool force)
2768 if (!view->pipe)
2769 return;
2770 while (!view->ops->read(view, NULL))
2771 if (!force)
2772 return;
2773 if (force)
2774 io_kill(view->pipe);
2775 io_done(view->pipe);
2776 view->pipe = NULL;
2779 static void
2780 setup_update(struct view *view, const char *vid)
2782 reset_view(view);
2783 string_copy_rev(view->vid, vid);
2784 view->pipe = &view->io;
2785 view->start_time = time(NULL);
2788 static bool
2789 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2791 bool extra = !!(flags & (OPEN_EXTRA));
2792 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2793 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2795 if (!reload && !strcmp(view->vid, view->id))
2796 return TRUE;
2798 if (view->pipe) {
2799 if (extra)
2800 io_done(view->pipe);
2801 else
2802 end_update(view, TRUE);
2805 if (!refresh && argv) {
2806 view->dir = dir;
2807 if (!format_argv(&view->argv, argv, !view->prev))
2808 return FALSE;
2810 /* Put the current ref_* value to the view title ref
2811 * member. This is needed by the blob view. Most other
2812 * views sets it automatically after loading because the
2813 * first line is a commit line. */
2814 string_copy_rev(view->ref, view->id);
2817 if (view->argv && view->argv[0] &&
2818 !io_run(&view->io, IO_RD, view->dir, view->argv))
2819 return FALSE;
2821 if (!extra)
2822 setup_update(view, view->id);
2824 return TRUE;
2827 static bool
2828 update_view(struct view *view)
2830 char *line;
2831 /* Clear the view and redraw everything since the tree sorting
2832 * might have rearranged things. */
2833 bool redraw = view->lines == 0;
2834 bool can_read = TRUE;
2835 struct encoding *encoding = view->encoding ? view->encoding : opt_encoding;
2837 if (!view->pipe)
2838 return TRUE;
2840 if (!io_can_read(view->pipe, FALSE)) {
2841 if (view->lines == 0 && view_is_displayed(view)) {
2842 time_t secs = time(NULL) - view->start_time;
2844 if (secs > 1 && secs > view->update_secs) {
2845 if (view->update_secs == 0)
2846 redraw_view(view);
2847 update_view_title(view);
2848 view->update_secs = secs;
2851 return TRUE;
2854 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2855 if (encoding) {
2856 line = encoding_convert(encoding, line);
2859 if (!view->ops->read(view, line)) {
2860 report("Allocation failure");
2861 end_update(view, TRUE);
2862 return FALSE;
2867 unsigned long lines = view->lines;
2868 int digits;
2870 for (digits = 0; lines; digits++)
2871 lines /= 10;
2873 /* Keep the displayed view in sync with line number scaling. */
2874 if (digits != view->digits) {
2875 view->digits = digits;
2876 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
2877 redraw = TRUE;
2881 if (io_error(view->pipe)) {
2882 report("Failed to read: %s", io_strerror(view->pipe));
2883 end_update(view, TRUE);
2885 } else if (io_eof(view->pipe)) {
2886 if (view_is_displayed(view))
2887 report("");
2888 end_update(view, FALSE);
2891 if (restore_view_position(view))
2892 redraw = TRUE;
2894 if (!view_is_displayed(view))
2895 return TRUE;
2897 if (redraw)
2898 redraw_view_from(view, 0);
2899 else
2900 redraw_view_dirty(view);
2902 /* Update the title _after_ the redraw so that if the redraw picks up a
2903 * commit reference in view->ref it'll be available here. */
2904 update_view_title(view);
2905 return TRUE;
2908 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2910 static struct line *
2911 add_line_data(struct view *view, void *data, enum line_type type)
2913 struct line *line;
2915 if (!realloc_lines(&view->line, view->lines, 1))
2916 return NULL;
2918 line = &view->line[view->lines++];
2919 memset(line, 0, sizeof(*line));
2920 line->type = type;
2921 line->data = data;
2922 line->dirty = 1;
2924 return line;
2927 static struct line *
2928 add_line_text(struct view *view, const char *text, enum line_type type)
2930 char *data = text ? strdup(text) : NULL;
2932 return data ? add_line_data(view, data, type) : NULL;
2935 static struct line *
2936 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2938 char buf[SIZEOF_STR];
2939 int retval;
2941 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
2942 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
2946 * View opening
2949 static void
2950 load_view(struct view *view, enum open_flags flags)
2952 if (view->pipe)
2953 end_update(view, TRUE);
2954 if (view->ops->private_size) {
2955 if (!view->private)
2956 view->private = calloc(1, view->ops->private_size);
2957 else
2958 memset(view->private, 0, view->ops->private_size);
2960 if (!view->ops->open(view, flags)) {
2961 report("Failed to load %s view", view->name);
2962 return;
2964 restore_view_position(view);
2966 if (view->pipe && view->lines == 0) {
2967 /* Clear the old view and let the incremental updating refill
2968 * the screen. */
2969 werase(view->win);
2970 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2971 report("");
2972 } else if (view_is_displayed(view)) {
2973 redraw_view(view);
2974 report("");
2978 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2979 #define reload_view(view) load_view(view, OPEN_RELOAD)
2981 static void
2982 split_view(struct view *prev, struct view *view)
2984 display[1] = view;
2985 current_view = 1;
2986 view->parent = prev;
2987 resize_display();
2989 if (prev->lineno - prev->offset >= prev->height) {
2990 /* Take the title line into account. */
2991 int lines = prev->lineno - prev->offset - prev->height + 1;
2993 /* Scroll the view that was split if the current line is
2994 * outside the new limited view. */
2995 do_scroll_view(prev, lines);
2998 if (view != prev && view_is_displayed(prev)) {
2999 /* "Blur" the previous view. */
3000 update_view_title(prev);
3004 static void
3005 open_view(struct view *prev, enum request request, enum open_flags flags)
3007 bool split = !!(flags & OPEN_SPLIT);
3008 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3009 struct view *view = VIEW(request);
3010 int nviews = displayed_views();
3012 assert(flags ^ OPEN_REFRESH);
3014 if (view == prev && nviews == 1 && !reload) {
3015 report("Already in %s view", view->name);
3016 return;
3019 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3020 report("The %s view is disabled in pager view", view->name);
3021 return;
3024 if (split) {
3025 split_view(prev, view);
3026 } else {
3027 maximize_view(view, FALSE);
3030 /* No prev signals that this is the first loaded view. */
3031 if (prev && view != prev) {
3032 view->prev = prev;
3035 load_view(view, flags);
3038 static void
3039 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3041 enum request request = view - views + REQ_OFFSET + 1;
3043 if (view->pipe)
3044 end_update(view, TRUE);
3045 view->dir = dir;
3047 if (!argv_copy(&view->argv, argv)) {
3048 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3049 } else {
3050 open_view(prev, request, flags | OPEN_PREPARED);
3054 static void
3055 open_external_viewer(const char *argv[], const char *dir)
3057 def_prog_mode(); /* save current tty modes */
3058 endwin(); /* restore original tty modes */
3059 io_run_fg(argv, dir);
3060 fprintf(stderr, "Press Enter to continue");
3061 getc(opt_tty);
3062 reset_prog_mode();
3063 redraw_display(TRUE);
3066 static void
3067 open_mergetool(const char *file)
3069 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3071 open_external_viewer(mergetool_argv, opt_cdup);
3074 static void
3075 open_editor(const char *file)
3077 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3078 char editor_cmd[SIZEOF_STR];
3079 const char *editor;
3080 int argc = 0;
3082 editor = getenv("GIT_EDITOR");
3083 if (!editor && *opt_editor)
3084 editor = opt_editor;
3085 if (!editor)
3086 editor = getenv("VISUAL");
3087 if (!editor)
3088 editor = getenv("EDITOR");
3089 if (!editor)
3090 editor = "vi";
3092 string_ncopy(editor_cmd, editor, strlen(editor));
3093 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3094 report("Failed to read editor command");
3095 return;
3098 editor_argv[argc] = file;
3099 open_external_viewer(editor_argv, opt_cdup);
3102 static void
3103 open_run_request(enum request request)
3105 struct run_request *req = get_run_request(request);
3106 const char **argv = NULL;
3108 if (!req) {
3109 report("Unknown run request");
3110 return;
3113 if (format_argv(&argv, req->argv, FALSE))
3114 open_external_viewer(argv, NULL);
3115 if (argv)
3116 argv_free(argv);
3117 free(argv);
3121 * User request switch noodle
3124 static int
3125 view_driver(struct view *view, enum request request)
3127 int i;
3129 if (request == REQ_NONE)
3130 return TRUE;
3132 if (request > REQ_NONE) {
3133 open_run_request(request);
3134 view_request(view, REQ_REFRESH);
3135 return TRUE;
3138 request = view_request(view, request);
3139 if (request == REQ_NONE)
3140 return TRUE;
3142 switch (request) {
3143 case REQ_MOVE_UP:
3144 case REQ_MOVE_DOWN:
3145 case REQ_MOVE_PAGE_UP:
3146 case REQ_MOVE_PAGE_DOWN:
3147 case REQ_MOVE_FIRST_LINE:
3148 case REQ_MOVE_LAST_LINE:
3149 move_view(view, request);
3150 break;
3152 case REQ_SCROLL_FIRST_COL:
3153 case REQ_SCROLL_LEFT:
3154 case REQ_SCROLL_RIGHT:
3155 case REQ_SCROLL_LINE_DOWN:
3156 case REQ_SCROLL_LINE_UP:
3157 case REQ_SCROLL_PAGE_DOWN:
3158 case REQ_SCROLL_PAGE_UP:
3159 scroll_view(view, request);
3160 break;
3162 case REQ_VIEW_BLAME:
3163 if (!opt_file[0]) {
3164 report("No file chosen, press %s to open tree view",
3165 get_view_key(view, REQ_VIEW_TREE));
3166 break;
3168 open_view(view, request, OPEN_DEFAULT);
3169 break;
3171 case REQ_VIEW_BLOB:
3172 if (!ref_blob[0]) {
3173 report("No file chosen, press %s to open tree view",
3174 get_view_key(view, REQ_VIEW_TREE));
3175 break;
3177 open_view(view, request, OPEN_DEFAULT);
3178 break;
3180 case REQ_VIEW_PAGER:
3181 if (view == NULL) {
3182 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
3183 die("Failed to open stdin");
3184 open_view(view, request, OPEN_PREPARED);
3185 break;
3188 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
3189 report("No pager content, press %s to run command from prompt",
3190 get_view_key(view, REQ_PROMPT));
3191 break;
3193 open_view(view, request, OPEN_DEFAULT);
3194 break;
3196 case REQ_VIEW_STAGE:
3197 if (!VIEW(REQ_VIEW_STAGE)->lines) {
3198 report("No stage content, press %s to open the status view and choose file",
3199 get_view_key(view, REQ_VIEW_STATUS));
3200 break;
3202 open_view(view, request, OPEN_DEFAULT);
3203 break;
3205 case REQ_VIEW_STATUS:
3206 if (opt_is_inside_work_tree == FALSE) {
3207 report("The status view requires a working tree");
3208 break;
3210 open_view(view, request, OPEN_DEFAULT);
3211 break;
3213 case REQ_VIEW_MAIN:
3214 case REQ_VIEW_DIFF:
3215 case REQ_VIEW_LOG:
3216 case REQ_VIEW_TREE:
3217 case REQ_VIEW_HELP:
3218 case REQ_VIEW_BRANCH:
3219 open_view(view, request, OPEN_DEFAULT);
3220 break;
3222 case REQ_NEXT:
3223 case REQ_PREVIOUS:
3224 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
3226 if (view->parent) {
3227 int line;
3229 view = view->parent;
3230 line = view->lineno;
3231 move_view(view, request);
3232 if (view_is_displayed(view))
3233 update_view_title(view);
3234 if (line != view->lineno)
3235 view_request(view, REQ_ENTER);
3236 } else {
3237 move_view(view, request);
3239 break;
3241 case REQ_VIEW_NEXT:
3243 int nviews = displayed_views();
3244 int next_view = (current_view + 1) % nviews;
3246 if (next_view == current_view) {
3247 report("Only one view is displayed");
3248 break;
3251 current_view = next_view;
3252 /* Blur out the title of the previous view. */
3253 update_view_title(view);
3254 report("");
3255 break;
3257 case REQ_REFRESH:
3258 report("Refreshing is not yet supported for the %s view", view->name);
3259 break;
3261 case REQ_MAXIMIZE:
3262 if (displayed_views() == 2)
3263 maximize_view(view, TRUE);
3264 break;
3266 case REQ_OPTIONS:
3267 case REQ_TOGGLE_LINENO:
3268 case REQ_TOGGLE_DATE:
3269 case REQ_TOGGLE_AUTHOR:
3270 case REQ_TOGGLE_FILENAME:
3271 case REQ_TOGGLE_GRAPHIC:
3272 case REQ_TOGGLE_REV_GRAPH:
3273 case REQ_TOGGLE_REFS:
3274 case REQ_TOGGLE_IGNORE_SPACE:
3275 if (toggle_option(request))
3276 reload_view(view);
3277 break;
3279 case REQ_TOGGLE_SORT_FIELD:
3280 case REQ_TOGGLE_SORT_ORDER:
3281 report("Sorting is not yet supported for the %s view", view->name);
3282 break;
3284 case REQ_DIFF_CONTEXT_UP:
3285 case REQ_DIFF_CONTEXT_DOWN:
3286 report("Changing the diff context is not yet supported for the %s view", view->name);
3287 break;
3289 case REQ_SEARCH:
3290 case REQ_SEARCH_BACK:
3291 search_view(view, request);
3292 break;
3294 case REQ_FIND_NEXT:
3295 case REQ_FIND_PREV:
3296 find_next(view, request);
3297 break;
3299 case REQ_STOP_LOADING:
3300 foreach_view(view, i) {
3301 if (view->pipe)
3302 report("Stopped loading the %s view", view->name),
3303 end_update(view, TRUE);
3305 break;
3307 case REQ_SHOW_VERSION:
3308 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3309 return TRUE;
3311 case REQ_SCREEN_REDRAW:
3312 redraw_display(TRUE);
3313 break;
3315 case REQ_EDIT:
3316 report("Nothing to edit");
3317 break;
3319 case REQ_ENTER:
3320 report("Nothing to enter");
3321 break;
3323 case REQ_VIEW_CLOSE:
3324 /* XXX: Mark closed views by letting view->prev point to the
3325 * view itself. Parents to closed view should never be
3326 * followed. */
3327 if (view->prev && view->prev != view) {
3328 maximize_view(view->prev, TRUE);
3329 view->prev = view;
3330 break;
3332 /* Fall-through */
3333 case REQ_QUIT:
3334 return FALSE;
3336 default:
3337 report("Unknown key, press %s for help",
3338 get_view_key(view, REQ_VIEW_HELP));
3339 return TRUE;
3342 return TRUE;
3347 * View backend utilities
3350 enum sort_field {
3351 ORDERBY_NAME,
3352 ORDERBY_DATE,
3353 ORDERBY_AUTHOR,
3356 struct sort_state {
3357 const enum sort_field *fields;
3358 size_t size, current;
3359 bool reverse;
3362 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3363 #define get_sort_field(state) ((state).fields[(state).current])
3364 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3366 static void
3367 sort_view(struct view *view, enum request request, struct sort_state *state,
3368 int (*compare)(const void *, const void *))
3370 switch (request) {
3371 case REQ_TOGGLE_SORT_FIELD:
3372 state->current = (state->current + 1) % state->size;
3373 break;
3375 case REQ_TOGGLE_SORT_ORDER:
3376 state->reverse = !state->reverse;
3377 break;
3378 default:
3379 die("Not a sort request");
3382 qsort(view->line, view->lines, sizeof(*view->line), compare);
3383 redraw_view(view);
3386 static bool
3387 update_diff_context(enum request request)
3389 int diff_context = opt_diff_context;
3391 switch (request) {
3392 case REQ_DIFF_CONTEXT_UP:
3393 opt_diff_context += 1;
3394 update_diff_context_arg(opt_diff_context);
3395 break;
3397 case REQ_DIFF_CONTEXT_DOWN:
3398 if (opt_diff_context == 0) {
3399 report("Diff context cannot be less than zero");
3400 break;
3402 opt_diff_context -= 1;
3403 update_diff_context_arg(opt_diff_context);
3404 break;
3406 default:
3407 die("Not a diff context request");
3410 return diff_context != opt_diff_context;
3413 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3415 /* Small author cache to reduce memory consumption. It uses binary
3416 * search to lookup or find place to position new entries. No entries
3417 * are ever freed. */
3418 static const char *
3419 get_author(const char *name)
3421 static const char **authors;
3422 static size_t authors_size;
3423 int from = 0, to = authors_size - 1;
3425 while (from <= to) {
3426 size_t pos = (to + from) / 2;
3427 int cmp = strcmp(name, authors[pos]);
3429 if (!cmp)
3430 return authors[pos];
3432 if (cmp < 0)
3433 to = pos - 1;
3434 else
3435 from = pos + 1;
3438 if (!realloc_authors(&authors, authors_size, 1))
3439 return NULL;
3440 name = strdup(name);
3441 if (!name)
3442 return NULL;
3444 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3445 authors[from] = name;
3446 authors_size++;
3448 return name;
3451 static void
3452 parse_timesec(struct time *time, const char *sec)
3454 time->sec = (time_t) atol(sec);
3457 static void
3458 parse_timezone(struct time *time, const char *zone)
3460 long tz;
3462 tz = ('0' - zone[1]) * 60 * 60 * 10;
3463 tz += ('0' - zone[2]) * 60 * 60;
3464 tz += ('0' - zone[3]) * 60 * 10;
3465 tz += ('0' - zone[4]) * 60;
3467 if (zone[0] == '-')
3468 tz = -tz;
3470 time->tz = tz;
3471 time->sec -= tz;
3474 /* Parse author lines where the name may be empty:
3475 * author <email@address.tld> 1138474660 +0100
3477 static void
3478 parse_author_line(char *ident, const char **author, struct time *time)
3480 char *nameend = strchr(ident, '<');
3481 char *emailend = strchr(ident, '>');
3483 if (nameend && emailend)
3484 *nameend = *emailend = 0;
3485 ident = chomp_string(ident);
3486 if (!*ident) {
3487 if (nameend)
3488 ident = chomp_string(nameend + 1);
3489 if (!*ident)
3490 ident = "Unknown";
3493 *author = get_author(ident);
3495 /* Parse epoch and timezone */
3496 if (emailend && emailend[1] == ' ') {
3497 char *secs = emailend + 2;
3498 char *zone = strchr(secs, ' ');
3500 parse_timesec(time, secs);
3502 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3503 parse_timezone(time, zone + 1);
3507 static struct line *
3508 find_prev_line_by_type(struct view *view, struct line *line, enum line_type type)
3510 for (; view->line < line; line--)
3511 if (line->type == type)
3512 return line;
3514 return NULL;
3518 * Blame
3521 struct blame_commit {
3522 char id[SIZEOF_REV]; /* SHA1 ID. */
3523 char title[128]; /* First line of the commit message. */
3524 const char *author; /* Author of the commit. */
3525 struct time time; /* Date from the author ident. */
3526 char filename[128]; /* Name of file. */
3527 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3528 char parent_filename[128]; /* Parent/previous name of file. */
3531 struct blame_header {
3532 char id[SIZEOF_REV]; /* SHA1 ID. */
3533 size_t orig_lineno;
3534 size_t lineno;
3535 size_t group;
3538 static bool
3539 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3541 const char *pos = *posref;
3543 *posref = NULL;
3544 pos = strchr(pos + 1, ' ');
3545 if (!pos || !isdigit(pos[1]))
3546 return FALSE;
3547 *number = atoi(pos + 1);
3548 if (*number < min || *number > max)
3549 return FALSE;
3551 *posref = pos;
3552 return TRUE;
3555 static bool
3556 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3558 const char *pos = text + SIZEOF_REV - 2;
3560 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3561 return FALSE;
3563 string_ncopy(header->id, text, SIZEOF_REV);
3565 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3566 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3567 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3568 return FALSE;
3570 return TRUE;
3573 static bool
3574 match_blame_header(const char *name, char **line)
3576 size_t namelen = strlen(name);
3577 bool matched = !strncmp(name, *line, namelen);
3579 if (matched)
3580 *line += namelen;
3582 return matched;
3585 static bool
3586 parse_blame_info(struct blame_commit *commit, char *line)
3588 if (match_blame_header("author ", &line)) {
3589 commit->author = get_author(line);
3591 } else if (match_blame_header("author-time ", &line)) {
3592 parse_timesec(&commit->time, line);
3594 } else if (match_blame_header("author-tz ", &line)) {
3595 parse_timezone(&commit->time, line);
3597 } else if (match_blame_header("summary ", &line)) {
3598 string_ncopy(commit->title, line, strlen(line));
3600 } else if (match_blame_header("previous ", &line)) {
3601 if (strlen(line) <= SIZEOF_REV)
3602 return FALSE;
3603 string_copy_rev(commit->parent_id, line);
3604 line += SIZEOF_REV;
3605 string_ncopy(commit->parent_filename, line, strlen(line));
3607 } else if (match_blame_header("filename ", &line)) {
3608 string_ncopy(commit->filename, line, strlen(line));
3609 return TRUE;
3612 return FALSE;
3616 * Pager backend
3619 static bool
3620 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3622 if (opt_line_number && draw_lineno(view, lineno))
3623 return TRUE;
3625 draw_text(view, line->type, line->data);
3626 return TRUE;
3629 static bool
3630 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3632 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3633 char ref[SIZEOF_STR];
3635 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3636 return TRUE;
3638 /* This is the only fatal call, since it can "corrupt" the buffer. */
3639 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3640 return FALSE;
3642 return TRUE;
3645 static void
3646 add_pager_refs(struct view *view, struct line *line)
3648 char buf[SIZEOF_STR];
3649 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3650 struct ref_list *list;
3651 size_t bufpos = 0, i;
3652 const char *sep = "Refs: ";
3653 bool is_tag = FALSE;
3655 assert(line->type == LINE_COMMIT);
3657 list = get_ref_list(commit_id);
3658 if (!list) {
3659 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3660 goto try_add_describe_ref;
3661 return;
3664 for (i = 0; i < list->size; i++) {
3665 struct ref *ref = list->refs[i];
3666 const char *fmt = ref->tag ? "%s[%s]" :
3667 ref->remote ? "%s<%s>" : "%s%s";
3669 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3670 return;
3671 sep = ", ";
3672 if (ref->tag)
3673 is_tag = TRUE;
3676 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3677 try_add_describe_ref:
3678 /* Add <tag>-g<commit_id> "fake" reference. */
3679 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3680 return;
3683 if (bufpos == 0)
3684 return;
3686 add_line_text(view, buf, LINE_PP_REFS);
3689 static bool
3690 pager_read(struct view *view, char *data)
3692 struct line *line;
3694 if (!data)
3695 return TRUE;
3697 line = add_line_text(view, data, get_line_type(data));
3698 if (!line)
3699 return FALSE;
3701 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
3702 add_pager_refs(view, line);
3704 return TRUE;
3707 static enum request
3708 pager_request(struct view *view, enum request request, struct line *line)
3710 int split = 0;
3712 if (request != REQ_ENTER)
3713 return request;
3715 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
3716 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3717 split = 1;
3720 /* Always scroll the view even if it was split. That way
3721 * you can use Enter to scroll through the log view and
3722 * split open each commit diff. */
3723 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3725 /* FIXME: A minor workaround. Scrolling the view will call report("")
3726 * but if we are scrolling a non-current view this won't properly
3727 * update the view title. */
3728 if (split)
3729 update_view_title(view);
3731 return REQ_NONE;
3734 static bool
3735 pager_grep(struct view *view, struct line *line)
3737 const char *text[] = { line->data, NULL };
3739 return grep_text(view, text);
3742 static void
3743 pager_select(struct view *view, struct line *line)
3745 if (line->type == LINE_COMMIT) {
3746 char *text = (char *)line->data + STRING_SIZE("commit ");
3748 if (!view_has_flags(view, VIEW_NO_REF))
3749 string_copy_rev(view->ref, text);
3750 string_copy_rev(ref_commit, text);
3754 static bool
3755 pager_open(struct view *view, enum open_flags flags)
3757 return begin_update(view, NULL, NULL, flags);
3760 static struct view_ops pager_ops = {
3761 "line",
3762 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
3764 pager_open,
3765 pager_read,
3766 pager_draw,
3767 pager_request,
3768 pager_grep,
3769 pager_select,
3772 static bool
3773 log_open(struct view *view, enum open_flags flags)
3775 static const char *log_argv[] = {
3776 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3779 return begin_update(view, NULL, log_argv, flags);
3782 static enum request
3783 log_request(struct view *view, enum request request, struct line *line)
3785 switch (request) {
3786 case REQ_REFRESH:
3787 load_refs();
3788 refresh_view(view);
3789 return REQ_NONE;
3790 default:
3791 return pager_request(view, request, line);
3795 static struct view_ops log_ops = {
3796 "line",
3797 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
3799 log_open,
3800 pager_read,
3801 pager_draw,
3802 log_request,
3803 pager_grep,
3804 pager_select,
3807 struct diff_state {
3808 bool reading_diff_stat;
3811 static bool
3812 diff_open(struct view *view, enum open_flags flags)
3814 static const char *diff_argv[] = {
3815 "git", "show", "--pretty=fuller", "--no-color", "--root",
3816 "--patch-with-stat", "--find-copies-harder", "-C",
3817 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
3818 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3821 return begin_update(view, NULL, diff_argv, flags);
3824 static bool
3825 diff_common_read(struct view *view, char *data, struct diff_state *state)
3827 if (state->reading_diff_stat) {
3828 size_t len = strlen(data);
3829 char *pipe = strchr(data, '|');
3830 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3831 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3833 if (pipe && (has_histogram || has_bin_diff)) {
3834 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3835 } else {
3836 state->reading_diff_stat = FALSE;
3839 } else if (!strcmp(data, "---")) {
3840 state->reading_diff_stat = TRUE;
3843 return pager_read(view, data);
3846 static enum request
3847 diff_common_enter(struct view *view, enum request request, struct line *line)
3849 if (line->type == LINE_DIFF_STAT) {
3850 int file_number = 0;
3852 while (line >= view->line && line->type == LINE_DIFF_STAT) {
3853 file_number++;
3854 line--;
3857 while (line < view->line + view->lines) {
3858 if (line->type == LINE_DIFF_HEADER) {
3859 if (file_number == 1) {
3860 break;
3862 file_number--;
3864 line++;
3868 select_view_line(view, line - view->line);
3869 report("");
3870 return REQ_NONE;
3872 } else {
3873 return pager_request(view, request, line);
3877 static bool
3878 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
3880 char *sep = strchr(*text, c);
3882 if (sep != NULL) {
3883 *sep = 0;
3884 draw_text(view, *type, *text);
3885 *sep = c;
3886 *text = sep;
3887 *type = next_type;
3890 return sep != NULL;
3893 static bool
3894 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
3896 char *text = line->data;
3897 enum line_type type = line->type;
3899 if (opt_line_number && draw_lineno(view, lineno))
3900 return TRUE;
3902 if (type == LINE_DIFF_STAT) {
3903 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
3904 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
3905 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
3906 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
3907 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
3908 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
3909 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
3911 } else {
3912 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
3913 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
3917 draw_text(view, type, text);
3918 return TRUE;
3921 static bool
3922 diff_read(struct view *view, char *data)
3924 struct diff_state *state = view->private;
3926 if (!data) {
3927 /* Fall back to retry if no diff will be shown. */
3928 if (view->lines == 0 && opt_file_argv) {
3929 int pos = argv_size(view->argv)
3930 - argv_size(opt_file_argv) - 1;
3932 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3933 for (; view->argv[pos]; pos++) {
3934 free((void *) view->argv[pos]);
3935 view->argv[pos] = NULL;
3938 if (view->pipe)
3939 io_done(view->pipe);
3940 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3941 return FALSE;
3944 return TRUE;
3947 return diff_common_read(view, data, state);
3950 static bool
3951 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
3952 struct blame_header *header, struct blame_commit *commit)
3954 char line_arg[SIZEOF_STR];
3955 const char *blame_argv[] = {
3956 "git", "blame", "-p", line_arg, ref, "--", file, NULL
3958 struct io io;
3959 bool ok = FALSE;
3960 char *buf;
3962 if (!string_format(line_arg, "-L%d,+1", lineno))
3963 return FALSE;
3965 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
3966 return FALSE;
3968 while ((buf = io_get(&io, '\n', TRUE))) {
3969 if (header) {
3970 if (!parse_blame_header(header, buf, 9999999))
3971 break;
3972 header = NULL;
3974 } else if (parse_blame_info(commit, buf)) {
3975 ok = TRUE;
3976 break;
3980 if (io_error(&io))
3981 ok = FALSE;
3983 io_done(&io);
3984 return ok;
3987 static bool
3988 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
3990 return prefixcmp(chunk, "@@ -") ||
3991 !(chunk = strchr(chunk, marker)) ||
3992 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
3995 static enum request
3996 diff_trace_origin(struct view *view, struct line *line)
3998 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
3999 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4000 const char *chunk_data;
4001 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4002 int lineno = 0;
4003 const char *file = NULL;
4004 char ref[SIZEOF_REF];
4005 struct blame_header header;
4006 struct blame_commit commit;
4008 if (!diff || !chunk || chunk == line) {
4009 report("The line to trace must be inside a diff chunk");
4010 return REQ_NONE;
4013 for (; diff < line && !file; diff++) {
4014 const char *data = diff->data;
4016 if (!prefixcmp(data, "--- a/")) {
4017 file = data + STRING_SIZE("--- a/");
4018 break;
4022 if (diff == line || !file) {
4023 report("Failed to read the file name");
4024 return REQ_NONE;
4027 chunk_data = chunk->data;
4029 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4030 report("Failed to read the line number");
4031 return REQ_NONE;
4034 if (lineno == 0) {
4035 report("This is the origin of the line");
4036 return REQ_NONE;
4039 for (chunk += 1; chunk < line; chunk++) {
4040 if (chunk->type == LINE_DIFF_ADD) {
4041 lineno += chunk_marker == '+';
4042 } else if (chunk->type == LINE_DIFF_DEL) {
4043 lineno += chunk_marker == '-';
4044 } else {
4045 lineno++;
4049 if (chunk_marker == '+')
4050 string_copy(ref, view->vid);
4051 else
4052 string_format(ref, "%s^", view->vid);
4054 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4055 report("Failed to read blame data");
4056 return REQ_NONE;
4059 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4060 string_copy(opt_ref, header.id);
4061 opt_goto_line = header.orig_lineno - 1;
4063 return REQ_VIEW_BLAME;
4066 static enum request
4067 diff_request(struct view *view, enum request request, struct line *line)
4069 switch (request) {
4070 case REQ_VIEW_BLAME:
4071 return diff_trace_origin(view, line);
4073 case REQ_DIFF_CONTEXT_UP:
4074 case REQ_DIFF_CONTEXT_DOWN:
4075 if (!update_diff_context(request))
4076 return REQ_NONE;
4077 reload_view(view);
4078 return REQ_NONE;
4081 case REQ_ENTER:
4082 return diff_common_enter(view, request, line);
4084 default:
4085 return pager_request(view, request, line);
4089 static void
4090 diff_select(struct view *view, struct line *line)
4092 if (line->type == LINE_DIFF_STAT) {
4093 const char *key = get_view_key(view, REQ_ENTER);
4095 string_format(view->ref, "Press '%s' to jump to file diff", key);
4096 } else {
4097 string_ncopy(view->ref, view->id, strlen(view->id));
4098 return pager_select(view, line);
4102 static struct view_ops diff_ops = {
4103 "line",
4104 VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS,
4105 sizeof(struct diff_state),
4106 diff_open,
4107 diff_read,
4108 diff_common_draw,
4109 diff_request,
4110 pager_grep,
4111 diff_select,
4115 * Help backend
4118 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
4120 static bool
4121 help_open_keymap_title(struct view *view, enum keymap keymap)
4123 struct line *line;
4125 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
4126 help_keymap_hidden[keymap] ? '+' : '-',
4127 enum_name(keymap_map[keymap]));
4128 if (line)
4129 line->other = keymap;
4131 return help_keymap_hidden[keymap];
4134 static void
4135 help_open_keymap(struct view *view, enum keymap keymap)
4137 const char *group = NULL;
4138 char buf[SIZEOF_STR];
4139 size_t bufpos;
4140 bool add_title = TRUE;
4141 int i;
4143 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4144 const char *key = NULL;
4146 if (req_info[i].request == REQ_NONE)
4147 continue;
4149 if (!req_info[i].request) {
4150 group = req_info[i].help;
4151 continue;
4154 key = get_keys(keymap, req_info[i].request, TRUE);
4155 if (!key || !*key)
4156 continue;
4158 if (add_title && help_open_keymap_title(view, keymap))
4159 return;
4160 add_title = FALSE;
4162 if (group) {
4163 add_line_text(view, group, LINE_HELP_GROUP);
4164 group = NULL;
4167 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4168 enum_name(req_info[i]), req_info[i].help);
4171 group = "External commands:";
4173 for (i = 0; i < run_requests; i++) {
4174 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4175 const char *key;
4176 int argc;
4178 if (!req || req->keymap != keymap)
4179 continue;
4181 key = get_key_name(req->key);
4182 if (!*key)
4183 key = "(no key defined)";
4185 if (add_title && help_open_keymap_title(view, keymap))
4186 return;
4187 if (group) {
4188 add_line_text(view, group, LINE_HELP_GROUP);
4189 group = NULL;
4192 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
4193 if (!string_format_from(buf, &bufpos, "%s%s",
4194 argc ? " " : "", req->argv[argc]))
4195 return;
4197 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4201 static bool
4202 help_open(struct view *view, enum open_flags flags)
4204 enum keymap keymap;
4206 reset_view(view);
4207 view->p_restore = TRUE;
4208 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4209 add_line_text(view, "", LINE_DEFAULT);
4211 for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
4212 help_open_keymap(view, keymap);
4214 return TRUE;
4217 static enum request
4218 help_request(struct view *view, enum request request, struct line *line)
4220 switch (request) {
4221 case REQ_ENTER:
4222 if (line->type == LINE_HELP_KEYMAP) {
4223 help_keymap_hidden[line->other] =
4224 !help_keymap_hidden[line->other];
4225 refresh_view(view);
4228 return REQ_NONE;
4229 default:
4230 return pager_request(view, request, line);
4234 static struct view_ops help_ops = {
4235 "line",
4236 VIEW_NO_GIT_DIR,
4238 help_open,
4239 NULL,
4240 pager_draw,
4241 help_request,
4242 pager_grep,
4243 pager_select,
4248 * Tree backend
4251 struct tree_stack_entry {
4252 struct tree_stack_entry *prev; /* Entry below this in the stack */
4253 unsigned long lineno; /* Line number to restore */
4254 char *name; /* Position of name in opt_path */
4257 /* The top of the path stack. */
4258 static struct tree_stack_entry *tree_stack = NULL;
4259 unsigned long tree_lineno = 0;
4261 static void
4262 pop_tree_stack_entry(void)
4264 struct tree_stack_entry *entry = tree_stack;
4266 tree_lineno = entry->lineno;
4267 entry->name[0] = 0;
4268 tree_stack = entry->prev;
4269 free(entry);
4272 static void
4273 push_tree_stack_entry(const char *name, unsigned long lineno)
4275 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4276 size_t pathlen = strlen(opt_path);
4278 if (!entry)
4279 return;
4281 entry->prev = tree_stack;
4282 entry->name = opt_path + pathlen;
4283 tree_stack = entry;
4285 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4286 pop_tree_stack_entry();
4287 return;
4290 /* Move the current line to the first tree entry. */
4291 tree_lineno = 1;
4292 entry->lineno = lineno;
4295 /* Parse output from git-ls-tree(1):
4297 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4300 #define SIZEOF_TREE_ATTR \
4301 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4303 #define SIZEOF_TREE_MODE \
4304 STRING_SIZE("100644 ")
4306 #define TREE_ID_OFFSET \
4307 STRING_SIZE("100644 blob ")
4309 struct tree_entry {
4310 char id[SIZEOF_REV];
4311 mode_t mode;
4312 struct time time; /* Date from the author ident. */
4313 const char *author; /* Author of the commit. */
4314 char name[1];
4317 struct tree_state {
4318 const char *author_name;
4319 struct time author_time;
4320 bool read_date;
4323 static const char *
4324 tree_path(const struct line *line)
4326 return ((struct tree_entry *) line->data)->name;
4329 static int
4330 tree_compare_entry(const struct line *line1, const struct line *line2)
4332 if (line1->type != line2->type)
4333 return line1->type == LINE_TREE_DIR ? -1 : 1;
4334 return strcmp(tree_path(line1), tree_path(line2));
4337 static const enum sort_field tree_sort_fields[] = {
4338 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4340 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4342 static int
4343 tree_compare(const void *l1, const void *l2)
4345 const struct line *line1 = (const struct line *) l1;
4346 const struct line *line2 = (const struct line *) l2;
4347 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4348 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4350 if (line1->type == LINE_TREE_HEAD)
4351 return -1;
4352 if (line2->type == LINE_TREE_HEAD)
4353 return 1;
4355 switch (get_sort_field(tree_sort_state)) {
4356 case ORDERBY_DATE:
4357 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4359 case ORDERBY_AUTHOR:
4360 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4362 case ORDERBY_NAME:
4363 default:
4364 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4369 static struct line *
4370 tree_entry(struct view *view, enum line_type type, const char *path,
4371 const char *mode, const char *id)
4373 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4374 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4376 if (!entry || !line) {
4377 free(entry);
4378 return NULL;
4381 strncpy(entry->name, path, strlen(path));
4382 if (mode)
4383 entry->mode = strtoul(mode, NULL, 8);
4384 if (id)
4385 string_copy_rev(entry->id, id);
4387 return line;
4390 static bool
4391 tree_read_date(struct view *view, char *text, struct tree_state *state)
4393 if (!text && state->read_date) {
4394 state->read_date = FALSE;
4395 return TRUE;
4397 } else if (!text) {
4398 /* Find next entry to process */
4399 const char *log_file[] = {
4400 "git", "log", "--no-color", "--pretty=raw",
4401 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4404 if (!view->lines) {
4405 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4406 report("Tree is empty");
4407 return TRUE;
4410 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4411 report("Failed to load tree data");
4412 return TRUE;
4415 state->read_date = TRUE;
4416 return FALSE;
4418 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4419 parse_author_line(text + STRING_SIZE("author "),
4420 &state->author_name, &state->author_time);
4422 } else if (*text == ':') {
4423 char *pos;
4424 size_t annotated = 1;
4425 size_t i;
4427 pos = strchr(text, '\t');
4428 if (!pos)
4429 return TRUE;
4430 text = pos + 1;
4431 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4432 text += strlen(opt_path);
4433 pos = strchr(text, '/');
4434 if (pos)
4435 *pos = 0;
4437 for (i = 1; i < view->lines; i++) {
4438 struct line *line = &view->line[i];
4439 struct tree_entry *entry = line->data;
4441 annotated += !!entry->author;
4442 if (entry->author || strcmp(entry->name, text))
4443 continue;
4445 entry->author = state->author_name;
4446 entry->time = state->author_time;
4447 line->dirty = 1;
4448 break;
4451 if (annotated == view->lines)
4452 io_kill(view->pipe);
4454 return TRUE;
4457 static bool
4458 tree_read(struct view *view, char *text)
4460 struct tree_state *state = view->private;
4461 struct tree_entry *data;
4462 struct line *entry, *line;
4463 enum line_type type;
4464 size_t textlen = text ? strlen(text) : 0;
4465 char *path = text + SIZEOF_TREE_ATTR;
4467 if (state->read_date || !text)
4468 return tree_read_date(view, text, state);
4470 if (textlen <= SIZEOF_TREE_ATTR)
4471 return FALSE;
4472 if (view->lines == 0 &&
4473 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4474 return FALSE;
4476 /* Strip the path part ... */
4477 if (*opt_path) {
4478 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4479 size_t striplen = strlen(opt_path);
4481 if (pathlen > striplen)
4482 memmove(path, path + striplen,
4483 pathlen - striplen + 1);
4485 /* Insert "link" to parent directory. */
4486 if (view->lines == 1 &&
4487 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4488 return FALSE;
4491 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4492 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4493 if (!entry)
4494 return FALSE;
4495 data = entry->data;
4497 /* Skip "Directory ..." and ".." line. */
4498 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4499 if (tree_compare_entry(line, entry) <= 0)
4500 continue;
4502 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4504 line->data = data;
4505 line->type = type;
4506 for (; line <= entry; line++)
4507 line->dirty = line->cleareol = 1;
4508 return TRUE;
4511 if (tree_lineno > view->lineno) {
4512 view->lineno = tree_lineno;
4513 tree_lineno = 0;
4516 return TRUE;
4519 static bool
4520 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4522 struct tree_entry *entry = line->data;
4524 if (line->type == LINE_TREE_HEAD) {
4525 if (draw_text(view, line->type, "Directory path /"))
4526 return TRUE;
4527 } else {
4528 if (draw_mode(view, entry->mode))
4529 return TRUE;
4531 if (draw_author(view, entry->author))
4532 return TRUE;
4534 if (draw_date(view, &entry->time))
4535 return TRUE;
4538 draw_text(view, line->type, entry->name);
4539 return TRUE;
4542 static void
4543 open_blob_editor(const char *id)
4545 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4546 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4547 int fd = mkstemp(file);
4549 if (fd == -1)
4550 report("Failed to create temporary file");
4551 else if (!io_run_append(blob_argv, fd))
4552 report("Failed to save blob data to file");
4553 else
4554 open_editor(file);
4555 if (fd != -1)
4556 unlink(file);
4559 static enum request
4560 tree_request(struct view *view, enum request request, struct line *line)
4562 enum open_flags flags;
4563 struct tree_entry *entry = line->data;
4565 switch (request) {
4566 case REQ_VIEW_BLAME:
4567 if (line->type != LINE_TREE_FILE) {
4568 report("Blame only supported for files");
4569 return REQ_NONE;
4572 string_copy(opt_ref, view->vid);
4573 return request;
4575 case REQ_EDIT:
4576 if (line->type != LINE_TREE_FILE) {
4577 report("Edit only supported for files");
4578 } else if (!is_head_commit(view->vid)) {
4579 open_blob_editor(entry->id);
4580 } else {
4581 open_editor(opt_file);
4583 return REQ_NONE;
4585 case REQ_TOGGLE_SORT_FIELD:
4586 case REQ_TOGGLE_SORT_ORDER:
4587 sort_view(view, request, &tree_sort_state, tree_compare);
4588 return REQ_NONE;
4590 case REQ_PARENT:
4591 if (!*opt_path) {
4592 /* quit view if at top of tree */
4593 return REQ_VIEW_CLOSE;
4595 /* fake 'cd ..' */
4596 line = &view->line[1];
4597 break;
4599 case REQ_ENTER:
4600 break;
4602 default:
4603 return request;
4606 /* Cleanup the stack if the tree view is at a different tree. */
4607 while (!*opt_path && tree_stack)
4608 pop_tree_stack_entry();
4610 switch (line->type) {
4611 case LINE_TREE_DIR:
4612 /* Depending on whether it is a subdirectory or parent link
4613 * mangle the path buffer. */
4614 if (line == &view->line[1] && *opt_path) {
4615 pop_tree_stack_entry();
4617 } else {
4618 const char *basename = tree_path(line);
4620 push_tree_stack_entry(basename, view->lineno);
4623 /* Trees and subtrees share the same ID, so they are not not
4624 * unique like blobs. */
4625 flags = OPEN_RELOAD;
4626 request = REQ_VIEW_TREE;
4627 break;
4629 case LINE_TREE_FILE:
4630 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4631 request = REQ_VIEW_BLOB;
4632 break;
4634 default:
4635 return REQ_NONE;
4638 open_view(view, request, flags);
4639 if (request == REQ_VIEW_TREE)
4640 view->lineno = tree_lineno;
4642 return REQ_NONE;
4645 static bool
4646 tree_grep(struct view *view, struct line *line)
4648 struct tree_entry *entry = line->data;
4649 const char *text[] = {
4650 entry->name,
4651 mkauthor(entry->author, opt_author_cols, opt_author),
4652 mkdate(&entry->time, opt_date),
4653 NULL
4656 return grep_text(view, text);
4659 static void
4660 tree_select(struct view *view, struct line *line)
4662 struct tree_entry *entry = line->data;
4664 if (line->type == LINE_TREE_FILE) {
4665 string_copy_rev(ref_blob, entry->id);
4666 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4668 } else if (line->type != LINE_TREE_DIR) {
4669 return;
4672 string_copy_rev(view->ref, entry->id);
4675 static bool
4676 tree_open(struct view *view, enum open_flags flags)
4678 static const char *tree_argv[] = {
4679 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4682 if (view->lines == 0 && opt_prefix[0]) {
4683 char *pos = opt_prefix;
4685 while (pos && *pos) {
4686 char *end = strchr(pos, '/');
4688 if (end)
4689 *end = 0;
4690 push_tree_stack_entry(pos, 0);
4691 pos = end;
4692 if (end) {
4693 *end = '/';
4694 pos++;
4698 } else if (strcmp(view->vid, view->id)) {
4699 opt_path[0] = 0;
4702 return begin_update(view, opt_cdup, tree_argv, flags);
4705 static struct view_ops tree_ops = {
4706 "file",
4707 VIEW_NO_FLAGS,
4708 sizeof(struct tree_state),
4709 tree_open,
4710 tree_read,
4711 tree_draw,
4712 tree_request,
4713 tree_grep,
4714 tree_select,
4717 static bool
4718 blob_open(struct view *view, enum open_flags flags)
4720 static const char *blob_argv[] = {
4721 "git", "cat-file", "blob", "%(blob)", NULL
4724 view->encoding = get_path_encoding(opt_file, opt_encoding);
4726 return begin_update(view, NULL, blob_argv, flags);
4729 static bool
4730 blob_read(struct view *view, char *line)
4732 if (!line)
4733 return TRUE;
4734 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4737 static enum request
4738 blob_request(struct view *view, enum request request, struct line *line)
4740 switch (request) {
4741 case REQ_EDIT:
4742 open_blob_editor(view->vid);
4743 return REQ_NONE;
4744 default:
4745 return pager_request(view, request, line);
4749 static struct view_ops blob_ops = {
4750 "line",
4751 VIEW_NO_FLAGS,
4753 blob_open,
4754 blob_read,
4755 pager_draw,
4756 blob_request,
4757 pager_grep,
4758 pager_select,
4762 * Blame backend
4764 * Loading the blame view is a two phase job:
4766 * 1. File content is read either using opt_file from the
4767 * filesystem or using git-cat-file.
4768 * 2. Then blame information is incrementally added by
4769 * reading output from git-blame.
4772 struct blame {
4773 struct blame_commit *commit;
4774 unsigned long lineno;
4775 char text[1];
4778 struct blame_state {
4779 struct blame_commit *commit;
4780 int blamed;
4781 bool done_reading;
4782 bool auto_filename_display;
4785 static bool
4786 blame_detect_filename_display(struct view *view)
4788 bool show_filenames = FALSE;
4789 const char *filename = NULL;
4790 int i;
4792 if (opt_blame_argv) {
4793 for (i = 0; opt_blame_argv[i]; i++) {
4794 if (prefixcmp(opt_blame_argv[i], "-C"))
4795 continue;
4797 show_filenames = TRUE;
4801 for (i = 0; i < view->lines; i++) {
4802 struct blame *blame = view->line[i].data;
4804 if (blame->commit && blame->commit->id[0]) {
4805 if (!filename)
4806 filename = blame->commit->filename;
4807 else if (strcmp(filename, blame->commit->filename))
4808 show_filenames = TRUE;
4812 return show_filenames;
4815 static bool
4816 blame_open(struct view *view, enum open_flags flags)
4818 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4819 char path[SIZEOF_STR];
4820 size_t i;
4822 if (!view->prev && *opt_prefix) {
4823 string_copy(path, opt_file);
4824 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4825 return FALSE;
4828 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4829 const char *blame_cat_file_argv[] = {
4830 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4833 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4834 return FALSE;
4837 /* First pass: remove multiple references to the same commit. */
4838 for (i = 0; i < view->lines; i++) {
4839 struct blame *blame = view->line[i].data;
4841 if (blame->commit && blame->commit->id[0])
4842 blame->commit->id[0] = 0;
4843 else
4844 blame->commit = NULL;
4847 /* Second pass: free existing references. */
4848 for (i = 0; i < view->lines; i++) {
4849 struct blame *blame = view->line[i].data;
4851 if (blame->commit)
4852 free(blame->commit);
4855 string_format(view->vid, "%s", opt_file);
4856 string_format(view->ref, "%s ...", opt_file);
4858 return TRUE;
4861 static struct blame_commit *
4862 get_blame_commit(struct view *view, const char *id)
4864 size_t i;
4866 for (i = 0; i < view->lines; i++) {
4867 struct blame *blame = view->line[i].data;
4869 if (!blame->commit)
4870 continue;
4872 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4873 return blame->commit;
4877 struct blame_commit *commit = calloc(1, sizeof(*commit));
4879 if (commit)
4880 string_ncopy(commit->id, id, SIZEOF_REV);
4881 return commit;
4885 static struct blame_commit *
4886 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
4888 struct blame_header header;
4889 struct blame_commit *commit;
4890 struct blame *blame;
4892 if (!parse_blame_header(&header, text, view->lines))
4893 return NULL;
4895 commit = get_blame_commit(view, text);
4896 if (!commit)
4897 return NULL;
4899 state->blamed += header.group;
4900 while (header.group--) {
4901 struct line *line = &view->line[header.lineno + header.group - 1];
4903 blame = line->data;
4904 blame->commit = commit;
4905 blame->lineno = header.orig_lineno + header.group - 1;
4906 line->dirty = 1;
4909 return commit;
4912 static bool
4913 blame_read_file(struct view *view, const char *line, struct blame_state *state)
4915 if (!line) {
4916 const char *blame_argv[] = {
4917 "git", "blame", "%(blameargs)", "--incremental",
4918 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4921 if (view->lines == 0 && !view->prev)
4922 die("No blame exist for %s", view->vid);
4924 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
4925 report("Failed to load blame data");
4926 return TRUE;
4929 if (opt_goto_line > 0) {
4930 select_view_line(view, opt_goto_line);
4931 opt_goto_line = 0;
4934 state->done_reading = TRUE;
4935 return FALSE;
4937 } else {
4938 size_t linelen = strlen(line);
4939 struct blame *blame = malloc(sizeof(*blame) + linelen);
4941 if (!blame)
4942 return FALSE;
4944 blame->commit = NULL;
4945 strncpy(blame->text, line, linelen);
4946 blame->text[linelen] = 0;
4947 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4951 static bool
4952 blame_read(struct view *view, char *line)
4954 struct blame_state *state = view->private;
4956 if (!state->done_reading)
4957 return blame_read_file(view, line, state);
4959 if (!line) {
4960 state->auto_filename_display = blame_detect_filename_display(view);
4961 string_format(view->ref, "%s", view->vid);
4962 if (view_is_displayed(view)) {
4963 update_view_title(view);
4964 redraw_view_from(view, 0);
4966 return TRUE;
4969 if (!state->commit) {
4970 state->commit = read_blame_commit(view, line, state);
4971 string_format(view->ref, "%s %2d%%", view->vid,
4972 view->lines ? state->blamed * 100 / view->lines : 0);
4974 } else if (parse_blame_info(state->commit, line)) {
4975 state->commit = NULL;
4978 return TRUE;
4981 static bool
4982 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4984 struct blame_state *state = view->private;
4985 struct blame *blame = line->data;
4986 struct time *time = NULL;
4987 const char *id = NULL, *author = NULL, *filename = NULL;
4988 enum line_type id_type = LINE_BLAME_ID;
4989 static const enum line_type blame_colors[] = {
4990 LINE_PALETTE_0,
4991 LINE_PALETTE_1,
4992 LINE_PALETTE_2,
4993 LINE_PALETTE_3,
4994 LINE_PALETTE_4,
4995 LINE_PALETTE_5,
4996 LINE_PALETTE_6,
4999 #define BLAME_COLOR(i) \
5000 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5002 if (blame->commit && *blame->commit->filename) {
5003 id = blame->commit->id;
5004 author = blame->commit->author;
5005 filename = blame->commit->filename;
5006 time = &blame->commit->time;
5007 id_type = BLAME_COLOR((long) blame->commit);
5010 if (draw_date(view, time))
5011 return TRUE;
5013 if (draw_author(view, author))
5014 return TRUE;
5016 if (draw_filename(view, filename, state->auto_filename_display))
5017 return TRUE;
5019 if (draw_field(view, id_type, id, ID_COLS, FALSE))
5020 return TRUE;
5022 if (draw_lineno(view, lineno))
5023 return TRUE;
5025 draw_text(view, LINE_DEFAULT, blame->text);
5026 return TRUE;
5029 static bool
5030 check_blame_commit(struct blame *blame, bool check_null_id)
5032 if (!blame->commit)
5033 report("Commit data not loaded yet");
5034 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
5035 report("No commit exist for the selected line");
5036 else
5037 return TRUE;
5038 return FALSE;
5041 static void
5042 setup_blame_parent_line(struct view *view, struct blame *blame)
5044 char from[SIZEOF_REF + SIZEOF_STR];
5045 char to[SIZEOF_REF + SIZEOF_STR];
5046 const char *diff_tree_argv[] = {
5047 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
5048 "-U0", from, to, "--", NULL
5050 struct io io;
5051 int parent_lineno = -1;
5052 int blamed_lineno = -1;
5053 char *line;
5055 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5056 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5057 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5058 return;
5060 while ((line = io_get(&io, '\n', TRUE))) {
5061 if (*line == '@') {
5062 char *pos = strchr(line, '+');
5064 parent_lineno = atoi(line + 4);
5065 if (pos)
5066 blamed_lineno = atoi(pos + 1);
5068 } else if (*line == '+' && parent_lineno != -1) {
5069 if (blame->lineno == blamed_lineno - 1 &&
5070 !strcmp(blame->text, line + 1)) {
5071 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
5072 break;
5074 blamed_lineno++;
5078 io_done(&io);
5081 static enum request
5082 blame_request(struct view *view, enum request request, struct line *line)
5084 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5085 struct blame *blame = line->data;
5087 switch (request) {
5088 case REQ_VIEW_BLAME:
5089 if (check_blame_commit(blame, TRUE)) {
5090 string_copy(opt_ref, blame->commit->id);
5091 string_copy(opt_file, blame->commit->filename);
5092 if (blame->lineno)
5093 view->lineno = blame->lineno;
5094 reload_view(view);
5096 break;
5098 case REQ_PARENT:
5099 if (!check_blame_commit(blame, TRUE))
5100 break;
5101 if (!*blame->commit->parent_id) {
5102 report("The selected commit has no parents");
5103 } else {
5104 string_copy_rev(opt_ref, blame->commit->parent_id);
5105 string_copy(opt_file, blame->commit->parent_filename);
5106 setup_blame_parent_line(view, blame);
5107 opt_goto_line = blame->lineno;
5108 reload_view(view);
5110 break;
5112 case REQ_ENTER:
5113 if (!check_blame_commit(blame, FALSE))
5114 break;
5116 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5117 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5118 break;
5120 if (!strcmp(blame->commit->id, NULL_ID)) {
5121 struct view *diff = VIEW(REQ_VIEW_DIFF);
5122 const char *diff_index_argv[] = {
5123 "git", "diff-index", "--root", "--patch-with-stat",
5124 "-C", "-M", opt_diff_context_arg,
5125 opt_ignore_space_arg,
5126 "HEAD", "--", view->vid, NULL
5129 if (!*blame->commit->parent_id) {
5130 diff_index_argv[1] = "diff";
5131 diff_index_argv[2] = "--no-color";
5132 diff_index_argv[8] = "--";
5133 diff_index_argv[9] = "/dev/null";
5136 open_argv(view, diff, diff_index_argv, NULL, flags);
5137 if (diff->pipe)
5138 string_copy_rev(diff->ref, NULL_ID);
5139 } else {
5140 open_view(view, REQ_VIEW_DIFF, flags);
5142 break;
5144 default:
5145 return request;
5148 return REQ_NONE;
5151 static bool
5152 blame_grep(struct view *view, struct line *line)
5154 struct blame *blame = line->data;
5155 struct blame_commit *commit = blame->commit;
5156 const char *text[] = {
5157 blame->text,
5158 commit ? commit->title : "",
5159 commit ? commit->id : "",
5160 commit && opt_author ? commit->author : "",
5161 commit ? mkdate(&commit->time, opt_date) : "",
5162 NULL
5165 return grep_text(view, text);
5168 static void
5169 blame_select(struct view *view, struct line *line)
5171 struct blame *blame = line->data;
5172 struct blame_commit *commit = blame->commit;
5174 if (!commit)
5175 return;
5177 if (!strcmp(commit->id, NULL_ID))
5178 string_ncopy(ref_commit, "HEAD", 4);
5179 else
5180 string_copy_rev(ref_commit, commit->id);
5183 static struct view_ops blame_ops = {
5184 "line",
5185 VIEW_ALWAYS_LINENO,
5186 sizeof(struct blame_state),
5187 blame_open,
5188 blame_read,
5189 blame_draw,
5190 blame_request,
5191 blame_grep,
5192 blame_select,
5196 * Branch backend
5199 struct branch {
5200 const char *author; /* Author of the last commit. */
5201 struct time time; /* Date of the last activity. */
5202 const struct ref *ref; /* Name and commit ID information. */
5205 static const struct ref branch_all;
5207 static const enum sort_field branch_sort_fields[] = {
5208 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5210 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5212 struct branch_state {
5213 char id[SIZEOF_REV];
5216 static int
5217 branch_compare(const void *l1, const void *l2)
5219 const struct branch *branch1 = ((const struct line *) l1)->data;
5220 const struct branch *branch2 = ((const struct line *) l2)->data;
5222 if (branch1->ref == &branch_all)
5223 return -1;
5224 else if (branch2->ref == &branch_all)
5225 return 1;
5227 switch (get_sort_field(branch_sort_state)) {
5228 case ORDERBY_DATE:
5229 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5231 case ORDERBY_AUTHOR:
5232 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5234 case ORDERBY_NAME:
5235 default:
5236 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5240 static bool
5241 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5243 struct branch *branch = line->data;
5244 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5246 if (draw_date(view, &branch->time))
5247 return TRUE;
5249 if (draw_author(view, branch->author))
5250 return TRUE;
5252 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
5253 return TRUE;
5256 static enum request
5257 branch_request(struct view *view, enum request request, struct line *line)
5259 struct branch *branch = line->data;
5261 switch (request) {
5262 case REQ_REFRESH:
5263 load_refs();
5264 refresh_view(view);
5265 return REQ_NONE;
5267 case REQ_TOGGLE_SORT_FIELD:
5268 case REQ_TOGGLE_SORT_ORDER:
5269 sort_view(view, request, &branch_sort_state, branch_compare);
5270 return REQ_NONE;
5272 case REQ_ENTER:
5274 const struct ref *ref = branch->ref;
5275 const char *all_branches_argv[] = {
5276 "git", "log", "--no-color", "--pretty=raw", "--parents",
5277 "--topo-order",
5278 ref == &branch_all ? "--all" : ref->name, NULL
5280 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5282 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5283 return REQ_NONE;
5285 case REQ_JUMP_COMMIT:
5287 int lineno;
5289 for (lineno = 0; lineno < view->lines; lineno++) {
5290 struct branch *branch = view->line[lineno].data;
5292 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5293 select_view_line(view, lineno);
5294 report("");
5295 return REQ_NONE;
5299 default:
5300 return request;
5304 static bool
5305 branch_read(struct view *view, char *line)
5307 struct branch_state *state = view->private;
5308 struct branch *reference;
5309 size_t i;
5311 if (!line)
5312 return TRUE;
5314 switch (get_line_type(line)) {
5315 case LINE_COMMIT:
5316 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5317 return TRUE;
5319 case LINE_AUTHOR:
5320 for (i = 0, reference = NULL; i < view->lines; i++) {
5321 struct branch *branch = view->line[i].data;
5323 if (strcmp(branch->ref->id, state->id))
5324 continue;
5326 view->line[i].dirty = TRUE;
5327 if (reference) {
5328 branch->author = reference->author;
5329 branch->time = reference->time;
5330 continue;
5333 parse_author_line(line + STRING_SIZE("author "),
5334 &branch->author, &branch->time);
5335 reference = branch;
5337 return TRUE;
5339 default:
5340 return TRUE;
5345 static bool
5346 branch_open_visitor(void *data, const struct ref *ref)
5348 struct view *view = data;
5349 struct branch *branch;
5351 if (ref->tag || ref->ltag)
5352 return TRUE;
5354 branch = calloc(1, sizeof(*branch));
5355 if (!branch)
5356 return FALSE;
5358 branch->ref = ref;
5359 return !!add_line_data(view, branch, LINE_DEFAULT);
5362 static bool
5363 branch_open(struct view *view, enum open_flags flags)
5365 const char *branch_log[] = {
5366 "git", "log", "--no-color", "--pretty=raw",
5367 "--simplify-by-decoration", "--all", NULL
5370 if (!begin_update(view, NULL, branch_log, flags)) {
5371 report("Failed to load branch data");
5372 return TRUE;
5375 branch_open_visitor(view, &branch_all);
5376 foreach_ref(branch_open_visitor, view);
5377 view->p_restore = TRUE;
5379 return TRUE;
5382 static bool
5383 branch_grep(struct view *view, struct line *line)
5385 struct branch *branch = line->data;
5386 const char *text[] = {
5387 branch->ref->name,
5388 mkauthor(branch->author, opt_author_cols, opt_author),
5389 NULL
5392 return grep_text(view, text);
5395 static void
5396 branch_select(struct view *view, struct line *line)
5398 struct branch *branch = line->data;
5400 string_copy_rev(view->ref, branch->ref->id);
5401 string_copy_rev(ref_commit, branch->ref->id);
5402 string_copy_rev(ref_head, branch->ref->id);
5403 string_copy_rev(ref_branch, branch->ref->name);
5406 static struct view_ops branch_ops = {
5407 "branch",
5408 VIEW_NO_FLAGS,
5409 sizeof(struct branch_state),
5410 branch_open,
5411 branch_read,
5412 branch_draw,
5413 branch_request,
5414 branch_grep,
5415 branch_select,
5419 * Status backend
5422 struct status {
5423 char status;
5424 struct {
5425 mode_t mode;
5426 char rev[SIZEOF_REV];
5427 char name[SIZEOF_STR];
5428 } old;
5429 struct {
5430 mode_t mode;
5431 char rev[SIZEOF_REV];
5432 char name[SIZEOF_STR];
5433 } new;
5436 static char status_onbranch[SIZEOF_STR];
5437 static struct status stage_status;
5438 static enum line_type stage_line_type;
5440 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5442 /* This should work even for the "On branch" line. */
5443 static inline bool
5444 status_has_none(struct view *view, struct line *line)
5446 return line < view->line + view->lines && !line[1].data;
5449 /* Get fields from the diff line:
5450 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5452 static inline bool
5453 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5455 const char *old_mode = buf + 1;
5456 const char *new_mode = buf + 8;
5457 const char *old_rev = buf + 15;
5458 const char *new_rev = buf + 56;
5459 const char *status = buf + 97;
5461 if (bufsize < 98 ||
5462 old_mode[-1] != ':' ||
5463 new_mode[-1] != ' ' ||
5464 old_rev[-1] != ' ' ||
5465 new_rev[-1] != ' ' ||
5466 status[-1] != ' ')
5467 return FALSE;
5469 file->status = *status;
5471 string_copy_rev(file->old.rev, old_rev);
5472 string_copy_rev(file->new.rev, new_rev);
5474 file->old.mode = strtoul(old_mode, NULL, 8);
5475 file->new.mode = strtoul(new_mode, NULL, 8);
5477 file->old.name[0] = file->new.name[0] = 0;
5479 return TRUE;
5482 static bool
5483 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5485 struct status *unmerged = NULL;
5486 char *buf;
5487 struct io io;
5489 if (!io_run(&io, IO_RD, opt_cdup, argv))
5490 return FALSE;
5492 add_line_data(view, NULL, type);
5494 while ((buf = io_get(&io, 0, TRUE))) {
5495 struct status *file = unmerged;
5497 if (!file) {
5498 file = calloc(1, sizeof(*file));
5499 if (!file || !add_line_data(view, file, type))
5500 goto error_out;
5503 /* Parse diff info part. */
5504 if (status) {
5505 file->status = status;
5506 if (status == 'A')
5507 string_copy(file->old.rev, NULL_ID);
5509 } else if (!file->status || file == unmerged) {
5510 if (!status_get_diff(file, buf, strlen(buf)))
5511 goto error_out;
5513 buf = io_get(&io, 0, TRUE);
5514 if (!buf)
5515 break;
5517 /* Collapse all modified entries that follow an
5518 * associated unmerged entry. */
5519 if (unmerged == file) {
5520 unmerged->status = 'U';
5521 unmerged = NULL;
5522 } else if (file->status == 'U') {
5523 unmerged = file;
5527 /* Grab the old name for rename/copy. */
5528 if (!*file->old.name &&
5529 (file->status == 'R' || file->status == 'C')) {
5530 string_ncopy(file->old.name, buf, strlen(buf));
5532 buf = io_get(&io, 0, TRUE);
5533 if (!buf)
5534 break;
5537 /* git-ls-files just delivers a NUL separated list of
5538 * file names similar to the second half of the
5539 * git-diff-* output. */
5540 string_ncopy(file->new.name, buf, strlen(buf));
5541 if (!*file->old.name)
5542 string_copy(file->old.name, file->new.name);
5543 file = NULL;
5546 if (io_error(&io)) {
5547 error_out:
5548 io_done(&io);
5549 return FALSE;
5552 if (!view->line[view->lines - 1].data)
5553 add_line_data(view, NULL, LINE_STAT_NONE);
5555 io_done(&io);
5556 return TRUE;
5559 /* Don't show unmerged entries in the staged section. */
5560 static const char *status_diff_index_argv[] = {
5561 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
5562 "--cached", "-M", "HEAD", NULL
5565 static const char *status_diff_files_argv[] = {
5566 "git", "diff-files", "-z", NULL
5569 static const char *status_list_other_argv[] = {
5570 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5573 static const char *status_list_no_head_argv[] = {
5574 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5577 static const char *update_index_argv[] = {
5578 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5581 /* Restore the previous line number to stay in the context or select a
5582 * line with something that can be updated. */
5583 static void
5584 status_restore(struct view *view)
5586 if (view->p_lineno >= view->lines)
5587 view->p_lineno = view->lines - 1;
5588 while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
5589 view->p_lineno++;
5590 while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
5591 view->p_lineno--;
5593 /* If the above fails, always skip the "On branch" line. */
5594 if (view->p_lineno < view->lines)
5595 view->lineno = view->p_lineno;
5596 else
5597 view->lineno = 1;
5599 if (view->lineno < view->offset)
5600 view->offset = view->lineno;
5601 else if (view->offset + view->height <= view->lineno)
5602 view->offset = view->lineno - view->height + 1;
5604 view->p_restore = FALSE;
5607 static void
5608 status_update_onbranch(void)
5610 static const char *paths[][2] = {
5611 { "rebase-apply/rebasing", "Rebasing" },
5612 { "rebase-apply/applying", "Applying mailbox" },
5613 { "rebase-apply/", "Rebasing mailbox" },
5614 { "rebase-merge/interactive", "Interactive rebase" },
5615 { "rebase-merge/", "Rebase merge" },
5616 { "MERGE_HEAD", "Merging" },
5617 { "BISECT_LOG", "Bisecting" },
5618 { "HEAD", "On branch" },
5620 char buf[SIZEOF_STR];
5621 struct stat stat;
5622 int i;
5624 if (is_initial_commit()) {
5625 string_copy(status_onbranch, "Initial commit");
5626 return;
5629 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5630 char *head = opt_head;
5632 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5633 lstat(buf, &stat) < 0)
5634 continue;
5636 if (!*opt_head) {
5637 struct io io;
5639 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5640 io_read_buf(&io, buf, sizeof(buf))) {
5641 head = buf;
5642 if (!prefixcmp(head, "refs/heads/"))
5643 head += STRING_SIZE("refs/heads/");
5647 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5648 string_copy(status_onbranch, opt_head);
5649 return;
5652 string_copy(status_onbranch, "Not currently on any branch");
5655 /* First parse staged info using git-diff-index(1), then parse unstaged
5656 * info using git-diff-files(1), and finally untracked files using
5657 * git-ls-files(1). */
5658 static bool
5659 status_open(struct view *view, enum open_flags flags)
5661 reset_view(view);
5663 add_line_data(view, NULL, LINE_STAT_HEAD);
5664 status_update_onbranch();
5666 io_run_bg(update_index_argv);
5668 if (is_initial_commit()) {
5669 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5670 return FALSE;
5671 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5672 return FALSE;
5675 if (!opt_untracked_dirs_content)
5676 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5678 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5679 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5680 return FALSE;
5682 /* Restore the exact position or use the specialized restore
5683 * mode? */
5684 if (!view->p_restore)
5685 status_restore(view);
5686 return TRUE;
5689 static bool
5690 status_draw(struct view *view, struct line *line, unsigned int lineno)
5692 struct status *status = line->data;
5693 enum line_type type;
5694 const char *text;
5696 if (!status) {
5697 switch (line->type) {
5698 case LINE_STAT_STAGED:
5699 type = LINE_STAT_SECTION;
5700 text = "Changes to be committed:";
5701 break;
5703 case LINE_STAT_UNSTAGED:
5704 type = LINE_STAT_SECTION;
5705 text = "Changed but not updated:";
5706 break;
5708 case LINE_STAT_UNTRACKED:
5709 type = LINE_STAT_SECTION;
5710 text = "Untracked files:";
5711 break;
5713 case LINE_STAT_NONE:
5714 type = LINE_DEFAULT;
5715 text = " (no files)";
5716 break;
5718 case LINE_STAT_HEAD:
5719 type = LINE_STAT_HEAD;
5720 text = status_onbranch;
5721 break;
5723 default:
5724 return FALSE;
5726 } else {
5727 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5729 buf[0] = status->status;
5730 if (draw_text(view, line->type, buf))
5731 return TRUE;
5732 type = LINE_DEFAULT;
5733 text = status->new.name;
5736 draw_text(view, type, text);
5737 return TRUE;
5740 static enum request
5741 status_enter(struct view *view, struct line *line)
5743 struct status *status = line->data;
5744 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5746 if (line->type == LINE_STAT_NONE ||
5747 (!status && line[1].type == LINE_STAT_NONE)) {
5748 report("No file to diff");
5749 return REQ_NONE;
5752 switch (line->type) {
5753 case LINE_STAT_STAGED:
5754 case LINE_STAT_UNSTAGED:
5755 break;
5757 case LINE_STAT_UNTRACKED:
5758 if (!status) {
5759 report("No file to show");
5760 return REQ_NONE;
5763 if (!suffixcmp(status->new.name, -1, "/")) {
5764 report("Cannot display a directory");
5765 return REQ_NONE;
5767 break;
5769 case LINE_STAT_HEAD:
5770 return REQ_NONE;
5772 default:
5773 die("line type %d not handled in switch", line->type);
5776 if (status) {
5777 stage_status = *status;
5778 } else {
5779 memset(&stage_status, 0, sizeof(stage_status));
5782 stage_line_type = line->type;
5784 open_view(view, REQ_VIEW_STAGE, flags);
5785 return REQ_NONE;
5788 static bool
5789 status_exists(struct view *view, struct status *status, enum line_type type)
5791 unsigned long lineno;
5793 for (lineno = 0; lineno < view->lines; lineno++) {
5794 struct line *line = &view->line[lineno];
5795 struct status *pos = line->data;
5797 if (line->type != type)
5798 continue;
5799 if (!pos && (!status || !status->status) && line[1].data) {
5800 select_view_line(view, lineno);
5801 return TRUE;
5803 if (pos && !strcmp(status->new.name, pos->new.name)) {
5804 select_view_line(view, lineno);
5805 return TRUE;
5809 return FALSE;
5813 static bool
5814 status_update_prepare(struct io *io, enum line_type type)
5816 const char *staged_argv[] = {
5817 "git", "update-index", "-z", "--index-info", NULL
5819 const char *others_argv[] = {
5820 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5823 switch (type) {
5824 case LINE_STAT_STAGED:
5825 return io_run(io, IO_WR, opt_cdup, staged_argv);
5827 case LINE_STAT_UNSTAGED:
5828 case LINE_STAT_UNTRACKED:
5829 return io_run(io, IO_WR, opt_cdup, others_argv);
5831 default:
5832 die("line type %d not handled in switch", type);
5833 return FALSE;
5837 static bool
5838 status_update_write(struct io *io, struct status *status, enum line_type type)
5840 switch (type) {
5841 case LINE_STAT_STAGED:
5842 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
5843 status->old.rev, status->old.name, 0);
5845 case LINE_STAT_UNSTAGED:
5846 case LINE_STAT_UNTRACKED:
5847 return io_printf(io, "%s%c", status->new.name, 0);
5849 default:
5850 die("line type %d not handled in switch", type);
5851 return FALSE;
5855 static bool
5856 status_update_file(struct status *status, enum line_type type)
5858 struct io io;
5859 bool result;
5861 if (!status_update_prepare(&io, type))
5862 return FALSE;
5864 result = status_update_write(&io, status, type);
5865 return io_done(&io) && result;
5868 static bool
5869 status_update_files(struct view *view, struct line *line)
5871 char buf[sizeof(view->ref)];
5872 struct io io;
5873 bool result = TRUE;
5874 struct line *pos = view->line + view->lines;
5875 int files = 0;
5876 int file, done;
5877 int cursor_y = -1, cursor_x = -1;
5879 if (!status_update_prepare(&io, line->type))
5880 return FALSE;
5882 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5883 files++;
5885 string_copy(buf, view->ref);
5886 getsyx(cursor_y, cursor_x);
5887 for (file = 0, done = 5; result && file < files; line++, file++) {
5888 int almost_done = file * 100 / files;
5890 if (almost_done > done) {
5891 done = almost_done;
5892 string_format(view->ref, "updating file %u of %u (%d%% done)",
5893 file, files, done);
5894 update_view_title(view);
5895 setsyx(cursor_y, cursor_x);
5896 doupdate();
5898 result = status_update_write(&io, line->data, line->type);
5900 string_copy(view->ref, buf);
5902 return io_done(&io) && result;
5905 static bool
5906 status_update(struct view *view)
5908 struct line *line = &view->line[view->lineno];
5910 assert(view->lines);
5912 if (!line->data) {
5913 /* This should work even for the "On branch" line. */
5914 if (line < view->line + view->lines && !line[1].data) {
5915 report("Nothing to update");
5916 return FALSE;
5919 if (!status_update_files(view, line + 1)) {
5920 report("Failed to update file status");
5921 return FALSE;
5924 } else if (!status_update_file(line->data, line->type)) {
5925 report("Failed to update file status");
5926 return FALSE;
5929 return TRUE;
5932 static bool
5933 status_revert(struct status *status, enum line_type type, bool has_none)
5935 if (!status || type != LINE_STAT_UNSTAGED) {
5936 if (type == LINE_STAT_STAGED) {
5937 report("Cannot revert changes to staged files");
5938 } else if (type == LINE_STAT_UNTRACKED) {
5939 report("Cannot revert changes to untracked files");
5940 } else if (has_none) {
5941 report("Nothing to revert");
5942 } else {
5943 report("Cannot revert changes to multiple files");
5946 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5947 char mode[10] = "100644";
5948 const char *reset_argv[] = {
5949 "git", "update-index", "--cacheinfo", mode,
5950 status->old.rev, status->old.name, NULL
5952 const char *checkout_argv[] = {
5953 "git", "checkout", "--", status->old.name, NULL
5956 if (status->status == 'U') {
5957 string_format(mode, "%5o", status->old.mode);
5959 if (status->old.mode == 0 && status->new.mode == 0) {
5960 reset_argv[2] = "--force-remove";
5961 reset_argv[3] = status->old.name;
5962 reset_argv[4] = NULL;
5965 if (!io_run_fg(reset_argv, opt_cdup))
5966 return FALSE;
5967 if (status->old.mode == 0 && status->new.mode == 0)
5968 return TRUE;
5971 return io_run_fg(checkout_argv, opt_cdup);
5974 return FALSE;
5977 static enum request
5978 status_request(struct view *view, enum request request, struct line *line)
5980 struct status *status = line->data;
5982 switch (request) {
5983 case REQ_STATUS_UPDATE:
5984 if (!status_update(view))
5985 return REQ_NONE;
5986 break;
5988 case REQ_STATUS_REVERT:
5989 if (!status_revert(status, line->type, status_has_none(view, line)))
5990 return REQ_NONE;
5991 break;
5993 case REQ_STATUS_MERGE:
5994 if (!status || status->status != 'U') {
5995 report("Merging only possible for files with unmerged status ('U').");
5996 return REQ_NONE;
5998 open_mergetool(status->new.name);
5999 break;
6001 case REQ_EDIT:
6002 if (!status)
6003 return request;
6004 if (status->status == 'D') {
6005 report("File has been deleted.");
6006 return REQ_NONE;
6009 open_editor(status->new.name);
6010 break;
6012 case REQ_VIEW_BLAME:
6013 if (status)
6014 opt_ref[0] = 0;
6015 return request;
6017 case REQ_ENTER:
6018 /* After returning the status view has been split to
6019 * show the stage view. No further reloading is
6020 * necessary. */
6021 return status_enter(view, line);
6023 case REQ_REFRESH:
6024 /* Simply reload the view. */
6025 break;
6027 default:
6028 return request;
6031 refresh_view(view);
6033 return REQ_NONE;
6036 static void
6037 status_select(struct view *view, struct line *line)
6039 struct status *status = line->data;
6040 char file[SIZEOF_STR] = "all files";
6041 const char *text;
6042 const char *key;
6044 if (status && !string_format(file, "'%s'", status->new.name))
6045 return;
6047 if (!status && line[1].type == LINE_STAT_NONE)
6048 line++;
6050 switch (line->type) {
6051 case LINE_STAT_STAGED:
6052 text = "Press %s to unstage %s for commit";
6053 break;
6055 case LINE_STAT_UNSTAGED:
6056 text = "Press %s to stage %s for commit";
6057 break;
6059 case LINE_STAT_UNTRACKED:
6060 text = "Press %s to stage %s for addition";
6061 break;
6063 case LINE_STAT_HEAD:
6064 case LINE_STAT_NONE:
6065 text = "Nothing to update";
6066 break;
6068 default:
6069 die("line type %d not handled in switch", line->type);
6072 if (status && status->status == 'U') {
6073 text = "Press %s to resolve conflict in %s";
6074 key = get_view_key(view, REQ_STATUS_MERGE);
6076 } else {
6077 key = get_view_key(view, REQ_STATUS_UPDATE);
6080 string_format(view->ref, text, key, file);
6081 if (status)
6082 string_copy(opt_file, status->new.name);
6085 static bool
6086 status_grep(struct view *view, struct line *line)
6088 struct status *status = line->data;
6090 if (status) {
6091 const char buf[2] = { status->status, 0 };
6092 const char *text[] = { status->new.name, buf, NULL };
6094 return grep_text(view, text);
6097 return FALSE;
6100 static struct view_ops status_ops = {
6101 "file",
6102 VIEW_CUSTOM_STATUS,
6104 status_open,
6105 NULL,
6106 status_draw,
6107 status_request,
6108 status_grep,
6109 status_select,
6113 struct stage_state {
6114 struct diff_state diff;
6115 size_t chunks;
6116 int *chunk;
6119 static bool
6120 stage_diff_write(struct io *io, struct line *line, struct line *end)
6122 while (line < end) {
6123 if (!io_write(io, line->data, strlen(line->data)) ||
6124 !io_write(io, "\n", 1))
6125 return FALSE;
6126 line++;
6127 if (line->type == LINE_DIFF_CHUNK ||
6128 line->type == LINE_DIFF_HEADER)
6129 break;
6132 return TRUE;
6135 static bool
6136 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6138 const char *apply_argv[SIZEOF_ARG] = {
6139 "git", "apply", "--whitespace=nowarn", NULL
6141 struct line *diff_hdr;
6142 struct io io;
6143 int argc = 3;
6145 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6146 if (!diff_hdr)
6147 return FALSE;
6149 if (!revert)
6150 apply_argv[argc++] = "--cached";
6151 if (line != NULL)
6152 apply_argv[argc++] = "--unidiff-zero";
6153 if (revert || stage_line_type == LINE_STAT_STAGED)
6154 apply_argv[argc++] = "-R";
6155 apply_argv[argc++] = "-";
6156 apply_argv[argc++] = NULL;
6157 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6158 return FALSE;
6160 if (line != NULL) {
6161 int lineno = 0;
6162 struct line *context = chunk + 1;
6163 const char *markers[] = {
6164 line->type == LINE_DIFF_DEL ? "" : ",0",
6165 line->type == LINE_DIFF_DEL ? ",0" : "",
6168 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6170 while (context < line) {
6171 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6172 break;
6173 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6174 lineno++;
6176 context++;
6179 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6180 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6181 lineno, markers[0], lineno, markers[1]) ||
6182 !stage_diff_write(&io, line, line + 1)) {
6183 chunk = NULL;
6185 } else {
6186 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6187 !stage_diff_write(&io, chunk, view->line + view->lines))
6188 chunk = NULL;
6191 io_done(&io);
6192 io_run_bg(update_index_argv);
6194 return chunk ? TRUE : FALSE;
6197 static bool
6198 stage_update(struct view *view, struct line *line, bool single)
6200 struct line *chunk = NULL;
6202 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6203 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6205 if (chunk) {
6206 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6207 report("Failed to apply chunk");
6208 return FALSE;
6211 } else if (!stage_status.status) {
6212 view = view->parent;
6214 for (line = view->line; line < view->line + view->lines; line++)
6215 if (line->type == stage_line_type)
6216 break;
6218 if (!status_update_files(view, line + 1)) {
6219 report("Failed to update files");
6220 return FALSE;
6223 } else if (!status_update_file(&stage_status, stage_line_type)) {
6224 report("Failed to update file");
6225 return FALSE;
6228 return TRUE;
6231 static bool
6232 stage_revert(struct view *view, struct line *line)
6234 struct line *chunk = NULL;
6236 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6237 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6239 if (chunk) {
6240 if (!prompt_yesno("Are you sure you want to revert changes?"))
6241 return FALSE;
6243 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6244 report("Failed to revert chunk");
6245 return FALSE;
6247 return TRUE;
6249 } else {
6250 return status_revert(stage_status.status ? &stage_status : NULL,
6251 stage_line_type, FALSE);
6256 static void
6257 stage_next(struct view *view, struct line *line)
6259 struct stage_state *state = view->private;
6260 int i;
6262 if (!state->chunks) {
6263 for (line = view->line; line < view->line + view->lines; line++) {
6264 if (line->type != LINE_DIFF_CHUNK)
6265 continue;
6267 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6268 report("Allocation failure");
6269 return;
6272 state->chunk[state->chunks++] = line - view->line;
6276 for (i = 0; i < state->chunks; i++) {
6277 if (state->chunk[i] > view->lineno) {
6278 do_scroll_view(view, state->chunk[i] - view->lineno);
6279 report("Chunk %d of %d", i + 1, state->chunks);
6280 return;
6284 report("No next chunk found");
6287 static enum request
6288 stage_request(struct view *view, enum request request, struct line *line)
6290 switch (request) {
6291 case REQ_STATUS_UPDATE:
6292 if (!stage_update(view, line, FALSE))
6293 return REQ_NONE;
6294 break;
6296 case REQ_STATUS_REVERT:
6297 if (!stage_revert(view, line))
6298 return REQ_NONE;
6299 break;
6301 case REQ_STAGE_UPDATE_LINE:
6302 if (stage_line_type == LINE_STAT_UNTRACKED ||
6303 stage_status.status == 'A') {
6304 report("Staging single lines is not supported for new files");
6305 return REQ_NONE;
6307 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6308 report("Please select a change to stage");
6309 return REQ_NONE;
6311 if (!stage_update(view, line, TRUE))
6312 return REQ_NONE;
6313 break;
6315 case REQ_STAGE_NEXT:
6316 if (stage_line_type == LINE_STAT_UNTRACKED) {
6317 report("File is untracked; press %s to add",
6318 get_view_key(view, REQ_STATUS_UPDATE));
6319 return REQ_NONE;
6321 stage_next(view, line);
6322 return REQ_NONE;
6324 case REQ_EDIT:
6325 if (!stage_status.new.name[0])
6326 return request;
6327 if (stage_status.status == 'D') {
6328 report("File has been deleted.");
6329 return REQ_NONE;
6332 open_editor(stage_status.new.name);
6333 break;
6335 case REQ_REFRESH:
6336 /* Reload everything ... */
6337 break;
6339 case REQ_VIEW_BLAME:
6340 if (stage_status.new.name[0]) {
6341 string_copy(opt_file, stage_status.new.name);
6342 opt_ref[0] = 0;
6344 return request;
6346 case REQ_ENTER:
6347 return diff_common_enter(view, request, line);
6349 case REQ_DIFF_CONTEXT_UP:
6350 case REQ_DIFF_CONTEXT_DOWN:
6351 if (!update_diff_context(request))
6352 return REQ_NONE;
6353 break;
6355 default:
6356 return request;
6359 refresh_view(view->parent);
6361 /* Check whether the staged entry still exists, and close the
6362 * stage view if it doesn't. */
6363 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6364 status_restore(view->parent);
6365 return REQ_VIEW_CLOSE;
6368 refresh_view(view);
6370 return REQ_NONE;
6373 static bool
6374 stage_open(struct view *view, enum open_flags flags)
6376 static const char *no_head_diff_argv[] = {
6377 "git", "diff", "--no-color", "--patch-with-stat",
6378 opt_diff_context_arg, opt_ignore_space_arg,
6379 "--", "/dev/null", stage_status.new.name, NULL
6381 static const char *index_show_argv[] = {
6382 "git", "diff-index", "--root", "--patch-with-stat", "-C", "-M",
6383 "--cached", opt_diff_context_arg, opt_ignore_space_arg,
6384 "HEAD", "--",
6385 stage_status.old.name, stage_status.new.name, NULL
6387 static const char *files_show_argv[] = {
6388 "git", "diff-files", "--root", "--patch-with-stat", "-C", "-M",
6389 opt_diff_context_arg, opt_ignore_space_arg, "--",
6390 stage_status.old.name, stage_status.new.name, NULL
6392 /* Diffs for unmerged entries are empty when passing the new
6393 * path, so leave out the new path. */
6394 static const char *files_unmerged_argv[] = {
6395 "git", "diff-files", "--root", "--patch-with-stat", "-C", "-M",
6396 opt_diff_context_arg, opt_ignore_space_arg, "--",
6397 stage_status.old.name, NULL
6399 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6400 const char **argv = NULL;
6401 const char *info;
6403 view->encoding = NULL;
6405 switch (stage_line_type) {
6406 case LINE_STAT_STAGED:
6407 if (is_initial_commit()) {
6408 argv = no_head_diff_argv;
6409 } else {
6410 argv = index_show_argv;
6412 if (stage_status.status)
6413 info = "Staged changes to %s";
6414 else
6415 info = "Staged changes";
6416 break;
6418 case LINE_STAT_UNSTAGED:
6419 if (stage_status.status != 'U')
6420 argv = files_show_argv;
6421 else
6422 argv = files_unmerged_argv;
6423 if (stage_status.status)
6424 info = "Unstaged changes to %s";
6425 else
6426 info = "Unstaged changes";
6427 break;
6429 case LINE_STAT_UNTRACKED:
6430 info = "Untracked file %s";
6431 argv = file_argv;
6432 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
6433 break;
6435 case LINE_STAT_HEAD:
6436 default:
6437 die("line type %d not handled in switch", stage_line_type);
6440 string_format(view->ref, info, stage_status.new.name);
6441 view->vid[0] = 0;
6442 view->dir = opt_cdup;
6443 return argv_copy(&view->argv, argv)
6444 && begin_update(view, NULL, NULL, flags);
6447 static bool
6448 stage_read(struct view *view, char *data)
6450 struct stage_state *state = view->private;
6452 if (data && diff_common_read(view, data, &state->diff))
6453 return TRUE;
6455 return pager_read(view, data);
6458 static struct view_ops stage_ops = {
6459 "line",
6460 VIEW_NO_FLAGS,
6461 sizeof(struct stage_state),
6462 stage_open,
6463 stage_read,
6464 diff_common_draw,
6465 stage_request,
6466 pager_grep,
6467 pager_select,
6472 * Revision graph
6475 static const enum line_type graph_colors[] = {
6476 LINE_PALETTE_0,
6477 LINE_PALETTE_1,
6478 LINE_PALETTE_2,
6479 LINE_PALETTE_3,
6480 LINE_PALETTE_4,
6481 LINE_PALETTE_5,
6482 LINE_PALETTE_6,
6485 static enum line_type get_graph_color(struct graph_symbol *symbol)
6487 if (symbol->commit)
6488 return LINE_GRAPH_COMMIT;
6489 assert(symbol->color < ARRAY_SIZE(graph_colors));
6490 return graph_colors[symbol->color];
6493 static bool
6494 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6496 const char *chars = graph_symbol_to_utf8(symbol);
6498 return draw_text(view, color, chars + !!first);
6501 static bool
6502 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6504 const char *chars = graph_symbol_to_ascii(symbol);
6506 return draw_text(view, color, chars + !!first);
6509 static bool
6510 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6512 const chtype *chars = graph_symbol_to_chtype(symbol);
6514 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6517 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6519 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6521 static const draw_graph_fn fns[] = {
6522 draw_graph_ascii,
6523 draw_graph_chtype,
6524 draw_graph_utf8
6526 draw_graph_fn fn = fns[opt_line_graphics];
6527 int i;
6529 for (i = 0; i < canvas->size; i++) {
6530 struct graph_symbol *symbol = &canvas->symbols[i];
6531 enum line_type color = get_graph_color(symbol);
6533 if (fn(view, symbol, color, i == 0))
6534 return TRUE;
6537 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6541 * Main view backend
6544 struct commit {
6545 char id[SIZEOF_REV]; /* SHA1 ID. */
6546 char title[128]; /* First line of the commit message. */
6547 const char *author; /* Author of the commit. */
6548 struct time time; /* Date from the author ident. */
6549 struct ref_list *refs; /* Repository references. */
6550 struct graph_canvas graph; /* Ancestry chain graphics. */
6553 static bool
6554 main_open(struct view *view, enum open_flags flags)
6556 static const char *main_argv[] = {
6557 "git", "log", "--no-color", "--pretty=raw", "--parents",
6558 "--topo-order", "%(diffargs)", "%(revargs)",
6559 "--", "%(fileargs)", NULL
6562 return begin_update(view, NULL, main_argv, flags);
6565 static bool
6566 main_draw(struct view *view, struct line *line, unsigned int lineno)
6568 struct commit *commit = line->data;
6570 if (!commit->author)
6571 return FALSE;
6573 if (opt_line_number && draw_lineno(view, lineno))
6574 return TRUE;
6576 if (draw_date(view, &commit->time))
6577 return TRUE;
6579 if (draw_author(view, commit->author))
6580 return TRUE;
6582 if (opt_rev_graph && draw_graph(view, &commit->graph))
6583 return TRUE;
6585 if (draw_refs(view, commit->refs))
6586 return TRUE;
6588 draw_text(view, LINE_DEFAULT, commit->title);
6589 return TRUE;
6592 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6593 static bool
6594 main_read(struct view *view, char *line)
6596 struct graph *graph = view->private;
6597 enum line_type type;
6598 struct commit *commit;
6600 if (!line) {
6601 if (!view->lines && !view->prev)
6602 die("No revisions match the given arguments.");
6603 if (view->lines > 0) {
6604 commit = view->line[view->lines - 1].data;
6605 view->line[view->lines - 1].dirty = 1;
6606 if (!commit->author) {
6607 view->lines--;
6608 free(commit);
6612 done_graph(graph);
6613 return TRUE;
6616 type = get_line_type(line);
6617 if (type == LINE_COMMIT) {
6618 bool is_boundary;
6620 commit = calloc(1, sizeof(struct commit));
6621 if (!commit)
6622 return FALSE;
6624 line += STRING_SIZE("commit ");
6625 is_boundary = *line == '-';
6626 if (is_boundary)
6627 line++;
6629 string_copy_rev(commit->id, line);
6630 commit->refs = get_ref_list(commit->id);
6631 add_line_data(view, commit, LINE_MAIN_COMMIT);
6632 graph_add_commit(graph, &commit->graph, commit->id, line, is_boundary);
6633 return TRUE;
6636 if (!view->lines)
6637 return TRUE;
6638 commit = view->line[view->lines - 1].data;
6640 switch (type) {
6641 case LINE_PARENT:
6642 if (!graph->has_parents)
6643 graph_add_parent(graph, line + STRING_SIZE("parent "));
6644 break;
6646 case LINE_AUTHOR:
6647 parse_author_line(line + STRING_SIZE("author "),
6648 &commit->author, &commit->time);
6649 graph_render_parents(graph);
6650 break;
6652 default:
6653 /* Fill in the commit title if it has not already been set. */
6654 if (commit->title[0])
6655 break;
6657 /* Require titles to start with a non-space character at the
6658 * offset used by git log. */
6659 if (strncmp(line, " ", 4))
6660 break;
6661 line += 4;
6662 /* Well, if the title starts with a whitespace character,
6663 * try to be forgiving. Otherwise we end up with no title. */
6664 while (isspace(*line))
6665 line++;
6666 if (*line == '\0')
6667 break;
6668 /* FIXME: More graceful handling of titles; append "..." to
6669 * shortened titles, etc. */
6671 string_expand(commit->title, sizeof(commit->title), line, 1);
6672 view->line[view->lines - 1].dirty = 1;
6675 return TRUE;
6678 static enum request
6679 main_request(struct view *view, enum request request, struct line *line)
6681 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6683 switch (request) {
6684 case REQ_ENTER:
6685 if (view_is_displayed(view) && display[0] != view)
6686 maximize_view(view, TRUE);
6687 open_view(view, REQ_VIEW_DIFF, flags);
6688 break;
6689 case REQ_REFRESH:
6690 load_refs();
6691 refresh_view(view);
6692 break;
6694 case REQ_JUMP_COMMIT:
6696 int lineno;
6698 for (lineno = 0; lineno < view->lines; lineno++) {
6699 struct commit *commit = view->line[lineno].data;
6701 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
6702 select_view_line(view, lineno);
6703 report("");
6704 return REQ_NONE;
6708 report("Unable to find commit '%s'", opt_search);
6709 break;
6711 default:
6712 return request;
6715 return REQ_NONE;
6718 static bool
6719 grep_refs(struct ref_list *list, regex_t *regex)
6721 regmatch_t pmatch;
6722 size_t i;
6724 if (!opt_show_refs || !list)
6725 return FALSE;
6727 for (i = 0; i < list->size; i++) {
6728 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
6729 return TRUE;
6732 return FALSE;
6735 static bool
6736 main_grep(struct view *view, struct line *line)
6738 struct commit *commit = line->data;
6739 const char *text[] = {
6740 commit->title,
6741 mkauthor(commit->author, opt_author_cols, opt_author),
6742 mkdate(&commit->time, opt_date),
6743 NULL
6746 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
6749 static void
6750 main_select(struct view *view, struct line *line)
6752 struct commit *commit = line->data;
6754 string_copy_rev(view->ref, commit->id);
6755 string_copy_rev(ref_commit, view->ref);
6758 static struct view_ops main_ops = {
6759 "commit",
6760 VIEW_NO_FLAGS,
6761 sizeof(struct graph),
6762 main_open,
6763 main_read,
6764 main_draw,
6765 main_request,
6766 main_grep,
6767 main_select,
6772 * Status management
6775 /* Whether or not the curses interface has been initialized. */
6776 static bool cursed = FALSE;
6778 /* Terminal hacks and workarounds. */
6779 static bool use_scroll_redrawwin;
6780 static bool use_scroll_status_wclear;
6782 /* The status window is used for polling keystrokes. */
6783 static WINDOW *status_win;
6785 /* Reading from the prompt? */
6786 static bool input_mode = FALSE;
6788 static bool status_empty = FALSE;
6790 /* Update status and title window. */
6791 static void
6792 report(const char *msg, ...)
6794 struct view *view = display[current_view];
6796 if (input_mode)
6797 return;
6799 if (!view) {
6800 char buf[SIZEOF_STR];
6801 int retval;
6803 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
6804 die("%s", buf);
6807 if (!status_empty || *msg) {
6808 va_list args;
6810 va_start(args, msg);
6812 wmove(status_win, 0, 0);
6813 if (view->has_scrolled && use_scroll_status_wclear)
6814 wclear(status_win);
6815 if (*msg) {
6816 vwprintw(status_win, msg, args);
6817 status_empty = FALSE;
6818 } else {
6819 status_empty = TRUE;
6821 wclrtoeol(status_win);
6822 wnoutrefresh(status_win);
6824 va_end(args);
6827 update_view_title(view);
6830 static void
6831 init_display(void)
6833 const char *term;
6834 int x, y;
6836 /* Initialize the curses library */
6837 if (isatty(STDIN_FILENO)) {
6838 cursed = !!initscr();
6839 opt_tty = stdin;
6840 } else {
6841 /* Leave stdin and stdout alone when acting as a pager. */
6842 opt_tty = fopen("/dev/tty", "r+");
6843 if (!opt_tty)
6844 die("Failed to open /dev/tty");
6845 cursed = !!newterm(NULL, opt_tty, opt_tty);
6848 if (!cursed)
6849 die("Failed to initialize curses");
6851 nonl(); /* Disable conversion and detect newlines from input. */
6852 cbreak(); /* Take input chars one at a time, no wait for \n */
6853 noecho(); /* Don't echo input */
6854 leaveok(stdscr, FALSE);
6856 if (has_colors())
6857 init_colors();
6859 getmaxyx(stdscr, y, x);
6860 status_win = newwin(1, x, y - 1, 0);
6861 if (!status_win)
6862 die("Failed to create status window");
6864 /* Enable keyboard mapping */
6865 keypad(status_win, TRUE);
6866 wbkgdset(status_win, get_line_attr(LINE_STATUS));
6868 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6869 set_tabsize(opt_tab_size);
6870 #else
6871 TABSIZE = opt_tab_size;
6872 #endif
6874 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6875 if (term && !strcmp(term, "gnome-terminal")) {
6876 /* In the gnome-terminal-emulator, the message from
6877 * scrolling up one line when impossible followed by
6878 * scrolling down one line causes corruption of the
6879 * status line. This is fixed by calling wclear. */
6880 use_scroll_status_wclear = TRUE;
6881 use_scroll_redrawwin = FALSE;
6883 } else if (term && !strcmp(term, "xrvt-xpm")) {
6884 /* No problems with full optimizations in xrvt-(unicode)
6885 * and aterm. */
6886 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6888 } else {
6889 /* When scrolling in (u)xterm the last line in the
6890 * scrolling direction will update slowly. */
6891 use_scroll_redrawwin = TRUE;
6892 use_scroll_status_wclear = FALSE;
6896 static int
6897 get_input(int prompt_position)
6899 struct view *view;
6900 int i, key, cursor_y, cursor_x;
6902 if (prompt_position)
6903 input_mode = TRUE;
6905 while (TRUE) {
6906 bool loading = FALSE;
6908 foreach_view (view, i) {
6909 update_view(view);
6910 if (view_is_displayed(view) && view->has_scrolled &&
6911 use_scroll_redrawwin)
6912 redrawwin(view->win);
6913 view->has_scrolled = FALSE;
6914 if (view->pipe)
6915 loading = TRUE;
6918 /* Update the cursor position. */
6919 if (prompt_position) {
6920 getbegyx(status_win, cursor_y, cursor_x);
6921 cursor_x = prompt_position;
6922 } else {
6923 view = display[current_view];
6924 getbegyx(view->win, cursor_y, cursor_x);
6925 cursor_x = view->width - 1;
6926 cursor_y += view->lineno - view->offset;
6928 setsyx(cursor_y, cursor_x);
6930 /* Refresh, accept single keystroke of input */
6931 doupdate();
6932 nodelay(status_win, loading);
6933 key = wgetch(status_win);
6935 /* wgetch() with nodelay() enabled returns ERR when
6936 * there's no input. */
6937 if (key == ERR) {
6939 } else if (key == KEY_RESIZE) {
6940 int height, width;
6942 getmaxyx(stdscr, height, width);
6944 wresize(status_win, 1, width);
6945 mvwin(status_win, height - 1, 0);
6946 wnoutrefresh(status_win);
6947 resize_display();
6948 redraw_display(TRUE);
6950 } else {
6951 input_mode = FALSE;
6952 if (key == erasechar())
6953 key = KEY_BACKSPACE;
6954 return key;
6959 static char *
6960 prompt_input(const char *prompt, input_handler handler, void *data)
6962 enum input_status status = INPUT_OK;
6963 static char buf[SIZEOF_STR];
6964 size_t pos = 0;
6966 buf[pos] = 0;
6968 while (status == INPUT_OK || status == INPUT_SKIP) {
6969 int key;
6971 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6972 wclrtoeol(status_win);
6974 key = get_input(pos + 1);
6975 switch (key) {
6976 case KEY_RETURN:
6977 case KEY_ENTER:
6978 case '\n':
6979 status = pos ? INPUT_STOP : INPUT_CANCEL;
6980 break;
6982 case KEY_BACKSPACE:
6983 if (pos > 0)
6984 buf[--pos] = 0;
6985 else
6986 status = INPUT_CANCEL;
6987 break;
6989 case KEY_ESC:
6990 status = INPUT_CANCEL;
6991 break;
6993 default:
6994 if (pos >= sizeof(buf)) {
6995 report("Input string too long");
6996 return NULL;
6999 status = handler(data, buf, key);
7000 if (status == INPUT_OK)
7001 buf[pos++] = (char) key;
7005 /* Clear the status window */
7006 status_empty = FALSE;
7007 report("");
7009 if (status == INPUT_CANCEL)
7010 return NULL;
7012 buf[pos++] = 0;
7014 return buf;
7017 static enum input_status
7018 prompt_yesno_handler(void *data, char *buf, int c)
7020 if (c == 'y' || c == 'Y')
7021 return INPUT_STOP;
7022 if (c == 'n' || c == 'N')
7023 return INPUT_CANCEL;
7024 return INPUT_SKIP;
7027 static bool
7028 prompt_yesno(const char *prompt)
7030 char prompt2[SIZEOF_STR];
7032 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7033 return FALSE;
7035 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7038 static enum input_status
7039 read_prompt_handler(void *data, char *buf, int c)
7041 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7044 static char *
7045 read_prompt(const char *prompt)
7047 return prompt_input(prompt, read_prompt_handler, NULL);
7050 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7052 enum input_status status = INPUT_OK;
7053 int size = 0;
7055 while (items[size].text)
7056 size++;
7058 while (status == INPUT_OK) {
7059 const struct menu_item *item = &items[*selected];
7060 int key;
7061 int i;
7063 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7064 prompt, *selected + 1, size);
7065 if (item->hotkey)
7066 wprintw(status_win, "[%c] ", (char) item->hotkey);
7067 wprintw(status_win, "%s", item->text);
7068 wclrtoeol(status_win);
7070 key = get_input(COLS - 1);
7071 switch (key) {
7072 case KEY_RETURN:
7073 case KEY_ENTER:
7074 case '\n':
7075 status = INPUT_STOP;
7076 break;
7078 case KEY_LEFT:
7079 case KEY_UP:
7080 *selected = *selected - 1;
7081 if (*selected < 0)
7082 *selected = size - 1;
7083 break;
7085 case KEY_RIGHT:
7086 case KEY_DOWN:
7087 *selected = (*selected + 1) % size;
7088 break;
7090 case KEY_ESC:
7091 status = INPUT_CANCEL;
7092 break;
7094 default:
7095 for (i = 0; items[i].text; i++)
7096 if (items[i].hotkey == key) {
7097 *selected = i;
7098 status = INPUT_STOP;
7099 break;
7104 /* Clear the status window */
7105 status_empty = FALSE;
7106 report("");
7108 return status != INPUT_CANCEL;
7112 * Repository properties
7115 static struct ref **refs = NULL;
7116 static size_t refs_size = 0;
7117 static struct ref *refs_head = NULL;
7119 static struct ref_list **ref_lists = NULL;
7120 static size_t ref_lists_size = 0;
7122 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
7123 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
7124 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
7126 static int
7127 compare_refs(const void *ref1_, const void *ref2_)
7129 const struct ref *ref1 = *(const struct ref **)ref1_;
7130 const struct ref *ref2 = *(const struct ref **)ref2_;
7132 if (ref1->tag != ref2->tag)
7133 return ref2->tag - ref1->tag;
7134 if (ref1->ltag != ref2->ltag)
7135 return ref2->ltag - ref1->ltag;
7136 if (ref1->head != ref2->head)
7137 return ref2->head - ref1->head;
7138 if (ref1->tracked != ref2->tracked)
7139 return ref2->tracked - ref1->tracked;
7140 if (ref1->replace != ref2->replace)
7141 return ref2->replace - ref1->replace;
7142 /* Order remotes last. */
7143 if (ref1->remote != ref2->remote)
7144 return ref1->remote - ref2->remote;
7145 return strcmp(ref1->name, ref2->name);
7148 static void
7149 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
7151 size_t i;
7153 for (i = 0; i < refs_size; i++)
7154 if (!visitor(data, refs[i]))
7155 break;
7158 static struct ref *
7159 get_ref_head()
7161 return refs_head;
7164 static struct ref_list *
7165 get_ref_list(const char *id)
7167 struct ref_list *list;
7168 size_t i;
7170 for (i = 0; i < ref_lists_size; i++)
7171 if (!strcmp(id, ref_lists[i]->id))
7172 return ref_lists[i];
7174 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
7175 return NULL;
7176 list = calloc(1, sizeof(*list));
7177 if (!list)
7178 return NULL;
7180 for (i = 0; i < refs_size; i++) {
7181 if (!strcmp(id, refs[i]->id) &&
7182 realloc_refs_list(&list->refs, list->size, 1))
7183 list->refs[list->size++] = refs[i];
7186 if (!list->refs) {
7187 free(list);
7188 return NULL;
7191 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
7192 ref_lists[ref_lists_size++] = list;
7193 return list;
7196 static int
7197 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
7199 struct ref *ref = NULL;
7200 bool tag = FALSE;
7201 bool ltag = FALSE;
7202 bool remote = FALSE;
7203 bool replace = FALSE;
7204 bool tracked = FALSE;
7205 bool head = FALSE;
7206 int from = 0, to = refs_size - 1;
7208 if (!prefixcmp(name, "refs/tags/")) {
7209 if (!suffixcmp(name, namelen, "^{}")) {
7210 namelen -= 3;
7211 name[namelen] = 0;
7212 } else {
7213 ltag = TRUE;
7216 tag = TRUE;
7217 namelen -= STRING_SIZE("refs/tags/");
7218 name += STRING_SIZE("refs/tags/");
7220 } else if (!prefixcmp(name, "refs/remotes/")) {
7221 remote = TRUE;
7222 namelen -= STRING_SIZE("refs/remotes/");
7223 name += STRING_SIZE("refs/remotes/");
7224 tracked = !strcmp(opt_remote, name);
7226 } else if (!prefixcmp(name, "refs/replace/")) {
7227 replace = TRUE;
7228 id = name + strlen("refs/replace/");
7229 idlen = namelen - strlen("refs/replace/");
7230 name = "replaced";
7231 namelen = strlen(name);
7233 } else if (!prefixcmp(name, "refs/heads/")) {
7234 namelen -= STRING_SIZE("refs/heads/");
7235 name += STRING_SIZE("refs/heads/");
7236 if (strlen(opt_head) == namelen
7237 && !strncmp(opt_head, name, namelen))
7238 return OK;
7240 } else if (!strcmp(name, "HEAD")) {
7241 head = TRUE;
7242 if (*opt_head) {
7243 namelen = strlen(opt_head);
7244 name = opt_head;
7248 /* If we are reloading or it's an annotated tag, replace the
7249 * previous SHA1 with the resolved commit id; relies on the fact
7250 * git-ls-remote lists the commit id of an annotated tag right
7251 * before the commit id it points to. */
7252 while ((from <= to) && !replace) {
7253 size_t pos = (to + from) / 2;
7254 int cmp = strcmp(name, refs[pos]->name);
7256 if (!cmp) {
7257 ref = refs[pos];
7258 break;
7261 if (cmp < 0)
7262 to = pos - 1;
7263 else
7264 from = pos + 1;
7267 if (!ref) {
7268 if (!realloc_refs(&refs, refs_size, 1))
7269 return ERR;
7270 ref = calloc(1, sizeof(*ref) + namelen);
7271 if (!ref)
7272 return ERR;
7273 memmove(refs + from + 1, refs + from,
7274 (refs_size - from) * sizeof(*refs));
7275 refs[from] = ref;
7276 strncpy(ref->name, name, namelen);
7277 refs_size++;
7280 ref->head = head;
7281 ref->tag = tag;
7282 ref->ltag = ltag;
7283 ref->remote = remote;
7284 ref->replace = replace;
7285 ref->tracked = tracked;
7286 string_copy_rev(ref->id, id);
7288 if (head)
7289 refs_head = ref;
7290 return OK;
7293 static int
7294 load_refs(void)
7296 const char *head_argv[] = {
7297 "git", "symbolic-ref", "HEAD", NULL
7299 static const char *ls_remote_argv[SIZEOF_ARG] = {
7300 "git", "ls-remote", opt_git_dir, NULL
7302 static bool init = FALSE;
7303 size_t i;
7305 if (!init) {
7306 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
7307 die("TIG_LS_REMOTE contains too many arguments");
7308 init = TRUE;
7311 if (!*opt_git_dir)
7312 return OK;
7314 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
7315 !prefixcmp(opt_head, "refs/heads/")) {
7316 char *offset = opt_head + STRING_SIZE("refs/heads/");
7318 memmove(opt_head, offset, strlen(offset) + 1);
7321 refs_head = NULL;
7322 for (i = 0; i < refs_size; i++)
7323 refs[i]->id[0] = 0;
7325 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
7326 return ERR;
7328 /* Update the ref lists to reflect changes. */
7329 for (i = 0; i < ref_lists_size; i++) {
7330 struct ref_list *list = ref_lists[i];
7331 size_t old, new;
7333 for (old = new = 0; old < list->size; old++)
7334 if (!strcmp(list->id, list->refs[old]->id))
7335 list->refs[new++] = list->refs[old];
7336 list->size = new;
7339 qsort(refs, refs_size, sizeof(*refs), compare_refs);
7341 return OK;
7344 static void
7345 set_remote_branch(const char *name, const char *value, size_t valuelen)
7347 if (!strcmp(name, ".remote")) {
7348 string_ncopy(opt_remote, value, valuelen);
7350 } else if (*opt_remote && !strcmp(name, ".merge")) {
7351 size_t from = strlen(opt_remote);
7353 if (!prefixcmp(value, "refs/heads/"))
7354 value += STRING_SIZE("refs/heads/");
7356 if (!string_format_from(opt_remote, &from, "/%s", value))
7357 opt_remote[0] = 0;
7361 static void
7362 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7364 const char *argv[SIZEOF_ARG] = { name, "=" };
7365 int argc = 1 + (cmd == option_set_command);
7366 enum option_code error;
7368 if (!argv_from_string(argv, &argc, value))
7369 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7370 else
7371 error = cmd(argc, argv);
7373 if (error != OPT_OK)
7374 warn("Option 'tig.%s': %s", name, option_errors[error]);
7377 static bool
7378 set_environment_variable(const char *name, const char *value)
7380 size_t len = strlen(name) + 1 + strlen(value) + 1;
7381 char *env = malloc(len);
7383 if (env &&
7384 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7385 putenv(env) == 0)
7386 return TRUE;
7387 free(env);
7388 return FALSE;
7391 static void
7392 set_work_tree(const char *value)
7394 char cwd[SIZEOF_STR];
7396 if (!getcwd(cwd, sizeof(cwd)))
7397 die("Failed to get cwd path: %s", strerror(errno));
7398 if (chdir(opt_git_dir) < 0)
7399 die("Failed to chdir(%s): %s", strerror(errno));
7400 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7401 die("Failed to get git path: %s", strerror(errno));
7402 if (chdir(cwd) < 0)
7403 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7404 if (chdir(value) < 0)
7405 die("Failed to chdir(%s): %s", value, strerror(errno));
7406 if (!getcwd(cwd, sizeof(cwd)))
7407 die("Failed to get cwd path: %s", strerror(errno));
7408 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7409 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7410 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7411 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7412 opt_is_inside_work_tree = TRUE;
7415 static int
7416 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7418 if (!strcmp(name, "i18n.commitencoding"))
7419 parse_encoding(&opt_encoding, value, FALSE);
7421 else if (!strcmp(name, "gui.encoding"))
7422 parse_encoding(&opt_encoding, value, TRUE);
7424 else if (!strcmp(name, "core.editor"))
7425 string_ncopy(opt_editor, value, valuelen);
7427 else if (!strcmp(name, "core.worktree"))
7428 set_work_tree(value);
7430 else if (!prefixcmp(name, "tig.color."))
7431 set_repo_config_option(name + 10, value, option_color_command);
7433 else if (!prefixcmp(name, "tig.bind."))
7434 set_repo_config_option(name + 9, value, option_bind_command);
7436 else if (!prefixcmp(name, "tig."))
7437 set_repo_config_option(name + 4, value, option_set_command);
7439 else if (*opt_head && !prefixcmp(name, "branch.") &&
7440 !strncmp(name + 7, opt_head, strlen(opt_head)))
7441 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7443 return OK;
7446 static int
7447 load_git_config(void)
7449 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7451 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7454 static int
7455 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7457 if (!opt_git_dir[0]) {
7458 string_ncopy(opt_git_dir, name, namelen);
7460 } else if (opt_is_inside_work_tree == -1) {
7461 /* This can be 3 different values depending on the
7462 * version of git being used. If git-rev-parse does not
7463 * understand --is-inside-work-tree it will simply echo
7464 * the option else either "true" or "false" is printed.
7465 * Default to true for the unknown case. */
7466 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7468 } else if (*name == '.') {
7469 string_ncopy(opt_cdup, name, namelen);
7471 } else {
7472 string_ncopy(opt_prefix, name, namelen);
7475 return OK;
7478 static int
7479 load_repo_info(void)
7481 const char *rev_parse_argv[] = {
7482 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7483 "--show-cdup", "--show-prefix", NULL
7486 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7491 * Main
7494 static const char usage[] =
7495 "tig " TIG_VERSION " (" __DATE__ ")\n"
7496 "\n"
7497 "Usage: tig [options] [revs] [--] [paths]\n"
7498 " or: tig show [options] [revs] [--] [paths]\n"
7499 " or: tig blame [options] [rev] [--] path\n"
7500 " or: tig status\n"
7501 " or: tig < [git command output]\n"
7502 "\n"
7503 "Options:\n"
7504 " +<number> Select line <number> in the first view\n"
7505 " -v, --version Show version and exit\n"
7506 " -h, --help Show help message and exit";
7508 static void __NORETURN
7509 quit(int sig)
7511 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7512 if (cursed)
7513 endwin();
7514 exit(0);
7517 static void __NORETURN
7518 die(const char *err, ...)
7520 va_list args;
7522 endwin();
7524 va_start(args, err);
7525 fputs("tig: ", stderr);
7526 vfprintf(stderr, err, args);
7527 fputs("\n", stderr);
7528 va_end(args);
7530 exit(1);
7533 static void
7534 warn(const char *msg, ...)
7536 va_list args;
7538 va_start(args, msg);
7539 fputs("tig warning: ", stderr);
7540 vfprintf(stderr, msg, args);
7541 fputs("\n", stderr);
7542 va_end(args);
7545 static int
7546 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7548 const char ***filter_args = data;
7550 return argv_append(filter_args, name) ? OK : ERR;
7553 static void
7554 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7556 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7557 const char **all_argv = NULL;
7559 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7560 !argv_append_array(&all_argv, argv) ||
7561 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7562 die("Failed to split arguments");
7563 argv_free(all_argv);
7564 free(all_argv);
7567 static void
7568 filter_options(const char *argv[], bool blame)
7570 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7572 if (blame)
7573 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7574 else
7575 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7577 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7580 static enum request
7581 parse_options(int argc, const char *argv[])
7583 enum request request = REQ_VIEW_MAIN;
7584 const char *subcommand;
7585 bool seen_dashdash = FALSE;
7586 const char **filter_argv = NULL;
7587 int i;
7589 if (!isatty(STDIN_FILENO))
7590 return REQ_VIEW_PAGER;
7592 if (argc <= 1)
7593 return REQ_VIEW_MAIN;
7595 subcommand = argv[1];
7596 if (!strcmp(subcommand, "status")) {
7597 if (argc > 2)
7598 warn("ignoring arguments after `%s'", subcommand);
7599 return REQ_VIEW_STATUS;
7601 } else if (!strcmp(subcommand, "blame")) {
7602 request = REQ_VIEW_BLAME;
7604 } else if (!strcmp(subcommand, "show")) {
7605 request = REQ_VIEW_DIFF;
7607 } else {
7608 subcommand = NULL;
7611 for (i = 1 + !!subcommand; i < argc; i++) {
7612 const char *opt = argv[i];
7614 // stop parsing our options after -- and let rev-parse handle the rest
7615 if (!seen_dashdash) {
7616 if (!strcmp(opt, "--")) {
7617 seen_dashdash = TRUE;
7618 continue;
7620 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7621 printf("tig version %s\n", TIG_VERSION);
7622 quit(0);
7624 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7625 printf("%s\n", usage);
7626 quit(0);
7628 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7629 opt_lineno = atoi(opt + 1);
7630 continue;
7635 if (!argv_append(&filter_argv, opt))
7636 die("command too long");
7639 if (filter_argv)
7640 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7642 /* Finish validating and setting up blame options */
7643 if (request == REQ_VIEW_BLAME) {
7644 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7645 die("invalid number of options to blame\n\n%s", usage);
7647 if (opt_rev_argv) {
7648 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7651 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7654 return request;
7658 main(int argc, const char *argv[])
7660 const char *codeset = ENCODING_UTF8;
7661 enum request request = parse_options(argc, argv);
7662 struct view *view;
7664 signal(SIGINT, quit);
7665 signal(SIGPIPE, SIG_IGN);
7667 if (setlocale(LC_ALL, "")) {
7668 codeset = nl_langinfo(CODESET);
7671 if (load_repo_info() == ERR)
7672 die("Failed to load repo info.");
7674 if (load_options() == ERR)
7675 die("Failed to load user config.");
7677 if (load_git_config() == ERR)
7678 die("Failed to load repo config.");
7680 /* Require a git repository unless when running in pager mode. */
7681 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7682 die("Not a git repository");
7684 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
7685 char translit[SIZEOF_STR];
7687 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
7688 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
7689 else
7690 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
7691 if (opt_iconv_out == ICONV_NONE)
7692 die("Failed to initialize character set conversion");
7695 if (load_refs() == ERR)
7696 die("Failed to load refs.");
7698 init_display();
7700 while (view_driver(display[current_view], request)) {
7701 int key = get_input(0);
7703 view = display[current_view];
7704 request = get_keybinding(view->keymap, key);
7706 /* Some low-level request handling. This keeps access to
7707 * status_win restricted. */
7708 switch (request) {
7709 case REQ_NONE:
7710 report("Unknown key, press %s for help",
7711 get_view_key(view, REQ_VIEW_HELP));
7712 break;
7713 case REQ_PROMPT:
7715 char *cmd = read_prompt(":");
7717 if (cmd && string_isnumber(cmd)) {
7718 int lineno = view->lineno + 1;
7720 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
7721 select_view_line(view, lineno - 1);
7722 report("");
7723 } else {
7724 report("Unable to parse '%s' as a line number", cmd);
7726 } else if (cmd && iscommit(cmd)) {
7727 string_ncopy(opt_search, cmd, strlen(cmd));
7729 request = view_request(view, REQ_JUMP_COMMIT);
7730 if (request == REQ_JUMP_COMMIT) {
7731 report("Jumping to commits is not supported by the '%s' view", view->name);
7734 } else if (cmd) {
7735 struct view *next = VIEW(REQ_VIEW_PAGER);
7736 const char *argv[SIZEOF_ARG] = { "git" };
7737 int argc = 1;
7739 /* When running random commands, initially show the
7740 * command in the title. However, it maybe later be
7741 * overwritten if a commit line is selected. */
7742 string_ncopy(next->ref, cmd, strlen(cmd));
7744 if (!argv_from_string(argv, &argc, cmd)) {
7745 report("Too many arguments");
7746 } else if (!format_argv(&next->argv, argv, FALSE)) {
7747 report("Argument formatting failed");
7748 } else {
7749 next->dir = NULL;
7750 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7754 request = REQ_NONE;
7755 break;
7757 case REQ_SEARCH:
7758 case REQ_SEARCH_BACK:
7760 const char *prompt = request == REQ_SEARCH ? "/" : "?";
7761 char *search = read_prompt(prompt);
7763 if (search)
7764 string_ncopy(opt_search, search, strlen(search));
7765 else if (*opt_search)
7766 request = request == REQ_SEARCH ?
7767 REQ_FIND_NEXT :
7768 REQ_FIND_PREV;
7769 else
7770 request = REQ_NONE;
7771 break;
7773 default:
7774 break;
7778 quit(0);
7780 return 0;