Minor improvement of status view restoration
[tig.git] / tig.c
blobfb7cadae76e3fda138c409c123097640754fbee0
1 /* Copyright (c) 2006-2012 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"
17 #include "git.h"
19 static void __NORETURN die(const char *err, ...);
20 static void warn(const char *msg, ...);
21 static void report(const char *msg, ...);
24 struct ref {
25 char id[SIZEOF_REV]; /* Commit SHA1 ID */
26 unsigned int head:1; /* Is it the current HEAD? */
27 unsigned int tag:1; /* Is it a tag? */
28 unsigned int ltag:1; /* If so, is the tag local? */
29 unsigned int remote:1; /* Is it a remote ref? */
30 unsigned int replace:1; /* Is it a replace ref? */
31 unsigned int tracked:1; /* Is it the remote for the current HEAD? */
32 char name[1]; /* Ref name; tag or head names are shortened. */
35 struct ref_list {
36 char id[SIZEOF_REV]; /* Commit SHA1 ID */
37 size_t size; /* Number of refs. */
38 struct ref **refs; /* References for this ID. */
41 static struct ref *get_ref_head();
42 static struct ref_list *get_ref_list(const char *id);
43 static void foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data);
44 static int load_refs(void);
46 enum input_status {
47 INPUT_OK,
48 INPUT_SKIP,
49 INPUT_STOP,
50 INPUT_CANCEL
53 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
55 static char *prompt_input(const char *prompt, input_handler handler, void *data);
56 static bool prompt_yesno(const char *prompt);
57 static char *read_prompt(const char *prompt);
59 struct menu_item {
60 int hotkey;
61 const char *text;
62 void *data;
65 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
67 #define GRAPHIC_ENUM(_) \
68 _(GRAPHIC, ASCII), \
69 _(GRAPHIC, DEFAULT), \
70 _(GRAPHIC, UTF_8)
72 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
74 #define DATE_ENUM(_) \
75 _(DATE, NO), \
76 _(DATE, DEFAULT), \
77 _(DATE, LOCAL), \
78 _(DATE, RELATIVE), \
79 _(DATE, SHORT)
81 DEFINE_ENUM(date, DATE_ENUM);
83 struct time {
84 time_t sec;
85 int tz;
88 static inline int timecmp(const struct time *t1, const struct time *t2)
90 return t1->sec - t2->sec;
93 static const char *
94 mkdate(const struct time *time, enum date date)
96 static char buf[DATE_COLS + 1];
97 static const struct enum_map reldate[] = {
98 { "second", 1, 60 * 2 },
99 { "minute", 60, 60 * 60 * 2 },
100 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
101 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
102 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
103 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 30 * 12 },
105 struct tm tm;
107 if (!date || !time || !time->sec)
108 return "";
110 if (date == DATE_RELATIVE) {
111 struct timeval now;
112 time_t date = time->sec + time->tz;
113 time_t seconds;
114 int i;
116 gettimeofday(&now, NULL);
117 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
118 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
119 if (seconds >= reldate[i].value)
120 continue;
122 seconds /= reldate[i].namelen;
123 if (!string_format(buf, "%ld %s%s %s",
124 seconds, reldate[i].name,
125 seconds > 1 ? "s" : "",
126 now.tv_sec >= date ? "ago" : "ahead"))
127 break;
128 return buf;
132 if (date == DATE_LOCAL) {
133 time_t date = time->sec + time->tz;
134 localtime_r(&date, &tm);
136 else {
137 gmtime_r(&time->sec, &tm);
139 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
143 #define AUTHOR_ENUM(_) \
144 _(AUTHOR, NO), \
145 _(AUTHOR, FULL), \
146 _(AUTHOR, ABBREVIATED)
148 DEFINE_ENUM(author, AUTHOR_ENUM);
150 static const char *
151 get_author_initials(const char *author)
153 static char initials[AUTHOR_COLS * 6 + 1];
154 size_t pos = 0;
155 const char *end = strchr(author, '\0');
157 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
159 memset(initials, 0, sizeof(initials));
160 while (author < end) {
161 unsigned char bytes;
162 size_t i;
164 while (author < end && is_initial_sep(*author))
165 author++;
167 bytes = utf8_char_length(author, end);
168 if (bytes >= sizeof(initials) - 1 - pos)
169 break;
170 while (bytes--) {
171 initials[pos++] = *author++;
174 i = pos;
175 while (author < end && !is_initial_sep(*author)) {
176 bytes = utf8_char_length(author, end);
177 if (bytes >= sizeof(initials) - 1 - i) {
178 while (author < end && !is_initial_sep(*author))
179 author++;
180 break;
182 while (bytes--) {
183 initials[i++] = *author++;
187 initials[i++] = 0;
190 return initials;
193 #define author_trim(cols) (cols == 0 || cols > 5)
195 static const char *
196 mkauthor(const char *text, int cols, enum author author)
198 bool trim = author_trim(cols);
199 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
201 if (author == AUTHOR_NO)
202 return "";
203 if (abbreviate && text)
204 return get_author_initials(text);
205 return text;
208 static const char *
209 mkmode(mode_t mode)
211 if (S_ISDIR(mode))
212 return "drwxr-xr-x";
213 else if (S_ISLNK(mode))
214 return "lrwxrwxrwx";
215 else if (S_ISGITLINK(mode))
216 return "m---------";
217 else if (S_ISREG(mode) && mode & S_IXUSR)
218 return "-rwxr-xr-x";
219 else if (S_ISREG(mode))
220 return "-rw-r--r--";
221 else
222 return "----------";
225 #define FILENAME_ENUM(_) \
226 _(FILENAME, NO), \
227 _(FILENAME, ALWAYS), \
228 _(FILENAME, AUTO)
230 DEFINE_ENUM(filename, FILENAME_ENUM);
232 #define IGNORE_SPACE_ENUM(_) \
233 _(IGNORE_SPACE, NO), \
234 _(IGNORE_SPACE, ALL), \
235 _(IGNORE_SPACE, SOME), \
236 _(IGNORE_SPACE, AT_EOL)
238 DEFINE_ENUM(ignore_space, IGNORE_SPACE_ENUM);
240 #define COMMIT_ORDER_ENUM(_) \
241 _(COMMIT_ORDER, DEFAULT), \
242 _(COMMIT_ORDER, TOPO), \
243 _(COMMIT_ORDER, DATE), \
244 _(COMMIT_ORDER, REVERSE)
246 DEFINE_ENUM(commit_order, COMMIT_ORDER_ENUM);
248 #define VIEW_INFO(_) \
249 _(MAIN, main, ref_head), \
250 _(DIFF, diff, ref_commit), \
251 _(LOG, log, ref_head), \
252 _(TREE, tree, ref_commit), \
253 _(BLOB, blob, ref_blob), \
254 _(BLAME, blame, ref_commit), \
255 _(BRANCH, branch, ref_head), \
256 _(HELP, help, ""), \
257 _(PAGER, pager, ""), \
258 _(STATUS, status, "status"), \
259 _(STAGE, stage, "stage")
261 static struct encoding *
262 get_path_encoding(const char *path, struct encoding *default_encoding)
264 const char *check_attr_argv[] = {
265 "git", "check-attr", "encoding", "--", path, NULL
267 char buf[SIZEOF_STR];
268 char *encoding;
270 /* <path>: encoding: <encoding> */
272 if (!*path || !io_run_buf(check_attr_argv, buf, sizeof(buf))
273 || !(encoding = strstr(buf, ENCODING_SEP)))
274 return default_encoding;
276 encoding += STRING_SIZE(ENCODING_SEP);
277 if (!strcmp(encoding, ENCODING_UTF8)
278 || !strcmp(encoding, "unspecified")
279 || !strcmp(encoding, "set"))
280 return default_encoding;
282 return encoding_open(encoding);
286 * User requests
289 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
291 #define REQ_INFO \
292 REQ_GROUP("View switching") \
293 VIEW_INFO(VIEW_REQ), \
295 REQ_GROUP("View manipulation") \
296 REQ_(ENTER, "Enter current line and scroll"), \
297 REQ_(NEXT, "Move to next"), \
298 REQ_(PREVIOUS, "Move to previous"), \
299 REQ_(PARENT, "Move to parent"), \
300 REQ_(VIEW_NEXT, "Move focus to next view"), \
301 REQ_(REFRESH, "Reload and refresh"), \
302 REQ_(MAXIMIZE, "Maximize the current view"), \
303 REQ_(VIEW_CLOSE, "Close the current view"), \
304 REQ_(QUIT, "Close all views and quit"), \
306 REQ_GROUP("View specific requests") \
307 REQ_(STATUS_UPDATE, "Update file status"), \
308 REQ_(STATUS_REVERT, "Revert file changes"), \
309 REQ_(STATUS_MERGE, "Merge file using external tool"), \
310 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
311 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
312 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
313 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
315 REQ_GROUP("Cursor navigation") \
316 REQ_(MOVE_UP, "Move cursor one line up"), \
317 REQ_(MOVE_DOWN, "Move cursor one line down"), \
318 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
319 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
320 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
321 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
323 REQ_GROUP("Scrolling") \
324 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
325 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
326 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
327 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
328 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
329 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
330 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
332 REQ_GROUP("Searching") \
333 REQ_(SEARCH, "Search the view"), \
334 REQ_(SEARCH_BACK, "Search backwards in the view"), \
335 REQ_(FIND_NEXT, "Find next search match"), \
336 REQ_(FIND_PREV, "Find previous search match"), \
338 REQ_GROUP("Option manipulation") \
339 REQ_(OPTIONS, "Open option menu"), \
340 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
341 REQ_(TOGGLE_DATE, "Toggle date display"), \
342 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
343 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
344 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
345 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
346 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
347 REQ_(TOGGLE_CHANGES, "Toggle local changes display in the main view"), \
348 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
349 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
350 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
351 REQ_(TOGGLE_COMMIT_ORDER, "Toggle commit ordering"), \
353 REQ_GROUP("Misc") \
354 REQ_(PROMPT, "Bring up the prompt"), \
355 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
356 REQ_(SHOW_VERSION, "Show version information"), \
357 REQ_(STOP_LOADING, "Stop all loading views"), \
358 REQ_(EDIT, "Open in editor"), \
359 REQ_(NONE, "Do nothing")
362 /* User action requests. */
363 enum request {
364 #define REQ_GROUP(help)
365 #define REQ_(req, help) REQ_##req
367 /* Offset all requests to avoid conflicts with ncurses getch values. */
368 REQ_UNKNOWN = KEY_MAX + 1,
369 REQ_OFFSET,
370 REQ_INFO,
372 /* Internal requests. */
373 REQ_JUMP_COMMIT,
375 #undef REQ_GROUP
376 #undef REQ_
379 struct request_info {
380 enum request request;
381 const char *name;
382 int namelen;
383 const char *help;
386 static const struct request_info req_info[] = {
387 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
388 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
389 REQ_INFO
390 #undef REQ_GROUP
391 #undef REQ_
394 static enum request
395 get_request(const char *name)
397 int namelen = strlen(name);
398 int i;
400 for (i = 0; i < ARRAY_SIZE(req_info); i++)
401 if (enum_equals(req_info[i], name, namelen))
402 return req_info[i].request;
404 return REQ_UNKNOWN;
409 * Options
412 /* Option and state variables. */
413 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
414 static enum date opt_date = DATE_DEFAULT;
415 static enum author opt_author = AUTHOR_FULL;
416 static enum filename opt_filename = FILENAME_AUTO;
417 static bool opt_rev_graph = TRUE;
418 static bool opt_line_number = FALSE;
419 static bool opt_show_refs = TRUE;
420 static bool opt_show_changes = TRUE;
421 static bool opt_untracked_dirs_content = TRUE;
422 static bool opt_read_git_colors = TRUE;
423 static int opt_diff_context = 3;
424 static char opt_diff_context_arg[9] = "";
425 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
426 static char opt_ignore_space_arg[22] = "";
427 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
428 static char opt_commit_order_arg[22] = "";
429 static bool opt_notes = TRUE;
430 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
431 static int opt_num_interval = 5;
432 static double opt_hscroll = 0.50;
433 static double opt_scale_split_view = 2.0 / 3.0;
434 static int opt_tab_size = 8;
435 static int opt_author_cols = AUTHOR_COLS;
436 static int opt_filename_cols = FILENAME_COLS;
437 static char opt_path[SIZEOF_STR] = "";
438 static char opt_file[SIZEOF_STR] = "";
439 static char opt_ref[SIZEOF_REF] = "";
440 static unsigned long opt_goto_line = 0;
441 static char opt_head[SIZEOF_REF] = "";
442 static char opt_remote[SIZEOF_REF] = "";
443 static struct encoding *opt_encoding = NULL;
444 static iconv_t opt_iconv_out = ICONV_NONE;
445 static char opt_search[SIZEOF_STR] = "";
446 static char opt_cdup[SIZEOF_STR] = "";
447 static char opt_prefix[SIZEOF_STR] = "";
448 static char opt_git_dir[SIZEOF_STR] = "";
449 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
450 static char opt_editor[SIZEOF_STR] = "";
451 static FILE *opt_tty = NULL;
452 static const char **opt_diff_argv = NULL;
453 static const char **opt_rev_argv = NULL;
454 static const char **opt_file_argv = NULL;
455 static const char **opt_blame_argv = NULL;
456 static int opt_lineno = 0;
458 #define is_initial_commit() (!get_ref_head())
459 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
461 static inline void
462 update_diff_context_arg(int diff_context)
464 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
465 string_ncopy(opt_diff_context_arg, "-U3", 3);
468 static inline void
469 update_ignore_space_arg()
471 if (opt_ignore_space == IGNORE_SPACE_ALL) {
472 string_copy(opt_ignore_space_arg, "--ignore-all-space");
473 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
474 string_copy(opt_ignore_space_arg, "--ignore-space-change");
475 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
476 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
477 } else {
478 string_copy(opt_ignore_space_arg, "");
482 static inline void
483 update_commit_order_arg()
485 if (opt_commit_order == COMMIT_ORDER_TOPO) {
486 string_copy(opt_commit_order_arg, "--topo-order");
487 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
488 string_copy(opt_commit_order_arg, "--date-order");
489 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
490 string_copy(opt_commit_order_arg, "--reverse");
491 } else {
492 string_copy(opt_commit_order_arg, "");
496 static inline void
497 update_notes_arg()
499 if (opt_notes) {
500 string_copy(opt_notes_arg, "--show-notes");
501 } else {
502 /* Notes are disabled by default when passing --pretty args. */
503 string_copy(opt_notes_arg, "");
508 * Line-oriented content detection.
511 #define LINE_INFO \
512 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
513 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
514 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
515 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
516 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
517 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
518 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
519 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
520 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
521 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
522 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
523 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
524 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
525 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
526 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
527 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
528 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
529 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
530 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
531 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
532 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
533 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
534 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
535 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
536 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
537 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
538 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
539 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
540 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
541 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
542 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
543 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
544 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
545 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
546 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
547 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
548 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
549 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
550 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
551 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
552 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
553 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
554 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
555 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
556 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
557 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
558 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
559 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
560 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
561 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
562 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
563 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
564 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
565 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
566 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
567 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
568 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
569 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
570 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
571 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
572 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
573 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
574 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
575 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
576 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
577 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
578 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
579 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
580 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
581 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
582 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
583 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
585 enum line_type {
586 #define LINE(type, line, fg, bg, attr) \
587 LINE_##type
588 LINE_INFO,
589 LINE_NONE
590 #undef LINE
593 struct line_info {
594 const char *name; /* Option name. */
595 int namelen; /* Size of option name. */
596 const char *line; /* The start of line to match. */
597 int linelen; /* Size of string to match. */
598 int fg, bg, attr; /* Color and text attributes for the lines. */
599 int color_pair;
602 static struct line_info line_info[] = {
603 #define LINE(type, line, fg, bg, attr) \
604 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
605 LINE_INFO
606 #undef LINE
609 static struct line_info **color_pair;
610 static size_t color_pairs;
612 static struct line_info *custom_color;
613 static size_t custom_colors;
615 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
616 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
618 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
619 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
621 /* Color IDs must be 1 or higher. [GH #15] */
622 #define COLOR_ID(line_type) ((line_type) + 1)
624 static enum line_type
625 get_line_type(const char *line)
627 int linelen = strlen(line);
628 enum line_type type;
630 for (type = 0; type < custom_colors; type++)
631 /* Case insensitive search matches Signed-off-by lines better. */
632 if (linelen >= custom_color[type].linelen &&
633 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
634 return TO_CUSTOM_COLOR_TYPE(type);
636 for (type = 0; type < ARRAY_SIZE(line_info); type++)
637 /* Case insensitive search matches Signed-off-by lines better. */
638 if (linelen >= line_info[type].linelen &&
639 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
640 return type;
642 return LINE_DEFAULT;
645 static enum line_type
646 get_line_type_from_ref(const struct ref *ref)
648 if (ref->head)
649 return LINE_MAIN_HEAD;
650 else if (ref->ltag)
651 return LINE_MAIN_LOCAL_TAG;
652 else if (ref->tag)
653 return LINE_MAIN_TAG;
654 else if (ref->tracked)
655 return LINE_MAIN_TRACKED;
656 else if (ref->remote)
657 return LINE_MAIN_REMOTE;
658 else if (ref->replace)
659 return LINE_MAIN_REPLACE;
661 return LINE_MAIN_REF;
664 static inline struct line_info *
665 get_line(enum line_type type)
667 struct line_info *info;
669 if (type > LINE_NONE) {
670 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
671 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
672 } else {
673 assert(type < ARRAY_SIZE(line_info));
674 return &line_info[type];
678 static inline int
679 get_line_color(enum line_type type)
681 return COLOR_ID(get_line(type)->color_pair);
684 static inline int
685 get_line_attr(enum line_type type)
687 struct line_info *info = get_line(type);
689 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
692 static struct line_info *
693 get_line_info(const char *name)
695 size_t namelen = strlen(name);
696 enum line_type type;
698 for (type = 0; type < ARRAY_SIZE(line_info); type++)
699 if (enum_equals(line_info[type], name, namelen))
700 return &line_info[type];
702 return NULL;
705 static struct line_info *
706 add_custom_color(const char *quoted_line)
708 struct line_info *info;
709 char *line;
710 size_t linelen;
712 if (!realloc_custom_color(&custom_color, custom_colors, 1))
713 die("Failed to alloc custom line info");
715 linelen = strlen(quoted_line) - 1;
716 line = malloc(linelen);
717 if (!line)
718 return NULL;
720 strncpy(line, quoted_line + 1, linelen);
721 line[linelen - 1] = 0;
723 info = &custom_color[custom_colors++];
724 info->name = info->line = line;
725 info->namelen = info->linelen = strlen(line);
727 return info;
730 static void
731 init_line_info_color_pair(struct line_info *info, enum line_type type,
732 int default_bg, int default_fg)
734 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
735 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
736 int i;
738 for (i = 0; i < color_pairs; i++) {
739 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
740 info->color_pair = i;
741 return;
745 if (!realloc_color_pair(&color_pair, color_pairs, 1))
746 die("Failed to alloc color pair");
748 color_pair[color_pairs] = info;
749 info->color_pair = color_pairs++;
750 init_pair(COLOR_ID(info->color_pair), fg, bg);
753 static void
754 init_colors(void)
756 int default_bg = line_info[LINE_DEFAULT].bg;
757 int default_fg = line_info[LINE_DEFAULT].fg;
758 enum line_type type;
760 start_color();
762 if (assume_default_colors(default_fg, default_bg) == ERR) {
763 default_bg = COLOR_BLACK;
764 default_fg = COLOR_WHITE;
767 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
768 struct line_info *info = &line_info[type];
770 init_line_info_color_pair(info, type, default_bg, default_fg);
773 for (type = 0; type < custom_colors; type++) {
774 struct line_info *info = &custom_color[type];
776 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
777 default_bg, default_fg);
781 struct line {
782 enum line_type type;
784 /* State flags */
785 unsigned int selected:1;
786 unsigned int dirty:1;
787 unsigned int cleareol:1;
788 unsigned int other:16;
790 void *data; /* User data */
795 * Keys
798 struct keybinding {
799 int alias;
800 enum request request;
803 static struct keybinding default_keybindings[] = {
804 /* View switching */
805 { 'm', REQ_VIEW_MAIN },
806 { 'd', REQ_VIEW_DIFF },
807 { 'l', REQ_VIEW_LOG },
808 { 't', REQ_VIEW_TREE },
809 { 'f', REQ_VIEW_BLOB },
810 { 'B', REQ_VIEW_BLAME },
811 { 'H', REQ_VIEW_BRANCH },
812 { 'p', REQ_VIEW_PAGER },
813 { 'h', REQ_VIEW_HELP },
814 { 'S', REQ_VIEW_STATUS },
815 { 'c', REQ_VIEW_STAGE },
817 /* View manipulation */
818 { 'q', REQ_VIEW_CLOSE },
819 { KEY_TAB, REQ_VIEW_NEXT },
820 { KEY_RETURN, REQ_ENTER },
821 { KEY_UP, REQ_PREVIOUS },
822 { KEY_CTL('P'), REQ_PREVIOUS },
823 { KEY_DOWN, REQ_NEXT },
824 { KEY_CTL('N'), REQ_NEXT },
825 { 'R', REQ_REFRESH },
826 { KEY_F(5), REQ_REFRESH },
827 { 'O', REQ_MAXIMIZE },
828 { ',', REQ_PARENT },
830 /* View specific */
831 { 'u', REQ_STATUS_UPDATE },
832 { '!', REQ_STATUS_REVERT },
833 { 'M', REQ_STATUS_MERGE },
834 { '1', REQ_STAGE_UPDATE_LINE },
835 { '@', REQ_STAGE_NEXT },
836 { '[', REQ_DIFF_CONTEXT_DOWN },
837 { ']', REQ_DIFF_CONTEXT_UP },
839 /* Cursor navigation */
840 { 'k', REQ_MOVE_UP },
841 { 'j', REQ_MOVE_DOWN },
842 { KEY_HOME, REQ_MOVE_FIRST_LINE },
843 { KEY_END, REQ_MOVE_LAST_LINE },
844 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
845 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
846 { ' ', REQ_MOVE_PAGE_DOWN },
847 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
848 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
849 { 'b', REQ_MOVE_PAGE_UP },
850 { '-', REQ_MOVE_PAGE_UP },
852 /* Scrolling */
853 { '|', REQ_SCROLL_FIRST_COL },
854 { KEY_LEFT, REQ_SCROLL_LEFT },
855 { KEY_RIGHT, REQ_SCROLL_RIGHT },
856 { KEY_IC, REQ_SCROLL_LINE_UP },
857 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
858 { KEY_DC, REQ_SCROLL_LINE_DOWN },
859 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
860 { 'w', REQ_SCROLL_PAGE_UP },
861 { 's', REQ_SCROLL_PAGE_DOWN },
863 /* Searching */
864 { '/', REQ_SEARCH },
865 { '?', REQ_SEARCH_BACK },
866 { 'n', REQ_FIND_NEXT },
867 { 'N', REQ_FIND_PREV },
869 /* Misc */
870 { 'Q', REQ_QUIT },
871 { 'z', REQ_STOP_LOADING },
872 { 'v', REQ_SHOW_VERSION },
873 { 'r', REQ_SCREEN_REDRAW },
874 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
875 { 'o', REQ_OPTIONS },
876 { '.', REQ_TOGGLE_LINENO },
877 { 'D', REQ_TOGGLE_DATE },
878 { 'A', REQ_TOGGLE_AUTHOR },
879 { 'g', REQ_TOGGLE_REV_GRAPH },
880 { '~', REQ_TOGGLE_GRAPHIC },
881 { '#', REQ_TOGGLE_FILENAME },
882 { 'F', REQ_TOGGLE_REFS },
883 { 'I', REQ_TOGGLE_SORT_ORDER },
884 { 'i', REQ_TOGGLE_SORT_FIELD },
885 { 'W', REQ_TOGGLE_IGNORE_SPACE },
886 { ':', REQ_PROMPT },
887 { 'e', REQ_EDIT },
890 #define KEYMAP_ENUM(_) \
891 _(KEYMAP, GENERIC), \
892 _(KEYMAP, MAIN), \
893 _(KEYMAP, DIFF), \
894 _(KEYMAP, LOG), \
895 _(KEYMAP, TREE), \
896 _(KEYMAP, BLOB), \
897 _(KEYMAP, BLAME), \
898 _(KEYMAP, BRANCH), \
899 _(KEYMAP, PAGER), \
900 _(KEYMAP, HELP), \
901 _(KEYMAP, STATUS), \
902 _(KEYMAP, STAGE)
904 DEFINE_ENUM(keymap, KEYMAP_ENUM);
906 #define set_keymap(map, name) map_enum(map, keymap_map, name)
908 struct keybinding_table {
909 struct keybinding *data;
910 size_t size;
913 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_map)];
915 static void
916 add_keybinding(enum keymap keymap, enum request request, int key)
918 struct keybinding_table *table = &keybindings[keymap];
919 size_t i;
921 for (i = 0; i < table->size; i++) {
922 if (table->data[i].alias == key) {
923 table->data[i].request = request;
924 return;
928 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
929 if (!table->data)
930 die("Failed to allocate keybinding");
931 table->data[table->size].alias = key;
932 table->data[table->size++].request = request;
934 if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
935 int i;
937 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
938 if (default_keybindings[i].alias == key)
939 default_keybindings[i].request = REQ_NONE;
943 /* Looks for a key binding first in the given map, then in the generic map, and
944 * lastly in the default keybindings. */
945 static enum request
946 get_keybinding(enum keymap keymap, int key)
948 size_t i;
950 for (i = 0; i < keybindings[keymap].size; i++)
951 if (keybindings[keymap].data[i].alias == key)
952 return keybindings[keymap].data[i].request;
954 for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
955 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
956 return keybindings[KEYMAP_GENERIC].data[i].request;
958 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
959 if (default_keybindings[i].alias == key)
960 return default_keybindings[i].request;
962 return (enum request) key;
966 struct key {
967 const char *name;
968 int value;
971 static const struct key key_table[] = {
972 { "Enter", KEY_RETURN },
973 { "Space", ' ' },
974 { "Backspace", KEY_BACKSPACE },
975 { "Tab", KEY_TAB },
976 { "Escape", KEY_ESC },
977 { "Left", KEY_LEFT },
978 { "Right", KEY_RIGHT },
979 { "Up", KEY_UP },
980 { "Down", KEY_DOWN },
981 { "Insert", KEY_IC },
982 { "Delete", KEY_DC },
983 { "Hash", '#' },
984 { "Home", KEY_HOME },
985 { "End", KEY_END },
986 { "PageUp", KEY_PPAGE },
987 { "PageDown", KEY_NPAGE },
988 { "F1", KEY_F(1) },
989 { "F2", KEY_F(2) },
990 { "F3", KEY_F(3) },
991 { "F4", KEY_F(4) },
992 { "F5", KEY_F(5) },
993 { "F6", KEY_F(6) },
994 { "F7", KEY_F(7) },
995 { "F8", KEY_F(8) },
996 { "F9", KEY_F(9) },
997 { "F10", KEY_F(10) },
998 { "F11", KEY_F(11) },
999 { "F12", KEY_F(12) },
1002 static int
1003 get_key_value(const char *name)
1005 int i;
1007 for (i = 0; i < ARRAY_SIZE(key_table); i++)
1008 if (!strcasecmp(key_table[i].name, name))
1009 return key_table[i].value;
1011 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1012 return (int)name[1] & 0x1f;
1013 if (strlen(name) == 1 && isprint(*name))
1014 return (int) *name;
1015 return ERR;
1018 static const char *
1019 get_key_name(int key_value)
1021 static char key_char[] = "'X'\0";
1022 const char *seq = NULL;
1023 int key;
1025 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1026 if (key_table[key].value == key_value)
1027 seq = key_table[key].name;
1029 if (seq == NULL && key_value < 0x7f) {
1030 char *s = key_char + 1;
1032 if (key_value >= 0x20) {
1033 *s++ = key_value;
1034 } else {
1035 *s++ = '^';
1036 *s++ = 0x40 | (key_value & 0x1f);
1038 *s++ = '\'';
1039 *s++ = '\0';
1040 seq = key_char;
1043 return seq ? seq : "(no key)";
1046 static bool
1047 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1049 const char *sep = *pos > 0 ? ", " : "";
1050 const char *keyname = get_key_name(keybinding->alias);
1052 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1055 static bool
1056 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1057 enum keymap keymap, bool all)
1059 int i;
1061 for (i = 0; i < keybindings[keymap].size; i++) {
1062 if (keybindings[keymap].data[i].request == request) {
1063 if (!append_key(buf, pos, &keybindings[keymap].data[i]))
1064 return FALSE;
1065 if (!all)
1066 break;
1070 return TRUE;
1073 #define get_view_key(view, request) get_keys((view)->keymap, request, FALSE)
1075 static const char *
1076 get_keys(enum keymap keymap, enum request request, bool all)
1078 static char buf[BUFSIZ];
1079 size_t pos = 0;
1080 int i;
1082 buf[pos] = 0;
1084 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1085 return "Too many keybindings!";
1086 if (pos > 0 && !all)
1087 return buf;
1089 if (keymap != KEYMAP_GENERIC) {
1090 /* Only the generic keymap includes the default keybindings when
1091 * listing all keys. */
1092 if (all)
1093 return buf;
1095 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
1096 return "Too many keybindings!";
1097 if (pos)
1098 return buf;
1101 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1102 if (default_keybindings[i].request == request) {
1103 if (!append_key(buf, &pos, &default_keybindings[i]))
1104 return "Too many keybindings!";
1105 if (!all)
1106 return buf;
1110 return buf;
1113 struct run_request {
1114 enum keymap keymap;
1115 int key;
1116 const char **argv;
1117 bool silent;
1120 static struct run_request *run_request;
1121 static size_t run_requests;
1123 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1125 static enum request
1126 add_run_request(enum keymap keymap, int key, const char **argv, bool silent)
1128 struct run_request *req;
1130 if (!realloc_run_requests(&run_request, run_requests, 1))
1131 return REQ_NONE;
1133 req = &run_request[run_requests];
1134 req->silent = silent;
1135 req->keymap = keymap;
1136 req->key = key;
1137 req->argv = NULL;
1139 if (!argv_copy(&req->argv, argv))
1140 return REQ_NONE;
1142 return REQ_NONE + ++run_requests;
1145 static struct run_request *
1146 get_run_request(enum request request)
1148 if (request <= REQ_NONE)
1149 return NULL;
1150 return &run_request[request - REQ_NONE - 1];
1153 static void
1154 add_builtin_run_requests(void)
1156 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1157 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1158 const char *commit[] = { "git", "commit", NULL };
1159 const char *gc[] = { "git", "gc", NULL };
1160 struct run_request reqs[] = {
1161 { KEYMAP_MAIN, 'C', cherry_pick },
1162 { KEYMAP_STATUS, 'C', commit },
1163 { KEYMAP_BRANCH, 'C', checkout },
1164 { KEYMAP_GENERIC, 'G', gc },
1166 int i;
1168 for (i = 0; i < ARRAY_SIZE(reqs); i++) {
1169 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
1171 if (req != reqs[i].key)
1172 continue;
1173 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv, FALSE);
1174 if (req != REQ_NONE)
1175 add_keybinding(reqs[i].keymap, req, reqs[i].key);
1180 * User config file handling.
1183 #define OPT_ERR_INFO \
1184 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1185 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1186 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1187 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1188 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1189 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1190 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1191 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1192 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1193 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1194 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1195 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1196 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1197 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1198 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1199 OPT_ERR_(OBSOLETE_VARIABLE_NAME, "Obsolete variable name"), \
1200 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1201 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1202 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1204 enum option_code {
1205 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1206 OPT_ERR_INFO
1207 #undef OPT_ERR_
1208 OPT_OK
1211 static const char *option_errors[] = {
1212 #define OPT_ERR_(name, msg) msg
1213 OPT_ERR_INFO
1214 #undef OPT_ERR_
1217 static const struct enum_map color_map[] = {
1218 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1219 COLOR_MAP(DEFAULT),
1220 COLOR_MAP(BLACK),
1221 COLOR_MAP(BLUE),
1222 COLOR_MAP(CYAN),
1223 COLOR_MAP(GREEN),
1224 COLOR_MAP(MAGENTA),
1225 COLOR_MAP(RED),
1226 COLOR_MAP(WHITE),
1227 COLOR_MAP(YELLOW),
1230 static const struct enum_map attr_map[] = {
1231 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1232 ATTR_MAP(NORMAL),
1233 ATTR_MAP(BLINK),
1234 ATTR_MAP(BOLD),
1235 ATTR_MAP(DIM),
1236 ATTR_MAP(REVERSE),
1237 ATTR_MAP(STANDOUT),
1238 ATTR_MAP(UNDERLINE),
1241 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1243 static enum option_code
1244 parse_step(double *opt, const char *arg)
1246 *opt = atoi(arg);
1247 if (!strchr(arg, '%'))
1248 return OPT_OK;
1250 /* "Shift down" so 100% and 1 does not conflict. */
1251 *opt = (*opt - 1) / 100;
1252 if (*opt >= 1.0) {
1253 *opt = 0.99;
1254 return OPT_ERR_INVALID_STEP_VALUE;
1256 if (*opt < 0.0) {
1257 *opt = 1;
1258 return OPT_ERR_INVALID_STEP_VALUE;
1260 return OPT_OK;
1263 static enum option_code
1264 parse_int(int *opt, const char *arg, int min, int max)
1266 int value = atoi(arg);
1268 if (min <= value && value <= max) {
1269 *opt = value;
1270 return OPT_OK;
1273 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1276 static bool
1277 set_color(int *color, const char *name)
1279 if (map_enum(color, color_map, name))
1280 return TRUE;
1281 if (!prefixcmp(name, "color"))
1282 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1283 return FALSE;
1286 /* Wants: object fgcolor bgcolor [attribute] */
1287 static enum option_code
1288 option_color_command(int argc, const char *argv[])
1290 struct line_info *info;
1292 if (argc < 3)
1293 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1295 if (*argv[0] == '"' || *argv[0] == '\'') {
1296 info = add_custom_color(argv[0]);
1297 } else {
1298 info = get_line_info(argv[0]);
1300 if (!info) {
1301 static const struct enum_map obsolete[] = {
1302 ENUM_MAP("main-delim", LINE_DELIMITER),
1303 ENUM_MAP("main-date", LINE_DATE),
1304 ENUM_MAP("main-author", LINE_AUTHOR),
1306 int index;
1308 if (!map_enum(&index, obsolete, argv[0]))
1309 return OPT_ERR_UNKNOWN_COLOR_NAME;
1310 info = &line_info[index];
1313 if (!set_color(&info->fg, argv[1]) ||
1314 !set_color(&info->bg, argv[2]))
1315 return OPT_ERR_UNKNOWN_COLOR;
1317 info->attr = 0;
1318 while (argc-- > 3) {
1319 int attr;
1321 if (!set_attribute(&attr, argv[argc]))
1322 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1323 info->attr |= attr;
1326 return OPT_OK;
1329 static enum option_code
1330 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1332 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1333 ? TRUE : FALSE;
1334 if (matched)
1335 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1336 return OPT_OK;
1339 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1341 static enum option_code
1342 parse_enum_do(unsigned int *opt, const char *arg,
1343 const struct enum_map *map, size_t map_size)
1345 bool is_true;
1347 assert(map_size > 1);
1349 if (map_enum_do(map, map_size, (int *) opt, arg))
1350 return OPT_OK;
1352 parse_bool(&is_true, arg);
1353 *opt = is_true ? map[1].value : map[0].value;
1354 return OPT_OK;
1357 #define parse_enum(opt, arg, map) \
1358 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1360 static enum option_code
1361 parse_string(char *opt, const char *arg, size_t optsize)
1363 int arglen = strlen(arg);
1365 switch (arg[0]) {
1366 case '\"':
1367 case '\'':
1368 if (arglen == 1 || arg[arglen - 1] != arg[0])
1369 return OPT_ERR_UNMATCHED_QUOTATION;
1370 arg += 1; arglen -= 2;
1371 default:
1372 string_ncopy_do(opt, optsize, arg, arglen);
1373 return OPT_OK;
1377 static enum option_code
1378 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1380 char buf[SIZEOF_STR];
1381 enum option_code code = parse_string(buf, arg, sizeof(buf));
1383 if (code == OPT_OK) {
1384 struct encoding *encoding = *encoding_ref;
1386 if (encoding && !priority)
1387 return code;
1388 encoding = encoding_open(buf);
1389 if (encoding)
1390 *encoding_ref = encoding;
1393 return code;
1396 static enum option_code
1397 parse_args(const char ***args, const char *argv[])
1399 if (*args == NULL && !argv_copy(args, argv))
1400 return OPT_ERR_OUT_OF_MEMORY;
1401 return OPT_OK;
1404 /* Wants: name = value */
1405 static enum option_code
1406 option_set_command(int argc, const char *argv[])
1408 if (argc < 3)
1409 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1411 if (strcmp(argv[1], "="))
1412 return OPT_ERR_NO_VALUE_ASSIGNED;
1414 if (!strcmp(argv[0], "blame-options"))
1415 return parse_args(&opt_blame_argv, argv + 2);
1417 if (argc != 3)
1418 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1420 if (!strcmp(argv[0], "show-author"))
1421 return parse_enum(&opt_author, argv[2], author_map);
1423 if (!strcmp(argv[0], "show-date"))
1424 return parse_enum(&opt_date, argv[2], date_map);
1426 if (!strcmp(argv[0], "show-rev-graph"))
1427 return parse_bool(&opt_rev_graph, argv[2]);
1429 if (!strcmp(argv[0], "show-refs"))
1430 return parse_bool(&opt_show_refs, argv[2]);
1432 if (!strcmp(argv[0], "show-changes"))
1433 return parse_bool(&opt_show_changes, argv[2]);
1435 if (!strcmp(argv[0], "show-notes")) {
1436 bool matched = FALSE;
1437 enum option_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1439 if (res == OPT_OK && matched) {
1440 update_notes_arg();
1441 return res;
1444 opt_notes = TRUE;
1445 strcpy(opt_notes_arg, "--show-notes=");
1446 res = parse_string(opt_notes_arg + 8, argv[2],
1447 sizeof(opt_notes_arg) - 8);
1448 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1449 opt_notes_arg[7] = '\0';
1450 return res;
1453 if (!strcmp(argv[0], "show-line-numbers"))
1454 return parse_bool(&opt_line_number, argv[2]);
1456 if (!strcmp(argv[0], "line-graphics"))
1457 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1459 if (!strcmp(argv[0], "line-number-interval"))
1460 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1462 if (!strcmp(argv[0], "author-width"))
1463 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1465 if (!strcmp(argv[0], "filename-width"))
1466 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1468 if (!strcmp(argv[0], "show-filename"))
1469 return parse_enum(&opt_filename, argv[2], filename_map);
1471 if (!strcmp(argv[0], "horizontal-scroll"))
1472 return parse_step(&opt_hscroll, argv[2]);
1474 if (!strcmp(argv[0], "split-view-height"))
1475 return parse_step(&opt_scale_split_view, argv[2]);
1477 if (!strcmp(argv[0], "tab-size"))
1478 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1480 if (!strcmp(argv[0], "diff-context")) {
1481 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1483 if (code == OPT_OK)
1484 update_diff_context_arg(opt_diff_context);
1485 return code;
1488 if (!strcmp(argv[0], "ignore-space")) {
1489 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1491 if (code == OPT_OK)
1492 update_ignore_space_arg();
1493 return code;
1496 if (!strcmp(argv[0], "commit-order")) {
1497 enum option_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1499 if (code == OPT_OK)
1500 update_commit_order_arg();
1501 return code;
1504 if (!strcmp(argv[0], "status-untracked-dirs"))
1505 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1507 if (!strcmp(argv[0], "use-git-colors"))
1508 return parse_bool(&opt_read_git_colors, argv[2]);
1510 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1513 /* Wants: mode request key */
1514 static enum option_code
1515 option_bind_command(int argc, const char *argv[])
1517 enum request request;
1518 int keymap = -1;
1519 int key;
1521 if (argc < 3)
1522 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1524 if (!set_keymap(&keymap, argv[0]))
1525 return OPT_ERR_UNKNOWN_KEY_MAP;
1527 key = get_key_value(argv[1]);
1528 if (key == ERR)
1529 return OPT_ERR_UNKNOWN_KEY;
1531 request = get_request(argv[2]);
1532 if (request == REQ_UNKNOWN) {
1533 static const struct enum_map obsolete[] = {
1534 ENUM_MAP("cherry-pick", REQ_NONE),
1535 ENUM_MAP("screen-resize", REQ_NONE),
1536 ENUM_MAP("tree-parent", REQ_PARENT),
1538 int alias;
1540 if (map_enum(&alias, obsolete, argv[2])) {
1541 if (alias != REQ_NONE)
1542 add_keybinding(keymap, alias, key);
1543 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1546 if (request == REQ_UNKNOWN && *argv[2]++ == '!') {
1547 bool silent = *argv[2] == '@';
1549 if (silent)
1550 argv[2]++;
1551 request = add_run_request(keymap, key, argv + 2, silent);
1553 if (request == REQ_UNKNOWN)
1554 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1556 add_keybinding(keymap, request, key);
1558 return OPT_OK;
1562 static enum option_code load_option_file(const char *path);
1564 static enum option_code
1565 option_source_command(int argc, const char *argv[])
1567 if (argc < 1)
1568 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1570 return load_option_file(argv[0]);
1573 static enum option_code
1574 set_option(const char *opt, char *value)
1576 const char *argv[SIZEOF_ARG];
1577 int argc = 0;
1579 if (!argv_from_string(argv, &argc, value))
1580 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1582 if (!strcmp(opt, "color"))
1583 return option_color_command(argc, argv);
1585 if (!strcmp(opt, "set"))
1586 return option_set_command(argc, argv);
1588 if (!strcmp(opt, "bind"))
1589 return option_bind_command(argc, argv);
1591 if (!strcmp(opt, "source"))
1592 return option_source_command(argc, argv);
1594 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1597 struct config_state {
1598 const char *path;
1599 int lineno;
1600 bool errors;
1603 static int
1604 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1606 struct config_state *config = data;
1607 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1609 config->lineno++;
1611 /* Check for comment markers, since read_properties() will
1612 * only ensure opt and value are split at first " \t". */
1613 optlen = strcspn(opt, "#");
1614 if (optlen == 0)
1615 return OK;
1617 if (opt[optlen] == 0) {
1618 /* Look for comment endings in the value. */
1619 size_t len = strcspn(value, "#");
1621 if (len < valuelen) {
1622 valuelen = len;
1623 value[valuelen] = 0;
1626 status = set_option(opt, value);
1629 if (status != OPT_OK) {
1630 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1631 option_errors[status], (int) optlen, opt);
1632 config->errors = TRUE;
1635 /* Always keep going if errors are encountered. */
1636 return OK;
1639 static enum option_code
1640 load_option_file(const char *path)
1642 struct config_state config = { path, 0, FALSE };
1643 struct io io;
1645 /* Do not read configuration from stdin if set to "" */
1646 if (!path || !strlen(path))
1647 return OPT_OK;
1649 /* It's OK that the file doesn't exist. */
1650 if (!io_open(&io, "%s", path))
1651 return OPT_ERR_FILE_DOES_NOT_EXIST;
1653 if (io_load(&io, " \t", read_option, &config) == ERR ||
1654 config.errors == TRUE)
1655 warn("Errors while loading %s.", path);
1656 return OPT_OK;
1659 static int
1660 load_options(void)
1662 const char *home = getenv("HOME");
1663 const char *tigrc_user = getenv("TIGRC_USER");
1664 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1665 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1666 char buf[SIZEOF_STR];
1668 if (!tigrc_system)
1669 tigrc_system = SYSCONFDIR "/tigrc";
1670 load_option_file(tigrc_system);
1672 if (!tigrc_user) {
1673 if (!home || !string_format(buf, "%s/.tigrc", home))
1674 return ERR;
1675 tigrc_user = buf;
1677 load_option_file(tigrc_user);
1679 /* Add _after_ loading config files to avoid adding run requests
1680 * that conflict with keybindings. */
1681 add_builtin_run_requests();
1683 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1684 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1685 int argc = 0;
1687 if (!string_format(buf, "%s", tig_diff_opts) ||
1688 !argv_from_string(diff_opts, &argc, buf))
1689 die("TIG_DIFF_OPTS contains too many arguments");
1690 else if (!argv_copy(&opt_diff_argv, diff_opts))
1691 die("Failed to format TIG_DIFF_OPTS arguments");
1694 return OK;
1699 * The viewer
1702 struct view;
1703 struct view_ops;
1705 /* The display array of active views and the index of the current view. */
1706 static struct view *display[2];
1707 static WINDOW *display_win[2];
1708 static WINDOW *display_title[2];
1709 static unsigned int current_view;
1711 #define foreach_displayed_view(view, i) \
1712 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1714 #define displayed_views() (display[1] != NULL ? 2 : 1)
1716 /* Current head and commit ID */
1717 static char ref_blob[SIZEOF_REF] = "";
1718 static char ref_commit[SIZEOF_REF] = "HEAD";
1719 static char ref_head[SIZEOF_REF] = "HEAD";
1720 static char ref_branch[SIZEOF_REF] = "";
1722 enum view_flag {
1723 VIEW_NO_FLAGS = 0,
1724 VIEW_ALWAYS_LINENO = 1 << 0,
1725 VIEW_CUSTOM_STATUS = 1 << 1,
1726 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1727 VIEW_ADD_PAGER_REFS = 1 << 3,
1728 VIEW_OPEN_DIFF = 1 << 4,
1729 VIEW_NO_REF = 1 << 5,
1730 VIEW_NO_GIT_DIR = 1 << 6,
1731 VIEW_DIFF_LIKE = 1 << 7,
1734 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1736 struct position {
1737 unsigned long offset; /* Offset of the window top */
1738 unsigned long col; /* Offset from the window side. */
1739 unsigned long lineno; /* Current line number */
1742 struct view {
1743 const char *name; /* View name */
1744 const char *id; /* Points to either of ref_{head,commit,blob} */
1746 struct view_ops *ops; /* View operations */
1748 enum keymap keymap; /* What keymap does this view have */
1750 char ref[SIZEOF_REF]; /* Hovered commit reference */
1751 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1753 int height, width; /* The width and height of the main window */
1754 WINDOW *win; /* The main window */
1756 /* Navigation */
1757 struct position pos; /* Current position. */
1758 struct position prev_pos; /* Previous position. */
1760 /* Searching */
1761 char grep[SIZEOF_STR]; /* Search string */
1762 regex_t *regex; /* Pre-compiled regexp */
1764 /* If non-NULL, points to the view that opened this view. If this view
1765 * is closed tig will switch back to the parent view. */
1766 struct view *parent;
1767 struct view *prev;
1769 /* Buffering */
1770 size_t lines; /* Total number of lines */
1771 struct line *line; /* Line index */
1772 unsigned int digits; /* Number of digits in the lines member. */
1774 /* Drawing */
1775 struct line *curline; /* Line currently being drawn. */
1776 enum line_type curtype; /* Attribute currently used for drawing. */
1777 unsigned long col; /* Column when drawing. */
1778 bool has_scrolled; /* View was scrolled. */
1780 /* Loading */
1781 const char **argv; /* Shell command arguments. */
1782 const char *dir; /* Directory from which to execute. */
1783 struct io io;
1784 struct io *pipe;
1785 time_t start_time;
1786 time_t update_secs;
1787 struct encoding *encoding;
1789 /* Private data */
1790 void *private;
1793 enum open_flags {
1794 OPEN_DEFAULT = 0, /* Use default view switching. */
1795 OPEN_SPLIT = 1, /* Split current view. */
1796 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1797 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1798 OPEN_PREPARED = 32, /* Open already prepared command. */
1799 OPEN_EXTRA = 64, /* Open extra data from command. */
1802 struct view_ops {
1803 /* What type of content being displayed. Used in the title bar. */
1804 const char *type;
1805 /* Flags to control the view behavior. */
1806 enum view_flag flags;
1807 /* Size of private data. */
1808 size_t private_size;
1809 /* Open and reads in all view content. */
1810 bool (*open)(struct view *view, enum open_flags flags);
1811 /* Read one line; updates view->line. */
1812 bool (*read)(struct view *view, char *data);
1813 /* Draw one line; @lineno must be < view->height. */
1814 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1815 /* Depending on view handle a special requests. */
1816 enum request (*request)(struct view *view, enum request request, struct line *line);
1817 /* Search for regexp in a line. */
1818 bool (*grep)(struct view *view, struct line *line);
1819 /* Select line */
1820 void (*select)(struct view *view, struct line *line);
1823 #define VIEW_OPS(id, name, ref) name##_ops
1824 static struct view_ops VIEW_INFO(VIEW_OPS);
1826 static struct view views[] = {
1827 #define VIEW_DATA(id, name, ref) \
1828 { #name, ref, &name##_ops, KEYMAP_##id }
1829 VIEW_INFO(VIEW_DATA)
1832 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1834 #define foreach_view(view, i) \
1835 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1837 #define view_is_displayed(view) \
1838 (view == display[0] || view == display[1])
1840 static enum request
1841 view_request(struct view *view, enum request request)
1843 if (!view || !view->lines)
1844 return request;
1845 return view->ops->request(view, request, &view->line[view->pos.lineno]);
1850 * View drawing.
1853 static inline void
1854 set_view_attr(struct view *view, enum line_type type)
1856 if (!view->curline->selected && view->curtype != type) {
1857 (void) wattrset(view->win, get_line_attr(type));
1858 wchgat(view->win, -1, 0, get_line_color(type), NULL);
1859 view->curtype = type;
1863 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
1865 static bool
1866 draw_chars(struct view *view, enum line_type type, const char *string,
1867 int max_len, bool use_tilde)
1869 static char out_buffer[BUFSIZ * 2];
1870 int len = 0;
1871 int col = 0;
1872 int trimmed = FALSE;
1873 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1875 if (max_len <= 0)
1876 return VIEW_MAX_LEN(view) <= 0;
1878 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1880 set_view_attr(view, type);
1881 if (len > 0) {
1882 if (opt_iconv_out != ICONV_NONE) {
1883 size_t inlen = len + 1;
1884 char *instr = calloc(1, inlen);
1885 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1886 if (!instr)
1887 return VIEW_MAX_LEN(view) <= 0;
1889 strncpy(instr, string, len);
1891 char *outbuf = out_buffer;
1892 size_t outlen = sizeof(out_buffer);
1894 size_t ret;
1896 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1897 if (ret != (size_t) -1) {
1898 string = out_buffer;
1899 len = sizeof(out_buffer) - outlen;
1901 free(instr);
1904 waddnstr(view->win, string, len);
1906 if (trimmed && use_tilde) {
1907 set_view_attr(view, LINE_DELIMITER);
1908 waddch(view->win, '~');
1909 col++;
1913 view->col += col;
1914 return VIEW_MAX_LEN(view) <= 0;
1917 static bool
1918 draw_space(struct view *view, enum line_type type, int max, int spaces)
1920 static char space[] = " ";
1922 spaces = MIN(max, spaces);
1924 while (spaces > 0) {
1925 int len = MIN(spaces, sizeof(space) - 1);
1927 if (draw_chars(view, type, space, len, FALSE))
1928 return TRUE;
1929 spaces -= len;
1932 return VIEW_MAX_LEN(view) <= 0;
1935 static bool
1936 draw_text(struct view *view, enum line_type type, const char *string)
1938 char text[SIZEOF_STR];
1940 do {
1941 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1943 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1944 return TRUE;
1945 string += pos;
1946 } while (*string);
1948 return VIEW_MAX_LEN(view) <= 0;
1951 static bool
1952 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
1954 char text[SIZEOF_STR];
1955 int retval;
1957 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
1958 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
1961 static bool
1962 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1964 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1965 int max = VIEW_MAX_LEN(view);
1966 int i;
1968 if (max < size)
1969 size = max;
1971 set_view_attr(view, type);
1972 /* Using waddch() instead of waddnstr() ensures that
1973 * they'll be rendered correctly for the cursor line. */
1974 for (i = skip; i < size; i++)
1975 waddch(view->win, graphic[i]);
1977 view->col += size;
1978 if (separator) {
1979 if (size < max && skip <= size)
1980 waddch(view->win, ' ');
1981 view->col++;
1984 return VIEW_MAX_LEN(view) <= 0;
1987 static bool
1988 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1990 int max = MIN(VIEW_MAX_LEN(view), len);
1991 int col = view->col;
1993 if (!text)
1994 return draw_space(view, type, max, max);
1996 return draw_chars(view, type, text, max - 1, trim)
1997 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2000 static bool
2001 draw_date(struct view *view, struct time *time)
2003 const char *date = mkdate(time, opt_date);
2004 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
2006 if (opt_date == DATE_NO)
2007 return FALSE;
2009 return draw_field(view, LINE_DATE, date, cols, FALSE);
2012 static bool
2013 draw_author(struct view *view, const char *author)
2015 bool trim = author_trim(opt_author_cols);
2016 const char *text = mkauthor(author, opt_author_cols, opt_author);
2018 if (opt_author == AUTHOR_NO)
2019 return FALSE;
2021 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
2024 static bool
2025 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2027 bool trim = filename && strlen(filename) >= opt_filename_cols;
2029 if (opt_filename == FILENAME_NO)
2030 return FALSE;
2032 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2033 return FALSE;
2035 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
2038 static bool
2039 draw_mode(struct view *view, mode_t mode)
2041 const char *str = mkmode(mode);
2043 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
2046 static bool
2047 draw_lineno(struct view *view, unsigned int lineno)
2049 char number[10];
2050 int digits3 = view->digits < 3 ? 3 : view->digits;
2051 int max = MIN(VIEW_MAX_LEN(view), digits3);
2052 char *text = NULL;
2053 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2055 if (!opt_line_number)
2056 return FALSE;
2058 lineno += view->pos.offset + 1;
2059 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2060 static char fmt[] = "%1ld";
2062 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2063 if (string_format(number, fmt, lineno))
2064 text = number;
2066 if (text)
2067 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2068 else
2069 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2070 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2073 static bool
2074 draw_refs(struct view *view, struct ref_list *refs)
2076 size_t i;
2078 if (!opt_show_refs || !refs)
2079 return FALSE;
2081 for (i = 0; i < refs->size; i++) {
2082 struct ref *ref = refs->refs[i];
2083 enum line_type type = get_line_type_from_ref(ref);
2085 if (draw_formatted(view, type, "[%s]", ref->name))
2086 return TRUE;
2088 if (draw_text(view, LINE_DEFAULT, " "))
2089 return TRUE;
2092 return FALSE;
2095 static bool
2096 draw_view_line(struct view *view, unsigned int lineno)
2098 struct line *line;
2099 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2101 assert(view_is_displayed(view));
2103 if (view->pos.offset + lineno >= view->lines)
2104 return FALSE;
2106 line = &view->line[view->pos.offset + lineno];
2108 wmove(view->win, lineno, 0);
2109 if (line->cleareol)
2110 wclrtoeol(view->win);
2111 view->col = 0;
2112 view->curline = line;
2113 view->curtype = LINE_NONE;
2114 line->selected = FALSE;
2115 line->dirty = line->cleareol = 0;
2117 if (selected) {
2118 set_view_attr(view, LINE_CURSOR);
2119 line->selected = TRUE;
2120 view->ops->select(view, line);
2123 return view->ops->draw(view, line, lineno);
2126 static void
2127 redraw_view_dirty(struct view *view)
2129 bool dirty = FALSE;
2130 int lineno;
2132 for (lineno = 0; lineno < view->height; lineno++) {
2133 if (view->pos.offset + lineno >= view->lines)
2134 break;
2135 if (!view->line[view->pos.offset + lineno].dirty)
2136 continue;
2137 dirty = TRUE;
2138 if (!draw_view_line(view, lineno))
2139 break;
2142 if (!dirty)
2143 return;
2144 wnoutrefresh(view->win);
2147 static void
2148 redraw_view_from(struct view *view, int lineno)
2150 assert(0 <= lineno && lineno < view->height);
2152 for (; lineno < view->height; lineno++) {
2153 if (!draw_view_line(view, lineno))
2154 break;
2157 wnoutrefresh(view->win);
2160 static void
2161 redraw_view(struct view *view)
2163 werase(view->win);
2164 redraw_view_from(view, 0);
2168 static void
2169 update_view_title(struct view *view)
2171 char buf[SIZEOF_STR];
2172 char state[SIZEOF_STR];
2173 size_t bufpos = 0, statelen = 0;
2174 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2176 assert(view_is_displayed(view));
2178 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view->lines) {
2179 unsigned int view_lines = view->pos.offset + view->height;
2180 unsigned int lines = view->lines
2181 ? MIN(view_lines, view->lines) * 100 / view->lines
2182 : 0;
2184 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
2185 view->ops->type,
2186 view->pos.lineno + 1,
2187 view->lines,
2188 lines);
2192 if (view->pipe) {
2193 time_t secs = time(NULL) - view->start_time;
2195 /* Three git seconds are a long time ... */
2196 if (secs > 2)
2197 string_format_from(state, &statelen, " loading %lds", secs);
2200 string_format_from(buf, &bufpos, "[%s]", view->name);
2201 if (*view->ref && bufpos < view->width) {
2202 size_t refsize = strlen(view->ref);
2203 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2205 if (minsize < view->width)
2206 refsize = view->width - minsize + 7;
2207 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2210 if (statelen && bufpos < view->width) {
2211 string_format_from(buf, &bufpos, "%s", state);
2214 if (view == display[current_view])
2215 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2216 else
2217 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2219 mvwaddnstr(window, 0, 0, buf, bufpos);
2220 wclrtoeol(window);
2221 wnoutrefresh(window);
2224 static int
2225 apply_step(double step, int value)
2227 if (step >= 1)
2228 return (int) step;
2229 value *= step + 0.01;
2230 return value ? value : 1;
2233 static void
2234 resize_display(void)
2236 int offset, i;
2237 struct view *base = display[0];
2238 struct view *view = display[1] ? display[1] : display[0];
2240 /* Setup window dimensions */
2242 getmaxyx(stdscr, base->height, base->width);
2244 /* Make room for the status window. */
2245 base->height -= 1;
2247 if (view != base) {
2248 /* Horizontal split. */
2249 view->width = base->width;
2250 view->height = apply_step(opt_scale_split_view, base->height);
2251 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2252 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2253 base->height -= view->height;
2255 /* Make room for the title bar. */
2256 view->height -= 1;
2259 /* Make room for the title bar. */
2260 base->height -= 1;
2262 offset = 0;
2264 foreach_displayed_view (view, i) {
2265 if (!display_win[i]) {
2266 display_win[i] = newwin(view->height, view->width, offset, 0);
2267 if (!display_win[i])
2268 die("Failed to create %s view", view->name);
2270 scrollok(display_win[i], FALSE);
2272 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2273 if (!display_title[i])
2274 die("Failed to create title window");
2276 } else {
2277 wresize(display_win[i], view->height, view->width);
2278 mvwin(display_win[i], offset, 0);
2279 mvwin(display_title[i], offset + view->height, 0);
2282 view->win = display_win[i];
2284 offset += view->height + 1;
2288 static void
2289 redraw_display(bool clear)
2291 struct view *view;
2292 int i;
2294 foreach_displayed_view (view, i) {
2295 if (clear)
2296 wclear(view->win);
2297 redraw_view(view);
2298 update_view_title(view);
2304 * Option management
2307 #define TOGGLE_MENU \
2308 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2309 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2310 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2311 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2312 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2313 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2314 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2315 TOGGLE_(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map) \
2316 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL) \
2317 TOGGLE_(CHANGES, 'C', "local change display", &opt_show_changes, NULL)
2319 static bool
2320 toggle_option(enum request request)
2322 const struct {
2323 enum request request;
2324 const struct enum_map *map;
2325 size_t map_size;
2326 } data[] = {
2327 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2328 TOGGLE_MENU
2329 #undef TOGGLE_
2331 const struct menu_item menu[] = {
2332 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2333 TOGGLE_MENU
2334 #undef TOGGLE_
2335 { 0 }
2337 int i = 0;
2339 if (request == REQ_OPTIONS) {
2340 if (!prompt_menu("Toggle option", menu, &i))
2341 return FALSE;
2342 } else {
2343 while (i < ARRAY_SIZE(data) && data[i].request != request)
2344 i++;
2345 if (i >= ARRAY_SIZE(data))
2346 die("Invalid request (%d)", request);
2349 if (data[i].map != NULL) {
2350 unsigned int *opt = menu[i].data;
2352 *opt = (*opt + 1) % data[i].map_size;
2353 if (data[i].map == ignore_space_map) {
2354 update_ignore_space_arg();
2355 report("Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2356 return TRUE;
2358 } else if (data[i].map == commit_order_map) {
2359 update_commit_order_arg();
2360 report("Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2361 return TRUE;
2364 redraw_display(FALSE);
2365 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2367 } else {
2368 bool *option = menu[i].data;
2370 *option = !*option;
2371 redraw_display(FALSE);
2372 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2375 return FALSE;
2378 static void
2379 maximize_view(struct view *view, bool redraw)
2381 memset(display, 0, sizeof(display));
2382 current_view = 0;
2383 display[current_view] = view;
2384 resize_display();
2385 if (redraw) {
2386 redraw_display(FALSE);
2387 report("");
2393 * Navigation
2396 static bool
2397 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2399 if (lineno >= view->lines)
2400 lineno = view->lines > 0 ? view->lines - 1 : 0;
2402 if (offset > lineno || offset + view->height <= lineno) {
2403 unsigned long half = view->height / 2;
2405 if (lineno > half)
2406 offset = lineno - half;
2407 else
2408 offset = 0;
2411 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2412 view->pos.offset = offset;
2413 view->pos.lineno = lineno;
2414 return TRUE;
2417 return FALSE;
2420 /* Scrolling backend */
2421 static void
2422 do_scroll_view(struct view *view, int lines)
2424 bool redraw_current_line = FALSE;
2426 /* The rendering expects the new offset. */
2427 view->pos.offset += lines;
2429 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2430 assert(lines);
2432 /* Move current line into the view. */
2433 if (view->pos.lineno < view->pos.offset) {
2434 view->pos.lineno = view->pos.offset;
2435 redraw_current_line = TRUE;
2436 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2437 view->pos.lineno = view->pos.offset + view->height - 1;
2438 redraw_current_line = TRUE;
2441 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2443 /* Redraw the whole screen if scrolling is pointless. */
2444 if (view->height < ABS(lines)) {
2445 redraw_view(view);
2447 } else {
2448 int line = lines > 0 ? view->height - lines : 0;
2449 int end = line + ABS(lines);
2451 scrollok(view->win, TRUE);
2452 wscrl(view->win, lines);
2453 scrollok(view->win, FALSE);
2455 while (line < end && draw_view_line(view, line))
2456 line++;
2458 if (redraw_current_line)
2459 draw_view_line(view, view->pos.lineno - view->pos.offset);
2460 wnoutrefresh(view->win);
2463 view->has_scrolled = TRUE;
2464 report("");
2467 /* Scroll frontend */
2468 static void
2469 scroll_view(struct view *view, enum request request)
2471 int lines = 1;
2473 assert(view_is_displayed(view));
2475 switch (request) {
2476 case REQ_SCROLL_FIRST_COL:
2477 view->pos.col = 0;
2478 redraw_view_from(view, 0);
2479 report("");
2480 return;
2481 case REQ_SCROLL_LEFT:
2482 if (view->pos.col == 0) {
2483 report("Cannot scroll beyond the first column");
2484 return;
2486 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2487 view->pos.col = 0;
2488 else
2489 view->pos.col -= apply_step(opt_hscroll, view->width);
2490 redraw_view_from(view, 0);
2491 report("");
2492 return;
2493 case REQ_SCROLL_RIGHT:
2494 view->pos.col += apply_step(opt_hscroll, view->width);
2495 redraw_view(view);
2496 report("");
2497 return;
2498 case REQ_SCROLL_PAGE_DOWN:
2499 lines = view->height;
2500 case REQ_SCROLL_LINE_DOWN:
2501 if (view->pos.offset + lines > view->lines)
2502 lines = view->lines - view->pos.offset;
2504 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2505 report("Cannot scroll beyond the last line");
2506 return;
2508 break;
2510 case REQ_SCROLL_PAGE_UP:
2511 lines = view->height;
2512 case REQ_SCROLL_LINE_UP:
2513 if (lines > view->pos.offset)
2514 lines = view->pos.offset;
2516 if (lines == 0) {
2517 report("Cannot scroll beyond the first line");
2518 return;
2521 lines = -lines;
2522 break;
2524 default:
2525 die("request %d not handled in switch", request);
2528 do_scroll_view(view, lines);
2531 /* Cursor moving */
2532 static void
2533 move_view(struct view *view, enum request request)
2535 int scroll_steps = 0;
2536 int steps;
2538 switch (request) {
2539 case REQ_MOVE_FIRST_LINE:
2540 steps = -view->pos.lineno;
2541 break;
2543 case REQ_MOVE_LAST_LINE:
2544 steps = view->lines - view->pos.lineno - 1;
2545 break;
2547 case REQ_MOVE_PAGE_UP:
2548 steps = view->height > view->pos.lineno
2549 ? -view->pos.lineno : -view->height;
2550 break;
2552 case REQ_MOVE_PAGE_DOWN:
2553 steps = view->pos.lineno + view->height >= view->lines
2554 ? view->lines - view->pos.lineno - 1 : view->height;
2555 break;
2557 case REQ_MOVE_UP:
2558 case REQ_PREVIOUS:
2559 steps = -1;
2560 break;
2562 case REQ_MOVE_DOWN:
2563 case REQ_NEXT:
2564 steps = 1;
2565 break;
2567 default:
2568 die("request %d not handled in switch", request);
2571 if (steps <= 0 && view->pos.lineno == 0) {
2572 report("Cannot move beyond the first line");
2573 return;
2575 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2576 report("Cannot move beyond the last line");
2577 return;
2580 /* Move the current line */
2581 view->pos.lineno += steps;
2582 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2584 /* Check whether the view needs to be scrolled */
2585 if (view->pos.lineno < view->pos.offset ||
2586 view->pos.lineno >= view->pos.offset + view->height) {
2587 scroll_steps = steps;
2588 if (steps < 0 && -steps > view->pos.offset) {
2589 scroll_steps = -view->pos.offset;
2591 } else if (steps > 0) {
2592 if (view->pos.lineno == view->lines - 1 &&
2593 view->lines > view->height) {
2594 scroll_steps = view->lines - view->pos.offset - 1;
2595 if (scroll_steps >= view->height)
2596 scroll_steps -= view->height - 1;
2601 if (!view_is_displayed(view)) {
2602 view->pos.offset += scroll_steps;
2603 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2604 view->ops->select(view, &view->line[view->pos.lineno]);
2605 return;
2608 /* Repaint the old "current" line if we be scrolling */
2609 if (ABS(steps) < view->height)
2610 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2612 if (scroll_steps) {
2613 do_scroll_view(view, scroll_steps);
2614 return;
2617 /* Draw the current line */
2618 draw_view_line(view, view->pos.lineno - view->pos.offset);
2620 wnoutrefresh(view->win);
2621 report("");
2626 * Searching
2629 static void search_view(struct view *view, enum request request);
2631 static bool
2632 grep_text(struct view *view, const char *text[])
2634 regmatch_t pmatch;
2635 size_t i;
2637 for (i = 0; text[i]; i++)
2638 if (*text[i] &&
2639 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2640 return TRUE;
2641 return FALSE;
2644 static void
2645 select_view_line(struct view *view, unsigned long lineno)
2647 struct position old = view->pos;
2649 if (goto_view_line(view, view->pos.offset, lineno)) {
2650 if (view_is_displayed(view)) {
2651 if (old.offset != view->pos.offset) {
2652 redraw_view(view);
2653 } else {
2654 draw_view_line(view, old.lineno - view->pos.offset);
2655 draw_view_line(view, view->pos.lineno - view->pos.offset);
2656 wnoutrefresh(view->win);
2658 } else {
2659 view->ops->select(view, &view->line[view->pos.lineno]);
2664 static void
2665 find_next(struct view *view, enum request request)
2667 unsigned long lineno = view->pos.lineno;
2668 int direction;
2670 if (!*view->grep) {
2671 if (!*opt_search)
2672 report("No previous search");
2673 else
2674 search_view(view, request);
2675 return;
2678 switch (request) {
2679 case REQ_SEARCH:
2680 case REQ_FIND_NEXT:
2681 direction = 1;
2682 break;
2684 case REQ_SEARCH_BACK:
2685 case REQ_FIND_PREV:
2686 direction = -1;
2687 break;
2689 default:
2690 return;
2693 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2694 lineno += direction;
2696 /* Note, lineno is unsigned long so will wrap around in which case it
2697 * will become bigger than view->lines. */
2698 for (; lineno < view->lines; lineno += direction) {
2699 if (view->ops->grep(view, &view->line[lineno])) {
2700 select_view_line(view, lineno);
2701 report("Line %ld matches '%s'", lineno + 1, view->grep);
2702 return;
2706 report("No match found for '%s'", view->grep);
2709 static void
2710 search_view(struct view *view, enum request request)
2712 int regex_err;
2714 if (view->regex) {
2715 regfree(view->regex);
2716 *view->grep = 0;
2717 } else {
2718 view->regex = calloc(1, sizeof(*view->regex));
2719 if (!view->regex)
2720 return;
2723 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2724 if (regex_err != 0) {
2725 char buf[SIZEOF_STR] = "unknown error";
2727 regerror(regex_err, view->regex, buf, sizeof(buf));
2728 report("Search failed: %s", buf);
2729 return;
2732 string_copy(view->grep, opt_search);
2734 find_next(view, request);
2738 * Incremental updating
2741 static inline bool
2742 check_position(struct position *pos)
2744 return pos->lineno || pos->col || pos->offset;
2747 static inline void
2748 clear_position(struct position *pos)
2750 memset(pos, 0, sizeof(*pos));
2753 static void
2754 reset_view(struct view *view)
2756 int i;
2758 for (i = 0; i < view->lines; i++)
2759 free(view->line[i].data);
2760 free(view->line);
2762 view->prev_pos = view->pos;
2763 clear_position(&view->pos);
2765 view->line = NULL;
2766 view->lines = 0;
2767 view->vid[0] = 0;
2768 view->update_secs = 0;
2771 static const char *
2772 format_arg(const char *name)
2774 static struct {
2775 const char *name;
2776 size_t namelen;
2777 const char *value;
2778 const char *value_if_empty;
2779 } vars[] = {
2780 #define FORMAT_VAR(name, value, value_if_empty) \
2781 { name, STRING_SIZE(name), value, value_if_empty }
2782 FORMAT_VAR("%(directory)", opt_path, "."),
2783 FORMAT_VAR("%(file)", opt_file, ""),
2784 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2785 FORMAT_VAR("%(head)", ref_head, ""),
2786 FORMAT_VAR("%(commit)", ref_commit, ""),
2787 FORMAT_VAR("%(blob)", ref_blob, ""),
2788 FORMAT_VAR("%(branch)", ref_branch, ""),
2790 int i;
2792 if (!prefixcmp(name, "%(prompt"))
2793 return read_prompt("Command argument: ");
2795 for (i = 0; i < ARRAY_SIZE(vars); i++)
2796 if (!strncmp(name, vars[i].name, vars[i].namelen))
2797 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2799 report("Unknown replacement: `%s`", name);
2800 return NULL;
2803 static bool
2804 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2806 char buf[SIZEOF_STR];
2807 int argc;
2809 argv_free(*dst_argv);
2811 for (argc = 0; src_argv[argc]; argc++) {
2812 const char *arg = src_argv[argc];
2813 size_t bufpos = 0;
2815 if (!strcmp(arg, "%(fileargs)")) {
2816 if (!argv_append_array(dst_argv, opt_file_argv))
2817 break;
2818 continue;
2820 } else if (!strcmp(arg, "%(diffargs)")) {
2821 if (!argv_append_array(dst_argv, opt_diff_argv))
2822 break;
2823 continue;
2825 } else if (!strcmp(arg, "%(blameargs)")) {
2826 if (!argv_append_array(dst_argv, opt_blame_argv))
2827 break;
2828 continue;
2830 } else if (!strcmp(arg, "%(revargs)") ||
2831 (first && !strcmp(arg, "%(commit)"))) {
2832 if (!argv_append_array(dst_argv, opt_rev_argv))
2833 break;
2834 continue;
2837 while (arg) {
2838 char *next = strstr(arg, "%(");
2839 int len = next - arg;
2840 const char *value;
2842 if (!next) {
2843 len = strlen(arg);
2844 value = "";
2846 } else {
2847 value = format_arg(next);
2849 if (!value) {
2850 return FALSE;
2854 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2855 return FALSE;
2857 arg = next ? strchr(next, ')') + 1 : NULL;
2860 if (!argv_append(dst_argv, buf))
2861 break;
2864 return src_argv[argc] == NULL;
2867 static bool
2868 restore_view_position(struct view *view)
2870 /* A view without a previous view is the first view */
2871 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2872 select_view_line(view, opt_lineno - 1);
2873 opt_lineno = 0;
2876 /* Ensure that the view position is in a valid state. */
2877 if (!check_position(&view->prev_pos) ||
2878 (view->pipe && view->lines <= view->prev_pos.lineno))
2879 return goto_view_line(view, view->pos.offset, view->pos.lineno);
2881 /* Changing the view position cancels the restoring. */
2882 /* FIXME: Changing back to the first line is not detected. */
2883 if (check_position(&view->pos)) {
2884 clear_position(&view->prev_pos);
2885 return FALSE;
2888 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
2889 view_is_displayed(view))
2890 werase(view->win);
2892 view->pos.col = view->prev_pos.col;
2893 clear_position(&view->prev_pos);
2895 return TRUE;
2898 static void
2899 end_update(struct view *view, bool force)
2901 if (!view->pipe)
2902 return;
2903 while (!view->ops->read(view, NULL))
2904 if (!force)
2905 return;
2906 if (force)
2907 io_kill(view->pipe);
2908 io_done(view->pipe);
2909 view->pipe = NULL;
2912 static void
2913 setup_update(struct view *view, const char *vid)
2915 reset_view(view);
2916 string_copy_rev(view->vid, vid);
2917 view->pipe = &view->io;
2918 view->start_time = time(NULL);
2921 static bool
2922 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2924 bool extra = !!(flags & (OPEN_EXTRA));
2925 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2926 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2928 if (!reload && !strcmp(view->vid, view->id))
2929 return TRUE;
2931 if (view->pipe) {
2932 if (extra)
2933 io_done(view->pipe);
2934 else
2935 end_update(view, TRUE);
2938 if (!refresh && argv) {
2939 view->dir = dir;
2940 if (!format_argv(&view->argv, argv, !view->prev))
2941 return FALSE;
2943 /* Put the current ref_* value to the view title ref
2944 * member. This is needed by the blob view. Most other
2945 * views sets it automatically after loading because the
2946 * first line is a commit line. */
2947 string_copy_rev(view->ref, view->id);
2950 if (view->argv && view->argv[0] &&
2951 !io_run(&view->io, IO_RD, view->dir, view->argv))
2952 return FALSE;
2954 if (!extra)
2955 setup_update(view, view->id);
2957 return TRUE;
2960 static bool
2961 update_view(struct view *view)
2963 char *line;
2964 /* Clear the view and redraw everything since the tree sorting
2965 * might have rearranged things. */
2966 bool redraw = view->lines == 0;
2967 bool can_read = TRUE;
2969 if (!view->pipe)
2970 return TRUE;
2972 if (!io_can_read(view->pipe, FALSE)) {
2973 if (view->lines == 0 && view_is_displayed(view)) {
2974 time_t secs = time(NULL) - view->start_time;
2976 if (secs > 1 && secs > view->update_secs) {
2977 if (view->update_secs == 0)
2978 redraw_view(view);
2979 update_view_title(view);
2980 view->update_secs = secs;
2983 return TRUE;
2986 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2987 if (view->encoding) {
2988 line = encoding_convert(view->encoding, line);
2991 if (!view->ops->read(view, line)) {
2992 report("Allocation failure");
2993 end_update(view, TRUE);
2994 return FALSE;
2999 unsigned long lines = view->lines;
3000 int digits;
3002 for (digits = 0; lines; digits++)
3003 lines /= 10;
3005 /* Keep the displayed view in sync with line number scaling. */
3006 if (digits != view->digits) {
3007 view->digits = digits;
3008 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3009 redraw = TRUE;
3013 if (io_error(view->pipe)) {
3014 report("Failed to read: %s", io_strerror(view->pipe));
3015 end_update(view, TRUE);
3017 } else if (io_eof(view->pipe)) {
3018 if (view_is_displayed(view))
3019 report("");
3020 end_update(view, FALSE);
3023 if (restore_view_position(view))
3024 redraw = TRUE;
3026 if (!view_is_displayed(view))
3027 return TRUE;
3029 if (redraw)
3030 redraw_view_from(view, 0);
3031 else
3032 redraw_view_dirty(view);
3034 /* Update the title _after_ the redraw so that if the redraw picks up a
3035 * commit reference in view->ref it'll be available here. */
3036 update_view_title(view);
3037 return TRUE;
3040 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3042 static struct line *
3043 add_line_data(struct view *view, void *data, enum line_type type)
3045 struct line *line;
3047 if (!realloc_lines(&view->line, view->lines, 1))
3048 return NULL;
3050 line = &view->line[view->lines++];
3051 memset(line, 0, sizeof(*line));
3052 line->type = type;
3053 line->data = data;
3054 line->dirty = 1;
3056 return line;
3059 static struct line *
3060 add_line_text(struct view *view, const char *text, enum line_type type)
3062 char *data = text ? strdup(text) : NULL;
3064 return data ? add_line_data(view, data, type) : NULL;
3067 static struct line *
3068 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3070 char buf[SIZEOF_STR];
3071 int retval;
3073 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3074 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3078 * View opening
3081 static void
3082 load_view(struct view *view, enum open_flags flags)
3084 if (view->pipe)
3085 end_update(view, TRUE);
3086 if (view->ops->private_size) {
3087 if (!view->private)
3088 view->private = calloc(1, view->ops->private_size);
3089 else
3090 memset(view->private, 0, view->ops->private_size);
3092 if (!view->ops->open(view, flags)) {
3093 report("Failed to load %s view", view->name);
3094 return;
3096 restore_view_position(view);
3098 if (view->pipe && view->lines == 0) {
3099 /* Clear the old view and let the incremental updating refill
3100 * the screen. */
3101 werase(view->win);
3102 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3103 clear_position(&view->prev_pos);
3104 report("");
3105 } else if (view_is_displayed(view)) {
3106 redraw_view(view);
3107 report("");
3111 #define refresh_view(view) load_view(view, OPEN_REFRESH)
3112 #define reload_view(view) load_view(view, OPEN_RELOAD)
3114 static void
3115 split_view(struct view *prev, struct view *view)
3117 display[1] = view;
3118 current_view = 1;
3119 view->parent = prev;
3120 resize_display();
3122 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3123 /* Take the title line into account. */
3124 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3126 /* Scroll the view that was split if the current line is
3127 * outside the new limited view. */
3128 do_scroll_view(prev, lines);
3131 if (view != prev && view_is_displayed(prev)) {
3132 /* "Blur" the previous view. */
3133 update_view_title(prev);
3137 static void
3138 open_view(struct view *prev, enum request request, enum open_flags flags)
3140 bool split = !!(flags & OPEN_SPLIT);
3141 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3142 struct view *view = VIEW(request);
3143 int nviews = displayed_views();
3145 assert(flags ^ OPEN_REFRESH);
3147 if (view == prev && nviews == 1 && !reload) {
3148 report("Already in %s view", view->name);
3149 return;
3152 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3153 report("The %s view is disabled in pager view", view->name);
3154 return;
3157 if (split) {
3158 split_view(prev, view);
3159 } else {
3160 maximize_view(view, FALSE);
3163 /* No prev signals that this is the first loaded view. */
3164 if (prev && view != prev) {
3165 view->prev = prev;
3168 load_view(view, flags);
3171 static void
3172 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3174 enum request request = view - views + REQ_OFFSET + 1;
3176 if (view->pipe)
3177 end_update(view, TRUE);
3178 view->dir = dir;
3180 if (!argv_copy(&view->argv, argv)) {
3181 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3182 } else {
3183 open_view(prev, request, flags | OPEN_PREPARED);
3187 static void
3188 open_external_viewer(const char *argv[], const char *dir)
3190 def_prog_mode(); /* save current tty modes */
3191 endwin(); /* restore original tty modes */
3192 io_run_fg(argv, dir);
3193 fprintf(stderr, "Press Enter to continue");
3194 getc(opt_tty);
3195 reset_prog_mode();
3196 redraw_display(TRUE);
3199 static void
3200 open_mergetool(const char *file)
3202 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3204 open_external_viewer(mergetool_argv, opt_cdup);
3207 static void
3208 open_editor(const char *file)
3210 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3211 char editor_cmd[SIZEOF_STR];
3212 const char *editor;
3213 int argc = 0;
3215 editor = getenv("GIT_EDITOR");
3216 if (!editor && *opt_editor)
3217 editor = opt_editor;
3218 if (!editor)
3219 editor = getenv("VISUAL");
3220 if (!editor)
3221 editor = getenv("EDITOR");
3222 if (!editor)
3223 editor = "vi";
3225 string_ncopy(editor_cmd, editor, strlen(editor));
3226 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3227 report("Failed to read editor command");
3228 return;
3231 editor_argv[argc] = file;
3232 open_external_viewer(editor_argv, opt_cdup);
3235 static void
3236 open_run_request(enum request request)
3238 struct run_request *req = get_run_request(request);
3239 const char **argv = NULL;
3241 if (!req) {
3242 report("Unknown run request");
3243 return;
3246 if (format_argv(&argv, req->argv, FALSE)) {
3247 if (req->silent)
3248 io_run_bg(argv);
3249 else
3250 open_external_viewer(argv, NULL);
3252 if (argv)
3253 argv_free(argv);
3254 free(argv);
3258 * User request switch noodle
3261 static int
3262 view_driver(struct view *view, enum request request)
3264 int i;
3266 if (request == REQ_NONE)
3267 return TRUE;
3269 if (request > REQ_NONE) {
3270 open_run_request(request);
3271 view_request(view, REQ_REFRESH);
3272 return TRUE;
3275 request = view_request(view, request);
3276 if (request == REQ_NONE)
3277 return TRUE;
3279 switch (request) {
3280 case REQ_MOVE_UP:
3281 case REQ_MOVE_DOWN:
3282 case REQ_MOVE_PAGE_UP:
3283 case REQ_MOVE_PAGE_DOWN:
3284 case REQ_MOVE_FIRST_LINE:
3285 case REQ_MOVE_LAST_LINE:
3286 move_view(view, request);
3287 break;
3289 case REQ_SCROLL_FIRST_COL:
3290 case REQ_SCROLL_LEFT:
3291 case REQ_SCROLL_RIGHT:
3292 case REQ_SCROLL_LINE_DOWN:
3293 case REQ_SCROLL_LINE_UP:
3294 case REQ_SCROLL_PAGE_DOWN:
3295 case REQ_SCROLL_PAGE_UP:
3296 scroll_view(view, request);
3297 break;
3299 case REQ_VIEW_BLAME:
3300 if (!opt_file[0]) {
3301 report("No file chosen, press %s to open tree view",
3302 get_view_key(view, REQ_VIEW_TREE));
3303 break;
3305 open_view(view, request, OPEN_DEFAULT);
3306 break;
3308 case REQ_VIEW_BLOB:
3309 if (!ref_blob[0]) {
3310 report("No file chosen, press %s to open tree view",
3311 get_view_key(view, REQ_VIEW_TREE));
3312 break;
3314 open_view(view, request, OPEN_DEFAULT);
3315 break;
3317 case REQ_VIEW_PAGER:
3318 if (view == NULL) {
3319 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
3320 die("Failed to open stdin");
3321 open_view(view, request, OPEN_PREPARED);
3322 break;
3325 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
3326 report("No pager content, press %s to run command from prompt",
3327 get_view_key(view, REQ_PROMPT));
3328 break;
3330 open_view(view, request, OPEN_DEFAULT);
3331 break;
3333 case REQ_VIEW_STAGE:
3334 if (!VIEW(REQ_VIEW_STAGE)->lines) {
3335 report("No stage content, press %s to open the status view and choose file",
3336 get_view_key(view, REQ_VIEW_STATUS));
3337 break;
3339 open_view(view, request, OPEN_DEFAULT);
3340 break;
3342 case REQ_VIEW_STATUS:
3343 if (opt_is_inside_work_tree == FALSE) {
3344 report("The status view requires a working tree");
3345 break;
3347 open_view(view, request, OPEN_DEFAULT);
3348 break;
3350 case REQ_VIEW_MAIN:
3351 case REQ_VIEW_DIFF:
3352 case REQ_VIEW_LOG:
3353 case REQ_VIEW_TREE:
3354 case REQ_VIEW_HELP:
3355 case REQ_VIEW_BRANCH:
3356 open_view(view, request, OPEN_DEFAULT);
3357 break;
3359 case REQ_NEXT:
3360 case REQ_PREVIOUS:
3361 if (view->parent) {
3362 int line;
3364 view = view->parent;
3365 line = view->pos.lineno;
3366 move_view(view, request);
3367 if (view_is_displayed(view))
3368 update_view_title(view);
3369 if (line != view->pos.lineno)
3370 view_request(view, REQ_ENTER);
3371 } else {
3372 move_view(view, request);
3374 break;
3376 case REQ_VIEW_NEXT:
3378 int nviews = displayed_views();
3379 int next_view = (current_view + 1) % nviews;
3381 if (next_view == current_view) {
3382 report("Only one view is displayed");
3383 break;
3386 current_view = next_view;
3387 /* Blur out the title of the previous view. */
3388 update_view_title(view);
3389 report("");
3390 break;
3392 case REQ_REFRESH:
3393 report("Refreshing is not yet supported for the %s view", view->name);
3394 break;
3396 case REQ_MAXIMIZE:
3397 if (displayed_views() == 2)
3398 maximize_view(view, TRUE);
3399 break;
3401 case REQ_OPTIONS:
3402 case REQ_TOGGLE_LINENO:
3403 case REQ_TOGGLE_DATE:
3404 case REQ_TOGGLE_AUTHOR:
3405 case REQ_TOGGLE_FILENAME:
3406 case REQ_TOGGLE_GRAPHIC:
3407 case REQ_TOGGLE_REV_GRAPH:
3408 case REQ_TOGGLE_REFS:
3409 case REQ_TOGGLE_CHANGES:
3410 case REQ_TOGGLE_IGNORE_SPACE:
3411 if (toggle_option(request) && view_has_flags(view, VIEW_DIFF_LIKE))
3412 reload_view(view);
3413 break;
3415 case REQ_TOGGLE_SORT_FIELD:
3416 case REQ_TOGGLE_SORT_ORDER:
3417 report("Sorting is not yet supported for the %s view", view->name);
3418 break;
3420 case REQ_DIFF_CONTEXT_UP:
3421 case REQ_DIFF_CONTEXT_DOWN:
3422 report("Changing the diff context is not yet supported for the %s view", view->name);
3423 break;
3425 case REQ_SEARCH:
3426 case REQ_SEARCH_BACK:
3427 search_view(view, request);
3428 break;
3430 case REQ_FIND_NEXT:
3431 case REQ_FIND_PREV:
3432 find_next(view, request);
3433 break;
3435 case REQ_STOP_LOADING:
3436 foreach_view(view, i) {
3437 if (view->pipe)
3438 report("Stopped loading the %s view", view->name),
3439 end_update(view, TRUE);
3441 break;
3443 case REQ_SHOW_VERSION:
3444 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3445 return TRUE;
3447 case REQ_SCREEN_REDRAW:
3448 redraw_display(TRUE);
3449 break;
3451 case REQ_EDIT:
3452 report("Nothing to edit");
3453 break;
3455 case REQ_ENTER:
3456 report("Nothing to enter");
3457 break;
3459 case REQ_VIEW_CLOSE:
3460 /* XXX: Mark closed views by letting view->prev point to the
3461 * view itself. Parents to closed view should never be
3462 * followed. */
3463 if (view->prev && view->prev != view) {
3464 maximize_view(view->prev, TRUE);
3465 view->prev = view;
3466 break;
3468 /* Fall-through */
3469 case REQ_QUIT:
3470 return FALSE;
3472 default:
3473 report("Unknown key, press %s for help",
3474 get_view_key(view, REQ_VIEW_HELP));
3475 return TRUE;
3478 return TRUE;
3483 * View backend utilities
3486 enum sort_field {
3487 ORDERBY_NAME,
3488 ORDERBY_DATE,
3489 ORDERBY_AUTHOR,
3492 struct sort_state {
3493 const enum sort_field *fields;
3494 size_t size, current;
3495 bool reverse;
3498 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3499 #define get_sort_field(state) ((state).fields[(state).current])
3500 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3502 static void
3503 sort_view(struct view *view, enum request request, struct sort_state *state,
3504 int (*compare)(const void *, const void *))
3506 switch (request) {
3507 case REQ_TOGGLE_SORT_FIELD:
3508 state->current = (state->current + 1) % state->size;
3509 break;
3511 case REQ_TOGGLE_SORT_ORDER:
3512 state->reverse = !state->reverse;
3513 break;
3514 default:
3515 die("Not a sort request");
3518 qsort(view->line, view->lines, sizeof(*view->line), compare);
3519 redraw_view(view);
3522 static bool
3523 update_diff_context(enum request request)
3525 int diff_context = opt_diff_context;
3527 switch (request) {
3528 case REQ_DIFF_CONTEXT_UP:
3529 opt_diff_context += 1;
3530 update_diff_context_arg(opt_diff_context);
3531 break;
3533 case REQ_DIFF_CONTEXT_DOWN:
3534 if (opt_diff_context == 0) {
3535 report("Diff context cannot be less than zero");
3536 break;
3538 opt_diff_context -= 1;
3539 update_diff_context_arg(opt_diff_context);
3540 break;
3542 default:
3543 die("Not a diff context request");
3546 return diff_context != opt_diff_context;
3549 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3551 /* Small author cache to reduce memory consumption. It uses binary
3552 * search to lookup or find place to position new entries. No entries
3553 * are ever freed. */
3554 static const char *
3555 get_author(const char *name)
3557 static const char **authors;
3558 static size_t authors_size;
3559 int from = 0, to = authors_size - 1;
3561 while (from <= to) {
3562 size_t pos = (to + from) / 2;
3563 int cmp = strcmp(name, authors[pos]);
3565 if (!cmp)
3566 return authors[pos];
3568 if (cmp < 0)
3569 to = pos - 1;
3570 else
3571 from = pos + 1;
3574 if (!realloc_authors(&authors, authors_size, 1))
3575 return NULL;
3576 name = strdup(name);
3577 if (!name)
3578 return NULL;
3580 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3581 authors[from] = name;
3582 authors_size++;
3584 return name;
3587 static void
3588 parse_timesec(struct time *time, const char *sec)
3590 time->sec = (time_t) atol(sec);
3593 static void
3594 parse_timezone(struct time *time, const char *zone)
3596 long tz;
3598 tz = ('0' - zone[1]) * 60 * 60 * 10;
3599 tz += ('0' - zone[2]) * 60 * 60;
3600 tz += ('0' - zone[3]) * 60 * 10;
3601 tz += ('0' - zone[4]) * 60;
3603 if (zone[0] == '-')
3604 tz = -tz;
3606 time->tz = tz;
3607 time->sec -= tz;
3610 /* Parse author lines where the name may be empty:
3611 * author <email@address.tld> 1138474660 +0100
3613 static void
3614 parse_author_line(char *ident, const char **author, struct time *time)
3616 char *nameend = strchr(ident, '<');
3617 char *emailend = strchr(ident, '>');
3619 if (nameend && emailend)
3620 *nameend = *emailend = 0;
3621 ident = chomp_string(ident);
3622 if (!*ident) {
3623 if (nameend)
3624 ident = chomp_string(nameend + 1);
3625 if (!*ident)
3626 ident = "Unknown";
3629 *author = get_author(ident);
3631 /* Parse epoch and timezone */
3632 if (emailend && emailend[1] == ' ') {
3633 char *secs = emailend + 2;
3634 char *zone = strchr(secs, ' ');
3636 parse_timesec(time, secs);
3638 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3639 parse_timezone(time, zone + 1);
3643 static struct line *
3644 find_prev_line_by_type(struct view *view, struct line *line, enum line_type type)
3646 for (; view->line < line; line--)
3647 if (line->type == type)
3648 return line;
3650 return NULL;
3654 * Blame
3657 struct blame_commit {
3658 char id[SIZEOF_REV]; /* SHA1 ID. */
3659 char title[128]; /* First line of the commit message. */
3660 const char *author; /* Author of the commit. */
3661 struct time time; /* Date from the author ident. */
3662 char filename[128]; /* Name of file. */
3663 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3664 char parent_filename[128]; /* Parent/previous name of file. */
3667 struct blame_header {
3668 char id[SIZEOF_REV]; /* SHA1 ID. */
3669 size_t orig_lineno;
3670 size_t lineno;
3671 size_t group;
3674 static bool
3675 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3677 const char *pos = *posref;
3679 *posref = NULL;
3680 pos = strchr(pos + 1, ' ');
3681 if (!pos || !isdigit(pos[1]))
3682 return FALSE;
3683 *number = atoi(pos + 1);
3684 if (*number < min || *number > max)
3685 return FALSE;
3687 *posref = pos;
3688 return TRUE;
3691 static bool
3692 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3694 const char *pos = text + SIZEOF_REV - 2;
3696 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3697 return FALSE;
3699 string_ncopy(header->id, text, SIZEOF_REV);
3701 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3702 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3703 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3704 return FALSE;
3706 return TRUE;
3709 static bool
3710 match_blame_header(const char *name, char **line)
3712 size_t namelen = strlen(name);
3713 bool matched = !strncmp(name, *line, namelen);
3715 if (matched)
3716 *line += namelen;
3718 return matched;
3721 static bool
3722 parse_blame_info(struct blame_commit *commit, char *line)
3724 if (match_blame_header("author ", &line)) {
3725 commit->author = get_author(line);
3727 } else if (match_blame_header("author-time ", &line)) {
3728 parse_timesec(&commit->time, line);
3730 } else if (match_blame_header("author-tz ", &line)) {
3731 parse_timezone(&commit->time, line);
3733 } else if (match_blame_header("summary ", &line)) {
3734 string_ncopy(commit->title, line, strlen(line));
3736 } else if (match_blame_header("previous ", &line)) {
3737 if (strlen(line) <= SIZEOF_REV)
3738 return FALSE;
3739 string_copy_rev(commit->parent_id, line);
3740 line += SIZEOF_REV;
3741 string_ncopy(commit->parent_filename, line, strlen(line));
3743 } else if (match_blame_header("filename ", &line)) {
3744 string_ncopy(commit->filename, line, strlen(line));
3745 return TRUE;
3748 return FALSE;
3752 * Pager backend
3755 static bool
3756 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3758 if (draw_lineno(view, lineno))
3759 return TRUE;
3761 draw_text(view, line->type, line->data);
3762 return TRUE;
3765 static bool
3766 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3768 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3769 char ref[SIZEOF_STR];
3771 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3772 return TRUE;
3774 /* This is the only fatal call, since it can "corrupt" the buffer. */
3775 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3776 return FALSE;
3778 return TRUE;
3781 static void
3782 add_pager_refs(struct view *view, struct line *line)
3784 char buf[SIZEOF_STR];
3785 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3786 struct ref_list *list;
3787 size_t bufpos = 0, i;
3788 const char *sep = "Refs: ";
3789 bool is_tag = FALSE;
3791 assert(line->type == LINE_COMMIT);
3793 list = get_ref_list(commit_id);
3794 if (!list) {
3795 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3796 goto try_add_describe_ref;
3797 return;
3800 for (i = 0; i < list->size; i++) {
3801 struct ref *ref = list->refs[i];
3802 const char *fmt = ref->tag ? "%s[%s]" :
3803 ref->remote ? "%s<%s>" : "%s%s";
3805 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3806 return;
3807 sep = ", ";
3808 if (ref->tag)
3809 is_tag = TRUE;
3812 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3813 try_add_describe_ref:
3814 /* Add <tag>-g<commit_id> "fake" reference. */
3815 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3816 return;
3819 if (bufpos == 0)
3820 return;
3822 add_line_text(view, buf, LINE_PP_REFS);
3825 static bool
3826 pager_common_read(struct view *view, char *data, enum line_type type)
3828 struct line *line;
3830 if (!data)
3831 return TRUE;
3833 line = add_line_text(view, data, type);
3834 if (!line)
3835 return FALSE;
3837 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
3838 add_pager_refs(view, line);
3840 return TRUE;
3843 static bool
3844 pager_read(struct view *view, char *data)
3846 if (!data)
3847 return TRUE;
3849 return pager_common_read(view, data, get_line_type(data));
3852 static enum request
3853 pager_request(struct view *view, enum request request, struct line *line)
3855 int split = 0;
3857 if (request != REQ_ENTER)
3858 return request;
3860 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
3861 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3862 split = 1;
3865 /* Always scroll the view even if it was split. That way
3866 * you can use Enter to scroll through the log view and
3867 * split open each commit diff. */
3868 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3870 /* FIXME: A minor workaround. Scrolling the view will call report("")
3871 * but if we are scrolling a non-current view this won't properly
3872 * update the view title. */
3873 if (split)
3874 update_view_title(view);
3876 return REQ_NONE;
3879 static bool
3880 pager_grep(struct view *view, struct line *line)
3882 const char *text[] = { line->data, NULL };
3884 return grep_text(view, text);
3887 static void
3888 pager_select(struct view *view, struct line *line)
3890 if (line->type == LINE_COMMIT) {
3891 char *text = (char *)line->data + STRING_SIZE("commit ");
3893 if (!view_has_flags(view, VIEW_NO_REF))
3894 string_copy_rev(view->ref, text);
3895 string_copy_rev(ref_commit, text);
3899 static bool
3900 pager_open(struct view *view, enum open_flags flags)
3902 return begin_update(view, NULL, NULL, flags);
3905 static struct view_ops pager_ops = {
3906 "line",
3907 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
3909 pager_open,
3910 pager_read,
3911 pager_draw,
3912 pager_request,
3913 pager_grep,
3914 pager_select,
3917 static bool
3918 log_open(struct view *view, enum open_flags flags)
3920 static const char *log_argv[] = {
3921 "git", "log", ENCODING_ARG, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3924 return begin_update(view, NULL, log_argv, flags);
3927 static enum request
3928 log_request(struct view *view, enum request request, struct line *line)
3930 switch (request) {
3931 case REQ_REFRESH:
3932 load_refs();
3933 refresh_view(view);
3934 return REQ_NONE;
3935 default:
3936 return pager_request(view, request, line);
3940 static struct view_ops log_ops = {
3941 "line",
3942 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
3944 log_open,
3945 pager_read,
3946 pager_draw,
3947 log_request,
3948 pager_grep,
3949 pager_select,
3952 struct diff_state {
3953 bool reading_diff_stat;
3954 bool combined_diff;
3957 static bool
3958 diff_open(struct view *view, enum open_flags flags)
3960 static const char *diff_argv[] = {
3961 "git", "show", ENCODING_ARG, "--pretty=fuller", "--no-color", "--root",
3962 "--patch-with-stat", "--find-copies-harder", "-C",
3963 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
3964 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3967 return begin_update(view, NULL, diff_argv, flags);
3970 static bool
3971 diff_common_read(struct view *view, char *data, struct diff_state *state)
3973 enum line_type type;
3975 if (state->reading_diff_stat) {
3976 size_t len = strlen(data);
3977 char *pipe = strchr(data, '|');
3978 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3979 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3981 if (pipe && (has_histogram || has_bin_diff)) {
3982 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3983 } else {
3984 state->reading_diff_stat = FALSE;
3987 } else if (!strcmp(data, "---")) {
3988 state->reading_diff_stat = TRUE;
3991 type = get_line_type(data);
3993 if (type == LINE_DIFF_HEADER) {
3994 const int len = line_info[LINE_DIFF_HEADER].linelen;
3996 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
3997 !strncmp(data + len, "cc ", strlen("cc ")))
3998 state->combined_diff = TRUE;
4001 /* ADD2 and DEL2 are only valid in combined diff hunks */
4002 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4003 type = LINE_DEFAULT;
4005 return pager_common_read(view, data, type);
4008 static enum request
4009 diff_common_enter(struct view *view, enum request request, struct line *line)
4011 if (line->type == LINE_DIFF_STAT) {
4012 int file_number = 0;
4014 while (line >= view->line && line->type == LINE_DIFF_STAT) {
4015 file_number++;
4016 line--;
4019 while (line < view->line + view->lines) {
4020 if (line->type == LINE_DIFF_HEADER) {
4021 if (file_number == 1) {
4022 break;
4024 file_number--;
4026 line++;
4030 select_view_line(view, line - view->line);
4031 report("");
4032 return REQ_NONE;
4034 } else {
4035 return pager_request(view, request, line);
4039 static bool
4040 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4042 char *sep = strchr(*text, c);
4044 if (sep != NULL) {
4045 *sep = 0;
4046 draw_text(view, *type, *text);
4047 *sep = c;
4048 *text = sep;
4049 *type = next_type;
4052 return sep != NULL;
4055 static bool
4056 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4058 char *text = line->data;
4059 enum line_type type = line->type;
4061 if (draw_lineno(view, lineno))
4062 return TRUE;
4064 if (type == LINE_DIFF_STAT) {
4065 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4066 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4067 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4068 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4069 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4070 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4071 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4073 } else {
4074 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4075 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4079 draw_text(view, type, text);
4080 return TRUE;
4083 static bool
4084 diff_read(struct view *view, char *data)
4086 struct diff_state *state = view->private;
4088 if (!data) {
4089 /* Fall back to retry if no diff will be shown. */
4090 if (view->lines == 0 && opt_file_argv) {
4091 int pos = argv_size(view->argv)
4092 - argv_size(opt_file_argv) - 1;
4094 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4095 for (; view->argv[pos]; pos++) {
4096 free((void *) view->argv[pos]);
4097 view->argv[pos] = NULL;
4100 if (view->pipe)
4101 io_done(view->pipe);
4102 if (io_run(&view->io, IO_RD, view->dir, view->argv))
4103 return FALSE;
4106 return TRUE;
4109 return diff_common_read(view, data, state);
4112 static bool
4113 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4114 struct blame_header *header, struct blame_commit *commit)
4116 char line_arg[SIZEOF_STR];
4117 const char *blame_argv[] = {
4118 "git", "blame", ENCODING_ARG, "-p", line_arg, ref, "--", file, NULL
4120 struct io io;
4121 bool ok = FALSE;
4122 char *buf;
4124 if (!string_format(line_arg, "-L%d,+1", lineno))
4125 return FALSE;
4127 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
4128 return FALSE;
4130 while ((buf = io_get(&io, '\n', TRUE))) {
4131 if (header) {
4132 if (!parse_blame_header(header, buf, 9999999))
4133 break;
4134 header = NULL;
4136 } else if (parse_blame_info(commit, buf)) {
4137 ok = TRUE;
4138 break;
4142 if (io_error(&io))
4143 ok = FALSE;
4145 io_done(&io);
4146 return ok;
4149 static bool
4150 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4152 return prefixcmp(chunk, "@@ -") ||
4153 !(chunk = strchr(chunk, marker)) ||
4154 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4157 static enum request
4158 diff_trace_origin(struct view *view, struct line *line)
4160 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4161 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4162 const char *chunk_data;
4163 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4164 int lineno = 0;
4165 const char *file = NULL;
4166 char ref[SIZEOF_REF];
4167 struct blame_header header;
4168 struct blame_commit commit;
4170 if (!diff || !chunk || chunk == line) {
4171 report("The line to trace must be inside a diff chunk");
4172 return REQ_NONE;
4175 for (; diff < line && !file; diff++) {
4176 const char *data = diff->data;
4178 if (!prefixcmp(data, "--- a/")) {
4179 file = data + STRING_SIZE("--- a/");
4180 break;
4184 if (diff == line || !file) {
4185 report("Failed to read the file name");
4186 return REQ_NONE;
4189 chunk_data = chunk->data;
4191 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4192 report("Failed to read the line number");
4193 return REQ_NONE;
4196 if (lineno == 0) {
4197 report("This is the origin of the line");
4198 return REQ_NONE;
4201 for (chunk += 1; chunk < line; chunk++) {
4202 if (chunk->type == LINE_DIFF_ADD) {
4203 lineno += chunk_marker == '+';
4204 } else if (chunk->type == LINE_DIFF_DEL) {
4205 lineno += chunk_marker == '-';
4206 } else {
4207 lineno++;
4211 if (chunk_marker == '+')
4212 string_copy(ref, view->vid);
4213 else
4214 string_format(ref, "%s^", view->vid);
4216 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4217 report("Failed to read blame data");
4218 return REQ_NONE;
4221 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4222 string_copy(opt_ref, header.id);
4223 opt_goto_line = header.orig_lineno - 1;
4225 return REQ_VIEW_BLAME;
4228 static enum request
4229 diff_request(struct view *view, enum request request, struct line *line)
4231 switch (request) {
4232 case REQ_VIEW_BLAME:
4233 return diff_trace_origin(view, line);
4235 case REQ_DIFF_CONTEXT_UP:
4236 case REQ_DIFF_CONTEXT_DOWN:
4237 if (!update_diff_context(request))
4238 return REQ_NONE;
4239 reload_view(view);
4240 return REQ_NONE;
4243 case REQ_ENTER:
4244 return diff_common_enter(view, request, line);
4246 default:
4247 return pager_request(view, request, line);
4251 static void
4252 diff_select(struct view *view, struct line *line)
4254 if (line->type == LINE_DIFF_STAT) {
4255 const char *key = get_view_key(view, REQ_ENTER);
4257 string_format(view->ref, "Press '%s' to jump to file diff", key);
4258 } else {
4259 string_ncopy(view->ref, view->id, strlen(view->id));
4260 return pager_select(view, line);
4264 static struct view_ops diff_ops = {
4265 "line",
4266 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS,
4267 sizeof(struct diff_state),
4268 diff_open,
4269 diff_read,
4270 diff_common_draw,
4271 diff_request,
4272 pager_grep,
4273 diff_select,
4277 * Help backend
4280 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
4282 static bool
4283 help_open_keymap_title(struct view *view, enum keymap keymap)
4285 struct line *line;
4287 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
4288 help_keymap_hidden[keymap] ? '+' : '-',
4289 enum_name(keymap_map[keymap]));
4290 if (line)
4291 line->other = keymap;
4293 return help_keymap_hidden[keymap];
4296 static void
4297 help_open_keymap(struct view *view, enum keymap keymap)
4299 const char *group = NULL;
4300 char buf[SIZEOF_STR];
4301 size_t bufpos;
4302 bool add_title = TRUE;
4303 int i;
4305 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4306 const char *key = NULL;
4308 if (req_info[i].request == REQ_NONE)
4309 continue;
4311 if (!req_info[i].request) {
4312 group = req_info[i].help;
4313 continue;
4316 key = get_keys(keymap, req_info[i].request, TRUE);
4317 if (!key || !*key)
4318 continue;
4320 if (add_title && help_open_keymap_title(view, keymap))
4321 return;
4322 add_title = FALSE;
4324 if (group) {
4325 add_line_text(view, group, LINE_HELP_GROUP);
4326 group = NULL;
4329 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4330 enum_name(req_info[i]), req_info[i].help);
4333 group = "External commands:";
4335 for (i = 0; i < run_requests; i++) {
4336 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4337 const char *key;
4338 int argc;
4340 if (!req || req->keymap != keymap)
4341 continue;
4343 key = get_key_name(req->key);
4344 if (!*key)
4345 key = "(no key defined)";
4347 if (add_title && help_open_keymap_title(view, keymap))
4348 return;
4349 add_title = FALSE;
4351 if (group) {
4352 add_line_text(view, group, LINE_HELP_GROUP);
4353 group = NULL;
4356 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
4357 if (!string_format_from(buf, &bufpos, "%s%s",
4358 argc ? " " : "", req->argv[argc]))
4359 return;
4361 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4365 static bool
4366 help_open(struct view *view, enum open_flags flags)
4368 enum keymap keymap;
4370 reset_view(view);
4371 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4372 add_line_text(view, "", LINE_DEFAULT);
4374 for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
4375 help_open_keymap(view, keymap);
4377 return TRUE;
4380 static enum request
4381 help_request(struct view *view, enum request request, struct line *line)
4383 switch (request) {
4384 case REQ_ENTER:
4385 if (line->type == LINE_HELP_KEYMAP) {
4386 help_keymap_hidden[line->other] =
4387 !help_keymap_hidden[line->other];
4388 refresh_view(view);
4391 return REQ_NONE;
4392 default:
4393 return pager_request(view, request, line);
4397 static struct view_ops help_ops = {
4398 "line",
4399 VIEW_NO_GIT_DIR,
4401 help_open,
4402 NULL,
4403 pager_draw,
4404 help_request,
4405 pager_grep,
4406 pager_select,
4411 * Tree backend
4414 struct tree_stack_entry {
4415 struct tree_stack_entry *prev; /* Entry below this in the stack */
4416 unsigned long lineno; /* Line number to restore */
4417 char *name; /* Position of name in opt_path */
4420 /* The top of the path stack. */
4421 static struct tree_stack_entry *tree_stack = NULL;
4422 unsigned long tree_lineno = 0;
4424 static void
4425 pop_tree_stack_entry(void)
4427 struct tree_stack_entry *entry = tree_stack;
4429 tree_lineno = entry->lineno;
4430 entry->name[0] = 0;
4431 tree_stack = entry->prev;
4432 free(entry);
4435 static void
4436 push_tree_stack_entry(const char *name, unsigned long lineno)
4438 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4439 size_t pathlen = strlen(opt_path);
4441 if (!entry)
4442 return;
4444 entry->prev = tree_stack;
4445 entry->name = opt_path + pathlen;
4446 tree_stack = entry;
4448 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4449 pop_tree_stack_entry();
4450 return;
4453 /* Move the current line to the first tree entry. */
4454 tree_lineno = 1;
4455 entry->lineno = lineno;
4458 /* Parse output from git-ls-tree(1):
4460 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4463 #define SIZEOF_TREE_ATTR \
4464 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4466 #define SIZEOF_TREE_MODE \
4467 STRING_SIZE("100644 ")
4469 #define TREE_ID_OFFSET \
4470 STRING_SIZE("100644 blob ")
4472 struct tree_entry {
4473 char id[SIZEOF_REV];
4474 mode_t mode;
4475 struct time time; /* Date from the author ident. */
4476 const char *author; /* Author of the commit. */
4477 char name[1];
4480 struct tree_state {
4481 const char *author_name;
4482 struct time author_time;
4483 bool read_date;
4486 static const char *
4487 tree_path(const struct line *line)
4489 return ((struct tree_entry *) line->data)->name;
4492 static int
4493 tree_compare_entry(const struct line *line1, const struct line *line2)
4495 if (line1->type != line2->type)
4496 return line1->type == LINE_TREE_DIR ? -1 : 1;
4497 return strcmp(tree_path(line1), tree_path(line2));
4500 static const enum sort_field tree_sort_fields[] = {
4501 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4503 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4505 static int
4506 tree_compare(const void *l1, const void *l2)
4508 const struct line *line1 = (const struct line *) l1;
4509 const struct line *line2 = (const struct line *) l2;
4510 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4511 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4513 if (line1->type == LINE_TREE_HEAD)
4514 return -1;
4515 if (line2->type == LINE_TREE_HEAD)
4516 return 1;
4518 switch (get_sort_field(tree_sort_state)) {
4519 case ORDERBY_DATE:
4520 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4522 case ORDERBY_AUTHOR:
4523 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4525 case ORDERBY_NAME:
4526 default:
4527 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4532 static struct line *
4533 tree_entry(struct view *view, enum line_type type, const char *path,
4534 const char *mode, const char *id)
4536 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4537 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4539 if (!entry || !line) {
4540 free(entry);
4541 return NULL;
4544 strncpy(entry->name, path, strlen(path));
4545 if (mode)
4546 entry->mode = strtoul(mode, NULL, 8);
4547 if (id)
4548 string_copy_rev(entry->id, id);
4550 return line;
4553 static bool
4554 tree_read_date(struct view *view, char *text, struct tree_state *state)
4556 if (!text && state->read_date) {
4557 state->read_date = FALSE;
4558 return TRUE;
4560 } else if (!text) {
4561 /* Find next entry to process */
4562 const char *log_file[] = {
4563 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
4564 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4567 if (!view->lines) {
4568 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4569 report("Tree is empty");
4570 return TRUE;
4573 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4574 report("Failed to load tree data");
4575 return TRUE;
4578 state->read_date = TRUE;
4579 return FALSE;
4581 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4582 parse_author_line(text + STRING_SIZE("author "),
4583 &state->author_name, &state->author_time);
4585 } else if (*text == ':') {
4586 char *pos;
4587 size_t annotated = 1;
4588 size_t i;
4590 pos = strchr(text, '\t');
4591 if (!pos)
4592 return TRUE;
4593 text = pos + 1;
4594 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4595 text += strlen(opt_path);
4596 pos = strchr(text, '/');
4597 if (pos)
4598 *pos = 0;
4600 for (i = 1; i < view->lines; i++) {
4601 struct line *line = &view->line[i];
4602 struct tree_entry *entry = line->data;
4604 annotated += !!entry->author;
4605 if (entry->author || strcmp(entry->name, text))
4606 continue;
4608 entry->author = state->author_name;
4609 entry->time = state->author_time;
4610 line->dirty = 1;
4611 break;
4614 if (annotated == view->lines)
4615 io_kill(view->pipe);
4617 return TRUE;
4620 static bool
4621 tree_read(struct view *view, char *text)
4623 struct tree_state *state = view->private;
4624 struct tree_entry *data;
4625 struct line *entry, *line;
4626 enum line_type type;
4627 size_t textlen = text ? strlen(text) : 0;
4628 char *path = text + SIZEOF_TREE_ATTR;
4630 if (state->read_date || !text)
4631 return tree_read_date(view, text, state);
4633 if (textlen <= SIZEOF_TREE_ATTR)
4634 return FALSE;
4635 if (view->lines == 0 &&
4636 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4637 return FALSE;
4639 /* Strip the path part ... */
4640 if (*opt_path) {
4641 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4642 size_t striplen = strlen(opt_path);
4644 if (pathlen > striplen)
4645 memmove(path, path + striplen,
4646 pathlen - striplen + 1);
4648 /* Insert "link" to parent directory. */
4649 if (view->lines == 1 &&
4650 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4651 return FALSE;
4654 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4655 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4656 if (!entry)
4657 return FALSE;
4658 data = entry->data;
4660 /* Skip "Directory ..." and ".." line. */
4661 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4662 if (tree_compare_entry(line, entry) <= 0)
4663 continue;
4665 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4667 line->data = data;
4668 line->type = type;
4669 for (; line <= entry; line++)
4670 line->dirty = line->cleareol = 1;
4671 return TRUE;
4674 if (tree_lineno > view->pos.lineno) {
4675 view->pos.lineno = tree_lineno;
4676 tree_lineno = 0;
4679 return TRUE;
4682 static bool
4683 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4685 struct tree_entry *entry = line->data;
4687 if (line->type == LINE_TREE_HEAD) {
4688 if (draw_text(view, line->type, "Directory path /"))
4689 return TRUE;
4690 } else {
4691 if (draw_mode(view, entry->mode))
4692 return TRUE;
4694 if (draw_author(view, entry->author))
4695 return TRUE;
4697 if (draw_date(view, &entry->time))
4698 return TRUE;
4701 draw_text(view, line->type, entry->name);
4702 return TRUE;
4705 static void
4706 open_blob_editor(const char *id)
4708 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4709 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4710 int fd = mkstemp(file);
4712 if (fd == -1)
4713 report("Failed to create temporary file");
4714 else if (!io_run_append(blob_argv, fd))
4715 report("Failed to save blob data to file");
4716 else
4717 open_editor(file);
4718 if (fd != -1)
4719 unlink(file);
4722 static enum request
4723 tree_request(struct view *view, enum request request, struct line *line)
4725 enum open_flags flags;
4726 struct tree_entry *entry = line->data;
4728 switch (request) {
4729 case REQ_VIEW_BLAME:
4730 if (line->type != LINE_TREE_FILE) {
4731 report("Blame only supported for files");
4732 return REQ_NONE;
4735 string_copy(opt_ref, view->vid);
4736 return request;
4738 case REQ_EDIT:
4739 if (line->type != LINE_TREE_FILE) {
4740 report("Edit only supported for files");
4741 } else if (!is_head_commit(view->vid)) {
4742 open_blob_editor(entry->id);
4743 } else {
4744 open_editor(opt_file);
4746 return REQ_NONE;
4748 case REQ_TOGGLE_SORT_FIELD:
4749 case REQ_TOGGLE_SORT_ORDER:
4750 sort_view(view, request, &tree_sort_state, tree_compare);
4751 return REQ_NONE;
4753 case REQ_PARENT:
4754 if (!*opt_path) {
4755 /* quit view if at top of tree */
4756 return REQ_VIEW_CLOSE;
4758 /* fake 'cd ..' */
4759 line = &view->line[1];
4760 break;
4762 case REQ_ENTER:
4763 break;
4765 default:
4766 return request;
4769 /* Cleanup the stack if the tree view is at a different tree. */
4770 while (!*opt_path && tree_stack)
4771 pop_tree_stack_entry();
4773 switch (line->type) {
4774 case LINE_TREE_DIR:
4775 /* Depending on whether it is a subdirectory or parent link
4776 * mangle the path buffer. */
4777 if (line == &view->line[1] && *opt_path) {
4778 pop_tree_stack_entry();
4780 } else {
4781 const char *basename = tree_path(line);
4783 push_tree_stack_entry(basename, view->pos.lineno);
4786 /* Trees and subtrees share the same ID, so they are not not
4787 * unique like blobs. */
4788 flags = OPEN_RELOAD;
4789 request = REQ_VIEW_TREE;
4790 break;
4792 case LINE_TREE_FILE:
4793 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4794 request = REQ_VIEW_BLOB;
4795 break;
4797 default:
4798 return REQ_NONE;
4801 open_view(view, request, flags);
4802 if (request == REQ_VIEW_TREE)
4803 view->pos.lineno = tree_lineno;
4805 return REQ_NONE;
4808 static bool
4809 tree_grep(struct view *view, struct line *line)
4811 struct tree_entry *entry = line->data;
4812 const char *text[] = {
4813 entry->name,
4814 mkauthor(entry->author, opt_author_cols, opt_author),
4815 mkdate(&entry->time, opt_date),
4816 NULL
4819 return grep_text(view, text);
4822 static void
4823 tree_select(struct view *view, struct line *line)
4825 struct tree_entry *entry = line->data;
4827 if (line->type == LINE_TREE_FILE) {
4828 string_copy_rev(ref_blob, entry->id);
4829 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4831 } else if (line->type != LINE_TREE_DIR) {
4832 return;
4835 string_copy_rev(view->ref, entry->id);
4838 static bool
4839 tree_open(struct view *view, enum open_flags flags)
4841 static const char *tree_argv[] = {
4842 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4845 if (view->lines == 0 && opt_prefix[0]) {
4846 char *pos = opt_prefix;
4848 while (pos && *pos) {
4849 char *end = strchr(pos, '/');
4851 if (end)
4852 *end = 0;
4853 push_tree_stack_entry(pos, 0);
4854 pos = end;
4855 if (end) {
4856 *end = '/';
4857 pos++;
4861 } else if (strcmp(view->vid, view->id)) {
4862 opt_path[0] = 0;
4865 return begin_update(view, opt_cdup, tree_argv, flags);
4868 static struct view_ops tree_ops = {
4869 "file",
4870 VIEW_NO_FLAGS,
4871 sizeof(struct tree_state),
4872 tree_open,
4873 tree_read,
4874 tree_draw,
4875 tree_request,
4876 tree_grep,
4877 tree_select,
4880 static bool
4881 blob_open(struct view *view, enum open_flags flags)
4883 static const char *blob_argv[] = {
4884 "git", "cat-file", "blob", "%(blob)", NULL
4887 view->encoding = get_path_encoding(opt_file, opt_encoding);
4889 return begin_update(view, NULL, blob_argv, flags);
4892 static bool
4893 blob_read(struct view *view, char *line)
4895 if (!line)
4896 return TRUE;
4897 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4900 static enum request
4901 blob_request(struct view *view, enum request request, struct line *line)
4903 switch (request) {
4904 case REQ_EDIT:
4905 open_blob_editor(view->vid);
4906 return REQ_NONE;
4907 default:
4908 return pager_request(view, request, line);
4912 static struct view_ops blob_ops = {
4913 "line",
4914 VIEW_NO_FLAGS,
4916 blob_open,
4917 blob_read,
4918 pager_draw,
4919 blob_request,
4920 pager_grep,
4921 pager_select,
4925 * Blame backend
4927 * Loading the blame view is a two phase job:
4929 * 1. File content is read either using opt_file from the
4930 * filesystem or using git-cat-file.
4931 * 2. Then blame information is incrementally added by
4932 * reading output from git-blame.
4935 struct blame {
4936 struct blame_commit *commit;
4937 unsigned long lineno;
4938 char text[1];
4941 struct blame_state {
4942 struct blame_commit *commit;
4943 int blamed;
4944 bool done_reading;
4945 bool auto_filename_display;
4948 static bool
4949 blame_detect_filename_display(struct view *view)
4951 bool show_filenames = FALSE;
4952 const char *filename = NULL;
4953 int i;
4955 if (opt_blame_argv) {
4956 for (i = 0; opt_blame_argv[i]; i++) {
4957 if (prefixcmp(opt_blame_argv[i], "-C"))
4958 continue;
4960 show_filenames = TRUE;
4964 for (i = 0; i < view->lines; i++) {
4965 struct blame *blame = view->line[i].data;
4967 if (blame->commit && blame->commit->id[0]) {
4968 if (!filename)
4969 filename = blame->commit->filename;
4970 else if (strcmp(filename, blame->commit->filename))
4971 show_filenames = TRUE;
4975 return show_filenames;
4978 static bool
4979 blame_open(struct view *view, enum open_flags flags)
4981 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4982 char path[SIZEOF_STR];
4983 size_t i;
4985 if (!view->prev && *opt_prefix) {
4986 string_copy(path, opt_file);
4987 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4988 return FALSE;
4991 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4992 const char *blame_cat_file_argv[] = {
4993 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4996 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4997 return FALSE;
5000 /* First pass: remove multiple references to the same commit. */
5001 for (i = 0; i < view->lines; i++) {
5002 struct blame *blame = view->line[i].data;
5004 if (blame->commit && blame->commit->id[0])
5005 blame->commit->id[0] = 0;
5006 else
5007 blame->commit = NULL;
5010 /* Second pass: free existing references. */
5011 for (i = 0; i < view->lines; i++) {
5012 struct blame *blame = view->line[i].data;
5014 if (blame->commit)
5015 free(blame->commit);
5018 string_format(view->vid, "%s", opt_file);
5019 string_format(view->ref, "%s ...", opt_file);
5021 return TRUE;
5024 static struct blame_commit *
5025 get_blame_commit(struct view *view, const char *id)
5027 size_t i;
5029 for (i = 0; i < view->lines; i++) {
5030 struct blame *blame = view->line[i].data;
5032 if (!blame->commit)
5033 continue;
5035 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5036 return blame->commit;
5040 struct blame_commit *commit = calloc(1, sizeof(*commit));
5042 if (commit)
5043 string_ncopy(commit->id, id, SIZEOF_REV);
5044 return commit;
5048 static struct blame_commit *
5049 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5051 struct blame_header header;
5052 struct blame_commit *commit;
5053 struct blame *blame;
5055 if (!parse_blame_header(&header, text, view->lines))
5056 return NULL;
5058 commit = get_blame_commit(view, text);
5059 if (!commit)
5060 return NULL;
5062 state->blamed += header.group;
5063 while (header.group--) {
5064 struct line *line = &view->line[header.lineno + header.group - 1];
5066 blame = line->data;
5067 blame->commit = commit;
5068 blame->lineno = header.orig_lineno + header.group - 1;
5069 line->dirty = 1;
5072 return commit;
5075 static bool
5076 blame_read_file(struct view *view, const char *line, struct blame_state *state)
5078 if (!line) {
5079 const char *blame_argv[] = {
5080 "git", "blame", ENCODING_ARG, "%(blameargs)", "--incremental",
5081 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5084 if (view->lines == 0 && !view->prev)
5085 die("No blame exist for %s", view->vid);
5087 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5088 report("Failed to load blame data");
5089 return TRUE;
5092 if (opt_goto_line > 0) {
5093 select_view_line(view, opt_goto_line);
5094 opt_goto_line = 0;
5097 state->done_reading = TRUE;
5098 return FALSE;
5100 } else {
5101 size_t linelen = strlen(line);
5102 struct blame *blame = malloc(sizeof(*blame) + linelen);
5104 if (!blame)
5105 return FALSE;
5107 blame->commit = NULL;
5108 strncpy(blame->text, line, linelen);
5109 blame->text[linelen] = 0;
5110 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
5114 static bool
5115 blame_read(struct view *view, char *line)
5117 struct blame_state *state = view->private;
5119 if (!state->done_reading)
5120 return blame_read_file(view, line, state);
5122 if (!line) {
5123 state->auto_filename_display = blame_detect_filename_display(view);
5124 string_format(view->ref, "%s", view->vid);
5125 if (view_is_displayed(view)) {
5126 update_view_title(view);
5127 redraw_view_from(view, 0);
5129 return TRUE;
5132 if (!state->commit) {
5133 state->commit = read_blame_commit(view, line, state);
5134 string_format(view->ref, "%s %2d%%", view->vid,
5135 view->lines ? state->blamed * 100 / view->lines : 0);
5137 } else if (parse_blame_info(state->commit, line)) {
5138 state->commit = NULL;
5141 return TRUE;
5144 static bool
5145 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5147 struct blame_state *state = view->private;
5148 struct blame *blame = line->data;
5149 struct time *time = NULL;
5150 const char *id = NULL, *author = NULL, *filename = NULL;
5151 enum line_type id_type = LINE_BLAME_ID;
5152 static const enum line_type blame_colors[] = {
5153 LINE_PALETTE_0,
5154 LINE_PALETTE_1,
5155 LINE_PALETTE_2,
5156 LINE_PALETTE_3,
5157 LINE_PALETTE_4,
5158 LINE_PALETTE_5,
5159 LINE_PALETTE_6,
5162 #define BLAME_COLOR(i) \
5163 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5165 if (blame->commit && *blame->commit->filename) {
5166 id = blame->commit->id;
5167 author = blame->commit->author;
5168 filename = blame->commit->filename;
5169 time = &blame->commit->time;
5170 id_type = BLAME_COLOR((long) blame->commit);
5173 if (draw_date(view, time))
5174 return TRUE;
5176 if (draw_author(view, author))
5177 return TRUE;
5179 if (draw_filename(view, filename, state->auto_filename_display))
5180 return TRUE;
5182 if (draw_field(view, id_type, id, ID_COLS, FALSE))
5183 return TRUE;
5185 if (draw_lineno(view, lineno))
5186 return TRUE;
5188 draw_text(view, LINE_DEFAULT, blame->text);
5189 return TRUE;
5192 static bool
5193 check_blame_commit(struct blame *blame, bool check_null_id)
5195 if (!blame->commit)
5196 report("Commit data not loaded yet");
5197 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
5198 report("No commit exist for the selected line");
5199 else
5200 return TRUE;
5201 return FALSE;
5204 static void
5205 setup_blame_parent_line(struct view *view, struct blame *blame)
5207 char from[SIZEOF_REF + SIZEOF_STR];
5208 char to[SIZEOF_REF + SIZEOF_STR];
5209 const char *diff_tree_argv[] = {
5210 "git", "diff", ENCODING_ARG, "--no-textconv", "--no-extdiff",
5211 "--no-color", "-U0", from, to, "--", NULL
5213 struct io io;
5214 int parent_lineno = -1;
5215 int blamed_lineno = -1;
5216 char *line;
5218 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5219 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5220 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5221 return;
5223 while ((line = io_get(&io, '\n', TRUE))) {
5224 if (*line == '@') {
5225 char *pos = strchr(line, '+');
5227 parent_lineno = atoi(line + 4);
5228 if (pos)
5229 blamed_lineno = atoi(pos + 1);
5231 } else if (*line == '+' && parent_lineno != -1) {
5232 if (blame->lineno == blamed_lineno - 1 &&
5233 !strcmp(blame->text, line + 1)) {
5234 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
5235 break;
5237 blamed_lineno++;
5241 io_done(&io);
5244 static enum request
5245 blame_request(struct view *view, enum request request, struct line *line)
5247 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5248 struct blame *blame = line->data;
5250 switch (request) {
5251 case REQ_VIEW_BLAME:
5252 if (check_blame_commit(blame, TRUE)) {
5253 string_copy(opt_ref, blame->commit->id);
5254 string_copy(opt_file, blame->commit->filename);
5255 if (blame->lineno)
5256 view->pos.lineno = blame->lineno;
5257 reload_view(view);
5259 break;
5261 case REQ_PARENT:
5262 if (!check_blame_commit(blame, TRUE))
5263 break;
5264 if (!*blame->commit->parent_id) {
5265 report("The selected commit has no parents");
5266 } else {
5267 string_copy_rev(opt_ref, blame->commit->parent_id);
5268 string_copy(opt_file, blame->commit->parent_filename);
5269 setup_blame_parent_line(view, blame);
5270 opt_goto_line = blame->lineno;
5271 reload_view(view);
5273 break;
5275 case REQ_ENTER:
5276 if (!check_blame_commit(blame, FALSE))
5277 break;
5279 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5280 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5281 break;
5283 if (!strcmp(blame->commit->id, NULL_ID)) {
5284 struct view *diff = VIEW(REQ_VIEW_DIFF);
5285 const char *diff_parent_argv[] = {
5286 GIT_DIFF_BLAME(opt_diff_context_arg,
5287 opt_ignore_space_arg, view->vid)
5289 const char *diff_no_parent_argv[] = {
5290 GIT_DIFF_BLAME_NO_PARENT(opt_diff_context_arg,
5291 opt_ignore_space_arg, view->vid)
5293 const char **diff_index_argv = *blame->commit->parent_id
5294 ? diff_parent_argv : diff_no_parent_argv;
5296 open_argv(view, diff, diff_index_argv, NULL, flags);
5297 if (diff->pipe)
5298 string_copy_rev(diff->ref, NULL_ID);
5299 } else {
5300 open_view(view, REQ_VIEW_DIFF, flags);
5302 break;
5304 default:
5305 return request;
5308 return REQ_NONE;
5311 static bool
5312 blame_grep(struct view *view, struct line *line)
5314 struct blame *blame = line->data;
5315 struct blame_commit *commit = blame->commit;
5316 const char *text[] = {
5317 blame->text,
5318 commit ? commit->title : "",
5319 commit ? commit->id : "",
5320 commit && opt_author ? commit->author : "",
5321 commit ? mkdate(&commit->time, opt_date) : "",
5322 NULL
5325 return grep_text(view, text);
5328 static void
5329 blame_select(struct view *view, struct line *line)
5331 struct blame *blame = line->data;
5332 struct blame_commit *commit = blame->commit;
5334 if (!commit)
5335 return;
5337 if (!strcmp(commit->id, NULL_ID))
5338 string_ncopy(ref_commit, "HEAD", 4);
5339 else
5340 string_copy_rev(ref_commit, commit->id);
5343 static struct view_ops blame_ops = {
5344 "line",
5345 VIEW_ALWAYS_LINENO,
5346 sizeof(struct blame_state),
5347 blame_open,
5348 blame_read,
5349 blame_draw,
5350 blame_request,
5351 blame_grep,
5352 blame_select,
5356 * Branch backend
5359 struct branch {
5360 const char *author; /* Author of the last commit. */
5361 struct time time; /* Date of the last activity. */
5362 const struct ref *ref; /* Name and commit ID information. */
5365 static const struct ref branch_all;
5367 static const enum sort_field branch_sort_fields[] = {
5368 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5370 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5372 struct branch_state {
5373 char id[SIZEOF_REV];
5376 static int
5377 branch_compare(const void *l1, const void *l2)
5379 const struct branch *branch1 = ((const struct line *) l1)->data;
5380 const struct branch *branch2 = ((const struct line *) l2)->data;
5382 if (branch1->ref == &branch_all)
5383 return -1;
5384 else if (branch2->ref == &branch_all)
5385 return 1;
5387 switch (get_sort_field(branch_sort_state)) {
5388 case ORDERBY_DATE:
5389 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5391 case ORDERBY_AUTHOR:
5392 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5394 case ORDERBY_NAME:
5395 default:
5396 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5400 static bool
5401 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5403 struct branch *branch = line->data;
5404 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5406 if (draw_date(view, &branch->time))
5407 return TRUE;
5409 if (draw_author(view, branch->author))
5410 return TRUE;
5412 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
5413 return TRUE;
5416 static enum request
5417 branch_request(struct view *view, enum request request, struct line *line)
5419 struct branch *branch = line->data;
5421 switch (request) {
5422 case REQ_REFRESH:
5423 load_refs();
5424 refresh_view(view);
5425 return REQ_NONE;
5427 case REQ_TOGGLE_SORT_FIELD:
5428 case REQ_TOGGLE_SORT_ORDER:
5429 sort_view(view, request, &branch_sort_state, branch_compare);
5430 return REQ_NONE;
5432 case REQ_ENTER:
5434 const struct ref *ref = branch->ref;
5435 const char *all_branches_argv[] = {
5436 "git", "log", ENCODING_ARG, "--no-color",
5437 "--pretty=raw", "--parents", opt_commit_order_arg,
5438 ref == &branch_all ? "--all" : ref->name, NULL
5440 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5442 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5443 return REQ_NONE;
5445 case REQ_JUMP_COMMIT:
5447 int lineno;
5449 for (lineno = 0; lineno < view->lines; lineno++) {
5450 struct branch *branch = view->line[lineno].data;
5452 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5453 select_view_line(view, lineno);
5454 report("");
5455 return REQ_NONE;
5459 default:
5460 return request;
5464 static bool
5465 branch_read(struct view *view, char *line)
5467 struct branch_state *state = view->private;
5468 struct branch *reference;
5469 size_t i;
5471 if (!line)
5472 return TRUE;
5474 switch (get_line_type(line)) {
5475 case LINE_COMMIT:
5476 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5477 return TRUE;
5479 case LINE_AUTHOR:
5480 for (i = 0, reference = NULL; i < view->lines; i++) {
5481 struct branch *branch = view->line[i].data;
5483 if (strcmp(branch->ref->id, state->id))
5484 continue;
5486 view->line[i].dirty = TRUE;
5487 if (reference) {
5488 branch->author = reference->author;
5489 branch->time = reference->time;
5490 continue;
5493 parse_author_line(line + STRING_SIZE("author "),
5494 &branch->author, &branch->time);
5495 reference = branch;
5497 return TRUE;
5499 default:
5500 return TRUE;
5505 static bool
5506 branch_open_visitor(void *data, const struct ref *ref)
5508 struct view *view = data;
5509 struct branch *branch;
5511 if (ref->tag || ref->ltag)
5512 return TRUE;
5514 branch = calloc(1, sizeof(*branch));
5515 if (!branch)
5516 return FALSE;
5518 branch->ref = ref;
5519 return !!add_line_data(view, branch, LINE_DEFAULT);
5522 static bool
5523 branch_open(struct view *view, enum open_flags flags)
5525 const char *branch_log[] = {
5526 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
5527 "--simplify-by-decoration", "--all", NULL
5530 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
5531 report("Failed to load branch data");
5532 return TRUE;
5535 branch_open_visitor(view, &branch_all);
5536 foreach_ref(branch_open_visitor, view);
5538 return TRUE;
5541 static bool
5542 branch_grep(struct view *view, struct line *line)
5544 struct branch *branch = line->data;
5545 const char *text[] = {
5546 branch->ref->name,
5547 mkauthor(branch->author, opt_author_cols, opt_author),
5548 NULL
5551 return grep_text(view, text);
5554 static void
5555 branch_select(struct view *view, struct line *line)
5557 struct branch *branch = line->data;
5559 string_copy_rev(view->ref, branch->ref->id);
5560 string_copy_rev(ref_commit, branch->ref->id);
5561 string_copy_rev(ref_head, branch->ref->id);
5562 string_copy_rev(ref_branch, branch->ref->name);
5565 static struct view_ops branch_ops = {
5566 "branch",
5567 VIEW_NO_FLAGS,
5568 sizeof(struct branch_state),
5569 branch_open,
5570 branch_read,
5571 branch_draw,
5572 branch_request,
5573 branch_grep,
5574 branch_select,
5578 * Status backend
5581 struct status {
5582 char status;
5583 struct {
5584 mode_t mode;
5585 char rev[SIZEOF_REV];
5586 char name[SIZEOF_STR];
5587 } old;
5588 struct {
5589 mode_t mode;
5590 char rev[SIZEOF_REV];
5591 char name[SIZEOF_STR];
5592 } new;
5595 static char status_onbranch[SIZEOF_STR];
5596 static struct status stage_status;
5597 static enum line_type stage_line_type;
5599 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5601 /* This should work even for the "On branch" line. */
5602 static inline bool
5603 status_has_none(struct view *view, struct line *line)
5605 return line < view->line + view->lines && !line[1].data;
5608 /* Get fields from the diff line:
5609 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5611 static inline bool
5612 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5614 const char *old_mode = buf + 1;
5615 const char *new_mode = buf + 8;
5616 const char *old_rev = buf + 15;
5617 const char *new_rev = buf + 56;
5618 const char *status = buf + 97;
5620 if (bufsize < 98 ||
5621 old_mode[-1] != ':' ||
5622 new_mode[-1] != ' ' ||
5623 old_rev[-1] != ' ' ||
5624 new_rev[-1] != ' ' ||
5625 status[-1] != ' ')
5626 return FALSE;
5628 file->status = *status;
5630 string_copy_rev(file->old.rev, old_rev);
5631 string_copy_rev(file->new.rev, new_rev);
5633 file->old.mode = strtoul(old_mode, NULL, 8);
5634 file->new.mode = strtoul(new_mode, NULL, 8);
5636 file->old.name[0] = file->new.name[0] = 0;
5638 return TRUE;
5641 static bool
5642 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5644 struct status *unmerged = NULL;
5645 char *buf;
5646 struct io io;
5648 if (!io_run(&io, IO_RD, opt_cdup, argv))
5649 return FALSE;
5651 add_line_data(view, NULL, type);
5653 while ((buf = io_get(&io, 0, TRUE))) {
5654 struct status *file = unmerged;
5656 if (!file) {
5657 file = calloc(1, sizeof(*file));
5658 if (!file || !add_line_data(view, file, type))
5659 goto error_out;
5662 /* Parse diff info part. */
5663 if (status) {
5664 file->status = status;
5665 if (status == 'A')
5666 string_copy(file->old.rev, NULL_ID);
5668 } else if (!file->status || file == unmerged) {
5669 if (!status_get_diff(file, buf, strlen(buf)))
5670 goto error_out;
5672 buf = io_get(&io, 0, TRUE);
5673 if (!buf)
5674 break;
5676 /* Collapse all modified entries that follow an
5677 * associated unmerged entry. */
5678 if (unmerged == file) {
5679 unmerged->status = 'U';
5680 unmerged = NULL;
5681 } else if (file->status == 'U') {
5682 unmerged = file;
5686 /* Grab the old name for rename/copy. */
5687 if (!*file->old.name &&
5688 (file->status == 'R' || file->status == 'C')) {
5689 string_ncopy(file->old.name, buf, strlen(buf));
5691 buf = io_get(&io, 0, TRUE);
5692 if (!buf)
5693 break;
5696 /* git-ls-files just delivers a NUL separated list of
5697 * file names similar to the second half of the
5698 * git-diff-* output. */
5699 string_ncopy(file->new.name, buf, strlen(buf));
5700 if (!*file->old.name)
5701 string_copy(file->old.name, file->new.name);
5702 file = NULL;
5705 if (io_error(&io)) {
5706 error_out:
5707 io_done(&io);
5708 return FALSE;
5711 if (!view->line[view->lines - 1].data)
5712 add_line_data(view, NULL, LINE_STAT_NONE);
5714 io_done(&io);
5715 return TRUE;
5718 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
5719 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
5721 static const char *status_list_other_argv[] = {
5722 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5725 static const char *status_list_no_head_argv[] = {
5726 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5729 static const char *update_index_argv[] = {
5730 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5733 /* Restore the previous line number to stay in the context or select a
5734 * line with something that can be updated. */
5735 static void
5736 status_restore(struct view *view)
5738 if (view->prev_pos.lineno >= view->lines)
5739 view->prev_pos.lineno = view->lines - 1;
5740 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
5741 view->prev_pos.lineno++;
5742 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
5743 view->prev_pos.lineno--;
5745 /* If the above fails, always skip the "On branch" line. */
5746 if (view->prev_pos.lineno < view->lines)
5747 view->pos.lineno = view->prev_pos.lineno;
5748 else
5749 view->pos.lineno = 1;
5751 if (view->prev_pos.offset > view->pos.lineno)
5752 view->pos.offset = view->pos.lineno;
5753 else if (view->prev_pos.offset < view->lines)
5754 view->pos.offset = view->prev_pos.offset;
5756 clear_position(&view->prev_pos);
5759 static void
5760 status_update_onbranch(void)
5762 static const char *paths[][2] = {
5763 { "rebase-apply/rebasing", "Rebasing" },
5764 { "rebase-apply/applying", "Applying mailbox" },
5765 { "rebase-apply/", "Rebasing mailbox" },
5766 { "rebase-merge/interactive", "Interactive rebase" },
5767 { "rebase-merge/", "Rebase merge" },
5768 { "MERGE_HEAD", "Merging" },
5769 { "BISECT_LOG", "Bisecting" },
5770 { "HEAD", "On branch" },
5772 char buf[SIZEOF_STR];
5773 struct stat stat;
5774 int i;
5776 if (is_initial_commit()) {
5777 string_copy(status_onbranch, "Initial commit");
5778 return;
5781 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5782 char *head = opt_head;
5784 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5785 lstat(buf, &stat) < 0)
5786 continue;
5788 if (!*opt_head) {
5789 struct io io;
5791 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5792 io_read_buf(&io, buf, sizeof(buf))) {
5793 head = buf;
5794 if (!prefixcmp(head, "refs/heads/"))
5795 head += STRING_SIZE("refs/heads/");
5799 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5800 string_copy(status_onbranch, opt_head);
5801 return;
5804 string_copy(status_onbranch, "Not currently on any branch");
5807 /* First parse staged info using git-diff-index(1), then parse unstaged
5808 * info using git-diff-files(1), and finally untracked files using
5809 * git-ls-files(1). */
5810 static bool
5811 status_open(struct view *view, enum open_flags flags)
5813 reset_view(view);
5815 add_line_data(view, NULL, LINE_STAT_HEAD);
5816 status_update_onbranch();
5818 io_run_bg(update_index_argv);
5820 if (is_initial_commit()) {
5821 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5822 return FALSE;
5823 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5824 return FALSE;
5827 if (!opt_untracked_dirs_content)
5828 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5830 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5831 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5832 return FALSE;
5834 /* Restore the exact position or use the specialized restore
5835 * mode? */
5836 status_restore(view);
5837 return TRUE;
5840 static bool
5841 status_draw(struct view *view, struct line *line, unsigned int lineno)
5843 struct status *status = line->data;
5844 enum line_type type;
5845 const char *text;
5847 if (!status) {
5848 switch (line->type) {
5849 case LINE_STAT_STAGED:
5850 type = LINE_STAT_SECTION;
5851 text = "Changes to be committed:";
5852 break;
5854 case LINE_STAT_UNSTAGED:
5855 type = LINE_STAT_SECTION;
5856 text = "Changed but not updated:";
5857 break;
5859 case LINE_STAT_UNTRACKED:
5860 type = LINE_STAT_SECTION;
5861 text = "Untracked files:";
5862 break;
5864 case LINE_STAT_NONE:
5865 type = LINE_DEFAULT;
5866 text = " (no files)";
5867 break;
5869 case LINE_STAT_HEAD:
5870 type = LINE_STAT_HEAD;
5871 text = status_onbranch;
5872 break;
5874 default:
5875 return FALSE;
5877 } else {
5878 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5880 buf[0] = status->status;
5881 if (draw_text(view, line->type, buf))
5882 return TRUE;
5883 type = LINE_DEFAULT;
5884 text = status->new.name;
5887 draw_text(view, type, text);
5888 return TRUE;
5891 static enum request
5892 status_enter(struct view *view, struct line *line)
5894 struct status *status = line->data;
5895 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5897 if (line->type == LINE_STAT_NONE ||
5898 (!status && line[1].type == LINE_STAT_NONE)) {
5899 report("No file to diff");
5900 return REQ_NONE;
5903 switch (line->type) {
5904 case LINE_STAT_STAGED:
5905 case LINE_STAT_UNSTAGED:
5906 break;
5908 case LINE_STAT_UNTRACKED:
5909 if (!status) {
5910 report("No file to show");
5911 return REQ_NONE;
5914 if (!suffixcmp(status->new.name, -1, "/")) {
5915 report("Cannot display a directory");
5916 return REQ_NONE;
5918 break;
5920 case LINE_STAT_HEAD:
5921 return REQ_NONE;
5923 default:
5924 die("line type %d not handled in switch", line->type);
5927 if (status) {
5928 stage_status = *status;
5929 } else {
5930 memset(&stage_status, 0, sizeof(stage_status));
5933 stage_line_type = line->type;
5935 open_view(view, REQ_VIEW_STAGE, flags);
5936 return REQ_NONE;
5939 static bool
5940 status_exists(struct view *view, struct status *status, enum line_type type)
5942 unsigned long lineno;
5944 for (lineno = 0; lineno < view->lines; lineno++) {
5945 struct line *line = &view->line[lineno];
5946 struct status *pos = line->data;
5948 if (line->type != type)
5949 continue;
5950 if (!pos && (!status || !status->status) && line[1].data) {
5951 select_view_line(view, lineno);
5952 return TRUE;
5954 if (pos && !strcmp(status->new.name, pos->new.name)) {
5955 select_view_line(view, lineno);
5956 return TRUE;
5960 return FALSE;
5964 static bool
5965 status_update_prepare(struct io *io, enum line_type type)
5967 const char *staged_argv[] = {
5968 "git", "update-index", "-z", "--index-info", NULL
5970 const char *others_argv[] = {
5971 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5974 switch (type) {
5975 case LINE_STAT_STAGED:
5976 return io_run(io, IO_WR, opt_cdup, staged_argv);
5978 case LINE_STAT_UNSTAGED:
5979 case LINE_STAT_UNTRACKED:
5980 return io_run(io, IO_WR, opt_cdup, others_argv);
5982 default:
5983 die("line type %d not handled in switch", type);
5984 return FALSE;
5988 static bool
5989 status_update_write(struct io *io, struct status *status, enum line_type type)
5991 switch (type) {
5992 case LINE_STAT_STAGED:
5993 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
5994 status->old.rev, status->old.name, 0);
5996 case LINE_STAT_UNSTAGED:
5997 case LINE_STAT_UNTRACKED:
5998 return io_printf(io, "%s%c", status->new.name, 0);
6000 default:
6001 die("line type %d not handled in switch", type);
6002 return FALSE;
6006 static bool
6007 status_update_file(struct status *status, enum line_type type)
6009 struct io io;
6010 bool result;
6012 if (!status_update_prepare(&io, type))
6013 return FALSE;
6015 result = status_update_write(&io, status, type);
6016 return io_done(&io) && result;
6019 static bool
6020 status_update_files(struct view *view, struct line *line)
6022 char buf[sizeof(view->ref)];
6023 struct io io;
6024 bool result = TRUE;
6025 struct line *pos = view->line + view->lines;
6026 int files = 0;
6027 int file, done;
6028 int cursor_y = -1, cursor_x = -1;
6030 if (!status_update_prepare(&io, line->type))
6031 return FALSE;
6033 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
6034 files++;
6036 string_copy(buf, view->ref);
6037 getsyx(cursor_y, cursor_x);
6038 for (file = 0, done = 5; result && file < files; line++, file++) {
6039 int almost_done = file * 100 / files;
6041 if (almost_done > done) {
6042 done = almost_done;
6043 string_format(view->ref, "updating file %u of %u (%d%% done)",
6044 file, files, done);
6045 update_view_title(view);
6046 setsyx(cursor_y, cursor_x);
6047 doupdate();
6049 result = status_update_write(&io, line->data, line->type);
6051 string_copy(view->ref, buf);
6053 return io_done(&io) && result;
6056 static bool
6057 status_update(struct view *view)
6059 struct line *line = &view->line[view->pos.lineno];
6061 assert(view->lines);
6063 if (!line->data) {
6064 /* This should work even for the "On branch" line. */
6065 if (line < view->line + view->lines && !line[1].data) {
6066 report("Nothing to update");
6067 return FALSE;
6070 if (!status_update_files(view, line + 1)) {
6071 report("Failed to update file status");
6072 return FALSE;
6075 } else if (!status_update_file(line->data, line->type)) {
6076 report("Failed to update file status");
6077 return FALSE;
6080 return TRUE;
6083 static bool
6084 status_revert(struct status *status, enum line_type type, bool has_none)
6086 if (!status || type != LINE_STAT_UNSTAGED) {
6087 if (type == LINE_STAT_STAGED) {
6088 report("Cannot revert changes to staged files");
6089 } else if (type == LINE_STAT_UNTRACKED) {
6090 report("Cannot revert changes to untracked files");
6091 } else if (has_none) {
6092 report("Nothing to revert");
6093 } else {
6094 report("Cannot revert changes to multiple files");
6097 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6098 char mode[10] = "100644";
6099 const char *reset_argv[] = {
6100 "git", "update-index", "--cacheinfo", mode,
6101 status->old.rev, status->old.name, NULL
6103 const char *checkout_argv[] = {
6104 "git", "checkout", "--", status->old.name, NULL
6107 if (status->status == 'U') {
6108 string_format(mode, "%5o", status->old.mode);
6110 if (status->old.mode == 0 && status->new.mode == 0) {
6111 reset_argv[2] = "--force-remove";
6112 reset_argv[3] = status->old.name;
6113 reset_argv[4] = NULL;
6116 if (!io_run_fg(reset_argv, opt_cdup))
6117 return FALSE;
6118 if (status->old.mode == 0 && status->new.mode == 0)
6119 return TRUE;
6122 return io_run_fg(checkout_argv, opt_cdup);
6125 return FALSE;
6128 static enum request
6129 status_request(struct view *view, enum request request, struct line *line)
6131 struct status *status = line->data;
6133 switch (request) {
6134 case REQ_STATUS_UPDATE:
6135 if (!status_update(view))
6136 return REQ_NONE;
6137 break;
6139 case REQ_STATUS_REVERT:
6140 if (!status_revert(status, line->type, status_has_none(view, line)))
6141 return REQ_NONE;
6142 break;
6144 case REQ_STATUS_MERGE:
6145 if (!status || status->status != 'U') {
6146 report("Merging only possible for files with unmerged status ('U').");
6147 return REQ_NONE;
6149 open_mergetool(status->new.name);
6150 break;
6152 case REQ_EDIT:
6153 if (!status)
6154 return request;
6155 if (status->status == 'D') {
6156 report("File has been deleted.");
6157 return REQ_NONE;
6160 open_editor(status->new.name);
6161 break;
6163 case REQ_VIEW_BLAME:
6164 if (status)
6165 opt_ref[0] = 0;
6166 return request;
6168 case REQ_ENTER:
6169 /* After returning the status view has been split to
6170 * show the stage view. No further reloading is
6171 * necessary. */
6172 return status_enter(view, line);
6174 case REQ_REFRESH:
6175 /* Simply reload the view. */
6176 break;
6178 default:
6179 return request;
6182 refresh_view(view);
6184 return REQ_NONE;
6187 static void
6188 status_select(struct view *view, struct line *line)
6190 struct status *status = line->data;
6191 char file[SIZEOF_STR] = "all files";
6192 const char *text;
6193 const char *key;
6195 if (status && !string_format(file, "'%s'", status->new.name))
6196 return;
6198 if (!status && line[1].type == LINE_STAT_NONE)
6199 line++;
6201 switch (line->type) {
6202 case LINE_STAT_STAGED:
6203 text = "Press %s to unstage %s for commit";
6204 break;
6206 case LINE_STAT_UNSTAGED:
6207 text = "Press %s to stage %s for commit";
6208 break;
6210 case LINE_STAT_UNTRACKED:
6211 text = "Press %s to stage %s for addition";
6212 break;
6214 case LINE_STAT_HEAD:
6215 case LINE_STAT_NONE:
6216 text = "Nothing to update";
6217 break;
6219 default:
6220 die("line type %d not handled in switch", line->type);
6223 if (status && status->status == 'U') {
6224 text = "Press %s to resolve conflict in %s";
6225 key = get_view_key(view, REQ_STATUS_MERGE);
6227 } else {
6228 key = get_view_key(view, REQ_STATUS_UPDATE);
6231 string_format(view->ref, text, key, file);
6232 if (status)
6233 string_copy(opt_file, status->new.name);
6236 static bool
6237 status_grep(struct view *view, struct line *line)
6239 struct status *status = line->data;
6241 if (status) {
6242 const char buf[2] = { status->status, 0 };
6243 const char *text[] = { status->new.name, buf, NULL };
6245 return grep_text(view, text);
6248 return FALSE;
6251 static struct view_ops status_ops = {
6252 "file",
6253 VIEW_CUSTOM_STATUS,
6255 status_open,
6256 NULL,
6257 status_draw,
6258 status_request,
6259 status_grep,
6260 status_select,
6264 struct stage_state {
6265 struct diff_state diff;
6266 size_t chunks;
6267 int *chunk;
6270 static bool
6271 stage_diff_write(struct io *io, struct line *line, struct line *end)
6273 while (line < end) {
6274 if (!io_write(io, line->data, strlen(line->data)) ||
6275 !io_write(io, "\n", 1))
6276 return FALSE;
6277 line++;
6278 if (line->type == LINE_DIFF_CHUNK ||
6279 line->type == LINE_DIFF_HEADER)
6280 break;
6283 return TRUE;
6286 static bool
6287 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6289 const char *apply_argv[SIZEOF_ARG] = {
6290 "git", "apply", "--whitespace=nowarn", NULL
6292 struct line *diff_hdr;
6293 struct io io;
6294 int argc = 3;
6296 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6297 if (!diff_hdr)
6298 return FALSE;
6300 if (!revert)
6301 apply_argv[argc++] = "--cached";
6302 if (line != NULL)
6303 apply_argv[argc++] = "--unidiff-zero";
6304 if (revert || stage_line_type == LINE_STAT_STAGED)
6305 apply_argv[argc++] = "-R";
6306 apply_argv[argc++] = "-";
6307 apply_argv[argc++] = NULL;
6308 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6309 return FALSE;
6311 if (line != NULL) {
6312 int lineno = 0;
6313 struct line *context = chunk + 1;
6314 const char *markers[] = {
6315 line->type == LINE_DIFF_DEL ? "" : ",0",
6316 line->type == LINE_DIFF_DEL ? ",0" : "",
6319 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6321 while (context < line) {
6322 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6323 break;
6324 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6325 lineno++;
6327 context++;
6330 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6331 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6332 lineno, markers[0], lineno, markers[1]) ||
6333 !stage_diff_write(&io, line, line + 1)) {
6334 chunk = NULL;
6336 } else {
6337 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6338 !stage_diff_write(&io, chunk, view->line + view->lines))
6339 chunk = NULL;
6342 io_done(&io);
6343 io_run_bg(update_index_argv);
6345 return chunk ? TRUE : FALSE;
6348 static bool
6349 stage_update(struct view *view, struct line *line, bool single)
6351 struct line *chunk = NULL;
6353 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6354 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6356 if (chunk) {
6357 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6358 report("Failed to apply chunk");
6359 return FALSE;
6362 } else if (!stage_status.status) {
6363 view = view->parent;
6365 for (line = view->line; line < view->line + view->lines; line++)
6366 if (line->type == stage_line_type)
6367 break;
6369 if (!status_update_files(view, line + 1)) {
6370 report("Failed to update files");
6371 return FALSE;
6374 } else if (!status_update_file(&stage_status, stage_line_type)) {
6375 report("Failed to update file");
6376 return FALSE;
6379 return TRUE;
6382 static bool
6383 stage_revert(struct view *view, struct line *line)
6385 struct line *chunk = NULL;
6387 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6388 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6390 if (chunk) {
6391 if (!prompt_yesno("Are you sure you want to revert changes?"))
6392 return FALSE;
6394 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6395 report("Failed to revert chunk");
6396 return FALSE;
6398 return TRUE;
6400 } else {
6401 return status_revert(stage_status.status ? &stage_status : NULL,
6402 stage_line_type, FALSE);
6407 static void
6408 stage_next(struct view *view, struct line *line)
6410 struct stage_state *state = view->private;
6411 int i;
6413 if (!state->chunks) {
6414 for (line = view->line; line < view->line + view->lines; line++) {
6415 if (line->type != LINE_DIFF_CHUNK)
6416 continue;
6418 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6419 report("Allocation failure");
6420 return;
6423 state->chunk[state->chunks++] = line - view->line;
6427 for (i = 0; i < state->chunks; i++) {
6428 if (state->chunk[i] > view->pos.lineno) {
6429 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
6430 report("Chunk %d of %d", i + 1, state->chunks);
6431 return;
6435 report("No next chunk found");
6438 static enum request
6439 stage_request(struct view *view, enum request request, struct line *line)
6441 switch (request) {
6442 case REQ_STATUS_UPDATE:
6443 if (!stage_update(view, line, FALSE))
6444 return REQ_NONE;
6445 break;
6447 case REQ_STATUS_REVERT:
6448 if (!stage_revert(view, line))
6449 return REQ_NONE;
6450 break;
6452 case REQ_STAGE_UPDATE_LINE:
6453 if (stage_line_type == LINE_STAT_UNTRACKED ||
6454 stage_status.status == 'A') {
6455 report("Staging single lines is not supported for new files");
6456 return REQ_NONE;
6458 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6459 report("Please select a change to stage");
6460 return REQ_NONE;
6462 if (!stage_update(view, line, TRUE))
6463 return REQ_NONE;
6464 break;
6466 case REQ_STAGE_NEXT:
6467 if (stage_line_type == LINE_STAT_UNTRACKED) {
6468 report("File is untracked; press %s to add",
6469 get_view_key(view, REQ_STATUS_UPDATE));
6470 return REQ_NONE;
6472 stage_next(view, line);
6473 return REQ_NONE;
6475 case REQ_EDIT:
6476 if (!stage_status.new.name[0])
6477 return request;
6478 if (stage_status.status == 'D') {
6479 report("File has been deleted.");
6480 return REQ_NONE;
6483 open_editor(stage_status.new.name);
6484 break;
6486 case REQ_REFRESH:
6487 /* Reload everything ... */
6488 break;
6490 case REQ_VIEW_BLAME:
6491 if (stage_status.new.name[0]) {
6492 string_copy(opt_file, stage_status.new.name);
6493 opt_ref[0] = 0;
6495 return request;
6497 case REQ_ENTER:
6498 return diff_common_enter(view, request, line);
6500 case REQ_DIFF_CONTEXT_UP:
6501 case REQ_DIFF_CONTEXT_DOWN:
6502 if (!update_diff_context(request))
6503 return REQ_NONE;
6504 break;
6506 default:
6507 return request;
6510 refresh_view(view->parent);
6512 /* Check whether the staged entry still exists, and close the
6513 * stage view if it doesn't. */
6514 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6515 status_restore(view->parent);
6516 return REQ_VIEW_CLOSE;
6519 refresh_view(view);
6521 return REQ_NONE;
6524 static bool
6525 stage_open(struct view *view, enum open_flags flags)
6527 static const char *no_head_diff_argv[] = {
6528 GIT_DIFF_STAGED_INITIAL(opt_diff_context_arg, opt_ignore_space_arg,
6529 stage_status.new.name)
6531 static const char *index_show_argv[] = {
6532 GIT_DIFF_STAGED(opt_diff_context_arg, opt_ignore_space_arg,
6533 stage_status.old.name, stage_status.new.name)
6535 static const char *files_show_argv[] = {
6536 GIT_DIFF_UNSTAGED(opt_diff_context_arg, opt_ignore_space_arg,
6537 stage_status.old.name, stage_status.new.name)
6539 /* Diffs for unmerged entries are empty when passing the new
6540 * path, so leave out the new path. */
6541 static const char *files_unmerged_argv[] = {
6542 "git", "diff-files", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6543 opt_diff_context_arg, opt_ignore_space_arg, "--",
6544 stage_status.old.name, NULL
6546 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6547 const char **argv = NULL;
6548 const char *info;
6550 view->encoding = NULL;
6552 switch (stage_line_type) {
6553 case LINE_STAT_STAGED:
6554 if (is_initial_commit()) {
6555 argv = no_head_diff_argv;
6556 } else {
6557 argv = index_show_argv;
6559 if (stage_status.status)
6560 info = "Staged changes to %s";
6561 else
6562 info = "Staged changes";
6563 break;
6565 case LINE_STAT_UNSTAGED:
6566 if (stage_status.status != 'U')
6567 argv = files_show_argv;
6568 else
6569 argv = files_unmerged_argv;
6570 if (stage_status.status)
6571 info = "Unstaged changes to %s";
6572 else
6573 info = "Unstaged changes";
6574 break;
6576 case LINE_STAT_UNTRACKED:
6577 info = "Untracked file %s";
6578 argv = file_argv;
6579 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
6580 break;
6582 case LINE_STAT_HEAD:
6583 default:
6584 die("line type %d not handled in switch", stage_line_type);
6587 string_format(view->ref, info, stage_status.new.name);
6588 view->vid[0] = 0;
6589 view->dir = opt_cdup;
6590 return argv_copy(&view->argv, argv)
6591 && begin_update(view, NULL, NULL, flags);
6594 static bool
6595 stage_read(struct view *view, char *data)
6597 struct stage_state *state = view->private;
6599 if (data && diff_common_read(view, data, &state->diff))
6600 return TRUE;
6602 return pager_read(view, data);
6605 static struct view_ops stage_ops = {
6606 "line",
6607 VIEW_DIFF_LIKE,
6608 sizeof(struct stage_state),
6609 stage_open,
6610 stage_read,
6611 diff_common_draw,
6612 stage_request,
6613 pager_grep,
6614 pager_select,
6619 * Revision graph
6622 static const enum line_type graph_colors[] = {
6623 LINE_PALETTE_0,
6624 LINE_PALETTE_1,
6625 LINE_PALETTE_2,
6626 LINE_PALETTE_3,
6627 LINE_PALETTE_4,
6628 LINE_PALETTE_5,
6629 LINE_PALETTE_6,
6632 static enum line_type get_graph_color(struct graph_symbol *symbol)
6634 if (symbol->commit)
6635 return LINE_GRAPH_COMMIT;
6636 assert(symbol->color < ARRAY_SIZE(graph_colors));
6637 return graph_colors[symbol->color];
6640 static bool
6641 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6643 const char *chars = graph_symbol_to_utf8(symbol);
6645 return draw_text(view, color, chars + !!first);
6648 static bool
6649 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6651 const char *chars = graph_symbol_to_ascii(symbol);
6653 return draw_text(view, color, chars + !!first);
6656 static bool
6657 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6659 const chtype *chars = graph_symbol_to_chtype(symbol);
6661 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6664 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6666 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6668 static const draw_graph_fn fns[] = {
6669 draw_graph_ascii,
6670 draw_graph_chtype,
6671 draw_graph_utf8
6673 draw_graph_fn fn = fns[opt_line_graphics];
6674 int i;
6676 for (i = 0; i < canvas->size; i++) {
6677 struct graph_symbol *symbol = &canvas->symbols[i];
6678 enum line_type color = get_graph_color(symbol);
6680 if (fn(view, symbol, color, i == 0))
6681 return TRUE;
6684 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6688 * Main view backend
6691 struct commit {
6692 char id[SIZEOF_REV]; /* SHA1 ID. */
6693 char title[128]; /* First line of the commit message. */
6694 const char *author; /* Author of the commit. */
6695 struct time time; /* Date from the author ident. */
6696 struct ref_list *refs; /* Repository references. */
6697 struct graph_canvas graph; /* Ancestry chain graphics. */
6700 static struct commit *
6701 main_add_commit(struct view *view, enum line_type type, const char *ids, bool is_boundary)
6703 struct graph *graph = view->private;
6704 struct commit *commit;
6706 commit = calloc(1, sizeof(struct commit));
6707 if (!commit)
6708 return NULL;
6710 string_copy_rev(commit->id, ids);
6711 commit->refs = get_ref_list(commit->id);
6712 add_line_data(view, commit, type);
6713 graph_add_commit(graph, &commit->graph, commit->id, ids, is_boundary);
6714 return commit;
6717 bool
6718 main_has_changes(const char *argv[])
6720 struct io io;
6722 if (!io_run(&io, IO_BG, NULL, argv, -1))
6723 return FALSE;
6724 io_done(&io);
6725 return io.status == 1;
6728 static void
6729 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
6731 char ids[SIZEOF_STR] = NULL_ID " ";
6732 struct graph *graph = view->private;
6733 struct commit *commit;
6734 struct timeval now;
6735 struct timezone tz;
6737 if (!parent)
6738 return;
6740 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
6742 commit = main_add_commit(view, type, ids, FALSE);
6743 if (!commit)
6744 return;
6746 if (!gettimeofday(&now, &tz)) {
6747 commit->time.tz = tz.tz_minuteswest * 60;
6748 commit->time.sec = now.tv_sec - commit->time.tz;
6751 commit->author = "";
6752 string_ncopy(commit->title, title, strlen(title));
6753 graph_render_parents(graph);
6756 static void
6757 main_add_changes_commits(struct view *view, const char *parent)
6759 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
6760 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
6761 const char *staged_parent = NULL_ID;
6762 const char *unstaged_parent = parent;
6764 if (!main_has_changes(unstaged_argv)) {
6765 unstaged_parent = NULL;
6766 staged_parent = parent;
6769 if (!main_has_changes(staged_argv)) {
6770 staged_parent = NULL;
6773 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
6774 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
6777 static bool
6778 main_open(struct view *view, enum open_flags flags)
6780 static const char *main_argv[] = {
6781 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw", "--parents",
6782 opt_commit_order_arg, "%(diffargs)", "%(revargs)",
6783 "--", "%(fileargs)", NULL
6786 return begin_update(view, NULL, main_argv, flags);
6789 static bool
6790 main_draw(struct view *view, struct line *line, unsigned int lineno)
6792 struct commit *commit = line->data;
6794 if (!commit->author)
6795 return FALSE;
6797 if (draw_lineno(view, lineno))
6798 return TRUE;
6800 if (draw_date(view, &commit->time))
6801 return TRUE;
6803 if (draw_author(view, commit->author))
6804 return TRUE;
6806 if (opt_rev_graph && draw_graph(view, &commit->graph))
6807 return TRUE;
6809 if (draw_refs(view, commit->refs))
6810 return TRUE;
6812 draw_text(view, LINE_DEFAULT, commit->title);
6813 return TRUE;
6816 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6817 static bool
6818 main_read(struct view *view, char *line)
6820 struct graph *graph = view->private;
6821 enum line_type type;
6822 struct commit *commit;
6823 static bool in_header;
6825 if (!line) {
6826 if (!view->lines && !view->prev)
6827 die("No revisions match the given arguments.");
6828 if (view->lines > 0) {
6829 commit = view->line[view->lines - 1].data;
6830 view->line[view->lines - 1].dirty = 1;
6831 if (!commit->author) {
6832 view->lines--;
6833 free(commit);
6837 done_graph(graph);
6838 return TRUE;
6841 type = get_line_type(line);
6842 if (type == LINE_COMMIT) {
6843 bool is_boundary;
6845 in_header = TRUE;
6846 line += STRING_SIZE("commit ");
6847 is_boundary = *line == '-';
6848 if (is_boundary)
6849 line++;
6851 if (opt_show_changes && opt_is_inside_work_tree && !view->lines)
6852 main_add_changes_commits(view, line);
6854 return main_add_commit(view, LINE_MAIN_COMMIT, line, is_boundary) != NULL;
6857 if (!view->lines)
6858 return TRUE;
6859 commit = view->line[view->lines - 1].data;
6861 /* Empty line separates the commit header from the log itself. */
6862 if (*line == '\0')
6863 in_header = FALSE;
6865 switch (type) {
6866 case LINE_PARENT:
6867 if (!graph->has_parents)
6868 graph_add_parent(graph, line + STRING_SIZE("parent "));
6869 break;
6871 case LINE_AUTHOR:
6872 parse_author_line(line + STRING_SIZE("author "),
6873 &commit->author, &commit->time);
6874 graph_render_parents(graph);
6875 break;
6877 default:
6878 /* Fill in the commit title if it has not already been set. */
6879 if (commit->title[0])
6880 break;
6882 /* Skip lines in the commit header. */
6883 if (in_header)
6884 break;
6886 /* Require titles to start with a non-space character at the
6887 * offset used by git log. */
6888 if (strncmp(line, " ", 4))
6889 break;
6890 line += 4;
6891 /* Well, if the title starts with a whitespace character,
6892 * try to be forgiving. Otherwise we end up with no title. */
6893 while (isspace(*line))
6894 line++;
6895 if (*line == '\0')
6896 break;
6897 /* FIXME: More graceful handling of titles; append "..." to
6898 * shortened titles, etc. */
6900 string_expand(commit->title, sizeof(commit->title), line, 1);
6901 view->line[view->lines - 1].dirty = 1;
6904 return TRUE;
6907 static enum request
6908 main_request(struct view *view, enum request request, struct line *line)
6910 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6912 switch (request) {
6913 case REQ_NEXT:
6914 case REQ_PREVIOUS:
6915 if (view_is_displayed(view) && display[0] != view)
6916 return request;
6917 /* Do not pass navigation requests to the branch view
6918 * when the main view is maximized. (GH #38) */
6919 move_view(view, request);
6920 break;
6922 case REQ_ENTER:
6923 if (view_is_displayed(view) && display[0] != view)
6924 maximize_view(view, TRUE);
6926 if (line->type == LINE_STAT_UNSTAGED
6927 || line->type == LINE_STAT_STAGED) {
6928 struct view *diff = VIEW(REQ_VIEW_DIFF);
6929 const char *diff_staged_argv[] = {
6930 GIT_DIFF_STAGED(opt_diff_context_arg,
6931 opt_ignore_space_arg, NULL, NULL)
6933 const char *diff_unstaged_argv[] = {
6934 GIT_DIFF_UNSTAGED(opt_diff_context_arg,
6935 opt_ignore_space_arg, NULL, NULL)
6937 const char **diff_argv = line->type == LINE_STAT_STAGED
6938 ? diff_staged_argv : diff_unstaged_argv;
6940 open_argv(view, diff, diff_argv, NULL, flags);
6941 break;
6944 open_view(view, REQ_VIEW_DIFF, flags);
6945 break;
6946 case REQ_REFRESH:
6947 load_refs();
6948 refresh_view(view);
6949 break;
6951 case REQ_JUMP_COMMIT:
6953 int lineno;
6955 for (lineno = 0; lineno < view->lines; lineno++) {
6956 struct commit *commit = view->line[lineno].data;
6958 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
6959 select_view_line(view, lineno);
6960 report("");
6961 return REQ_NONE;
6965 report("Unable to find commit '%s'", opt_search);
6966 break;
6968 default:
6969 return request;
6972 return REQ_NONE;
6975 static bool
6976 grep_refs(struct ref_list *list, regex_t *regex)
6978 regmatch_t pmatch;
6979 size_t i;
6981 if (!opt_show_refs || !list)
6982 return FALSE;
6984 for (i = 0; i < list->size; i++) {
6985 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
6986 return TRUE;
6989 return FALSE;
6992 static bool
6993 main_grep(struct view *view, struct line *line)
6995 struct commit *commit = line->data;
6996 const char *text[] = {
6997 commit->title,
6998 mkauthor(commit->author, opt_author_cols, opt_author),
6999 mkdate(&commit->time, opt_date),
7000 NULL
7003 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
7006 static void
7007 main_select(struct view *view, struct line *line)
7009 struct commit *commit = line->data;
7011 string_copy_rev(view->ref, commit->id);
7012 string_copy_rev(ref_commit, view->ref);
7015 static struct view_ops main_ops = {
7016 "commit",
7017 VIEW_NO_FLAGS,
7018 sizeof(struct graph),
7019 main_open,
7020 main_read,
7021 main_draw,
7022 main_request,
7023 main_grep,
7024 main_select,
7029 * Status management
7032 /* Whether or not the curses interface has been initialized. */
7033 static bool cursed = FALSE;
7035 /* Terminal hacks and workarounds. */
7036 static bool use_scroll_redrawwin;
7037 static bool use_scroll_status_wclear;
7039 /* The status window is used for polling keystrokes. */
7040 static WINDOW *status_win;
7042 /* Reading from the prompt? */
7043 static bool input_mode = FALSE;
7045 static bool status_empty = FALSE;
7047 /* Update status and title window. */
7048 static void
7049 report(const char *msg, ...)
7051 struct view *view = display[current_view];
7053 if (input_mode)
7054 return;
7056 if (!view) {
7057 char buf[SIZEOF_STR];
7058 int retval;
7060 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
7061 die("%s", buf);
7064 if (!status_empty || *msg) {
7065 va_list args;
7067 va_start(args, msg);
7069 wmove(status_win, 0, 0);
7070 if (view->has_scrolled && use_scroll_status_wclear)
7071 wclear(status_win);
7072 if (*msg) {
7073 vwprintw(status_win, msg, args);
7074 status_empty = FALSE;
7075 } else {
7076 status_empty = TRUE;
7078 wclrtoeol(status_win);
7079 wnoutrefresh(status_win);
7081 va_end(args);
7084 update_view_title(view);
7087 static void
7088 init_display(void)
7090 const char *term;
7091 int x, y;
7093 /* Initialize the curses library */
7094 if (isatty(STDIN_FILENO)) {
7095 cursed = !!initscr();
7096 opt_tty = stdin;
7097 } else {
7098 /* Leave stdin and stdout alone when acting as a pager. */
7099 opt_tty = fopen("/dev/tty", "r+");
7100 if (!opt_tty)
7101 die("Failed to open /dev/tty");
7102 cursed = !!newterm(NULL, opt_tty, opt_tty);
7105 if (!cursed)
7106 die("Failed to initialize curses");
7108 nonl(); /* Disable conversion and detect newlines from input. */
7109 cbreak(); /* Take input chars one at a time, no wait for \n */
7110 noecho(); /* Don't echo input */
7111 leaveok(stdscr, FALSE);
7113 if (has_colors())
7114 init_colors();
7116 getmaxyx(stdscr, y, x);
7117 status_win = newwin(1, x, y - 1, 0);
7118 if (!status_win)
7119 die("Failed to create status window");
7121 /* Enable keyboard mapping */
7122 keypad(status_win, TRUE);
7123 wbkgdset(status_win, get_line_attr(LINE_STATUS));
7125 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
7126 set_tabsize(opt_tab_size);
7127 #else
7128 TABSIZE = opt_tab_size;
7129 #endif
7131 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
7132 if (term && !strcmp(term, "gnome-terminal")) {
7133 /* In the gnome-terminal-emulator, the message from
7134 * scrolling up one line when impossible followed by
7135 * scrolling down one line causes corruption of the
7136 * status line. This is fixed by calling wclear. */
7137 use_scroll_status_wclear = TRUE;
7138 use_scroll_redrawwin = FALSE;
7140 } else if (term && !strcmp(term, "xrvt-xpm")) {
7141 /* No problems with full optimizations in xrvt-(unicode)
7142 * and aterm. */
7143 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
7145 } else {
7146 /* When scrolling in (u)xterm the last line in the
7147 * scrolling direction will update slowly. */
7148 use_scroll_redrawwin = TRUE;
7149 use_scroll_status_wclear = FALSE;
7153 static int
7154 get_input(int prompt_position)
7156 struct view *view;
7157 int i, key, cursor_y, cursor_x;
7159 if (prompt_position)
7160 input_mode = TRUE;
7162 while (TRUE) {
7163 bool loading = FALSE;
7165 foreach_view (view, i) {
7166 update_view(view);
7167 if (view_is_displayed(view) && view->has_scrolled &&
7168 use_scroll_redrawwin)
7169 redrawwin(view->win);
7170 view->has_scrolled = FALSE;
7171 if (view->pipe)
7172 loading = TRUE;
7175 /* Update the cursor position. */
7176 if (prompt_position) {
7177 getbegyx(status_win, cursor_y, cursor_x);
7178 cursor_x = prompt_position;
7179 } else {
7180 view = display[current_view];
7181 getbegyx(view->win, cursor_y, cursor_x);
7182 cursor_x = view->width - 1;
7183 cursor_y += view->pos.lineno - view->pos.offset;
7185 setsyx(cursor_y, cursor_x);
7187 /* Refresh, accept single keystroke of input */
7188 doupdate();
7189 nodelay(status_win, loading);
7190 key = wgetch(status_win);
7192 /* wgetch() with nodelay() enabled returns ERR when
7193 * there's no input. */
7194 if (key == ERR) {
7196 } else if (key == KEY_RESIZE) {
7197 int height, width;
7199 getmaxyx(stdscr, height, width);
7201 wresize(status_win, 1, width);
7202 mvwin(status_win, height - 1, 0);
7203 wnoutrefresh(status_win);
7204 resize_display();
7205 redraw_display(TRUE);
7207 } else {
7208 input_mode = FALSE;
7209 if (key == erasechar())
7210 key = KEY_BACKSPACE;
7211 return key;
7216 static char *
7217 prompt_input(const char *prompt, input_handler handler, void *data)
7219 enum input_status status = INPUT_OK;
7220 static char buf[SIZEOF_STR];
7221 size_t pos = 0;
7223 buf[pos] = 0;
7225 while (status == INPUT_OK || status == INPUT_SKIP) {
7226 int key;
7228 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
7229 wclrtoeol(status_win);
7231 key = get_input(pos + 1);
7232 switch (key) {
7233 case KEY_RETURN:
7234 case KEY_ENTER:
7235 case '\n':
7236 status = pos ? INPUT_STOP : INPUT_CANCEL;
7237 break;
7239 case KEY_BACKSPACE:
7240 if (pos > 0)
7241 buf[--pos] = 0;
7242 else
7243 status = INPUT_CANCEL;
7244 break;
7246 case KEY_ESC:
7247 status = INPUT_CANCEL;
7248 break;
7250 default:
7251 if (pos >= sizeof(buf)) {
7252 report("Input string too long");
7253 return NULL;
7256 status = handler(data, buf, key);
7257 if (status == INPUT_OK)
7258 buf[pos++] = (char) key;
7262 /* Clear the status window */
7263 status_empty = FALSE;
7264 report("");
7266 if (status == INPUT_CANCEL)
7267 return NULL;
7269 buf[pos++] = 0;
7271 return buf;
7274 static enum input_status
7275 prompt_yesno_handler(void *data, char *buf, int c)
7277 if (c == 'y' || c == 'Y')
7278 return INPUT_STOP;
7279 if (c == 'n' || c == 'N')
7280 return INPUT_CANCEL;
7281 return INPUT_SKIP;
7284 static bool
7285 prompt_yesno(const char *prompt)
7287 char prompt2[SIZEOF_STR];
7289 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7290 return FALSE;
7292 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7295 static enum input_status
7296 read_prompt_handler(void *data, char *buf, int c)
7298 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7301 static char *
7302 read_prompt(const char *prompt)
7304 return prompt_input(prompt, read_prompt_handler, NULL);
7307 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7309 enum input_status status = INPUT_OK;
7310 int size = 0;
7312 while (items[size].text)
7313 size++;
7315 while (status == INPUT_OK) {
7316 const struct menu_item *item = &items[*selected];
7317 int key;
7318 int i;
7320 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7321 prompt, *selected + 1, size);
7322 if (item->hotkey)
7323 wprintw(status_win, "[%c] ", (char) item->hotkey);
7324 wprintw(status_win, "%s", item->text);
7325 wclrtoeol(status_win);
7327 key = get_input(COLS - 1);
7328 switch (key) {
7329 case KEY_RETURN:
7330 case KEY_ENTER:
7331 case '\n':
7332 status = INPUT_STOP;
7333 break;
7335 case KEY_LEFT:
7336 case KEY_UP:
7337 *selected = *selected - 1;
7338 if (*selected < 0)
7339 *selected = size - 1;
7340 break;
7342 case KEY_RIGHT:
7343 case KEY_DOWN:
7344 *selected = (*selected + 1) % size;
7345 break;
7347 case KEY_ESC:
7348 status = INPUT_CANCEL;
7349 break;
7351 default:
7352 for (i = 0; items[i].text; i++)
7353 if (items[i].hotkey == key) {
7354 *selected = i;
7355 status = INPUT_STOP;
7356 break;
7361 /* Clear the status window */
7362 status_empty = FALSE;
7363 report("");
7365 return status != INPUT_CANCEL;
7369 * Repository properties
7372 static struct ref **refs = NULL;
7373 static size_t refs_size = 0;
7374 static struct ref *refs_head = NULL;
7376 static struct ref_list **ref_lists = NULL;
7377 static size_t ref_lists_size = 0;
7379 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
7380 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
7381 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
7383 static int
7384 compare_refs(const void *ref1_, const void *ref2_)
7386 const struct ref *ref1 = *(const struct ref **)ref1_;
7387 const struct ref *ref2 = *(const struct ref **)ref2_;
7389 if (ref1->tag != ref2->tag)
7390 return ref2->tag - ref1->tag;
7391 if (ref1->ltag != ref2->ltag)
7392 return ref2->ltag - ref1->ltag;
7393 if (ref1->head != ref2->head)
7394 return ref2->head - ref1->head;
7395 if (ref1->tracked != ref2->tracked)
7396 return ref2->tracked - ref1->tracked;
7397 if (ref1->replace != ref2->replace)
7398 return ref2->replace - ref1->replace;
7399 /* Order remotes last. */
7400 if (ref1->remote != ref2->remote)
7401 return ref1->remote - ref2->remote;
7402 return strcmp(ref1->name, ref2->name);
7405 static void
7406 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
7408 size_t i;
7410 for (i = 0; i < refs_size; i++)
7411 if (!visitor(data, refs[i]))
7412 break;
7415 static struct ref *
7416 get_ref_head()
7418 return refs_head;
7421 static struct ref_list *
7422 get_ref_list(const char *id)
7424 struct ref_list *list;
7425 size_t i;
7427 for (i = 0; i < ref_lists_size; i++)
7428 if (!strcmp(id, ref_lists[i]->id))
7429 return ref_lists[i];
7431 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
7432 return NULL;
7433 list = calloc(1, sizeof(*list));
7434 if (!list)
7435 return NULL;
7437 for (i = 0; i < refs_size; i++) {
7438 if (!strcmp(id, refs[i]->id) &&
7439 realloc_refs_list(&list->refs, list->size, 1))
7440 list->refs[list->size++] = refs[i];
7443 if (!list->refs) {
7444 free(list);
7445 return NULL;
7448 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
7449 ref_lists[ref_lists_size++] = list;
7450 return list;
7453 static int
7454 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
7456 struct ref *ref = NULL;
7457 bool tag = FALSE;
7458 bool ltag = FALSE;
7459 bool remote = FALSE;
7460 bool replace = FALSE;
7461 bool tracked = FALSE;
7462 bool head = FALSE;
7463 int pos;
7465 if (!prefixcmp(name, "refs/tags/")) {
7466 if (!suffixcmp(name, namelen, "^{}")) {
7467 namelen -= 3;
7468 name[namelen] = 0;
7469 } else {
7470 ltag = TRUE;
7473 tag = TRUE;
7474 namelen -= STRING_SIZE("refs/tags/");
7475 name += STRING_SIZE("refs/tags/");
7477 } else if (!prefixcmp(name, "refs/remotes/")) {
7478 remote = TRUE;
7479 namelen -= STRING_SIZE("refs/remotes/");
7480 name += STRING_SIZE("refs/remotes/");
7481 tracked = !strcmp(opt_remote, name);
7483 } else if (!prefixcmp(name, "refs/replace/")) {
7484 replace = TRUE;
7485 id = name + strlen("refs/replace/");
7486 idlen = namelen - strlen("refs/replace/");
7487 name = "replaced";
7488 namelen = strlen(name);
7490 } else if (!prefixcmp(name, "refs/heads/")) {
7491 namelen -= STRING_SIZE("refs/heads/");
7492 name += STRING_SIZE("refs/heads/");
7493 if (strlen(opt_head) == namelen
7494 && !strncmp(opt_head, name, namelen))
7495 return OK;
7497 } else if (!strcmp(name, "HEAD")) {
7498 head = TRUE;
7499 if (*opt_head) {
7500 namelen = strlen(opt_head);
7501 name = opt_head;
7505 /* If we are reloading or it's an annotated tag, replace the
7506 * previous SHA1 with the resolved commit id; relies on the fact
7507 * git-ls-remote lists the commit id of an annotated tag right
7508 * before the commit id it points to. */
7509 for (pos = 0; pos < refs_size; pos++) {
7510 int cmp = replace ? strcmp(id, refs[pos]->id) : strcmp(name, refs[pos]->name);
7512 if (!cmp) {
7513 ref = refs[pos];
7514 break;
7518 if (!ref) {
7519 if (!realloc_refs(&refs, refs_size, 1))
7520 return ERR;
7521 ref = calloc(1, sizeof(*ref) + namelen);
7522 if (!ref)
7523 return ERR;
7524 refs[refs_size++] = ref;
7525 strncpy(ref->name, name, namelen);
7528 ref->head = head;
7529 ref->tag = tag;
7530 ref->ltag = ltag;
7531 ref->remote = remote;
7532 ref->replace = replace;
7533 ref->tracked = tracked;
7534 string_copy_rev(ref->id, id);
7536 if (head)
7537 refs_head = ref;
7538 return OK;
7541 static int
7542 load_refs(void)
7544 const char *head_argv[] = {
7545 "git", "symbolic-ref", "HEAD", NULL
7547 static const char *ls_remote_argv[SIZEOF_ARG] = {
7548 "git", "ls-remote", opt_git_dir, NULL
7550 static bool init = FALSE;
7551 size_t i;
7553 if (!init) {
7554 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
7555 die("TIG_LS_REMOTE contains too many arguments");
7556 init = TRUE;
7559 if (!*opt_git_dir)
7560 return OK;
7562 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
7563 !prefixcmp(opt_head, "refs/heads/")) {
7564 char *offset = opt_head + STRING_SIZE("refs/heads/");
7566 memmove(opt_head, offset, strlen(offset) + 1);
7569 refs_head = NULL;
7570 for (i = 0; i < refs_size; i++)
7571 refs[i]->id[0] = 0;
7573 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
7574 return ERR;
7576 /* Update the ref lists to reflect changes. */
7577 for (i = 0; i < ref_lists_size; i++) {
7578 struct ref_list *list = ref_lists[i];
7579 size_t old, new;
7581 for (old = new = 0; old < list->size; old++)
7582 if (!strcmp(list->id, list->refs[old]->id))
7583 list->refs[new++] = list->refs[old];
7584 list->size = new;
7587 qsort(refs, refs_size, sizeof(*refs), compare_refs);
7589 return OK;
7592 static void
7593 set_remote_branch(const char *name, const char *value, size_t valuelen)
7595 if (!strcmp(name, ".remote")) {
7596 string_ncopy(opt_remote, value, valuelen);
7598 } else if (*opt_remote && !strcmp(name, ".merge")) {
7599 size_t from = strlen(opt_remote);
7601 if (!prefixcmp(value, "refs/heads/"))
7602 value += STRING_SIZE("refs/heads/");
7604 if (!string_format_from(opt_remote, &from, "/%s", value))
7605 opt_remote[0] = 0;
7609 static void
7610 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7612 const char *argv[SIZEOF_ARG] = { name, "=" };
7613 int argc = 1 + (cmd == option_set_command);
7614 enum option_code error;
7616 if (!argv_from_string(argv, &argc, value))
7617 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7618 else
7619 error = cmd(argc, argv);
7621 if (error != OPT_OK)
7622 warn("Option 'tig.%s': %s", name, option_errors[error]);
7625 static bool
7626 set_environment_variable(const char *name, const char *value)
7628 size_t len = strlen(name) + 1 + strlen(value) + 1;
7629 char *env = malloc(len);
7631 if (env &&
7632 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7633 putenv(env) == 0)
7634 return TRUE;
7635 free(env);
7636 return FALSE;
7639 static void
7640 set_work_tree(const char *value)
7642 char cwd[SIZEOF_STR];
7644 if (!getcwd(cwd, sizeof(cwd)))
7645 die("Failed to get cwd path: %s", strerror(errno));
7646 if (chdir(opt_git_dir) < 0)
7647 die("Failed to chdir(%s): %s", strerror(errno));
7648 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7649 die("Failed to get git path: %s", strerror(errno));
7650 if (chdir(cwd) < 0)
7651 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7652 if (chdir(value) < 0)
7653 die("Failed to chdir(%s): %s", value, strerror(errno));
7654 if (!getcwd(cwd, sizeof(cwd)))
7655 die("Failed to get cwd path: %s", strerror(errno));
7656 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7657 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7658 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7659 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7660 opt_is_inside_work_tree = TRUE;
7663 static void
7664 parse_git_color_option(enum line_type type, char *value)
7666 struct line_info *info = &line_info[type];
7667 const char *argv[SIZEOF_ARG];
7668 int argc = 0;
7669 bool first_color = TRUE;
7670 int i;
7672 if (!argv_from_string(argv, &argc, value))
7673 return;
7675 info->fg = COLOR_DEFAULT;
7676 info->bg = COLOR_DEFAULT;
7677 info->attr = 0;
7679 for (i = 0; i < argc; i++) {
7680 int attr = 0;
7682 if (set_attribute(&attr, argv[i])) {
7683 info->attr |= attr;
7685 } else if (set_color(&attr, argv[i])) {
7686 if (first_color)
7687 info->fg = attr;
7688 else
7689 info->bg = attr;
7690 first_color = FALSE;
7695 static void
7696 set_git_color_option(const char *name, char *value)
7698 static const struct enum_map color_option_map[] = {
7699 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
7700 ENUM_MAP("branch.local", LINE_MAIN_REF),
7701 ENUM_MAP("branch.plain", LINE_MAIN_REF),
7702 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
7704 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
7705 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
7706 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
7707 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
7708 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
7709 ENUM_MAP("diff.old", LINE_DIFF_DEL),
7710 ENUM_MAP("diff.new", LINE_DIFF_ADD),
7712 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
7714 ENUM_MAP("status.branch", LINE_STAT_HEAD),
7715 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
7716 ENUM_MAP("status.added", LINE_STAT_STAGED),
7717 ENUM_MAP("status.updated", LINE_STAT_STAGED),
7718 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
7719 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
7722 int type = LINE_NONE;
7724 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
7725 parse_git_color_option(type, value);
7729 static int
7730 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7732 if (!strcmp(name, "gui.encoding"))
7733 parse_encoding(&opt_encoding, value, TRUE);
7735 else if (!strcmp(name, "core.editor"))
7736 string_ncopy(opt_editor, value, valuelen);
7738 else if (!strcmp(name, "core.worktree"))
7739 set_work_tree(value);
7741 else if (!prefixcmp(name, "tig.color."))
7742 set_repo_config_option(name + 10, value, option_color_command);
7744 else if (!prefixcmp(name, "tig.bind."))
7745 set_repo_config_option(name + 9, value, option_bind_command);
7747 else if (!prefixcmp(name, "tig."))
7748 set_repo_config_option(name + 4, value, option_set_command);
7750 else if (!prefixcmp(name, "color."))
7751 set_git_color_option(name + STRING_SIZE("color."), value);
7753 else if (*opt_head && !prefixcmp(name, "branch.") &&
7754 !strncmp(name + 7, opt_head, strlen(opt_head)))
7755 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7757 return OK;
7760 static int
7761 load_git_config(void)
7763 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7765 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7768 static int
7769 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7771 if (!opt_git_dir[0]) {
7772 string_ncopy(opt_git_dir, name, namelen);
7774 } else if (opt_is_inside_work_tree == -1) {
7775 /* This can be 3 different values depending on the
7776 * version of git being used. If git-rev-parse does not
7777 * understand --is-inside-work-tree it will simply echo
7778 * the option else either "true" or "false" is printed.
7779 * Default to true for the unknown case. */
7780 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7782 } else if (*name == '.') {
7783 string_ncopy(opt_cdup, name, namelen);
7785 } else {
7786 string_ncopy(opt_prefix, name, namelen);
7789 return OK;
7792 static int
7793 load_repo_info(void)
7795 const char *rev_parse_argv[] = {
7796 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7797 "--show-cdup", "--show-prefix", NULL
7800 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7805 * Main
7808 static const char usage[] =
7809 "tig " TIG_VERSION " (" __DATE__ ")\n"
7810 "\n"
7811 "Usage: tig [options] [revs] [--] [paths]\n"
7812 " or: tig show [options] [revs] [--] [paths]\n"
7813 " or: tig blame [options] [rev] [--] path\n"
7814 " or: tig status\n"
7815 " or: tig < [git command output]\n"
7816 "\n"
7817 "Options:\n"
7818 " +<number> Select line <number> in the first view\n"
7819 " -v, --version Show version and exit\n"
7820 " -h, --help Show help message and exit";
7822 static void __NORETURN
7823 quit(int sig)
7825 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7826 if (cursed)
7827 endwin();
7828 exit(0);
7831 static void __NORETURN
7832 die(const char *err, ...)
7834 va_list args;
7836 endwin();
7838 va_start(args, err);
7839 fputs("tig: ", stderr);
7840 vfprintf(stderr, err, args);
7841 fputs("\n", stderr);
7842 va_end(args);
7844 exit(1);
7847 static void
7848 warn(const char *msg, ...)
7850 va_list args;
7852 va_start(args, msg);
7853 fputs("tig warning: ", stderr);
7854 vfprintf(stderr, msg, args);
7855 fputs("\n", stderr);
7856 va_end(args);
7859 static int
7860 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7862 const char ***filter_args = data;
7864 return argv_append(filter_args, name) ? OK : ERR;
7867 static void
7868 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7870 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7871 const char **all_argv = NULL;
7873 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7874 !argv_append_array(&all_argv, argv) ||
7875 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7876 die("Failed to split arguments");
7877 argv_free(all_argv);
7878 free(all_argv);
7881 static void
7882 filter_options(const char *argv[], bool blame)
7884 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7886 if (blame)
7887 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7888 else
7889 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7891 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7894 static enum request
7895 parse_options(int argc, const char *argv[])
7897 enum request request = REQ_VIEW_MAIN;
7898 const char *subcommand;
7899 bool seen_dashdash = FALSE;
7900 const char **filter_argv = NULL;
7901 int i;
7903 if (!isatty(STDIN_FILENO))
7904 return REQ_VIEW_PAGER;
7906 if (argc <= 1)
7907 return REQ_VIEW_MAIN;
7909 subcommand = argv[1];
7910 if (!strcmp(subcommand, "status")) {
7911 if (argc > 2)
7912 warn("ignoring arguments after `%s'", subcommand);
7913 return REQ_VIEW_STATUS;
7915 } else if (!strcmp(subcommand, "blame")) {
7916 request = REQ_VIEW_BLAME;
7918 } else if (!strcmp(subcommand, "show")) {
7919 request = REQ_VIEW_DIFF;
7921 } else {
7922 subcommand = NULL;
7925 for (i = 1 + !!subcommand; i < argc; i++) {
7926 const char *opt = argv[i];
7928 // stop parsing our options after -- and let rev-parse handle the rest
7929 if (!seen_dashdash) {
7930 if (!strcmp(opt, "--")) {
7931 seen_dashdash = TRUE;
7932 continue;
7934 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7935 printf("tig version %s\n", TIG_VERSION);
7936 quit(0);
7938 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7939 printf("%s\n", usage);
7940 quit(0);
7942 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7943 opt_lineno = atoi(opt + 1);
7944 continue;
7949 if (!argv_append(&filter_argv, opt))
7950 die("command too long");
7953 if (filter_argv)
7954 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7956 /* Finish validating and setting up blame options */
7957 if (request == REQ_VIEW_BLAME) {
7958 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7959 die("invalid number of options to blame\n\n%s", usage);
7961 if (opt_rev_argv) {
7962 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7965 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7968 return request;
7972 main(int argc, const char *argv[])
7974 const char *codeset = ENCODING_UTF8;
7975 enum request request = parse_options(argc, argv);
7976 struct view *view;
7978 signal(SIGINT, quit);
7979 signal(SIGPIPE, SIG_IGN);
7981 if (setlocale(LC_ALL, "")) {
7982 codeset = nl_langinfo(CODESET);
7985 if (load_repo_info() == ERR)
7986 die("Failed to load repo info.");
7988 if (load_options() == ERR)
7989 die("Failed to load user config.");
7991 if (load_git_config() == ERR)
7992 die("Failed to load repo config.");
7994 /* Require a git repository unless when running in pager mode. */
7995 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7996 die("Not a git repository");
7998 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
7999 char translit[SIZEOF_STR];
8001 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
8002 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
8003 else
8004 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
8005 if (opt_iconv_out == ICONV_NONE)
8006 die("Failed to initialize character set conversion");
8009 if (load_refs() == ERR)
8010 die("Failed to load refs.");
8012 init_display();
8014 while (view_driver(display[current_view], request)) {
8015 int key = get_input(0);
8017 view = display[current_view];
8018 request = get_keybinding(view->keymap, key);
8020 /* Some low-level request handling. This keeps access to
8021 * status_win restricted. */
8022 switch (request) {
8023 case REQ_NONE:
8024 report("Unknown key, press %s for help",
8025 get_view_key(view, REQ_VIEW_HELP));
8026 break;
8027 case REQ_PROMPT:
8029 char *cmd = read_prompt(":");
8031 if (cmd && string_isnumber(cmd)) {
8032 int lineno = view->pos.lineno + 1;
8034 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
8035 select_view_line(view, lineno - 1);
8036 report("");
8037 } else {
8038 report("Unable to parse '%s' as a line number", cmd);
8040 } else if (cmd && iscommit(cmd)) {
8041 string_ncopy(opt_search, cmd, strlen(cmd));
8043 request = view_request(view, REQ_JUMP_COMMIT);
8044 if (request == REQ_JUMP_COMMIT) {
8045 report("Jumping to commits is not supported by the '%s' view", view->name);
8048 } else if (cmd) {
8049 struct view *next = VIEW(REQ_VIEW_PAGER);
8050 const char *argv[SIZEOF_ARG] = { "git" };
8051 int argc = 1;
8053 /* When running random commands, initially show the
8054 * command in the title. However, it maybe later be
8055 * overwritten if a commit line is selected. */
8056 string_ncopy(next->ref, cmd, strlen(cmd));
8058 if (!argv_from_string(argv, &argc, cmd)) {
8059 report("Too many arguments");
8060 } else if (!format_argv(&next->argv, argv, FALSE)) {
8061 report("Argument formatting failed");
8062 } else {
8063 next->dir = NULL;
8064 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
8068 request = REQ_NONE;
8069 break;
8071 case REQ_SEARCH:
8072 case REQ_SEARCH_BACK:
8074 const char *prompt = request == REQ_SEARCH ? "/" : "?";
8075 char *search = read_prompt(prompt);
8077 if (search)
8078 string_ncopy(opt_search, search, strlen(search));
8079 else if (*opt_search)
8080 request = request == REQ_SEARCH ?
8081 REQ_FIND_NEXT :
8082 REQ_FIND_PREV;
8083 else
8084 request = REQ_NONE;
8085 break;
8087 default:
8088 break;
8092 quit(0);
8094 return 0;