Offload commit encoding entirely to git
[tig.git] / tig.c
blobfc3326b0459d5a024b00b117b7a7e1060e15fb9f
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_(OBSOLETE_VARIABLE_NAME, "Obsolete variable name"), \
1121 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1122 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1123 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1125 enum option_code {
1126 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1127 OPT_ERR_INFO
1128 #undef OPT_ERR_
1129 OPT_OK
1132 static const char *option_errors[] = {
1133 #define OPT_ERR_(name, msg) msg
1134 OPT_ERR_INFO
1135 #undef OPT_ERR_
1138 static const struct enum_map color_map[] = {
1139 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1140 COLOR_MAP(DEFAULT),
1141 COLOR_MAP(BLACK),
1142 COLOR_MAP(BLUE),
1143 COLOR_MAP(CYAN),
1144 COLOR_MAP(GREEN),
1145 COLOR_MAP(MAGENTA),
1146 COLOR_MAP(RED),
1147 COLOR_MAP(WHITE),
1148 COLOR_MAP(YELLOW),
1151 static const struct enum_map attr_map[] = {
1152 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1153 ATTR_MAP(NORMAL),
1154 ATTR_MAP(BLINK),
1155 ATTR_MAP(BOLD),
1156 ATTR_MAP(DIM),
1157 ATTR_MAP(REVERSE),
1158 ATTR_MAP(STANDOUT),
1159 ATTR_MAP(UNDERLINE),
1162 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1164 static enum option_code
1165 parse_step(double *opt, const char *arg)
1167 *opt = atoi(arg);
1168 if (!strchr(arg, '%'))
1169 return OPT_OK;
1171 /* "Shift down" so 100% and 1 does not conflict. */
1172 *opt = (*opt - 1) / 100;
1173 if (*opt >= 1.0) {
1174 *opt = 0.99;
1175 return OPT_ERR_INVALID_STEP_VALUE;
1177 if (*opt < 0.0) {
1178 *opt = 1;
1179 return OPT_ERR_INVALID_STEP_VALUE;
1181 return OPT_OK;
1184 static enum option_code
1185 parse_int(int *opt, const char *arg, int min, int max)
1187 int value = atoi(arg);
1189 if (min <= value && value <= max) {
1190 *opt = value;
1191 return OPT_OK;
1194 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1197 static bool
1198 set_color(int *color, const char *name)
1200 if (map_enum(color, color_map, name))
1201 return TRUE;
1202 if (!prefixcmp(name, "color"))
1203 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1204 return FALSE;
1207 /* Wants: object fgcolor bgcolor [attribute] */
1208 static enum option_code
1209 option_color_command(int argc, const char *argv[])
1211 struct line_info *info;
1213 if (argc < 3)
1214 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1216 if (*argv[0] == '"' || *argv[0] == '\'') {
1217 info = add_custom_color(argv[0]);
1218 } else {
1219 info = get_line_info(argv[0]);
1221 if (!info) {
1222 static const struct enum_map obsolete[] = {
1223 ENUM_MAP("main-delim", LINE_DELIMITER),
1224 ENUM_MAP("main-date", LINE_DATE),
1225 ENUM_MAP("main-author", LINE_AUTHOR),
1227 int index;
1229 if (!map_enum(&index, obsolete, argv[0]))
1230 return OPT_ERR_UNKNOWN_COLOR_NAME;
1231 info = &line_info[index];
1234 if (!set_color(&info->fg, argv[1]) ||
1235 !set_color(&info->bg, argv[2]))
1236 return OPT_ERR_UNKNOWN_COLOR;
1238 info->attr = 0;
1239 while (argc-- > 3) {
1240 int attr;
1242 if (!set_attribute(&attr, argv[argc]))
1243 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1244 info->attr |= attr;
1247 return OPT_OK;
1250 static enum option_code
1251 parse_bool(bool *opt, const char *arg)
1253 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1254 ? TRUE : FALSE;
1255 return OPT_OK;
1258 static enum option_code
1259 parse_enum_do(unsigned int *opt, const char *arg,
1260 const struct enum_map *map, size_t map_size)
1262 bool is_true;
1264 assert(map_size > 1);
1266 if (map_enum_do(map, map_size, (int *) opt, arg))
1267 return OPT_OK;
1269 parse_bool(&is_true, arg);
1270 *opt = is_true ? map[1].value : map[0].value;
1271 return OPT_OK;
1274 #define parse_enum(opt, arg, map) \
1275 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1277 static enum option_code
1278 parse_string(char *opt, const char *arg, size_t optsize)
1280 int arglen = strlen(arg);
1282 switch (arg[0]) {
1283 case '\"':
1284 case '\'':
1285 if (arglen == 1 || arg[arglen - 1] != arg[0])
1286 return OPT_ERR_UNMATCHED_QUOTATION;
1287 arg += 1; arglen -= 2;
1288 default:
1289 string_ncopy_do(opt, optsize, arg, arglen);
1290 return OPT_OK;
1294 static enum option_code
1295 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1297 char buf[SIZEOF_STR];
1298 enum option_code code = parse_string(buf, arg, sizeof(buf));
1300 if (code == OPT_OK) {
1301 struct encoding *encoding = *encoding_ref;
1303 if (encoding && !priority)
1304 return code;
1305 encoding = encoding_open(buf);
1306 if (encoding)
1307 *encoding_ref = encoding;
1310 return code;
1313 static enum option_code
1314 parse_args(const char ***args, const char *argv[])
1316 if (*args == NULL && !argv_copy(args, argv))
1317 return OPT_ERR_OUT_OF_MEMORY;
1318 return OPT_OK;
1321 /* Wants: name = value */
1322 static enum option_code
1323 option_set_command(int argc, const char *argv[])
1325 if (argc < 3)
1326 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1328 if (strcmp(argv[1], "="))
1329 return OPT_ERR_NO_VALUE_ASSIGNED;
1331 if (!strcmp(argv[0], "blame-options"))
1332 return parse_args(&opt_blame_argv, argv + 2);
1334 if (argc != 3)
1335 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1337 if (!strcmp(argv[0], "show-author"))
1338 return parse_enum(&opt_author, argv[2], author_map);
1340 if (!strcmp(argv[0], "show-date"))
1341 return parse_enum(&opt_date, argv[2], date_map);
1343 if (!strcmp(argv[0], "show-rev-graph"))
1344 return parse_bool(&opt_rev_graph, argv[2]);
1346 if (!strcmp(argv[0], "show-refs"))
1347 return parse_bool(&opt_show_refs, argv[2]);
1349 if (!strcmp(argv[0], "show-notes")) {
1350 int res;
1352 strcpy(opt_notes_arg, "--notes=");
1353 res = parse_string(opt_notes_arg + 8, argv[2],
1354 sizeof(opt_notes_arg) - 8);
1355 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1356 opt_notes_arg[7] = '\0';
1357 return res;
1360 if (!strcmp(argv[0], "show-line-numbers"))
1361 return parse_bool(&opt_line_number, argv[2]);
1363 if (!strcmp(argv[0], "line-graphics"))
1364 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1366 if (!strcmp(argv[0], "line-number-interval"))
1367 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1369 if (!strcmp(argv[0], "author-width"))
1370 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1372 if (!strcmp(argv[0], "filename-width"))
1373 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1375 if (!strcmp(argv[0], "show-filename"))
1376 return parse_enum(&opt_filename, argv[2], filename_map);
1378 if (!strcmp(argv[0], "horizontal-scroll"))
1379 return parse_step(&opt_hscroll, argv[2]);
1381 if (!strcmp(argv[0], "split-view-height"))
1382 return parse_step(&opt_scale_split_view, argv[2]);
1384 if (!strcmp(argv[0], "tab-size"))
1385 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1387 if (!strcmp(argv[0], "diff-context")) {
1388 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1390 if (code == OPT_OK)
1391 update_diff_context_arg(opt_diff_context);
1392 return code;
1395 if (!strcmp(argv[0], "ignore-space")) {
1396 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1398 if (code == OPT_OK)
1399 update_ignore_space_arg();
1400 return code;
1403 if (!strcmp(argv[0], "status-untracked-dirs"))
1404 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1406 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1409 /* Wants: mode request key */
1410 static enum option_code
1411 option_bind_command(int argc, const char *argv[])
1413 enum request request;
1414 int keymap = -1;
1415 int key;
1417 if (argc < 3)
1418 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1420 if (!set_keymap(&keymap, argv[0]))
1421 return OPT_ERR_UNKNOWN_KEY_MAP;
1423 key = get_key_value(argv[1]);
1424 if (key == ERR)
1425 return OPT_ERR_UNKNOWN_KEY;
1427 request = get_request(argv[2]);
1428 if (request == REQ_UNKNOWN) {
1429 static const struct enum_map obsolete[] = {
1430 ENUM_MAP("cherry-pick", REQ_NONE),
1431 ENUM_MAP("screen-resize", REQ_NONE),
1432 ENUM_MAP("tree-parent", REQ_PARENT),
1434 int alias;
1436 if (map_enum(&alias, obsolete, argv[2])) {
1437 if (alias != REQ_NONE)
1438 add_keybinding(keymap, alias, key);
1439 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1442 if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1443 request = add_run_request(keymap, key, argv + 2);
1444 if (request == REQ_UNKNOWN)
1445 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1447 add_keybinding(keymap, request, key);
1449 return OPT_OK;
1453 static enum option_code load_option_file(const char *path);
1455 static enum option_code
1456 option_source_command(int argc, const char *argv[])
1458 if (argc < 1)
1459 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1461 return load_option_file(argv[0]);
1464 static enum option_code
1465 set_option(const char *opt, char *value)
1467 const char *argv[SIZEOF_ARG];
1468 int argc = 0;
1470 if (!argv_from_string(argv, &argc, value))
1471 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1473 if (!strcmp(opt, "color"))
1474 return option_color_command(argc, argv);
1476 if (!strcmp(opt, "set"))
1477 return option_set_command(argc, argv);
1479 if (!strcmp(opt, "bind"))
1480 return option_bind_command(argc, argv);
1482 if (!strcmp(opt, "source"))
1483 return option_source_command(argc, argv);
1485 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1488 struct config_state {
1489 const char *path;
1490 int lineno;
1491 bool errors;
1494 static int
1495 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1497 struct config_state *config = data;
1498 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1500 config->lineno++;
1502 /* Check for comment markers, since read_properties() will
1503 * only ensure opt and value are split at first " \t". */
1504 optlen = strcspn(opt, "#");
1505 if (optlen == 0)
1506 return OK;
1508 if (opt[optlen] == 0) {
1509 /* Look for comment endings in the value. */
1510 size_t len = strcspn(value, "#");
1512 if (len < valuelen) {
1513 valuelen = len;
1514 value[valuelen] = 0;
1517 status = set_option(opt, value);
1520 if (status != OPT_OK) {
1521 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1522 option_errors[status], (int) optlen, opt);
1523 config->errors = TRUE;
1526 /* Always keep going if errors are encountered. */
1527 return OK;
1530 static enum option_code
1531 load_option_file(const char *path)
1533 struct config_state config = { path, 0, FALSE };
1534 struct io io;
1536 /* Do not read configuration from stdin if set to "" */
1537 if (!path || !strlen(path))
1538 return OPT_OK;
1540 /* It's OK that the file doesn't exist. */
1541 if (!io_open(&io, "%s", path))
1542 return OPT_ERR_FILE_DOES_NOT_EXIST;
1544 if (io_load(&io, " \t", read_option, &config) == ERR ||
1545 config.errors == TRUE)
1546 warn("Errors while loading %s.", path);
1547 return OPT_OK;
1550 static int
1551 load_options(void)
1553 const char *home = getenv("HOME");
1554 const char *tigrc_user = getenv("TIGRC_USER");
1555 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1556 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1557 char buf[SIZEOF_STR];
1559 if (!tigrc_system)
1560 tigrc_system = SYSCONFDIR "/tigrc";
1561 load_option_file(tigrc_system);
1563 if (!tigrc_user) {
1564 if (!home || !string_format(buf, "%s/.tigrc", home))
1565 return ERR;
1566 tigrc_user = buf;
1568 load_option_file(tigrc_user);
1570 /* Add _after_ loading config files to avoid adding run requests
1571 * that conflict with keybindings. */
1572 add_builtin_run_requests();
1574 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1575 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1576 int argc = 0;
1578 if (!string_format(buf, "%s", tig_diff_opts) ||
1579 !argv_from_string(diff_opts, &argc, buf))
1580 die("TIG_DIFF_OPTS contains too many arguments");
1581 else if (!argv_copy(&opt_diff_argv, diff_opts))
1582 die("Failed to format TIG_DIFF_OPTS arguments");
1585 return OK;
1590 * The viewer
1593 struct view;
1594 struct view_ops;
1596 /* The display array of active views and the index of the current view. */
1597 static struct view *display[2];
1598 static WINDOW *display_win[2];
1599 static WINDOW *display_title[2];
1600 static unsigned int current_view;
1602 #define foreach_displayed_view(view, i) \
1603 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1605 #define displayed_views() (display[1] != NULL ? 2 : 1)
1607 /* Current head and commit ID */
1608 static char ref_blob[SIZEOF_REF] = "";
1609 static char ref_commit[SIZEOF_REF] = "HEAD";
1610 static char ref_head[SIZEOF_REF] = "HEAD";
1611 static char ref_branch[SIZEOF_REF] = "";
1613 enum view_flag {
1614 VIEW_NO_FLAGS = 0,
1615 VIEW_ALWAYS_LINENO = 1 << 0,
1616 VIEW_CUSTOM_STATUS = 1 << 1,
1617 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1618 VIEW_ADD_PAGER_REFS = 1 << 3,
1619 VIEW_OPEN_DIFF = 1 << 4,
1620 VIEW_NO_REF = 1 << 5,
1621 VIEW_NO_GIT_DIR = 1 << 6,
1624 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1626 struct view {
1627 const char *name; /* View name */
1628 const char *id; /* Points to either of ref_{head,commit,blob} */
1630 struct view_ops *ops; /* View operations */
1632 enum keymap keymap; /* What keymap does this view have */
1634 char ref[SIZEOF_REF]; /* Hovered commit reference */
1635 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1637 int height, width; /* The width and height of the main window */
1638 WINDOW *win; /* The main window */
1640 /* Navigation */
1641 unsigned long offset; /* Offset of the window top */
1642 unsigned long yoffset; /* Offset from the window side. */
1643 unsigned long lineno; /* Current line number */
1644 unsigned long p_offset; /* Previous offset of the window top */
1645 unsigned long p_yoffset;/* Previous offset from the window side */
1646 unsigned long p_lineno; /* Previous current line number */
1647 bool p_restore; /* Should the previous position be restored. */
1649 /* Searching */
1650 char grep[SIZEOF_STR]; /* Search string */
1651 regex_t *regex; /* Pre-compiled regexp */
1653 /* If non-NULL, points to the view that opened this view. If this view
1654 * is closed tig will switch back to the parent view. */
1655 struct view *parent;
1656 struct view *prev;
1658 /* Buffering */
1659 size_t lines; /* Total number of lines */
1660 struct line *line; /* Line index */
1661 unsigned int digits; /* Number of digits in the lines member. */
1663 /* Drawing */
1664 struct line *curline; /* Line currently being drawn. */
1665 enum line_type curtype; /* Attribute currently used for drawing. */
1666 unsigned long col; /* Column when drawing. */
1667 bool has_scrolled; /* View was scrolled. */
1669 /* Loading */
1670 const char **argv; /* Shell command arguments. */
1671 const char *dir; /* Directory from which to execute. */
1672 struct io io;
1673 struct io *pipe;
1674 time_t start_time;
1675 time_t update_secs;
1676 struct encoding *encoding;
1678 /* Private data */
1679 void *private;
1682 enum open_flags {
1683 OPEN_DEFAULT = 0, /* Use default view switching. */
1684 OPEN_SPLIT = 1, /* Split current view. */
1685 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1686 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1687 OPEN_PREPARED = 32, /* Open already prepared command. */
1688 OPEN_EXTRA = 64, /* Open extra data from command. */
1691 struct view_ops {
1692 /* What type of content being displayed. Used in the title bar. */
1693 const char *type;
1694 /* Flags to control the view behavior. */
1695 enum view_flag flags;
1696 /* Size of private data. */
1697 size_t private_size;
1698 /* Open and reads in all view content. */
1699 bool (*open)(struct view *view, enum open_flags flags);
1700 /* Read one line; updates view->line. */
1701 bool (*read)(struct view *view, char *data);
1702 /* Draw one line; @lineno must be < view->height. */
1703 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1704 /* Depending on view handle a special requests. */
1705 enum request (*request)(struct view *view, enum request request, struct line *line);
1706 /* Search for regexp in a line. */
1707 bool (*grep)(struct view *view, struct line *line);
1708 /* Select line */
1709 void (*select)(struct view *view, struct line *line);
1712 #define VIEW_OPS(id, name, ref) name##_ops
1713 static struct view_ops VIEW_INFO(VIEW_OPS);
1715 static struct view views[] = {
1716 #define VIEW_DATA(id, name, ref) \
1717 { #name, ref, &name##_ops, KEYMAP_##id }
1718 VIEW_INFO(VIEW_DATA)
1721 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1723 #define foreach_view(view, i) \
1724 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1726 #define view_is_displayed(view) \
1727 (view == display[0] || view == display[1])
1729 static enum request
1730 view_request(struct view *view, enum request request)
1732 if (!view || !view->lines)
1733 return request;
1734 return view->ops->request(view, request, &view->line[view->lineno]);
1739 * View drawing.
1742 static inline void
1743 set_view_attr(struct view *view, enum line_type type)
1745 if (!view->curline->selected && view->curtype != type) {
1746 (void) wattrset(view->win, get_line_attr(type));
1747 wchgat(view->win, -1, 0, COLOR_ID(type), NULL);
1748 view->curtype = type;
1752 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1754 static bool
1755 draw_chars(struct view *view, enum line_type type, const char *string,
1756 int max_len, bool use_tilde)
1758 static char out_buffer[BUFSIZ * 2];
1759 int len = 0;
1760 int col = 0;
1761 int trimmed = FALSE;
1762 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1764 if (max_len <= 0)
1765 return VIEW_MAX_LEN(view) <= 0;
1767 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1769 set_view_attr(view, type);
1770 if (len > 0) {
1771 if (opt_iconv_out != ICONV_NONE) {
1772 size_t inlen = len + 1;
1773 char *instr = calloc(1, inlen);
1774 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1775 if (!instr)
1776 return VIEW_MAX_LEN(view) <= 0;
1778 strncpy(instr, string, len);
1780 char *outbuf = out_buffer;
1781 size_t outlen = sizeof(out_buffer);
1783 size_t ret;
1785 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1786 if (ret != (size_t) -1) {
1787 string = out_buffer;
1788 len = sizeof(out_buffer) - outlen;
1790 free(instr);
1793 waddnstr(view->win, string, len);
1795 if (trimmed && use_tilde) {
1796 set_view_attr(view, LINE_DELIMITER);
1797 waddch(view->win, '~');
1798 col++;
1802 view->col += col;
1803 return VIEW_MAX_LEN(view) <= 0;
1806 static bool
1807 draw_space(struct view *view, enum line_type type, int max, int spaces)
1809 static char space[] = " ";
1811 spaces = MIN(max, spaces);
1813 while (spaces > 0) {
1814 int len = MIN(spaces, sizeof(space) - 1);
1816 if (draw_chars(view, type, space, len, FALSE))
1817 return TRUE;
1818 spaces -= len;
1821 return VIEW_MAX_LEN(view) <= 0;
1824 static bool
1825 draw_text(struct view *view, enum line_type type, const char *string)
1827 char text[SIZEOF_STR];
1829 do {
1830 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1832 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1833 return TRUE;
1834 string += pos;
1835 } while (*string);
1837 return VIEW_MAX_LEN(view) <= 0;
1840 static bool
1841 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
1843 char text[SIZEOF_STR];
1844 int retval;
1846 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
1847 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
1850 static bool
1851 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1853 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1854 int max = VIEW_MAX_LEN(view);
1855 int i;
1857 if (max < size)
1858 size = max;
1860 set_view_attr(view, type);
1861 /* Using waddch() instead of waddnstr() ensures that
1862 * they'll be rendered correctly for the cursor line. */
1863 for (i = skip; i < size; i++)
1864 waddch(view->win, graphic[i]);
1866 view->col += size;
1867 if (separator) {
1868 if (size < max && skip <= size)
1869 waddch(view->win, ' ');
1870 view->col++;
1873 return VIEW_MAX_LEN(view) <= 0;
1876 static bool
1877 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1879 int max = MIN(VIEW_MAX_LEN(view), len);
1880 int col = view->col;
1882 if (!text)
1883 return draw_space(view, type, max, max);
1885 return draw_chars(view, type, text, max - 1, trim)
1886 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1889 static bool
1890 draw_date(struct view *view, struct time *time)
1892 const char *date = mkdate(time, opt_date);
1893 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1895 if (opt_date == DATE_NO)
1896 return FALSE;
1898 return draw_field(view, LINE_DATE, date, cols, FALSE);
1901 static bool
1902 draw_author(struct view *view, const char *author)
1904 bool trim = author_trim(opt_author_cols);
1905 const char *text = mkauthor(author, opt_author_cols, opt_author);
1907 if (opt_author == AUTHOR_NO)
1908 return FALSE;
1910 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1913 static bool
1914 draw_filename(struct view *view, const char *filename, bool auto_enabled)
1916 bool trim = filename && strlen(filename) >= opt_filename_cols;
1918 if (opt_filename == FILENAME_NO)
1919 return FALSE;
1921 if (opt_filename == FILENAME_AUTO && !auto_enabled)
1922 return FALSE;
1924 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
1927 static bool
1928 draw_mode(struct view *view, mode_t mode)
1930 const char *str = mkmode(mode);
1932 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1935 static bool
1936 draw_lineno(struct view *view, unsigned int lineno)
1938 char number[10];
1939 int digits3 = view->digits < 3 ? 3 : view->digits;
1940 int max = MIN(VIEW_MAX_LEN(view), digits3);
1941 char *text = NULL;
1942 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1944 lineno += view->offset + 1;
1945 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1946 static char fmt[] = "%1ld";
1948 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1949 if (string_format(number, fmt, lineno))
1950 text = number;
1952 if (text)
1953 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1954 else
1955 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1956 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1959 static bool
1960 draw_refs(struct view *view, struct ref_list *refs)
1962 size_t i;
1964 if (!opt_show_refs || !refs)
1965 return FALSE;
1967 for (i = 0; i < refs->size; i++) {
1968 struct ref *ref = refs->refs[i];
1969 enum line_type type = get_line_type_from_ref(ref);
1971 if (draw_formatted(view, type, "[%s]", ref->name))
1972 return TRUE;
1974 if (draw_text(view, LINE_DEFAULT, " "))
1975 return TRUE;
1978 return FALSE;
1981 static bool
1982 draw_view_line(struct view *view, unsigned int lineno)
1984 struct line *line;
1985 bool selected = (view->offset + lineno == view->lineno);
1987 assert(view_is_displayed(view));
1989 if (view->offset + lineno >= view->lines)
1990 return FALSE;
1992 line = &view->line[view->offset + lineno];
1994 wmove(view->win, lineno, 0);
1995 if (line->cleareol)
1996 wclrtoeol(view->win);
1997 view->col = 0;
1998 view->curline = line;
1999 view->curtype = LINE_NONE;
2000 line->selected = FALSE;
2001 line->dirty = line->cleareol = 0;
2003 if (selected) {
2004 set_view_attr(view, LINE_CURSOR);
2005 line->selected = TRUE;
2006 view->ops->select(view, line);
2009 return view->ops->draw(view, line, lineno);
2012 static void
2013 redraw_view_dirty(struct view *view)
2015 bool dirty = FALSE;
2016 int lineno;
2018 for (lineno = 0; lineno < view->height; lineno++) {
2019 if (view->offset + lineno >= view->lines)
2020 break;
2021 if (!view->line[view->offset + lineno].dirty)
2022 continue;
2023 dirty = TRUE;
2024 if (!draw_view_line(view, lineno))
2025 break;
2028 if (!dirty)
2029 return;
2030 wnoutrefresh(view->win);
2033 static void
2034 redraw_view_from(struct view *view, int lineno)
2036 assert(0 <= lineno && lineno < view->height);
2038 for (; lineno < view->height; lineno++) {
2039 if (!draw_view_line(view, lineno))
2040 break;
2043 wnoutrefresh(view->win);
2046 static void
2047 redraw_view(struct view *view)
2049 werase(view->win);
2050 redraw_view_from(view, 0);
2054 static void
2055 update_view_title(struct view *view)
2057 char buf[SIZEOF_STR];
2058 char state[SIZEOF_STR];
2059 size_t bufpos = 0, statelen = 0;
2060 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2062 assert(view_is_displayed(view));
2064 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view->lines) {
2065 unsigned int view_lines = view->offset + view->height;
2066 unsigned int lines = view->lines
2067 ? MIN(view_lines, view->lines) * 100 / view->lines
2068 : 0;
2070 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
2071 view->ops->type,
2072 view->lineno + 1,
2073 view->lines,
2074 lines);
2078 if (view->pipe) {
2079 time_t secs = time(NULL) - view->start_time;
2081 /* Three git seconds are a long time ... */
2082 if (secs > 2)
2083 string_format_from(state, &statelen, " loading %lds", secs);
2086 string_format_from(buf, &bufpos, "[%s]", view->name);
2087 if (*view->ref && bufpos < view->width) {
2088 size_t refsize = strlen(view->ref);
2089 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2091 if (minsize < view->width)
2092 refsize = view->width - minsize + 7;
2093 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2096 if (statelen && bufpos < view->width) {
2097 string_format_from(buf, &bufpos, "%s", state);
2100 if (view == display[current_view])
2101 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2102 else
2103 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2105 mvwaddnstr(window, 0, 0, buf, bufpos);
2106 wclrtoeol(window);
2107 wnoutrefresh(window);
2110 static int
2111 apply_step(double step, int value)
2113 if (step >= 1)
2114 return (int) step;
2115 value *= step + 0.01;
2116 return value ? value : 1;
2119 static void
2120 resize_display(void)
2122 int offset, i;
2123 struct view *base = display[0];
2124 struct view *view = display[1] ? display[1] : display[0];
2126 /* Setup window dimensions */
2128 getmaxyx(stdscr, base->height, base->width);
2130 /* Make room for the status window. */
2131 base->height -= 1;
2133 if (view != base) {
2134 /* Horizontal split. */
2135 view->width = base->width;
2136 view->height = apply_step(opt_scale_split_view, base->height);
2137 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2138 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2139 base->height -= view->height;
2141 /* Make room for the title bar. */
2142 view->height -= 1;
2145 /* Make room for the title bar. */
2146 base->height -= 1;
2148 offset = 0;
2150 foreach_displayed_view (view, i) {
2151 if (!display_win[i]) {
2152 display_win[i] = newwin(view->height, view->width, offset, 0);
2153 if (!display_win[i])
2154 die("Failed to create %s view", view->name);
2156 scrollok(display_win[i], FALSE);
2158 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2159 if (!display_title[i])
2160 die("Failed to create title window");
2162 } else {
2163 wresize(display_win[i], view->height, view->width);
2164 mvwin(display_win[i], offset, 0);
2165 mvwin(display_title[i], offset + view->height, 0);
2168 view->win = display_win[i];
2170 offset += view->height + 1;
2174 static void
2175 redraw_display(bool clear)
2177 struct view *view;
2178 int i;
2180 foreach_displayed_view (view, i) {
2181 if (clear)
2182 wclear(view->win);
2183 redraw_view(view);
2184 update_view_title(view);
2190 * Option management
2193 #define TOGGLE_MENU \
2194 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2195 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2196 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2197 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2198 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2199 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2200 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2201 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL)
2203 static bool
2204 toggle_option(enum request request)
2206 const struct {
2207 enum request request;
2208 const struct enum_map *map;
2209 size_t map_size;
2210 } data[] = {
2211 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2212 TOGGLE_MENU
2213 #undef TOGGLE_
2215 const struct menu_item menu[] = {
2216 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2217 TOGGLE_MENU
2218 #undef TOGGLE_
2219 { 0 }
2221 int i = 0;
2223 if (request == REQ_OPTIONS) {
2224 if (!prompt_menu("Toggle option", menu, &i))
2225 return FALSE;
2226 } else {
2227 while (i < ARRAY_SIZE(data) && data[i].request != request)
2228 i++;
2229 if (i >= ARRAY_SIZE(data))
2230 die("Invalid request (%d)", request);
2233 if (data[i].map != NULL) {
2234 unsigned int *opt = menu[i].data;
2236 *opt = (*opt + 1) % data[i].map_size;
2237 if (data[i].map == ignore_space_map) {
2238 update_ignore_space_arg();
2239 report("Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2240 return TRUE;
2243 redraw_display(FALSE);
2244 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2246 } else {
2247 bool *option = menu[i].data;
2249 *option = !*option;
2250 redraw_display(FALSE);
2251 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2254 return FALSE;
2257 static void
2258 maximize_view(struct view *view, bool redraw)
2260 memset(display, 0, sizeof(display));
2261 current_view = 0;
2262 display[current_view] = view;
2263 resize_display();
2264 if (redraw) {
2265 redraw_display(FALSE);
2266 report("");
2272 * Navigation
2275 static bool
2276 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2278 if (lineno >= view->lines)
2279 lineno = view->lines > 0 ? view->lines - 1 : 0;
2281 if (offset > lineno || offset + view->height <= lineno) {
2282 unsigned long half = view->height / 2;
2284 if (lineno > half)
2285 offset = lineno - half;
2286 else
2287 offset = 0;
2290 if (offset != view->offset || lineno != view->lineno) {
2291 view->offset = offset;
2292 view->lineno = lineno;
2293 return TRUE;
2296 return FALSE;
2299 /* Scrolling backend */
2300 static void
2301 do_scroll_view(struct view *view, int lines)
2303 bool redraw_current_line = FALSE;
2305 /* The rendering expects the new offset. */
2306 view->offset += lines;
2308 assert(0 <= view->offset && view->offset < view->lines);
2309 assert(lines);
2311 /* Move current line into the view. */
2312 if (view->lineno < view->offset) {
2313 view->lineno = view->offset;
2314 redraw_current_line = TRUE;
2315 } else if (view->lineno >= view->offset + view->height) {
2316 view->lineno = view->offset + view->height - 1;
2317 redraw_current_line = TRUE;
2320 assert(view->offset <= view->lineno && view->lineno < view->lines);
2322 /* Redraw the whole screen if scrolling is pointless. */
2323 if (view->height < ABS(lines)) {
2324 redraw_view(view);
2326 } else {
2327 int line = lines > 0 ? view->height - lines : 0;
2328 int end = line + ABS(lines);
2330 scrollok(view->win, TRUE);
2331 wscrl(view->win, lines);
2332 scrollok(view->win, FALSE);
2334 while (line < end && draw_view_line(view, line))
2335 line++;
2337 if (redraw_current_line)
2338 draw_view_line(view, view->lineno - view->offset);
2339 wnoutrefresh(view->win);
2342 view->has_scrolled = TRUE;
2343 report("");
2346 /* Scroll frontend */
2347 static void
2348 scroll_view(struct view *view, enum request request)
2350 int lines = 1;
2352 assert(view_is_displayed(view));
2354 switch (request) {
2355 case REQ_SCROLL_FIRST_COL:
2356 view->yoffset = 0;
2357 redraw_view_from(view, 0);
2358 report("");
2359 return;
2360 case REQ_SCROLL_LEFT:
2361 if (view->yoffset == 0) {
2362 report("Cannot scroll beyond the first column");
2363 return;
2365 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2366 view->yoffset = 0;
2367 else
2368 view->yoffset -= apply_step(opt_hscroll, view->width);
2369 redraw_view_from(view, 0);
2370 report("");
2371 return;
2372 case REQ_SCROLL_RIGHT:
2373 view->yoffset += apply_step(opt_hscroll, view->width);
2374 redraw_view(view);
2375 report("");
2376 return;
2377 case REQ_SCROLL_PAGE_DOWN:
2378 lines = view->height;
2379 case REQ_SCROLL_LINE_DOWN:
2380 if (view->offset + lines > view->lines)
2381 lines = view->lines - view->offset;
2383 if (lines == 0 || view->offset + view->height >= view->lines) {
2384 report("Cannot scroll beyond the last line");
2385 return;
2387 break;
2389 case REQ_SCROLL_PAGE_UP:
2390 lines = view->height;
2391 case REQ_SCROLL_LINE_UP:
2392 if (lines > view->offset)
2393 lines = view->offset;
2395 if (lines == 0) {
2396 report("Cannot scroll beyond the first line");
2397 return;
2400 lines = -lines;
2401 break;
2403 default:
2404 die("request %d not handled in switch", request);
2407 do_scroll_view(view, lines);
2410 /* Cursor moving */
2411 static void
2412 move_view(struct view *view, enum request request)
2414 int scroll_steps = 0;
2415 int steps;
2417 switch (request) {
2418 case REQ_MOVE_FIRST_LINE:
2419 steps = -view->lineno;
2420 break;
2422 case REQ_MOVE_LAST_LINE:
2423 steps = view->lines - view->lineno - 1;
2424 break;
2426 case REQ_MOVE_PAGE_UP:
2427 steps = view->height > view->lineno
2428 ? -view->lineno : -view->height;
2429 break;
2431 case REQ_MOVE_PAGE_DOWN:
2432 steps = view->lineno + view->height >= view->lines
2433 ? view->lines - view->lineno - 1 : view->height;
2434 break;
2436 case REQ_MOVE_UP:
2437 steps = -1;
2438 break;
2440 case REQ_MOVE_DOWN:
2441 steps = 1;
2442 break;
2444 default:
2445 die("request %d not handled in switch", request);
2448 if (steps <= 0 && view->lineno == 0) {
2449 report("Cannot move beyond the first line");
2450 return;
2452 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2453 report("Cannot move beyond the last line");
2454 return;
2457 /* Move the current line */
2458 view->lineno += steps;
2459 assert(0 <= view->lineno && view->lineno < view->lines);
2461 /* Check whether the view needs to be scrolled */
2462 if (view->lineno < view->offset ||
2463 view->lineno >= view->offset + view->height) {
2464 scroll_steps = steps;
2465 if (steps < 0 && -steps > view->offset) {
2466 scroll_steps = -view->offset;
2468 } else if (steps > 0) {
2469 if (view->lineno == view->lines - 1 &&
2470 view->lines > view->height) {
2471 scroll_steps = view->lines - view->offset - 1;
2472 if (scroll_steps >= view->height)
2473 scroll_steps -= view->height - 1;
2478 if (!view_is_displayed(view)) {
2479 view->offset += scroll_steps;
2480 assert(0 <= view->offset && view->offset < view->lines);
2481 view->ops->select(view, &view->line[view->lineno]);
2482 return;
2485 /* Repaint the old "current" line if we be scrolling */
2486 if (ABS(steps) < view->height)
2487 draw_view_line(view, view->lineno - steps - view->offset);
2489 if (scroll_steps) {
2490 do_scroll_view(view, scroll_steps);
2491 return;
2494 /* Draw the current line */
2495 draw_view_line(view, view->lineno - view->offset);
2497 wnoutrefresh(view->win);
2498 report("");
2503 * Searching
2506 static void search_view(struct view *view, enum request request);
2508 static bool
2509 grep_text(struct view *view, const char *text[])
2511 regmatch_t pmatch;
2512 size_t i;
2514 for (i = 0; text[i]; i++)
2515 if (*text[i] &&
2516 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2517 return TRUE;
2518 return FALSE;
2521 static void
2522 select_view_line(struct view *view, unsigned long lineno)
2524 unsigned long old_lineno = view->lineno;
2525 unsigned long old_offset = view->offset;
2527 if (goto_view_line(view, view->offset, lineno)) {
2528 if (view_is_displayed(view)) {
2529 if (old_offset != view->offset) {
2530 redraw_view(view);
2531 } else {
2532 draw_view_line(view, old_lineno - view->offset);
2533 draw_view_line(view, view->lineno - view->offset);
2534 wnoutrefresh(view->win);
2536 } else {
2537 view->ops->select(view, &view->line[view->lineno]);
2542 static void
2543 find_next(struct view *view, enum request request)
2545 unsigned long lineno = view->lineno;
2546 int direction;
2548 if (!*view->grep) {
2549 if (!*opt_search)
2550 report("No previous search");
2551 else
2552 search_view(view, request);
2553 return;
2556 switch (request) {
2557 case REQ_SEARCH:
2558 case REQ_FIND_NEXT:
2559 direction = 1;
2560 break;
2562 case REQ_SEARCH_BACK:
2563 case REQ_FIND_PREV:
2564 direction = -1;
2565 break;
2567 default:
2568 return;
2571 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2572 lineno += direction;
2574 /* Note, lineno is unsigned long so will wrap around in which case it
2575 * will become bigger than view->lines. */
2576 for (; lineno < view->lines; lineno += direction) {
2577 if (view->ops->grep(view, &view->line[lineno])) {
2578 select_view_line(view, lineno);
2579 report("Line %ld matches '%s'", lineno + 1, view->grep);
2580 return;
2584 report("No match found for '%s'", view->grep);
2587 static void
2588 search_view(struct view *view, enum request request)
2590 int regex_err;
2592 if (view->regex) {
2593 regfree(view->regex);
2594 *view->grep = 0;
2595 } else {
2596 view->regex = calloc(1, sizeof(*view->regex));
2597 if (!view->regex)
2598 return;
2601 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2602 if (regex_err != 0) {
2603 char buf[SIZEOF_STR] = "unknown error";
2605 regerror(regex_err, view->regex, buf, sizeof(buf));
2606 report("Search failed: %s", buf);
2607 return;
2610 string_copy(view->grep, opt_search);
2612 find_next(view, request);
2616 * Incremental updating
2619 static void
2620 reset_view(struct view *view)
2622 int i;
2624 for (i = 0; i < view->lines; i++)
2625 free(view->line[i].data);
2626 free(view->line);
2628 view->p_offset = view->offset;
2629 view->p_yoffset = view->yoffset;
2630 view->p_lineno = view->lineno;
2632 view->line = NULL;
2633 view->offset = 0;
2634 view->yoffset = 0;
2635 view->lines = 0;
2636 view->lineno = 0;
2637 view->vid[0] = 0;
2638 view->update_secs = 0;
2641 static const char *
2642 format_arg(const char *name)
2644 static struct {
2645 const char *name;
2646 size_t namelen;
2647 const char *value;
2648 const char *value_if_empty;
2649 } vars[] = {
2650 #define FORMAT_VAR(name, value, value_if_empty) \
2651 { name, STRING_SIZE(name), value, value_if_empty }
2652 FORMAT_VAR("%(directory)", opt_path, "."),
2653 FORMAT_VAR("%(file)", opt_file, ""),
2654 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2655 FORMAT_VAR("%(head)", ref_head, ""),
2656 FORMAT_VAR("%(commit)", ref_commit, ""),
2657 FORMAT_VAR("%(blob)", ref_blob, ""),
2658 FORMAT_VAR("%(branch)", ref_branch, ""),
2660 int i;
2662 for (i = 0; i < ARRAY_SIZE(vars); i++)
2663 if (!strncmp(name, vars[i].name, vars[i].namelen))
2664 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2666 report("Unknown replacement: `%s`", name);
2667 return NULL;
2670 static bool
2671 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2673 char buf[SIZEOF_STR];
2674 int argc;
2676 argv_free(*dst_argv);
2678 for (argc = 0; src_argv[argc]; argc++) {
2679 const char *arg = src_argv[argc];
2680 size_t bufpos = 0;
2682 if (!strcmp(arg, "%(fileargs)")) {
2683 if (!argv_append_array(dst_argv, opt_file_argv))
2684 break;
2685 continue;
2687 } else if (!strcmp(arg, "%(diffargs)")) {
2688 if (!argv_append_array(dst_argv, opt_diff_argv))
2689 break;
2690 continue;
2692 } else if (!strcmp(arg, "%(blameargs)")) {
2693 if (!argv_append_array(dst_argv, opt_blame_argv))
2694 break;
2695 continue;
2697 } else if (!strcmp(arg, "%(revargs)") ||
2698 (first && !strcmp(arg, "%(commit)"))) {
2699 if (!argv_append_array(dst_argv, opt_rev_argv))
2700 break;
2701 continue;
2704 while (arg) {
2705 char *next = strstr(arg, "%(");
2706 int len = next - arg;
2707 const char *value;
2709 if (!next) {
2710 len = strlen(arg);
2711 value = "";
2713 } else {
2714 value = format_arg(next);
2716 if (!value) {
2717 return FALSE;
2721 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2722 return FALSE;
2724 arg = next ? strchr(next, ')') + 1 : NULL;
2727 if (!argv_append(dst_argv, buf))
2728 break;
2731 return src_argv[argc] == NULL;
2734 static bool
2735 restore_view_position(struct view *view)
2737 /* A view without a previous view is the first view */
2738 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2739 select_view_line(view, opt_lineno - 1);
2740 opt_lineno = 0;
2743 if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2744 return FALSE;
2746 /* Changing the view position cancels the restoring. */
2747 /* FIXME: Changing back to the first line is not detected. */
2748 if (view->offset != 0 || view->lineno != 0) {
2749 view->p_restore = FALSE;
2750 return FALSE;
2753 if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2754 view_is_displayed(view))
2755 werase(view->win);
2757 view->yoffset = view->p_yoffset;
2758 view->p_restore = FALSE;
2760 return TRUE;
2763 static void
2764 end_update(struct view *view, bool force)
2766 if (!view->pipe)
2767 return;
2768 while (!view->ops->read(view, NULL))
2769 if (!force)
2770 return;
2771 if (force)
2772 io_kill(view->pipe);
2773 io_done(view->pipe);
2774 view->pipe = NULL;
2777 static void
2778 setup_update(struct view *view, const char *vid)
2780 reset_view(view);
2781 string_copy_rev(view->vid, vid);
2782 view->pipe = &view->io;
2783 view->start_time = time(NULL);
2786 static bool
2787 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2789 bool extra = !!(flags & (OPEN_EXTRA));
2790 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2791 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2793 if (!reload && !strcmp(view->vid, view->id))
2794 return TRUE;
2796 if (view->pipe) {
2797 if (extra)
2798 io_done(view->pipe);
2799 else
2800 end_update(view, TRUE);
2803 if (!refresh && argv) {
2804 view->dir = dir;
2805 if (!format_argv(&view->argv, argv, !view->prev))
2806 return FALSE;
2808 /* Put the current ref_* value to the view title ref
2809 * member. This is needed by the blob view. Most other
2810 * views sets it automatically after loading because the
2811 * first line is a commit line. */
2812 string_copy_rev(view->ref, view->id);
2815 if (view->argv && view->argv[0] &&
2816 !io_run(&view->io, IO_RD, view->dir, view->argv))
2817 return FALSE;
2819 if (!extra)
2820 setup_update(view, view->id);
2822 return TRUE;
2825 static bool
2826 update_view(struct view *view)
2828 char *line;
2829 /* Clear the view and redraw everything since the tree sorting
2830 * might have rearranged things. */
2831 bool redraw = view->lines == 0;
2832 bool can_read = TRUE;
2834 if (!view->pipe)
2835 return TRUE;
2837 if (!io_can_read(view->pipe, FALSE)) {
2838 if (view->lines == 0 && view_is_displayed(view)) {
2839 time_t secs = time(NULL) - view->start_time;
2841 if (secs > 1 && secs > view->update_secs) {
2842 if (view->update_secs == 0)
2843 redraw_view(view);
2844 update_view_title(view);
2845 view->update_secs = secs;
2848 return TRUE;
2851 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2852 if (view->encoding) {
2853 line = encoding_convert(view->encoding, line);
2856 if (!view->ops->read(view, line)) {
2857 report("Allocation failure");
2858 end_update(view, TRUE);
2859 return FALSE;
2864 unsigned long lines = view->lines;
2865 int digits;
2867 for (digits = 0; lines; digits++)
2868 lines /= 10;
2870 /* Keep the displayed view in sync with line number scaling. */
2871 if (digits != view->digits) {
2872 view->digits = digits;
2873 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
2874 redraw = TRUE;
2878 if (io_error(view->pipe)) {
2879 report("Failed to read: %s", io_strerror(view->pipe));
2880 end_update(view, TRUE);
2882 } else if (io_eof(view->pipe)) {
2883 if (view_is_displayed(view))
2884 report("");
2885 end_update(view, FALSE);
2888 if (restore_view_position(view))
2889 redraw = TRUE;
2891 if (!view_is_displayed(view))
2892 return TRUE;
2894 if (redraw)
2895 redraw_view_from(view, 0);
2896 else
2897 redraw_view_dirty(view);
2899 /* Update the title _after_ the redraw so that if the redraw picks up a
2900 * commit reference in view->ref it'll be available here. */
2901 update_view_title(view);
2902 return TRUE;
2905 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2907 static struct line *
2908 add_line_data(struct view *view, void *data, enum line_type type)
2910 struct line *line;
2912 if (!realloc_lines(&view->line, view->lines, 1))
2913 return NULL;
2915 line = &view->line[view->lines++];
2916 memset(line, 0, sizeof(*line));
2917 line->type = type;
2918 line->data = data;
2919 line->dirty = 1;
2921 return line;
2924 static struct line *
2925 add_line_text(struct view *view, const char *text, enum line_type type)
2927 char *data = text ? strdup(text) : NULL;
2929 return data ? add_line_data(view, data, type) : NULL;
2932 static struct line *
2933 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2935 char buf[SIZEOF_STR];
2936 int retval;
2938 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
2939 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
2943 * View opening
2946 static void
2947 load_view(struct view *view, enum open_flags flags)
2949 if (view->pipe)
2950 end_update(view, TRUE);
2951 if (view->ops->private_size) {
2952 if (!view->private)
2953 view->private = calloc(1, view->ops->private_size);
2954 else
2955 memset(view->private, 0, view->ops->private_size);
2957 if (!view->ops->open(view, flags)) {
2958 report("Failed to load %s view", view->name);
2959 return;
2961 restore_view_position(view);
2963 if (view->pipe && view->lines == 0) {
2964 /* Clear the old view and let the incremental updating refill
2965 * the screen. */
2966 werase(view->win);
2967 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2968 report("");
2969 } else if (view_is_displayed(view)) {
2970 redraw_view(view);
2971 report("");
2975 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2976 #define reload_view(view) load_view(view, OPEN_RELOAD)
2978 static void
2979 split_view(struct view *prev, struct view *view)
2981 display[1] = view;
2982 current_view = 1;
2983 view->parent = prev;
2984 resize_display();
2986 if (prev->lineno - prev->offset >= prev->height) {
2987 /* Take the title line into account. */
2988 int lines = prev->lineno - prev->offset - prev->height + 1;
2990 /* Scroll the view that was split if the current line is
2991 * outside the new limited view. */
2992 do_scroll_view(prev, lines);
2995 if (view != prev && view_is_displayed(prev)) {
2996 /* "Blur" the previous view. */
2997 update_view_title(prev);
3001 static void
3002 open_view(struct view *prev, enum request request, enum open_flags flags)
3004 bool split = !!(flags & OPEN_SPLIT);
3005 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3006 struct view *view = VIEW(request);
3007 int nviews = displayed_views();
3009 assert(flags ^ OPEN_REFRESH);
3011 if (view == prev && nviews == 1 && !reload) {
3012 report("Already in %s view", view->name);
3013 return;
3016 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3017 report("The %s view is disabled in pager view", view->name);
3018 return;
3021 if (split) {
3022 split_view(prev, view);
3023 } else {
3024 maximize_view(view, FALSE);
3027 /* No prev signals that this is the first loaded view. */
3028 if (prev && view != prev) {
3029 view->prev = prev;
3032 load_view(view, flags);
3035 static void
3036 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3038 enum request request = view - views + REQ_OFFSET + 1;
3040 if (view->pipe)
3041 end_update(view, TRUE);
3042 view->dir = dir;
3044 if (!argv_copy(&view->argv, argv)) {
3045 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3046 } else {
3047 open_view(prev, request, flags | OPEN_PREPARED);
3051 static void
3052 open_external_viewer(const char *argv[], const char *dir)
3054 def_prog_mode(); /* save current tty modes */
3055 endwin(); /* restore original tty modes */
3056 io_run_fg(argv, dir);
3057 fprintf(stderr, "Press Enter to continue");
3058 getc(opt_tty);
3059 reset_prog_mode();
3060 redraw_display(TRUE);
3063 static void
3064 open_mergetool(const char *file)
3066 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3068 open_external_viewer(mergetool_argv, opt_cdup);
3071 static void
3072 open_editor(const char *file)
3074 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3075 char editor_cmd[SIZEOF_STR];
3076 const char *editor;
3077 int argc = 0;
3079 editor = getenv("GIT_EDITOR");
3080 if (!editor && *opt_editor)
3081 editor = opt_editor;
3082 if (!editor)
3083 editor = getenv("VISUAL");
3084 if (!editor)
3085 editor = getenv("EDITOR");
3086 if (!editor)
3087 editor = "vi";
3089 string_ncopy(editor_cmd, editor, strlen(editor));
3090 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3091 report("Failed to read editor command");
3092 return;
3095 editor_argv[argc] = file;
3096 open_external_viewer(editor_argv, opt_cdup);
3099 static void
3100 open_run_request(enum request request)
3102 struct run_request *req = get_run_request(request);
3103 const char **argv = NULL;
3105 if (!req) {
3106 report("Unknown run request");
3107 return;
3110 if (format_argv(&argv, req->argv, FALSE))
3111 open_external_viewer(argv, NULL);
3112 if (argv)
3113 argv_free(argv);
3114 free(argv);
3118 * User request switch noodle
3121 static int
3122 view_driver(struct view *view, enum request request)
3124 int i;
3126 if (request == REQ_NONE)
3127 return TRUE;
3129 if (request > REQ_NONE) {
3130 open_run_request(request);
3131 view_request(view, REQ_REFRESH);
3132 return TRUE;
3135 request = view_request(view, request);
3136 if (request == REQ_NONE)
3137 return TRUE;
3139 switch (request) {
3140 case REQ_MOVE_UP:
3141 case REQ_MOVE_DOWN:
3142 case REQ_MOVE_PAGE_UP:
3143 case REQ_MOVE_PAGE_DOWN:
3144 case REQ_MOVE_FIRST_LINE:
3145 case REQ_MOVE_LAST_LINE:
3146 move_view(view, request);
3147 break;
3149 case REQ_SCROLL_FIRST_COL:
3150 case REQ_SCROLL_LEFT:
3151 case REQ_SCROLL_RIGHT:
3152 case REQ_SCROLL_LINE_DOWN:
3153 case REQ_SCROLL_LINE_UP:
3154 case REQ_SCROLL_PAGE_DOWN:
3155 case REQ_SCROLL_PAGE_UP:
3156 scroll_view(view, request);
3157 break;
3159 case REQ_VIEW_BLAME:
3160 if (!opt_file[0]) {
3161 report("No file chosen, press %s to open tree view",
3162 get_view_key(view, REQ_VIEW_TREE));
3163 break;
3165 open_view(view, request, OPEN_DEFAULT);
3166 break;
3168 case REQ_VIEW_BLOB:
3169 if (!ref_blob[0]) {
3170 report("No file chosen, press %s to open tree view",
3171 get_view_key(view, REQ_VIEW_TREE));
3172 break;
3174 open_view(view, request, OPEN_DEFAULT);
3175 break;
3177 case REQ_VIEW_PAGER:
3178 if (view == NULL) {
3179 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
3180 die("Failed to open stdin");
3181 open_view(view, request, OPEN_PREPARED);
3182 break;
3185 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
3186 report("No pager content, press %s to run command from prompt",
3187 get_view_key(view, REQ_PROMPT));
3188 break;
3190 open_view(view, request, OPEN_DEFAULT);
3191 break;
3193 case REQ_VIEW_STAGE:
3194 if (!VIEW(REQ_VIEW_STAGE)->lines) {
3195 report("No stage content, press %s to open the status view and choose file",
3196 get_view_key(view, REQ_VIEW_STATUS));
3197 break;
3199 open_view(view, request, OPEN_DEFAULT);
3200 break;
3202 case REQ_VIEW_STATUS:
3203 if (opt_is_inside_work_tree == FALSE) {
3204 report("The status view requires a working tree");
3205 break;
3207 open_view(view, request, OPEN_DEFAULT);
3208 break;
3210 case REQ_VIEW_MAIN:
3211 case REQ_VIEW_DIFF:
3212 case REQ_VIEW_LOG:
3213 case REQ_VIEW_TREE:
3214 case REQ_VIEW_HELP:
3215 case REQ_VIEW_BRANCH:
3216 open_view(view, request, OPEN_DEFAULT);
3217 break;
3219 case REQ_NEXT:
3220 case REQ_PREVIOUS:
3221 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
3223 if (view->parent) {
3224 int line;
3226 view = view->parent;
3227 line = view->lineno;
3228 move_view(view, request);
3229 if (view_is_displayed(view))
3230 update_view_title(view);
3231 if (line != view->lineno)
3232 view_request(view, REQ_ENTER);
3233 } else {
3234 move_view(view, request);
3236 break;
3238 case REQ_VIEW_NEXT:
3240 int nviews = displayed_views();
3241 int next_view = (current_view + 1) % nviews;
3243 if (next_view == current_view) {
3244 report("Only one view is displayed");
3245 break;
3248 current_view = next_view;
3249 /* Blur out the title of the previous view. */
3250 update_view_title(view);
3251 report("");
3252 break;
3254 case REQ_REFRESH:
3255 report("Refreshing is not yet supported for the %s view", view->name);
3256 break;
3258 case REQ_MAXIMIZE:
3259 if (displayed_views() == 2)
3260 maximize_view(view, TRUE);
3261 break;
3263 case REQ_OPTIONS:
3264 case REQ_TOGGLE_LINENO:
3265 case REQ_TOGGLE_DATE:
3266 case REQ_TOGGLE_AUTHOR:
3267 case REQ_TOGGLE_FILENAME:
3268 case REQ_TOGGLE_GRAPHIC:
3269 case REQ_TOGGLE_REV_GRAPH:
3270 case REQ_TOGGLE_REFS:
3271 case REQ_TOGGLE_IGNORE_SPACE:
3272 if (toggle_option(request))
3273 reload_view(view);
3274 break;
3276 case REQ_TOGGLE_SORT_FIELD:
3277 case REQ_TOGGLE_SORT_ORDER:
3278 report("Sorting is not yet supported for the %s view", view->name);
3279 break;
3281 case REQ_DIFF_CONTEXT_UP:
3282 case REQ_DIFF_CONTEXT_DOWN:
3283 report("Changing the diff context is not yet supported for the %s view", view->name);
3284 break;
3286 case REQ_SEARCH:
3287 case REQ_SEARCH_BACK:
3288 search_view(view, request);
3289 break;
3291 case REQ_FIND_NEXT:
3292 case REQ_FIND_PREV:
3293 find_next(view, request);
3294 break;
3296 case REQ_STOP_LOADING:
3297 foreach_view(view, i) {
3298 if (view->pipe)
3299 report("Stopped loading the %s view", view->name),
3300 end_update(view, TRUE);
3302 break;
3304 case REQ_SHOW_VERSION:
3305 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3306 return TRUE;
3308 case REQ_SCREEN_REDRAW:
3309 redraw_display(TRUE);
3310 break;
3312 case REQ_EDIT:
3313 report("Nothing to edit");
3314 break;
3316 case REQ_ENTER:
3317 report("Nothing to enter");
3318 break;
3320 case REQ_VIEW_CLOSE:
3321 /* XXX: Mark closed views by letting view->prev point to the
3322 * view itself. Parents to closed view should never be
3323 * followed. */
3324 if (view->prev && view->prev != view) {
3325 maximize_view(view->prev, TRUE);
3326 view->prev = view;
3327 break;
3329 /* Fall-through */
3330 case REQ_QUIT:
3331 return FALSE;
3333 default:
3334 report("Unknown key, press %s for help",
3335 get_view_key(view, REQ_VIEW_HELP));
3336 return TRUE;
3339 return TRUE;
3344 * View backend utilities
3347 enum sort_field {
3348 ORDERBY_NAME,
3349 ORDERBY_DATE,
3350 ORDERBY_AUTHOR,
3353 struct sort_state {
3354 const enum sort_field *fields;
3355 size_t size, current;
3356 bool reverse;
3359 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3360 #define get_sort_field(state) ((state).fields[(state).current])
3361 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3363 static void
3364 sort_view(struct view *view, enum request request, struct sort_state *state,
3365 int (*compare)(const void *, const void *))
3367 switch (request) {
3368 case REQ_TOGGLE_SORT_FIELD:
3369 state->current = (state->current + 1) % state->size;
3370 break;
3372 case REQ_TOGGLE_SORT_ORDER:
3373 state->reverse = !state->reverse;
3374 break;
3375 default:
3376 die("Not a sort request");
3379 qsort(view->line, view->lines, sizeof(*view->line), compare);
3380 redraw_view(view);
3383 static bool
3384 update_diff_context(enum request request)
3386 int diff_context = opt_diff_context;
3388 switch (request) {
3389 case REQ_DIFF_CONTEXT_UP:
3390 opt_diff_context += 1;
3391 update_diff_context_arg(opt_diff_context);
3392 break;
3394 case REQ_DIFF_CONTEXT_DOWN:
3395 if (opt_diff_context == 0) {
3396 report("Diff context cannot be less than zero");
3397 break;
3399 opt_diff_context -= 1;
3400 update_diff_context_arg(opt_diff_context);
3401 break;
3403 default:
3404 die("Not a diff context request");
3407 return diff_context != opt_diff_context;
3410 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3412 /* Small author cache to reduce memory consumption. It uses binary
3413 * search to lookup or find place to position new entries. No entries
3414 * are ever freed. */
3415 static const char *
3416 get_author(const char *name)
3418 static const char **authors;
3419 static size_t authors_size;
3420 int from = 0, to = authors_size - 1;
3422 while (from <= to) {
3423 size_t pos = (to + from) / 2;
3424 int cmp = strcmp(name, authors[pos]);
3426 if (!cmp)
3427 return authors[pos];
3429 if (cmp < 0)
3430 to = pos - 1;
3431 else
3432 from = pos + 1;
3435 if (!realloc_authors(&authors, authors_size, 1))
3436 return NULL;
3437 name = strdup(name);
3438 if (!name)
3439 return NULL;
3441 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3442 authors[from] = name;
3443 authors_size++;
3445 return name;
3448 static void
3449 parse_timesec(struct time *time, const char *sec)
3451 time->sec = (time_t) atol(sec);
3454 static void
3455 parse_timezone(struct time *time, const char *zone)
3457 long tz;
3459 tz = ('0' - zone[1]) * 60 * 60 * 10;
3460 tz += ('0' - zone[2]) * 60 * 60;
3461 tz += ('0' - zone[3]) * 60 * 10;
3462 tz += ('0' - zone[4]) * 60;
3464 if (zone[0] == '-')
3465 tz = -tz;
3467 time->tz = tz;
3468 time->sec -= tz;
3471 /* Parse author lines where the name may be empty:
3472 * author <email@address.tld> 1138474660 +0100
3474 static void
3475 parse_author_line(char *ident, const char **author, struct time *time)
3477 char *nameend = strchr(ident, '<');
3478 char *emailend = strchr(ident, '>');
3480 if (nameend && emailend)
3481 *nameend = *emailend = 0;
3482 ident = chomp_string(ident);
3483 if (!*ident) {
3484 if (nameend)
3485 ident = chomp_string(nameend + 1);
3486 if (!*ident)
3487 ident = "Unknown";
3490 *author = get_author(ident);
3492 /* Parse epoch and timezone */
3493 if (emailend && emailend[1] == ' ') {
3494 char *secs = emailend + 2;
3495 char *zone = strchr(secs, ' ');
3497 parse_timesec(time, secs);
3499 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3500 parse_timezone(time, zone + 1);
3504 static struct line *
3505 find_prev_line_by_type(struct view *view, struct line *line, enum line_type type)
3507 for (; view->line < line; line--)
3508 if (line->type == type)
3509 return line;
3511 return NULL;
3515 * Blame
3518 struct blame_commit {
3519 char id[SIZEOF_REV]; /* SHA1 ID. */
3520 char title[128]; /* First line of the commit message. */
3521 const char *author; /* Author of the commit. */
3522 struct time time; /* Date from the author ident. */
3523 char filename[128]; /* Name of file. */
3524 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3525 char parent_filename[128]; /* Parent/previous name of file. */
3528 struct blame_header {
3529 char id[SIZEOF_REV]; /* SHA1 ID. */
3530 size_t orig_lineno;
3531 size_t lineno;
3532 size_t group;
3535 static bool
3536 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3538 const char *pos = *posref;
3540 *posref = NULL;
3541 pos = strchr(pos + 1, ' ');
3542 if (!pos || !isdigit(pos[1]))
3543 return FALSE;
3544 *number = atoi(pos + 1);
3545 if (*number < min || *number > max)
3546 return FALSE;
3548 *posref = pos;
3549 return TRUE;
3552 static bool
3553 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3555 const char *pos = text + SIZEOF_REV - 2;
3557 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3558 return FALSE;
3560 string_ncopy(header->id, text, SIZEOF_REV);
3562 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3563 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3564 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3565 return FALSE;
3567 return TRUE;
3570 static bool
3571 match_blame_header(const char *name, char **line)
3573 size_t namelen = strlen(name);
3574 bool matched = !strncmp(name, *line, namelen);
3576 if (matched)
3577 *line += namelen;
3579 return matched;
3582 static bool
3583 parse_blame_info(struct blame_commit *commit, char *line)
3585 if (match_blame_header("author ", &line)) {
3586 commit->author = get_author(line);
3588 } else if (match_blame_header("author-time ", &line)) {
3589 parse_timesec(&commit->time, line);
3591 } else if (match_blame_header("author-tz ", &line)) {
3592 parse_timezone(&commit->time, line);
3594 } else if (match_blame_header("summary ", &line)) {
3595 string_ncopy(commit->title, line, strlen(line));
3597 } else if (match_blame_header("previous ", &line)) {
3598 if (strlen(line) <= SIZEOF_REV)
3599 return FALSE;
3600 string_copy_rev(commit->parent_id, line);
3601 line += SIZEOF_REV;
3602 string_ncopy(commit->parent_filename, line, strlen(line));
3604 } else if (match_blame_header("filename ", &line)) {
3605 string_ncopy(commit->filename, line, strlen(line));
3606 return TRUE;
3609 return FALSE;
3613 * Pager backend
3616 static bool
3617 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3619 if (opt_line_number && draw_lineno(view, lineno))
3620 return TRUE;
3622 draw_text(view, line->type, line->data);
3623 return TRUE;
3626 static bool
3627 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3629 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3630 char ref[SIZEOF_STR];
3632 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3633 return TRUE;
3635 /* This is the only fatal call, since it can "corrupt" the buffer. */
3636 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3637 return FALSE;
3639 return TRUE;
3642 static void
3643 add_pager_refs(struct view *view, struct line *line)
3645 char buf[SIZEOF_STR];
3646 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3647 struct ref_list *list;
3648 size_t bufpos = 0, i;
3649 const char *sep = "Refs: ";
3650 bool is_tag = FALSE;
3652 assert(line->type == LINE_COMMIT);
3654 list = get_ref_list(commit_id);
3655 if (!list) {
3656 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3657 goto try_add_describe_ref;
3658 return;
3661 for (i = 0; i < list->size; i++) {
3662 struct ref *ref = list->refs[i];
3663 const char *fmt = ref->tag ? "%s[%s]" :
3664 ref->remote ? "%s<%s>" : "%s%s";
3666 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3667 return;
3668 sep = ", ";
3669 if (ref->tag)
3670 is_tag = TRUE;
3673 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3674 try_add_describe_ref:
3675 /* Add <tag>-g<commit_id> "fake" reference. */
3676 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3677 return;
3680 if (bufpos == 0)
3681 return;
3683 add_line_text(view, buf, LINE_PP_REFS);
3686 static bool
3687 pager_read(struct view *view, char *data)
3689 struct line *line;
3691 if (!data)
3692 return TRUE;
3694 line = add_line_text(view, data, get_line_type(data));
3695 if (!line)
3696 return FALSE;
3698 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
3699 add_pager_refs(view, line);
3701 return TRUE;
3704 static enum request
3705 pager_request(struct view *view, enum request request, struct line *line)
3707 int split = 0;
3709 if (request != REQ_ENTER)
3710 return request;
3712 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
3713 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3714 split = 1;
3717 /* Always scroll the view even if it was split. That way
3718 * you can use Enter to scroll through the log view and
3719 * split open each commit diff. */
3720 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3722 /* FIXME: A minor workaround. Scrolling the view will call report("")
3723 * but if we are scrolling a non-current view this won't properly
3724 * update the view title. */
3725 if (split)
3726 update_view_title(view);
3728 return REQ_NONE;
3731 static bool
3732 pager_grep(struct view *view, struct line *line)
3734 const char *text[] = { line->data, NULL };
3736 return grep_text(view, text);
3739 static void
3740 pager_select(struct view *view, struct line *line)
3742 if (line->type == LINE_COMMIT) {
3743 char *text = (char *)line->data + STRING_SIZE("commit ");
3745 if (!view_has_flags(view, VIEW_NO_REF))
3746 string_copy_rev(view->ref, text);
3747 string_copy_rev(ref_commit, text);
3751 static bool
3752 pager_open(struct view *view, enum open_flags flags)
3754 return begin_update(view, NULL, NULL, flags);
3757 static struct view_ops pager_ops = {
3758 "line",
3759 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
3761 pager_open,
3762 pager_read,
3763 pager_draw,
3764 pager_request,
3765 pager_grep,
3766 pager_select,
3769 static bool
3770 log_open(struct view *view, enum open_flags flags)
3772 static const char *log_argv[] = {
3773 "git", "log", ENCODING_ARG, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3776 return begin_update(view, NULL, log_argv, flags);
3779 static enum request
3780 log_request(struct view *view, enum request request, struct line *line)
3782 switch (request) {
3783 case REQ_REFRESH:
3784 load_refs();
3785 refresh_view(view);
3786 return REQ_NONE;
3787 default:
3788 return pager_request(view, request, line);
3792 static struct view_ops log_ops = {
3793 "line",
3794 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
3796 log_open,
3797 pager_read,
3798 pager_draw,
3799 log_request,
3800 pager_grep,
3801 pager_select,
3804 struct diff_state {
3805 bool reading_diff_stat;
3808 static bool
3809 diff_open(struct view *view, enum open_flags flags)
3811 static const char *diff_argv[] = {
3812 "git", "show", ENCODING_ARG, "--pretty=fuller", "--no-color", "--root",
3813 "--patch-with-stat", "--find-copies-harder", "-C",
3814 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
3815 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3818 return begin_update(view, NULL, diff_argv, flags);
3821 static bool
3822 diff_common_read(struct view *view, char *data, struct diff_state *state)
3824 if (state->reading_diff_stat) {
3825 size_t len = strlen(data);
3826 char *pipe = strchr(data, '|');
3827 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3828 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3830 if (pipe && (has_histogram || has_bin_diff)) {
3831 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3832 } else {
3833 state->reading_diff_stat = FALSE;
3836 } else if (!strcmp(data, "---")) {
3837 state->reading_diff_stat = TRUE;
3840 return pager_read(view, data);
3843 static enum request
3844 diff_common_enter(struct view *view, enum request request, struct line *line)
3846 if (line->type == LINE_DIFF_STAT) {
3847 int file_number = 0;
3849 while (line >= view->line && line->type == LINE_DIFF_STAT) {
3850 file_number++;
3851 line--;
3854 while (line < view->line + view->lines) {
3855 if (line->type == LINE_DIFF_HEADER) {
3856 if (file_number == 1) {
3857 break;
3859 file_number--;
3861 line++;
3865 select_view_line(view, line - view->line);
3866 report("");
3867 return REQ_NONE;
3869 } else {
3870 return pager_request(view, request, line);
3874 static bool
3875 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
3877 char *sep = strchr(*text, c);
3879 if (sep != NULL) {
3880 *sep = 0;
3881 draw_text(view, *type, *text);
3882 *sep = c;
3883 *text = sep;
3884 *type = next_type;
3887 return sep != NULL;
3890 static bool
3891 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
3893 char *text = line->data;
3894 enum line_type type = line->type;
3896 if (opt_line_number && draw_lineno(view, lineno))
3897 return TRUE;
3899 if (type == LINE_DIFF_STAT) {
3900 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
3901 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
3902 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
3903 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
3904 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
3905 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
3906 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
3908 } else {
3909 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
3910 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
3914 draw_text(view, type, text);
3915 return TRUE;
3918 static bool
3919 diff_read(struct view *view, char *data)
3921 struct diff_state *state = view->private;
3923 if (!data) {
3924 /* Fall back to retry if no diff will be shown. */
3925 if (view->lines == 0 && opt_file_argv) {
3926 int pos = argv_size(view->argv)
3927 - argv_size(opt_file_argv) - 1;
3929 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3930 for (; view->argv[pos]; pos++) {
3931 free((void *) view->argv[pos]);
3932 view->argv[pos] = NULL;
3935 if (view->pipe)
3936 io_done(view->pipe);
3937 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3938 return FALSE;
3941 return TRUE;
3944 return diff_common_read(view, data, state);
3947 static bool
3948 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
3949 struct blame_header *header, struct blame_commit *commit)
3951 char line_arg[SIZEOF_STR];
3952 const char *blame_argv[] = {
3953 "git", "blame", ENCODING_ARG, "-p", line_arg, ref, "--", file, NULL
3955 struct io io;
3956 bool ok = FALSE;
3957 char *buf;
3959 if (!string_format(line_arg, "-L%d,+1", lineno))
3960 return FALSE;
3962 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
3963 return FALSE;
3965 while ((buf = io_get(&io, '\n', TRUE))) {
3966 if (header) {
3967 if (!parse_blame_header(header, buf, 9999999))
3968 break;
3969 header = NULL;
3971 } else if (parse_blame_info(commit, buf)) {
3972 ok = TRUE;
3973 break;
3977 if (io_error(&io))
3978 ok = FALSE;
3980 io_done(&io);
3981 return ok;
3984 static bool
3985 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
3987 return prefixcmp(chunk, "@@ -") ||
3988 !(chunk = strchr(chunk, marker)) ||
3989 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
3992 static enum request
3993 diff_trace_origin(struct view *view, struct line *line)
3995 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
3996 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
3997 const char *chunk_data;
3998 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
3999 int lineno = 0;
4000 const char *file = NULL;
4001 char ref[SIZEOF_REF];
4002 struct blame_header header;
4003 struct blame_commit commit;
4005 if (!diff || !chunk || chunk == line) {
4006 report("The line to trace must be inside a diff chunk");
4007 return REQ_NONE;
4010 for (; diff < line && !file; diff++) {
4011 const char *data = diff->data;
4013 if (!prefixcmp(data, "--- a/")) {
4014 file = data + STRING_SIZE("--- a/");
4015 break;
4019 if (diff == line || !file) {
4020 report("Failed to read the file name");
4021 return REQ_NONE;
4024 chunk_data = chunk->data;
4026 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4027 report("Failed to read the line number");
4028 return REQ_NONE;
4031 if (lineno == 0) {
4032 report("This is the origin of the line");
4033 return REQ_NONE;
4036 for (chunk += 1; chunk < line; chunk++) {
4037 if (chunk->type == LINE_DIFF_ADD) {
4038 lineno += chunk_marker == '+';
4039 } else if (chunk->type == LINE_DIFF_DEL) {
4040 lineno += chunk_marker == '-';
4041 } else {
4042 lineno++;
4046 if (chunk_marker == '+')
4047 string_copy(ref, view->vid);
4048 else
4049 string_format(ref, "%s^", view->vid);
4051 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4052 report("Failed to read blame data");
4053 return REQ_NONE;
4056 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4057 string_copy(opt_ref, header.id);
4058 opt_goto_line = header.orig_lineno - 1;
4060 return REQ_VIEW_BLAME;
4063 static enum request
4064 diff_request(struct view *view, enum request request, struct line *line)
4066 switch (request) {
4067 case REQ_VIEW_BLAME:
4068 return diff_trace_origin(view, line);
4070 case REQ_DIFF_CONTEXT_UP:
4071 case REQ_DIFF_CONTEXT_DOWN:
4072 if (!update_diff_context(request))
4073 return REQ_NONE;
4074 reload_view(view);
4075 return REQ_NONE;
4078 case REQ_ENTER:
4079 return diff_common_enter(view, request, line);
4081 default:
4082 return pager_request(view, request, line);
4086 static void
4087 diff_select(struct view *view, struct line *line)
4089 if (line->type == LINE_DIFF_STAT) {
4090 const char *key = get_view_key(view, REQ_ENTER);
4092 string_format(view->ref, "Press '%s' to jump to file diff", key);
4093 } else {
4094 string_ncopy(view->ref, view->id, strlen(view->id));
4095 return pager_select(view, line);
4099 static struct view_ops diff_ops = {
4100 "line",
4101 VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS,
4102 sizeof(struct diff_state),
4103 diff_open,
4104 diff_read,
4105 diff_common_draw,
4106 diff_request,
4107 pager_grep,
4108 diff_select,
4112 * Help backend
4115 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
4117 static bool
4118 help_open_keymap_title(struct view *view, enum keymap keymap)
4120 struct line *line;
4122 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
4123 help_keymap_hidden[keymap] ? '+' : '-',
4124 enum_name(keymap_map[keymap]));
4125 if (line)
4126 line->other = keymap;
4128 return help_keymap_hidden[keymap];
4131 static void
4132 help_open_keymap(struct view *view, enum keymap keymap)
4134 const char *group = NULL;
4135 char buf[SIZEOF_STR];
4136 size_t bufpos;
4137 bool add_title = TRUE;
4138 int i;
4140 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4141 const char *key = NULL;
4143 if (req_info[i].request == REQ_NONE)
4144 continue;
4146 if (!req_info[i].request) {
4147 group = req_info[i].help;
4148 continue;
4151 key = get_keys(keymap, req_info[i].request, TRUE);
4152 if (!key || !*key)
4153 continue;
4155 if (add_title && help_open_keymap_title(view, keymap))
4156 return;
4157 add_title = FALSE;
4159 if (group) {
4160 add_line_text(view, group, LINE_HELP_GROUP);
4161 group = NULL;
4164 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4165 enum_name(req_info[i]), req_info[i].help);
4168 group = "External commands:";
4170 for (i = 0; i < run_requests; i++) {
4171 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4172 const char *key;
4173 int argc;
4175 if (!req || req->keymap != keymap)
4176 continue;
4178 key = get_key_name(req->key);
4179 if (!*key)
4180 key = "(no key defined)";
4182 if (add_title && help_open_keymap_title(view, keymap))
4183 return;
4184 if (group) {
4185 add_line_text(view, group, LINE_HELP_GROUP);
4186 group = NULL;
4189 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
4190 if (!string_format_from(buf, &bufpos, "%s%s",
4191 argc ? " " : "", req->argv[argc]))
4192 return;
4194 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4198 static bool
4199 help_open(struct view *view, enum open_flags flags)
4201 enum keymap keymap;
4203 reset_view(view);
4204 view->p_restore = TRUE;
4205 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4206 add_line_text(view, "", LINE_DEFAULT);
4208 for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
4209 help_open_keymap(view, keymap);
4211 return TRUE;
4214 static enum request
4215 help_request(struct view *view, enum request request, struct line *line)
4217 switch (request) {
4218 case REQ_ENTER:
4219 if (line->type == LINE_HELP_KEYMAP) {
4220 help_keymap_hidden[line->other] =
4221 !help_keymap_hidden[line->other];
4222 refresh_view(view);
4225 return REQ_NONE;
4226 default:
4227 return pager_request(view, request, line);
4231 static struct view_ops help_ops = {
4232 "line",
4233 VIEW_NO_GIT_DIR,
4235 help_open,
4236 NULL,
4237 pager_draw,
4238 help_request,
4239 pager_grep,
4240 pager_select,
4245 * Tree backend
4248 struct tree_stack_entry {
4249 struct tree_stack_entry *prev; /* Entry below this in the stack */
4250 unsigned long lineno; /* Line number to restore */
4251 char *name; /* Position of name in opt_path */
4254 /* The top of the path stack. */
4255 static struct tree_stack_entry *tree_stack = NULL;
4256 unsigned long tree_lineno = 0;
4258 static void
4259 pop_tree_stack_entry(void)
4261 struct tree_stack_entry *entry = tree_stack;
4263 tree_lineno = entry->lineno;
4264 entry->name[0] = 0;
4265 tree_stack = entry->prev;
4266 free(entry);
4269 static void
4270 push_tree_stack_entry(const char *name, unsigned long lineno)
4272 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4273 size_t pathlen = strlen(opt_path);
4275 if (!entry)
4276 return;
4278 entry->prev = tree_stack;
4279 entry->name = opt_path + pathlen;
4280 tree_stack = entry;
4282 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4283 pop_tree_stack_entry();
4284 return;
4287 /* Move the current line to the first tree entry. */
4288 tree_lineno = 1;
4289 entry->lineno = lineno;
4292 /* Parse output from git-ls-tree(1):
4294 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4297 #define SIZEOF_TREE_ATTR \
4298 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4300 #define SIZEOF_TREE_MODE \
4301 STRING_SIZE("100644 ")
4303 #define TREE_ID_OFFSET \
4304 STRING_SIZE("100644 blob ")
4306 struct tree_entry {
4307 char id[SIZEOF_REV];
4308 mode_t mode;
4309 struct time time; /* Date from the author ident. */
4310 const char *author; /* Author of the commit. */
4311 char name[1];
4314 struct tree_state {
4315 const char *author_name;
4316 struct time author_time;
4317 bool read_date;
4320 static const char *
4321 tree_path(const struct line *line)
4323 return ((struct tree_entry *) line->data)->name;
4326 static int
4327 tree_compare_entry(const struct line *line1, const struct line *line2)
4329 if (line1->type != line2->type)
4330 return line1->type == LINE_TREE_DIR ? -1 : 1;
4331 return strcmp(tree_path(line1), tree_path(line2));
4334 static const enum sort_field tree_sort_fields[] = {
4335 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4337 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4339 static int
4340 tree_compare(const void *l1, const void *l2)
4342 const struct line *line1 = (const struct line *) l1;
4343 const struct line *line2 = (const struct line *) l2;
4344 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4345 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4347 if (line1->type == LINE_TREE_HEAD)
4348 return -1;
4349 if (line2->type == LINE_TREE_HEAD)
4350 return 1;
4352 switch (get_sort_field(tree_sort_state)) {
4353 case ORDERBY_DATE:
4354 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4356 case ORDERBY_AUTHOR:
4357 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4359 case ORDERBY_NAME:
4360 default:
4361 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4366 static struct line *
4367 tree_entry(struct view *view, enum line_type type, const char *path,
4368 const char *mode, const char *id)
4370 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4371 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4373 if (!entry || !line) {
4374 free(entry);
4375 return NULL;
4378 strncpy(entry->name, path, strlen(path));
4379 if (mode)
4380 entry->mode = strtoul(mode, NULL, 8);
4381 if (id)
4382 string_copy_rev(entry->id, id);
4384 return line;
4387 static bool
4388 tree_read_date(struct view *view, char *text, struct tree_state *state)
4390 if (!text && state->read_date) {
4391 state->read_date = FALSE;
4392 return TRUE;
4394 } else if (!text) {
4395 /* Find next entry to process */
4396 const char *log_file[] = {
4397 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
4398 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4401 if (!view->lines) {
4402 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4403 report("Tree is empty");
4404 return TRUE;
4407 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4408 report("Failed to load tree data");
4409 return TRUE;
4412 state->read_date = TRUE;
4413 return FALSE;
4415 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4416 parse_author_line(text + STRING_SIZE("author "),
4417 &state->author_name, &state->author_time);
4419 } else if (*text == ':') {
4420 char *pos;
4421 size_t annotated = 1;
4422 size_t i;
4424 pos = strchr(text, '\t');
4425 if (!pos)
4426 return TRUE;
4427 text = pos + 1;
4428 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4429 text += strlen(opt_path);
4430 pos = strchr(text, '/');
4431 if (pos)
4432 *pos = 0;
4434 for (i = 1; i < view->lines; i++) {
4435 struct line *line = &view->line[i];
4436 struct tree_entry *entry = line->data;
4438 annotated += !!entry->author;
4439 if (entry->author || strcmp(entry->name, text))
4440 continue;
4442 entry->author = state->author_name;
4443 entry->time = state->author_time;
4444 line->dirty = 1;
4445 break;
4448 if (annotated == view->lines)
4449 io_kill(view->pipe);
4451 return TRUE;
4454 static bool
4455 tree_read(struct view *view, char *text)
4457 struct tree_state *state = view->private;
4458 struct tree_entry *data;
4459 struct line *entry, *line;
4460 enum line_type type;
4461 size_t textlen = text ? strlen(text) : 0;
4462 char *path = text + SIZEOF_TREE_ATTR;
4464 if (state->read_date || !text)
4465 return tree_read_date(view, text, state);
4467 if (textlen <= SIZEOF_TREE_ATTR)
4468 return FALSE;
4469 if (view->lines == 0 &&
4470 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4471 return FALSE;
4473 /* Strip the path part ... */
4474 if (*opt_path) {
4475 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4476 size_t striplen = strlen(opt_path);
4478 if (pathlen > striplen)
4479 memmove(path, path + striplen,
4480 pathlen - striplen + 1);
4482 /* Insert "link" to parent directory. */
4483 if (view->lines == 1 &&
4484 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4485 return FALSE;
4488 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4489 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4490 if (!entry)
4491 return FALSE;
4492 data = entry->data;
4494 /* Skip "Directory ..." and ".." line. */
4495 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4496 if (tree_compare_entry(line, entry) <= 0)
4497 continue;
4499 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4501 line->data = data;
4502 line->type = type;
4503 for (; line <= entry; line++)
4504 line->dirty = line->cleareol = 1;
4505 return TRUE;
4508 if (tree_lineno > view->lineno) {
4509 view->lineno = tree_lineno;
4510 tree_lineno = 0;
4513 return TRUE;
4516 static bool
4517 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4519 struct tree_entry *entry = line->data;
4521 if (line->type == LINE_TREE_HEAD) {
4522 if (draw_text(view, line->type, "Directory path /"))
4523 return TRUE;
4524 } else {
4525 if (draw_mode(view, entry->mode))
4526 return TRUE;
4528 if (draw_author(view, entry->author))
4529 return TRUE;
4531 if (draw_date(view, &entry->time))
4532 return TRUE;
4535 draw_text(view, line->type, entry->name);
4536 return TRUE;
4539 static void
4540 open_blob_editor(const char *id)
4542 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4543 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4544 int fd = mkstemp(file);
4546 if (fd == -1)
4547 report("Failed to create temporary file");
4548 else if (!io_run_append(blob_argv, fd))
4549 report("Failed to save blob data to file");
4550 else
4551 open_editor(file);
4552 if (fd != -1)
4553 unlink(file);
4556 static enum request
4557 tree_request(struct view *view, enum request request, struct line *line)
4559 enum open_flags flags;
4560 struct tree_entry *entry = line->data;
4562 switch (request) {
4563 case REQ_VIEW_BLAME:
4564 if (line->type != LINE_TREE_FILE) {
4565 report("Blame only supported for files");
4566 return REQ_NONE;
4569 string_copy(opt_ref, view->vid);
4570 return request;
4572 case REQ_EDIT:
4573 if (line->type != LINE_TREE_FILE) {
4574 report("Edit only supported for files");
4575 } else if (!is_head_commit(view->vid)) {
4576 open_blob_editor(entry->id);
4577 } else {
4578 open_editor(opt_file);
4580 return REQ_NONE;
4582 case REQ_TOGGLE_SORT_FIELD:
4583 case REQ_TOGGLE_SORT_ORDER:
4584 sort_view(view, request, &tree_sort_state, tree_compare);
4585 return REQ_NONE;
4587 case REQ_PARENT:
4588 if (!*opt_path) {
4589 /* quit view if at top of tree */
4590 return REQ_VIEW_CLOSE;
4592 /* fake 'cd ..' */
4593 line = &view->line[1];
4594 break;
4596 case REQ_ENTER:
4597 break;
4599 default:
4600 return request;
4603 /* Cleanup the stack if the tree view is at a different tree. */
4604 while (!*opt_path && tree_stack)
4605 pop_tree_stack_entry();
4607 switch (line->type) {
4608 case LINE_TREE_DIR:
4609 /* Depending on whether it is a subdirectory or parent link
4610 * mangle the path buffer. */
4611 if (line == &view->line[1] && *opt_path) {
4612 pop_tree_stack_entry();
4614 } else {
4615 const char *basename = tree_path(line);
4617 push_tree_stack_entry(basename, view->lineno);
4620 /* Trees and subtrees share the same ID, so they are not not
4621 * unique like blobs. */
4622 flags = OPEN_RELOAD;
4623 request = REQ_VIEW_TREE;
4624 break;
4626 case LINE_TREE_FILE:
4627 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4628 request = REQ_VIEW_BLOB;
4629 break;
4631 default:
4632 return REQ_NONE;
4635 open_view(view, request, flags);
4636 if (request == REQ_VIEW_TREE)
4637 view->lineno = tree_lineno;
4639 return REQ_NONE;
4642 static bool
4643 tree_grep(struct view *view, struct line *line)
4645 struct tree_entry *entry = line->data;
4646 const char *text[] = {
4647 entry->name,
4648 mkauthor(entry->author, opt_author_cols, opt_author),
4649 mkdate(&entry->time, opt_date),
4650 NULL
4653 return grep_text(view, text);
4656 static void
4657 tree_select(struct view *view, struct line *line)
4659 struct tree_entry *entry = line->data;
4661 if (line->type == LINE_TREE_FILE) {
4662 string_copy_rev(ref_blob, entry->id);
4663 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4665 } else if (line->type != LINE_TREE_DIR) {
4666 return;
4669 string_copy_rev(view->ref, entry->id);
4672 static bool
4673 tree_open(struct view *view, enum open_flags flags)
4675 static const char *tree_argv[] = {
4676 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4679 if (view->lines == 0 && opt_prefix[0]) {
4680 char *pos = opt_prefix;
4682 while (pos && *pos) {
4683 char *end = strchr(pos, '/');
4685 if (end)
4686 *end = 0;
4687 push_tree_stack_entry(pos, 0);
4688 pos = end;
4689 if (end) {
4690 *end = '/';
4691 pos++;
4695 } else if (strcmp(view->vid, view->id)) {
4696 opt_path[0] = 0;
4699 return begin_update(view, opt_cdup, tree_argv, flags);
4702 static struct view_ops tree_ops = {
4703 "file",
4704 VIEW_NO_FLAGS,
4705 sizeof(struct tree_state),
4706 tree_open,
4707 tree_read,
4708 tree_draw,
4709 tree_request,
4710 tree_grep,
4711 tree_select,
4714 static bool
4715 blob_open(struct view *view, enum open_flags flags)
4717 static const char *blob_argv[] = {
4718 "git", "cat-file", "blob", "%(blob)", NULL
4721 view->encoding = get_path_encoding(opt_file, opt_encoding);
4723 return begin_update(view, NULL, blob_argv, flags);
4726 static bool
4727 blob_read(struct view *view, char *line)
4729 if (!line)
4730 return TRUE;
4731 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4734 static enum request
4735 blob_request(struct view *view, enum request request, struct line *line)
4737 switch (request) {
4738 case REQ_EDIT:
4739 open_blob_editor(view->vid);
4740 return REQ_NONE;
4741 default:
4742 return pager_request(view, request, line);
4746 static struct view_ops blob_ops = {
4747 "line",
4748 VIEW_NO_FLAGS,
4750 blob_open,
4751 blob_read,
4752 pager_draw,
4753 blob_request,
4754 pager_grep,
4755 pager_select,
4759 * Blame backend
4761 * Loading the blame view is a two phase job:
4763 * 1. File content is read either using opt_file from the
4764 * filesystem or using git-cat-file.
4765 * 2. Then blame information is incrementally added by
4766 * reading output from git-blame.
4769 struct blame {
4770 struct blame_commit *commit;
4771 unsigned long lineno;
4772 char text[1];
4775 struct blame_state {
4776 struct blame_commit *commit;
4777 int blamed;
4778 bool done_reading;
4779 bool auto_filename_display;
4782 static bool
4783 blame_detect_filename_display(struct view *view)
4785 bool show_filenames = FALSE;
4786 const char *filename = NULL;
4787 int i;
4789 if (opt_blame_argv) {
4790 for (i = 0; opt_blame_argv[i]; i++) {
4791 if (prefixcmp(opt_blame_argv[i], "-C"))
4792 continue;
4794 show_filenames = TRUE;
4798 for (i = 0; i < view->lines; i++) {
4799 struct blame *blame = view->line[i].data;
4801 if (blame->commit && blame->commit->id[0]) {
4802 if (!filename)
4803 filename = blame->commit->filename;
4804 else if (strcmp(filename, blame->commit->filename))
4805 show_filenames = TRUE;
4809 return show_filenames;
4812 static bool
4813 blame_open(struct view *view, enum open_flags flags)
4815 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4816 char path[SIZEOF_STR];
4817 size_t i;
4819 if (!view->prev && *opt_prefix) {
4820 string_copy(path, opt_file);
4821 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4822 return FALSE;
4825 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4826 const char *blame_cat_file_argv[] = {
4827 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4830 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4831 return FALSE;
4834 /* First pass: remove multiple references to the same commit. */
4835 for (i = 0; i < view->lines; i++) {
4836 struct blame *blame = view->line[i].data;
4838 if (blame->commit && blame->commit->id[0])
4839 blame->commit->id[0] = 0;
4840 else
4841 blame->commit = NULL;
4844 /* Second pass: free existing references. */
4845 for (i = 0; i < view->lines; i++) {
4846 struct blame *blame = view->line[i].data;
4848 if (blame->commit)
4849 free(blame->commit);
4852 string_format(view->vid, "%s", opt_file);
4853 string_format(view->ref, "%s ...", opt_file);
4855 return TRUE;
4858 static struct blame_commit *
4859 get_blame_commit(struct view *view, const char *id)
4861 size_t i;
4863 for (i = 0; i < view->lines; i++) {
4864 struct blame *blame = view->line[i].data;
4866 if (!blame->commit)
4867 continue;
4869 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4870 return blame->commit;
4874 struct blame_commit *commit = calloc(1, sizeof(*commit));
4876 if (commit)
4877 string_ncopy(commit->id, id, SIZEOF_REV);
4878 return commit;
4882 static struct blame_commit *
4883 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
4885 struct blame_header header;
4886 struct blame_commit *commit;
4887 struct blame *blame;
4889 if (!parse_blame_header(&header, text, view->lines))
4890 return NULL;
4892 commit = get_blame_commit(view, text);
4893 if (!commit)
4894 return NULL;
4896 state->blamed += header.group;
4897 while (header.group--) {
4898 struct line *line = &view->line[header.lineno + header.group - 1];
4900 blame = line->data;
4901 blame->commit = commit;
4902 blame->lineno = header.orig_lineno + header.group - 1;
4903 line->dirty = 1;
4906 return commit;
4909 static bool
4910 blame_read_file(struct view *view, const char *line, struct blame_state *state)
4912 if (!line) {
4913 const char *blame_argv[] = {
4914 "git", "blame", ENCODING_ARG, "%(blameargs)", "--incremental",
4915 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4918 if (view->lines == 0 && !view->prev)
4919 die("No blame exist for %s", view->vid);
4921 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
4922 report("Failed to load blame data");
4923 return TRUE;
4926 if (opt_goto_line > 0) {
4927 select_view_line(view, opt_goto_line);
4928 opt_goto_line = 0;
4931 state->done_reading = TRUE;
4932 return FALSE;
4934 } else {
4935 size_t linelen = strlen(line);
4936 struct blame *blame = malloc(sizeof(*blame) + linelen);
4938 if (!blame)
4939 return FALSE;
4941 blame->commit = NULL;
4942 strncpy(blame->text, line, linelen);
4943 blame->text[linelen] = 0;
4944 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4948 static bool
4949 blame_read(struct view *view, char *line)
4951 struct blame_state *state = view->private;
4953 if (!state->done_reading)
4954 return blame_read_file(view, line, state);
4956 if (!line) {
4957 state->auto_filename_display = blame_detect_filename_display(view);
4958 string_format(view->ref, "%s", view->vid);
4959 if (view_is_displayed(view)) {
4960 update_view_title(view);
4961 redraw_view_from(view, 0);
4963 return TRUE;
4966 if (!state->commit) {
4967 state->commit = read_blame_commit(view, line, state);
4968 string_format(view->ref, "%s %2d%%", view->vid,
4969 view->lines ? state->blamed * 100 / view->lines : 0);
4971 } else if (parse_blame_info(state->commit, line)) {
4972 state->commit = NULL;
4975 return TRUE;
4978 static bool
4979 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4981 struct blame_state *state = view->private;
4982 struct blame *blame = line->data;
4983 struct time *time = NULL;
4984 const char *id = NULL, *author = NULL, *filename = NULL;
4985 enum line_type id_type = LINE_BLAME_ID;
4986 static const enum line_type blame_colors[] = {
4987 LINE_PALETTE_0,
4988 LINE_PALETTE_1,
4989 LINE_PALETTE_2,
4990 LINE_PALETTE_3,
4991 LINE_PALETTE_4,
4992 LINE_PALETTE_5,
4993 LINE_PALETTE_6,
4996 #define BLAME_COLOR(i) \
4997 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
4999 if (blame->commit && *blame->commit->filename) {
5000 id = blame->commit->id;
5001 author = blame->commit->author;
5002 filename = blame->commit->filename;
5003 time = &blame->commit->time;
5004 id_type = BLAME_COLOR((long) blame->commit);
5007 if (draw_date(view, time))
5008 return TRUE;
5010 if (draw_author(view, author))
5011 return TRUE;
5013 if (draw_filename(view, filename, state->auto_filename_display))
5014 return TRUE;
5016 if (draw_field(view, id_type, id, ID_COLS, FALSE))
5017 return TRUE;
5019 if (draw_lineno(view, lineno))
5020 return TRUE;
5022 draw_text(view, LINE_DEFAULT, blame->text);
5023 return TRUE;
5026 static bool
5027 check_blame_commit(struct blame *blame, bool check_null_id)
5029 if (!blame->commit)
5030 report("Commit data not loaded yet");
5031 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
5032 report("No commit exist for the selected line");
5033 else
5034 return TRUE;
5035 return FALSE;
5038 static void
5039 setup_blame_parent_line(struct view *view, struct blame *blame)
5041 char from[SIZEOF_REF + SIZEOF_STR];
5042 char to[SIZEOF_REF + SIZEOF_STR];
5043 const char *diff_tree_argv[] = {
5044 "git", "diff", ENCODING_ARG, "--no-textconv", "--no-extdiff",
5045 "--no-color", "-U0", from, to, "--", NULL
5047 struct io io;
5048 int parent_lineno = -1;
5049 int blamed_lineno = -1;
5050 char *line;
5052 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5053 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5054 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5055 return;
5057 while ((line = io_get(&io, '\n', TRUE))) {
5058 if (*line == '@') {
5059 char *pos = strchr(line, '+');
5061 parent_lineno = atoi(line + 4);
5062 if (pos)
5063 blamed_lineno = atoi(pos + 1);
5065 } else if (*line == '+' && parent_lineno != -1) {
5066 if (blame->lineno == blamed_lineno - 1 &&
5067 !strcmp(blame->text, line + 1)) {
5068 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
5069 break;
5071 blamed_lineno++;
5075 io_done(&io);
5078 static enum request
5079 blame_request(struct view *view, enum request request, struct line *line)
5081 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5082 struct blame *blame = line->data;
5084 switch (request) {
5085 case REQ_VIEW_BLAME:
5086 if (check_blame_commit(blame, TRUE)) {
5087 string_copy(opt_ref, blame->commit->id);
5088 string_copy(opt_file, blame->commit->filename);
5089 if (blame->lineno)
5090 view->lineno = blame->lineno;
5091 reload_view(view);
5093 break;
5095 case REQ_PARENT:
5096 if (!check_blame_commit(blame, TRUE))
5097 break;
5098 if (!*blame->commit->parent_id) {
5099 report("The selected commit has no parents");
5100 } else {
5101 string_copy_rev(opt_ref, blame->commit->parent_id);
5102 string_copy(opt_file, blame->commit->parent_filename);
5103 setup_blame_parent_line(view, blame);
5104 opt_goto_line = blame->lineno;
5105 reload_view(view);
5107 break;
5109 case REQ_ENTER:
5110 if (!check_blame_commit(blame, FALSE))
5111 break;
5113 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5114 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5115 break;
5117 if (!strcmp(blame->commit->id, NULL_ID)) {
5118 struct view *diff = VIEW(REQ_VIEW_DIFF);
5119 const char *diff_index_argv[] = {
5120 "git", "diff-index", ENCODING_ARG, "--root",
5121 "--patch-with-stat",
5122 "-C", "-M", opt_diff_context_arg,
5123 opt_ignore_space_arg,
5124 "HEAD", "--", view->vid, NULL
5127 if (!*blame->commit->parent_id) {
5128 diff_index_argv[1] = "diff";
5129 diff_index_argv[2] = "--no-color";
5130 diff_index_argv[8] = "--";
5131 diff_index_argv[9] = "/dev/null";
5134 open_argv(view, diff, diff_index_argv, NULL, flags);
5135 if (diff->pipe)
5136 string_copy_rev(diff->ref, NULL_ID);
5137 } else {
5138 open_view(view, REQ_VIEW_DIFF, flags);
5140 break;
5142 default:
5143 return request;
5146 return REQ_NONE;
5149 static bool
5150 blame_grep(struct view *view, struct line *line)
5152 struct blame *blame = line->data;
5153 struct blame_commit *commit = blame->commit;
5154 const char *text[] = {
5155 blame->text,
5156 commit ? commit->title : "",
5157 commit ? commit->id : "",
5158 commit && opt_author ? commit->author : "",
5159 commit ? mkdate(&commit->time, opt_date) : "",
5160 NULL
5163 return grep_text(view, text);
5166 static void
5167 blame_select(struct view *view, struct line *line)
5169 struct blame *blame = line->data;
5170 struct blame_commit *commit = blame->commit;
5172 if (!commit)
5173 return;
5175 if (!strcmp(commit->id, NULL_ID))
5176 string_ncopy(ref_commit, "HEAD", 4);
5177 else
5178 string_copy_rev(ref_commit, commit->id);
5181 static struct view_ops blame_ops = {
5182 "line",
5183 VIEW_ALWAYS_LINENO,
5184 sizeof(struct blame_state),
5185 blame_open,
5186 blame_read,
5187 blame_draw,
5188 blame_request,
5189 blame_grep,
5190 blame_select,
5194 * Branch backend
5197 struct branch {
5198 const char *author; /* Author of the last commit. */
5199 struct time time; /* Date of the last activity. */
5200 const struct ref *ref; /* Name and commit ID information. */
5203 static const struct ref branch_all;
5205 static const enum sort_field branch_sort_fields[] = {
5206 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5208 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5210 struct branch_state {
5211 char id[SIZEOF_REV];
5214 static int
5215 branch_compare(const void *l1, const void *l2)
5217 const struct branch *branch1 = ((const struct line *) l1)->data;
5218 const struct branch *branch2 = ((const struct line *) l2)->data;
5220 if (branch1->ref == &branch_all)
5221 return -1;
5222 else if (branch2->ref == &branch_all)
5223 return 1;
5225 switch (get_sort_field(branch_sort_state)) {
5226 case ORDERBY_DATE:
5227 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5229 case ORDERBY_AUTHOR:
5230 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5232 case ORDERBY_NAME:
5233 default:
5234 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5238 static bool
5239 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5241 struct branch *branch = line->data;
5242 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5244 if (draw_date(view, &branch->time))
5245 return TRUE;
5247 if (draw_author(view, branch->author))
5248 return TRUE;
5250 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
5251 return TRUE;
5254 static enum request
5255 branch_request(struct view *view, enum request request, struct line *line)
5257 struct branch *branch = line->data;
5259 switch (request) {
5260 case REQ_REFRESH:
5261 load_refs();
5262 refresh_view(view);
5263 return REQ_NONE;
5265 case REQ_TOGGLE_SORT_FIELD:
5266 case REQ_TOGGLE_SORT_ORDER:
5267 sort_view(view, request, &branch_sort_state, branch_compare);
5268 return REQ_NONE;
5270 case REQ_ENTER:
5272 const struct ref *ref = branch->ref;
5273 const char *all_branches_argv[] = {
5274 "git", "log", ENCODING_ARG, "--no-color",
5275 "--pretty=raw", "--parents", "--topo-order",
5276 ref == &branch_all ? "--all" : ref->name, NULL
5278 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5280 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5281 return REQ_NONE;
5283 case REQ_JUMP_COMMIT:
5285 int lineno;
5287 for (lineno = 0; lineno < view->lines; lineno++) {
5288 struct branch *branch = view->line[lineno].data;
5290 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5291 select_view_line(view, lineno);
5292 report("");
5293 return REQ_NONE;
5297 default:
5298 return request;
5302 static bool
5303 branch_read(struct view *view, char *line)
5305 struct branch_state *state = view->private;
5306 struct branch *reference;
5307 size_t i;
5309 if (!line)
5310 return TRUE;
5312 switch (get_line_type(line)) {
5313 case LINE_COMMIT:
5314 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5315 return TRUE;
5317 case LINE_AUTHOR:
5318 for (i = 0, reference = NULL; i < view->lines; i++) {
5319 struct branch *branch = view->line[i].data;
5321 if (strcmp(branch->ref->id, state->id))
5322 continue;
5324 view->line[i].dirty = TRUE;
5325 if (reference) {
5326 branch->author = reference->author;
5327 branch->time = reference->time;
5328 continue;
5331 parse_author_line(line + STRING_SIZE("author "),
5332 &branch->author, &branch->time);
5333 reference = branch;
5335 return TRUE;
5337 default:
5338 return TRUE;
5343 static bool
5344 branch_open_visitor(void *data, const struct ref *ref)
5346 struct view *view = data;
5347 struct branch *branch;
5349 if (ref->tag || ref->ltag)
5350 return TRUE;
5352 branch = calloc(1, sizeof(*branch));
5353 if (!branch)
5354 return FALSE;
5356 branch->ref = ref;
5357 return !!add_line_data(view, branch, LINE_DEFAULT);
5360 static bool
5361 branch_open(struct view *view, enum open_flags flags)
5363 const char *branch_log[] = {
5364 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
5365 "--simplify-by-decoration", "--all", NULL
5368 if (!begin_update(view, NULL, branch_log, flags)) {
5369 report("Failed to load branch data");
5370 return TRUE;
5373 branch_open_visitor(view, &branch_all);
5374 foreach_ref(branch_open_visitor, view);
5375 view->p_restore = TRUE;
5377 return TRUE;
5380 static bool
5381 branch_grep(struct view *view, struct line *line)
5383 struct branch *branch = line->data;
5384 const char *text[] = {
5385 branch->ref->name,
5386 mkauthor(branch->author, opt_author_cols, opt_author),
5387 NULL
5390 return grep_text(view, text);
5393 static void
5394 branch_select(struct view *view, struct line *line)
5396 struct branch *branch = line->data;
5398 string_copy_rev(view->ref, branch->ref->id);
5399 string_copy_rev(ref_commit, branch->ref->id);
5400 string_copy_rev(ref_head, branch->ref->id);
5401 string_copy_rev(ref_branch, branch->ref->name);
5404 static struct view_ops branch_ops = {
5405 "branch",
5406 VIEW_NO_FLAGS,
5407 sizeof(struct branch_state),
5408 branch_open,
5409 branch_read,
5410 branch_draw,
5411 branch_request,
5412 branch_grep,
5413 branch_select,
5417 * Status backend
5420 struct status {
5421 char status;
5422 struct {
5423 mode_t mode;
5424 char rev[SIZEOF_REV];
5425 char name[SIZEOF_STR];
5426 } old;
5427 struct {
5428 mode_t mode;
5429 char rev[SIZEOF_REV];
5430 char name[SIZEOF_STR];
5431 } new;
5434 static char status_onbranch[SIZEOF_STR];
5435 static struct status stage_status;
5436 static enum line_type stage_line_type;
5438 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5440 /* This should work even for the "On branch" line. */
5441 static inline bool
5442 status_has_none(struct view *view, struct line *line)
5444 return line < view->line + view->lines && !line[1].data;
5447 /* Get fields from the diff line:
5448 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5450 static inline bool
5451 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5453 const char *old_mode = buf + 1;
5454 const char *new_mode = buf + 8;
5455 const char *old_rev = buf + 15;
5456 const char *new_rev = buf + 56;
5457 const char *status = buf + 97;
5459 if (bufsize < 98 ||
5460 old_mode[-1] != ':' ||
5461 new_mode[-1] != ' ' ||
5462 old_rev[-1] != ' ' ||
5463 new_rev[-1] != ' ' ||
5464 status[-1] != ' ')
5465 return FALSE;
5467 file->status = *status;
5469 string_copy_rev(file->old.rev, old_rev);
5470 string_copy_rev(file->new.rev, new_rev);
5472 file->old.mode = strtoul(old_mode, NULL, 8);
5473 file->new.mode = strtoul(new_mode, NULL, 8);
5475 file->old.name[0] = file->new.name[0] = 0;
5477 return TRUE;
5480 static bool
5481 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5483 struct status *unmerged = NULL;
5484 char *buf;
5485 struct io io;
5487 if (!io_run(&io, IO_RD, opt_cdup, argv))
5488 return FALSE;
5490 add_line_data(view, NULL, type);
5492 while ((buf = io_get(&io, 0, TRUE))) {
5493 struct status *file = unmerged;
5495 if (!file) {
5496 file = calloc(1, sizeof(*file));
5497 if (!file || !add_line_data(view, file, type))
5498 goto error_out;
5501 /* Parse diff info part. */
5502 if (status) {
5503 file->status = status;
5504 if (status == 'A')
5505 string_copy(file->old.rev, NULL_ID);
5507 } else if (!file->status || file == unmerged) {
5508 if (!status_get_diff(file, buf, strlen(buf)))
5509 goto error_out;
5511 buf = io_get(&io, 0, TRUE);
5512 if (!buf)
5513 break;
5515 /* Collapse all modified entries that follow an
5516 * associated unmerged entry. */
5517 if (unmerged == file) {
5518 unmerged->status = 'U';
5519 unmerged = NULL;
5520 } else if (file->status == 'U') {
5521 unmerged = file;
5525 /* Grab the old name for rename/copy. */
5526 if (!*file->old.name &&
5527 (file->status == 'R' || file->status == 'C')) {
5528 string_ncopy(file->old.name, buf, strlen(buf));
5530 buf = io_get(&io, 0, TRUE);
5531 if (!buf)
5532 break;
5535 /* git-ls-files just delivers a NUL separated list of
5536 * file names similar to the second half of the
5537 * git-diff-* output. */
5538 string_ncopy(file->new.name, buf, strlen(buf));
5539 if (!*file->old.name)
5540 string_copy(file->old.name, file->new.name);
5541 file = NULL;
5544 if (io_error(&io)) {
5545 error_out:
5546 io_done(&io);
5547 return FALSE;
5550 if (!view->line[view->lines - 1].data)
5551 add_line_data(view, NULL, LINE_STAT_NONE);
5553 io_done(&io);
5554 return TRUE;
5557 /* Don't show unmerged entries in the staged section. */
5558 static const char *status_diff_index_argv[] = {
5559 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
5560 "--cached", "-M", "HEAD", NULL
5563 static const char *status_diff_files_argv[] = {
5564 "git", "diff-files", "-z", NULL
5567 static const char *status_list_other_argv[] = {
5568 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5571 static const char *status_list_no_head_argv[] = {
5572 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5575 static const char *update_index_argv[] = {
5576 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5579 /* Restore the previous line number to stay in the context or select a
5580 * line with something that can be updated. */
5581 static void
5582 status_restore(struct view *view)
5584 if (view->p_lineno >= view->lines)
5585 view->p_lineno = view->lines - 1;
5586 while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
5587 view->p_lineno++;
5588 while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
5589 view->p_lineno--;
5591 /* If the above fails, always skip the "On branch" line. */
5592 if (view->p_lineno < view->lines)
5593 view->lineno = view->p_lineno;
5594 else
5595 view->lineno = 1;
5597 if (view->lineno < view->offset)
5598 view->offset = view->lineno;
5599 else if (view->offset + view->height <= view->lineno)
5600 view->offset = view->lineno - view->height + 1;
5602 view->p_restore = FALSE;
5605 static void
5606 status_update_onbranch(void)
5608 static const char *paths[][2] = {
5609 { "rebase-apply/rebasing", "Rebasing" },
5610 { "rebase-apply/applying", "Applying mailbox" },
5611 { "rebase-apply/", "Rebasing mailbox" },
5612 { "rebase-merge/interactive", "Interactive rebase" },
5613 { "rebase-merge/", "Rebase merge" },
5614 { "MERGE_HEAD", "Merging" },
5615 { "BISECT_LOG", "Bisecting" },
5616 { "HEAD", "On branch" },
5618 char buf[SIZEOF_STR];
5619 struct stat stat;
5620 int i;
5622 if (is_initial_commit()) {
5623 string_copy(status_onbranch, "Initial commit");
5624 return;
5627 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5628 char *head = opt_head;
5630 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5631 lstat(buf, &stat) < 0)
5632 continue;
5634 if (!*opt_head) {
5635 struct io io;
5637 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5638 io_read_buf(&io, buf, sizeof(buf))) {
5639 head = buf;
5640 if (!prefixcmp(head, "refs/heads/"))
5641 head += STRING_SIZE("refs/heads/");
5645 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5646 string_copy(status_onbranch, opt_head);
5647 return;
5650 string_copy(status_onbranch, "Not currently on any branch");
5653 /* First parse staged info using git-diff-index(1), then parse unstaged
5654 * info using git-diff-files(1), and finally untracked files using
5655 * git-ls-files(1). */
5656 static bool
5657 status_open(struct view *view, enum open_flags flags)
5659 reset_view(view);
5661 add_line_data(view, NULL, LINE_STAT_HEAD);
5662 status_update_onbranch();
5664 io_run_bg(update_index_argv);
5666 if (is_initial_commit()) {
5667 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5668 return FALSE;
5669 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5670 return FALSE;
5673 if (!opt_untracked_dirs_content)
5674 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5676 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5677 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5678 return FALSE;
5680 /* Restore the exact position or use the specialized restore
5681 * mode? */
5682 if (!view->p_restore)
5683 status_restore(view);
5684 return TRUE;
5687 static bool
5688 status_draw(struct view *view, struct line *line, unsigned int lineno)
5690 struct status *status = line->data;
5691 enum line_type type;
5692 const char *text;
5694 if (!status) {
5695 switch (line->type) {
5696 case LINE_STAT_STAGED:
5697 type = LINE_STAT_SECTION;
5698 text = "Changes to be committed:";
5699 break;
5701 case LINE_STAT_UNSTAGED:
5702 type = LINE_STAT_SECTION;
5703 text = "Changed but not updated:";
5704 break;
5706 case LINE_STAT_UNTRACKED:
5707 type = LINE_STAT_SECTION;
5708 text = "Untracked files:";
5709 break;
5711 case LINE_STAT_NONE:
5712 type = LINE_DEFAULT;
5713 text = " (no files)";
5714 break;
5716 case LINE_STAT_HEAD:
5717 type = LINE_STAT_HEAD;
5718 text = status_onbranch;
5719 break;
5721 default:
5722 return FALSE;
5724 } else {
5725 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5727 buf[0] = status->status;
5728 if (draw_text(view, line->type, buf))
5729 return TRUE;
5730 type = LINE_DEFAULT;
5731 text = status->new.name;
5734 draw_text(view, type, text);
5735 return TRUE;
5738 static enum request
5739 status_enter(struct view *view, struct line *line)
5741 struct status *status = line->data;
5742 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5744 if (line->type == LINE_STAT_NONE ||
5745 (!status && line[1].type == LINE_STAT_NONE)) {
5746 report("No file to diff");
5747 return REQ_NONE;
5750 switch (line->type) {
5751 case LINE_STAT_STAGED:
5752 case LINE_STAT_UNSTAGED:
5753 break;
5755 case LINE_STAT_UNTRACKED:
5756 if (!status) {
5757 report("No file to show");
5758 return REQ_NONE;
5761 if (!suffixcmp(status->new.name, -1, "/")) {
5762 report("Cannot display a directory");
5763 return REQ_NONE;
5765 break;
5767 case LINE_STAT_HEAD:
5768 return REQ_NONE;
5770 default:
5771 die("line type %d not handled in switch", line->type);
5774 if (status) {
5775 stage_status = *status;
5776 } else {
5777 memset(&stage_status, 0, sizeof(stage_status));
5780 stage_line_type = line->type;
5782 open_view(view, REQ_VIEW_STAGE, flags);
5783 return REQ_NONE;
5786 static bool
5787 status_exists(struct view *view, struct status *status, enum line_type type)
5789 unsigned long lineno;
5791 for (lineno = 0; lineno < view->lines; lineno++) {
5792 struct line *line = &view->line[lineno];
5793 struct status *pos = line->data;
5795 if (line->type != type)
5796 continue;
5797 if (!pos && (!status || !status->status) && line[1].data) {
5798 select_view_line(view, lineno);
5799 return TRUE;
5801 if (pos && !strcmp(status->new.name, pos->new.name)) {
5802 select_view_line(view, lineno);
5803 return TRUE;
5807 return FALSE;
5811 static bool
5812 status_update_prepare(struct io *io, enum line_type type)
5814 const char *staged_argv[] = {
5815 "git", "update-index", "-z", "--index-info", NULL
5817 const char *others_argv[] = {
5818 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5821 switch (type) {
5822 case LINE_STAT_STAGED:
5823 return io_run(io, IO_WR, opt_cdup, staged_argv);
5825 case LINE_STAT_UNSTAGED:
5826 case LINE_STAT_UNTRACKED:
5827 return io_run(io, IO_WR, opt_cdup, others_argv);
5829 default:
5830 die("line type %d not handled in switch", type);
5831 return FALSE;
5835 static bool
5836 status_update_write(struct io *io, struct status *status, enum line_type type)
5838 switch (type) {
5839 case LINE_STAT_STAGED:
5840 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
5841 status->old.rev, status->old.name, 0);
5843 case LINE_STAT_UNSTAGED:
5844 case LINE_STAT_UNTRACKED:
5845 return io_printf(io, "%s%c", status->new.name, 0);
5847 default:
5848 die("line type %d not handled in switch", type);
5849 return FALSE;
5853 static bool
5854 status_update_file(struct status *status, enum line_type type)
5856 struct io io;
5857 bool result;
5859 if (!status_update_prepare(&io, type))
5860 return FALSE;
5862 result = status_update_write(&io, status, type);
5863 return io_done(&io) && result;
5866 static bool
5867 status_update_files(struct view *view, struct line *line)
5869 char buf[sizeof(view->ref)];
5870 struct io io;
5871 bool result = TRUE;
5872 struct line *pos = view->line + view->lines;
5873 int files = 0;
5874 int file, done;
5875 int cursor_y = -1, cursor_x = -1;
5877 if (!status_update_prepare(&io, line->type))
5878 return FALSE;
5880 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5881 files++;
5883 string_copy(buf, view->ref);
5884 getsyx(cursor_y, cursor_x);
5885 for (file = 0, done = 5; result && file < files; line++, file++) {
5886 int almost_done = file * 100 / files;
5888 if (almost_done > done) {
5889 done = almost_done;
5890 string_format(view->ref, "updating file %u of %u (%d%% done)",
5891 file, files, done);
5892 update_view_title(view);
5893 setsyx(cursor_y, cursor_x);
5894 doupdate();
5896 result = status_update_write(&io, line->data, line->type);
5898 string_copy(view->ref, buf);
5900 return io_done(&io) && result;
5903 static bool
5904 status_update(struct view *view)
5906 struct line *line = &view->line[view->lineno];
5908 assert(view->lines);
5910 if (!line->data) {
5911 /* This should work even for the "On branch" line. */
5912 if (line < view->line + view->lines && !line[1].data) {
5913 report("Nothing to update");
5914 return FALSE;
5917 if (!status_update_files(view, line + 1)) {
5918 report("Failed to update file status");
5919 return FALSE;
5922 } else if (!status_update_file(line->data, line->type)) {
5923 report("Failed to update file status");
5924 return FALSE;
5927 return TRUE;
5930 static bool
5931 status_revert(struct status *status, enum line_type type, bool has_none)
5933 if (!status || type != LINE_STAT_UNSTAGED) {
5934 if (type == LINE_STAT_STAGED) {
5935 report("Cannot revert changes to staged files");
5936 } else if (type == LINE_STAT_UNTRACKED) {
5937 report("Cannot revert changes to untracked files");
5938 } else if (has_none) {
5939 report("Nothing to revert");
5940 } else {
5941 report("Cannot revert changes to multiple files");
5944 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5945 char mode[10] = "100644";
5946 const char *reset_argv[] = {
5947 "git", "update-index", "--cacheinfo", mode,
5948 status->old.rev, status->old.name, NULL
5950 const char *checkout_argv[] = {
5951 "git", "checkout", "--", status->old.name, NULL
5954 if (status->status == 'U') {
5955 string_format(mode, "%5o", status->old.mode);
5957 if (status->old.mode == 0 && status->new.mode == 0) {
5958 reset_argv[2] = "--force-remove";
5959 reset_argv[3] = status->old.name;
5960 reset_argv[4] = NULL;
5963 if (!io_run_fg(reset_argv, opt_cdup))
5964 return FALSE;
5965 if (status->old.mode == 0 && status->new.mode == 0)
5966 return TRUE;
5969 return io_run_fg(checkout_argv, opt_cdup);
5972 return FALSE;
5975 static enum request
5976 status_request(struct view *view, enum request request, struct line *line)
5978 struct status *status = line->data;
5980 switch (request) {
5981 case REQ_STATUS_UPDATE:
5982 if (!status_update(view))
5983 return REQ_NONE;
5984 break;
5986 case REQ_STATUS_REVERT:
5987 if (!status_revert(status, line->type, status_has_none(view, line)))
5988 return REQ_NONE;
5989 break;
5991 case REQ_STATUS_MERGE:
5992 if (!status || status->status != 'U') {
5993 report("Merging only possible for files with unmerged status ('U').");
5994 return REQ_NONE;
5996 open_mergetool(status->new.name);
5997 break;
5999 case REQ_EDIT:
6000 if (!status)
6001 return request;
6002 if (status->status == 'D') {
6003 report("File has been deleted.");
6004 return REQ_NONE;
6007 open_editor(status->new.name);
6008 break;
6010 case REQ_VIEW_BLAME:
6011 if (status)
6012 opt_ref[0] = 0;
6013 return request;
6015 case REQ_ENTER:
6016 /* After returning the status view has been split to
6017 * show the stage view. No further reloading is
6018 * necessary. */
6019 return status_enter(view, line);
6021 case REQ_REFRESH:
6022 /* Simply reload the view. */
6023 break;
6025 default:
6026 return request;
6029 refresh_view(view);
6031 return REQ_NONE;
6034 static void
6035 status_select(struct view *view, struct line *line)
6037 struct status *status = line->data;
6038 char file[SIZEOF_STR] = "all files";
6039 const char *text;
6040 const char *key;
6042 if (status && !string_format(file, "'%s'", status->new.name))
6043 return;
6045 if (!status && line[1].type == LINE_STAT_NONE)
6046 line++;
6048 switch (line->type) {
6049 case LINE_STAT_STAGED:
6050 text = "Press %s to unstage %s for commit";
6051 break;
6053 case LINE_STAT_UNSTAGED:
6054 text = "Press %s to stage %s for commit";
6055 break;
6057 case LINE_STAT_UNTRACKED:
6058 text = "Press %s to stage %s for addition";
6059 break;
6061 case LINE_STAT_HEAD:
6062 case LINE_STAT_NONE:
6063 text = "Nothing to update";
6064 break;
6066 default:
6067 die("line type %d not handled in switch", line->type);
6070 if (status && status->status == 'U') {
6071 text = "Press %s to resolve conflict in %s";
6072 key = get_view_key(view, REQ_STATUS_MERGE);
6074 } else {
6075 key = get_view_key(view, REQ_STATUS_UPDATE);
6078 string_format(view->ref, text, key, file);
6079 if (status)
6080 string_copy(opt_file, status->new.name);
6083 static bool
6084 status_grep(struct view *view, struct line *line)
6086 struct status *status = line->data;
6088 if (status) {
6089 const char buf[2] = { status->status, 0 };
6090 const char *text[] = { status->new.name, buf, NULL };
6092 return grep_text(view, text);
6095 return FALSE;
6098 static struct view_ops status_ops = {
6099 "file",
6100 VIEW_CUSTOM_STATUS,
6102 status_open,
6103 NULL,
6104 status_draw,
6105 status_request,
6106 status_grep,
6107 status_select,
6111 struct stage_state {
6112 struct diff_state diff;
6113 size_t chunks;
6114 int *chunk;
6117 static bool
6118 stage_diff_write(struct io *io, struct line *line, struct line *end)
6120 while (line < end) {
6121 if (!io_write(io, line->data, strlen(line->data)) ||
6122 !io_write(io, "\n", 1))
6123 return FALSE;
6124 line++;
6125 if (line->type == LINE_DIFF_CHUNK ||
6126 line->type == LINE_DIFF_HEADER)
6127 break;
6130 return TRUE;
6133 static bool
6134 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6136 const char *apply_argv[SIZEOF_ARG] = {
6137 "git", "apply", "--whitespace=nowarn", NULL
6139 struct line *diff_hdr;
6140 struct io io;
6141 int argc = 3;
6143 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6144 if (!diff_hdr)
6145 return FALSE;
6147 if (!revert)
6148 apply_argv[argc++] = "--cached";
6149 if (line != NULL)
6150 apply_argv[argc++] = "--unidiff-zero";
6151 if (revert || stage_line_type == LINE_STAT_STAGED)
6152 apply_argv[argc++] = "-R";
6153 apply_argv[argc++] = "-";
6154 apply_argv[argc++] = NULL;
6155 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6156 return FALSE;
6158 if (line != NULL) {
6159 int lineno = 0;
6160 struct line *context = chunk + 1;
6161 const char *markers[] = {
6162 line->type == LINE_DIFF_DEL ? "" : ",0",
6163 line->type == LINE_DIFF_DEL ? ",0" : "",
6166 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6168 while (context < line) {
6169 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6170 break;
6171 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6172 lineno++;
6174 context++;
6177 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6178 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6179 lineno, markers[0], lineno, markers[1]) ||
6180 !stage_diff_write(&io, line, line + 1)) {
6181 chunk = NULL;
6183 } else {
6184 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6185 !stage_diff_write(&io, chunk, view->line + view->lines))
6186 chunk = NULL;
6189 io_done(&io);
6190 io_run_bg(update_index_argv);
6192 return chunk ? TRUE : FALSE;
6195 static bool
6196 stage_update(struct view *view, struct line *line, bool single)
6198 struct line *chunk = NULL;
6200 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6201 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6203 if (chunk) {
6204 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6205 report("Failed to apply chunk");
6206 return FALSE;
6209 } else if (!stage_status.status) {
6210 view = view->parent;
6212 for (line = view->line; line < view->line + view->lines; line++)
6213 if (line->type == stage_line_type)
6214 break;
6216 if (!status_update_files(view, line + 1)) {
6217 report("Failed to update files");
6218 return FALSE;
6221 } else if (!status_update_file(&stage_status, stage_line_type)) {
6222 report("Failed to update file");
6223 return FALSE;
6226 return TRUE;
6229 static bool
6230 stage_revert(struct view *view, struct line *line)
6232 struct line *chunk = NULL;
6234 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6235 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6237 if (chunk) {
6238 if (!prompt_yesno("Are you sure you want to revert changes?"))
6239 return FALSE;
6241 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6242 report("Failed to revert chunk");
6243 return FALSE;
6245 return TRUE;
6247 } else {
6248 return status_revert(stage_status.status ? &stage_status : NULL,
6249 stage_line_type, FALSE);
6254 static void
6255 stage_next(struct view *view, struct line *line)
6257 struct stage_state *state = view->private;
6258 int i;
6260 if (!state->chunks) {
6261 for (line = view->line; line < view->line + view->lines; line++) {
6262 if (line->type != LINE_DIFF_CHUNK)
6263 continue;
6265 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6266 report("Allocation failure");
6267 return;
6270 state->chunk[state->chunks++] = line - view->line;
6274 for (i = 0; i < state->chunks; i++) {
6275 if (state->chunk[i] > view->lineno) {
6276 do_scroll_view(view, state->chunk[i] - view->lineno);
6277 report("Chunk %d of %d", i + 1, state->chunks);
6278 return;
6282 report("No next chunk found");
6285 static enum request
6286 stage_request(struct view *view, enum request request, struct line *line)
6288 switch (request) {
6289 case REQ_STATUS_UPDATE:
6290 if (!stage_update(view, line, FALSE))
6291 return REQ_NONE;
6292 break;
6294 case REQ_STATUS_REVERT:
6295 if (!stage_revert(view, line))
6296 return REQ_NONE;
6297 break;
6299 case REQ_STAGE_UPDATE_LINE:
6300 if (stage_line_type == LINE_STAT_UNTRACKED ||
6301 stage_status.status == 'A') {
6302 report("Staging single lines is not supported for new files");
6303 return REQ_NONE;
6305 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6306 report("Please select a change to stage");
6307 return REQ_NONE;
6309 if (!stage_update(view, line, TRUE))
6310 return REQ_NONE;
6311 break;
6313 case REQ_STAGE_NEXT:
6314 if (stage_line_type == LINE_STAT_UNTRACKED) {
6315 report("File is untracked; press %s to add",
6316 get_view_key(view, REQ_STATUS_UPDATE));
6317 return REQ_NONE;
6319 stage_next(view, line);
6320 return REQ_NONE;
6322 case REQ_EDIT:
6323 if (!stage_status.new.name[0])
6324 return request;
6325 if (stage_status.status == 'D') {
6326 report("File has been deleted.");
6327 return REQ_NONE;
6330 open_editor(stage_status.new.name);
6331 break;
6333 case REQ_REFRESH:
6334 /* Reload everything ... */
6335 break;
6337 case REQ_VIEW_BLAME:
6338 if (stage_status.new.name[0]) {
6339 string_copy(opt_file, stage_status.new.name);
6340 opt_ref[0] = 0;
6342 return request;
6344 case REQ_ENTER:
6345 return diff_common_enter(view, request, line);
6347 case REQ_DIFF_CONTEXT_UP:
6348 case REQ_DIFF_CONTEXT_DOWN:
6349 if (!update_diff_context(request))
6350 return REQ_NONE;
6351 break;
6353 default:
6354 return request;
6357 refresh_view(view->parent);
6359 /* Check whether the staged entry still exists, and close the
6360 * stage view if it doesn't. */
6361 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6362 status_restore(view->parent);
6363 return REQ_VIEW_CLOSE;
6366 refresh_view(view);
6368 return REQ_NONE;
6371 static bool
6372 stage_open(struct view *view, enum open_flags flags)
6374 static const char *no_head_diff_argv[] = {
6375 "git", "diff", ENCODING_ARG, "--no-color", "--patch-with-stat",
6376 opt_diff_context_arg, opt_ignore_space_arg,
6377 "--", "/dev/null", stage_status.new.name, NULL
6379 static const char *index_show_argv[] = {
6380 "git", "diff-index", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6381 "--cached", opt_diff_context_arg, opt_ignore_space_arg,
6382 "HEAD", "--",
6383 stage_status.old.name, stage_status.new.name, NULL
6385 static const char *files_show_argv[] = {
6386 "git", "diff-files", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6387 opt_diff_context_arg, opt_ignore_space_arg, "--",
6388 stage_status.old.name, stage_status.new.name, NULL
6390 /* Diffs for unmerged entries are empty when passing the new
6391 * path, so leave out the new path. */
6392 static const char *files_unmerged_argv[] = {
6393 "git", "diff-files", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6394 opt_diff_context_arg, opt_ignore_space_arg, "--",
6395 stage_status.old.name, NULL
6397 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6398 const char **argv = NULL;
6399 const char *info;
6401 view->encoding = NULL;
6403 switch (stage_line_type) {
6404 case LINE_STAT_STAGED:
6405 if (is_initial_commit()) {
6406 argv = no_head_diff_argv;
6407 } else {
6408 argv = index_show_argv;
6410 if (stage_status.status)
6411 info = "Staged changes to %s";
6412 else
6413 info = "Staged changes";
6414 break;
6416 case LINE_STAT_UNSTAGED:
6417 if (stage_status.status != 'U')
6418 argv = files_show_argv;
6419 else
6420 argv = files_unmerged_argv;
6421 if (stage_status.status)
6422 info = "Unstaged changes to %s";
6423 else
6424 info = "Unstaged changes";
6425 break;
6427 case LINE_STAT_UNTRACKED:
6428 info = "Untracked file %s";
6429 argv = file_argv;
6430 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
6431 break;
6433 case LINE_STAT_HEAD:
6434 default:
6435 die("line type %d not handled in switch", stage_line_type);
6438 string_format(view->ref, info, stage_status.new.name);
6439 view->vid[0] = 0;
6440 view->dir = opt_cdup;
6441 return argv_copy(&view->argv, argv)
6442 && begin_update(view, NULL, NULL, flags);
6445 static bool
6446 stage_read(struct view *view, char *data)
6448 struct stage_state *state = view->private;
6450 if (data && diff_common_read(view, data, &state->diff))
6451 return TRUE;
6453 return pager_read(view, data);
6456 static struct view_ops stage_ops = {
6457 "line",
6458 VIEW_NO_FLAGS,
6459 sizeof(struct stage_state),
6460 stage_open,
6461 stage_read,
6462 diff_common_draw,
6463 stage_request,
6464 pager_grep,
6465 pager_select,
6470 * Revision graph
6473 static const enum line_type graph_colors[] = {
6474 LINE_PALETTE_0,
6475 LINE_PALETTE_1,
6476 LINE_PALETTE_2,
6477 LINE_PALETTE_3,
6478 LINE_PALETTE_4,
6479 LINE_PALETTE_5,
6480 LINE_PALETTE_6,
6483 static enum line_type get_graph_color(struct graph_symbol *symbol)
6485 if (symbol->commit)
6486 return LINE_GRAPH_COMMIT;
6487 assert(symbol->color < ARRAY_SIZE(graph_colors));
6488 return graph_colors[symbol->color];
6491 static bool
6492 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6494 const char *chars = graph_symbol_to_utf8(symbol);
6496 return draw_text(view, color, chars + !!first);
6499 static bool
6500 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6502 const char *chars = graph_symbol_to_ascii(symbol);
6504 return draw_text(view, color, chars + !!first);
6507 static bool
6508 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6510 const chtype *chars = graph_symbol_to_chtype(symbol);
6512 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6515 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6517 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6519 static const draw_graph_fn fns[] = {
6520 draw_graph_ascii,
6521 draw_graph_chtype,
6522 draw_graph_utf8
6524 draw_graph_fn fn = fns[opt_line_graphics];
6525 int i;
6527 for (i = 0; i < canvas->size; i++) {
6528 struct graph_symbol *symbol = &canvas->symbols[i];
6529 enum line_type color = get_graph_color(symbol);
6531 if (fn(view, symbol, color, i == 0))
6532 return TRUE;
6535 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6539 * Main view backend
6542 struct commit {
6543 char id[SIZEOF_REV]; /* SHA1 ID. */
6544 char title[128]; /* First line of the commit message. */
6545 const char *author; /* Author of the commit. */
6546 struct time time; /* Date from the author ident. */
6547 struct ref_list *refs; /* Repository references. */
6548 struct graph_canvas graph; /* Ancestry chain graphics. */
6551 static bool
6552 main_open(struct view *view, enum open_flags flags)
6554 static const char *main_argv[] = {
6555 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw", "--parents",
6556 "--topo-order", "%(diffargs)", "%(revargs)",
6557 "--", "%(fileargs)", NULL
6560 return begin_update(view, NULL, main_argv, flags);
6563 static bool
6564 main_draw(struct view *view, struct line *line, unsigned int lineno)
6566 struct commit *commit = line->data;
6568 if (!commit->author)
6569 return FALSE;
6571 if (opt_line_number && draw_lineno(view, lineno))
6572 return TRUE;
6574 if (draw_date(view, &commit->time))
6575 return TRUE;
6577 if (draw_author(view, commit->author))
6578 return TRUE;
6580 if (opt_rev_graph && draw_graph(view, &commit->graph))
6581 return TRUE;
6583 if (draw_refs(view, commit->refs))
6584 return TRUE;
6586 draw_text(view, LINE_DEFAULT, commit->title);
6587 return TRUE;
6590 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6591 static bool
6592 main_read(struct view *view, char *line)
6594 struct graph *graph = view->private;
6595 enum line_type type;
6596 struct commit *commit;
6598 if (!line) {
6599 if (!view->lines && !view->prev)
6600 die("No revisions match the given arguments.");
6601 if (view->lines > 0) {
6602 commit = view->line[view->lines - 1].data;
6603 view->line[view->lines - 1].dirty = 1;
6604 if (!commit->author) {
6605 view->lines--;
6606 free(commit);
6610 done_graph(graph);
6611 return TRUE;
6614 type = get_line_type(line);
6615 if (type == LINE_COMMIT) {
6616 bool is_boundary;
6618 commit = calloc(1, sizeof(struct commit));
6619 if (!commit)
6620 return FALSE;
6622 line += STRING_SIZE("commit ");
6623 is_boundary = *line == '-';
6624 if (is_boundary)
6625 line++;
6627 string_copy_rev(commit->id, line);
6628 commit->refs = get_ref_list(commit->id);
6629 add_line_data(view, commit, LINE_MAIN_COMMIT);
6630 graph_add_commit(graph, &commit->graph, commit->id, line, is_boundary);
6631 return TRUE;
6634 if (!view->lines)
6635 return TRUE;
6636 commit = view->line[view->lines - 1].data;
6638 switch (type) {
6639 case LINE_PARENT:
6640 if (!graph->has_parents)
6641 graph_add_parent(graph, line + STRING_SIZE("parent "));
6642 break;
6644 case LINE_AUTHOR:
6645 parse_author_line(line + STRING_SIZE("author "),
6646 &commit->author, &commit->time);
6647 graph_render_parents(graph);
6648 break;
6650 default:
6651 /* Fill in the commit title if it has not already been set. */
6652 if (commit->title[0])
6653 break;
6655 /* Require titles to start with a non-space character at the
6656 * offset used by git log. */
6657 if (strncmp(line, " ", 4))
6658 break;
6659 line += 4;
6660 /* Well, if the title starts with a whitespace character,
6661 * try to be forgiving. Otherwise we end up with no title. */
6662 while (isspace(*line))
6663 line++;
6664 if (*line == '\0')
6665 break;
6666 /* FIXME: More graceful handling of titles; append "..." to
6667 * shortened titles, etc. */
6669 string_expand(commit->title, sizeof(commit->title), line, 1);
6670 view->line[view->lines - 1].dirty = 1;
6673 return TRUE;
6676 static enum request
6677 main_request(struct view *view, enum request request, struct line *line)
6679 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6681 switch (request) {
6682 case REQ_ENTER:
6683 if (view_is_displayed(view) && display[0] != view)
6684 maximize_view(view, TRUE);
6685 open_view(view, REQ_VIEW_DIFF, flags);
6686 break;
6687 case REQ_REFRESH:
6688 load_refs();
6689 refresh_view(view);
6690 break;
6692 case REQ_JUMP_COMMIT:
6694 int lineno;
6696 for (lineno = 0; lineno < view->lines; lineno++) {
6697 struct commit *commit = view->line[lineno].data;
6699 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
6700 select_view_line(view, lineno);
6701 report("");
6702 return REQ_NONE;
6706 report("Unable to find commit '%s'", opt_search);
6707 break;
6709 default:
6710 return request;
6713 return REQ_NONE;
6716 static bool
6717 grep_refs(struct ref_list *list, regex_t *regex)
6719 regmatch_t pmatch;
6720 size_t i;
6722 if (!opt_show_refs || !list)
6723 return FALSE;
6725 for (i = 0; i < list->size; i++) {
6726 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
6727 return TRUE;
6730 return FALSE;
6733 static bool
6734 main_grep(struct view *view, struct line *line)
6736 struct commit *commit = line->data;
6737 const char *text[] = {
6738 commit->title,
6739 mkauthor(commit->author, opt_author_cols, opt_author),
6740 mkdate(&commit->time, opt_date),
6741 NULL
6744 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
6747 static void
6748 main_select(struct view *view, struct line *line)
6750 struct commit *commit = line->data;
6752 string_copy_rev(view->ref, commit->id);
6753 string_copy_rev(ref_commit, view->ref);
6756 static struct view_ops main_ops = {
6757 "commit",
6758 VIEW_NO_FLAGS,
6759 sizeof(struct graph),
6760 main_open,
6761 main_read,
6762 main_draw,
6763 main_request,
6764 main_grep,
6765 main_select,
6770 * Status management
6773 /* Whether or not the curses interface has been initialized. */
6774 static bool cursed = FALSE;
6776 /* Terminal hacks and workarounds. */
6777 static bool use_scroll_redrawwin;
6778 static bool use_scroll_status_wclear;
6780 /* The status window is used for polling keystrokes. */
6781 static WINDOW *status_win;
6783 /* Reading from the prompt? */
6784 static bool input_mode = FALSE;
6786 static bool status_empty = FALSE;
6788 /* Update status and title window. */
6789 static void
6790 report(const char *msg, ...)
6792 struct view *view = display[current_view];
6794 if (input_mode)
6795 return;
6797 if (!view) {
6798 char buf[SIZEOF_STR];
6799 int retval;
6801 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
6802 die("%s", buf);
6805 if (!status_empty || *msg) {
6806 va_list args;
6808 va_start(args, msg);
6810 wmove(status_win, 0, 0);
6811 if (view->has_scrolled && use_scroll_status_wclear)
6812 wclear(status_win);
6813 if (*msg) {
6814 vwprintw(status_win, msg, args);
6815 status_empty = FALSE;
6816 } else {
6817 status_empty = TRUE;
6819 wclrtoeol(status_win);
6820 wnoutrefresh(status_win);
6822 va_end(args);
6825 update_view_title(view);
6828 static void
6829 init_display(void)
6831 const char *term;
6832 int x, y;
6834 /* Initialize the curses library */
6835 if (isatty(STDIN_FILENO)) {
6836 cursed = !!initscr();
6837 opt_tty = stdin;
6838 } else {
6839 /* Leave stdin and stdout alone when acting as a pager. */
6840 opt_tty = fopen("/dev/tty", "r+");
6841 if (!opt_tty)
6842 die("Failed to open /dev/tty");
6843 cursed = !!newterm(NULL, opt_tty, opt_tty);
6846 if (!cursed)
6847 die("Failed to initialize curses");
6849 nonl(); /* Disable conversion and detect newlines from input. */
6850 cbreak(); /* Take input chars one at a time, no wait for \n */
6851 noecho(); /* Don't echo input */
6852 leaveok(stdscr, FALSE);
6854 if (has_colors())
6855 init_colors();
6857 getmaxyx(stdscr, y, x);
6858 status_win = newwin(1, x, y - 1, 0);
6859 if (!status_win)
6860 die("Failed to create status window");
6862 /* Enable keyboard mapping */
6863 keypad(status_win, TRUE);
6864 wbkgdset(status_win, get_line_attr(LINE_STATUS));
6866 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6867 set_tabsize(opt_tab_size);
6868 #else
6869 TABSIZE = opt_tab_size;
6870 #endif
6872 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6873 if (term && !strcmp(term, "gnome-terminal")) {
6874 /* In the gnome-terminal-emulator, the message from
6875 * scrolling up one line when impossible followed by
6876 * scrolling down one line causes corruption of the
6877 * status line. This is fixed by calling wclear. */
6878 use_scroll_status_wclear = TRUE;
6879 use_scroll_redrawwin = FALSE;
6881 } else if (term && !strcmp(term, "xrvt-xpm")) {
6882 /* No problems with full optimizations in xrvt-(unicode)
6883 * and aterm. */
6884 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6886 } else {
6887 /* When scrolling in (u)xterm the last line in the
6888 * scrolling direction will update slowly. */
6889 use_scroll_redrawwin = TRUE;
6890 use_scroll_status_wclear = FALSE;
6894 static int
6895 get_input(int prompt_position)
6897 struct view *view;
6898 int i, key, cursor_y, cursor_x;
6900 if (prompt_position)
6901 input_mode = TRUE;
6903 while (TRUE) {
6904 bool loading = FALSE;
6906 foreach_view (view, i) {
6907 update_view(view);
6908 if (view_is_displayed(view) && view->has_scrolled &&
6909 use_scroll_redrawwin)
6910 redrawwin(view->win);
6911 view->has_scrolled = FALSE;
6912 if (view->pipe)
6913 loading = TRUE;
6916 /* Update the cursor position. */
6917 if (prompt_position) {
6918 getbegyx(status_win, cursor_y, cursor_x);
6919 cursor_x = prompt_position;
6920 } else {
6921 view = display[current_view];
6922 getbegyx(view->win, cursor_y, cursor_x);
6923 cursor_x = view->width - 1;
6924 cursor_y += view->lineno - view->offset;
6926 setsyx(cursor_y, cursor_x);
6928 /* Refresh, accept single keystroke of input */
6929 doupdate();
6930 nodelay(status_win, loading);
6931 key = wgetch(status_win);
6933 /* wgetch() with nodelay() enabled returns ERR when
6934 * there's no input. */
6935 if (key == ERR) {
6937 } else if (key == KEY_RESIZE) {
6938 int height, width;
6940 getmaxyx(stdscr, height, width);
6942 wresize(status_win, 1, width);
6943 mvwin(status_win, height - 1, 0);
6944 wnoutrefresh(status_win);
6945 resize_display();
6946 redraw_display(TRUE);
6948 } else {
6949 input_mode = FALSE;
6950 if (key == erasechar())
6951 key = KEY_BACKSPACE;
6952 return key;
6957 static char *
6958 prompt_input(const char *prompt, input_handler handler, void *data)
6960 enum input_status status = INPUT_OK;
6961 static char buf[SIZEOF_STR];
6962 size_t pos = 0;
6964 buf[pos] = 0;
6966 while (status == INPUT_OK || status == INPUT_SKIP) {
6967 int key;
6969 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6970 wclrtoeol(status_win);
6972 key = get_input(pos + 1);
6973 switch (key) {
6974 case KEY_RETURN:
6975 case KEY_ENTER:
6976 case '\n':
6977 status = pos ? INPUT_STOP : INPUT_CANCEL;
6978 break;
6980 case KEY_BACKSPACE:
6981 if (pos > 0)
6982 buf[--pos] = 0;
6983 else
6984 status = INPUT_CANCEL;
6985 break;
6987 case KEY_ESC:
6988 status = INPUT_CANCEL;
6989 break;
6991 default:
6992 if (pos >= sizeof(buf)) {
6993 report("Input string too long");
6994 return NULL;
6997 status = handler(data, buf, key);
6998 if (status == INPUT_OK)
6999 buf[pos++] = (char) key;
7003 /* Clear the status window */
7004 status_empty = FALSE;
7005 report("");
7007 if (status == INPUT_CANCEL)
7008 return NULL;
7010 buf[pos++] = 0;
7012 return buf;
7015 static enum input_status
7016 prompt_yesno_handler(void *data, char *buf, int c)
7018 if (c == 'y' || c == 'Y')
7019 return INPUT_STOP;
7020 if (c == 'n' || c == 'N')
7021 return INPUT_CANCEL;
7022 return INPUT_SKIP;
7025 static bool
7026 prompt_yesno(const char *prompt)
7028 char prompt2[SIZEOF_STR];
7030 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7031 return FALSE;
7033 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7036 static enum input_status
7037 read_prompt_handler(void *data, char *buf, int c)
7039 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7042 static char *
7043 read_prompt(const char *prompt)
7045 return prompt_input(prompt, read_prompt_handler, NULL);
7048 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7050 enum input_status status = INPUT_OK;
7051 int size = 0;
7053 while (items[size].text)
7054 size++;
7056 while (status == INPUT_OK) {
7057 const struct menu_item *item = &items[*selected];
7058 int key;
7059 int i;
7061 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7062 prompt, *selected + 1, size);
7063 if (item->hotkey)
7064 wprintw(status_win, "[%c] ", (char) item->hotkey);
7065 wprintw(status_win, "%s", item->text);
7066 wclrtoeol(status_win);
7068 key = get_input(COLS - 1);
7069 switch (key) {
7070 case KEY_RETURN:
7071 case KEY_ENTER:
7072 case '\n':
7073 status = INPUT_STOP;
7074 break;
7076 case KEY_LEFT:
7077 case KEY_UP:
7078 *selected = *selected - 1;
7079 if (*selected < 0)
7080 *selected = size - 1;
7081 break;
7083 case KEY_RIGHT:
7084 case KEY_DOWN:
7085 *selected = (*selected + 1) % size;
7086 break;
7088 case KEY_ESC:
7089 status = INPUT_CANCEL;
7090 break;
7092 default:
7093 for (i = 0; items[i].text; i++)
7094 if (items[i].hotkey == key) {
7095 *selected = i;
7096 status = INPUT_STOP;
7097 break;
7102 /* Clear the status window */
7103 status_empty = FALSE;
7104 report("");
7106 return status != INPUT_CANCEL;
7110 * Repository properties
7113 static struct ref **refs = NULL;
7114 static size_t refs_size = 0;
7115 static struct ref *refs_head = NULL;
7117 static struct ref_list **ref_lists = NULL;
7118 static size_t ref_lists_size = 0;
7120 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
7121 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
7122 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
7124 static int
7125 compare_refs(const void *ref1_, const void *ref2_)
7127 const struct ref *ref1 = *(const struct ref **)ref1_;
7128 const struct ref *ref2 = *(const struct ref **)ref2_;
7130 if (ref1->tag != ref2->tag)
7131 return ref2->tag - ref1->tag;
7132 if (ref1->ltag != ref2->ltag)
7133 return ref2->ltag - ref1->ltag;
7134 if (ref1->head != ref2->head)
7135 return ref2->head - ref1->head;
7136 if (ref1->tracked != ref2->tracked)
7137 return ref2->tracked - ref1->tracked;
7138 if (ref1->replace != ref2->replace)
7139 return ref2->replace - ref1->replace;
7140 /* Order remotes last. */
7141 if (ref1->remote != ref2->remote)
7142 return ref1->remote - ref2->remote;
7143 return strcmp(ref1->name, ref2->name);
7146 static void
7147 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
7149 size_t i;
7151 for (i = 0; i < refs_size; i++)
7152 if (!visitor(data, refs[i]))
7153 break;
7156 static struct ref *
7157 get_ref_head()
7159 return refs_head;
7162 static struct ref_list *
7163 get_ref_list(const char *id)
7165 struct ref_list *list;
7166 size_t i;
7168 for (i = 0; i < ref_lists_size; i++)
7169 if (!strcmp(id, ref_lists[i]->id))
7170 return ref_lists[i];
7172 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
7173 return NULL;
7174 list = calloc(1, sizeof(*list));
7175 if (!list)
7176 return NULL;
7178 for (i = 0; i < refs_size; i++) {
7179 if (!strcmp(id, refs[i]->id) &&
7180 realloc_refs_list(&list->refs, list->size, 1))
7181 list->refs[list->size++] = refs[i];
7184 if (!list->refs) {
7185 free(list);
7186 return NULL;
7189 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
7190 ref_lists[ref_lists_size++] = list;
7191 return list;
7194 static int
7195 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
7197 struct ref *ref = NULL;
7198 bool tag = FALSE;
7199 bool ltag = FALSE;
7200 bool remote = FALSE;
7201 bool replace = FALSE;
7202 bool tracked = FALSE;
7203 bool head = FALSE;
7204 int from = 0, to = refs_size - 1;
7206 if (!prefixcmp(name, "refs/tags/")) {
7207 if (!suffixcmp(name, namelen, "^{}")) {
7208 namelen -= 3;
7209 name[namelen] = 0;
7210 } else {
7211 ltag = TRUE;
7214 tag = TRUE;
7215 namelen -= STRING_SIZE("refs/tags/");
7216 name += STRING_SIZE("refs/tags/");
7218 } else if (!prefixcmp(name, "refs/remotes/")) {
7219 remote = TRUE;
7220 namelen -= STRING_SIZE("refs/remotes/");
7221 name += STRING_SIZE("refs/remotes/");
7222 tracked = !strcmp(opt_remote, name);
7224 } else if (!prefixcmp(name, "refs/replace/")) {
7225 replace = TRUE;
7226 id = name + strlen("refs/replace/");
7227 idlen = namelen - strlen("refs/replace/");
7228 name = "replaced";
7229 namelen = strlen(name);
7231 } else if (!prefixcmp(name, "refs/heads/")) {
7232 namelen -= STRING_SIZE("refs/heads/");
7233 name += STRING_SIZE("refs/heads/");
7234 if (strlen(opt_head) == namelen
7235 && !strncmp(opt_head, name, namelen))
7236 return OK;
7238 } else if (!strcmp(name, "HEAD")) {
7239 head = TRUE;
7240 if (*opt_head) {
7241 namelen = strlen(opt_head);
7242 name = opt_head;
7246 /* If we are reloading or it's an annotated tag, replace the
7247 * previous SHA1 with the resolved commit id; relies on the fact
7248 * git-ls-remote lists the commit id of an annotated tag right
7249 * before the commit id it points to. */
7250 while ((from <= to) && !replace) {
7251 size_t pos = (to + from) / 2;
7252 int cmp = strcmp(name, refs[pos]->name);
7254 if (!cmp) {
7255 ref = refs[pos];
7256 break;
7259 if (cmp < 0)
7260 to = pos - 1;
7261 else
7262 from = pos + 1;
7265 if (!ref) {
7266 if (!realloc_refs(&refs, refs_size, 1))
7267 return ERR;
7268 ref = calloc(1, sizeof(*ref) + namelen);
7269 if (!ref)
7270 return ERR;
7271 memmove(refs + from + 1, refs + from,
7272 (refs_size - from) * sizeof(*refs));
7273 refs[from] = ref;
7274 strncpy(ref->name, name, namelen);
7275 refs_size++;
7278 ref->head = head;
7279 ref->tag = tag;
7280 ref->ltag = ltag;
7281 ref->remote = remote;
7282 ref->replace = replace;
7283 ref->tracked = tracked;
7284 string_copy_rev(ref->id, id);
7286 if (head)
7287 refs_head = ref;
7288 return OK;
7291 static int
7292 load_refs(void)
7294 const char *head_argv[] = {
7295 "git", "symbolic-ref", "HEAD", NULL
7297 static const char *ls_remote_argv[SIZEOF_ARG] = {
7298 "git", "ls-remote", opt_git_dir, NULL
7300 static bool init = FALSE;
7301 size_t i;
7303 if (!init) {
7304 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
7305 die("TIG_LS_REMOTE contains too many arguments");
7306 init = TRUE;
7309 if (!*opt_git_dir)
7310 return OK;
7312 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
7313 !prefixcmp(opt_head, "refs/heads/")) {
7314 char *offset = opt_head + STRING_SIZE("refs/heads/");
7316 memmove(opt_head, offset, strlen(offset) + 1);
7319 refs_head = NULL;
7320 for (i = 0; i < refs_size; i++)
7321 refs[i]->id[0] = 0;
7323 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
7324 return ERR;
7326 /* Update the ref lists to reflect changes. */
7327 for (i = 0; i < ref_lists_size; i++) {
7328 struct ref_list *list = ref_lists[i];
7329 size_t old, new;
7331 for (old = new = 0; old < list->size; old++)
7332 if (!strcmp(list->id, list->refs[old]->id))
7333 list->refs[new++] = list->refs[old];
7334 list->size = new;
7337 qsort(refs, refs_size, sizeof(*refs), compare_refs);
7339 return OK;
7342 static void
7343 set_remote_branch(const char *name, const char *value, size_t valuelen)
7345 if (!strcmp(name, ".remote")) {
7346 string_ncopy(opt_remote, value, valuelen);
7348 } else if (*opt_remote && !strcmp(name, ".merge")) {
7349 size_t from = strlen(opt_remote);
7351 if (!prefixcmp(value, "refs/heads/"))
7352 value += STRING_SIZE("refs/heads/");
7354 if (!string_format_from(opt_remote, &from, "/%s", value))
7355 opt_remote[0] = 0;
7359 static void
7360 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7362 const char *argv[SIZEOF_ARG] = { name, "=" };
7363 int argc = 1 + (cmd == option_set_command);
7364 enum option_code error;
7366 if (!argv_from_string(argv, &argc, value))
7367 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7368 else
7369 error = cmd(argc, argv);
7371 if (error != OPT_OK)
7372 warn("Option 'tig.%s': %s", name, option_errors[error]);
7375 static bool
7376 set_environment_variable(const char *name, const char *value)
7378 size_t len = strlen(name) + 1 + strlen(value) + 1;
7379 char *env = malloc(len);
7381 if (env &&
7382 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7383 putenv(env) == 0)
7384 return TRUE;
7385 free(env);
7386 return FALSE;
7389 static void
7390 set_work_tree(const char *value)
7392 char cwd[SIZEOF_STR];
7394 if (!getcwd(cwd, sizeof(cwd)))
7395 die("Failed to get cwd path: %s", strerror(errno));
7396 if (chdir(opt_git_dir) < 0)
7397 die("Failed to chdir(%s): %s", strerror(errno));
7398 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7399 die("Failed to get git path: %s", strerror(errno));
7400 if (chdir(cwd) < 0)
7401 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7402 if (chdir(value) < 0)
7403 die("Failed to chdir(%s): %s", value, strerror(errno));
7404 if (!getcwd(cwd, sizeof(cwd)))
7405 die("Failed to get cwd path: %s", strerror(errno));
7406 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7407 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7408 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7409 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7410 opt_is_inside_work_tree = TRUE;
7413 static int
7414 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7416 if (!strcmp(name, "gui.encoding"))
7417 parse_encoding(&opt_encoding, value, TRUE);
7419 else if (!strcmp(name, "core.editor"))
7420 string_ncopy(opt_editor, value, valuelen);
7422 else if (!strcmp(name, "core.worktree"))
7423 set_work_tree(value);
7425 else if (!prefixcmp(name, "tig.color."))
7426 set_repo_config_option(name + 10, value, option_color_command);
7428 else if (!prefixcmp(name, "tig.bind."))
7429 set_repo_config_option(name + 9, value, option_bind_command);
7431 else if (!prefixcmp(name, "tig."))
7432 set_repo_config_option(name + 4, value, option_set_command);
7434 else if (*opt_head && !prefixcmp(name, "branch.") &&
7435 !strncmp(name + 7, opt_head, strlen(opt_head)))
7436 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7438 return OK;
7441 static int
7442 load_git_config(void)
7444 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7446 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7449 static int
7450 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7452 if (!opt_git_dir[0]) {
7453 string_ncopy(opt_git_dir, name, namelen);
7455 } else if (opt_is_inside_work_tree == -1) {
7456 /* This can be 3 different values depending on the
7457 * version of git being used. If git-rev-parse does not
7458 * understand --is-inside-work-tree it will simply echo
7459 * the option else either "true" or "false" is printed.
7460 * Default to true for the unknown case. */
7461 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7463 } else if (*name == '.') {
7464 string_ncopy(opt_cdup, name, namelen);
7466 } else {
7467 string_ncopy(opt_prefix, name, namelen);
7470 return OK;
7473 static int
7474 load_repo_info(void)
7476 const char *rev_parse_argv[] = {
7477 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7478 "--show-cdup", "--show-prefix", NULL
7481 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7486 * Main
7489 static const char usage[] =
7490 "tig " TIG_VERSION " (" __DATE__ ")\n"
7491 "\n"
7492 "Usage: tig [options] [revs] [--] [paths]\n"
7493 " or: tig show [options] [revs] [--] [paths]\n"
7494 " or: tig blame [options] [rev] [--] path\n"
7495 " or: tig status\n"
7496 " or: tig < [git command output]\n"
7497 "\n"
7498 "Options:\n"
7499 " +<number> Select line <number> in the first view\n"
7500 " -v, --version Show version and exit\n"
7501 " -h, --help Show help message and exit";
7503 static void __NORETURN
7504 quit(int sig)
7506 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7507 if (cursed)
7508 endwin();
7509 exit(0);
7512 static void __NORETURN
7513 die(const char *err, ...)
7515 va_list args;
7517 endwin();
7519 va_start(args, err);
7520 fputs("tig: ", stderr);
7521 vfprintf(stderr, err, args);
7522 fputs("\n", stderr);
7523 va_end(args);
7525 exit(1);
7528 static void
7529 warn(const char *msg, ...)
7531 va_list args;
7533 va_start(args, msg);
7534 fputs("tig warning: ", stderr);
7535 vfprintf(stderr, msg, args);
7536 fputs("\n", stderr);
7537 va_end(args);
7540 static int
7541 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7543 const char ***filter_args = data;
7545 return argv_append(filter_args, name) ? OK : ERR;
7548 static void
7549 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7551 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7552 const char **all_argv = NULL;
7554 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7555 !argv_append_array(&all_argv, argv) ||
7556 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7557 die("Failed to split arguments");
7558 argv_free(all_argv);
7559 free(all_argv);
7562 static void
7563 filter_options(const char *argv[], bool blame)
7565 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7567 if (blame)
7568 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7569 else
7570 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7572 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7575 static enum request
7576 parse_options(int argc, const char *argv[])
7578 enum request request = REQ_VIEW_MAIN;
7579 const char *subcommand;
7580 bool seen_dashdash = FALSE;
7581 const char **filter_argv = NULL;
7582 int i;
7584 if (!isatty(STDIN_FILENO))
7585 return REQ_VIEW_PAGER;
7587 if (argc <= 1)
7588 return REQ_VIEW_MAIN;
7590 subcommand = argv[1];
7591 if (!strcmp(subcommand, "status")) {
7592 if (argc > 2)
7593 warn("ignoring arguments after `%s'", subcommand);
7594 return REQ_VIEW_STATUS;
7596 } else if (!strcmp(subcommand, "blame")) {
7597 request = REQ_VIEW_BLAME;
7599 } else if (!strcmp(subcommand, "show")) {
7600 request = REQ_VIEW_DIFF;
7602 } else {
7603 subcommand = NULL;
7606 for (i = 1 + !!subcommand; i < argc; i++) {
7607 const char *opt = argv[i];
7609 // stop parsing our options after -- and let rev-parse handle the rest
7610 if (!seen_dashdash) {
7611 if (!strcmp(opt, "--")) {
7612 seen_dashdash = TRUE;
7613 continue;
7615 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7616 printf("tig version %s\n", TIG_VERSION);
7617 quit(0);
7619 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7620 printf("%s\n", usage);
7621 quit(0);
7623 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7624 opt_lineno = atoi(opt + 1);
7625 continue;
7630 if (!argv_append(&filter_argv, opt))
7631 die("command too long");
7634 if (filter_argv)
7635 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7637 /* Finish validating and setting up blame options */
7638 if (request == REQ_VIEW_BLAME) {
7639 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7640 die("invalid number of options to blame\n\n%s", usage);
7642 if (opt_rev_argv) {
7643 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7646 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7649 return request;
7653 main(int argc, const char *argv[])
7655 const char *codeset = ENCODING_UTF8;
7656 enum request request = parse_options(argc, argv);
7657 struct view *view;
7659 signal(SIGINT, quit);
7660 signal(SIGPIPE, SIG_IGN);
7662 if (setlocale(LC_ALL, "")) {
7663 codeset = nl_langinfo(CODESET);
7666 if (load_repo_info() == ERR)
7667 die("Failed to load repo info.");
7669 if (load_options() == ERR)
7670 die("Failed to load user config.");
7672 if (load_git_config() == ERR)
7673 die("Failed to load repo config.");
7675 /* Require a git repository unless when running in pager mode. */
7676 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7677 die("Not a git repository");
7679 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
7680 char translit[SIZEOF_STR];
7682 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
7683 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
7684 else
7685 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
7686 if (opt_iconv_out == ICONV_NONE)
7687 die("Failed to initialize character set conversion");
7690 if (load_refs() == ERR)
7691 die("Failed to load refs.");
7693 init_display();
7695 while (view_driver(display[current_view], request)) {
7696 int key = get_input(0);
7698 view = display[current_view];
7699 request = get_keybinding(view->keymap, key);
7701 /* Some low-level request handling. This keeps access to
7702 * status_win restricted. */
7703 switch (request) {
7704 case REQ_NONE:
7705 report("Unknown key, press %s for help",
7706 get_view_key(view, REQ_VIEW_HELP));
7707 break;
7708 case REQ_PROMPT:
7710 char *cmd = read_prompt(":");
7712 if (cmd && string_isnumber(cmd)) {
7713 int lineno = view->lineno + 1;
7715 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
7716 select_view_line(view, lineno - 1);
7717 report("");
7718 } else {
7719 report("Unable to parse '%s' as a line number", cmd);
7721 } else if (cmd && iscommit(cmd)) {
7722 string_ncopy(opt_search, cmd, strlen(cmd));
7724 request = view_request(view, REQ_JUMP_COMMIT);
7725 if (request == REQ_JUMP_COMMIT) {
7726 report("Jumping to commits is not supported by the '%s' view", view->name);
7729 } else if (cmd) {
7730 struct view *next = VIEW(REQ_VIEW_PAGER);
7731 const char *argv[SIZEOF_ARG] = { "git" };
7732 int argc = 1;
7734 /* When running random commands, initially show the
7735 * command in the title. However, it maybe later be
7736 * overwritten if a commit line is selected. */
7737 string_ncopy(next->ref, cmd, strlen(cmd));
7739 if (!argv_from_string(argv, &argc, cmd)) {
7740 report("Too many arguments");
7741 } else if (!format_argv(&next->argv, argv, FALSE)) {
7742 report("Argument formatting failed");
7743 } else {
7744 next->dir = NULL;
7745 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7749 request = REQ_NONE;
7750 break;
7752 case REQ_SEARCH:
7753 case REQ_SEARCH_BACK:
7755 const char *prompt = request == REQ_SEARCH ? "/" : "?";
7756 char *search = read_prompt(prompt);
7758 if (search)
7759 string_ncopy(opt_search, search, strlen(search));
7760 else if (*opt_search)
7761 request = request == REQ_SEARCH ?
7762 REQ_FIND_NEXT :
7763 REQ_FIND_PREV;
7764 else
7765 request = REQ_NONE;
7766 break;
7768 default:
7769 break;
7773 quit(0);
7775 return 0;