User-defined commands prefixed with '@' are run with no console output
[tig.git] / tig.c
blob57755ecaacb7cd0e89fcecf0897f2441d8c69493
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 --", 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;
1040 bool silent;
1043 static struct run_request *run_request;
1044 static size_t run_requests;
1046 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1048 static enum request
1049 add_run_request(enum keymap keymap, int key, const char **argv, bool silent)
1051 struct run_request *req;
1053 if (!realloc_run_requests(&run_request, run_requests, 1))
1054 return REQ_NONE;
1056 req = &run_request[run_requests];
1057 req->silent = silent;
1058 req->keymap = keymap;
1059 req->key = key;
1060 req->argv = NULL;
1062 if (!argv_copy(&req->argv, argv))
1063 return REQ_NONE;
1065 return REQ_NONE + ++run_requests;
1068 static struct run_request *
1069 get_run_request(enum request request)
1071 if (request <= REQ_NONE)
1072 return NULL;
1073 return &run_request[request - REQ_NONE - 1];
1076 static void
1077 add_builtin_run_requests(void)
1079 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1080 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1081 const char *commit[] = { "git", "commit", NULL };
1082 const char *gc[] = { "git", "gc", NULL };
1083 struct run_request reqs[] = {
1084 { KEYMAP_MAIN, 'C', cherry_pick },
1085 { KEYMAP_STATUS, 'C', commit },
1086 { KEYMAP_BRANCH, 'C', checkout },
1087 { KEYMAP_GENERIC, 'G', gc },
1089 int i;
1091 for (i = 0; i < ARRAY_SIZE(reqs); i++) {
1092 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
1094 if (req != reqs[i].key)
1095 continue;
1096 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv, FALSE);
1097 if (req != REQ_NONE)
1098 add_keybinding(reqs[i].keymap, req, reqs[i].key);
1103 * User config file handling.
1106 #define OPT_ERR_INFO \
1107 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1108 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1109 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1110 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1111 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1112 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1113 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1114 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1115 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1116 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1117 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1118 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1119 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1120 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1121 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1122 OPT_ERR_(OBSOLETE_VARIABLE_NAME, "Obsolete variable name"), \
1123 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1124 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1125 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1127 enum option_code {
1128 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1129 OPT_ERR_INFO
1130 #undef OPT_ERR_
1131 OPT_OK
1134 static const char *option_errors[] = {
1135 #define OPT_ERR_(name, msg) msg
1136 OPT_ERR_INFO
1137 #undef OPT_ERR_
1140 static const struct enum_map color_map[] = {
1141 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1142 COLOR_MAP(DEFAULT),
1143 COLOR_MAP(BLACK),
1144 COLOR_MAP(BLUE),
1145 COLOR_MAP(CYAN),
1146 COLOR_MAP(GREEN),
1147 COLOR_MAP(MAGENTA),
1148 COLOR_MAP(RED),
1149 COLOR_MAP(WHITE),
1150 COLOR_MAP(YELLOW),
1153 static const struct enum_map attr_map[] = {
1154 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1155 ATTR_MAP(NORMAL),
1156 ATTR_MAP(BLINK),
1157 ATTR_MAP(BOLD),
1158 ATTR_MAP(DIM),
1159 ATTR_MAP(REVERSE),
1160 ATTR_MAP(STANDOUT),
1161 ATTR_MAP(UNDERLINE),
1164 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1166 static enum option_code
1167 parse_step(double *opt, const char *arg)
1169 *opt = atoi(arg);
1170 if (!strchr(arg, '%'))
1171 return OPT_OK;
1173 /* "Shift down" so 100% and 1 does not conflict. */
1174 *opt = (*opt - 1) / 100;
1175 if (*opt >= 1.0) {
1176 *opt = 0.99;
1177 return OPT_ERR_INVALID_STEP_VALUE;
1179 if (*opt < 0.0) {
1180 *opt = 1;
1181 return OPT_ERR_INVALID_STEP_VALUE;
1183 return OPT_OK;
1186 static enum option_code
1187 parse_int(int *opt, const char *arg, int min, int max)
1189 int value = atoi(arg);
1191 if (min <= value && value <= max) {
1192 *opt = value;
1193 return OPT_OK;
1196 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1199 static bool
1200 set_color(int *color, const char *name)
1202 if (map_enum(color, color_map, name))
1203 return TRUE;
1204 if (!prefixcmp(name, "color"))
1205 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1206 return FALSE;
1209 /* Wants: object fgcolor bgcolor [attribute] */
1210 static enum option_code
1211 option_color_command(int argc, const char *argv[])
1213 struct line_info *info;
1215 if (argc < 3)
1216 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1218 if (*argv[0] == '"' || *argv[0] == '\'') {
1219 info = add_custom_color(argv[0]);
1220 } else {
1221 info = get_line_info(argv[0]);
1223 if (!info) {
1224 static const struct enum_map obsolete[] = {
1225 ENUM_MAP("main-delim", LINE_DELIMITER),
1226 ENUM_MAP("main-date", LINE_DATE),
1227 ENUM_MAP("main-author", LINE_AUTHOR),
1229 int index;
1231 if (!map_enum(&index, obsolete, argv[0]))
1232 return OPT_ERR_UNKNOWN_COLOR_NAME;
1233 info = &line_info[index];
1236 if (!set_color(&info->fg, argv[1]) ||
1237 !set_color(&info->bg, argv[2]))
1238 return OPT_ERR_UNKNOWN_COLOR;
1240 info->attr = 0;
1241 while (argc-- > 3) {
1242 int attr;
1244 if (!set_attribute(&attr, argv[argc]))
1245 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1246 info->attr |= attr;
1249 return OPT_OK;
1252 static enum option_code
1253 parse_bool(bool *opt, const char *arg)
1255 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1256 ? TRUE : FALSE;
1257 return OPT_OK;
1260 static enum option_code
1261 parse_enum_do(unsigned int *opt, const char *arg,
1262 const struct enum_map *map, size_t map_size)
1264 bool is_true;
1266 assert(map_size > 1);
1268 if (map_enum_do(map, map_size, (int *) opt, arg))
1269 return OPT_OK;
1271 parse_bool(&is_true, arg);
1272 *opt = is_true ? map[1].value : map[0].value;
1273 return OPT_OK;
1276 #define parse_enum(opt, arg, map) \
1277 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1279 static enum option_code
1280 parse_string(char *opt, const char *arg, size_t optsize)
1282 int arglen = strlen(arg);
1284 switch (arg[0]) {
1285 case '\"':
1286 case '\'':
1287 if (arglen == 1 || arg[arglen - 1] != arg[0])
1288 return OPT_ERR_UNMATCHED_QUOTATION;
1289 arg += 1; arglen -= 2;
1290 default:
1291 string_ncopy_do(opt, optsize, arg, arglen);
1292 return OPT_OK;
1296 static enum option_code
1297 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1299 char buf[SIZEOF_STR];
1300 enum option_code code = parse_string(buf, arg, sizeof(buf));
1302 if (code == OPT_OK) {
1303 struct encoding *encoding = *encoding_ref;
1305 if (encoding && !priority)
1306 return code;
1307 encoding = encoding_open(buf);
1308 if (encoding)
1309 *encoding_ref = encoding;
1312 return code;
1315 static enum option_code
1316 parse_args(const char ***args, const char *argv[])
1318 if (*args == NULL && !argv_copy(args, argv))
1319 return OPT_ERR_OUT_OF_MEMORY;
1320 return OPT_OK;
1323 /* Wants: name = value */
1324 static enum option_code
1325 option_set_command(int argc, const char *argv[])
1327 if (argc < 3)
1328 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1330 if (strcmp(argv[1], "="))
1331 return OPT_ERR_NO_VALUE_ASSIGNED;
1333 if (!strcmp(argv[0], "blame-options"))
1334 return parse_args(&opt_blame_argv, argv + 2);
1336 if (argc != 3)
1337 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1339 if (!strcmp(argv[0], "show-author"))
1340 return parse_enum(&opt_author, argv[2], author_map);
1342 if (!strcmp(argv[0], "show-date"))
1343 return parse_enum(&opt_date, argv[2], date_map);
1345 if (!strcmp(argv[0], "show-rev-graph"))
1346 return parse_bool(&opt_rev_graph, argv[2]);
1348 if (!strcmp(argv[0], "show-refs"))
1349 return parse_bool(&opt_show_refs, argv[2]);
1351 if (!strcmp(argv[0], "show-notes")) {
1352 int res;
1354 strcpy(opt_notes_arg, "--notes=");
1355 res = parse_string(opt_notes_arg + 8, argv[2],
1356 sizeof(opt_notes_arg) - 8);
1357 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1358 opt_notes_arg[7] = '\0';
1359 return res;
1362 if (!strcmp(argv[0], "show-line-numbers"))
1363 return parse_bool(&opt_line_number, argv[2]);
1365 if (!strcmp(argv[0], "line-graphics"))
1366 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1368 if (!strcmp(argv[0], "line-number-interval"))
1369 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1371 if (!strcmp(argv[0], "author-width"))
1372 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1374 if (!strcmp(argv[0], "filename-width"))
1375 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1377 if (!strcmp(argv[0], "show-filename"))
1378 return parse_enum(&opt_filename, argv[2], filename_map);
1380 if (!strcmp(argv[0], "horizontal-scroll"))
1381 return parse_step(&opt_hscroll, argv[2]);
1383 if (!strcmp(argv[0], "split-view-height"))
1384 return parse_step(&opt_scale_split_view, argv[2]);
1386 if (!strcmp(argv[0], "tab-size"))
1387 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1389 if (!strcmp(argv[0], "diff-context")) {
1390 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1392 if (code == OPT_OK)
1393 update_diff_context_arg(opt_diff_context);
1394 return code;
1397 if (!strcmp(argv[0], "ignore-space")) {
1398 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1400 if (code == OPT_OK)
1401 update_ignore_space_arg();
1402 return code;
1405 if (!strcmp(argv[0], "status-untracked-dirs"))
1406 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1408 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1411 /* Wants: mode request key */
1412 static enum option_code
1413 option_bind_command(int argc, const char *argv[])
1415 enum request request;
1416 int keymap = -1;
1417 int key;
1419 if (argc < 3)
1420 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1422 if (!set_keymap(&keymap, argv[0]))
1423 return OPT_ERR_UNKNOWN_KEY_MAP;
1425 key = get_key_value(argv[1]);
1426 if (key == ERR)
1427 return OPT_ERR_UNKNOWN_KEY;
1429 request = get_request(argv[2]);
1430 if (request == REQ_UNKNOWN) {
1431 static const struct enum_map obsolete[] = {
1432 ENUM_MAP("cherry-pick", REQ_NONE),
1433 ENUM_MAP("screen-resize", REQ_NONE),
1434 ENUM_MAP("tree-parent", REQ_PARENT),
1436 int alias;
1438 if (map_enum(&alias, obsolete, argv[2])) {
1439 if (alias != REQ_NONE)
1440 add_keybinding(keymap, alias, key);
1441 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1444 if (request == REQ_UNKNOWN && *argv[2]++ == '!') {
1445 bool silent = *argv[2] == '@';
1447 if (silent)
1448 argv[2]++;
1449 request = add_run_request(keymap, key, argv + 2, silent);
1451 if (request == REQ_UNKNOWN)
1452 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1454 add_keybinding(keymap, request, key);
1456 return OPT_OK;
1460 static enum option_code load_option_file(const char *path);
1462 static enum option_code
1463 option_source_command(int argc, const char *argv[])
1465 if (argc < 1)
1466 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1468 return load_option_file(argv[0]);
1471 static enum option_code
1472 set_option(const char *opt, char *value)
1474 const char *argv[SIZEOF_ARG];
1475 int argc = 0;
1477 if (!argv_from_string(argv, &argc, value))
1478 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1480 if (!strcmp(opt, "color"))
1481 return option_color_command(argc, argv);
1483 if (!strcmp(opt, "set"))
1484 return option_set_command(argc, argv);
1486 if (!strcmp(opt, "bind"))
1487 return option_bind_command(argc, argv);
1489 if (!strcmp(opt, "source"))
1490 return option_source_command(argc, argv);
1492 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1495 struct config_state {
1496 const char *path;
1497 int lineno;
1498 bool errors;
1501 static int
1502 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1504 struct config_state *config = data;
1505 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1507 config->lineno++;
1509 /* Check for comment markers, since read_properties() will
1510 * only ensure opt and value are split at first " \t". */
1511 optlen = strcspn(opt, "#");
1512 if (optlen == 0)
1513 return OK;
1515 if (opt[optlen] == 0) {
1516 /* Look for comment endings in the value. */
1517 size_t len = strcspn(value, "#");
1519 if (len < valuelen) {
1520 valuelen = len;
1521 value[valuelen] = 0;
1524 status = set_option(opt, value);
1527 if (status != OPT_OK) {
1528 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1529 option_errors[status], (int) optlen, opt);
1530 config->errors = TRUE;
1533 /* Always keep going if errors are encountered. */
1534 return OK;
1537 static enum option_code
1538 load_option_file(const char *path)
1540 struct config_state config = { path, 0, FALSE };
1541 struct io io;
1543 /* Do not read configuration from stdin if set to "" */
1544 if (!path || !strlen(path))
1545 return OPT_OK;
1547 /* It's OK that the file doesn't exist. */
1548 if (!io_open(&io, "%s", path))
1549 return OPT_ERR_FILE_DOES_NOT_EXIST;
1551 if (io_load(&io, " \t", read_option, &config) == ERR ||
1552 config.errors == TRUE)
1553 warn("Errors while loading %s.", path);
1554 return OPT_OK;
1557 static int
1558 load_options(void)
1560 const char *home = getenv("HOME");
1561 const char *tigrc_user = getenv("TIGRC_USER");
1562 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1563 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1564 char buf[SIZEOF_STR];
1566 if (!tigrc_system)
1567 tigrc_system = SYSCONFDIR "/tigrc";
1568 load_option_file(tigrc_system);
1570 if (!tigrc_user) {
1571 if (!home || !string_format(buf, "%s/.tigrc", home))
1572 return ERR;
1573 tigrc_user = buf;
1575 load_option_file(tigrc_user);
1577 /* Add _after_ loading config files to avoid adding run requests
1578 * that conflict with keybindings. */
1579 add_builtin_run_requests();
1581 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1582 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1583 int argc = 0;
1585 if (!string_format(buf, "%s", tig_diff_opts) ||
1586 !argv_from_string(diff_opts, &argc, buf))
1587 die("TIG_DIFF_OPTS contains too many arguments");
1588 else if (!argv_copy(&opt_diff_argv, diff_opts))
1589 die("Failed to format TIG_DIFF_OPTS arguments");
1592 return OK;
1597 * The viewer
1600 struct view;
1601 struct view_ops;
1603 /* The display array of active views and the index of the current view. */
1604 static struct view *display[2];
1605 static WINDOW *display_win[2];
1606 static WINDOW *display_title[2];
1607 static unsigned int current_view;
1609 #define foreach_displayed_view(view, i) \
1610 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1612 #define displayed_views() (display[1] != NULL ? 2 : 1)
1614 /* Current head and commit ID */
1615 static char ref_blob[SIZEOF_REF] = "";
1616 static char ref_commit[SIZEOF_REF] = "HEAD";
1617 static char ref_head[SIZEOF_REF] = "HEAD";
1618 static char ref_branch[SIZEOF_REF] = "";
1620 enum view_flag {
1621 VIEW_NO_FLAGS = 0,
1622 VIEW_ALWAYS_LINENO = 1 << 0,
1623 VIEW_CUSTOM_STATUS = 1 << 1,
1624 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1625 VIEW_ADD_PAGER_REFS = 1 << 3,
1626 VIEW_OPEN_DIFF = 1 << 4,
1627 VIEW_NO_REF = 1 << 5,
1628 VIEW_NO_GIT_DIR = 1 << 6,
1629 VIEW_DIFF_LIKE = 1 << 7,
1632 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1634 struct view {
1635 const char *name; /* View name */
1636 const char *id; /* Points to either of ref_{head,commit,blob} */
1638 struct view_ops *ops; /* View operations */
1640 enum keymap keymap; /* What keymap does this view have */
1642 char ref[SIZEOF_REF]; /* Hovered commit reference */
1643 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1645 int height, width; /* The width and height of the main window */
1646 WINDOW *win; /* The main window */
1648 /* Navigation */
1649 unsigned long offset; /* Offset of the window top */
1650 unsigned long yoffset; /* Offset from the window side. */
1651 unsigned long lineno; /* Current line number */
1652 unsigned long p_offset; /* Previous offset of the window top */
1653 unsigned long p_yoffset;/* Previous offset from the window side */
1654 unsigned long p_lineno; /* Previous current line number */
1655 bool p_restore; /* Should the previous position be restored. */
1657 /* Searching */
1658 char grep[SIZEOF_STR]; /* Search string */
1659 regex_t *regex; /* Pre-compiled regexp */
1661 /* If non-NULL, points to the view that opened this view. If this view
1662 * is closed tig will switch back to the parent view. */
1663 struct view *parent;
1664 struct view *prev;
1666 /* Buffering */
1667 size_t lines; /* Total number of lines */
1668 struct line *line; /* Line index */
1669 unsigned int digits; /* Number of digits in the lines member. */
1671 /* Drawing */
1672 struct line *curline; /* Line currently being drawn. */
1673 enum line_type curtype; /* Attribute currently used for drawing. */
1674 unsigned long col; /* Column when drawing. */
1675 bool has_scrolled; /* View was scrolled. */
1677 /* Loading */
1678 const char **argv; /* Shell command arguments. */
1679 const char *dir; /* Directory from which to execute. */
1680 struct io io;
1681 struct io *pipe;
1682 time_t start_time;
1683 time_t update_secs;
1684 struct encoding *encoding;
1686 /* Private data */
1687 void *private;
1690 enum open_flags {
1691 OPEN_DEFAULT = 0, /* Use default view switching. */
1692 OPEN_SPLIT = 1, /* Split current view. */
1693 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1694 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1695 OPEN_PREPARED = 32, /* Open already prepared command. */
1696 OPEN_EXTRA = 64, /* Open extra data from command. */
1699 struct view_ops {
1700 /* What type of content being displayed. Used in the title bar. */
1701 const char *type;
1702 /* Flags to control the view behavior. */
1703 enum view_flag flags;
1704 /* Size of private data. */
1705 size_t private_size;
1706 /* Open and reads in all view content. */
1707 bool (*open)(struct view *view, enum open_flags flags);
1708 /* Read one line; updates view->line. */
1709 bool (*read)(struct view *view, char *data);
1710 /* Draw one line; @lineno must be < view->height. */
1711 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1712 /* Depending on view handle a special requests. */
1713 enum request (*request)(struct view *view, enum request request, struct line *line);
1714 /* Search for regexp in a line. */
1715 bool (*grep)(struct view *view, struct line *line);
1716 /* Select line */
1717 void (*select)(struct view *view, struct line *line);
1720 #define VIEW_OPS(id, name, ref) name##_ops
1721 static struct view_ops VIEW_INFO(VIEW_OPS);
1723 static struct view views[] = {
1724 #define VIEW_DATA(id, name, ref) \
1725 { #name, ref, &name##_ops, KEYMAP_##id }
1726 VIEW_INFO(VIEW_DATA)
1729 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1731 #define foreach_view(view, i) \
1732 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1734 #define view_is_displayed(view) \
1735 (view == display[0] || view == display[1])
1737 static enum request
1738 view_request(struct view *view, enum request request)
1740 if (!view || !view->lines)
1741 return request;
1742 return view->ops->request(view, request, &view->line[view->lineno]);
1747 * View drawing.
1750 static inline void
1751 set_view_attr(struct view *view, enum line_type type)
1753 if (!view->curline->selected && view->curtype != type) {
1754 (void) wattrset(view->win, get_line_attr(type));
1755 wchgat(view->win, -1, 0, COLOR_ID(type), NULL);
1756 view->curtype = type;
1760 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1762 static bool
1763 draw_chars(struct view *view, enum line_type type, const char *string,
1764 int max_len, bool use_tilde)
1766 static char out_buffer[BUFSIZ * 2];
1767 int len = 0;
1768 int col = 0;
1769 int trimmed = FALSE;
1770 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1772 if (max_len <= 0)
1773 return VIEW_MAX_LEN(view) <= 0;
1775 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1777 set_view_attr(view, type);
1778 if (len > 0) {
1779 if (opt_iconv_out != ICONV_NONE) {
1780 size_t inlen = len + 1;
1781 char *instr = calloc(1, inlen);
1782 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1783 if (!instr)
1784 return VIEW_MAX_LEN(view) <= 0;
1786 strncpy(instr, string, len);
1788 char *outbuf = out_buffer;
1789 size_t outlen = sizeof(out_buffer);
1791 size_t ret;
1793 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1794 if (ret != (size_t) -1) {
1795 string = out_buffer;
1796 len = sizeof(out_buffer) - outlen;
1798 free(instr);
1801 waddnstr(view->win, string, len);
1803 if (trimmed && use_tilde) {
1804 set_view_attr(view, LINE_DELIMITER);
1805 waddch(view->win, '~');
1806 col++;
1810 view->col += col;
1811 return VIEW_MAX_LEN(view) <= 0;
1814 static bool
1815 draw_space(struct view *view, enum line_type type, int max, int spaces)
1817 static char space[] = " ";
1819 spaces = MIN(max, spaces);
1821 while (spaces > 0) {
1822 int len = MIN(spaces, sizeof(space) - 1);
1824 if (draw_chars(view, type, space, len, FALSE))
1825 return TRUE;
1826 spaces -= len;
1829 return VIEW_MAX_LEN(view) <= 0;
1832 static bool
1833 draw_text(struct view *view, enum line_type type, const char *string)
1835 char text[SIZEOF_STR];
1837 do {
1838 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1840 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1841 return TRUE;
1842 string += pos;
1843 } while (*string);
1845 return VIEW_MAX_LEN(view) <= 0;
1848 static bool
1849 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
1851 char text[SIZEOF_STR];
1852 int retval;
1854 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
1855 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
1858 static bool
1859 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1861 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1862 int max = VIEW_MAX_LEN(view);
1863 int i;
1865 if (max < size)
1866 size = max;
1868 set_view_attr(view, type);
1869 /* Using waddch() instead of waddnstr() ensures that
1870 * they'll be rendered correctly for the cursor line. */
1871 for (i = skip; i < size; i++)
1872 waddch(view->win, graphic[i]);
1874 view->col += size;
1875 if (separator) {
1876 if (size < max && skip <= size)
1877 waddch(view->win, ' ');
1878 view->col++;
1881 return VIEW_MAX_LEN(view) <= 0;
1884 static bool
1885 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1887 int max = MIN(VIEW_MAX_LEN(view), len);
1888 int col = view->col;
1890 if (!text)
1891 return draw_space(view, type, max, max);
1893 return draw_chars(view, type, text, max - 1, trim)
1894 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1897 static bool
1898 draw_date(struct view *view, struct time *time)
1900 const char *date = mkdate(time, opt_date);
1901 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1903 if (opt_date == DATE_NO)
1904 return FALSE;
1906 return draw_field(view, LINE_DATE, date, cols, FALSE);
1909 static bool
1910 draw_author(struct view *view, const char *author)
1912 bool trim = author_trim(opt_author_cols);
1913 const char *text = mkauthor(author, opt_author_cols, opt_author);
1915 if (opt_author == AUTHOR_NO)
1916 return FALSE;
1918 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1921 static bool
1922 draw_filename(struct view *view, const char *filename, bool auto_enabled)
1924 bool trim = filename && strlen(filename) >= opt_filename_cols;
1926 if (opt_filename == FILENAME_NO)
1927 return FALSE;
1929 if (opt_filename == FILENAME_AUTO && !auto_enabled)
1930 return FALSE;
1932 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
1935 static bool
1936 draw_mode(struct view *view, mode_t mode)
1938 const char *str = mkmode(mode);
1940 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1943 static bool
1944 draw_lineno(struct view *view, unsigned int lineno)
1946 char number[10];
1947 int digits3 = view->digits < 3 ? 3 : view->digits;
1948 int max = MIN(VIEW_MAX_LEN(view), digits3);
1949 char *text = NULL;
1950 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1952 if (!opt_line_number)
1953 return FALSE;
1955 lineno += view->offset + 1;
1956 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1957 static char fmt[] = "%1ld";
1959 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1960 if (string_format(number, fmt, lineno))
1961 text = number;
1963 if (text)
1964 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1965 else
1966 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1967 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1970 static bool
1971 draw_refs(struct view *view, struct ref_list *refs)
1973 size_t i;
1975 if (!opt_show_refs || !refs)
1976 return FALSE;
1978 for (i = 0; i < refs->size; i++) {
1979 struct ref *ref = refs->refs[i];
1980 enum line_type type = get_line_type_from_ref(ref);
1982 if (draw_formatted(view, type, "[%s]", ref->name))
1983 return TRUE;
1985 if (draw_text(view, LINE_DEFAULT, " "))
1986 return TRUE;
1989 return FALSE;
1992 static bool
1993 draw_view_line(struct view *view, unsigned int lineno)
1995 struct line *line;
1996 bool selected = (view->offset + lineno == view->lineno);
1998 assert(view_is_displayed(view));
2000 if (view->offset + lineno >= view->lines)
2001 return FALSE;
2003 line = &view->line[view->offset + lineno];
2005 wmove(view->win, lineno, 0);
2006 if (line->cleareol)
2007 wclrtoeol(view->win);
2008 view->col = 0;
2009 view->curline = line;
2010 view->curtype = LINE_NONE;
2011 line->selected = FALSE;
2012 line->dirty = line->cleareol = 0;
2014 if (selected) {
2015 set_view_attr(view, LINE_CURSOR);
2016 line->selected = TRUE;
2017 view->ops->select(view, line);
2020 return view->ops->draw(view, line, lineno);
2023 static void
2024 redraw_view_dirty(struct view *view)
2026 bool dirty = FALSE;
2027 int lineno;
2029 for (lineno = 0; lineno < view->height; lineno++) {
2030 if (view->offset + lineno >= view->lines)
2031 break;
2032 if (!view->line[view->offset + lineno].dirty)
2033 continue;
2034 dirty = TRUE;
2035 if (!draw_view_line(view, lineno))
2036 break;
2039 if (!dirty)
2040 return;
2041 wnoutrefresh(view->win);
2044 static void
2045 redraw_view_from(struct view *view, int lineno)
2047 assert(0 <= lineno && lineno < view->height);
2049 for (; lineno < view->height; lineno++) {
2050 if (!draw_view_line(view, lineno))
2051 break;
2054 wnoutrefresh(view->win);
2057 static void
2058 redraw_view(struct view *view)
2060 werase(view->win);
2061 redraw_view_from(view, 0);
2065 static void
2066 update_view_title(struct view *view)
2068 char buf[SIZEOF_STR];
2069 char state[SIZEOF_STR];
2070 size_t bufpos = 0, statelen = 0;
2071 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2073 assert(view_is_displayed(view));
2075 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view->lines) {
2076 unsigned int view_lines = view->offset + view->height;
2077 unsigned int lines = view->lines
2078 ? MIN(view_lines, view->lines) * 100 / view->lines
2079 : 0;
2081 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
2082 view->ops->type,
2083 view->lineno + 1,
2084 view->lines,
2085 lines);
2089 if (view->pipe) {
2090 time_t secs = time(NULL) - view->start_time;
2092 /* Three git seconds are a long time ... */
2093 if (secs > 2)
2094 string_format_from(state, &statelen, " loading %lds", secs);
2097 string_format_from(buf, &bufpos, "[%s]", view->name);
2098 if (*view->ref && bufpos < view->width) {
2099 size_t refsize = strlen(view->ref);
2100 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2102 if (minsize < view->width)
2103 refsize = view->width - minsize + 7;
2104 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2107 if (statelen && bufpos < view->width) {
2108 string_format_from(buf, &bufpos, "%s", state);
2111 if (view == display[current_view])
2112 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2113 else
2114 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2116 mvwaddnstr(window, 0, 0, buf, bufpos);
2117 wclrtoeol(window);
2118 wnoutrefresh(window);
2121 static int
2122 apply_step(double step, int value)
2124 if (step >= 1)
2125 return (int) step;
2126 value *= step + 0.01;
2127 return value ? value : 1;
2130 static void
2131 resize_display(void)
2133 int offset, i;
2134 struct view *base = display[0];
2135 struct view *view = display[1] ? display[1] : display[0];
2137 /* Setup window dimensions */
2139 getmaxyx(stdscr, base->height, base->width);
2141 /* Make room for the status window. */
2142 base->height -= 1;
2144 if (view != base) {
2145 /* Horizontal split. */
2146 view->width = base->width;
2147 view->height = apply_step(opt_scale_split_view, base->height);
2148 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2149 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2150 base->height -= view->height;
2152 /* Make room for the title bar. */
2153 view->height -= 1;
2156 /* Make room for the title bar. */
2157 base->height -= 1;
2159 offset = 0;
2161 foreach_displayed_view (view, i) {
2162 if (!display_win[i]) {
2163 display_win[i] = newwin(view->height, view->width, offset, 0);
2164 if (!display_win[i])
2165 die("Failed to create %s view", view->name);
2167 scrollok(display_win[i], FALSE);
2169 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2170 if (!display_title[i])
2171 die("Failed to create title window");
2173 } else {
2174 wresize(display_win[i], view->height, view->width);
2175 mvwin(display_win[i], offset, 0);
2176 mvwin(display_title[i], offset + view->height, 0);
2179 view->win = display_win[i];
2181 offset += view->height + 1;
2185 static void
2186 redraw_display(bool clear)
2188 struct view *view;
2189 int i;
2191 foreach_displayed_view (view, i) {
2192 if (clear)
2193 wclear(view->win);
2194 redraw_view(view);
2195 update_view_title(view);
2201 * Option management
2204 #define TOGGLE_MENU \
2205 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2206 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2207 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2208 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2209 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2210 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2211 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2212 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL)
2214 static bool
2215 toggle_option(enum request request)
2217 const struct {
2218 enum request request;
2219 const struct enum_map *map;
2220 size_t map_size;
2221 } data[] = {
2222 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2223 TOGGLE_MENU
2224 #undef TOGGLE_
2226 const struct menu_item menu[] = {
2227 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2228 TOGGLE_MENU
2229 #undef TOGGLE_
2230 { 0 }
2232 int i = 0;
2234 if (request == REQ_OPTIONS) {
2235 if (!prompt_menu("Toggle option", menu, &i))
2236 return FALSE;
2237 } else {
2238 while (i < ARRAY_SIZE(data) && data[i].request != request)
2239 i++;
2240 if (i >= ARRAY_SIZE(data))
2241 die("Invalid request (%d)", request);
2244 if (data[i].map != NULL) {
2245 unsigned int *opt = menu[i].data;
2247 *opt = (*opt + 1) % data[i].map_size;
2248 if (data[i].map == ignore_space_map) {
2249 update_ignore_space_arg();
2250 report("Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2251 return TRUE;
2254 redraw_display(FALSE);
2255 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2257 } else {
2258 bool *option = menu[i].data;
2260 *option = !*option;
2261 redraw_display(FALSE);
2262 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2265 return FALSE;
2268 static void
2269 maximize_view(struct view *view, bool redraw)
2271 memset(display, 0, sizeof(display));
2272 current_view = 0;
2273 display[current_view] = view;
2274 resize_display();
2275 if (redraw) {
2276 redraw_display(FALSE);
2277 report("");
2283 * Navigation
2286 static bool
2287 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2289 if (lineno >= view->lines)
2290 lineno = view->lines > 0 ? view->lines - 1 : 0;
2292 if (offset > lineno || offset + view->height <= lineno) {
2293 unsigned long half = view->height / 2;
2295 if (lineno > half)
2296 offset = lineno - half;
2297 else
2298 offset = 0;
2301 if (offset != view->offset || lineno != view->lineno) {
2302 view->offset = offset;
2303 view->lineno = lineno;
2304 return TRUE;
2307 return FALSE;
2310 /* Scrolling backend */
2311 static void
2312 do_scroll_view(struct view *view, int lines)
2314 bool redraw_current_line = FALSE;
2316 /* The rendering expects the new offset. */
2317 view->offset += lines;
2319 assert(0 <= view->offset && view->offset < view->lines);
2320 assert(lines);
2322 /* Move current line into the view. */
2323 if (view->lineno < view->offset) {
2324 view->lineno = view->offset;
2325 redraw_current_line = TRUE;
2326 } else if (view->lineno >= view->offset + view->height) {
2327 view->lineno = view->offset + view->height - 1;
2328 redraw_current_line = TRUE;
2331 assert(view->offset <= view->lineno && view->lineno < view->lines);
2333 /* Redraw the whole screen if scrolling is pointless. */
2334 if (view->height < ABS(lines)) {
2335 redraw_view(view);
2337 } else {
2338 int line = lines > 0 ? view->height - lines : 0;
2339 int end = line + ABS(lines);
2341 scrollok(view->win, TRUE);
2342 wscrl(view->win, lines);
2343 scrollok(view->win, FALSE);
2345 while (line < end && draw_view_line(view, line))
2346 line++;
2348 if (redraw_current_line)
2349 draw_view_line(view, view->lineno - view->offset);
2350 wnoutrefresh(view->win);
2353 view->has_scrolled = TRUE;
2354 report("");
2357 /* Scroll frontend */
2358 static void
2359 scroll_view(struct view *view, enum request request)
2361 int lines = 1;
2363 assert(view_is_displayed(view));
2365 switch (request) {
2366 case REQ_SCROLL_FIRST_COL:
2367 view->yoffset = 0;
2368 redraw_view_from(view, 0);
2369 report("");
2370 return;
2371 case REQ_SCROLL_LEFT:
2372 if (view->yoffset == 0) {
2373 report("Cannot scroll beyond the first column");
2374 return;
2376 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2377 view->yoffset = 0;
2378 else
2379 view->yoffset -= apply_step(opt_hscroll, view->width);
2380 redraw_view_from(view, 0);
2381 report("");
2382 return;
2383 case REQ_SCROLL_RIGHT:
2384 view->yoffset += apply_step(opt_hscroll, view->width);
2385 redraw_view(view);
2386 report("");
2387 return;
2388 case REQ_SCROLL_PAGE_DOWN:
2389 lines = view->height;
2390 case REQ_SCROLL_LINE_DOWN:
2391 if (view->offset + lines > view->lines)
2392 lines = view->lines - view->offset;
2394 if (lines == 0 || view->offset + view->height >= view->lines) {
2395 report("Cannot scroll beyond the last line");
2396 return;
2398 break;
2400 case REQ_SCROLL_PAGE_UP:
2401 lines = view->height;
2402 case REQ_SCROLL_LINE_UP:
2403 if (lines > view->offset)
2404 lines = view->offset;
2406 if (lines == 0) {
2407 report("Cannot scroll beyond the first line");
2408 return;
2411 lines = -lines;
2412 break;
2414 default:
2415 die("request %d not handled in switch", request);
2418 do_scroll_view(view, lines);
2421 /* Cursor moving */
2422 static void
2423 move_view(struct view *view, enum request request)
2425 int scroll_steps = 0;
2426 int steps;
2428 switch (request) {
2429 case REQ_MOVE_FIRST_LINE:
2430 steps = -view->lineno;
2431 break;
2433 case REQ_MOVE_LAST_LINE:
2434 steps = view->lines - view->lineno - 1;
2435 break;
2437 case REQ_MOVE_PAGE_UP:
2438 steps = view->height > view->lineno
2439 ? -view->lineno : -view->height;
2440 break;
2442 case REQ_MOVE_PAGE_DOWN:
2443 steps = view->lineno + view->height >= view->lines
2444 ? view->lines - view->lineno - 1 : view->height;
2445 break;
2447 case REQ_MOVE_UP:
2448 steps = -1;
2449 break;
2451 case REQ_MOVE_DOWN:
2452 steps = 1;
2453 break;
2455 default:
2456 die("request %d not handled in switch", request);
2459 if (steps <= 0 && view->lineno == 0) {
2460 report("Cannot move beyond the first line");
2461 return;
2463 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2464 report("Cannot move beyond the last line");
2465 return;
2468 /* Move the current line */
2469 view->lineno += steps;
2470 assert(0 <= view->lineno && view->lineno < view->lines);
2472 /* Check whether the view needs to be scrolled */
2473 if (view->lineno < view->offset ||
2474 view->lineno >= view->offset + view->height) {
2475 scroll_steps = steps;
2476 if (steps < 0 && -steps > view->offset) {
2477 scroll_steps = -view->offset;
2479 } else if (steps > 0) {
2480 if (view->lineno == view->lines - 1 &&
2481 view->lines > view->height) {
2482 scroll_steps = view->lines - view->offset - 1;
2483 if (scroll_steps >= view->height)
2484 scroll_steps -= view->height - 1;
2489 if (!view_is_displayed(view)) {
2490 view->offset += scroll_steps;
2491 assert(0 <= view->offset && view->offset < view->lines);
2492 view->ops->select(view, &view->line[view->lineno]);
2493 return;
2496 /* Repaint the old "current" line if we be scrolling */
2497 if (ABS(steps) < view->height)
2498 draw_view_line(view, view->lineno - steps - view->offset);
2500 if (scroll_steps) {
2501 do_scroll_view(view, scroll_steps);
2502 return;
2505 /* Draw the current line */
2506 draw_view_line(view, view->lineno - view->offset);
2508 wnoutrefresh(view->win);
2509 report("");
2514 * Searching
2517 static void search_view(struct view *view, enum request request);
2519 static bool
2520 grep_text(struct view *view, const char *text[])
2522 regmatch_t pmatch;
2523 size_t i;
2525 for (i = 0; text[i]; i++)
2526 if (*text[i] &&
2527 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2528 return TRUE;
2529 return FALSE;
2532 static void
2533 select_view_line(struct view *view, unsigned long lineno)
2535 unsigned long old_lineno = view->lineno;
2536 unsigned long old_offset = view->offset;
2538 if (goto_view_line(view, view->offset, lineno)) {
2539 if (view_is_displayed(view)) {
2540 if (old_offset != view->offset) {
2541 redraw_view(view);
2542 } else {
2543 draw_view_line(view, old_lineno - view->offset);
2544 draw_view_line(view, view->lineno - view->offset);
2545 wnoutrefresh(view->win);
2547 } else {
2548 view->ops->select(view, &view->line[view->lineno]);
2553 static void
2554 find_next(struct view *view, enum request request)
2556 unsigned long lineno = view->lineno;
2557 int direction;
2559 if (!*view->grep) {
2560 if (!*opt_search)
2561 report("No previous search");
2562 else
2563 search_view(view, request);
2564 return;
2567 switch (request) {
2568 case REQ_SEARCH:
2569 case REQ_FIND_NEXT:
2570 direction = 1;
2571 break;
2573 case REQ_SEARCH_BACK:
2574 case REQ_FIND_PREV:
2575 direction = -1;
2576 break;
2578 default:
2579 return;
2582 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2583 lineno += direction;
2585 /* Note, lineno is unsigned long so will wrap around in which case it
2586 * will become bigger than view->lines. */
2587 for (; lineno < view->lines; lineno += direction) {
2588 if (view->ops->grep(view, &view->line[lineno])) {
2589 select_view_line(view, lineno);
2590 report("Line %ld matches '%s'", lineno + 1, view->grep);
2591 return;
2595 report("No match found for '%s'", view->grep);
2598 static void
2599 search_view(struct view *view, enum request request)
2601 int regex_err;
2603 if (view->regex) {
2604 regfree(view->regex);
2605 *view->grep = 0;
2606 } else {
2607 view->regex = calloc(1, sizeof(*view->regex));
2608 if (!view->regex)
2609 return;
2612 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2613 if (regex_err != 0) {
2614 char buf[SIZEOF_STR] = "unknown error";
2616 regerror(regex_err, view->regex, buf, sizeof(buf));
2617 report("Search failed: %s", buf);
2618 return;
2621 string_copy(view->grep, opt_search);
2623 find_next(view, request);
2627 * Incremental updating
2630 static void
2631 reset_view(struct view *view)
2633 int i;
2635 for (i = 0; i < view->lines; i++)
2636 free(view->line[i].data);
2637 free(view->line);
2639 view->p_offset = view->offset;
2640 view->p_yoffset = view->yoffset;
2641 view->p_lineno = view->lineno;
2643 view->line = NULL;
2644 view->offset = 0;
2645 view->yoffset = 0;
2646 view->lines = 0;
2647 view->lineno = 0;
2648 view->vid[0] = 0;
2649 view->update_secs = 0;
2652 static const char *
2653 format_arg(const char *name)
2655 static struct {
2656 const char *name;
2657 size_t namelen;
2658 const char *value;
2659 const char *value_if_empty;
2660 } vars[] = {
2661 #define FORMAT_VAR(name, value, value_if_empty) \
2662 { name, STRING_SIZE(name), value, value_if_empty }
2663 FORMAT_VAR("%(directory)", opt_path, "."),
2664 FORMAT_VAR("%(file)", opt_file, ""),
2665 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2666 FORMAT_VAR("%(head)", ref_head, ""),
2667 FORMAT_VAR("%(commit)", ref_commit, ""),
2668 FORMAT_VAR("%(blob)", ref_blob, ""),
2669 FORMAT_VAR("%(branch)", ref_branch, ""),
2671 int i;
2673 for (i = 0; i < ARRAY_SIZE(vars); i++)
2674 if (!strncmp(name, vars[i].name, vars[i].namelen))
2675 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2677 report("Unknown replacement: `%s`", name);
2678 return NULL;
2681 static bool
2682 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2684 char buf[SIZEOF_STR];
2685 int argc;
2687 argv_free(*dst_argv);
2689 for (argc = 0; src_argv[argc]; argc++) {
2690 const char *arg = src_argv[argc];
2691 size_t bufpos = 0;
2693 if (!strcmp(arg, "%(fileargs)")) {
2694 if (!argv_append_array(dst_argv, opt_file_argv))
2695 break;
2696 continue;
2698 } else if (!strcmp(arg, "%(diffargs)")) {
2699 if (!argv_append_array(dst_argv, opt_diff_argv))
2700 break;
2701 continue;
2703 } else if (!strcmp(arg, "%(blameargs)")) {
2704 if (!argv_append_array(dst_argv, opt_blame_argv))
2705 break;
2706 continue;
2708 } else if (!strcmp(arg, "%(revargs)") ||
2709 (first && !strcmp(arg, "%(commit)"))) {
2710 if (!argv_append_array(dst_argv, opt_rev_argv))
2711 break;
2712 continue;
2715 while (arg) {
2716 char *next = strstr(arg, "%(");
2717 int len = next - arg;
2718 const char *value;
2720 if (!next) {
2721 len = strlen(arg);
2722 value = "";
2724 } else {
2725 value = format_arg(next);
2727 if (!value) {
2728 return FALSE;
2732 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2733 return FALSE;
2735 arg = next ? strchr(next, ')') + 1 : NULL;
2738 if (!argv_append(dst_argv, buf))
2739 break;
2742 return src_argv[argc] == NULL;
2745 static bool
2746 restore_view_position(struct view *view)
2748 /* A view without a previous view is the first view */
2749 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2750 select_view_line(view, opt_lineno - 1);
2751 opt_lineno = 0;
2754 if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2755 return FALSE;
2757 /* Changing the view position cancels the restoring. */
2758 /* FIXME: Changing back to the first line is not detected. */
2759 if (view->offset != 0 || view->lineno != 0) {
2760 view->p_restore = FALSE;
2761 return FALSE;
2764 if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2765 view_is_displayed(view))
2766 werase(view->win);
2768 view->yoffset = view->p_yoffset;
2769 view->p_restore = FALSE;
2771 return TRUE;
2774 static void
2775 end_update(struct view *view, bool force)
2777 if (!view->pipe)
2778 return;
2779 while (!view->ops->read(view, NULL))
2780 if (!force)
2781 return;
2782 if (force)
2783 io_kill(view->pipe);
2784 io_done(view->pipe);
2785 view->pipe = NULL;
2788 static void
2789 setup_update(struct view *view, const char *vid)
2791 reset_view(view);
2792 string_copy_rev(view->vid, vid);
2793 view->pipe = &view->io;
2794 view->start_time = time(NULL);
2797 static bool
2798 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2800 bool extra = !!(flags & (OPEN_EXTRA));
2801 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2802 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2804 if (!reload && !strcmp(view->vid, view->id))
2805 return TRUE;
2807 if (view->pipe) {
2808 if (extra)
2809 io_done(view->pipe);
2810 else
2811 end_update(view, TRUE);
2814 if (!refresh && argv) {
2815 view->dir = dir;
2816 if (!format_argv(&view->argv, argv, !view->prev))
2817 return FALSE;
2819 /* Put the current ref_* value to the view title ref
2820 * member. This is needed by the blob view. Most other
2821 * views sets it automatically after loading because the
2822 * first line is a commit line. */
2823 string_copy_rev(view->ref, view->id);
2826 if (view->argv && view->argv[0] &&
2827 !io_run(&view->io, IO_RD, view->dir, view->argv))
2828 return FALSE;
2830 if (!extra)
2831 setup_update(view, view->id);
2833 return TRUE;
2836 static bool
2837 update_view(struct view *view)
2839 char *line;
2840 /* Clear the view and redraw everything since the tree sorting
2841 * might have rearranged things. */
2842 bool redraw = view->lines == 0;
2843 bool can_read = TRUE;
2845 if (!view->pipe)
2846 return TRUE;
2848 if (!io_can_read(view->pipe, FALSE)) {
2849 if (view->lines == 0 && view_is_displayed(view)) {
2850 time_t secs = time(NULL) - view->start_time;
2852 if (secs > 1 && secs > view->update_secs) {
2853 if (view->update_secs == 0)
2854 redraw_view(view);
2855 update_view_title(view);
2856 view->update_secs = secs;
2859 return TRUE;
2862 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2863 if (view->encoding) {
2864 line = encoding_convert(view->encoding, line);
2867 if (!view->ops->read(view, line)) {
2868 report("Allocation failure");
2869 end_update(view, TRUE);
2870 return FALSE;
2875 unsigned long lines = view->lines;
2876 int digits;
2878 for (digits = 0; lines; digits++)
2879 lines /= 10;
2881 /* Keep the displayed view in sync with line number scaling. */
2882 if (digits != view->digits) {
2883 view->digits = digits;
2884 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
2885 redraw = TRUE;
2889 if (io_error(view->pipe)) {
2890 report("Failed to read: %s", io_strerror(view->pipe));
2891 end_update(view, TRUE);
2893 } else if (io_eof(view->pipe)) {
2894 if (view_is_displayed(view))
2895 report("");
2896 end_update(view, FALSE);
2899 if (restore_view_position(view))
2900 redraw = TRUE;
2902 if (!view_is_displayed(view))
2903 return TRUE;
2905 if (redraw)
2906 redraw_view_from(view, 0);
2907 else
2908 redraw_view_dirty(view);
2910 /* Update the title _after_ the redraw so that if the redraw picks up a
2911 * commit reference in view->ref it'll be available here. */
2912 update_view_title(view);
2913 return TRUE;
2916 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2918 static struct line *
2919 add_line_data(struct view *view, void *data, enum line_type type)
2921 struct line *line;
2923 if (!realloc_lines(&view->line, view->lines, 1))
2924 return NULL;
2926 line = &view->line[view->lines++];
2927 memset(line, 0, sizeof(*line));
2928 line->type = type;
2929 line->data = data;
2930 line->dirty = 1;
2932 return line;
2935 static struct line *
2936 add_line_text(struct view *view, const char *text, enum line_type type)
2938 char *data = text ? strdup(text) : NULL;
2940 return data ? add_line_data(view, data, type) : NULL;
2943 static struct line *
2944 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2946 char buf[SIZEOF_STR];
2947 int retval;
2949 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
2950 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
2954 * View opening
2957 static void
2958 load_view(struct view *view, enum open_flags flags)
2960 if (view->pipe)
2961 end_update(view, TRUE);
2962 if (view->ops->private_size) {
2963 if (!view->private)
2964 view->private = calloc(1, view->ops->private_size);
2965 else
2966 memset(view->private, 0, view->ops->private_size);
2968 if (!view->ops->open(view, flags)) {
2969 report("Failed to load %s view", view->name);
2970 return;
2972 restore_view_position(view);
2974 if (view->pipe && view->lines == 0) {
2975 /* Clear the old view and let the incremental updating refill
2976 * the screen. */
2977 werase(view->win);
2978 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2979 report("");
2980 } else if (view_is_displayed(view)) {
2981 redraw_view(view);
2982 report("");
2986 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2987 #define reload_view(view) load_view(view, OPEN_RELOAD)
2989 static void
2990 split_view(struct view *prev, struct view *view)
2992 display[1] = view;
2993 current_view = 1;
2994 view->parent = prev;
2995 resize_display();
2997 if (prev->lineno - prev->offset >= prev->height) {
2998 /* Take the title line into account. */
2999 int lines = prev->lineno - prev->offset - prev->height + 1;
3001 /* Scroll the view that was split if the current line is
3002 * outside the new limited view. */
3003 do_scroll_view(prev, lines);
3006 if (view != prev && view_is_displayed(prev)) {
3007 /* "Blur" the previous view. */
3008 update_view_title(prev);
3012 static void
3013 open_view(struct view *prev, enum request request, enum open_flags flags)
3015 bool split = !!(flags & OPEN_SPLIT);
3016 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3017 struct view *view = VIEW(request);
3018 int nviews = displayed_views();
3020 assert(flags ^ OPEN_REFRESH);
3022 if (view == prev && nviews == 1 && !reload) {
3023 report("Already in %s view", view->name);
3024 return;
3027 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3028 report("The %s view is disabled in pager view", view->name);
3029 return;
3032 if (split) {
3033 split_view(prev, view);
3034 } else {
3035 maximize_view(view, FALSE);
3038 /* No prev signals that this is the first loaded view. */
3039 if (prev && view != prev) {
3040 view->prev = prev;
3043 load_view(view, flags);
3046 static void
3047 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3049 enum request request = view - views + REQ_OFFSET + 1;
3051 if (view->pipe)
3052 end_update(view, TRUE);
3053 view->dir = dir;
3055 if (!argv_copy(&view->argv, argv)) {
3056 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3057 } else {
3058 open_view(prev, request, flags | OPEN_PREPARED);
3062 static void
3063 open_external_viewer(const char *argv[], const char *dir)
3065 def_prog_mode(); /* save current tty modes */
3066 endwin(); /* restore original tty modes */
3067 io_run_fg(argv, dir);
3068 fprintf(stderr, "Press Enter to continue");
3069 getc(opt_tty);
3070 reset_prog_mode();
3071 redraw_display(TRUE);
3074 static void
3075 open_mergetool(const char *file)
3077 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3079 open_external_viewer(mergetool_argv, opt_cdup);
3082 static void
3083 open_editor(const char *file)
3085 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3086 char editor_cmd[SIZEOF_STR];
3087 const char *editor;
3088 int argc = 0;
3090 editor = getenv("GIT_EDITOR");
3091 if (!editor && *opt_editor)
3092 editor = opt_editor;
3093 if (!editor)
3094 editor = getenv("VISUAL");
3095 if (!editor)
3096 editor = getenv("EDITOR");
3097 if (!editor)
3098 editor = "vi";
3100 string_ncopy(editor_cmd, editor, strlen(editor));
3101 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3102 report("Failed to read editor command");
3103 return;
3106 editor_argv[argc] = file;
3107 open_external_viewer(editor_argv, opt_cdup);
3110 static void
3111 open_run_request(enum request request)
3113 struct run_request *req = get_run_request(request);
3114 const char **argv = NULL;
3116 if (!req) {
3117 report("Unknown run request");
3118 return;
3121 if (format_argv(&argv, req->argv, FALSE)) {
3122 if (req->silent)
3123 io_run_bg(argv);
3124 else
3125 open_external_viewer(argv, NULL);
3127 if (argv)
3128 argv_free(argv);
3129 free(argv);
3133 * User request switch noodle
3136 static int
3137 view_driver(struct view *view, enum request request)
3139 int i;
3141 if (request == REQ_NONE)
3142 return TRUE;
3144 if (request > REQ_NONE) {
3145 open_run_request(request);
3146 view_request(view, REQ_REFRESH);
3147 return TRUE;
3150 request = view_request(view, request);
3151 if (request == REQ_NONE)
3152 return TRUE;
3154 switch (request) {
3155 case REQ_MOVE_UP:
3156 case REQ_MOVE_DOWN:
3157 case REQ_MOVE_PAGE_UP:
3158 case REQ_MOVE_PAGE_DOWN:
3159 case REQ_MOVE_FIRST_LINE:
3160 case REQ_MOVE_LAST_LINE:
3161 move_view(view, request);
3162 break;
3164 case REQ_SCROLL_FIRST_COL:
3165 case REQ_SCROLL_LEFT:
3166 case REQ_SCROLL_RIGHT:
3167 case REQ_SCROLL_LINE_DOWN:
3168 case REQ_SCROLL_LINE_UP:
3169 case REQ_SCROLL_PAGE_DOWN:
3170 case REQ_SCROLL_PAGE_UP:
3171 scroll_view(view, request);
3172 break;
3174 case REQ_VIEW_BLAME:
3175 if (!opt_file[0]) {
3176 report("No file chosen, press %s to open tree view",
3177 get_view_key(view, REQ_VIEW_TREE));
3178 break;
3180 open_view(view, request, OPEN_DEFAULT);
3181 break;
3183 case REQ_VIEW_BLOB:
3184 if (!ref_blob[0]) {
3185 report("No file chosen, press %s to open tree view",
3186 get_view_key(view, REQ_VIEW_TREE));
3187 break;
3189 open_view(view, request, OPEN_DEFAULT);
3190 break;
3192 case REQ_VIEW_PAGER:
3193 if (view == NULL) {
3194 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
3195 die("Failed to open stdin");
3196 open_view(view, request, OPEN_PREPARED);
3197 break;
3200 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
3201 report("No pager content, press %s to run command from prompt",
3202 get_view_key(view, REQ_PROMPT));
3203 break;
3205 open_view(view, request, OPEN_DEFAULT);
3206 break;
3208 case REQ_VIEW_STAGE:
3209 if (!VIEW(REQ_VIEW_STAGE)->lines) {
3210 report("No stage content, press %s to open the status view and choose file",
3211 get_view_key(view, REQ_VIEW_STATUS));
3212 break;
3214 open_view(view, request, OPEN_DEFAULT);
3215 break;
3217 case REQ_VIEW_STATUS:
3218 if (opt_is_inside_work_tree == FALSE) {
3219 report("The status view requires a working tree");
3220 break;
3222 open_view(view, request, OPEN_DEFAULT);
3223 break;
3225 case REQ_VIEW_MAIN:
3226 case REQ_VIEW_DIFF:
3227 case REQ_VIEW_LOG:
3228 case REQ_VIEW_TREE:
3229 case REQ_VIEW_HELP:
3230 case REQ_VIEW_BRANCH:
3231 open_view(view, request, OPEN_DEFAULT);
3232 break;
3234 case REQ_NEXT:
3235 case REQ_PREVIOUS:
3236 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
3238 if (view->parent) {
3239 int line;
3241 view = view->parent;
3242 line = view->lineno;
3243 move_view(view, request);
3244 if (view_is_displayed(view))
3245 update_view_title(view);
3246 if (line != view->lineno)
3247 view_request(view, REQ_ENTER);
3248 } else {
3249 move_view(view, request);
3251 break;
3253 case REQ_VIEW_NEXT:
3255 int nviews = displayed_views();
3256 int next_view = (current_view + 1) % nviews;
3258 if (next_view == current_view) {
3259 report("Only one view is displayed");
3260 break;
3263 current_view = next_view;
3264 /* Blur out the title of the previous view. */
3265 update_view_title(view);
3266 report("");
3267 break;
3269 case REQ_REFRESH:
3270 report("Refreshing is not yet supported for the %s view", view->name);
3271 break;
3273 case REQ_MAXIMIZE:
3274 if (displayed_views() == 2)
3275 maximize_view(view, TRUE);
3276 break;
3278 case REQ_OPTIONS:
3279 case REQ_TOGGLE_LINENO:
3280 case REQ_TOGGLE_DATE:
3281 case REQ_TOGGLE_AUTHOR:
3282 case REQ_TOGGLE_FILENAME:
3283 case REQ_TOGGLE_GRAPHIC:
3284 case REQ_TOGGLE_REV_GRAPH:
3285 case REQ_TOGGLE_REFS:
3286 case REQ_TOGGLE_IGNORE_SPACE:
3287 if (toggle_option(request) && view_has_flags(view, VIEW_DIFF_LIKE))
3288 reload_view(view);
3289 break;
3291 case REQ_TOGGLE_SORT_FIELD:
3292 case REQ_TOGGLE_SORT_ORDER:
3293 report("Sorting is not yet supported for the %s view", view->name);
3294 break;
3296 case REQ_DIFF_CONTEXT_UP:
3297 case REQ_DIFF_CONTEXT_DOWN:
3298 report("Changing the diff context is not yet supported for the %s view", view->name);
3299 break;
3301 case REQ_SEARCH:
3302 case REQ_SEARCH_BACK:
3303 search_view(view, request);
3304 break;
3306 case REQ_FIND_NEXT:
3307 case REQ_FIND_PREV:
3308 find_next(view, request);
3309 break;
3311 case REQ_STOP_LOADING:
3312 foreach_view(view, i) {
3313 if (view->pipe)
3314 report("Stopped loading the %s view", view->name),
3315 end_update(view, TRUE);
3317 break;
3319 case REQ_SHOW_VERSION:
3320 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3321 return TRUE;
3323 case REQ_SCREEN_REDRAW:
3324 redraw_display(TRUE);
3325 break;
3327 case REQ_EDIT:
3328 report("Nothing to edit");
3329 break;
3331 case REQ_ENTER:
3332 report("Nothing to enter");
3333 break;
3335 case REQ_VIEW_CLOSE:
3336 /* XXX: Mark closed views by letting view->prev point to the
3337 * view itself. Parents to closed view should never be
3338 * followed. */
3339 if (view->prev && view->prev != view) {
3340 maximize_view(view->prev, TRUE);
3341 view->prev = view;
3342 break;
3344 /* Fall-through */
3345 case REQ_QUIT:
3346 return FALSE;
3348 default:
3349 report("Unknown key, press %s for help",
3350 get_view_key(view, REQ_VIEW_HELP));
3351 return TRUE;
3354 return TRUE;
3359 * View backend utilities
3362 enum sort_field {
3363 ORDERBY_NAME,
3364 ORDERBY_DATE,
3365 ORDERBY_AUTHOR,
3368 struct sort_state {
3369 const enum sort_field *fields;
3370 size_t size, current;
3371 bool reverse;
3374 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3375 #define get_sort_field(state) ((state).fields[(state).current])
3376 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3378 static void
3379 sort_view(struct view *view, enum request request, struct sort_state *state,
3380 int (*compare)(const void *, const void *))
3382 switch (request) {
3383 case REQ_TOGGLE_SORT_FIELD:
3384 state->current = (state->current + 1) % state->size;
3385 break;
3387 case REQ_TOGGLE_SORT_ORDER:
3388 state->reverse = !state->reverse;
3389 break;
3390 default:
3391 die("Not a sort request");
3394 qsort(view->line, view->lines, sizeof(*view->line), compare);
3395 redraw_view(view);
3398 static bool
3399 update_diff_context(enum request request)
3401 int diff_context = opt_diff_context;
3403 switch (request) {
3404 case REQ_DIFF_CONTEXT_UP:
3405 opt_diff_context += 1;
3406 update_diff_context_arg(opt_diff_context);
3407 break;
3409 case REQ_DIFF_CONTEXT_DOWN:
3410 if (opt_diff_context == 0) {
3411 report("Diff context cannot be less than zero");
3412 break;
3414 opt_diff_context -= 1;
3415 update_diff_context_arg(opt_diff_context);
3416 break;
3418 default:
3419 die("Not a diff context request");
3422 return diff_context != opt_diff_context;
3425 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3427 /* Small author cache to reduce memory consumption. It uses binary
3428 * search to lookup or find place to position new entries. No entries
3429 * are ever freed. */
3430 static const char *
3431 get_author(const char *name)
3433 static const char **authors;
3434 static size_t authors_size;
3435 int from = 0, to = authors_size - 1;
3437 while (from <= to) {
3438 size_t pos = (to + from) / 2;
3439 int cmp = strcmp(name, authors[pos]);
3441 if (!cmp)
3442 return authors[pos];
3444 if (cmp < 0)
3445 to = pos - 1;
3446 else
3447 from = pos + 1;
3450 if (!realloc_authors(&authors, authors_size, 1))
3451 return NULL;
3452 name = strdup(name);
3453 if (!name)
3454 return NULL;
3456 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3457 authors[from] = name;
3458 authors_size++;
3460 return name;
3463 static void
3464 parse_timesec(struct time *time, const char *sec)
3466 time->sec = (time_t) atol(sec);
3469 static void
3470 parse_timezone(struct time *time, const char *zone)
3472 long tz;
3474 tz = ('0' - zone[1]) * 60 * 60 * 10;
3475 tz += ('0' - zone[2]) * 60 * 60;
3476 tz += ('0' - zone[3]) * 60 * 10;
3477 tz += ('0' - zone[4]) * 60;
3479 if (zone[0] == '-')
3480 tz = -tz;
3482 time->tz = tz;
3483 time->sec -= tz;
3486 /* Parse author lines where the name may be empty:
3487 * author <email@address.tld> 1138474660 +0100
3489 static void
3490 parse_author_line(char *ident, const char **author, struct time *time)
3492 char *nameend = strchr(ident, '<');
3493 char *emailend = strchr(ident, '>');
3495 if (nameend && emailend)
3496 *nameend = *emailend = 0;
3497 ident = chomp_string(ident);
3498 if (!*ident) {
3499 if (nameend)
3500 ident = chomp_string(nameend + 1);
3501 if (!*ident)
3502 ident = "Unknown";
3505 *author = get_author(ident);
3507 /* Parse epoch and timezone */
3508 if (emailend && emailend[1] == ' ') {
3509 char *secs = emailend + 2;
3510 char *zone = strchr(secs, ' ');
3512 parse_timesec(time, secs);
3514 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3515 parse_timezone(time, zone + 1);
3519 static struct line *
3520 find_prev_line_by_type(struct view *view, struct line *line, enum line_type type)
3522 for (; view->line < line; line--)
3523 if (line->type == type)
3524 return line;
3526 return NULL;
3530 * Blame
3533 struct blame_commit {
3534 char id[SIZEOF_REV]; /* SHA1 ID. */
3535 char title[128]; /* First line of the commit message. */
3536 const char *author; /* Author of the commit. */
3537 struct time time; /* Date from the author ident. */
3538 char filename[128]; /* Name of file. */
3539 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3540 char parent_filename[128]; /* Parent/previous name of file. */
3543 struct blame_header {
3544 char id[SIZEOF_REV]; /* SHA1 ID. */
3545 size_t orig_lineno;
3546 size_t lineno;
3547 size_t group;
3550 static bool
3551 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3553 const char *pos = *posref;
3555 *posref = NULL;
3556 pos = strchr(pos + 1, ' ');
3557 if (!pos || !isdigit(pos[1]))
3558 return FALSE;
3559 *number = atoi(pos + 1);
3560 if (*number < min || *number > max)
3561 return FALSE;
3563 *posref = pos;
3564 return TRUE;
3567 static bool
3568 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3570 const char *pos = text + SIZEOF_REV - 2;
3572 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3573 return FALSE;
3575 string_ncopy(header->id, text, SIZEOF_REV);
3577 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3578 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3579 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3580 return FALSE;
3582 return TRUE;
3585 static bool
3586 match_blame_header(const char *name, char **line)
3588 size_t namelen = strlen(name);
3589 bool matched = !strncmp(name, *line, namelen);
3591 if (matched)
3592 *line += namelen;
3594 return matched;
3597 static bool
3598 parse_blame_info(struct blame_commit *commit, char *line)
3600 if (match_blame_header("author ", &line)) {
3601 commit->author = get_author(line);
3603 } else if (match_blame_header("author-time ", &line)) {
3604 parse_timesec(&commit->time, line);
3606 } else if (match_blame_header("author-tz ", &line)) {
3607 parse_timezone(&commit->time, line);
3609 } else if (match_blame_header("summary ", &line)) {
3610 string_ncopy(commit->title, line, strlen(line));
3612 } else if (match_blame_header("previous ", &line)) {
3613 if (strlen(line) <= SIZEOF_REV)
3614 return FALSE;
3615 string_copy_rev(commit->parent_id, line);
3616 line += SIZEOF_REV;
3617 string_ncopy(commit->parent_filename, line, strlen(line));
3619 } else if (match_blame_header("filename ", &line)) {
3620 string_ncopy(commit->filename, line, strlen(line));
3621 return TRUE;
3624 return FALSE;
3628 * Pager backend
3631 static bool
3632 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3634 if (draw_lineno(view, lineno))
3635 return TRUE;
3637 draw_text(view, line->type, line->data);
3638 return TRUE;
3641 static bool
3642 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3644 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3645 char ref[SIZEOF_STR];
3647 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3648 return TRUE;
3650 /* This is the only fatal call, since it can "corrupt" the buffer. */
3651 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3652 return FALSE;
3654 return TRUE;
3657 static void
3658 add_pager_refs(struct view *view, struct line *line)
3660 char buf[SIZEOF_STR];
3661 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3662 struct ref_list *list;
3663 size_t bufpos = 0, i;
3664 const char *sep = "Refs: ";
3665 bool is_tag = FALSE;
3667 assert(line->type == LINE_COMMIT);
3669 list = get_ref_list(commit_id);
3670 if (!list) {
3671 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3672 goto try_add_describe_ref;
3673 return;
3676 for (i = 0; i < list->size; i++) {
3677 struct ref *ref = list->refs[i];
3678 const char *fmt = ref->tag ? "%s[%s]" :
3679 ref->remote ? "%s<%s>" : "%s%s";
3681 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3682 return;
3683 sep = ", ";
3684 if (ref->tag)
3685 is_tag = TRUE;
3688 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3689 try_add_describe_ref:
3690 /* Add <tag>-g<commit_id> "fake" reference. */
3691 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3692 return;
3695 if (bufpos == 0)
3696 return;
3698 add_line_text(view, buf, LINE_PP_REFS);
3701 static bool
3702 pager_common_read(struct view *view, char *data, enum line_type type)
3704 struct line *line;
3706 if (!data)
3707 return TRUE;
3709 line = add_line_text(view, data, type);
3710 if (!line)
3711 return FALSE;
3713 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
3714 add_pager_refs(view, line);
3716 return TRUE;
3719 static bool
3720 pager_read(struct view *view, char *data)
3722 if (!data)
3723 return TRUE;
3725 return pager_common_read(view, data, get_line_type(data));
3728 static enum request
3729 pager_request(struct view *view, enum request request, struct line *line)
3731 int split = 0;
3733 if (request != REQ_ENTER)
3734 return request;
3736 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
3737 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3738 split = 1;
3741 /* Always scroll the view even if it was split. That way
3742 * you can use Enter to scroll through the log view and
3743 * split open each commit diff. */
3744 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3746 /* FIXME: A minor workaround. Scrolling the view will call report("")
3747 * but if we are scrolling a non-current view this won't properly
3748 * update the view title. */
3749 if (split)
3750 update_view_title(view);
3752 return REQ_NONE;
3755 static bool
3756 pager_grep(struct view *view, struct line *line)
3758 const char *text[] = { line->data, NULL };
3760 return grep_text(view, text);
3763 static void
3764 pager_select(struct view *view, struct line *line)
3766 if (line->type == LINE_COMMIT) {
3767 char *text = (char *)line->data + STRING_SIZE("commit ");
3769 if (!view_has_flags(view, VIEW_NO_REF))
3770 string_copy_rev(view->ref, text);
3771 string_copy_rev(ref_commit, text);
3775 static bool
3776 pager_open(struct view *view, enum open_flags flags)
3778 return begin_update(view, NULL, NULL, flags);
3781 static struct view_ops pager_ops = {
3782 "line",
3783 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
3785 pager_open,
3786 pager_read,
3787 pager_draw,
3788 pager_request,
3789 pager_grep,
3790 pager_select,
3793 static bool
3794 log_open(struct view *view, enum open_flags flags)
3796 static const char *log_argv[] = {
3797 "git", "log", ENCODING_ARG, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3800 return begin_update(view, NULL, log_argv, flags);
3803 static enum request
3804 log_request(struct view *view, enum request request, struct line *line)
3806 switch (request) {
3807 case REQ_REFRESH:
3808 load_refs();
3809 refresh_view(view);
3810 return REQ_NONE;
3811 default:
3812 return pager_request(view, request, line);
3816 static struct view_ops log_ops = {
3817 "line",
3818 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
3820 log_open,
3821 pager_read,
3822 pager_draw,
3823 log_request,
3824 pager_grep,
3825 pager_select,
3828 struct diff_state {
3829 bool reading_diff_stat;
3830 bool combined_diff;
3833 static bool
3834 diff_open(struct view *view, enum open_flags flags)
3836 static const char *diff_argv[] = {
3837 "git", "show", ENCODING_ARG, "--pretty=fuller", "--no-color", "--root",
3838 "--patch-with-stat", "--find-copies-harder", "-C",
3839 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
3840 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3843 return begin_update(view, NULL, diff_argv, flags);
3846 static bool
3847 diff_common_read(struct view *view, char *data, struct diff_state *state)
3849 enum line_type type;
3851 if (state->reading_diff_stat) {
3852 size_t len = strlen(data);
3853 char *pipe = strchr(data, '|');
3854 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3855 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3857 if (pipe && (has_histogram || has_bin_diff)) {
3858 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3859 } else {
3860 state->reading_diff_stat = FALSE;
3863 } else if (!strcmp(data, "---")) {
3864 state->reading_diff_stat = TRUE;
3867 type = get_line_type(data);
3869 if (type == LINE_DIFF_HEADER) {
3870 const int len = line_info[LINE_DIFF_HEADER].linelen;
3872 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
3873 !strncmp(data + len, "cc ", strlen("cc ")))
3874 state->combined_diff = TRUE;
3877 /* ADD2 and DEL2 are only valid in combined diff hunks */
3878 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
3879 type = LINE_DEFAULT;
3881 return pager_common_read(view, data, type);
3884 static enum request
3885 diff_common_enter(struct view *view, enum request request, struct line *line)
3887 if (line->type == LINE_DIFF_STAT) {
3888 int file_number = 0;
3890 while (line >= view->line && line->type == LINE_DIFF_STAT) {
3891 file_number++;
3892 line--;
3895 while (line < view->line + view->lines) {
3896 if (line->type == LINE_DIFF_HEADER) {
3897 if (file_number == 1) {
3898 break;
3900 file_number--;
3902 line++;
3906 select_view_line(view, line - view->line);
3907 report("");
3908 return REQ_NONE;
3910 } else {
3911 return pager_request(view, request, line);
3915 static bool
3916 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
3918 char *sep = strchr(*text, c);
3920 if (sep != NULL) {
3921 *sep = 0;
3922 draw_text(view, *type, *text);
3923 *sep = c;
3924 *text = sep;
3925 *type = next_type;
3928 return sep != NULL;
3931 static bool
3932 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
3934 char *text = line->data;
3935 enum line_type type = line->type;
3937 if (draw_lineno(view, lineno))
3938 return TRUE;
3940 if (type == LINE_DIFF_STAT) {
3941 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
3942 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
3943 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
3944 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
3945 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
3946 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
3947 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
3949 } else {
3950 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
3951 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
3955 draw_text(view, type, text);
3956 return TRUE;
3959 static bool
3960 diff_read(struct view *view, char *data)
3962 struct diff_state *state = view->private;
3964 if (!data) {
3965 /* Fall back to retry if no diff will be shown. */
3966 if (view->lines == 0 && opt_file_argv) {
3967 int pos = argv_size(view->argv)
3968 - argv_size(opt_file_argv) - 1;
3970 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3971 for (; view->argv[pos]; pos++) {
3972 free((void *) view->argv[pos]);
3973 view->argv[pos] = NULL;
3976 if (view->pipe)
3977 io_done(view->pipe);
3978 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3979 return FALSE;
3982 return TRUE;
3985 return diff_common_read(view, data, state);
3988 static bool
3989 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
3990 struct blame_header *header, struct blame_commit *commit)
3992 char line_arg[SIZEOF_STR];
3993 const char *blame_argv[] = {
3994 "git", "blame", ENCODING_ARG, "-p", line_arg, ref, "--", file, NULL
3996 struct io io;
3997 bool ok = FALSE;
3998 char *buf;
4000 if (!string_format(line_arg, "-L%d,+1", lineno))
4001 return FALSE;
4003 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
4004 return FALSE;
4006 while ((buf = io_get(&io, '\n', TRUE))) {
4007 if (header) {
4008 if (!parse_blame_header(header, buf, 9999999))
4009 break;
4010 header = NULL;
4012 } else if (parse_blame_info(commit, buf)) {
4013 ok = TRUE;
4014 break;
4018 if (io_error(&io))
4019 ok = FALSE;
4021 io_done(&io);
4022 return ok;
4025 static bool
4026 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4028 return prefixcmp(chunk, "@@ -") ||
4029 !(chunk = strchr(chunk, marker)) ||
4030 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4033 static enum request
4034 diff_trace_origin(struct view *view, struct line *line)
4036 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4037 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4038 const char *chunk_data;
4039 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4040 int lineno = 0;
4041 const char *file = NULL;
4042 char ref[SIZEOF_REF];
4043 struct blame_header header;
4044 struct blame_commit commit;
4046 if (!diff || !chunk || chunk == line) {
4047 report("The line to trace must be inside a diff chunk");
4048 return REQ_NONE;
4051 for (; diff < line && !file; diff++) {
4052 const char *data = diff->data;
4054 if (!prefixcmp(data, "--- a/")) {
4055 file = data + STRING_SIZE("--- a/");
4056 break;
4060 if (diff == line || !file) {
4061 report("Failed to read the file name");
4062 return REQ_NONE;
4065 chunk_data = chunk->data;
4067 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4068 report("Failed to read the line number");
4069 return REQ_NONE;
4072 if (lineno == 0) {
4073 report("This is the origin of the line");
4074 return REQ_NONE;
4077 for (chunk += 1; chunk < line; chunk++) {
4078 if (chunk->type == LINE_DIFF_ADD) {
4079 lineno += chunk_marker == '+';
4080 } else if (chunk->type == LINE_DIFF_DEL) {
4081 lineno += chunk_marker == '-';
4082 } else {
4083 lineno++;
4087 if (chunk_marker == '+')
4088 string_copy(ref, view->vid);
4089 else
4090 string_format(ref, "%s^", view->vid);
4092 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4093 report("Failed to read blame data");
4094 return REQ_NONE;
4097 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4098 string_copy(opt_ref, header.id);
4099 opt_goto_line = header.orig_lineno - 1;
4101 return REQ_VIEW_BLAME;
4104 static enum request
4105 diff_request(struct view *view, enum request request, struct line *line)
4107 switch (request) {
4108 case REQ_VIEW_BLAME:
4109 return diff_trace_origin(view, line);
4111 case REQ_DIFF_CONTEXT_UP:
4112 case REQ_DIFF_CONTEXT_DOWN:
4113 if (!update_diff_context(request))
4114 return REQ_NONE;
4115 reload_view(view);
4116 return REQ_NONE;
4119 case REQ_ENTER:
4120 return diff_common_enter(view, request, line);
4122 default:
4123 return pager_request(view, request, line);
4127 static void
4128 diff_select(struct view *view, struct line *line)
4130 if (line->type == LINE_DIFF_STAT) {
4131 const char *key = get_view_key(view, REQ_ENTER);
4133 string_format(view->ref, "Press '%s' to jump to file diff", key);
4134 } else {
4135 string_ncopy(view->ref, view->id, strlen(view->id));
4136 return pager_select(view, line);
4140 static struct view_ops diff_ops = {
4141 "line",
4142 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS,
4143 sizeof(struct diff_state),
4144 diff_open,
4145 diff_read,
4146 diff_common_draw,
4147 diff_request,
4148 pager_grep,
4149 diff_select,
4153 * Help backend
4156 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
4158 static bool
4159 help_open_keymap_title(struct view *view, enum keymap keymap)
4161 struct line *line;
4163 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
4164 help_keymap_hidden[keymap] ? '+' : '-',
4165 enum_name(keymap_map[keymap]));
4166 if (line)
4167 line->other = keymap;
4169 return help_keymap_hidden[keymap];
4172 static void
4173 help_open_keymap(struct view *view, enum keymap keymap)
4175 const char *group = NULL;
4176 char buf[SIZEOF_STR];
4177 size_t bufpos;
4178 bool add_title = TRUE;
4179 int i;
4181 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4182 const char *key = NULL;
4184 if (req_info[i].request == REQ_NONE)
4185 continue;
4187 if (!req_info[i].request) {
4188 group = req_info[i].help;
4189 continue;
4192 key = get_keys(keymap, req_info[i].request, TRUE);
4193 if (!key || !*key)
4194 continue;
4196 if (add_title && help_open_keymap_title(view, keymap))
4197 return;
4198 add_title = FALSE;
4200 if (group) {
4201 add_line_text(view, group, LINE_HELP_GROUP);
4202 group = NULL;
4205 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4206 enum_name(req_info[i]), req_info[i].help);
4209 group = "External commands:";
4211 for (i = 0; i < run_requests; i++) {
4212 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4213 const char *key;
4214 int argc;
4216 if (!req || req->keymap != keymap)
4217 continue;
4219 key = get_key_name(req->key);
4220 if (!*key)
4221 key = "(no key defined)";
4223 if (add_title && help_open_keymap_title(view, keymap))
4224 return;
4225 if (group) {
4226 add_line_text(view, group, LINE_HELP_GROUP);
4227 group = NULL;
4230 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
4231 if (!string_format_from(buf, &bufpos, "%s%s",
4232 argc ? " " : "", req->argv[argc]))
4233 return;
4235 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4239 static bool
4240 help_open(struct view *view, enum open_flags flags)
4242 enum keymap keymap;
4244 reset_view(view);
4245 view->p_restore = TRUE;
4246 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4247 add_line_text(view, "", LINE_DEFAULT);
4249 for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
4250 help_open_keymap(view, keymap);
4252 return TRUE;
4255 static enum request
4256 help_request(struct view *view, enum request request, struct line *line)
4258 switch (request) {
4259 case REQ_ENTER:
4260 if (line->type == LINE_HELP_KEYMAP) {
4261 help_keymap_hidden[line->other] =
4262 !help_keymap_hidden[line->other];
4263 refresh_view(view);
4266 return REQ_NONE;
4267 default:
4268 return pager_request(view, request, line);
4272 static struct view_ops help_ops = {
4273 "line",
4274 VIEW_NO_GIT_DIR,
4276 help_open,
4277 NULL,
4278 pager_draw,
4279 help_request,
4280 pager_grep,
4281 pager_select,
4286 * Tree backend
4289 struct tree_stack_entry {
4290 struct tree_stack_entry *prev; /* Entry below this in the stack */
4291 unsigned long lineno; /* Line number to restore */
4292 char *name; /* Position of name in opt_path */
4295 /* The top of the path stack. */
4296 static struct tree_stack_entry *tree_stack = NULL;
4297 unsigned long tree_lineno = 0;
4299 static void
4300 pop_tree_stack_entry(void)
4302 struct tree_stack_entry *entry = tree_stack;
4304 tree_lineno = entry->lineno;
4305 entry->name[0] = 0;
4306 tree_stack = entry->prev;
4307 free(entry);
4310 static void
4311 push_tree_stack_entry(const char *name, unsigned long lineno)
4313 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4314 size_t pathlen = strlen(opt_path);
4316 if (!entry)
4317 return;
4319 entry->prev = tree_stack;
4320 entry->name = opt_path + pathlen;
4321 tree_stack = entry;
4323 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4324 pop_tree_stack_entry();
4325 return;
4328 /* Move the current line to the first tree entry. */
4329 tree_lineno = 1;
4330 entry->lineno = lineno;
4333 /* Parse output from git-ls-tree(1):
4335 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4338 #define SIZEOF_TREE_ATTR \
4339 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4341 #define SIZEOF_TREE_MODE \
4342 STRING_SIZE("100644 ")
4344 #define TREE_ID_OFFSET \
4345 STRING_SIZE("100644 blob ")
4347 struct tree_entry {
4348 char id[SIZEOF_REV];
4349 mode_t mode;
4350 struct time time; /* Date from the author ident. */
4351 const char *author; /* Author of the commit. */
4352 char name[1];
4355 struct tree_state {
4356 const char *author_name;
4357 struct time author_time;
4358 bool read_date;
4361 static const char *
4362 tree_path(const struct line *line)
4364 return ((struct tree_entry *) line->data)->name;
4367 static int
4368 tree_compare_entry(const struct line *line1, const struct line *line2)
4370 if (line1->type != line2->type)
4371 return line1->type == LINE_TREE_DIR ? -1 : 1;
4372 return strcmp(tree_path(line1), tree_path(line2));
4375 static const enum sort_field tree_sort_fields[] = {
4376 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4378 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4380 static int
4381 tree_compare(const void *l1, const void *l2)
4383 const struct line *line1 = (const struct line *) l1;
4384 const struct line *line2 = (const struct line *) l2;
4385 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4386 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4388 if (line1->type == LINE_TREE_HEAD)
4389 return -1;
4390 if (line2->type == LINE_TREE_HEAD)
4391 return 1;
4393 switch (get_sort_field(tree_sort_state)) {
4394 case ORDERBY_DATE:
4395 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4397 case ORDERBY_AUTHOR:
4398 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4400 case ORDERBY_NAME:
4401 default:
4402 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4407 static struct line *
4408 tree_entry(struct view *view, enum line_type type, const char *path,
4409 const char *mode, const char *id)
4411 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4412 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4414 if (!entry || !line) {
4415 free(entry);
4416 return NULL;
4419 strncpy(entry->name, path, strlen(path));
4420 if (mode)
4421 entry->mode = strtoul(mode, NULL, 8);
4422 if (id)
4423 string_copy_rev(entry->id, id);
4425 return line;
4428 static bool
4429 tree_read_date(struct view *view, char *text, struct tree_state *state)
4431 if (!text && state->read_date) {
4432 state->read_date = FALSE;
4433 return TRUE;
4435 } else if (!text) {
4436 /* Find next entry to process */
4437 const char *log_file[] = {
4438 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
4439 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4442 if (!view->lines) {
4443 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4444 report("Tree is empty");
4445 return TRUE;
4448 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4449 report("Failed to load tree data");
4450 return TRUE;
4453 state->read_date = TRUE;
4454 return FALSE;
4456 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4457 parse_author_line(text + STRING_SIZE("author "),
4458 &state->author_name, &state->author_time);
4460 } else if (*text == ':') {
4461 char *pos;
4462 size_t annotated = 1;
4463 size_t i;
4465 pos = strchr(text, '\t');
4466 if (!pos)
4467 return TRUE;
4468 text = pos + 1;
4469 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4470 text += strlen(opt_path);
4471 pos = strchr(text, '/');
4472 if (pos)
4473 *pos = 0;
4475 for (i = 1; i < view->lines; i++) {
4476 struct line *line = &view->line[i];
4477 struct tree_entry *entry = line->data;
4479 annotated += !!entry->author;
4480 if (entry->author || strcmp(entry->name, text))
4481 continue;
4483 entry->author = state->author_name;
4484 entry->time = state->author_time;
4485 line->dirty = 1;
4486 break;
4489 if (annotated == view->lines)
4490 io_kill(view->pipe);
4492 return TRUE;
4495 static bool
4496 tree_read(struct view *view, char *text)
4498 struct tree_state *state = view->private;
4499 struct tree_entry *data;
4500 struct line *entry, *line;
4501 enum line_type type;
4502 size_t textlen = text ? strlen(text) : 0;
4503 char *path = text + SIZEOF_TREE_ATTR;
4505 if (state->read_date || !text)
4506 return tree_read_date(view, text, state);
4508 if (textlen <= SIZEOF_TREE_ATTR)
4509 return FALSE;
4510 if (view->lines == 0 &&
4511 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4512 return FALSE;
4514 /* Strip the path part ... */
4515 if (*opt_path) {
4516 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4517 size_t striplen = strlen(opt_path);
4519 if (pathlen > striplen)
4520 memmove(path, path + striplen,
4521 pathlen - striplen + 1);
4523 /* Insert "link" to parent directory. */
4524 if (view->lines == 1 &&
4525 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4526 return FALSE;
4529 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4530 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4531 if (!entry)
4532 return FALSE;
4533 data = entry->data;
4535 /* Skip "Directory ..." and ".." line. */
4536 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4537 if (tree_compare_entry(line, entry) <= 0)
4538 continue;
4540 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4542 line->data = data;
4543 line->type = type;
4544 for (; line <= entry; line++)
4545 line->dirty = line->cleareol = 1;
4546 return TRUE;
4549 if (tree_lineno > view->lineno) {
4550 view->lineno = tree_lineno;
4551 tree_lineno = 0;
4554 return TRUE;
4557 static bool
4558 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4560 struct tree_entry *entry = line->data;
4562 if (line->type == LINE_TREE_HEAD) {
4563 if (draw_text(view, line->type, "Directory path /"))
4564 return TRUE;
4565 } else {
4566 if (draw_mode(view, entry->mode))
4567 return TRUE;
4569 if (draw_author(view, entry->author))
4570 return TRUE;
4572 if (draw_date(view, &entry->time))
4573 return TRUE;
4576 draw_text(view, line->type, entry->name);
4577 return TRUE;
4580 static void
4581 open_blob_editor(const char *id)
4583 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4584 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4585 int fd = mkstemp(file);
4587 if (fd == -1)
4588 report("Failed to create temporary file");
4589 else if (!io_run_append(blob_argv, fd))
4590 report("Failed to save blob data to file");
4591 else
4592 open_editor(file);
4593 if (fd != -1)
4594 unlink(file);
4597 static enum request
4598 tree_request(struct view *view, enum request request, struct line *line)
4600 enum open_flags flags;
4601 struct tree_entry *entry = line->data;
4603 switch (request) {
4604 case REQ_VIEW_BLAME:
4605 if (line->type != LINE_TREE_FILE) {
4606 report("Blame only supported for files");
4607 return REQ_NONE;
4610 string_copy(opt_ref, view->vid);
4611 return request;
4613 case REQ_EDIT:
4614 if (line->type != LINE_TREE_FILE) {
4615 report("Edit only supported for files");
4616 } else if (!is_head_commit(view->vid)) {
4617 open_blob_editor(entry->id);
4618 } else {
4619 open_editor(opt_file);
4621 return REQ_NONE;
4623 case REQ_TOGGLE_SORT_FIELD:
4624 case REQ_TOGGLE_SORT_ORDER:
4625 sort_view(view, request, &tree_sort_state, tree_compare);
4626 return REQ_NONE;
4628 case REQ_PARENT:
4629 if (!*opt_path) {
4630 /* quit view if at top of tree */
4631 return REQ_VIEW_CLOSE;
4633 /* fake 'cd ..' */
4634 line = &view->line[1];
4635 break;
4637 case REQ_ENTER:
4638 break;
4640 default:
4641 return request;
4644 /* Cleanup the stack if the tree view is at a different tree. */
4645 while (!*opt_path && tree_stack)
4646 pop_tree_stack_entry();
4648 switch (line->type) {
4649 case LINE_TREE_DIR:
4650 /* Depending on whether it is a subdirectory or parent link
4651 * mangle the path buffer. */
4652 if (line == &view->line[1] && *opt_path) {
4653 pop_tree_stack_entry();
4655 } else {
4656 const char *basename = tree_path(line);
4658 push_tree_stack_entry(basename, view->lineno);
4661 /* Trees and subtrees share the same ID, so they are not not
4662 * unique like blobs. */
4663 flags = OPEN_RELOAD;
4664 request = REQ_VIEW_TREE;
4665 break;
4667 case LINE_TREE_FILE:
4668 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4669 request = REQ_VIEW_BLOB;
4670 break;
4672 default:
4673 return REQ_NONE;
4676 open_view(view, request, flags);
4677 if (request == REQ_VIEW_TREE)
4678 view->lineno = tree_lineno;
4680 return REQ_NONE;
4683 static bool
4684 tree_grep(struct view *view, struct line *line)
4686 struct tree_entry *entry = line->data;
4687 const char *text[] = {
4688 entry->name,
4689 mkauthor(entry->author, opt_author_cols, opt_author),
4690 mkdate(&entry->time, opt_date),
4691 NULL
4694 return grep_text(view, text);
4697 static void
4698 tree_select(struct view *view, struct line *line)
4700 struct tree_entry *entry = line->data;
4702 if (line->type == LINE_TREE_FILE) {
4703 string_copy_rev(ref_blob, entry->id);
4704 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4706 } else if (line->type != LINE_TREE_DIR) {
4707 return;
4710 string_copy_rev(view->ref, entry->id);
4713 static bool
4714 tree_open(struct view *view, enum open_flags flags)
4716 static const char *tree_argv[] = {
4717 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4720 if (view->lines == 0 && opt_prefix[0]) {
4721 char *pos = opt_prefix;
4723 while (pos && *pos) {
4724 char *end = strchr(pos, '/');
4726 if (end)
4727 *end = 0;
4728 push_tree_stack_entry(pos, 0);
4729 pos = end;
4730 if (end) {
4731 *end = '/';
4732 pos++;
4736 } else if (strcmp(view->vid, view->id)) {
4737 opt_path[0] = 0;
4740 return begin_update(view, opt_cdup, tree_argv, flags);
4743 static struct view_ops tree_ops = {
4744 "file",
4745 VIEW_NO_FLAGS,
4746 sizeof(struct tree_state),
4747 tree_open,
4748 tree_read,
4749 tree_draw,
4750 tree_request,
4751 tree_grep,
4752 tree_select,
4755 static bool
4756 blob_open(struct view *view, enum open_flags flags)
4758 static const char *blob_argv[] = {
4759 "git", "cat-file", "blob", "%(blob)", NULL
4762 view->encoding = get_path_encoding(opt_file, opt_encoding);
4764 return begin_update(view, NULL, blob_argv, flags);
4767 static bool
4768 blob_read(struct view *view, char *line)
4770 if (!line)
4771 return TRUE;
4772 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4775 static enum request
4776 blob_request(struct view *view, enum request request, struct line *line)
4778 switch (request) {
4779 case REQ_EDIT:
4780 open_blob_editor(view->vid);
4781 return REQ_NONE;
4782 default:
4783 return pager_request(view, request, line);
4787 static struct view_ops blob_ops = {
4788 "line",
4789 VIEW_NO_FLAGS,
4791 blob_open,
4792 blob_read,
4793 pager_draw,
4794 blob_request,
4795 pager_grep,
4796 pager_select,
4800 * Blame backend
4802 * Loading the blame view is a two phase job:
4804 * 1. File content is read either using opt_file from the
4805 * filesystem or using git-cat-file.
4806 * 2. Then blame information is incrementally added by
4807 * reading output from git-blame.
4810 struct blame {
4811 struct blame_commit *commit;
4812 unsigned long lineno;
4813 char text[1];
4816 struct blame_state {
4817 struct blame_commit *commit;
4818 int blamed;
4819 bool done_reading;
4820 bool auto_filename_display;
4823 static bool
4824 blame_detect_filename_display(struct view *view)
4826 bool show_filenames = FALSE;
4827 const char *filename = NULL;
4828 int i;
4830 if (opt_blame_argv) {
4831 for (i = 0; opt_blame_argv[i]; i++) {
4832 if (prefixcmp(opt_blame_argv[i], "-C"))
4833 continue;
4835 show_filenames = TRUE;
4839 for (i = 0; i < view->lines; i++) {
4840 struct blame *blame = view->line[i].data;
4842 if (blame->commit && blame->commit->id[0]) {
4843 if (!filename)
4844 filename = blame->commit->filename;
4845 else if (strcmp(filename, blame->commit->filename))
4846 show_filenames = TRUE;
4850 return show_filenames;
4853 static bool
4854 blame_open(struct view *view, enum open_flags flags)
4856 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4857 char path[SIZEOF_STR];
4858 size_t i;
4860 if (!view->prev && *opt_prefix) {
4861 string_copy(path, opt_file);
4862 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4863 return FALSE;
4866 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4867 const char *blame_cat_file_argv[] = {
4868 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4871 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4872 return FALSE;
4875 /* First pass: remove multiple references to the same commit. */
4876 for (i = 0; i < view->lines; i++) {
4877 struct blame *blame = view->line[i].data;
4879 if (blame->commit && blame->commit->id[0])
4880 blame->commit->id[0] = 0;
4881 else
4882 blame->commit = NULL;
4885 /* Second pass: free existing references. */
4886 for (i = 0; i < view->lines; i++) {
4887 struct blame *blame = view->line[i].data;
4889 if (blame->commit)
4890 free(blame->commit);
4893 string_format(view->vid, "%s", opt_file);
4894 string_format(view->ref, "%s ...", opt_file);
4896 return TRUE;
4899 static struct blame_commit *
4900 get_blame_commit(struct view *view, const char *id)
4902 size_t i;
4904 for (i = 0; i < view->lines; i++) {
4905 struct blame *blame = view->line[i].data;
4907 if (!blame->commit)
4908 continue;
4910 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4911 return blame->commit;
4915 struct blame_commit *commit = calloc(1, sizeof(*commit));
4917 if (commit)
4918 string_ncopy(commit->id, id, SIZEOF_REV);
4919 return commit;
4923 static struct blame_commit *
4924 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
4926 struct blame_header header;
4927 struct blame_commit *commit;
4928 struct blame *blame;
4930 if (!parse_blame_header(&header, text, view->lines))
4931 return NULL;
4933 commit = get_blame_commit(view, text);
4934 if (!commit)
4935 return NULL;
4937 state->blamed += header.group;
4938 while (header.group--) {
4939 struct line *line = &view->line[header.lineno + header.group - 1];
4941 blame = line->data;
4942 blame->commit = commit;
4943 blame->lineno = header.orig_lineno + header.group - 1;
4944 line->dirty = 1;
4947 return commit;
4950 static bool
4951 blame_read_file(struct view *view, const char *line, struct blame_state *state)
4953 if (!line) {
4954 const char *blame_argv[] = {
4955 "git", "blame", ENCODING_ARG, "%(blameargs)", "--incremental",
4956 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4959 if (view->lines == 0 && !view->prev)
4960 die("No blame exist for %s", view->vid);
4962 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
4963 report("Failed to load blame data");
4964 return TRUE;
4967 if (opt_goto_line > 0) {
4968 select_view_line(view, opt_goto_line);
4969 opt_goto_line = 0;
4972 state->done_reading = TRUE;
4973 return FALSE;
4975 } else {
4976 size_t linelen = strlen(line);
4977 struct blame *blame = malloc(sizeof(*blame) + linelen);
4979 if (!blame)
4980 return FALSE;
4982 blame->commit = NULL;
4983 strncpy(blame->text, line, linelen);
4984 blame->text[linelen] = 0;
4985 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4989 static bool
4990 blame_read(struct view *view, char *line)
4992 struct blame_state *state = view->private;
4994 if (!state->done_reading)
4995 return blame_read_file(view, line, state);
4997 if (!line) {
4998 state->auto_filename_display = blame_detect_filename_display(view);
4999 string_format(view->ref, "%s", view->vid);
5000 if (view_is_displayed(view)) {
5001 update_view_title(view);
5002 redraw_view_from(view, 0);
5004 return TRUE;
5007 if (!state->commit) {
5008 state->commit = read_blame_commit(view, line, state);
5009 string_format(view->ref, "%s %2d%%", view->vid,
5010 view->lines ? state->blamed * 100 / view->lines : 0);
5012 } else if (parse_blame_info(state->commit, line)) {
5013 state->commit = NULL;
5016 return TRUE;
5019 static bool
5020 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5022 struct blame_state *state = view->private;
5023 struct blame *blame = line->data;
5024 struct time *time = NULL;
5025 const char *id = NULL, *author = NULL, *filename = NULL;
5026 enum line_type id_type = LINE_BLAME_ID;
5027 static const enum line_type blame_colors[] = {
5028 LINE_PALETTE_0,
5029 LINE_PALETTE_1,
5030 LINE_PALETTE_2,
5031 LINE_PALETTE_3,
5032 LINE_PALETTE_4,
5033 LINE_PALETTE_5,
5034 LINE_PALETTE_6,
5037 #define BLAME_COLOR(i) \
5038 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5040 if (blame->commit && *blame->commit->filename) {
5041 id = blame->commit->id;
5042 author = blame->commit->author;
5043 filename = blame->commit->filename;
5044 time = &blame->commit->time;
5045 id_type = BLAME_COLOR((long) blame->commit);
5048 if (draw_date(view, time))
5049 return TRUE;
5051 if (draw_author(view, author))
5052 return TRUE;
5054 if (draw_filename(view, filename, state->auto_filename_display))
5055 return TRUE;
5057 if (draw_field(view, id_type, id, ID_COLS, FALSE))
5058 return TRUE;
5060 if (draw_lineno(view, lineno))
5061 return TRUE;
5063 draw_text(view, LINE_DEFAULT, blame->text);
5064 return TRUE;
5067 static bool
5068 check_blame_commit(struct blame *blame, bool check_null_id)
5070 if (!blame->commit)
5071 report("Commit data not loaded yet");
5072 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
5073 report("No commit exist for the selected line");
5074 else
5075 return TRUE;
5076 return FALSE;
5079 static void
5080 setup_blame_parent_line(struct view *view, struct blame *blame)
5082 char from[SIZEOF_REF + SIZEOF_STR];
5083 char to[SIZEOF_REF + SIZEOF_STR];
5084 const char *diff_tree_argv[] = {
5085 "git", "diff", ENCODING_ARG, "--no-textconv", "--no-extdiff",
5086 "--no-color", "-U0", from, to, "--", NULL
5088 struct io io;
5089 int parent_lineno = -1;
5090 int blamed_lineno = -1;
5091 char *line;
5093 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5094 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5095 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5096 return;
5098 while ((line = io_get(&io, '\n', TRUE))) {
5099 if (*line == '@') {
5100 char *pos = strchr(line, '+');
5102 parent_lineno = atoi(line + 4);
5103 if (pos)
5104 blamed_lineno = atoi(pos + 1);
5106 } else if (*line == '+' && parent_lineno != -1) {
5107 if (blame->lineno == blamed_lineno - 1 &&
5108 !strcmp(blame->text, line + 1)) {
5109 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
5110 break;
5112 blamed_lineno++;
5116 io_done(&io);
5119 static enum request
5120 blame_request(struct view *view, enum request request, struct line *line)
5122 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5123 struct blame *blame = line->data;
5125 switch (request) {
5126 case REQ_VIEW_BLAME:
5127 if (check_blame_commit(blame, TRUE)) {
5128 string_copy(opt_ref, blame->commit->id);
5129 string_copy(opt_file, blame->commit->filename);
5130 if (blame->lineno)
5131 view->lineno = blame->lineno;
5132 reload_view(view);
5134 break;
5136 case REQ_PARENT:
5137 if (!check_blame_commit(blame, TRUE))
5138 break;
5139 if (!*blame->commit->parent_id) {
5140 report("The selected commit has no parents");
5141 } else {
5142 string_copy_rev(opt_ref, blame->commit->parent_id);
5143 string_copy(opt_file, blame->commit->parent_filename);
5144 setup_blame_parent_line(view, blame);
5145 opt_goto_line = blame->lineno;
5146 reload_view(view);
5148 break;
5150 case REQ_ENTER:
5151 if (!check_blame_commit(blame, FALSE))
5152 break;
5154 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5155 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5156 break;
5158 if (!strcmp(blame->commit->id, NULL_ID)) {
5159 struct view *diff = VIEW(REQ_VIEW_DIFF);
5160 const char *diff_index_argv[] = {
5161 "git", "diff-index", ENCODING_ARG, "--root",
5162 "--patch-with-stat",
5163 "-C", "-M", opt_diff_context_arg,
5164 opt_ignore_space_arg,
5165 "HEAD", "--", view->vid, NULL
5168 if (!*blame->commit->parent_id) {
5169 diff_index_argv[1] = "diff";
5170 diff_index_argv[2] = "--no-color";
5171 diff_index_argv[8] = "--";
5172 diff_index_argv[9] = "/dev/null";
5175 open_argv(view, diff, diff_index_argv, NULL, flags);
5176 if (diff->pipe)
5177 string_copy_rev(diff->ref, NULL_ID);
5178 } else {
5179 open_view(view, REQ_VIEW_DIFF, flags);
5181 break;
5183 default:
5184 return request;
5187 return REQ_NONE;
5190 static bool
5191 blame_grep(struct view *view, struct line *line)
5193 struct blame *blame = line->data;
5194 struct blame_commit *commit = blame->commit;
5195 const char *text[] = {
5196 blame->text,
5197 commit ? commit->title : "",
5198 commit ? commit->id : "",
5199 commit && opt_author ? commit->author : "",
5200 commit ? mkdate(&commit->time, opt_date) : "",
5201 NULL
5204 return grep_text(view, text);
5207 static void
5208 blame_select(struct view *view, struct line *line)
5210 struct blame *blame = line->data;
5211 struct blame_commit *commit = blame->commit;
5213 if (!commit)
5214 return;
5216 if (!strcmp(commit->id, NULL_ID))
5217 string_ncopy(ref_commit, "HEAD", 4);
5218 else
5219 string_copy_rev(ref_commit, commit->id);
5222 static struct view_ops blame_ops = {
5223 "line",
5224 VIEW_ALWAYS_LINENO,
5225 sizeof(struct blame_state),
5226 blame_open,
5227 blame_read,
5228 blame_draw,
5229 blame_request,
5230 blame_grep,
5231 blame_select,
5235 * Branch backend
5238 struct branch {
5239 const char *author; /* Author of the last commit. */
5240 struct time time; /* Date of the last activity. */
5241 const struct ref *ref; /* Name and commit ID information. */
5244 static const struct ref branch_all;
5246 static const enum sort_field branch_sort_fields[] = {
5247 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5249 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5251 struct branch_state {
5252 char id[SIZEOF_REV];
5255 static int
5256 branch_compare(const void *l1, const void *l2)
5258 const struct branch *branch1 = ((const struct line *) l1)->data;
5259 const struct branch *branch2 = ((const struct line *) l2)->data;
5261 if (branch1->ref == &branch_all)
5262 return -1;
5263 else if (branch2->ref == &branch_all)
5264 return 1;
5266 switch (get_sort_field(branch_sort_state)) {
5267 case ORDERBY_DATE:
5268 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5270 case ORDERBY_AUTHOR:
5271 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5273 case ORDERBY_NAME:
5274 default:
5275 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5279 static bool
5280 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5282 struct branch *branch = line->data;
5283 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5285 if (draw_date(view, &branch->time))
5286 return TRUE;
5288 if (draw_author(view, branch->author))
5289 return TRUE;
5291 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
5292 return TRUE;
5295 static enum request
5296 branch_request(struct view *view, enum request request, struct line *line)
5298 struct branch *branch = line->data;
5300 switch (request) {
5301 case REQ_REFRESH:
5302 load_refs();
5303 refresh_view(view);
5304 return REQ_NONE;
5306 case REQ_TOGGLE_SORT_FIELD:
5307 case REQ_TOGGLE_SORT_ORDER:
5308 sort_view(view, request, &branch_sort_state, branch_compare);
5309 return REQ_NONE;
5311 case REQ_ENTER:
5313 const struct ref *ref = branch->ref;
5314 const char *all_branches_argv[] = {
5315 "git", "log", ENCODING_ARG, "--no-color",
5316 "--pretty=raw", "--parents", "--topo-order",
5317 ref == &branch_all ? "--all" : ref->name, NULL
5319 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5321 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5322 return REQ_NONE;
5324 case REQ_JUMP_COMMIT:
5326 int lineno;
5328 for (lineno = 0; lineno < view->lines; lineno++) {
5329 struct branch *branch = view->line[lineno].data;
5331 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5332 select_view_line(view, lineno);
5333 report("");
5334 return REQ_NONE;
5338 default:
5339 return request;
5343 static bool
5344 branch_read(struct view *view, char *line)
5346 struct branch_state *state = view->private;
5347 struct branch *reference;
5348 size_t i;
5350 if (!line)
5351 return TRUE;
5353 switch (get_line_type(line)) {
5354 case LINE_COMMIT:
5355 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5356 return TRUE;
5358 case LINE_AUTHOR:
5359 for (i = 0, reference = NULL; i < view->lines; i++) {
5360 struct branch *branch = view->line[i].data;
5362 if (strcmp(branch->ref->id, state->id))
5363 continue;
5365 view->line[i].dirty = TRUE;
5366 if (reference) {
5367 branch->author = reference->author;
5368 branch->time = reference->time;
5369 continue;
5372 parse_author_line(line + STRING_SIZE("author "),
5373 &branch->author, &branch->time);
5374 reference = branch;
5376 return TRUE;
5378 default:
5379 return TRUE;
5384 static bool
5385 branch_open_visitor(void *data, const struct ref *ref)
5387 struct view *view = data;
5388 struct branch *branch;
5390 if (ref->tag || ref->ltag)
5391 return TRUE;
5393 branch = calloc(1, sizeof(*branch));
5394 if (!branch)
5395 return FALSE;
5397 branch->ref = ref;
5398 return !!add_line_data(view, branch, LINE_DEFAULT);
5401 static bool
5402 branch_open(struct view *view, enum open_flags flags)
5404 const char *branch_log[] = {
5405 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
5406 "--simplify-by-decoration", "--all", NULL
5409 if (!begin_update(view, NULL, branch_log, flags)) {
5410 report("Failed to load branch data");
5411 return TRUE;
5414 branch_open_visitor(view, &branch_all);
5415 foreach_ref(branch_open_visitor, view);
5416 view->p_restore = TRUE;
5418 return TRUE;
5421 static bool
5422 branch_grep(struct view *view, struct line *line)
5424 struct branch *branch = line->data;
5425 const char *text[] = {
5426 branch->ref->name,
5427 mkauthor(branch->author, opt_author_cols, opt_author),
5428 NULL
5431 return grep_text(view, text);
5434 static void
5435 branch_select(struct view *view, struct line *line)
5437 struct branch *branch = line->data;
5439 string_copy_rev(view->ref, branch->ref->id);
5440 string_copy_rev(ref_commit, branch->ref->id);
5441 string_copy_rev(ref_head, branch->ref->id);
5442 string_copy_rev(ref_branch, branch->ref->name);
5445 static struct view_ops branch_ops = {
5446 "branch",
5447 VIEW_NO_FLAGS,
5448 sizeof(struct branch_state),
5449 branch_open,
5450 branch_read,
5451 branch_draw,
5452 branch_request,
5453 branch_grep,
5454 branch_select,
5458 * Status backend
5461 struct status {
5462 char status;
5463 struct {
5464 mode_t mode;
5465 char rev[SIZEOF_REV];
5466 char name[SIZEOF_STR];
5467 } old;
5468 struct {
5469 mode_t mode;
5470 char rev[SIZEOF_REV];
5471 char name[SIZEOF_STR];
5472 } new;
5475 static char status_onbranch[SIZEOF_STR];
5476 static struct status stage_status;
5477 static enum line_type stage_line_type;
5479 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5481 /* This should work even for the "On branch" line. */
5482 static inline bool
5483 status_has_none(struct view *view, struct line *line)
5485 return line < view->line + view->lines && !line[1].data;
5488 /* Get fields from the diff line:
5489 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5491 static inline bool
5492 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5494 const char *old_mode = buf + 1;
5495 const char *new_mode = buf + 8;
5496 const char *old_rev = buf + 15;
5497 const char *new_rev = buf + 56;
5498 const char *status = buf + 97;
5500 if (bufsize < 98 ||
5501 old_mode[-1] != ':' ||
5502 new_mode[-1] != ' ' ||
5503 old_rev[-1] != ' ' ||
5504 new_rev[-1] != ' ' ||
5505 status[-1] != ' ')
5506 return FALSE;
5508 file->status = *status;
5510 string_copy_rev(file->old.rev, old_rev);
5511 string_copy_rev(file->new.rev, new_rev);
5513 file->old.mode = strtoul(old_mode, NULL, 8);
5514 file->new.mode = strtoul(new_mode, NULL, 8);
5516 file->old.name[0] = file->new.name[0] = 0;
5518 return TRUE;
5521 static bool
5522 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5524 struct status *unmerged = NULL;
5525 char *buf;
5526 struct io io;
5528 if (!io_run(&io, IO_RD, opt_cdup, argv))
5529 return FALSE;
5531 add_line_data(view, NULL, type);
5533 while ((buf = io_get(&io, 0, TRUE))) {
5534 struct status *file = unmerged;
5536 if (!file) {
5537 file = calloc(1, sizeof(*file));
5538 if (!file || !add_line_data(view, file, type))
5539 goto error_out;
5542 /* Parse diff info part. */
5543 if (status) {
5544 file->status = status;
5545 if (status == 'A')
5546 string_copy(file->old.rev, NULL_ID);
5548 } else if (!file->status || file == unmerged) {
5549 if (!status_get_diff(file, buf, strlen(buf)))
5550 goto error_out;
5552 buf = io_get(&io, 0, TRUE);
5553 if (!buf)
5554 break;
5556 /* Collapse all modified entries that follow an
5557 * associated unmerged entry. */
5558 if (unmerged == file) {
5559 unmerged->status = 'U';
5560 unmerged = NULL;
5561 } else if (file->status == 'U') {
5562 unmerged = file;
5566 /* Grab the old name for rename/copy. */
5567 if (!*file->old.name &&
5568 (file->status == 'R' || file->status == 'C')) {
5569 string_ncopy(file->old.name, buf, strlen(buf));
5571 buf = io_get(&io, 0, TRUE);
5572 if (!buf)
5573 break;
5576 /* git-ls-files just delivers a NUL separated list of
5577 * file names similar to the second half of the
5578 * git-diff-* output. */
5579 string_ncopy(file->new.name, buf, strlen(buf));
5580 if (!*file->old.name)
5581 string_copy(file->old.name, file->new.name);
5582 file = NULL;
5585 if (io_error(&io)) {
5586 error_out:
5587 io_done(&io);
5588 return FALSE;
5591 if (!view->line[view->lines - 1].data)
5592 add_line_data(view, NULL, LINE_STAT_NONE);
5594 io_done(&io);
5595 return TRUE;
5598 /* Don't show unmerged entries in the staged section. */
5599 static const char *status_diff_index_argv[] = {
5600 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
5601 "--cached", "-M", "HEAD", NULL
5604 static const char *status_diff_files_argv[] = {
5605 "git", "diff-files", "-z", NULL
5608 static const char *status_list_other_argv[] = {
5609 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5612 static const char *status_list_no_head_argv[] = {
5613 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5616 static const char *update_index_argv[] = {
5617 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5620 /* Restore the previous line number to stay in the context or select a
5621 * line with something that can be updated. */
5622 static void
5623 status_restore(struct view *view)
5625 if (view->p_lineno >= view->lines)
5626 view->p_lineno = view->lines - 1;
5627 while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
5628 view->p_lineno++;
5629 while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
5630 view->p_lineno--;
5632 /* If the above fails, always skip the "On branch" line. */
5633 if (view->p_lineno < view->lines)
5634 view->lineno = view->p_lineno;
5635 else
5636 view->lineno = 1;
5638 if (view->lineno < view->offset)
5639 view->offset = view->lineno;
5640 else if (view->offset + view->height <= view->lineno)
5641 view->offset = view->lineno - view->height + 1;
5643 view->p_restore = FALSE;
5646 static void
5647 status_update_onbranch(void)
5649 static const char *paths[][2] = {
5650 { "rebase-apply/rebasing", "Rebasing" },
5651 { "rebase-apply/applying", "Applying mailbox" },
5652 { "rebase-apply/", "Rebasing mailbox" },
5653 { "rebase-merge/interactive", "Interactive rebase" },
5654 { "rebase-merge/", "Rebase merge" },
5655 { "MERGE_HEAD", "Merging" },
5656 { "BISECT_LOG", "Bisecting" },
5657 { "HEAD", "On branch" },
5659 char buf[SIZEOF_STR];
5660 struct stat stat;
5661 int i;
5663 if (is_initial_commit()) {
5664 string_copy(status_onbranch, "Initial commit");
5665 return;
5668 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5669 char *head = opt_head;
5671 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5672 lstat(buf, &stat) < 0)
5673 continue;
5675 if (!*opt_head) {
5676 struct io io;
5678 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5679 io_read_buf(&io, buf, sizeof(buf))) {
5680 head = buf;
5681 if (!prefixcmp(head, "refs/heads/"))
5682 head += STRING_SIZE("refs/heads/");
5686 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5687 string_copy(status_onbranch, opt_head);
5688 return;
5691 string_copy(status_onbranch, "Not currently on any branch");
5694 /* First parse staged info using git-diff-index(1), then parse unstaged
5695 * info using git-diff-files(1), and finally untracked files using
5696 * git-ls-files(1). */
5697 static bool
5698 status_open(struct view *view, enum open_flags flags)
5700 reset_view(view);
5702 add_line_data(view, NULL, LINE_STAT_HEAD);
5703 status_update_onbranch();
5705 io_run_bg(update_index_argv);
5707 if (is_initial_commit()) {
5708 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5709 return FALSE;
5710 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5711 return FALSE;
5714 if (!opt_untracked_dirs_content)
5715 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5717 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5718 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5719 return FALSE;
5721 /* Restore the exact position or use the specialized restore
5722 * mode? */
5723 if (!view->p_restore)
5724 status_restore(view);
5725 return TRUE;
5728 static bool
5729 status_draw(struct view *view, struct line *line, unsigned int lineno)
5731 struct status *status = line->data;
5732 enum line_type type;
5733 const char *text;
5735 if (!status) {
5736 switch (line->type) {
5737 case LINE_STAT_STAGED:
5738 type = LINE_STAT_SECTION;
5739 text = "Changes to be committed:";
5740 break;
5742 case LINE_STAT_UNSTAGED:
5743 type = LINE_STAT_SECTION;
5744 text = "Changed but not updated:";
5745 break;
5747 case LINE_STAT_UNTRACKED:
5748 type = LINE_STAT_SECTION;
5749 text = "Untracked files:";
5750 break;
5752 case LINE_STAT_NONE:
5753 type = LINE_DEFAULT;
5754 text = " (no files)";
5755 break;
5757 case LINE_STAT_HEAD:
5758 type = LINE_STAT_HEAD;
5759 text = status_onbranch;
5760 break;
5762 default:
5763 return FALSE;
5765 } else {
5766 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5768 buf[0] = status->status;
5769 if (draw_text(view, line->type, buf))
5770 return TRUE;
5771 type = LINE_DEFAULT;
5772 text = status->new.name;
5775 draw_text(view, type, text);
5776 return TRUE;
5779 static enum request
5780 status_enter(struct view *view, struct line *line)
5782 struct status *status = line->data;
5783 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5785 if (line->type == LINE_STAT_NONE ||
5786 (!status && line[1].type == LINE_STAT_NONE)) {
5787 report("No file to diff");
5788 return REQ_NONE;
5791 switch (line->type) {
5792 case LINE_STAT_STAGED:
5793 case LINE_STAT_UNSTAGED:
5794 break;
5796 case LINE_STAT_UNTRACKED:
5797 if (!status) {
5798 report("No file to show");
5799 return REQ_NONE;
5802 if (!suffixcmp(status->new.name, -1, "/")) {
5803 report("Cannot display a directory");
5804 return REQ_NONE;
5806 break;
5808 case LINE_STAT_HEAD:
5809 return REQ_NONE;
5811 default:
5812 die("line type %d not handled in switch", line->type);
5815 if (status) {
5816 stage_status = *status;
5817 } else {
5818 memset(&stage_status, 0, sizeof(stage_status));
5821 stage_line_type = line->type;
5823 open_view(view, REQ_VIEW_STAGE, flags);
5824 return REQ_NONE;
5827 static bool
5828 status_exists(struct view *view, struct status *status, enum line_type type)
5830 unsigned long lineno;
5832 for (lineno = 0; lineno < view->lines; lineno++) {
5833 struct line *line = &view->line[lineno];
5834 struct status *pos = line->data;
5836 if (line->type != type)
5837 continue;
5838 if (!pos && (!status || !status->status) && line[1].data) {
5839 select_view_line(view, lineno);
5840 return TRUE;
5842 if (pos && !strcmp(status->new.name, pos->new.name)) {
5843 select_view_line(view, lineno);
5844 return TRUE;
5848 return FALSE;
5852 static bool
5853 status_update_prepare(struct io *io, enum line_type type)
5855 const char *staged_argv[] = {
5856 "git", "update-index", "-z", "--index-info", NULL
5858 const char *others_argv[] = {
5859 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5862 switch (type) {
5863 case LINE_STAT_STAGED:
5864 return io_run(io, IO_WR, opt_cdup, staged_argv);
5866 case LINE_STAT_UNSTAGED:
5867 case LINE_STAT_UNTRACKED:
5868 return io_run(io, IO_WR, opt_cdup, others_argv);
5870 default:
5871 die("line type %d not handled in switch", type);
5872 return FALSE;
5876 static bool
5877 status_update_write(struct io *io, struct status *status, enum line_type type)
5879 switch (type) {
5880 case LINE_STAT_STAGED:
5881 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
5882 status->old.rev, status->old.name, 0);
5884 case LINE_STAT_UNSTAGED:
5885 case LINE_STAT_UNTRACKED:
5886 return io_printf(io, "%s%c", status->new.name, 0);
5888 default:
5889 die("line type %d not handled in switch", type);
5890 return FALSE;
5894 static bool
5895 status_update_file(struct status *status, enum line_type type)
5897 struct io io;
5898 bool result;
5900 if (!status_update_prepare(&io, type))
5901 return FALSE;
5903 result = status_update_write(&io, status, type);
5904 return io_done(&io) && result;
5907 static bool
5908 status_update_files(struct view *view, struct line *line)
5910 char buf[sizeof(view->ref)];
5911 struct io io;
5912 bool result = TRUE;
5913 struct line *pos = view->line + view->lines;
5914 int files = 0;
5915 int file, done;
5916 int cursor_y = -1, cursor_x = -1;
5918 if (!status_update_prepare(&io, line->type))
5919 return FALSE;
5921 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5922 files++;
5924 string_copy(buf, view->ref);
5925 getsyx(cursor_y, cursor_x);
5926 for (file = 0, done = 5; result && file < files; line++, file++) {
5927 int almost_done = file * 100 / files;
5929 if (almost_done > done) {
5930 done = almost_done;
5931 string_format(view->ref, "updating file %u of %u (%d%% done)",
5932 file, files, done);
5933 update_view_title(view);
5934 setsyx(cursor_y, cursor_x);
5935 doupdate();
5937 result = status_update_write(&io, line->data, line->type);
5939 string_copy(view->ref, buf);
5941 return io_done(&io) && result;
5944 static bool
5945 status_update(struct view *view)
5947 struct line *line = &view->line[view->lineno];
5949 assert(view->lines);
5951 if (!line->data) {
5952 /* This should work even for the "On branch" line. */
5953 if (line < view->line + view->lines && !line[1].data) {
5954 report("Nothing to update");
5955 return FALSE;
5958 if (!status_update_files(view, line + 1)) {
5959 report("Failed to update file status");
5960 return FALSE;
5963 } else if (!status_update_file(line->data, line->type)) {
5964 report("Failed to update file status");
5965 return FALSE;
5968 return TRUE;
5971 static bool
5972 status_revert(struct status *status, enum line_type type, bool has_none)
5974 if (!status || type != LINE_STAT_UNSTAGED) {
5975 if (type == LINE_STAT_STAGED) {
5976 report("Cannot revert changes to staged files");
5977 } else if (type == LINE_STAT_UNTRACKED) {
5978 report("Cannot revert changes to untracked files");
5979 } else if (has_none) {
5980 report("Nothing to revert");
5981 } else {
5982 report("Cannot revert changes to multiple files");
5985 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5986 char mode[10] = "100644";
5987 const char *reset_argv[] = {
5988 "git", "update-index", "--cacheinfo", mode,
5989 status->old.rev, status->old.name, NULL
5991 const char *checkout_argv[] = {
5992 "git", "checkout", "--", status->old.name, NULL
5995 if (status->status == 'U') {
5996 string_format(mode, "%5o", status->old.mode);
5998 if (status->old.mode == 0 && status->new.mode == 0) {
5999 reset_argv[2] = "--force-remove";
6000 reset_argv[3] = status->old.name;
6001 reset_argv[4] = NULL;
6004 if (!io_run_fg(reset_argv, opt_cdup))
6005 return FALSE;
6006 if (status->old.mode == 0 && status->new.mode == 0)
6007 return TRUE;
6010 return io_run_fg(checkout_argv, opt_cdup);
6013 return FALSE;
6016 static enum request
6017 status_request(struct view *view, enum request request, struct line *line)
6019 struct status *status = line->data;
6021 switch (request) {
6022 case REQ_STATUS_UPDATE:
6023 if (!status_update(view))
6024 return REQ_NONE;
6025 break;
6027 case REQ_STATUS_REVERT:
6028 if (!status_revert(status, line->type, status_has_none(view, line)))
6029 return REQ_NONE;
6030 break;
6032 case REQ_STATUS_MERGE:
6033 if (!status || status->status != 'U') {
6034 report("Merging only possible for files with unmerged status ('U').");
6035 return REQ_NONE;
6037 open_mergetool(status->new.name);
6038 break;
6040 case REQ_EDIT:
6041 if (!status)
6042 return request;
6043 if (status->status == 'D') {
6044 report("File has been deleted.");
6045 return REQ_NONE;
6048 open_editor(status->new.name);
6049 break;
6051 case REQ_VIEW_BLAME:
6052 if (status)
6053 opt_ref[0] = 0;
6054 return request;
6056 case REQ_ENTER:
6057 /* After returning the status view has been split to
6058 * show the stage view. No further reloading is
6059 * necessary. */
6060 return status_enter(view, line);
6062 case REQ_REFRESH:
6063 /* Simply reload the view. */
6064 break;
6066 default:
6067 return request;
6070 refresh_view(view);
6072 return REQ_NONE;
6075 static void
6076 status_select(struct view *view, struct line *line)
6078 struct status *status = line->data;
6079 char file[SIZEOF_STR] = "all files";
6080 const char *text;
6081 const char *key;
6083 if (status && !string_format(file, "'%s'", status->new.name))
6084 return;
6086 if (!status && line[1].type == LINE_STAT_NONE)
6087 line++;
6089 switch (line->type) {
6090 case LINE_STAT_STAGED:
6091 text = "Press %s to unstage %s for commit";
6092 break;
6094 case LINE_STAT_UNSTAGED:
6095 text = "Press %s to stage %s for commit";
6096 break;
6098 case LINE_STAT_UNTRACKED:
6099 text = "Press %s to stage %s for addition";
6100 break;
6102 case LINE_STAT_HEAD:
6103 case LINE_STAT_NONE:
6104 text = "Nothing to update";
6105 break;
6107 default:
6108 die("line type %d not handled in switch", line->type);
6111 if (status && status->status == 'U') {
6112 text = "Press %s to resolve conflict in %s";
6113 key = get_view_key(view, REQ_STATUS_MERGE);
6115 } else {
6116 key = get_view_key(view, REQ_STATUS_UPDATE);
6119 string_format(view->ref, text, key, file);
6120 if (status)
6121 string_copy(opt_file, status->new.name);
6124 static bool
6125 status_grep(struct view *view, struct line *line)
6127 struct status *status = line->data;
6129 if (status) {
6130 const char buf[2] = { status->status, 0 };
6131 const char *text[] = { status->new.name, buf, NULL };
6133 return grep_text(view, text);
6136 return FALSE;
6139 static struct view_ops status_ops = {
6140 "file",
6141 VIEW_CUSTOM_STATUS,
6143 status_open,
6144 NULL,
6145 status_draw,
6146 status_request,
6147 status_grep,
6148 status_select,
6152 struct stage_state {
6153 struct diff_state diff;
6154 size_t chunks;
6155 int *chunk;
6158 static bool
6159 stage_diff_write(struct io *io, struct line *line, struct line *end)
6161 while (line < end) {
6162 if (!io_write(io, line->data, strlen(line->data)) ||
6163 !io_write(io, "\n", 1))
6164 return FALSE;
6165 line++;
6166 if (line->type == LINE_DIFF_CHUNK ||
6167 line->type == LINE_DIFF_HEADER)
6168 break;
6171 return TRUE;
6174 static bool
6175 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6177 const char *apply_argv[SIZEOF_ARG] = {
6178 "git", "apply", "--whitespace=nowarn", NULL
6180 struct line *diff_hdr;
6181 struct io io;
6182 int argc = 3;
6184 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6185 if (!diff_hdr)
6186 return FALSE;
6188 if (!revert)
6189 apply_argv[argc++] = "--cached";
6190 if (line != NULL)
6191 apply_argv[argc++] = "--unidiff-zero";
6192 if (revert || stage_line_type == LINE_STAT_STAGED)
6193 apply_argv[argc++] = "-R";
6194 apply_argv[argc++] = "-";
6195 apply_argv[argc++] = NULL;
6196 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6197 return FALSE;
6199 if (line != NULL) {
6200 int lineno = 0;
6201 struct line *context = chunk + 1;
6202 const char *markers[] = {
6203 line->type == LINE_DIFF_DEL ? "" : ",0",
6204 line->type == LINE_DIFF_DEL ? ",0" : "",
6207 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6209 while (context < line) {
6210 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6211 break;
6212 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6213 lineno++;
6215 context++;
6218 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6219 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6220 lineno, markers[0], lineno, markers[1]) ||
6221 !stage_diff_write(&io, line, line + 1)) {
6222 chunk = NULL;
6224 } else {
6225 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6226 !stage_diff_write(&io, chunk, view->line + view->lines))
6227 chunk = NULL;
6230 io_done(&io);
6231 io_run_bg(update_index_argv);
6233 return chunk ? TRUE : FALSE;
6236 static bool
6237 stage_update(struct view *view, struct line *line, bool single)
6239 struct line *chunk = NULL;
6241 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6242 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6244 if (chunk) {
6245 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6246 report("Failed to apply chunk");
6247 return FALSE;
6250 } else if (!stage_status.status) {
6251 view = view->parent;
6253 for (line = view->line; line < view->line + view->lines; line++)
6254 if (line->type == stage_line_type)
6255 break;
6257 if (!status_update_files(view, line + 1)) {
6258 report("Failed to update files");
6259 return FALSE;
6262 } else if (!status_update_file(&stage_status, stage_line_type)) {
6263 report("Failed to update file");
6264 return FALSE;
6267 return TRUE;
6270 static bool
6271 stage_revert(struct view *view, struct line *line)
6273 struct line *chunk = NULL;
6275 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6276 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6278 if (chunk) {
6279 if (!prompt_yesno("Are you sure you want to revert changes?"))
6280 return FALSE;
6282 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6283 report("Failed to revert chunk");
6284 return FALSE;
6286 return TRUE;
6288 } else {
6289 return status_revert(stage_status.status ? &stage_status : NULL,
6290 stage_line_type, FALSE);
6295 static void
6296 stage_next(struct view *view, struct line *line)
6298 struct stage_state *state = view->private;
6299 int i;
6301 if (!state->chunks) {
6302 for (line = view->line; line < view->line + view->lines; line++) {
6303 if (line->type != LINE_DIFF_CHUNK)
6304 continue;
6306 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6307 report("Allocation failure");
6308 return;
6311 state->chunk[state->chunks++] = line - view->line;
6315 for (i = 0; i < state->chunks; i++) {
6316 if (state->chunk[i] > view->lineno) {
6317 do_scroll_view(view, state->chunk[i] - view->lineno);
6318 report("Chunk %d of %d", i + 1, state->chunks);
6319 return;
6323 report("No next chunk found");
6326 static enum request
6327 stage_request(struct view *view, enum request request, struct line *line)
6329 switch (request) {
6330 case REQ_STATUS_UPDATE:
6331 if (!stage_update(view, line, FALSE))
6332 return REQ_NONE;
6333 break;
6335 case REQ_STATUS_REVERT:
6336 if (!stage_revert(view, line))
6337 return REQ_NONE;
6338 break;
6340 case REQ_STAGE_UPDATE_LINE:
6341 if (stage_line_type == LINE_STAT_UNTRACKED ||
6342 stage_status.status == 'A') {
6343 report("Staging single lines is not supported for new files");
6344 return REQ_NONE;
6346 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6347 report("Please select a change to stage");
6348 return REQ_NONE;
6350 if (!stage_update(view, line, TRUE))
6351 return REQ_NONE;
6352 break;
6354 case REQ_STAGE_NEXT:
6355 if (stage_line_type == LINE_STAT_UNTRACKED) {
6356 report("File is untracked; press %s to add",
6357 get_view_key(view, REQ_STATUS_UPDATE));
6358 return REQ_NONE;
6360 stage_next(view, line);
6361 return REQ_NONE;
6363 case REQ_EDIT:
6364 if (!stage_status.new.name[0])
6365 return request;
6366 if (stage_status.status == 'D') {
6367 report("File has been deleted.");
6368 return REQ_NONE;
6371 open_editor(stage_status.new.name);
6372 break;
6374 case REQ_REFRESH:
6375 /* Reload everything ... */
6376 break;
6378 case REQ_VIEW_BLAME:
6379 if (stage_status.new.name[0]) {
6380 string_copy(opt_file, stage_status.new.name);
6381 opt_ref[0] = 0;
6383 return request;
6385 case REQ_ENTER:
6386 return diff_common_enter(view, request, line);
6388 case REQ_DIFF_CONTEXT_UP:
6389 case REQ_DIFF_CONTEXT_DOWN:
6390 if (!update_diff_context(request))
6391 return REQ_NONE;
6392 break;
6394 default:
6395 return request;
6398 refresh_view(view->parent);
6400 /* Check whether the staged entry still exists, and close the
6401 * stage view if it doesn't. */
6402 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6403 status_restore(view->parent);
6404 return REQ_VIEW_CLOSE;
6407 refresh_view(view);
6409 return REQ_NONE;
6412 static bool
6413 stage_open(struct view *view, enum open_flags flags)
6415 static const char *no_head_diff_argv[] = {
6416 "git", "diff", ENCODING_ARG, "--no-color", "--patch-with-stat",
6417 opt_diff_context_arg, opt_ignore_space_arg,
6418 "--", "/dev/null", stage_status.new.name, NULL
6420 static const char *index_show_argv[] = {
6421 "git", "diff-index", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6422 "--cached", opt_diff_context_arg, opt_ignore_space_arg,
6423 "HEAD", "--",
6424 stage_status.old.name, stage_status.new.name, NULL
6426 static const char *files_show_argv[] = {
6427 "git", "diff-files", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6428 opt_diff_context_arg, opt_ignore_space_arg, "--",
6429 stage_status.old.name, stage_status.new.name, NULL
6431 /* Diffs for unmerged entries are empty when passing the new
6432 * path, so leave out the new path. */
6433 static const char *files_unmerged_argv[] = {
6434 "git", "diff-files", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6435 opt_diff_context_arg, opt_ignore_space_arg, "--",
6436 stage_status.old.name, NULL
6438 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6439 const char **argv = NULL;
6440 const char *info;
6442 view->encoding = NULL;
6444 switch (stage_line_type) {
6445 case LINE_STAT_STAGED:
6446 if (is_initial_commit()) {
6447 argv = no_head_diff_argv;
6448 } else {
6449 argv = index_show_argv;
6451 if (stage_status.status)
6452 info = "Staged changes to %s";
6453 else
6454 info = "Staged changes";
6455 break;
6457 case LINE_STAT_UNSTAGED:
6458 if (stage_status.status != 'U')
6459 argv = files_show_argv;
6460 else
6461 argv = files_unmerged_argv;
6462 if (stage_status.status)
6463 info = "Unstaged changes to %s";
6464 else
6465 info = "Unstaged changes";
6466 break;
6468 case LINE_STAT_UNTRACKED:
6469 info = "Untracked file %s";
6470 argv = file_argv;
6471 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
6472 break;
6474 case LINE_STAT_HEAD:
6475 default:
6476 die("line type %d not handled in switch", stage_line_type);
6479 string_format(view->ref, info, stage_status.new.name);
6480 view->vid[0] = 0;
6481 view->dir = opt_cdup;
6482 return argv_copy(&view->argv, argv)
6483 && begin_update(view, NULL, NULL, flags);
6486 static bool
6487 stage_read(struct view *view, char *data)
6489 struct stage_state *state = view->private;
6491 if (data && diff_common_read(view, data, &state->diff))
6492 return TRUE;
6494 return pager_read(view, data);
6497 static struct view_ops stage_ops = {
6498 "line",
6499 VIEW_DIFF_LIKE,
6500 sizeof(struct stage_state),
6501 stage_open,
6502 stage_read,
6503 diff_common_draw,
6504 stage_request,
6505 pager_grep,
6506 pager_select,
6511 * Revision graph
6514 static const enum line_type graph_colors[] = {
6515 LINE_PALETTE_0,
6516 LINE_PALETTE_1,
6517 LINE_PALETTE_2,
6518 LINE_PALETTE_3,
6519 LINE_PALETTE_4,
6520 LINE_PALETTE_5,
6521 LINE_PALETTE_6,
6524 static enum line_type get_graph_color(struct graph_symbol *symbol)
6526 if (symbol->commit)
6527 return LINE_GRAPH_COMMIT;
6528 assert(symbol->color < ARRAY_SIZE(graph_colors));
6529 return graph_colors[symbol->color];
6532 static bool
6533 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6535 const char *chars = graph_symbol_to_utf8(symbol);
6537 return draw_text(view, color, chars + !!first);
6540 static bool
6541 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6543 const char *chars = graph_symbol_to_ascii(symbol);
6545 return draw_text(view, color, chars + !!first);
6548 static bool
6549 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6551 const chtype *chars = graph_symbol_to_chtype(symbol);
6553 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6556 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6558 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6560 static const draw_graph_fn fns[] = {
6561 draw_graph_ascii,
6562 draw_graph_chtype,
6563 draw_graph_utf8
6565 draw_graph_fn fn = fns[opt_line_graphics];
6566 int i;
6568 for (i = 0; i < canvas->size; i++) {
6569 struct graph_symbol *symbol = &canvas->symbols[i];
6570 enum line_type color = get_graph_color(symbol);
6572 if (fn(view, symbol, color, i == 0))
6573 return TRUE;
6576 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6580 * Main view backend
6583 struct commit {
6584 char id[SIZEOF_REV]; /* SHA1 ID. */
6585 char title[128]; /* First line of the commit message. */
6586 const char *author; /* Author of the commit. */
6587 struct time time; /* Date from the author ident. */
6588 struct ref_list *refs; /* Repository references. */
6589 struct graph_canvas graph; /* Ancestry chain graphics. */
6592 static bool
6593 main_open(struct view *view, enum open_flags flags)
6595 static const char *main_argv[] = {
6596 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw", "--parents",
6597 "--topo-order", "%(diffargs)", "%(revargs)",
6598 "--", "%(fileargs)", NULL
6601 return begin_update(view, NULL, main_argv, flags);
6604 static bool
6605 main_draw(struct view *view, struct line *line, unsigned int lineno)
6607 struct commit *commit = line->data;
6609 if (!commit->author)
6610 return FALSE;
6612 if (draw_lineno(view, lineno))
6613 return TRUE;
6615 if (draw_date(view, &commit->time))
6616 return TRUE;
6618 if (draw_author(view, commit->author))
6619 return TRUE;
6621 if (opt_rev_graph && draw_graph(view, &commit->graph))
6622 return TRUE;
6624 if (draw_refs(view, commit->refs))
6625 return TRUE;
6627 draw_text(view, LINE_DEFAULT, commit->title);
6628 return TRUE;
6631 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6632 static bool
6633 main_read(struct view *view, char *line)
6635 struct graph *graph = view->private;
6636 enum line_type type;
6637 struct commit *commit;
6639 if (!line) {
6640 if (!view->lines && !view->prev)
6641 die("No revisions match the given arguments.");
6642 if (view->lines > 0) {
6643 commit = view->line[view->lines - 1].data;
6644 view->line[view->lines - 1].dirty = 1;
6645 if (!commit->author) {
6646 view->lines--;
6647 free(commit);
6651 done_graph(graph);
6652 return TRUE;
6655 type = get_line_type(line);
6656 if (type == LINE_COMMIT) {
6657 bool is_boundary;
6659 commit = calloc(1, sizeof(struct commit));
6660 if (!commit)
6661 return FALSE;
6663 line += STRING_SIZE("commit ");
6664 is_boundary = *line == '-';
6665 if (is_boundary)
6666 line++;
6668 string_copy_rev(commit->id, line);
6669 commit->refs = get_ref_list(commit->id);
6670 add_line_data(view, commit, LINE_MAIN_COMMIT);
6671 graph_add_commit(graph, &commit->graph, commit->id, line, is_boundary);
6672 return TRUE;
6675 if (!view->lines)
6676 return TRUE;
6677 commit = view->line[view->lines - 1].data;
6679 switch (type) {
6680 case LINE_PARENT:
6681 if (!graph->has_parents)
6682 graph_add_parent(graph, line + STRING_SIZE("parent "));
6683 break;
6685 case LINE_AUTHOR:
6686 parse_author_line(line + STRING_SIZE("author "),
6687 &commit->author, &commit->time);
6688 graph_render_parents(graph);
6689 break;
6691 default:
6692 /* Fill in the commit title if it has not already been set. */
6693 if (commit->title[0])
6694 break;
6696 /* Require titles to start with a non-space character at the
6697 * offset used by git log. */
6698 if (strncmp(line, " ", 4))
6699 break;
6700 line += 4;
6701 /* Well, if the title starts with a whitespace character,
6702 * try to be forgiving. Otherwise we end up with no title. */
6703 while (isspace(*line))
6704 line++;
6705 if (*line == '\0')
6706 break;
6707 /* FIXME: More graceful handling of titles; append "..." to
6708 * shortened titles, etc. */
6710 string_expand(commit->title, sizeof(commit->title), line, 1);
6711 view->line[view->lines - 1].dirty = 1;
6714 return TRUE;
6717 static enum request
6718 main_request(struct view *view, enum request request, struct line *line)
6720 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6722 switch (request) {
6723 case REQ_ENTER:
6724 if (view_is_displayed(view) && display[0] != view)
6725 maximize_view(view, TRUE);
6726 open_view(view, REQ_VIEW_DIFF, flags);
6727 break;
6728 case REQ_REFRESH:
6729 load_refs();
6730 refresh_view(view);
6731 break;
6733 case REQ_JUMP_COMMIT:
6735 int lineno;
6737 for (lineno = 0; lineno < view->lines; lineno++) {
6738 struct commit *commit = view->line[lineno].data;
6740 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
6741 select_view_line(view, lineno);
6742 report("");
6743 return REQ_NONE;
6747 report("Unable to find commit '%s'", opt_search);
6748 break;
6750 default:
6751 return request;
6754 return REQ_NONE;
6757 static bool
6758 grep_refs(struct ref_list *list, regex_t *regex)
6760 regmatch_t pmatch;
6761 size_t i;
6763 if (!opt_show_refs || !list)
6764 return FALSE;
6766 for (i = 0; i < list->size; i++) {
6767 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
6768 return TRUE;
6771 return FALSE;
6774 static bool
6775 main_grep(struct view *view, struct line *line)
6777 struct commit *commit = line->data;
6778 const char *text[] = {
6779 commit->title,
6780 mkauthor(commit->author, opt_author_cols, opt_author),
6781 mkdate(&commit->time, opt_date),
6782 NULL
6785 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
6788 static void
6789 main_select(struct view *view, struct line *line)
6791 struct commit *commit = line->data;
6793 string_copy_rev(view->ref, commit->id);
6794 string_copy_rev(ref_commit, view->ref);
6797 static struct view_ops main_ops = {
6798 "commit",
6799 VIEW_NO_FLAGS,
6800 sizeof(struct graph),
6801 main_open,
6802 main_read,
6803 main_draw,
6804 main_request,
6805 main_grep,
6806 main_select,
6811 * Status management
6814 /* Whether or not the curses interface has been initialized. */
6815 static bool cursed = FALSE;
6817 /* Terminal hacks and workarounds. */
6818 static bool use_scroll_redrawwin;
6819 static bool use_scroll_status_wclear;
6821 /* The status window is used for polling keystrokes. */
6822 static WINDOW *status_win;
6824 /* Reading from the prompt? */
6825 static bool input_mode = FALSE;
6827 static bool status_empty = FALSE;
6829 /* Update status and title window. */
6830 static void
6831 report(const char *msg, ...)
6833 struct view *view = display[current_view];
6835 if (input_mode)
6836 return;
6838 if (!view) {
6839 char buf[SIZEOF_STR];
6840 int retval;
6842 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
6843 die("%s", buf);
6846 if (!status_empty || *msg) {
6847 va_list args;
6849 va_start(args, msg);
6851 wmove(status_win, 0, 0);
6852 if (view->has_scrolled && use_scroll_status_wclear)
6853 wclear(status_win);
6854 if (*msg) {
6855 vwprintw(status_win, msg, args);
6856 status_empty = FALSE;
6857 } else {
6858 status_empty = TRUE;
6860 wclrtoeol(status_win);
6861 wnoutrefresh(status_win);
6863 va_end(args);
6866 update_view_title(view);
6869 static void
6870 init_display(void)
6872 const char *term;
6873 int x, y;
6875 /* Initialize the curses library */
6876 if (isatty(STDIN_FILENO)) {
6877 cursed = !!initscr();
6878 opt_tty = stdin;
6879 } else {
6880 /* Leave stdin and stdout alone when acting as a pager. */
6881 opt_tty = fopen("/dev/tty", "r+");
6882 if (!opt_tty)
6883 die("Failed to open /dev/tty");
6884 cursed = !!newterm(NULL, opt_tty, opt_tty);
6887 if (!cursed)
6888 die("Failed to initialize curses");
6890 nonl(); /* Disable conversion and detect newlines from input. */
6891 cbreak(); /* Take input chars one at a time, no wait for \n */
6892 noecho(); /* Don't echo input */
6893 leaveok(stdscr, FALSE);
6895 if (has_colors())
6896 init_colors();
6898 getmaxyx(stdscr, y, x);
6899 status_win = newwin(1, x, y - 1, 0);
6900 if (!status_win)
6901 die("Failed to create status window");
6903 /* Enable keyboard mapping */
6904 keypad(status_win, TRUE);
6905 wbkgdset(status_win, get_line_attr(LINE_STATUS));
6907 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6908 set_tabsize(opt_tab_size);
6909 #else
6910 TABSIZE = opt_tab_size;
6911 #endif
6913 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6914 if (term && !strcmp(term, "gnome-terminal")) {
6915 /* In the gnome-terminal-emulator, the message from
6916 * scrolling up one line when impossible followed by
6917 * scrolling down one line causes corruption of the
6918 * status line. This is fixed by calling wclear. */
6919 use_scroll_status_wclear = TRUE;
6920 use_scroll_redrawwin = FALSE;
6922 } else if (term && !strcmp(term, "xrvt-xpm")) {
6923 /* No problems with full optimizations in xrvt-(unicode)
6924 * and aterm. */
6925 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6927 } else {
6928 /* When scrolling in (u)xterm the last line in the
6929 * scrolling direction will update slowly. */
6930 use_scroll_redrawwin = TRUE;
6931 use_scroll_status_wclear = FALSE;
6935 static int
6936 get_input(int prompt_position)
6938 struct view *view;
6939 int i, key, cursor_y, cursor_x;
6941 if (prompt_position)
6942 input_mode = TRUE;
6944 while (TRUE) {
6945 bool loading = FALSE;
6947 foreach_view (view, i) {
6948 update_view(view);
6949 if (view_is_displayed(view) && view->has_scrolled &&
6950 use_scroll_redrawwin)
6951 redrawwin(view->win);
6952 view->has_scrolled = FALSE;
6953 if (view->pipe)
6954 loading = TRUE;
6957 /* Update the cursor position. */
6958 if (prompt_position) {
6959 getbegyx(status_win, cursor_y, cursor_x);
6960 cursor_x = prompt_position;
6961 } else {
6962 view = display[current_view];
6963 getbegyx(view->win, cursor_y, cursor_x);
6964 cursor_x = view->width - 1;
6965 cursor_y += view->lineno - view->offset;
6967 setsyx(cursor_y, cursor_x);
6969 /* Refresh, accept single keystroke of input */
6970 doupdate();
6971 nodelay(status_win, loading);
6972 key = wgetch(status_win);
6974 /* wgetch() with nodelay() enabled returns ERR when
6975 * there's no input. */
6976 if (key == ERR) {
6978 } else if (key == KEY_RESIZE) {
6979 int height, width;
6981 getmaxyx(stdscr, height, width);
6983 wresize(status_win, 1, width);
6984 mvwin(status_win, height - 1, 0);
6985 wnoutrefresh(status_win);
6986 resize_display();
6987 redraw_display(TRUE);
6989 } else {
6990 input_mode = FALSE;
6991 if (key == erasechar())
6992 key = KEY_BACKSPACE;
6993 return key;
6998 static char *
6999 prompt_input(const char *prompt, input_handler handler, void *data)
7001 enum input_status status = INPUT_OK;
7002 static char buf[SIZEOF_STR];
7003 size_t pos = 0;
7005 buf[pos] = 0;
7007 while (status == INPUT_OK || status == INPUT_SKIP) {
7008 int key;
7010 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
7011 wclrtoeol(status_win);
7013 key = get_input(pos + 1);
7014 switch (key) {
7015 case KEY_RETURN:
7016 case KEY_ENTER:
7017 case '\n':
7018 status = pos ? INPUT_STOP : INPUT_CANCEL;
7019 break;
7021 case KEY_BACKSPACE:
7022 if (pos > 0)
7023 buf[--pos] = 0;
7024 else
7025 status = INPUT_CANCEL;
7026 break;
7028 case KEY_ESC:
7029 status = INPUT_CANCEL;
7030 break;
7032 default:
7033 if (pos >= sizeof(buf)) {
7034 report("Input string too long");
7035 return NULL;
7038 status = handler(data, buf, key);
7039 if (status == INPUT_OK)
7040 buf[pos++] = (char) key;
7044 /* Clear the status window */
7045 status_empty = FALSE;
7046 report("");
7048 if (status == INPUT_CANCEL)
7049 return NULL;
7051 buf[pos++] = 0;
7053 return buf;
7056 static enum input_status
7057 prompt_yesno_handler(void *data, char *buf, int c)
7059 if (c == 'y' || c == 'Y')
7060 return INPUT_STOP;
7061 if (c == 'n' || c == 'N')
7062 return INPUT_CANCEL;
7063 return INPUT_SKIP;
7066 static bool
7067 prompt_yesno(const char *prompt)
7069 char prompt2[SIZEOF_STR];
7071 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7072 return FALSE;
7074 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7077 static enum input_status
7078 read_prompt_handler(void *data, char *buf, int c)
7080 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7083 static char *
7084 read_prompt(const char *prompt)
7086 return prompt_input(prompt, read_prompt_handler, NULL);
7089 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7091 enum input_status status = INPUT_OK;
7092 int size = 0;
7094 while (items[size].text)
7095 size++;
7097 while (status == INPUT_OK) {
7098 const struct menu_item *item = &items[*selected];
7099 int key;
7100 int i;
7102 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7103 prompt, *selected + 1, size);
7104 if (item->hotkey)
7105 wprintw(status_win, "[%c] ", (char) item->hotkey);
7106 wprintw(status_win, "%s", item->text);
7107 wclrtoeol(status_win);
7109 key = get_input(COLS - 1);
7110 switch (key) {
7111 case KEY_RETURN:
7112 case KEY_ENTER:
7113 case '\n':
7114 status = INPUT_STOP;
7115 break;
7117 case KEY_LEFT:
7118 case KEY_UP:
7119 *selected = *selected - 1;
7120 if (*selected < 0)
7121 *selected = size - 1;
7122 break;
7124 case KEY_RIGHT:
7125 case KEY_DOWN:
7126 *selected = (*selected + 1) % size;
7127 break;
7129 case KEY_ESC:
7130 status = INPUT_CANCEL;
7131 break;
7133 default:
7134 for (i = 0; items[i].text; i++)
7135 if (items[i].hotkey == key) {
7136 *selected = i;
7137 status = INPUT_STOP;
7138 break;
7143 /* Clear the status window */
7144 status_empty = FALSE;
7145 report("");
7147 return status != INPUT_CANCEL;
7151 * Repository properties
7154 static struct ref **refs = NULL;
7155 static size_t refs_size = 0;
7156 static struct ref *refs_head = NULL;
7158 static struct ref_list **ref_lists = NULL;
7159 static size_t ref_lists_size = 0;
7161 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
7162 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
7163 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
7165 static int
7166 compare_refs(const void *ref1_, const void *ref2_)
7168 const struct ref *ref1 = *(const struct ref **)ref1_;
7169 const struct ref *ref2 = *(const struct ref **)ref2_;
7171 if (ref1->tag != ref2->tag)
7172 return ref2->tag - ref1->tag;
7173 if (ref1->ltag != ref2->ltag)
7174 return ref2->ltag - ref1->ltag;
7175 if (ref1->head != ref2->head)
7176 return ref2->head - ref1->head;
7177 if (ref1->tracked != ref2->tracked)
7178 return ref2->tracked - ref1->tracked;
7179 if (ref1->replace != ref2->replace)
7180 return ref2->replace - ref1->replace;
7181 /* Order remotes last. */
7182 if (ref1->remote != ref2->remote)
7183 return ref1->remote - ref2->remote;
7184 return strcmp(ref1->name, ref2->name);
7187 static void
7188 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
7190 size_t i;
7192 for (i = 0; i < refs_size; i++)
7193 if (!visitor(data, refs[i]))
7194 break;
7197 static struct ref *
7198 get_ref_head()
7200 return refs_head;
7203 static struct ref_list *
7204 get_ref_list(const char *id)
7206 struct ref_list *list;
7207 size_t i;
7209 for (i = 0; i < ref_lists_size; i++)
7210 if (!strcmp(id, ref_lists[i]->id))
7211 return ref_lists[i];
7213 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
7214 return NULL;
7215 list = calloc(1, sizeof(*list));
7216 if (!list)
7217 return NULL;
7219 for (i = 0; i < refs_size; i++) {
7220 if (!strcmp(id, refs[i]->id) &&
7221 realloc_refs_list(&list->refs, list->size, 1))
7222 list->refs[list->size++] = refs[i];
7225 if (!list->refs) {
7226 free(list);
7227 return NULL;
7230 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
7231 ref_lists[ref_lists_size++] = list;
7232 return list;
7235 static int
7236 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
7238 struct ref *ref = NULL;
7239 bool tag = FALSE;
7240 bool ltag = FALSE;
7241 bool remote = FALSE;
7242 bool replace = FALSE;
7243 bool tracked = FALSE;
7244 bool head = FALSE;
7245 int from = 0, to = refs_size - 1;
7247 if (!prefixcmp(name, "refs/tags/")) {
7248 if (!suffixcmp(name, namelen, "^{}")) {
7249 namelen -= 3;
7250 name[namelen] = 0;
7251 } else {
7252 ltag = TRUE;
7255 tag = TRUE;
7256 namelen -= STRING_SIZE("refs/tags/");
7257 name += STRING_SIZE("refs/tags/");
7259 } else if (!prefixcmp(name, "refs/remotes/")) {
7260 remote = TRUE;
7261 namelen -= STRING_SIZE("refs/remotes/");
7262 name += STRING_SIZE("refs/remotes/");
7263 tracked = !strcmp(opt_remote, name);
7265 } else if (!prefixcmp(name, "refs/replace/")) {
7266 replace = TRUE;
7267 id = name + strlen("refs/replace/");
7268 idlen = namelen - strlen("refs/replace/");
7269 name = "replaced";
7270 namelen = strlen(name);
7272 } else if (!prefixcmp(name, "refs/heads/")) {
7273 namelen -= STRING_SIZE("refs/heads/");
7274 name += STRING_SIZE("refs/heads/");
7275 if (strlen(opt_head) == namelen
7276 && !strncmp(opt_head, name, namelen))
7277 return OK;
7279 } else if (!strcmp(name, "HEAD")) {
7280 head = TRUE;
7281 if (*opt_head) {
7282 namelen = strlen(opt_head);
7283 name = opt_head;
7287 /* If we are reloading or it's an annotated tag, replace the
7288 * previous SHA1 with the resolved commit id; relies on the fact
7289 * git-ls-remote lists the commit id of an annotated tag right
7290 * before the commit id it points to. */
7291 while ((from <= to) && !replace) {
7292 size_t pos = (to + from) / 2;
7293 int cmp = strcmp(name, refs[pos]->name);
7295 if (!cmp) {
7296 ref = refs[pos];
7297 break;
7300 if (cmp < 0)
7301 to = pos - 1;
7302 else
7303 from = pos + 1;
7306 if (!ref) {
7307 if (!realloc_refs(&refs, refs_size, 1))
7308 return ERR;
7309 ref = calloc(1, sizeof(*ref) + namelen);
7310 if (!ref)
7311 return ERR;
7312 memmove(refs + from + 1, refs + from,
7313 (refs_size - from) * sizeof(*refs));
7314 refs[from] = ref;
7315 strncpy(ref->name, name, namelen);
7316 refs_size++;
7319 ref->head = head;
7320 ref->tag = tag;
7321 ref->ltag = ltag;
7322 ref->remote = remote;
7323 ref->replace = replace;
7324 ref->tracked = tracked;
7325 string_copy_rev(ref->id, id);
7327 if (head)
7328 refs_head = ref;
7329 return OK;
7332 static int
7333 load_refs(void)
7335 const char *head_argv[] = {
7336 "git", "symbolic-ref", "HEAD", NULL
7338 static const char *ls_remote_argv[SIZEOF_ARG] = {
7339 "git", "ls-remote", opt_git_dir, NULL
7341 static bool init = FALSE;
7342 size_t i;
7344 if (!init) {
7345 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
7346 die("TIG_LS_REMOTE contains too many arguments");
7347 init = TRUE;
7350 if (!*opt_git_dir)
7351 return OK;
7353 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
7354 !prefixcmp(opt_head, "refs/heads/")) {
7355 char *offset = opt_head + STRING_SIZE("refs/heads/");
7357 memmove(opt_head, offset, strlen(offset) + 1);
7360 refs_head = NULL;
7361 for (i = 0; i < refs_size; i++)
7362 refs[i]->id[0] = 0;
7364 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
7365 return ERR;
7367 /* Update the ref lists to reflect changes. */
7368 for (i = 0; i < ref_lists_size; i++) {
7369 struct ref_list *list = ref_lists[i];
7370 size_t old, new;
7372 for (old = new = 0; old < list->size; old++)
7373 if (!strcmp(list->id, list->refs[old]->id))
7374 list->refs[new++] = list->refs[old];
7375 list->size = new;
7378 qsort(refs, refs_size, sizeof(*refs), compare_refs);
7380 return OK;
7383 static void
7384 set_remote_branch(const char *name, const char *value, size_t valuelen)
7386 if (!strcmp(name, ".remote")) {
7387 string_ncopy(opt_remote, value, valuelen);
7389 } else if (*opt_remote && !strcmp(name, ".merge")) {
7390 size_t from = strlen(opt_remote);
7392 if (!prefixcmp(value, "refs/heads/"))
7393 value += STRING_SIZE("refs/heads/");
7395 if (!string_format_from(opt_remote, &from, "/%s", value))
7396 opt_remote[0] = 0;
7400 static void
7401 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7403 const char *argv[SIZEOF_ARG] = { name, "=" };
7404 int argc = 1 + (cmd == option_set_command);
7405 enum option_code error;
7407 if (!argv_from_string(argv, &argc, value))
7408 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7409 else
7410 error = cmd(argc, argv);
7412 if (error != OPT_OK)
7413 warn("Option 'tig.%s': %s", name, option_errors[error]);
7416 static bool
7417 set_environment_variable(const char *name, const char *value)
7419 size_t len = strlen(name) + 1 + strlen(value) + 1;
7420 char *env = malloc(len);
7422 if (env &&
7423 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7424 putenv(env) == 0)
7425 return TRUE;
7426 free(env);
7427 return FALSE;
7430 static void
7431 set_work_tree(const char *value)
7433 char cwd[SIZEOF_STR];
7435 if (!getcwd(cwd, sizeof(cwd)))
7436 die("Failed to get cwd path: %s", strerror(errno));
7437 if (chdir(opt_git_dir) < 0)
7438 die("Failed to chdir(%s): %s", strerror(errno));
7439 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7440 die("Failed to get git path: %s", strerror(errno));
7441 if (chdir(cwd) < 0)
7442 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7443 if (chdir(value) < 0)
7444 die("Failed to chdir(%s): %s", value, strerror(errno));
7445 if (!getcwd(cwd, sizeof(cwd)))
7446 die("Failed to get cwd path: %s", strerror(errno));
7447 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7448 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7449 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7450 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7451 opt_is_inside_work_tree = TRUE;
7454 static int
7455 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7457 if (!strcmp(name, "gui.encoding"))
7458 parse_encoding(&opt_encoding, value, TRUE);
7460 else if (!strcmp(name, "core.editor"))
7461 string_ncopy(opt_editor, value, valuelen);
7463 else if (!strcmp(name, "core.worktree"))
7464 set_work_tree(value);
7466 else if (!prefixcmp(name, "tig.color."))
7467 set_repo_config_option(name + 10, value, option_color_command);
7469 else if (!prefixcmp(name, "tig.bind."))
7470 set_repo_config_option(name + 9, value, option_bind_command);
7472 else if (!prefixcmp(name, "tig."))
7473 set_repo_config_option(name + 4, value, option_set_command);
7475 else if (*opt_head && !prefixcmp(name, "branch.") &&
7476 !strncmp(name + 7, opt_head, strlen(opt_head)))
7477 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7479 return OK;
7482 static int
7483 load_git_config(void)
7485 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7487 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7490 static int
7491 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7493 if (!opt_git_dir[0]) {
7494 string_ncopy(opt_git_dir, name, namelen);
7496 } else if (opt_is_inside_work_tree == -1) {
7497 /* This can be 3 different values depending on the
7498 * version of git being used. If git-rev-parse does not
7499 * understand --is-inside-work-tree it will simply echo
7500 * the option else either "true" or "false" is printed.
7501 * Default to true for the unknown case. */
7502 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7504 } else if (*name == '.') {
7505 string_ncopy(opt_cdup, name, namelen);
7507 } else {
7508 string_ncopy(opt_prefix, name, namelen);
7511 return OK;
7514 static int
7515 load_repo_info(void)
7517 const char *rev_parse_argv[] = {
7518 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7519 "--show-cdup", "--show-prefix", NULL
7522 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7527 * Main
7530 static const char usage[] =
7531 "tig " TIG_VERSION " (" __DATE__ ")\n"
7532 "\n"
7533 "Usage: tig [options] [revs] [--] [paths]\n"
7534 " or: tig show [options] [revs] [--] [paths]\n"
7535 " or: tig blame [options] [rev] [--] path\n"
7536 " or: tig status\n"
7537 " or: tig < [git command output]\n"
7538 "\n"
7539 "Options:\n"
7540 " +<number> Select line <number> in the first view\n"
7541 " -v, --version Show version and exit\n"
7542 " -h, --help Show help message and exit";
7544 static void __NORETURN
7545 quit(int sig)
7547 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7548 if (cursed)
7549 endwin();
7550 exit(0);
7553 static void __NORETURN
7554 die(const char *err, ...)
7556 va_list args;
7558 endwin();
7560 va_start(args, err);
7561 fputs("tig: ", stderr);
7562 vfprintf(stderr, err, args);
7563 fputs("\n", stderr);
7564 va_end(args);
7566 exit(1);
7569 static void
7570 warn(const char *msg, ...)
7572 va_list args;
7574 va_start(args, msg);
7575 fputs("tig warning: ", stderr);
7576 vfprintf(stderr, msg, args);
7577 fputs("\n", stderr);
7578 va_end(args);
7581 static int
7582 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7584 const char ***filter_args = data;
7586 return argv_append(filter_args, name) ? OK : ERR;
7589 static void
7590 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7592 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7593 const char **all_argv = NULL;
7595 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7596 !argv_append_array(&all_argv, argv) ||
7597 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7598 die("Failed to split arguments");
7599 argv_free(all_argv);
7600 free(all_argv);
7603 static void
7604 filter_options(const char *argv[], bool blame)
7606 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7608 if (blame)
7609 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7610 else
7611 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7613 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7616 static enum request
7617 parse_options(int argc, const char *argv[])
7619 enum request request = REQ_VIEW_MAIN;
7620 const char *subcommand;
7621 bool seen_dashdash = FALSE;
7622 const char **filter_argv = NULL;
7623 int i;
7625 if (!isatty(STDIN_FILENO))
7626 return REQ_VIEW_PAGER;
7628 if (argc <= 1)
7629 return REQ_VIEW_MAIN;
7631 subcommand = argv[1];
7632 if (!strcmp(subcommand, "status")) {
7633 if (argc > 2)
7634 warn("ignoring arguments after `%s'", subcommand);
7635 return REQ_VIEW_STATUS;
7637 } else if (!strcmp(subcommand, "blame")) {
7638 request = REQ_VIEW_BLAME;
7640 } else if (!strcmp(subcommand, "show")) {
7641 request = REQ_VIEW_DIFF;
7643 } else {
7644 subcommand = NULL;
7647 for (i = 1 + !!subcommand; i < argc; i++) {
7648 const char *opt = argv[i];
7650 // stop parsing our options after -- and let rev-parse handle the rest
7651 if (!seen_dashdash) {
7652 if (!strcmp(opt, "--")) {
7653 seen_dashdash = TRUE;
7654 continue;
7656 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7657 printf("tig version %s\n", TIG_VERSION);
7658 quit(0);
7660 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7661 printf("%s\n", usage);
7662 quit(0);
7664 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7665 opt_lineno = atoi(opt + 1);
7666 continue;
7671 if (!argv_append(&filter_argv, opt))
7672 die("command too long");
7675 if (filter_argv)
7676 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7678 /* Finish validating and setting up blame options */
7679 if (request == REQ_VIEW_BLAME) {
7680 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7681 die("invalid number of options to blame\n\n%s", usage);
7683 if (opt_rev_argv) {
7684 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7687 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7690 return request;
7694 main(int argc, const char *argv[])
7696 const char *codeset = ENCODING_UTF8;
7697 enum request request = parse_options(argc, argv);
7698 struct view *view;
7700 signal(SIGINT, quit);
7701 signal(SIGPIPE, SIG_IGN);
7703 if (setlocale(LC_ALL, "")) {
7704 codeset = nl_langinfo(CODESET);
7707 if (load_repo_info() == ERR)
7708 die("Failed to load repo info.");
7710 if (load_options() == ERR)
7711 die("Failed to load user config.");
7713 if (load_git_config() == ERR)
7714 die("Failed to load repo config.");
7716 /* Require a git repository unless when running in pager mode. */
7717 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7718 die("Not a git repository");
7720 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
7721 char translit[SIZEOF_STR];
7723 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
7724 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
7725 else
7726 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
7727 if (opt_iconv_out == ICONV_NONE)
7728 die("Failed to initialize character set conversion");
7731 if (load_refs() == ERR)
7732 die("Failed to load refs.");
7734 init_display();
7736 while (view_driver(display[current_view], request)) {
7737 int key = get_input(0);
7739 view = display[current_view];
7740 request = get_keybinding(view->keymap, key);
7742 /* Some low-level request handling. This keeps access to
7743 * status_win restricted. */
7744 switch (request) {
7745 case REQ_NONE:
7746 report("Unknown key, press %s for help",
7747 get_view_key(view, REQ_VIEW_HELP));
7748 break;
7749 case REQ_PROMPT:
7751 char *cmd = read_prompt(":");
7753 if (cmd && string_isnumber(cmd)) {
7754 int lineno = view->lineno + 1;
7756 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
7757 select_view_line(view, lineno - 1);
7758 report("");
7759 } else {
7760 report("Unable to parse '%s' as a line number", cmd);
7762 } else if (cmd && iscommit(cmd)) {
7763 string_ncopy(opt_search, cmd, strlen(cmd));
7765 request = view_request(view, REQ_JUMP_COMMIT);
7766 if (request == REQ_JUMP_COMMIT) {
7767 report("Jumping to commits is not supported by the '%s' view", view->name);
7770 } else if (cmd) {
7771 struct view *next = VIEW(REQ_VIEW_PAGER);
7772 const char *argv[SIZEOF_ARG] = { "git" };
7773 int argc = 1;
7775 /* When running random commands, initially show the
7776 * command in the title. However, it maybe later be
7777 * overwritten if a commit line is selected. */
7778 string_ncopy(next->ref, cmd, strlen(cmd));
7780 if (!argv_from_string(argv, &argc, cmd)) {
7781 report("Too many arguments");
7782 } else if (!format_argv(&next->argv, argv, FALSE)) {
7783 report("Argument formatting failed");
7784 } else {
7785 next->dir = NULL;
7786 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7790 request = REQ_NONE;
7791 break;
7793 case REQ_SEARCH:
7794 case REQ_SEARCH_BACK:
7796 const char *prompt = request == REQ_SEARCH ? "/" : "?";
7797 char *search = read_prompt(prompt);
7799 if (search)
7800 string_ncopy(opt_search, search, strlen(search));
7801 else if (*opt_search)
7802 request = request == REQ_SEARCH ?
7803 REQ_FIND_NEXT :
7804 REQ_FIND_PREV;
7805 else
7806 request = REQ_NONE;
7807 break;
7809 default:
7810 break;
7814 quit(0);
7816 return 0;