Refactor setup of built-in run requests
[tig.git] / tig.c
blob96bf4cebe7efd781177cf0961cf7ab072a24ea20
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 bool
1126 add_run_request(enum keymap keymap, int key, const char **argv, bool silent, bool force)
1128 struct run_request *req;
1130 if (!force && get_keybinding(keymap, key) != key)
1131 return TRUE;
1133 if (!realloc_run_requests(&run_request, run_requests, 1))
1134 return FALSE;
1136 if (!argv_copy(&run_request[run_requests].argv, argv))
1137 return FALSE;
1139 req = &run_request[run_requests++];
1140 req->silent = silent;
1141 req->keymap = keymap;
1142 req->key = key;
1144 add_keybinding(keymap, REQ_NONE + run_requests, key);
1145 return TRUE;
1148 static struct run_request *
1149 get_run_request(enum request request)
1151 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1152 return NULL;
1153 return &run_request[request - REQ_NONE - 1];
1156 static void
1157 add_builtin_run_requests(void)
1159 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1160 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1161 const char *commit[] = { "git", "commit", NULL };
1162 const char *gc[] = { "git", "gc", NULL };
1164 add_run_request(KEYMAP_MAIN, 'C', cherry_pick, FALSE, FALSE);
1165 add_run_request(KEYMAP_STATUS, 'C', commit, FALSE, FALSE);
1166 add_run_request(KEYMAP_BRANCH, 'C', checkout, FALSE, FALSE);
1167 add_run_request(KEYMAP_GENERIC, 'G', gc, FALSE, FALSE);
1171 * User config file handling.
1174 #define OPT_ERR_INFO \
1175 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1176 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1177 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1178 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1179 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1180 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1181 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1182 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1183 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1184 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1185 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1186 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1187 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1188 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1189 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1190 OPT_ERR_(OBSOLETE_VARIABLE_NAME, "Obsolete variable name"), \
1191 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1192 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1193 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1195 enum option_code {
1196 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1197 OPT_ERR_INFO
1198 #undef OPT_ERR_
1199 OPT_OK
1202 static const char *option_errors[] = {
1203 #define OPT_ERR_(name, msg) msg
1204 OPT_ERR_INFO
1205 #undef OPT_ERR_
1208 static const struct enum_map color_map[] = {
1209 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1210 COLOR_MAP(DEFAULT),
1211 COLOR_MAP(BLACK),
1212 COLOR_MAP(BLUE),
1213 COLOR_MAP(CYAN),
1214 COLOR_MAP(GREEN),
1215 COLOR_MAP(MAGENTA),
1216 COLOR_MAP(RED),
1217 COLOR_MAP(WHITE),
1218 COLOR_MAP(YELLOW),
1221 static const struct enum_map attr_map[] = {
1222 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1223 ATTR_MAP(NORMAL),
1224 ATTR_MAP(BLINK),
1225 ATTR_MAP(BOLD),
1226 ATTR_MAP(DIM),
1227 ATTR_MAP(REVERSE),
1228 ATTR_MAP(STANDOUT),
1229 ATTR_MAP(UNDERLINE),
1232 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1234 static enum option_code
1235 parse_step(double *opt, const char *arg)
1237 *opt = atoi(arg);
1238 if (!strchr(arg, '%'))
1239 return OPT_OK;
1241 /* "Shift down" so 100% and 1 does not conflict. */
1242 *opt = (*opt - 1) / 100;
1243 if (*opt >= 1.0) {
1244 *opt = 0.99;
1245 return OPT_ERR_INVALID_STEP_VALUE;
1247 if (*opt < 0.0) {
1248 *opt = 1;
1249 return OPT_ERR_INVALID_STEP_VALUE;
1251 return OPT_OK;
1254 static enum option_code
1255 parse_int(int *opt, const char *arg, int min, int max)
1257 int value = atoi(arg);
1259 if (min <= value && value <= max) {
1260 *opt = value;
1261 return OPT_OK;
1264 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1267 static bool
1268 set_color(int *color, const char *name)
1270 if (map_enum(color, color_map, name))
1271 return TRUE;
1272 if (!prefixcmp(name, "color"))
1273 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1274 return FALSE;
1277 /* Wants: object fgcolor bgcolor [attribute] */
1278 static enum option_code
1279 option_color_command(int argc, const char *argv[])
1281 struct line_info *info;
1283 if (argc < 3)
1284 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1286 if (*argv[0] == '"' || *argv[0] == '\'') {
1287 info = add_custom_color(argv[0]);
1288 } else {
1289 info = get_line_info(argv[0]);
1291 if (!info) {
1292 static const struct enum_map obsolete[] = {
1293 ENUM_MAP("main-delim", LINE_DELIMITER),
1294 ENUM_MAP("main-date", LINE_DATE),
1295 ENUM_MAP("main-author", LINE_AUTHOR),
1297 int index;
1299 if (!map_enum(&index, obsolete, argv[0]))
1300 return OPT_ERR_UNKNOWN_COLOR_NAME;
1301 info = &line_info[index];
1304 if (!set_color(&info->fg, argv[1]) ||
1305 !set_color(&info->bg, argv[2]))
1306 return OPT_ERR_UNKNOWN_COLOR;
1308 info->attr = 0;
1309 while (argc-- > 3) {
1310 int attr;
1312 if (!set_attribute(&attr, argv[argc]))
1313 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1314 info->attr |= attr;
1317 return OPT_OK;
1320 static enum option_code
1321 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1323 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1324 ? TRUE : FALSE;
1325 if (matched)
1326 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1327 return OPT_OK;
1330 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1332 static enum option_code
1333 parse_enum_do(unsigned int *opt, const char *arg,
1334 const struct enum_map *map, size_t map_size)
1336 bool is_true;
1338 assert(map_size > 1);
1340 if (map_enum_do(map, map_size, (int *) opt, arg))
1341 return OPT_OK;
1343 parse_bool(&is_true, arg);
1344 *opt = is_true ? map[1].value : map[0].value;
1345 return OPT_OK;
1348 #define parse_enum(opt, arg, map) \
1349 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1351 static enum option_code
1352 parse_string(char *opt, const char *arg, size_t optsize)
1354 int arglen = strlen(arg);
1356 switch (arg[0]) {
1357 case '\"':
1358 case '\'':
1359 if (arglen == 1 || arg[arglen - 1] != arg[0])
1360 return OPT_ERR_UNMATCHED_QUOTATION;
1361 arg += 1; arglen -= 2;
1362 default:
1363 string_ncopy_do(opt, optsize, arg, arglen);
1364 return OPT_OK;
1368 static enum option_code
1369 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1371 char buf[SIZEOF_STR];
1372 enum option_code code = parse_string(buf, arg, sizeof(buf));
1374 if (code == OPT_OK) {
1375 struct encoding *encoding = *encoding_ref;
1377 if (encoding && !priority)
1378 return code;
1379 encoding = encoding_open(buf);
1380 if (encoding)
1381 *encoding_ref = encoding;
1384 return code;
1387 static enum option_code
1388 parse_args(const char ***args, const char *argv[])
1390 if (*args == NULL && !argv_copy(args, argv))
1391 return OPT_ERR_OUT_OF_MEMORY;
1392 return OPT_OK;
1395 /* Wants: name = value */
1396 static enum option_code
1397 option_set_command(int argc, const char *argv[])
1399 if (argc < 3)
1400 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1402 if (strcmp(argv[1], "="))
1403 return OPT_ERR_NO_VALUE_ASSIGNED;
1405 if (!strcmp(argv[0], "blame-options"))
1406 return parse_args(&opt_blame_argv, argv + 2);
1408 if (argc != 3)
1409 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1411 if (!strcmp(argv[0], "show-author"))
1412 return parse_enum(&opt_author, argv[2], author_map);
1414 if (!strcmp(argv[0], "show-date"))
1415 return parse_enum(&opt_date, argv[2], date_map);
1417 if (!strcmp(argv[0], "show-rev-graph"))
1418 return parse_bool(&opt_rev_graph, argv[2]);
1420 if (!strcmp(argv[0], "show-refs"))
1421 return parse_bool(&opt_show_refs, argv[2]);
1423 if (!strcmp(argv[0], "show-changes"))
1424 return parse_bool(&opt_show_changes, argv[2]);
1426 if (!strcmp(argv[0], "show-notes")) {
1427 bool matched = FALSE;
1428 enum option_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1430 if (res == OPT_OK && matched) {
1431 update_notes_arg();
1432 return res;
1435 opt_notes = TRUE;
1436 strcpy(opt_notes_arg, "--show-notes=");
1437 res = parse_string(opt_notes_arg + 8, argv[2],
1438 sizeof(opt_notes_arg) - 8);
1439 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1440 opt_notes_arg[7] = '\0';
1441 return res;
1444 if (!strcmp(argv[0], "show-line-numbers"))
1445 return parse_bool(&opt_line_number, argv[2]);
1447 if (!strcmp(argv[0], "line-graphics"))
1448 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1450 if (!strcmp(argv[0], "line-number-interval"))
1451 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1453 if (!strcmp(argv[0], "author-width"))
1454 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1456 if (!strcmp(argv[0], "filename-width"))
1457 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1459 if (!strcmp(argv[0], "show-filename"))
1460 return parse_enum(&opt_filename, argv[2], filename_map);
1462 if (!strcmp(argv[0], "horizontal-scroll"))
1463 return parse_step(&opt_hscroll, argv[2]);
1465 if (!strcmp(argv[0], "split-view-height"))
1466 return parse_step(&opt_scale_split_view, argv[2]);
1468 if (!strcmp(argv[0], "tab-size"))
1469 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1471 if (!strcmp(argv[0], "diff-context")) {
1472 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1474 if (code == OPT_OK)
1475 update_diff_context_arg(opt_diff_context);
1476 return code;
1479 if (!strcmp(argv[0], "ignore-space")) {
1480 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1482 if (code == OPT_OK)
1483 update_ignore_space_arg();
1484 return code;
1487 if (!strcmp(argv[0], "commit-order")) {
1488 enum option_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1490 if (code == OPT_OK)
1491 update_commit_order_arg();
1492 return code;
1495 if (!strcmp(argv[0], "status-untracked-dirs"))
1496 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1498 if (!strcmp(argv[0], "use-git-colors"))
1499 return parse_bool(&opt_read_git_colors, argv[2]);
1501 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1504 /* Wants: mode request key */
1505 static enum option_code
1506 option_bind_command(int argc, const char *argv[])
1508 enum request request;
1509 int keymap = -1;
1510 int key;
1512 if (argc < 3)
1513 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1515 if (!set_keymap(&keymap, argv[0]))
1516 return OPT_ERR_UNKNOWN_KEY_MAP;
1518 key = get_key_value(argv[1]);
1519 if (key == ERR)
1520 return OPT_ERR_UNKNOWN_KEY;
1522 request = get_request(argv[2]);
1523 if (request == REQ_UNKNOWN) {
1524 static const struct enum_map obsolete[] = {
1525 ENUM_MAP("cherry-pick", REQ_NONE),
1526 ENUM_MAP("screen-resize", REQ_NONE),
1527 ENUM_MAP("tree-parent", REQ_PARENT),
1529 int alias;
1531 if (map_enum(&alias, obsolete, argv[2])) {
1532 if (alias != REQ_NONE)
1533 add_keybinding(keymap, alias, key);
1534 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1537 if (request == REQ_UNKNOWN && *argv[2]++ == '!') {
1538 bool silent = *argv[2] == '@';
1540 if (silent)
1541 argv[2]++;
1542 return add_run_request(keymap, key, argv + 2, silent, TRUE)
1543 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1545 if (request == REQ_UNKNOWN)
1546 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1548 add_keybinding(keymap, request, key);
1550 return OPT_OK;
1554 static enum option_code load_option_file(const char *path);
1556 static enum option_code
1557 option_source_command(int argc, const char *argv[])
1559 if (argc < 1)
1560 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1562 return load_option_file(argv[0]);
1565 static enum option_code
1566 set_option(const char *opt, char *value)
1568 const char *argv[SIZEOF_ARG];
1569 int argc = 0;
1571 if (!argv_from_string(argv, &argc, value))
1572 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1574 if (!strcmp(opt, "color"))
1575 return option_color_command(argc, argv);
1577 if (!strcmp(opt, "set"))
1578 return option_set_command(argc, argv);
1580 if (!strcmp(opt, "bind"))
1581 return option_bind_command(argc, argv);
1583 if (!strcmp(opt, "source"))
1584 return option_source_command(argc, argv);
1586 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1589 struct config_state {
1590 const char *path;
1591 int lineno;
1592 bool errors;
1595 static int
1596 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1598 struct config_state *config = data;
1599 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1601 config->lineno++;
1603 /* Check for comment markers, since read_properties() will
1604 * only ensure opt and value are split at first " \t". */
1605 optlen = strcspn(opt, "#");
1606 if (optlen == 0)
1607 return OK;
1609 if (opt[optlen] == 0) {
1610 /* Look for comment endings in the value. */
1611 size_t len = strcspn(value, "#");
1613 if (len < valuelen) {
1614 valuelen = len;
1615 value[valuelen] = 0;
1618 status = set_option(opt, value);
1621 if (status != OPT_OK) {
1622 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1623 option_errors[status], (int) optlen, opt);
1624 config->errors = TRUE;
1627 /* Always keep going if errors are encountered. */
1628 return OK;
1631 static enum option_code
1632 load_option_file(const char *path)
1634 struct config_state config = { path, 0, FALSE };
1635 struct io io;
1637 /* Do not read configuration from stdin if set to "" */
1638 if (!path || !strlen(path))
1639 return OPT_OK;
1641 /* It's OK that the file doesn't exist. */
1642 if (!io_open(&io, "%s", path))
1643 return OPT_ERR_FILE_DOES_NOT_EXIST;
1645 if (io_load(&io, " \t", read_option, &config) == ERR ||
1646 config.errors == TRUE)
1647 warn("Errors while loading %s.", path);
1648 return OPT_OK;
1651 static int
1652 load_options(void)
1654 const char *home = getenv("HOME");
1655 const char *tigrc_user = getenv("TIGRC_USER");
1656 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1657 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1658 char buf[SIZEOF_STR];
1660 if (!tigrc_system)
1661 tigrc_system = SYSCONFDIR "/tigrc";
1662 load_option_file(tigrc_system);
1664 if (!tigrc_user) {
1665 if (!home || !string_format(buf, "%s/.tigrc", home))
1666 return ERR;
1667 tigrc_user = buf;
1669 load_option_file(tigrc_user);
1671 /* Add _after_ loading config files to avoid adding run requests
1672 * that conflict with keybindings. */
1673 add_builtin_run_requests();
1675 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1676 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1677 int argc = 0;
1679 if (!string_format(buf, "%s", tig_diff_opts) ||
1680 !argv_from_string(diff_opts, &argc, buf))
1681 die("TIG_DIFF_OPTS contains too many arguments");
1682 else if (!argv_copy(&opt_diff_argv, diff_opts))
1683 die("Failed to format TIG_DIFF_OPTS arguments");
1686 return OK;
1691 * The viewer
1694 struct view;
1695 struct view_ops;
1697 /* The display array of active views and the index of the current view. */
1698 static struct view *display[2];
1699 static WINDOW *display_win[2];
1700 static WINDOW *display_title[2];
1701 static unsigned int current_view;
1703 #define foreach_displayed_view(view, i) \
1704 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1706 #define displayed_views() (display[1] != NULL ? 2 : 1)
1708 /* Current head and commit ID */
1709 static char ref_blob[SIZEOF_REF] = "";
1710 static char ref_commit[SIZEOF_REF] = "HEAD";
1711 static char ref_head[SIZEOF_REF] = "HEAD";
1712 static char ref_branch[SIZEOF_REF] = "";
1714 enum view_flag {
1715 VIEW_NO_FLAGS = 0,
1716 VIEW_ALWAYS_LINENO = 1 << 0,
1717 VIEW_CUSTOM_STATUS = 1 << 1,
1718 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1719 VIEW_ADD_PAGER_REFS = 1 << 3,
1720 VIEW_OPEN_DIFF = 1 << 4,
1721 VIEW_NO_REF = 1 << 5,
1722 VIEW_NO_GIT_DIR = 1 << 6,
1723 VIEW_DIFF_LIKE = 1 << 7,
1726 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1728 struct position {
1729 unsigned long offset; /* Offset of the window top */
1730 unsigned long col; /* Offset from the window side. */
1731 unsigned long lineno; /* Current line number */
1734 struct view {
1735 const char *name; /* View name */
1736 const char *id; /* Points to either of ref_{head,commit,blob} */
1738 struct view_ops *ops; /* View operations */
1740 enum keymap keymap; /* What keymap does this view have */
1742 char ref[SIZEOF_REF]; /* Hovered commit reference */
1743 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1745 int height, width; /* The width and height of the main window */
1746 WINDOW *win; /* The main window */
1748 /* Navigation */
1749 struct position pos; /* Current position. */
1750 struct position prev_pos; /* Previous position. */
1752 /* Searching */
1753 char grep[SIZEOF_STR]; /* Search string */
1754 regex_t *regex; /* Pre-compiled regexp */
1756 /* If non-NULL, points to the view that opened this view. If this view
1757 * is closed tig will switch back to the parent view. */
1758 struct view *parent;
1759 struct view *prev;
1761 /* Buffering */
1762 size_t lines; /* Total number of lines */
1763 struct line *line; /* Line index */
1764 unsigned int digits; /* Number of digits in the lines member. */
1766 /* Drawing */
1767 struct line *curline; /* Line currently being drawn. */
1768 enum line_type curtype; /* Attribute currently used for drawing. */
1769 unsigned long col; /* Column when drawing. */
1770 bool has_scrolled; /* View was scrolled. */
1772 /* Loading */
1773 const char **argv; /* Shell command arguments. */
1774 const char *dir; /* Directory from which to execute. */
1775 struct io io;
1776 struct io *pipe;
1777 time_t start_time;
1778 time_t update_secs;
1779 struct encoding *encoding;
1781 /* Private data */
1782 void *private;
1785 enum open_flags {
1786 OPEN_DEFAULT = 0, /* Use default view switching. */
1787 OPEN_SPLIT = 1, /* Split current view. */
1788 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1789 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1790 OPEN_PREPARED = 32, /* Open already prepared command. */
1791 OPEN_EXTRA = 64, /* Open extra data from command. */
1794 struct view_ops {
1795 /* What type of content being displayed. Used in the title bar. */
1796 const char *type;
1797 /* Flags to control the view behavior. */
1798 enum view_flag flags;
1799 /* Size of private data. */
1800 size_t private_size;
1801 /* Open and reads in all view content. */
1802 bool (*open)(struct view *view, enum open_flags flags);
1803 /* Read one line; updates view->line. */
1804 bool (*read)(struct view *view, char *data);
1805 /* Draw one line; @lineno must be < view->height. */
1806 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1807 /* Depending on view handle a special requests. */
1808 enum request (*request)(struct view *view, enum request request, struct line *line);
1809 /* Search for regexp in a line. */
1810 bool (*grep)(struct view *view, struct line *line);
1811 /* Select line */
1812 void (*select)(struct view *view, struct line *line);
1815 #define VIEW_OPS(id, name, ref) name##_ops
1816 static struct view_ops VIEW_INFO(VIEW_OPS);
1818 static struct view views[] = {
1819 #define VIEW_DATA(id, name, ref) \
1820 { #name, ref, &name##_ops, KEYMAP_##id }
1821 VIEW_INFO(VIEW_DATA)
1824 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1826 #define foreach_view(view, i) \
1827 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1829 #define view_is_displayed(view) \
1830 (view == display[0] || view == display[1])
1832 static enum request
1833 view_request(struct view *view, enum request request)
1835 if (!view || !view->lines)
1836 return request;
1837 return view->ops->request(view, request, &view->line[view->pos.lineno]);
1842 * View drawing.
1845 static inline void
1846 set_view_attr(struct view *view, enum line_type type)
1848 if (!view->curline->selected && view->curtype != type) {
1849 (void) wattrset(view->win, get_line_attr(type));
1850 wchgat(view->win, -1, 0, get_line_color(type), NULL);
1851 view->curtype = type;
1855 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
1857 static bool
1858 draw_chars(struct view *view, enum line_type type, const char *string,
1859 int max_len, bool use_tilde)
1861 static char out_buffer[BUFSIZ * 2];
1862 int len = 0;
1863 int col = 0;
1864 int trimmed = FALSE;
1865 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1867 if (max_len <= 0)
1868 return VIEW_MAX_LEN(view) <= 0;
1870 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1872 set_view_attr(view, type);
1873 if (len > 0) {
1874 if (opt_iconv_out != ICONV_NONE) {
1875 size_t inlen = len + 1;
1876 char *instr = calloc(1, inlen);
1877 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1878 if (!instr)
1879 return VIEW_MAX_LEN(view) <= 0;
1881 strncpy(instr, string, len);
1883 char *outbuf = out_buffer;
1884 size_t outlen = sizeof(out_buffer);
1886 size_t ret;
1888 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1889 if (ret != (size_t) -1) {
1890 string = out_buffer;
1891 len = sizeof(out_buffer) - outlen;
1893 free(instr);
1896 waddnstr(view->win, string, len);
1898 if (trimmed && use_tilde) {
1899 set_view_attr(view, LINE_DELIMITER);
1900 waddch(view->win, '~');
1901 col++;
1905 view->col += col;
1906 return VIEW_MAX_LEN(view) <= 0;
1909 static bool
1910 draw_space(struct view *view, enum line_type type, int max, int spaces)
1912 static char space[] = " ";
1914 spaces = MIN(max, spaces);
1916 while (spaces > 0) {
1917 int len = MIN(spaces, sizeof(space) - 1);
1919 if (draw_chars(view, type, space, len, FALSE))
1920 return TRUE;
1921 spaces -= len;
1924 return VIEW_MAX_LEN(view) <= 0;
1927 static bool
1928 draw_text(struct view *view, enum line_type type, const char *string)
1930 char text[SIZEOF_STR];
1932 do {
1933 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1935 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1936 return TRUE;
1937 string += pos;
1938 } while (*string);
1940 return VIEW_MAX_LEN(view) <= 0;
1943 static bool
1944 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
1946 char text[SIZEOF_STR];
1947 int retval;
1949 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
1950 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
1953 static bool
1954 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1956 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1957 int max = VIEW_MAX_LEN(view);
1958 int i;
1960 if (max < size)
1961 size = max;
1963 set_view_attr(view, type);
1964 /* Using waddch() instead of waddnstr() ensures that
1965 * they'll be rendered correctly for the cursor line. */
1966 for (i = skip; i < size; i++)
1967 waddch(view->win, graphic[i]);
1969 view->col += size;
1970 if (separator) {
1971 if (size < max && skip <= size)
1972 waddch(view->win, ' ');
1973 view->col++;
1976 return VIEW_MAX_LEN(view) <= 0;
1979 static bool
1980 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1982 int max = MIN(VIEW_MAX_LEN(view), len);
1983 int col = view->col;
1985 if (!text)
1986 return draw_space(view, type, max, max);
1988 return draw_chars(view, type, text, max - 1, trim)
1989 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1992 static bool
1993 draw_date(struct view *view, struct time *time)
1995 const char *date = mkdate(time, opt_date);
1996 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1998 if (opt_date == DATE_NO)
1999 return FALSE;
2001 return draw_field(view, LINE_DATE, date, cols, FALSE);
2004 static bool
2005 draw_author(struct view *view, const char *author)
2007 bool trim = author_trim(opt_author_cols);
2008 const char *text = mkauthor(author, opt_author_cols, opt_author);
2010 if (opt_author == AUTHOR_NO)
2011 return FALSE;
2013 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
2016 static bool
2017 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2019 bool trim = filename && strlen(filename) >= opt_filename_cols;
2021 if (opt_filename == FILENAME_NO)
2022 return FALSE;
2024 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2025 return FALSE;
2027 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
2030 static bool
2031 draw_mode(struct view *view, mode_t mode)
2033 const char *str = mkmode(mode);
2035 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
2038 static bool
2039 draw_lineno(struct view *view, unsigned int lineno)
2041 char number[10];
2042 int digits3 = view->digits < 3 ? 3 : view->digits;
2043 int max = MIN(VIEW_MAX_LEN(view), digits3);
2044 char *text = NULL;
2045 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2047 if (!opt_line_number)
2048 return FALSE;
2050 lineno += view->pos.offset + 1;
2051 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2052 static char fmt[] = "%1ld";
2054 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2055 if (string_format(number, fmt, lineno))
2056 text = number;
2058 if (text)
2059 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2060 else
2061 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2062 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2065 static bool
2066 draw_refs(struct view *view, struct ref_list *refs)
2068 size_t i;
2070 if (!opt_show_refs || !refs)
2071 return FALSE;
2073 for (i = 0; i < refs->size; i++) {
2074 struct ref *ref = refs->refs[i];
2075 enum line_type type = get_line_type_from_ref(ref);
2077 if (draw_formatted(view, type, "[%s]", ref->name))
2078 return TRUE;
2080 if (draw_text(view, LINE_DEFAULT, " "))
2081 return TRUE;
2084 return FALSE;
2087 static bool
2088 draw_view_line(struct view *view, unsigned int lineno)
2090 struct line *line;
2091 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2093 assert(view_is_displayed(view));
2095 if (view->pos.offset + lineno >= view->lines)
2096 return FALSE;
2098 line = &view->line[view->pos.offset + lineno];
2100 wmove(view->win, lineno, 0);
2101 if (line->cleareol)
2102 wclrtoeol(view->win);
2103 view->col = 0;
2104 view->curline = line;
2105 view->curtype = LINE_NONE;
2106 line->selected = FALSE;
2107 line->dirty = line->cleareol = 0;
2109 if (selected) {
2110 set_view_attr(view, LINE_CURSOR);
2111 line->selected = TRUE;
2112 view->ops->select(view, line);
2115 return view->ops->draw(view, line, lineno);
2118 static void
2119 redraw_view_dirty(struct view *view)
2121 bool dirty = FALSE;
2122 int lineno;
2124 for (lineno = 0; lineno < view->height; lineno++) {
2125 if (view->pos.offset + lineno >= view->lines)
2126 break;
2127 if (!view->line[view->pos.offset + lineno].dirty)
2128 continue;
2129 dirty = TRUE;
2130 if (!draw_view_line(view, lineno))
2131 break;
2134 if (!dirty)
2135 return;
2136 wnoutrefresh(view->win);
2139 static void
2140 redraw_view_from(struct view *view, int lineno)
2142 assert(0 <= lineno && lineno < view->height);
2144 for (; lineno < view->height; lineno++) {
2145 if (!draw_view_line(view, lineno))
2146 break;
2149 wnoutrefresh(view->win);
2152 static void
2153 redraw_view(struct view *view)
2155 werase(view->win);
2156 redraw_view_from(view, 0);
2160 static void
2161 update_view_title(struct view *view)
2163 char buf[SIZEOF_STR];
2164 char state[SIZEOF_STR];
2165 size_t bufpos = 0, statelen = 0;
2166 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2168 assert(view_is_displayed(view));
2170 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view->lines) {
2171 unsigned int view_lines = view->pos.offset + view->height;
2172 unsigned int lines = view->lines
2173 ? MIN(view_lines, view->lines) * 100 / view->lines
2174 : 0;
2176 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
2177 view->ops->type,
2178 view->pos.lineno + 1,
2179 view->lines,
2180 lines);
2184 if (view->pipe) {
2185 time_t secs = time(NULL) - view->start_time;
2187 /* Three git seconds are a long time ... */
2188 if (secs > 2)
2189 string_format_from(state, &statelen, " loading %lds", secs);
2192 string_format_from(buf, &bufpos, "[%s]", view->name);
2193 if (*view->ref && bufpos < view->width) {
2194 size_t refsize = strlen(view->ref);
2195 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2197 if (minsize < view->width)
2198 refsize = view->width - minsize + 7;
2199 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2202 if (statelen && bufpos < view->width) {
2203 string_format_from(buf, &bufpos, "%s", state);
2206 if (view == display[current_view])
2207 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2208 else
2209 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2211 mvwaddnstr(window, 0, 0, buf, bufpos);
2212 wclrtoeol(window);
2213 wnoutrefresh(window);
2216 static int
2217 apply_step(double step, int value)
2219 if (step >= 1)
2220 return (int) step;
2221 value *= step + 0.01;
2222 return value ? value : 1;
2225 static void
2226 resize_display(void)
2228 int offset, i;
2229 struct view *base = display[0];
2230 struct view *view = display[1] ? display[1] : display[0];
2232 /* Setup window dimensions */
2234 getmaxyx(stdscr, base->height, base->width);
2236 /* Make room for the status window. */
2237 base->height -= 1;
2239 if (view != base) {
2240 /* Horizontal split. */
2241 view->width = base->width;
2242 view->height = apply_step(opt_scale_split_view, base->height);
2243 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2244 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2245 base->height -= view->height;
2247 /* Make room for the title bar. */
2248 view->height -= 1;
2251 /* Make room for the title bar. */
2252 base->height -= 1;
2254 offset = 0;
2256 foreach_displayed_view (view, i) {
2257 if (!display_win[i]) {
2258 display_win[i] = newwin(view->height, view->width, offset, 0);
2259 if (!display_win[i])
2260 die("Failed to create %s view", view->name);
2262 scrollok(display_win[i], FALSE);
2264 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2265 if (!display_title[i])
2266 die("Failed to create title window");
2268 } else {
2269 wresize(display_win[i], view->height, view->width);
2270 mvwin(display_win[i], offset, 0);
2271 mvwin(display_title[i], offset + view->height, 0);
2274 view->win = display_win[i];
2276 offset += view->height + 1;
2280 static void
2281 redraw_display(bool clear)
2283 struct view *view;
2284 int i;
2286 foreach_displayed_view (view, i) {
2287 if (clear)
2288 wclear(view->win);
2289 redraw_view(view);
2290 update_view_title(view);
2296 * Option management
2299 #define TOGGLE_MENU \
2300 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2301 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2302 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2303 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2304 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2305 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2306 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2307 TOGGLE_(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map) \
2308 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL) \
2309 TOGGLE_(CHANGES, 'C', "local change display", &opt_show_changes, NULL)
2311 static bool
2312 toggle_option(enum request request)
2314 const struct {
2315 enum request request;
2316 const struct enum_map *map;
2317 size_t map_size;
2318 } data[] = {
2319 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2320 TOGGLE_MENU
2321 #undef TOGGLE_
2323 const struct menu_item menu[] = {
2324 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2325 TOGGLE_MENU
2326 #undef TOGGLE_
2327 { 0 }
2329 int i = 0;
2331 if (request == REQ_OPTIONS) {
2332 if (!prompt_menu("Toggle option", menu, &i))
2333 return FALSE;
2334 } else {
2335 while (i < ARRAY_SIZE(data) && data[i].request != request)
2336 i++;
2337 if (i >= ARRAY_SIZE(data))
2338 die("Invalid request (%d)", request);
2341 if (data[i].map != NULL) {
2342 unsigned int *opt = menu[i].data;
2344 *opt = (*opt + 1) % data[i].map_size;
2345 if (data[i].map == ignore_space_map) {
2346 update_ignore_space_arg();
2347 report("Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2348 return TRUE;
2350 } else if (data[i].map == commit_order_map) {
2351 update_commit_order_arg();
2352 report("Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2353 return TRUE;
2356 redraw_display(FALSE);
2357 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2359 } else {
2360 bool *option = menu[i].data;
2362 *option = !*option;
2363 redraw_display(FALSE);
2364 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2367 return FALSE;
2370 static void
2371 maximize_view(struct view *view, bool redraw)
2373 memset(display, 0, sizeof(display));
2374 current_view = 0;
2375 display[current_view] = view;
2376 resize_display();
2377 if (redraw) {
2378 redraw_display(FALSE);
2379 report("");
2385 * Navigation
2388 static bool
2389 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2391 if (lineno >= view->lines)
2392 lineno = view->lines > 0 ? view->lines - 1 : 0;
2394 if (offset > lineno || offset + view->height <= lineno) {
2395 unsigned long half = view->height / 2;
2397 if (lineno > half)
2398 offset = lineno - half;
2399 else
2400 offset = 0;
2403 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2404 view->pos.offset = offset;
2405 view->pos.lineno = lineno;
2406 return TRUE;
2409 return FALSE;
2412 /* Scrolling backend */
2413 static void
2414 do_scroll_view(struct view *view, int lines)
2416 bool redraw_current_line = FALSE;
2418 /* The rendering expects the new offset. */
2419 view->pos.offset += lines;
2421 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2422 assert(lines);
2424 /* Move current line into the view. */
2425 if (view->pos.lineno < view->pos.offset) {
2426 view->pos.lineno = view->pos.offset;
2427 redraw_current_line = TRUE;
2428 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2429 view->pos.lineno = view->pos.offset + view->height - 1;
2430 redraw_current_line = TRUE;
2433 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2435 /* Redraw the whole screen if scrolling is pointless. */
2436 if (view->height < ABS(lines)) {
2437 redraw_view(view);
2439 } else {
2440 int line = lines > 0 ? view->height - lines : 0;
2441 int end = line + ABS(lines);
2443 scrollok(view->win, TRUE);
2444 wscrl(view->win, lines);
2445 scrollok(view->win, FALSE);
2447 while (line < end && draw_view_line(view, line))
2448 line++;
2450 if (redraw_current_line)
2451 draw_view_line(view, view->pos.lineno - view->pos.offset);
2452 wnoutrefresh(view->win);
2455 view->has_scrolled = TRUE;
2456 report("");
2459 /* Scroll frontend */
2460 static void
2461 scroll_view(struct view *view, enum request request)
2463 int lines = 1;
2465 assert(view_is_displayed(view));
2467 switch (request) {
2468 case REQ_SCROLL_FIRST_COL:
2469 view->pos.col = 0;
2470 redraw_view_from(view, 0);
2471 report("");
2472 return;
2473 case REQ_SCROLL_LEFT:
2474 if (view->pos.col == 0) {
2475 report("Cannot scroll beyond the first column");
2476 return;
2478 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2479 view->pos.col = 0;
2480 else
2481 view->pos.col -= apply_step(opt_hscroll, view->width);
2482 redraw_view_from(view, 0);
2483 report("");
2484 return;
2485 case REQ_SCROLL_RIGHT:
2486 view->pos.col += apply_step(opt_hscroll, view->width);
2487 redraw_view(view);
2488 report("");
2489 return;
2490 case REQ_SCROLL_PAGE_DOWN:
2491 lines = view->height;
2492 case REQ_SCROLL_LINE_DOWN:
2493 if (view->pos.offset + lines > view->lines)
2494 lines = view->lines - view->pos.offset;
2496 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2497 report("Cannot scroll beyond the last line");
2498 return;
2500 break;
2502 case REQ_SCROLL_PAGE_UP:
2503 lines = view->height;
2504 case REQ_SCROLL_LINE_UP:
2505 if (lines > view->pos.offset)
2506 lines = view->pos.offset;
2508 if (lines == 0) {
2509 report("Cannot scroll beyond the first line");
2510 return;
2513 lines = -lines;
2514 break;
2516 default:
2517 die("request %d not handled in switch", request);
2520 do_scroll_view(view, lines);
2523 /* Cursor moving */
2524 static void
2525 move_view(struct view *view, enum request request)
2527 int scroll_steps = 0;
2528 int steps;
2530 switch (request) {
2531 case REQ_MOVE_FIRST_LINE:
2532 steps = -view->pos.lineno;
2533 break;
2535 case REQ_MOVE_LAST_LINE:
2536 steps = view->lines - view->pos.lineno - 1;
2537 break;
2539 case REQ_MOVE_PAGE_UP:
2540 steps = view->height > view->pos.lineno
2541 ? -view->pos.lineno : -view->height;
2542 break;
2544 case REQ_MOVE_PAGE_DOWN:
2545 steps = view->pos.lineno + view->height >= view->lines
2546 ? view->lines - view->pos.lineno - 1 : view->height;
2547 break;
2549 case REQ_MOVE_UP:
2550 case REQ_PREVIOUS:
2551 steps = -1;
2552 break;
2554 case REQ_MOVE_DOWN:
2555 case REQ_NEXT:
2556 steps = 1;
2557 break;
2559 default:
2560 die("request %d not handled in switch", request);
2563 if (steps <= 0 && view->pos.lineno == 0) {
2564 report("Cannot move beyond the first line");
2565 return;
2567 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2568 report("Cannot move beyond the last line");
2569 return;
2572 /* Move the current line */
2573 view->pos.lineno += steps;
2574 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2576 /* Check whether the view needs to be scrolled */
2577 if (view->pos.lineno < view->pos.offset ||
2578 view->pos.lineno >= view->pos.offset + view->height) {
2579 scroll_steps = steps;
2580 if (steps < 0 && -steps > view->pos.offset) {
2581 scroll_steps = -view->pos.offset;
2583 } else if (steps > 0) {
2584 if (view->pos.lineno == view->lines - 1 &&
2585 view->lines > view->height) {
2586 scroll_steps = view->lines - view->pos.offset - 1;
2587 if (scroll_steps >= view->height)
2588 scroll_steps -= view->height - 1;
2593 if (!view_is_displayed(view)) {
2594 view->pos.offset += scroll_steps;
2595 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2596 view->ops->select(view, &view->line[view->pos.lineno]);
2597 return;
2600 /* Repaint the old "current" line if we be scrolling */
2601 if (ABS(steps) < view->height)
2602 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2604 if (scroll_steps) {
2605 do_scroll_view(view, scroll_steps);
2606 return;
2609 /* Draw the current line */
2610 draw_view_line(view, view->pos.lineno - view->pos.offset);
2612 wnoutrefresh(view->win);
2613 report("");
2618 * Searching
2621 static void search_view(struct view *view, enum request request);
2623 static bool
2624 grep_text(struct view *view, const char *text[])
2626 regmatch_t pmatch;
2627 size_t i;
2629 for (i = 0; text[i]; i++)
2630 if (*text[i] &&
2631 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2632 return TRUE;
2633 return FALSE;
2636 static void
2637 select_view_line(struct view *view, unsigned long lineno)
2639 struct position old = view->pos;
2641 if (goto_view_line(view, view->pos.offset, lineno)) {
2642 if (view_is_displayed(view)) {
2643 if (old.offset != view->pos.offset) {
2644 redraw_view(view);
2645 } else {
2646 draw_view_line(view, old.lineno - view->pos.offset);
2647 draw_view_line(view, view->pos.lineno - view->pos.offset);
2648 wnoutrefresh(view->win);
2650 } else {
2651 view->ops->select(view, &view->line[view->pos.lineno]);
2656 static void
2657 find_next(struct view *view, enum request request)
2659 unsigned long lineno = view->pos.lineno;
2660 int direction;
2662 if (!*view->grep) {
2663 if (!*opt_search)
2664 report("No previous search");
2665 else
2666 search_view(view, request);
2667 return;
2670 switch (request) {
2671 case REQ_SEARCH:
2672 case REQ_FIND_NEXT:
2673 direction = 1;
2674 break;
2676 case REQ_SEARCH_BACK:
2677 case REQ_FIND_PREV:
2678 direction = -1;
2679 break;
2681 default:
2682 return;
2685 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2686 lineno += direction;
2688 /* Note, lineno is unsigned long so will wrap around in which case it
2689 * will become bigger than view->lines. */
2690 for (; lineno < view->lines; lineno += direction) {
2691 if (view->ops->grep(view, &view->line[lineno])) {
2692 select_view_line(view, lineno);
2693 report("Line %ld matches '%s'", lineno + 1, view->grep);
2694 return;
2698 report("No match found for '%s'", view->grep);
2701 static void
2702 search_view(struct view *view, enum request request)
2704 int regex_err;
2706 if (view->regex) {
2707 regfree(view->regex);
2708 *view->grep = 0;
2709 } else {
2710 view->regex = calloc(1, sizeof(*view->regex));
2711 if (!view->regex)
2712 return;
2715 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2716 if (regex_err != 0) {
2717 char buf[SIZEOF_STR] = "unknown error";
2719 regerror(regex_err, view->regex, buf, sizeof(buf));
2720 report("Search failed: %s", buf);
2721 return;
2724 string_copy(view->grep, opt_search);
2726 find_next(view, request);
2730 * Incremental updating
2733 static inline bool
2734 check_position(struct position *pos)
2736 return pos->lineno || pos->col || pos->offset;
2739 static inline void
2740 clear_position(struct position *pos)
2742 memset(pos, 0, sizeof(*pos));
2745 static void
2746 reset_view(struct view *view)
2748 int i;
2750 for (i = 0; i < view->lines; i++)
2751 free(view->line[i].data);
2752 free(view->line);
2754 view->prev_pos = view->pos;
2755 clear_position(&view->pos);
2757 view->line = NULL;
2758 view->lines = 0;
2759 view->vid[0] = 0;
2760 view->update_secs = 0;
2763 static const char *
2764 format_arg(const char *name)
2766 static struct {
2767 const char *name;
2768 size_t namelen;
2769 const char *value;
2770 const char *value_if_empty;
2771 } vars[] = {
2772 #define FORMAT_VAR(name, value, value_if_empty) \
2773 { name, STRING_SIZE(name), value, value_if_empty }
2774 FORMAT_VAR("%(directory)", opt_path, "."),
2775 FORMAT_VAR("%(file)", opt_file, ""),
2776 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2777 FORMAT_VAR("%(head)", ref_head, ""),
2778 FORMAT_VAR("%(commit)", ref_commit, ""),
2779 FORMAT_VAR("%(blob)", ref_blob, ""),
2780 FORMAT_VAR("%(branch)", ref_branch, ""),
2782 int i;
2784 if (!prefixcmp(name, "%(prompt"))
2785 return read_prompt("Command argument: ");
2787 for (i = 0; i < ARRAY_SIZE(vars); i++)
2788 if (!strncmp(name, vars[i].name, vars[i].namelen))
2789 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2791 report("Unknown replacement: `%s`", name);
2792 return NULL;
2795 static bool
2796 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2798 char buf[SIZEOF_STR];
2799 int argc;
2801 argv_free(*dst_argv);
2803 for (argc = 0; src_argv[argc]; argc++) {
2804 const char *arg = src_argv[argc];
2805 size_t bufpos = 0;
2807 if (!strcmp(arg, "%(fileargs)")) {
2808 if (!argv_append_array(dst_argv, opt_file_argv))
2809 break;
2810 continue;
2812 } else if (!strcmp(arg, "%(diffargs)")) {
2813 if (!argv_append_array(dst_argv, opt_diff_argv))
2814 break;
2815 continue;
2817 } else if (!strcmp(arg, "%(blameargs)")) {
2818 if (!argv_append_array(dst_argv, opt_blame_argv))
2819 break;
2820 continue;
2822 } else if (!strcmp(arg, "%(revargs)") ||
2823 (first && !strcmp(arg, "%(commit)"))) {
2824 if (!argv_append_array(dst_argv, opt_rev_argv))
2825 break;
2826 continue;
2829 while (arg) {
2830 char *next = strstr(arg, "%(");
2831 int len = next - arg;
2832 const char *value;
2834 if (!next) {
2835 len = strlen(arg);
2836 value = "";
2838 } else {
2839 value = format_arg(next);
2841 if (!value) {
2842 return FALSE;
2846 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2847 return FALSE;
2849 arg = next ? strchr(next, ')') + 1 : NULL;
2852 if (!argv_append(dst_argv, buf))
2853 break;
2856 return src_argv[argc] == NULL;
2859 static bool
2860 restore_view_position(struct view *view)
2862 /* A view without a previous view is the first view */
2863 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2864 select_view_line(view, opt_lineno - 1);
2865 opt_lineno = 0;
2868 /* Ensure that the view position is in a valid state. */
2869 if (!check_position(&view->prev_pos) ||
2870 (view->pipe && view->lines <= view->prev_pos.lineno))
2871 return goto_view_line(view, view->pos.offset, view->pos.lineno);
2873 /* Changing the view position cancels the restoring. */
2874 /* FIXME: Changing back to the first line is not detected. */
2875 if (check_position(&view->pos)) {
2876 clear_position(&view->prev_pos);
2877 return FALSE;
2880 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
2881 view_is_displayed(view))
2882 werase(view->win);
2884 view->pos.col = view->prev_pos.col;
2885 clear_position(&view->prev_pos);
2887 return TRUE;
2890 static void
2891 end_update(struct view *view, bool force)
2893 if (!view->pipe)
2894 return;
2895 while (!view->ops->read(view, NULL))
2896 if (!force)
2897 return;
2898 if (force)
2899 io_kill(view->pipe);
2900 io_done(view->pipe);
2901 view->pipe = NULL;
2904 static void
2905 setup_update(struct view *view, const char *vid)
2907 reset_view(view);
2908 string_copy_rev(view->vid, vid);
2909 view->pipe = &view->io;
2910 view->start_time = time(NULL);
2913 static bool
2914 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2916 bool extra = !!(flags & (OPEN_EXTRA));
2917 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2918 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2920 if (!reload && !strcmp(view->vid, view->id))
2921 return TRUE;
2923 if (view->pipe) {
2924 if (extra)
2925 io_done(view->pipe);
2926 else
2927 end_update(view, TRUE);
2930 if (!refresh && argv) {
2931 view->dir = dir;
2932 if (!format_argv(&view->argv, argv, !view->prev))
2933 return FALSE;
2935 /* Put the current ref_* value to the view title ref
2936 * member. This is needed by the blob view. Most other
2937 * views sets it automatically after loading because the
2938 * first line is a commit line. */
2939 string_copy_rev(view->ref, view->id);
2942 if (view->argv && view->argv[0] &&
2943 !io_run(&view->io, IO_RD, view->dir, view->argv))
2944 return FALSE;
2946 if (!extra)
2947 setup_update(view, view->id);
2949 return TRUE;
2952 static bool
2953 update_view(struct view *view)
2955 char *line;
2956 /* Clear the view and redraw everything since the tree sorting
2957 * might have rearranged things. */
2958 bool redraw = view->lines == 0;
2959 bool can_read = TRUE;
2961 if (!view->pipe)
2962 return TRUE;
2964 if (!io_can_read(view->pipe, FALSE)) {
2965 if (view->lines == 0 && view_is_displayed(view)) {
2966 time_t secs = time(NULL) - view->start_time;
2968 if (secs > 1 && secs > view->update_secs) {
2969 if (view->update_secs == 0)
2970 redraw_view(view);
2971 update_view_title(view);
2972 view->update_secs = secs;
2975 return TRUE;
2978 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2979 if (view->encoding) {
2980 line = encoding_convert(view->encoding, line);
2983 if (!view->ops->read(view, line)) {
2984 report("Allocation failure");
2985 end_update(view, TRUE);
2986 return FALSE;
2991 unsigned long lines = view->lines;
2992 int digits;
2994 for (digits = 0; lines; digits++)
2995 lines /= 10;
2997 /* Keep the displayed view in sync with line number scaling. */
2998 if (digits != view->digits) {
2999 view->digits = digits;
3000 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3001 redraw = TRUE;
3005 if (io_error(view->pipe)) {
3006 report("Failed to read: %s", io_strerror(view->pipe));
3007 end_update(view, TRUE);
3009 } else if (io_eof(view->pipe)) {
3010 if (view_is_displayed(view))
3011 report("");
3012 end_update(view, FALSE);
3015 if (restore_view_position(view))
3016 redraw = TRUE;
3018 if (!view_is_displayed(view))
3019 return TRUE;
3021 if (redraw)
3022 redraw_view_from(view, 0);
3023 else
3024 redraw_view_dirty(view);
3026 /* Update the title _after_ the redraw so that if the redraw picks up a
3027 * commit reference in view->ref it'll be available here. */
3028 update_view_title(view);
3029 return TRUE;
3032 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3034 static struct line *
3035 add_line_data(struct view *view, void *data, enum line_type type)
3037 struct line *line;
3039 if (!realloc_lines(&view->line, view->lines, 1))
3040 return NULL;
3042 line = &view->line[view->lines++];
3043 memset(line, 0, sizeof(*line));
3044 line->type = type;
3045 line->data = data;
3046 line->dirty = 1;
3048 return line;
3051 static struct line *
3052 add_line_text(struct view *view, const char *text, enum line_type type)
3054 char *data = text ? strdup(text) : NULL;
3056 return data ? add_line_data(view, data, type) : NULL;
3059 static struct line *
3060 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3062 char buf[SIZEOF_STR];
3063 int retval;
3065 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3066 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3070 * View opening
3073 static void
3074 load_view(struct view *view, enum open_flags flags)
3076 if (view->pipe)
3077 end_update(view, TRUE);
3078 if (view->ops->private_size) {
3079 if (!view->private)
3080 view->private = calloc(1, view->ops->private_size);
3081 else
3082 memset(view->private, 0, view->ops->private_size);
3084 if (!view->ops->open(view, flags)) {
3085 report("Failed to load %s view", view->name);
3086 return;
3088 restore_view_position(view);
3090 if (view->pipe && view->lines == 0) {
3091 /* Clear the old view and let the incremental updating refill
3092 * the screen. */
3093 werase(view->win);
3094 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3095 clear_position(&view->prev_pos);
3096 report("");
3097 } else if (view_is_displayed(view)) {
3098 redraw_view(view);
3099 report("");
3103 #define refresh_view(view) load_view(view, OPEN_REFRESH)
3104 #define reload_view(view) load_view(view, OPEN_RELOAD)
3106 static void
3107 split_view(struct view *prev, struct view *view)
3109 display[1] = view;
3110 current_view = 1;
3111 view->parent = prev;
3112 resize_display();
3114 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3115 /* Take the title line into account. */
3116 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3118 /* Scroll the view that was split if the current line is
3119 * outside the new limited view. */
3120 do_scroll_view(prev, lines);
3123 if (view != prev && view_is_displayed(prev)) {
3124 /* "Blur" the previous view. */
3125 update_view_title(prev);
3129 static void
3130 open_view(struct view *prev, enum request request, enum open_flags flags)
3132 bool split = !!(flags & OPEN_SPLIT);
3133 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3134 struct view *view = VIEW(request);
3135 int nviews = displayed_views();
3137 assert(flags ^ OPEN_REFRESH);
3139 if (view == prev && nviews == 1 && !reload) {
3140 report("Already in %s view", view->name);
3141 return;
3144 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3145 report("The %s view is disabled in pager view", view->name);
3146 return;
3149 if (split) {
3150 split_view(prev, view);
3151 } else {
3152 maximize_view(view, FALSE);
3155 /* No prev signals that this is the first loaded view. */
3156 if (prev && view != prev) {
3157 view->prev = prev;
3160 load_view(view, flags);
3163 static void
3164 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3166 enum request request = view - views + REQ_OFFSET + 1;
3168 if (view->pipe)
3169 end_update(view, TRUE);
3170 view->dir = dir;
3172 if (!argv_copy(&view->argv, argv)) {
3173 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3174 } else {
3175 open_view(prev, request, flags | OPEN_PREPARED);
3179 static void
3180 open_external_viewer(const char *argv[], const char *dir)
3182 def_prog_mode(); /* save current tty modes */
3183 endwin(); /* restore original tty modes */
3184 io_run_fg(argv, dir);
3185 fprintf(stderr, "Press Enter to continue");
3186 getc(opt_tty);
3187 reset_prog_mode();
3188 redraw_display(TRUE);
3191 static void
3192 open_mergetool(const char *file)
3194 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3196 open_external_viewer(mergetool_argv, opt_cdup);
3199 static void
3200 open_editor(const char *file)
3202 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3203 char editor_cmd[SIZEOF_STR];
3204 const char *editor;
3205 int argc = 0;
3207 editor = getenv("GIT_EDITOR");
3208 if (!editor && *opt_editor)
3209 editor = opt_editor;
3210 if (!editor)
3211 editor = getenv("VISUAL");
3212 if (!editor)
3213 editor = getenv("EDITOR");
3214 if (!editor)
3215 editor = "vi";
3217 string_ncopy(editor_cmd, editor, strlen(editor));
3218 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3219 report("Failed to read editor command");
3220 return;
3223 editor_argv[argc] = file;
3224 open_external_viewer(editor_argv, opt_cdup);
3227 static void
3228 open_run_request(enum request request)
3230 struct run_request *req = get_run_request(request);
3231 const char **argv = NULL;
3233 if (!req) {
3234 report("Unknown run request");
3235 return;
3238 if (format_argv(&argv, req->argv, FALSE)) {
3239 if (req->silent)
3240 io_run_bg(argv);
3241 else
3242 open_external_viewer(argv, NULL);
3244 if (argv)
3245 argv_free(argv);
3246 free(argv);
3250 * User request switch noodle
3253 static int
3254 view_driver(struct view *view, enum request request)
3256 int i;
3258 if (request == REQ_NONE)
3259 return TRUE;
3261 if (request > REQ_NONE) {
3262 open_run_request(request);
3263 view_request(view, REQ_REFRESH);
3264 return TRUE;
3267 request = view_request(view, request);
3268 if (request == REQ_NONE)
3269 return TRUE;
3271 switch (request) {
3272 case REQ_MOVE_UP:
3273 case REQ_MOVE_DOWN:
3274 case REQ_MOVE_PAGE_UP:
3275 case REQ_MOVE_PAGE_DOWN:
3276 case REQ_MOVE_FIRST_LINE:
3277 case REQ_MOVE_LAST_LINE:
3278 move_view(view, request);
3279 break;
3281 case REQ_SCROLL_FIRST_COL:
3282 case REQ_SCROLL_LEFT:
3283 case REQ_SCROLL_RIGHT:
3284 case REQ_SCROLL_LINE_DOWN:
3285 case REQ_SCROLL_LINE_UP:
3286 case REQ_SCROLL_PAGE_DOWN:
3287 case REQ_SCROLL_PAGE_UP:
3288 scroll_view(view, request);
3289 break;
3291 case REQ_VIEW_BLAME:
3292 if (!opt_file[0]) {
3293 report("No file chosen, press %s to open tree view",
3294 get_view_key(view, REQ_VIEW_TREE));
3295 break;
3297 open_view(view, request, OPEN_DEFAULT);
3298 break;
3300 case REQ_VIEW_BLOB:
3301 if (!ref_blob[0]) {
3302 report("No file chosen, press %s to open tree view",
3303 get_view_key(view, REQ_VIEW_TREE));
3304 break;
3306 open_view(view, request, OPEN_DEFAULT);
3307 break;
3309 case REQ_VIEW_PAGER:
3310 if (view == NULL) {
3311 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
3312 die("Failed to open stdin");
3313 open_view(view, request, OPEN_PREPARED);
3314 break;
3317 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
3318 report("No pager content, press %s to run command from prompt",
3319 get_view_key(view, REQ_PROMPT));
3320 break;
3322 open_view(view, request, OPEN_DEFAULT);
3323 break;
3325 case REQ_VIEW_STAGE:
3326 if (!VIEW(REQ_VIEW_STAGE)->lines) {
3327 report("No stage content, press %s to open the status view and choose file",
3328 get_view_key(view, REQ_VIEW_STATUS));
3329 break;
3331 open_view(view, request, OPEN_DEFAULT);
3332 break;
3334 case REQ_VIEW_STATUS:
3335 if (opt_is_inside_work_tree == FALSE) {
3336 report("The status view requires a working tree");
3337 break;
3339 open_view(view, request, OPEN_DEFAULT);
3340 break;
3342 case REQ_VIEW_MAIN:
3343 case REQ_VIEW_DIFF:
3344 case REQ_VIEW_LOG:
3345 case REQ_VIEW_TREE:
3346 case REQ_VIEW_HELP:
3347 case REQ_VIEW_BRANCH:
3348 open_view(view, request, OPEN_DEFAULT);
3349 break;
3351 case REQ_NEXT:
3352 case REQ_PREVIOUS:
3353 if (view->parent) {
3354 int line;
3356 view = view->parent;
3357 line = view->pos.lineno;
3358 move_view(view, request);
3359 if (view_is_displayed(view))
3360 update_view_title(view);
3361 if (line != view->pos.lineno)
3362 view_request(view, REQ_ENTER);
3363 } else {
3364 move_view(view, request);
3366 break;
3368 case REQ_VIEW_NEXT:
3370 int nviews = displayed_views();
3371 int next_view = (current_view + 1) % nviews;
3373 if (next_view == current_view) {
3374 report("Only one view is displayed");
3375 break;
3378 current_view = next_view;
3379 /* Blur out the title of the previous view. */
3380 update_view_title(view);
3381 report("");
3382 break;
3384 case REQ_REFRESH:
3385 report("Refreshing is not yet supported for the %s view", view->name);
3386 break;
3388 case REQ_MAXIMIZE:
3389 if (displayed_views() == 2)
3390 maximize_view(view, TRUE);
3391 break;
3393 case REQ_OPTIONS:
3394 case REQ_TOGGLE_LINENO:
3395 case REQ_TOGGLE_DATE:
3396 case REQ_TOGGLE_AUTHOR:
3397 case REQ_TOGGLE_FILENAME:
3398 case REQ_TOGGLE_GRAPHIC:
3399 case REQ_TOGGLE_REV_GRAPH:
3400 case REQ_TOGGLE_REFS:
3401 case REQ_TOGGLE_CHANGES:
3402 case REQ_TOGGLE_IGNORE_SPACE:
3403 if (toggle_option(request) && view_has_flags(view, VIEW_DIFF_LIKE))
3404 reload_view(view);
3405 break;
3407 case REQ_TOGGLE_SORT_FIELD:
3408 case REQ_TOGGLE_SORT_ORDER:
3409 report("Sorting is not yet supported for the %s view", view->name);
3410 break;
3412 case REQ_DIFF_CONTEXT_UP:
3413 case REQ_DIFF_CONTEXT_DOWN:
3414 report("Changing the diff context is not yet supported for the %s view", view->name);
3415 break;
3417 case REQ_SEARCH:
3418 case REQ_SEARCH_BACK:
3419 search_view(view, request);
3420 break;
3422 case REQ_FIND_NEXT:
3423 case REQ_FIND_PREV:
3424 find_next(view, request);
3425 break;
3427 case REQ_STOP_LOADING:
3428 foreach_view(view, i) {
3429 if (view->pipe)
3430 report("Stopped loading the %s view", view->name),
3431 end_update(view, TRUE);
3433 break;
3435 case REQ_SHOW_VERSION:
3436 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3437 return TRUE;
3439 case REQ_SCREEN_REDRAW:
3440 redraw_display(TRUE);
3441 break;
3443 case REQ_EDIT:
3444 report("Nothing to edit");
3445 break;
3447 case REQ_ENTER:
3448 report("Nothing to enter");
3449 break;
3451 case REQ_VIEW_CLOSE:
3452 /* XXX: Mark closed views by letting view->prev point to the
3453 * view itself. Parents to closed view should never be
3454 * followed. */
3455 if (view->prev && view->prev != view) {
3456 maximize_view(view->prev, TRUE);
3457 view->prev = view;
3458 break;
3460 /* Fall-through */
3461 case REQ_QUIT:
3462 return FALSE;
3464 default:
3465 report("Unknown key, press %s for help",
3466 get_view_key(view, REQ_VIEW_HELP));
3467 return TRUE;
3470 return TRUE;
3475 * View backend utilities
3478 enum sort_field {
3479 ORDERBY_NAME,
3480 ORDERBY_DATE,
3481 ORDERBY_AUTHOR,
3484 struct sort_state {
3485 const enum sort_field *fields;
3486 size_t size, current;
3487 bool reverse;
3490 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3491 #define get_sort_field(state) ((state).fields[(state).current])
3492 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3494 static void
3495 sort_view(struct view *view, enum request request, struct sort_state *state,
3496 int (*compare)(const void *, const void *))
3498 switch (request) {
3499 case REQ_TOGGLE_SORT_FIELD:
3500 state->current = (state->current + 1) % state->size;
3501 break;
3503 case REQ_TOGGLE_SORT_ORDER:
3504 state->reverse = !state->reverse;
3505 break;
3506 default:
3507 die("Not a sort request");
3510 qsort(view->line, view->lines, sizeof(*view->line), compare);
3511 redraw_view(view);
3514 static bool
3515 update_diff_context(enum request request)
3517 int diff_context = opt_diff_context;
3519 switch (request) {
3520 case REQ_DIFF_CONTEXT_UP:
3521 opt_diff_context += 1;
3522 update_diff_context_arg(opt_diff_context);
3523 break;
3525 case REQ_DIFF_CONTEXT_DOWN:
3526 if (opt_diff_context == 0) {
3527 report("Diff context cannot be less than zero");
3528 break;
3530 opt_diff_context -= 1;
3531 update_diff_context_arg(opt_diff_context);
3532 break;
3534 default:
3535 die("Not a diff context request");
3538 return diff_context != opt_diff_context;
3541 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3543 /* Small author cache to reduce memory consumption. It uses binary
3544 * search to lookup or find place to position new entries. No entries
3545 * are ever freed. */
3546 static const char *
3547 get_author(const char *name)
3549 static const char **authors;
3550 static size_t authors_size;
3551 int from = 0, to = authors_size - 1;
3553 while (from <= to) {
3554 size_t pos = (to + from) / 2;
3555 int cmp = strcmp(name, authors[pos]);
3557 if (!cmp)
3558 return authors[pos];
3560 if (cmp < 0)
3561 to = pos - 1;
3562 else
3563 from = pos + 1;
3566 if (!realloc_authors(&authors, authors_size, 1))
3567 return NULL;
3568 name = strdup(name);
3569 if (!name)
3570 return NULL;
3572 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3573 authors[from] = name;
3574 authors_size++;
3576 return name;
3579 static void
3580 parse_timesec(struct time *time, const char *sec)
3582 time->sec = (time_t) atol(sec);
3585 static void
3586 parse_timezone(struct time *time, const char *zone)
3588 long tz;
3590 tz = ('0' - zone[1]) * 60 * 60 * 10;
3591 tz += ('0' - zone[2]) * 60 * 60;
3592 tz += ('0' - zone[3]) * 60 * 10;
3593 tz += ('0' - zone[4]) * 60;
3595 if (zone[0] == '-')
3596 tz = -tz;
3598 time->tz = tz;
3599 time->sec -= tz;
3602 /* Parse author lines where the name may be empty:
3603 * author <email@address.tld> 1138474660 +0100
3605 static void
3606 parse_author_line(char *ident, const char **author, struct time *time)
3608 char *nameend = strchr(ident, '<');
3609 char *emailend = strchr(ident, '>');
3611 if (nameend && emailend)
3612 *nameend = *emailend = 0;
3613 ident = chomp_string(ident);
3614 if (!*ident) {
3615 if (nameend)
3616 ident = chomp_string(nameend + 1);
3617 if (!*ident)
3618 ident = "Unknown";
3621 *author = get_author(ident);
3623 /* Parse epoch and timezone */
3624 if (emailend && emailend[1] == ' ') {
3625 char *secs = emailend + 2;
3626 char *zone = strchr(secs, ' ');
3628 parse_timesec(time, secs);
3630 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3631 parse_timezone(time, zone + 1);
3635 static struct line *
3636 find_prev_line_by_type(struct view *view, struct line *line, enum line_type type)
3638 for (; view->line < line; line--)
3639 if (line->type == type)
3640 return line;
3642 return NULL;
3646 * Blame
3649 struct blame_commit {
3650 char id[SIZEOF_REV]; /* SHA1 ID. */
3651 char title[128]; /* First line of the commit message. */
3652 const char *author; /* Author of the commit. */
3653 struct time time; /* Date from the author ident. */
3654 char filename[128]; /* Name of file. */
3655 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3656 char parent_filename[128]; /* Parent/previous name of file. */
3659 struct blame_header {
3660 char id[SIZEOF_REV]; /* SHA1 ID. */
3661 size_t orig_lineno;
3662 size_t lineno;
3663 size_t group;
3666 static bool
3667 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3669 const char *pos = *posref;
3671 *posref = NULL;
3672 pos = strchr(pos + 1, ' ');
3673 if (!pos || !isdigit(pos[1]))
3674 return FALSE;
3675 *number = atoi(pos + 1);
3676 if (*number < min || *number > max)
3677 return FALSE;
3679 *posref = pos;
3680 return TRUE;
3683 static bool
3684 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3686 const char *pos = text + SIZEOF_REV - 2;
3688 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3689 return FALSE;
3691 string_ncopy(header->id, text, SIZEOF_REV);
3693 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3694 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3695 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3696 return FALSE;
3698 return TRUE;
3701 static bool
3702 match_blame_header(const char *name, char **line)
3704 size_t namelen = strlen(name);
3705 bool matched = !strncmp(name, *line, namelen);
3707 if (matched)
3708 *line += namelen;
3710 return matched;
3713 static bool
3714 parse_blame_info(struct blame_commit *commit, char *line)
3716 if (match_blame_header("author ", &line)) {
3717 commit->author = get_author(line);
3719 } else if (match_blame_header("author-time ", &line)) {
3720 parse_timesec(&commit->time, line);
3722 } else if (match_blame_header("author-tz ", &line)) {
3723 parse_timezone(&commit->time, line);
3725 } else if (match_blame_header("summary ", &line)) {
3726 string_ncopy(commit->title, line, strlen(line));
3728 } else if (match_blame_header("previous ", &line)) {
3729 if (strlen(line) <= SIZEOF_REV)
3730 return FALSE;
3731 string_copy_rev(commit->parent_id, line);
3732 line += SIZEOF_REV;
3733 string_ncopy(commit->parent_filename, line, strlen(line));
3735 } else if (match_blame_header("filename ", &line)) {
3736 string_ncopy(commit->filename, line, strlen(line));
3737 return TRUE;
3740 return FALSE;
3744 * Pager backend
3747 static bool
3748 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3750 if (draw_lineno(view, lineno))
3751 return TRUE;
3753 draw_text(view, line->type, line->data);
3754 return TRUE;
3757 static bool
3758 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3760 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3761 char ref[SIZEOF_STR];
3763 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3764 return TRUE;
3766 /* This is the only fatal call, since it can "corrupt" the buffer. */
3767 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3768 return FALSE;
3770 return TRUE;
3773 static void
3774 add_pager_refs(struct view *view, struct line *line)
3776 char buf[SIZEOF_STR];
3777 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3778 struct ref_list *list;
3779 size_t bufpos = 0, i;
3780 const char *sep = "Refs: ";
3781 bool is_tag = FALSE;
3783 assert(line->type == LINE_COMMIT);
3785 list = get_ref_list(commit_id);
3786 if (!list) {
3787 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3788 goto try_add_describe_ref;
3789 return;
3792 for (i = 0; i < list->size; i++) {
3793 struct ref *ref = list->refs[i];
3794 const char *fmt = ref->tag ? "%s[%s]" :
3795 ref->remote ? "%s<%s>" : "%s%s";
3797 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3798 return;
3799 sep = ", ";
3800 if (ref->tag)
3801 is_tag = TRUE;
3804 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3805 try_add_describe_ref:
3806 /* Add <tag>-g<commit_id> "fake" reference. */
3807 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3808 return;
3811 if (bufpos == 0)
3812 return;
3814 add_line_text(view, buf, LINE_PP_REFS);
3817 static bool
3818 pager_common_read(struct view *view, char *data, enum line_type type)
3820 struct line *line;
3822 if (!data)
3823 return TRUE;
3825 line = add_line_text(view, data, type);
3826 if (!line)
3827 return FALSE;
3829 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
3830 add_pager_refs(view, line);
3832 return TRUE;
3835 static bool
3836 pager_read(struct view *view, char *data)
3838 if (!data)
3839 return TRUE;
3841 return pager_common_read(view, data, get_line_type(data));
3844 static enum request
3845 pager_request(struct view *view, enum request request, struct line *line)
3847 int split = 0;
3849 if (request != REQ_ENTER)
3850 return request;
3852 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
3853 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3854 split = 1;
3857 /* Always scroll the view even if it was split. That way
3858 * you can use Enter to scroll through the log view and
3859 * split open each commit diff. */
3860 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3862 /* FIXME: A minor workaround. Scrolling the view will call report("")
3863 * but if we are scrolling a non-current view this won't properly
3864 * update the view title. */
3865 if (split)
3866 update_view_title(view);
3868 return REQ_NONE;
3871 static bool
3872 pager_grep(struct view *view, struct line *line)
3874 const char *text[] = { line->data, NULL };
3876 return grep_text(view, text);
3879 static void
3880 pager_select(struct view *view, struct line *line)
3882 if (line->type == LINE_COMMIT) {
3883 char *text = (char *)line->data + STRING_SIZE("commit ");
3885 if (!view_has_flags(view, VIEW_NO_REF))
3886 string_copy_rev(view->ref, text);
3887 string_copy_rev(ref_commit, text);
3891 static bool
3892 pager_open(struct view *view, enum open_flags flags)
3894 return begin_update(view, NULL, NULL, flags);
3897 static struct view_ops pager_ops = {
3898 "line",
3899 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
3901 pager_open,
3902 pager_read,
3903 pager_draw,
3904 pager_request,
3905 pager_grep,
3906 pager_select,
3909 static bool
3910 log_open(struct view *view, enum open_flags flags)
3912 static const char *log_argv[] = {
3913 "git", "log", ENCODING_ARG, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3916 return begin_update(view, NULL, log_argv, flags);
3919 static enum request
3920 log_request(struct view *view, enum request request, struct line *line)
3922 switch (request) {
3923 case REQ_REFRESH:
3924 load_refs();
3925 refresh_view(view);
3926 return REQ_NONE;
3927 default:
3928 return pager_request(view, request, line);
3932 static struct view_ops log_ops = {
3933 "line",
3934 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
3936 log_open,
3937 pager_read,
3938 pager_draw,
3939 log_request,
3940 pager_grep,
3941 pager_select,
3944 struct diff_state {
3945 bool reading_diff_stat;
3946 bool combined_diff;
3949 static bool
3950 diff_open(struct view *view, enum open_flags flags)
3952 static const char *diff_argv[] = {
3953 "git", "show", ENCODING_ARG, "--pretty=fuller", "--no-color", "--root",
3954 "--patch-with-stat", "--find-copies-harder", "-C",
3955 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
3956 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3959 return begin_update(view, NULL, diff_argv, flags);
3962 static bool
3963 diff_common_read(struct view *view, char *data, struct diff_state *state)
3965 enum line_type type;
3967 if (state->reading_diff_stat) {
3968 size_t len = strlen(data);
3969 char *pipe = strchr(data, '|');
3970 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3971 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3973 if (pipe && (has_histogram || has_bin_diff)) {
3974 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3975 } else {
3976 state->reading_diff_stat = FALSE;
3979 } else if (!strcmp(data, "---")) {
3980 state->reading_diff_stat = TRUE;
3983 type = get_line_type(data);
3985 if (type == LINE_DIFF_HEADER) {
3986 const int len = line_info[LINE_DIFF_HEADER].linelen;
3988 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
3989 !strncmp(data + len, "cc ", strlen("cc ")))
3990 state->combined_diff = TRUE;
3993 /* ADD2 and DEL2 are only valid in combined diff hunks */
3994 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
3995 type = LINE_DEFAULT;
3997 return pager_common_read(view, data, type);
4000 static enum request
4001 diff_common_enter(struct view *view, enum request request, struct line *line)
4003 if (line->type == LINE_DIFF_STAT) {
4004 int file_number = 0;
4006 while (line >= view->line && line->type == LINE_DIFF_STAT) {
4007 file_number++;
4008 line--;
4011 while (line < view->line + view->lines) {
4012 if (line->type == LINE_DIFF_HEADER) {
4013 if (file_number == 1) {
4014 break;
4016 file_number--;
4018 line++;
4022 select_view_line(view, line - view->line);
4023 report("");
4024 return REQ_NONE;
4026 } else {
4027 return pager_request(view, request, line);
4031 static bool
4032 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4034 char *sep = strchr(*text, c);
4036 if (sep != NULL) {
4037 *sep = 0;
4038 draw_text(view, *type, *text);
4039 *sep = c;
4040 *text = sep;
4041 *type = next_type;
4044 return sep != NULL;
4047 static bool
4048 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4050 char *text = line->data;
4051 enum line_type type = line->type;
4053 if (draw_lineno(view, lineno))
4054 return TRUE;
4056 if (type == LINE_DIFF_STAT) {
4057 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4058 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4059 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4060 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4061 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4062 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4063 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4065 } else {
4066 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4067 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4071 draw_text(view, type, text);
4072 return TRUE;
4075 static bool
4076 diff_read(struct view *view, char *data)
4078 struct diff_state *state = view->private;
4080 if (!data) {
4081 /* Fall back to retry if no diff will be shown. */
4082 if (view->lines == 0 && opt_file_argv) {
4083 int pos = argv_size(view->argv)
4084 - argv_size(opt_file_argv) - 1;
4086 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4087 for (; view->argv[pos]; pos++) {
4088 free((void *) view->argv[pos]);
4089 view->argv[pos] = NULL;
4092 if (view->pipe)
4093 io_done(view->pipe);
4094 if (io_run(&view->io, IO_RD, view->dir, view->argv))
4095 return FALSE;
4098 return TRUE;
4101 return diff_common_read(view, data, state);
4104 static bool
4105 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4106 struct blame_header *header, struct blame_commit *commit)
4108 char line_arg[SIZEOF_STR];
4109 const char *blame_argv[] = {
4110 "git", "blame", ENCODING_ARG, "-p", line_arg, ref, "--", file, NULL
4112 struct io io;
4113 bool ok = FALSE;
4114 char *buf;
4116 if (!string_format(line_arg, "-L%d,+1", lineno))
4117 return FALSE;
4119 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
4120 return FALSE;
4122 while ((buf = io_get(&io, '\n', TRUE))) {
4123 if (header) {
4124 if (!parse_blame_header(header, buf, 9999999))
4125 break;
4126 header = NULL;
4128 } else if (parse_blame_info(commit, buf)) {
4129 ok = TRUE;
4130 break;
4134 if (io_error(&io))
4135 ok = FALSE;
4137 io_done(&io);
4138 return ok;
4141 static bool
4142 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4144 return prefixcmp(chunk, "@@ -") ||
4145 !(chunk = strchr(chunk, marker)) ||
4146 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4149 static enum request
4150 diff_trace_origin(struct view *view, struct line *line)
4152 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4153 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4154 const char *chunk_data;
4155 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4156 int lineno = 0;
4157 const char *file = NULL;
4158 char ref[SIZEOF_REF];
4159 struct blame_header header;
4160 struct blame_commit commit;
4162 if (!diff || !chunk || chunk == line) {
4163 report("The line to trace must be inside a diff chunk");
4164 return REQ_NONE;
4167 for (; diff < line && !file; diff++) {
4168 const char *data = diff->data;
4170 if (!prefixcmp(data, "--- a/")) {
4171 file = data + STRING_SIZE("--- a/");
4172 break;
4176 if (diff == line || !file) {
4177 report("Failed to read the file name");
4178 return REQ_NONE;
4181 chunk_data = chunk->data;
4183 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4184 report("Failed to read the line number");
4185 return REQ_NONE;
4188 if (lineno == 0) {
4189 report("This is the origin of the line");
4190 return REQ_NONE;
4193 for (chunk += 1; chunk < line; chunk++) {
4194 if (chunk->type == LINE_DIFF_ADD) {
4195 lineno += chunk_marker == '+';
4196 } else if (chunk->type == LINE_DIFF_DEL) {
4197 lineno += chunk_marker == '-';
4198 } else {
4199 lineno++;
4203 if (chunk_marker == '+')
4204 string_copy(ref, view->vid);
4205 else
4206 string_format(ref, "%s^", view->vid);
4208 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4209 report("Failed to read blame data");
4210 return REQ_NONE;
4213 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4214 string_copy(opt_ref, header.id);
4215 opt_goto_line = header.orig_lineno - 1;
4217 return REQ_VIEW_BLAME;
4220 static enum request
4221 diff_request(struct view *view, enum request request, struct line *line)
4223 switch (request) {
4224 case REQ_VIEW_BLAME:
4225 return diff_trace_origin(view, line);
4227 case REQ_DIFF_CONTEXT_UP:
4228 case REQ_DIFF_CONTEXT_DOWN:
4229 if (!update_diff_context(request))
4230 return REQ_NONE;
4231 reload_view(view);
4232 return REQ_NONE;
4235 case REQ_ENTER:
4236 return diff_common_enter(view, request, line);
4238 default:
4239 return pager_request(view, request, line);
4243 static void
4244 diff_select(struct view *view, struct line *line)
4246 if (line->type == LINE_DIFF_STAT) {
4247 const char *key = get_view_key(view, REQ_ENTER);
4249 string_format(view->ref, "Press '%s' to jump to file diff", key);
4250 } else {
4251 string_ncopy(view->ref, view->id, strlen(view->id));
4252 return pager_select(view, line);
4256 static struct view_ops diff_ops = {
4257 "line",
4258 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS,
4259 sizeof(struct diff_state),
4260 diff_open,
4261 diff_read,
4262 diff_common_draw,
4263 diff_request,
4264 pager_grep,
4265 diff_select,
4269 * Help backend
4272 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
4274 static bool
4275 help_open_keymap_title(struct view *view, enum keymap keymap)
4277 struct line *line;
4279 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
4280 help_keymap_hidden[keymap] ? '+' : '-',
4281 enum_name(keymap_map[keymap]));
4282 if (line)
4283 line->other = keymap;
4285 return help_keymap_hidden[keymap];
4288 static void
4289 help_open_keymap(struct view *view, enum keymap keymap)
4291 const char *group = NULL;
4292 char buf[SIZEOF_STR];
4293 size_t bufpos;
4294 bool add_title = TRUE;
4295 int i;
4297 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4298 const char *key = NULL;
4300 if (req_info[i].request == REQ_NONE)
4301 continue;
4303 if (!req_info[i].request) {
4304 group = req_info[i].help;
4305 continue;
4308 key = get_keys(keymap, req_info[i].request, TRUE);
4309 if (!key || !*key)
4310 continue;
4312 if (add_title && help_open_keymap_title(view, keymap))
4313 return;
4314 add_title = FALSE;
4316 if (group) {
4317 add_line_text(view, group, LINE_HELP_GROUP);
4318 group = NULL;
4321 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4322 enum_name(req_info[i]), req_info[i].help);
4325 group = "External commands:";
4327 for (i = 0; i < run_requests; i++) {
4328 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4329 const char *key;
4330 int argc;
4332 if (!req || req->keymap != keymap)
4333 continue;
4335 key = get_key_name(req->key);
4336 if (!*key)
4337 key = "(no key defined)";
4339 if (add_title && help_open_keymap_title(view, keymap))
4340 return;
4341 add_title = FALSE;
4343 if (group) {
4344 add_line_text(view, group, LINE_HELP_GROUP);
4345 group = NULL;
4348 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
4349 if (!string_format_from(buf, &bufpos, "%s%s",
4350 argc ? " " : "", req->argv[argc]))
4351 return;
4353 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4357 static bool
4358 help_open(struct view *view, enum open_flags flags)
4360 enum keymap keymap;
4362 reset_view(view);
4363 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4364 add_line_text(view, "", LINE_DEFAULT);
4366 for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
4367 help_open_keymap(view, keymap);
4369 return TRUE;
4372 static enum request
4373 help_request(struct view *view, enum request request, struct line *line)
4375 switch (request) {
4376 case REQ_ENTER:
4377 if (line->type == LINE_HELP_KEYMAP) {
4378 help_keymap_hidden[line->other] =
4379 !help_keymap_hidden[line->other];
4380 refresh_view(view);
4383 return REQ_NONE;
4384 default:
4385 return pager_request(view, request, line);
4389 static struct view_ops help_ops = {
4390 "line",
4391 VIEW_NO_GIT_DIR,
4393 help_open,
4394 NULL,
4395 pager_draw,
4396 help_request,
4397 pager_grep,
4398 pager_select,
4403 * Tree backend
4406 struct tree_stack_entry {
4407 struct tree_stack_entry *prev; /* Entry below this in the stack */
4408 unsigned long lineno; /* Line number to restore */
4409 char *name; /* Position of name in opt_path */
4412 /* The top of the path stack. */
4413 static struct tree_stack_entry *tree_stack = NULL;
4414 unsigned long tree_lineno = 0;
4416 static void
4417 pop_tree_stack_entry(void)
4419 struct tree_stack_entry *entry = tree_stack;
4421 tree_lineno = entry->lineno;
4422 entry->name[0] = 0;
4423 tree_stack = entry->prev;
4424 free(entry);
4427 static void
4428 push_tree_stack_entry(const char *name, unsigned long lineno)
4430 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4431 size_t pathlen = strlen(opt_path);
4433 if (!entry)
4434 return;
4436 entry->prev = tree_stack;
4437 entry->name = opt_path + pathlen;
4438 tree_stack = entry;
4440 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4441 pop_tree_stack_entry();
4442 return;
4445 /* Move the current line to the first tree entry. */
4446 tree_lineno = 1;
4447 entry->lineno = lineno;
4450 /* Parse output from git-ls-tree(1):
4452 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4455 #define SIZEOF_TREE_ATTR \
4456 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4458 #define SIZEOF_TREE_MODE \
4459 STRING_SIZE("100644 ")
4461 #define TREE_ID_OFFSET \
4462 STRING_SIZE("100644 blob ")
4464 struct tree_entry {
4465 char id[SIZEOF_REV];
4466 mode_t mode;
4467 struct time time; /* Date from the author ident. */
4468 const char *author; /* Author of the commit. */
4469 char name[1];
4472 struct tree_state {
4473 const char *author_name;
4474 struct time author_time;
4475 bool read_date;
4478 static const char *
4479 tree_path(const struct line *line)
4481 return ((struct tree_entry *) line->data)->name;
4484 static int
4485 tree_compare_entry(const struct line *line1, const struct line *line2)
4487 if (line1->type != line2->type)
4488 return line1->type == LINE_TREE_DIR ? -1 : 1;
4489 return strcmp(tree_path(line1), tree_path(line2));
4492 static const enum sort_field tree_sort_fields[] = {
4493 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4495 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4497 static int
4498 tree_compare(const void *l1, const void *l2)
4500 const struct line *line1 = (const struct line *) l1;
4501 const struct line *line2 = (const struct line *) l2;
4502 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4503 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4505 if (line1->type == LINE_TREE_HEAD)
4506 return -1;
4507 if (line2->type == LINE_TREE_HEAD)
4508 return 1;
4510 switch (get_sort_field(tree_sort_state)) {
4511 case ORDERBY_DATE:
4512 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4514 case ORDERBY_AUTHOR:
4515 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4517 case ORDERBY_NAME:
4518 default:
4519 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4524 static struct line *
4525 tree_entry(struct view *view, enum line_type type, const char *path,
4526 const char *mode, const char *id)
4528 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4529 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4531 if (!entry || !line) {
4532 free(entry);
4533 return NULL;
4536 strncpy(entry->name, path, strlen(path));
4537 if (mode)
4538 entry->mode = strtoul(mode, NULL, 8);
4539 if (id)
4540 string_copy_rev(entry->id, id);
4542 return line;
4545 static bool
4546 tree_read_date(struct view *view, char *text, struct tree_state *state)
4548 if (!text && state->read_date) {
4549 state->read_date = FALSE;
4550 return TRUE;
4552 } else if (!text) {
4553 /* Find next entry to process */
4554 const char *log_file[] = {
4555 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
4556 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4559 if (!view->lines) {
4560 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4561 report("Tree is empty");
4562 return TRUE;
4565 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4566 report("Failed to load tree data");
4567 return TRUE;
4570 state->read_date = TRUE;
4571 return FALSE;
4573 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4574 parse_author_line(text + STRING_SIZE("author "),
4575 &state->author_name, &state->author_time);
4577 } else if (*text == ':') {
4578 char *pos;
4579 size_t annotated = 1;
4580 size_t i;
4582 pos = strchr(text, '\t');
4583 if (!pos)
4584 return TRUE;
4585 text = pos + 1;
4586 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4587 text += strlen(opt_path);
4588 pos = strchr(text, '/');
4589 if (pos)
4590 *pos = 0;
4592 for (i = 1; i < view->lines; i++) {
4593 struct line *line = &view->line[i];
4594 struct tree_entry *entry = line->data;
4596 annotated += !!entry->author;
4597 if (entry->author || strcmp(entry->name, text))
4598 continue;
4600 entry->author = state->author_name;
4601 entry->time = state->author_time;
4602 line->dirty = 1;
4603 break;
4606 if (annotated == view->lines)
4607 io_kill(view->pipe);
4609 return TRUE;
4612 static bool
4613 tree_read(struct view *view, char *text)
4615 struct tree_state *state = view->private;
4616 struct tree_entry *data;
4617 struct line *entry, *line;
4618 enum line_type type;
4619 size_t textlen = text ? strlen(text) : 0;
4620 char *path = text + SIZEOF_TREE_ATTR;
4622 if (state->read_date || !text)
4623 return tree_read_date(view, text, state);
4625 if (textlen <= SIZEOF_TREE_ATTR)
4626 return FALSE;
4627 if (view->lines == 0 &&
4628 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4629 return FALSE;
4631 /* Strip the path part ... */
4632 if (*opt_path) {
4633 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4634 size_t striplen = strlen(opt_path);
4636 if (pathlen > striplen)
4637 memmove(path, path + striplen,
4638 pathlen - striplen + 1);
4640 /* Insert "link" to parent directory. */
4641 if (view->lines == 1 &&
4642 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4643 return FALSE;
4646 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4647 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4648 if (!entry)
4649 return FALSE;
4650 data = entry->data;
4652 /* Skip "Directory ..." and ".." line. */
4653 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4654 if (tree_compare_entry(line, entry) <= 0)
4655 continue;
4657 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4659 line->data = data;
4660 line->type = type;
4661 for (; line <= entry; line++)
4662 line->dirty = line->cleareol = 1;
4663 return TRUE;
4666 if (tree_lineno > view->pos.lineno) {
4667 view->pos.lineno = tree_lineno;
4668 tree_lineno = 0;
4671 return TRUE;
4674 static bool
4675 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4677 struct tree_entry *entry = line->data;
4679 if (line->type == LINE_TREE_HEAD) {
4680 if (draw_text(view, line->type, "Directory path /"))
4681 return TRUE;
4682 } else {
4683 if (draw_mode(view, entry->mode))
4684 return TRUE;
4686 if (draw_author(view, entry->author))
4687 return TRUE;
4689 if (draw_date(view, &entry->time))
4690 return TRUE;
4693 draw_text(view, line->type, entry->name);
4694 return TRUE;
4697 static void
4698 open_blob_editor(const char *id)
4700 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4701 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4702 int fd = mkstemp(file);
4704 if (fd == -1)
4705 report("Failed to create temporary file");
4706 else if (!io_run_append(blob_argv, fd))
4707 report("Failed to save blob data to file");
4708 else
4709 open_editor(file);
4710 if (fd != -1)
4711 unlink(file);
4714 static enum request
4715 tree_request(struct view *view, enum request request, struct line *line)
4717 enum open_flags flags;
4718 struct tree_entry *entry = line->data;
4720 switch (request) {
4721 case REQ_VIEW_BLAME:
4722 if (line->type != LINE_TREE_FILE) {
4723 report("Blame only supported for files");
4724 return REQ_NONE;
4727 string_copy(opt_ref, view->vid);
4728 return request;
4730 case REQ_EDIT:
4731 if (line->type != LINE_TREE_FILE) {
4732 report("Edit only supported for files");
4733 } else if (!is_head_commit(view->vid)) {
4734 open_blob_editor(entry->id);
4735 } else {
4736 open_editor(opt_file);
4738 return REQ_NONE;
4740 case REQ_TOGGLE_SORT_FIELD:
4741 case REQ_TOGGLE_SORT_ORDER:
4742 sort_view(view, request, &tree_sort_state, tree_compare);
4743 return REQ_NONE;
4745 case REQ_PARENT:
4746 if (!*opt_path) {
4747 /* quit view if at top of tree */
4748 return REQ_VIEW_CLOSE;
4750 /* fake 'cd ..' */
4751 line = &view->line[1];
4752 break;
4754 case REQ_ENTER:
4755 break;
4757 default:
4758 return request;
4761 /* Cleanup the stack if the tree view is at a different tree. */
4762 while (!*opt_path && tree_stack)
4763 pop_tree_stack_entry();
4765 switch (line->type) {
4766 case LINE_TREE_DIR:
4767 /* Depending on whether it is a subdirectory or parent link
4768 * mangle the path buffer. */
4769 if (line == &view->line[1] && *opt_path) {
4770 pop_tree_stack_entry();
4772 } else {
4773 const char *basename = tree_path(line);
4775 push_tree_stack_entry(basename, view->pos.lineno);
4778 /* Trees and subtrees share the same ID, so they are not not
4779 * unique like blobs. */
4780 flags = OPEN_RELOAD;
4781 request = REQ_VIEW_TREE;
4782 break;
4784 case LINE_TREE_FILE:
4785 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4786 request = REQ_VIEW_BLOB;
4787 break;
4789 default:
4790 return REQ_NONE;
4793 open_view(view, request, flags);
4794 if (request == REQ_VIEW_TREE)
4795 view->pos.lineno = tree_lineno;
4797 return REQ_NONE;
4800 static bool
4801 tree_grep(struct view *view, struct line *line)
4803 struct tree_entry *entry = line->data;
4804 const char *text[] = {
4805 entry->name,
4806 mkauthor(entry->author, opt_author_cols, opt_author),
4807 mkdate(&entry->time, opt_date),
4808 NULL
4811 return grep_text(view, text);
4814 static void
4815 tree_select(struct view *view, struct line *line)
4817 struct tree_entry *entry = line->data;
4819 if (line->type == LINE_TREE_FILE) {
4820 string_copy_rev(ref_blob, entry->id);
4821 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4823 } else if (line->type != LINE_TREE_DIR) {
4824 return;
4827 string_copy_rev(view->ref, entry->id);
4830 static bool
4831 tree_open(struct view *view, enum open_flags flags)
4833 static const char *tree_argv[] = {
4834 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4837 if (view->lines == 0 && opt_prefix[0]) {
4838 char *pos = opt_prefix;
4840 while (pos && *pos) {
4841 char *end = strchr(pos, '/');
4843 if (end)
4844 *end = 0;
4845 push_tree_stack_entry(pos, 0);
4846 pos = end;
4847 if (end) {
4848 *end = '/';
4849 pos++;
4853 } else if (strcmp(view->vid, view->id)) {
4854 opt_path[0] = 0;
4857 return begin_update(view, opt_cdup, tree_argv, flags);
4860 static struct view_ops tree_ops = {
4861 "file",
4862 VIEW_NO_FLAGS,
4863 sizeof(struct tree_state),
4864 tree_open,
4865 tree_read,
4866 tree_draw,
4867 tree_request,
4868 tree_grep,
4869 tree_select,
4872 static bool
4873 blob_open(struct view *view, enum open_flags flags)
4875 static const char *blob_argv[] = {
4876 "git", "cat-file", "blob", "%(blob)", NULL
4879 view->encoding = get_path_encoding(opt_file, opt_encoding);
4881 return begin_update(view, NULL, blob_argv, flags);
4884 static bool
4885 blob_read(struct view *view, char *line)
4887 if (!line)
4888 return TRUE;
4889 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4892 static enum request
4893 blob_request(struct view *view, enum request request, struct line *line)
4895 switch (request) {
4896 case REQ_EDIT:
4897 open_blob_editor(view->vid);
4898 return REQ_NONE;
4899 default:
4900 return pager_request(view, request, line);
4904 static struct view_ops blob_ops = {
4905 "line",
4906 VIEW_NO_FLAGS,
4908 blob_open,
4909 blob_read,
4910 pager_draw,
4911 blob_request,
4912 pager_grep,
4913 pager_select,
4917 * Blame backend
4919 * Loading the blame view is a two phase job:
4921 * 1. File content is read either using opt_file from the
4922 * filesystem or using git-cat-file.
4923 * 2. Then blame information is incrementally added by
4924 * reading output from git-blame.
4927 struct blame {
4928 struct blame_commit *commit;
4929 unsigned long lineno;
4930 char text[1];
4933 struct blame_state {
4934 struct blame_commit *commit;
4935 int blamed;
4936 bool done_reading;
4937 bool auto_filename_display;
4940 static bool
4941 blame_detect_filename_display(struct view *view)
4943 bool show_filenames = FALSE;
4944 const char *filename = NULL;
4945 int i;
4947 if (opt_blame_argv) {
4948 for (i = 0; opt_blame_argv[i]; i++) {
4949 if (prefixcmp(opt_blame_argv[i], "-C"))
4950 continue;
4952 show_filenames = TRUE;
4956 for (i = 0; i < view->lines; i++) {
4957 struct blame *blame = view->line[i].data;
4959 if (blame->commit && blame->commit->id[0]) {
4960 if (!filename)
4961 filename = blame->commit->filename;
4962 else if (strcmp(filename, blame->commit->filename))
4963 show_filenames = TRUE;
4967 return show_filenames;
4970 static bool
4971 blame_open(struct view *view, enum open_flags flags)
4973 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4974 char path[SIZEOF_STR];
4975 size_t i;
4977 if (!view->prev && *opt_prefix) {
4978 string_copy(path, opt_file);
4979 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4980 return FALSE;
4983 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4984 const char *blame_cat_file_argv[] = {
4985 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4988 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4989 return FALSE;
4992 /* First pass: remove multiple references to the same commit. */
4993 for (i = 0; i < view->lines; i++) {
4994 struct blame *blame = view->line[i].data;
4996 if (blame->commit && blame->commit->id[0])
4997 blame->commit->id[0] = 0;
4998 else
4999 blame->commit = NULL;
5002 /* Second pass: free existing references. */
5003 for (i = 0; i < view->lines; i++) {
5004 struct blame *blame = view->line[i].data;
5006 if (blame->commit)
5007 free(blame->commit);
5010 string_format(view->vid, "%s", opt_file);
5011 string_format(view->ref, "%s ...", opt_file);
5013 return TRUE;
5016 static struct blame_commit *
5017 get_blame_commit(struct view *view, const char *id)
5019 size_t i;
5021 for (i = 0; i < view->lines; i++) {
5022 struct blame *blame = view->line[i].data;
5024 if (!blame->commit)
5025 continue;
5027 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5028 return blame->commit;
5032 struct blame_commit *commit = calloc(1, sizeof(*commit));
5034 if (commit)
5035 string_ncopy(commit->id, id, SIZEOF_REV);
5036 return commit;
5040 static struct blame_commit *
5041 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5043 struct blame_header header;
5044 struct blame_commit *commit;
5045 struct blame *blame;
5047 if (!parse_blame_header(&header, text, view->lines))
5048 return NULL;
5050 commit = get_blame_commit(view, text);
5051 if (!commit)
5052 return NULL;
5054 state->blamed += header.group;
5055 while (header.group--) {
5056 struct line *line = &view->line[header.lineno + header.group - 1];
5058 blame = line->data;
5059 blame->commit = commit;
5060 blame->lineno = header.orig_lineno + header.group - 1;
5061 line->dirty = 1;
5064 return commit;
5067 static bool
5068 blame_read_file(struct view *view, const char *line, struct blame_state *state)
5070 if (!line) {
5071 const char *blame_argv[] = {
5072 "git", "blame", ENCODING_ARG, "%(blameargs)", "--incremental",
5073 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5076 if (view->lines == 0 && !view->prev)
5077 die("No blame exist for %s", view->vid);
5079 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5080 report("Failed to load blame data");
5081 return TRUE;
5084 if (opt_goto_line > 0) {
5085 select_view_line(view, opt_goto_line);
5086 opt_goto_line = 0;
5089 state->done_reading = TRUE;
5090 return FALSE;
5092 } else {
5093 size_t linelen = strlen(line);
5094 struct blame *blame = malloc(sizeof(*blame) + linelen);
5096 if (!blame)
5097 return FALSE;
5099 blame->commit = NULL;
5100 strncpy(blame->text, line, linelen);
5101 blame->text[linelen] = 0;
5102 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
5106 static bool
5107 blame_read(struct view *view, char *line)
5109 struct blame_state *state = view->private;
5111 if (!state->done_reading)
5112 return blame_read_file(view, line, state);
5114 if (!line) {
5115 state->auto_filename_display = blame_detect_filename_display(view);
5116 string_format(view->ref, "%s", view->vid);
5117 if (view_is_displayed(view)) {
5118 update_view_title(view);
5119 redraw_view_from(view, 0);
5121 return TRUE;
5124 if (!state->commit) {
5125 state->commit = read_blame_commit(view, line, state);
5126 string_format(view->ref, "%s %2d%%", view->vid,
5127 view->lines ? state->blamed * 100 / view->lines : 0);
5129 } else if (parse_blame_info(state->commit, line)) {
5130 state->commit = NULL;
5133 return TRUE;
5136 static bool
5137 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5139 struct blame_state *state = view->private;
5140 struct blame *blame = line->data;
5141 struct time *time = NULL;
5142 const char *id = NULL, *author = NULL, *filename = NULL;
5143 enum line_type id_type = LINE_BLAME_ID;
5144 static const enum line_type blame_colors[] = {
5145 LINE_PALETTE_0,
5146 LINE_PALETTE_1,
5147 LINE_PALETTE_2,
5148 LINE_PALETTE_3,
5149 LINE_PALETTE_4,
5150 LINE_PALETTE_5,
5151 LINE_PALETTE_6,
5154 #define BLAME_COLOR(i) \
5155 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5157 if (blame->commit && *blame->commit->filename) {
5158 id = blame->commit->id;
5159 author = blame->commit->author;
5160 filename = blame->commit->filename;
5161 time = &blame->commit->time;
5162 id_type = BLAME_COLOR((long) blame->commit);
5165 if (draw_date(view, time))
5166 return TRUE;
5168 if (draw_author(view, author))
5169 return TRUE;
5171 if (draw_filename(view, filename, state->auto_filename_display))
5172 return TRUE;
5174 if (draw_field(view, id_type, id, ID_COLS, FALSE))
5175 return TRUE;
5177 if (draw_lineno(view, lineno))
5178 return TRUE;
5180 draw_text(view, LINE_DEFAULT, blame->text);
5181 return TRUE;
5184 static bool
5185 check_blame_commit(struct blame *blame, bool check_null_id)
5187 if (!blame->commit)
5188 report("Commit data not loaded yet");
5189 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
5190 report("No commit exist for the selected line");
5191 else
5192 return TRUE;
5193 return FALSE;
5196 static void
5197 setup_blame_parent_line(struct view *view, struct blame *blame)
5199 char from[SIZEOF_REF + SIZEOF_STR];
5200 char to[SIZEOF_REF + SIZEOF_STR];
5201 const char *diff_tree_argv[] = {
5202 "git", "diff", ENCODING_ARG, "--no-textconv", "--no-extdiff",
5203 "--no-color", "-U0", from, to, "--", NULL
5205 struct io io;
5206 int parent_lineno = -1;
5207 int blamed_lineno = -1;
5208 char *line;
5210 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5211 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5212 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5213 return;
5215 while ((line = io_get(&io, '\n', TRUE))) {
5216 if (*line == '@') {
5217 char *pos = strchr(line, '+');
5219 parent_lineno = atoi(line + 4);
5220 if (pos)
5221 blamed_lineno = atoi(pos + 1);
5223 } else if (*line == '+' && parent_lineno != -1) {
5224 if (blame->lineno == blamed_lineno - 1 &&
5225 !strcmp(blame->text, line + 1)) {
5226 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
5227 break;
5229 blamed_lineno++;
5233 io_done(&io);
5236 static enum request
5237 blame_request(struct view *view, enum request request, struct line *line)
5239 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5240 struct blame *blame = line->data;
5242 switch (request) {
5243 case REQ_VIEW_BLAME:
5244 if (check_blame_commit(blame, TRUE)) {
5245 string_copy(opt_ref, blame->commit->id);
5246 string_copy(opt_file, blame->commit->filename);
5247 if (blame->lineno)
5248 view->pos.lineno = blame->lineno;
5249 reload_view(view);
5251 break;
5253 case REQ_PARENT:
5254 if (!check_blame_commit(blame, TRUE))
5255 break;
5256 if (!*blame->commit->parent_id) {
5257 report("The selected commit has no parents");
5258 } else {
5259 string_copy_rev(opt_ref, blame->commit->parent_id);
5260 string_copy(opt_file, blame->commit->parent_filename);
5261 setup_blame_parent_line(view, blame);
5262 opt_goto_line = blame->lineno;
5263 reload_view(view);
5265 break;
5267 case REQ_ENTER:
5268 if (!check_blame_commit(blame, FALSE))
5269 break;
5271 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5272 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5273 break;
5275 if (!strcmp(blame->commit->id, NULL_ID)) {
5276 struct view *diff = VIEW(REQ_VIEW_DIFF);
5277 const char *diff_parent_argv[] = {
5278 GIT_DIFF_BLAME(opt_diff_context_arg,
5279 opt_ignore_space_arg, view->vid)
5281 const char *diff_no_parent_argv[] = {
5282 GIT_DIFF_BLAME_NO_PARENT(opt_diff_context_arg,
5283 opt_ignore_space_arg, view->vid)
5285 const char **diff_index_argv = *blame->commit->parent_id
5286 ? diff_parent_argv : diff_no_parent_argv;
5288 open_argv(view, diff, diff_index_argv, NULL, flags);
5289 if (diff->pipe)
5290 string_copy_rev(diff->ref, NULL_ID);
5291 } else {
5292 open_view(view, REQ_VIEW_DIFF, flags);
5294 break;
5296 default:
5297 return request;
5300 return REQ_NONE;
5303 static bool
5304 blame_grep(struct view *view, struct line *line)
5306 struct blame *blame = line->data;
5307 struct blame_commit *commit = blame->commit;
5308 const char *text[] = {
5309 blame->text,
5310 commit ? commit->title : "",
5311 commit ? commit->id : "",
5312 commit && opt_author ? commit->author : "",
5313 commit ? mkdate(&commit->time, opt_date) : "",
5314 NULL
5317 return grep_text(view, text);
5320 static void
5321 blame_select(struct view *view, struct line *line)
5323 struct blame *blame = line->data;
5324 struct blame_commit *commit = blame->commit;
5326 if (!commit)
5327 return;
5329 if (!strcmp(commit->id, NULL_ID))
5330 string_ncopy(ref_commit, "HEAD", 4);
5331 else
5332 string_copy_rev(ref_commit, commit->id);
5335 static struct view_ops blame_ops = {
5336 "line",
5337 VIEW_ALWAYS_LINENO,
5338 sizeof(struct blame_state),
5339 blame_open,
5340 blame_read,
5341 blame_draw,
5342 blame_request,
5343 blame_grep,
5344 blame_select,
5348 * Branch backend
5351 struct branch {
5352 const char *author; /* Author of the last commit. */
5353 struct time time; /* Date of the last activity. */
5354 const struct ref *ref; /* Name and commit ID information. */
5357 static const struct ref branch_all;
5359 static const enum sort_field branch_sort_fields[] = {
5360 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5362 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5364 struct branch_state {
5365 char id[SIZEOF_REV];
5368 static int
5369 branch_compare(const void *l1, const void *l2)
5371 const struct branch *branch1 = ((const struct line *) l1)->data;
5372 const struct branch *branch2 = ((const struct line *) l2)->data;
5374 if (branch1->ref == &branch_all)
5375 return -1;
5376 else if (branch2->ref == &branch_all)
5377 return 1;
5379 switch (get_sort_field(branch_sort_state)) {
5380 case ORDERBY_DATE:
5381 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5383 case ORDERBY_AUTHOR:
5384 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5386 case ORDERBY_NAME:
5387 default:
5388 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5392 static bool
5393 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5395 struct branch *branch = line->data;
5396 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5398 if (draw_date(view, &branch->time))
5399 return TRUE;
5401 if (draw_author(view, branch->author))
5402 return TRUE;
5404 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
5405 return TRUE;
5408 static enum request
5409 branch_request(struct view *view, enum request request, struct line *line)
5411 struct branch *branch = line->data;
5413 switch (request) {
5414 case REQ_REFRESH:
5415 load_refs();
5416 refresh_view(view);
5417 return REQ_NONE;
5419 case REQ_TOGGLE_SORT_FIELD:
5420 case REQ_TOGGLE_SORT_ORDER:
5421 sort_view(view, request, &branch_sort_state, branch_compare);
5422 return REQ_NONE;
5424 case REQ_ENTER:
5426 const struct ref *ref = branch->ref;
5427 const char *all_branches_argv[] = {
5428 "git", "log", ENCODING_ARG, "--no-color",
5429 "--pretty=raw", "--parents", opt_commit_order_arg,
5430 ref == &branch_all ? "--all" : ref->name, NULL
5432 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5434 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5435 return REQ_NONE;
5437 case REQ_JUMP_COMMIT:
5439 int lineno;
5441 for (lineno = 0; lineno < view->lines; lineno++) {
5442 struct branch *branch = view->line[lineno].data;
5444 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5445 select_view_line(view, lineno);
5446 report("");
5447 return REQ_NONE;
5451 default:
5452 return request;
5456 static bool
5457 branch_read(struct view *view, char *line)
5459 struct branch_state *state = view->private;
5460 struct branch *reference;
5461 size_t i;
5463 if (!line)
5464 return TRUE;
5466 switch (get_line_type(line)) {
5467 case LINE_COMMIT:
5468 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5469 return TRUE;
5471 case LINE_AUTHOR:
5472 for (i = 0, reference = NULL; i < view->lines; i++) {
5473 struct branch *branch = view->line[i].data;
5475 if (strcmp(branch->ref->id, state->id))
5476 continue;
5478 view->line[i].dirty = TRUE;
5479 if (reference) {
5480 branch->author = reference->author;
5481 branch->time = reference->time;
5482 continue;
5485 parse_author_line(line + STRING_SIZE("author "),
5486 &branch->author, &branch->time);
5487 reference = branch;
5489 return TRUE;
5491 default:
5492 return TRUE;
5497 static bool
5498 branch_open_visitor(void *data, const struct ref *ref)
5500 struct view *view = data;
5501 struct branch *branch;
5503 if (ref->tag || ref->ltag)
5504 return TRUE;
5506 branch = calloc(1, sizeof(*branch));
5507 if (!branch)
5508 return FALSE;
5510 branch->ref = ref;
5511 return !!add_line_data(view, branch, LINE_DEFAULT);
5514 static bool
5515 branch_open(struct view *view, enum open_flags flags)
5517 const char *branch_log[] = {
5518 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
5519 "--simplify-by-decoration", "--all", NULL
5522 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
5523 report("Failed to load branch data");
5524 return TRUE;
5527 branch_open_visitor(view, &branch_all);
5528 foreach_ref(branch_open_visitor, view);
5530 return TRUE;
5533 static bool
5534 branch_grep(struct view *view, struct line *line)
5536 struct branch *branch = line->data;
5537 const char *text[] = {
5538 branch->ref->name,
5539 mkauthor(branch->author, opt_author_cols, opt_author),
5540 NULL
5543 return grep_text(view, text);
5546 static void
5547 branch_select(struct view *view, struct line *line)
5549 struct branch *branch = line->data;
5551 string_copy_rev(view->ref, branch->ref->id);
5552 string_copy_rev(ref_commit, branch->ref->id);
5553 string_copy_rev(ref_head, branch->ref->id);
5554 string_copy_rev(ref_branch, branch->ref->name);
5557 static struct view_ops branch_ops = {
5558 "branch",
5559 VIEW_NO_FLAGS,
5560 sizeof(struct branch_state),
5561 branch_open,
5562 branch_read,
5563 branch_draw,
5564 branch_request,
5565 branch_grep,
5566 branch_select,
5570 * Status backend
5573 struct status {
5574 char status;
5575 struct {
5576 mode_t mode;
5577 char rev[SIZEOF_REV];
5578 char name[SIZEOF_STR];
5579 } old;
5580 struct {
5581 mode_t mode;
5582 char rev[SIZEOF_REV];
5583 char name[SIZEOF_STR];
5584 } new;
5587 static char status_onbranch[SIZEOF_STR];
5588 static struct status stage_status;
5589 static enum line_type stage_line_type;
5591 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5593 /* This should work even for the "On branch" line. */
5594 static inline bool
5595 status_has_none(struct view *view, struct line *line)
5597 return line < view->line + view->lines && !line[1].data;
5600 /* Get fields from the diff line:
5601 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5603 static inline bool
5604 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5606 const char *old_mode = buf + 1;
5607 const char *new_mode = buf + 8;
5608 const char *old_rev = buf + 15;
5609 const char *new_rev = buf + 56;
5610 const char *status = buf + 97;
5612 if (bufsize < 98 ||
5613 old_mode[-1] != ':' ||
5614 new_mode[-1] != ' ' ||
5615 old_rev[-1] != ' ' ||
5616 new_rev[-1] != ' ' ||
5617 status[-1] != ' ')
5618 return FALSE;
5620 file->status = *status;
5622 string_copy_rev(file->old.rev, old_rev);
5623 string_copy_rev(file->new.rev, new_rev);
5625 file->old.mode = strtoul(old_mode, NULL, 8);
5626 file->new.mode = strtoul(new_mode, NULL, 8);
5628 file->old.name[0] = file->new.name[0] = 0;
5630 return TRUE;
5633 static bool
5634 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5636 struct status *unmerged = NULL;
5637 char *buf;
5638 struct io io;
5640 if (!io_run(&io, IO_RD, opt_cdup, argv))
5641 return FALSE;
5643 add_line_data(view, NULL, type);
5645 while ((buf = io_get(&io, 0, TRUE))) {
5646 struct status *file = unmerged;
5648 if (!file) {
5649 file = calloc(1, sizeof(*file));
5650 if (!file || !add_line_data(view, file, type))
5651 goto error_out;
5654 /* Parse diff info part. */
5655 if (status) {
5656 file->status = status;
5657 if (status == 'A')
5658 string_copy(file->old.rev, NULL_ID);
5660 } else if (!file->status || file == unmerged) {
5661 if (!status_get_diff(file, buf, strlen(buf)))
5662 goto error_out;
5664 buf = io_get(&io, 0, TRUE);
5665 if (!buf)
5666 break;
5668 /* Collapse all modified entries that follow an
5669 * associated unmerged entry. */
5670 if (unmerged == file) {
5671 unmerged->status = 'U';
5672 unmerged = NULL;
5673 } else if (file->status == 'U') {
5674 unmerged = file;
5678 /* Grab the old name for rename/copy. */
5679 if (!*file->old.name &&
5680 (file->status == 'R' || file->status == 'C')) {
5681 string_ncopy(file->old.name, buf, strlen(buf));
5683 buf = io_get(&io, 0, TRUE);
5684 if (!buf)
5685 break;
5688 /* git-ls-files just delivers a NUL separated list of
5689 * file names similar to the second half of the
5690 * git-diff-* output. */
5691 string_ncopy(file->new.name, buf, strlen(buf));
5692 if (!*file->old.name)
5693 string_copy(file->old.name, file->new.name);
5694 file = NULL;
5697 if (io_error(&io)) {
5698 error_out:
5699 io_done(&io);
5700 return FALSE;
5703 if (!view->line[view->lines - 1].data)
5704 add_line_data(view, NULL, LINE_STAT_NONE);
5706 io_done(&io);
5707 return TRUE;
5710 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
5711 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
5713 static const char *status_list_other_argv[] = {
5714 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5717 static const char *status_list_no_head_argv[] = {
5718 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5721 static const char *update_index_argv[] = {
5722 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5725 /* Restore the previous line number to stay in the context or select a
5726 * line with something that can be updated. */
5727 static void
5728 status_restore(struct view *view)
5730 if (view->prev_pos.lineno >= view->lines)
5731 view->prev_pos.lineno = view->lines - 1;
5732 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
5733 view->prev_pos.lineno++;
5734 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
5735 view->prev_pos.lineno--;
5737 /* If the above fails, always skip the "On branch" line. */
5738 if (view->prev_pos.lineno < view->lines)
5739 view->pos.lineno = view->prev_pos.lineno;
5740 else
5741 view->pos.lineno = 1;
5743 if (view->prev_pos.offset > view->pos.lineno)
5744 view->pos.offset = view->pos.lineno;
5745 else if (view->prev_pos.offset < view->lines)
5746 view->pos.offset = view->prev_pos.offset;
5748 clear_position(&view->prev_pos);
5751 static void
5752 status_update_onbranch(void)
5754 static const char *paths[][2] = {
5755 { "rebase-apply/rebasing", "Rebasing" },
5756 { "rebase-apply/applying", "Applying mailbox" },
5757 { "rebase-apply/", "Rebasing mailbox" },
5758 { "rebase-merge/interactive", "Interactive rebase" },
5759 { "rebase-merge/", "Rebase merge" },
5760 { "MERGE_HEAD", "Merging" },
5761 { "BISECT_LOG", "Bisecting" },
5762 { "HEAD", "On branch" },
5764 char buf[SIZEOF_STR];
5765 struct stat stat;
5766 int i;
5768 if (is_initial_commit()) {
5769 string_copy(status_onbranch, "Initial commit");
5770 return;
5773 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5774 char *head = opt_head;
5776 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5777 lstat(buf, &stat) < 0)
5778 continue;
5780 if (!*opt_head) {
5781 struct io io;
5783 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5784 io_read_buf(&io, buf, sizeof(buf))) {
5785 head = buf;
5786 if (!prefixcmp(head, "refs/heads/"))
5787 head += STRING_SIZE("refs/heads/");
5791 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5792 string_copy(status_onbranch, opt_head);
5793 return;
5796 string_copy(status_onbranch, "Not currently on any branch");
5799 /* First parse staged info using git-diff-index(1), then parse unstaged
5800 * info using git-diff-files(1), and finally untracked files using
5801 * git-ls-files(1). */
5802 static bool
5803 status_open(struct view *view, enum open_flags flags)
5805 reset_view(view);
5807 add_line_data(view, NULL, LINE_STAT_HEAD);
5808 status_update_onbranch();
5810 io_run_bg(update_index_argv);
5812 if (is_initial_commit()) {
5813 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5814 return FALSE;
5815 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5816 return FALSE;
5819 if (!opt_untracked_dirs_content)
5820 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5822 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5823 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5824 return FALSE;
5826 /* Restore the exact position or use the specialized restore
5827 * mode? */
5828 status_restore(view);
5829 return TRUE;
5832 static bool
5833 status_draw(struct view *view, struct line *line, unsigned int lineno)
5835 struct status *status = line->data;
5836 enum line_type type;
5837 const char *text;
5839 if (!status) {
5840 switch (line->type) {
5841 case LINE_STAT_STAGED:
5842 type = LINE_STAT_SECTION;
5843 text = "Changes to be committed:";
5844 break;
5846 case LINE_STAT_UNSTAGED:
5847 type = LINE_STAT_SECTION;
5848 text = "Changed but not updated:";
5849 break;
5851 case LINE_STAT_UNTRACKED:
5852 type = LINE_STAT_SECTION;
5853 text = "Untracked files:";
5854 break;
5856 case LINE_STAT_NONE:
5857 type = LINE_DEFAULT;
5858 text = " (no files)";
5859 break;
5861 case LINE_STAT_HEAD:
5862 type = LINE_STAT_HEAD;
5863 text = status_onbranch;
5864 break;
5866 default:
5867 return FALSE;
5869 } else {
5870 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5872 buf[0] = status->status;
5873 if (draw_text(view, line->type, buf))
5874 return TRUE;
5875 type = LINE_DEFAULT;
5876 text = status->new.name;
5879 draw_text(view, type, text);
5880 return TRUE;
5883 static enum request
5884 status_enter(struct view *view, struct line *line)
5886 struct status *status = line->data;
5887 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5889 if (line->type == LINE_STAT_NONE ||
5890 (!status && line[1].type == LINE_STAT_NONE)) {
5891 report("No file to diff");
5892 return REQ_NONE;
5895 switch (line->type) {
5896 case LINE_STAT_STAGED:
5897 case LINE_STAT_UNSTAGED:
5898 break;
5900 case LINE_STAT_UNTRACKED:
5901 if (!status) {
5902 report("No file to show");
5903 return REQ_NONE;
5906 if (!suffixcmp(status->new.name, -1, "/")) {
5907 report("Cannot display a directory");
5908 return REQ_NONE;
5910 break;
5912 case LINE_STAT_HEAD:
5913 return REQ_NONE;
5915 default:
5916 die("line type %d not handled in switch", line->type);
5919 if (status) {
5920 stage_status = *status;
5921 } else {
5922 memset(&stage_status, 0, sizeof(stage_status));
5925 stage_line_type = line->type;
5927 open_view(view, REQ_VIEW_STAGE, flags);
5928 return REQ_NONE;
5931 static bool
5932 status_exists(struct view *view, struct status *status, enum line_type type)
5934 unsigned long lineno;
5936 for (lineno = 0; lineno < view->lines; lineno++) {
5937 struct line *line = &view->line[lineno];
5938 struct status *pos = line->data;
5940 if (line->type != type)
5941 continue;
5942 if (!pos && (!status || !status->status) && line[1].data) {
5943 select_view_line(view, lineno);
5944 return TRUE;
5946 if (pos && !strcmp(status->new.name, pos->new.name)) {
5947 select_view_line(view, lineno);
5948 return TRUE;
5952 return FALSE;
5956 static bool
5957 status_update_prepare(struct io *io, enum line_type type)
5959 const char *staged_argv[] = {
5960 "git", "update-index", "-z", "--index-info", NULL
5962 const char *others_argv[] = {
5963 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5966 switch (type) {
5967 case LINE_STAT_STAGED:
5968 return io_run(io, IO_WR, opt_cdup, staged_argv);
5970 case LINE_STAT_UNSTAGED:
5971 case LINE_STAT_UNTRACKED:
5972 return io_run(io, IO_WR, opt_cdup, others_argv);
5974 default:
5975 die("line type %d not handled in switch", type);
5976 return FALSE;
5980 static bool
5981 status_update_write(struct io *io, struct status *status, enum line_type type)
5983 switch (type) {
5984 case LINE_STAT_STAGED:
5985 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
5986 status->old.rev, status->old.name, 0);
5988 case LINE_STAT_UNSTAGED:
5989 case LINE_STAT_UNTRACKED:
5990 return io_printf(io, "%s%c", status->new.name, 0);
5992 default:
5993 die("line type %d not handled in switch", type);
5994 return FALSE;
5998 static bool
5999 status_update_file(struct status *status, enum line_type type)
6001 struct io io;
6002 bool result;
6004 if (!status_update_prepare(&io, type))
6005 return FALSE;
6007 result = status_update_write(&io, status, type);
6008 return io_done(&io) && result;
6011 static bool
6012 status_update_files(struct view *view, struct line *line)
6014 char buf[sizeof(view->ref)];
6015 struct io io;
6016 bool result = TRUE;
6017 struct line *pos = view->line + view->lines;
6018 int files = 0;
6019 int file, done;
6020 int cursor_y = -1, cursor_x = -1;
6022 if (!status_update_prepare(&io, line->type))
6023 return FALSE;
6025 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
6026 files++;
6028 string_copy(buf, view->ref);
6029 getsyx(cursor_y, cursor_x);
6030 for (file = 0, done = 5; result && file < files; line++, file++) {
6031 int almost_done = file * 100 / files;
6033 if (almost_done > done) {
6034 done = almost_done;
6035 string_format(view->ref, "updating file %u of %u (%d%% done)",
6036 file, files, done);
6037 update_view_title(view);
6038 setsyx(cursor_y, cursor_x);
6039 doupdate();
6041 result = status_update_write(&io, line->data, line->type);
6043 string_copy(view->ref, buf);
6045 return io_done(&io) && result;
6048 static bool
6049 status_update(struct view *view)
6051 struct line *line = &view->line[view->pos.lineno];
6053 assert(view->lines);
6055 if (!line->data) {
6056 /* This should work even for the "On branch" line. */
6057 if (line < view->line + view->lines && !line[1].data) {
6058 report("Nothing to update");
6059 return FALSE;
6062 if (!status_update_files(view, line + 1)) {
6063 report("Failed to update file status");
6064 return FALSE;
6067 } else if (!status_update_file(line->data, line->type)) {
6068 report("Failed to update file status");
6069 return FALSE;
6072 return TRUE;
6075 static bool
6076 status_revert(struct status *status, enum line_type type, bool has_none)
6078 if (!status || type != LINE_STAT_UNSTAGED) {
6079 if (type == LINE_STAT_STAGED) {
6080 report("Cannot revert changes to staged files");
6081 } else if (type == LINE_STAT_UNTRACKED) {
6082 report("Cannot revert changes to untracked files");
6083 } else if (has_none) {
6084 report("Nothing to revert");
6085 } else {
6086 report("Cannot revert changes to multiple files");
6089 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6090 char mode[10] = "100644";
6091 const char *reset_argv[] = {
6092 "git", "update-index", "--cacheinfo", mode,
6093 status->old.rev, status->old.name, NULL
6095 const char *checkout_argv[] = {
6096 "git", "checkout", "--", status->old.name, NULL
6099 if (status->status == 'U') {
6100 string_format(mode, "%5o", status->old.mode);
6102 if (status->old.mode == 0 && status->new.mode == 0) {
6103 reset_argv[2] = "--force-remove";
6104 reset_argv[3] = status->old.name;
6105 reset_argv[4] = NULL;
6108 if (!io_run_fg(reset_argv, opt_cdup))
6109 return FALSE;
6110 if (status->old.mode == 0 && status->new.mode == 0)
6111 return TRUE;
6114 return io_run_fg(checkout_argv, opt_cdup);
6117 return FALSE;
6120 static enum request
6121 status_request(struct view *view, enum request request, struct line *line)
6123 struct status *status = line->data;
6125 switch (request) {
6126 case REQ_STATUS_UPDATE:
6127 if (!status_update(view))
6128 return REQ_NONE;
6129 break;
6131 case REQ_STATUS_REVERT:
6132 if (!status_revert(status, line->type, status_has_none(view, line)))
6133 return REQ_NONE;
6134 break;
6136 case REQ_STATUS_MERGE:
6137 if (!status || status->status != 'U') {
6138 report("Merging only possible for files with unmerged status ('U').");
6139 return REQ_NONE;
6141 open_mergetool(status->new.name);
6142 break;
6144 case REQ_EDIT:
6145 if (!status)
6146 return request;
6147 if (status->status == 'D') {
6148 report("File has been deleted.");
6149 return REQ_NONE;
6152 open_editor(status->new.name);
6153 break;
6155 case REQ_VIEW_BLAME:
6156 if (status)
6157 opt_ref[0] = 0;
6158 return request;
6160 case REQ_ENTER:
6161 /* After returning the status view has been split to
6162 * show the stage view. No further reloading is
6163 * necessary. */
6164 return status_enter(view, line);
6166 case REQ_REFRESH:
6167 /* Simply reload the view. */
6168 break;
6170 default:
6171 return request;
6174 refresh_view(view);
6176 return REQ_NONE;
6179 static void
6180 status_select(struct view *view, struct line *line)
6182 struct status *status = line->data;
6183 char file[SIZEOF_STR] = "all files";
6184 const char *text;
6185 const char *key;
6187 if (status && !string_format(file, "'%s'", status->new.name))
6188 return;
6190 if (!status && line[1].type == LINE_STAT_NONE)
6191 line++;
6193 switch (line->type) {
6194 case LINE_STAT_STAGED:
6195 text = "Press %s to unstage %s for commit";
6196 break;
6198 case LINE_STAT_UNSTAGED:
6199 text = "Press %s to stage %s for commit";
6200 break;
6202 case LINE_STAT_UNTRACKED:
6203 text = "Press %s to stage %s for addition";
6204 break;
6206 case LINE_STAT_HEAD:
6207 case LINE_STAT_NONE:
6208 text = "Nothing to update";
6209 break;
6211 default:
6212 die("line type %d not handled in switch", line->type);
6215 if (status && status->status == 'U') {
6216 text = "Press %s to resolve conflict in %s";
6217 key = get_view_key(view, REQ_STATUS_MERGE);
6219 } else {
6220 key = get_view_key(view, REQ_STATUS_UPDATE);
6223 string_format(view->ref, text, key, file);
6224 if (status)
6225 string_copy(opt_file, status->new.name);
6228 static bool
6229 status_grep(struct view *view, struct line *line)
6231 struct status *status = line->data;
6233 if (status) {
6234 const char buf[2] = { status->status, 0 };
6235 const char *text[] = { status->new.name, buf, NULL };
6237 return grep_text(view, text);
6240 return FALSE;
6243 static struct view_ops status_ops = {
6244 "file",
6245 VIEW_CUSTOM_STATUS,
6247 status_open,
6248 NULL,
6249 status_draw,
6250 status_request,
6251 status_grep,
6252 status_select,
6256 struct stage_state {
6257 struct diff_state diff;
6258 size_t chunks;
6259 int *chunk;
6262 static bool
6263 stage_diff_write(struct io *io, struct line *line, struct line *end)
6265 while (line < end) {
6266 if (!io_write(io, line->data, strlen(line->data)) ||
6267 !io_write(io, "\n", 1))
6268 return FALSE;
6269 line++;
6270 if (line->type == LINE_DIFF_CHUNK ||
6271 line->type == LINE_DIFF_HEADER)
6272 break;
6275 return TRUE;
6278 static bool
6279 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6281 const char *apply_argv[SIZEOF_ARG] = {
6282 "git", "apply", "--whitespace=nowarn", NULL
6284 struct line *diff_hdr;
6285 struct io io;
6286 int argc = 3;
6288 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6289 if (!diff_hdr)
6290 return FALSE;
6292 if (!revert)
6293 apply_argv[argc++] = "--cached";
6294 if (line != NULL)
6295 apply_argv[argc++] = "--unidiff-zero";
6296 if (revert || stage_line_type == LINE_STAT_STAGED)
6297 apply_argv[argc++] = "-R";
6298 apply_argv[argc++] = "-";
6299 apply_argv[argc++] = NULL;
6300 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6301 return FALSE;
6303 if (line != NULL) {
6304 int lineno = 0;
6305 struct line *context = chunk + 1;
6306 const char *markers[] = {
6307 line->type == LINE_DIFF_DEL ? "" : ",0",
6308 line->type == LINE_DIFF_DEL ? ",0" : "",
6311 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6313 while (context < line) {
6314 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6315 break;
6316 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6317 lineno++;
6319 context++;
6322 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6323 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6324 lineno, markers[0], lineno, markers[1]) ||
6325 !stage_diff_write(&io, line, line + 1)) {
6326 chunk = NULL;
6328 } else {
6329 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6330 !stage_diff_write(&io, chunk, view->line + view->lines))
6331 chunk = NULL;
6334 io_done(&io);
6335 io_run_bg(update_index_argv);
6337 return chunk ? TRUE : FALSE;
6340 static bool
6341 stage_update(struct view *view, struct line *line, bool single)
6343 struct line *chunk = NULL;
6345 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6346 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6348 if (chunk) {
6349 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6350 report("Failed to apply chunk");
6351 return FALSE;
6354 } else if (!stage_status.status) {
6355 view = view->parent;
6357 for (line = view->line; line < view->line + view->lines; line++)
6358 if (line->type == stage_line_type)
6359 break;
6361 if (!status_update_files(view, line + 1)) {
6362 report("Failed to update files");
6363 return FALSE;
6366 } else if (!status_update_file(&stage_status, stage_line_type)) {
6367 report("Failed to update file");
6368 return FALSE;
6371 return TRUE;
6374 static bool
6375 stage_revert(struct view *view, struct line *line)
6377 struct line *chunk = NULL;
6379 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6380 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6382 if (chunk) {
6383 if (!prompt_yesno("Are you sure you want to revert changes?"))
6384 return FALSE;
6386 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6387 report("Failed to revert chunk");
6388 return FALSE;
6390 return TRUE;
6392 } else {
6393 return status_revert(stage_status.status ? &stage_status : NULL,
6394 stage_line_type, FALSE);
6399 static void
6400 stage_next(struct view *view, struct line *line)
6402 struct stage_state *state = view->private;
6403 int i;
6405 if (!state->chunks) {
6406 for (line = view->line; line < view->line + view->lines; line++) {
6407 if (line->type != LINE_DIFF_CHUNK)
6408 continue;
6410 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6411 report("Allocation failure");
6412 return;
6415 state->chunk[state->chunks++] = line - view->line;
6419 for (i = 0; i < state->chunks; i++) {
6420 if (state->chunk[i] > view->pos.lineno) {
6421 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
6422 report("Chunk %d of %d", i + 1, state->chunks);
6423 return;
6427 report("No next chunk found");
6430 static enum request
6431 stage_request(struct view *view, enum request request, struct line *line)
6433 switch (request) {
6434 case REQ_STATUS_UPDATE:
6435 if (!stage_update(view, line, FALSE))
6436 return REQ_NONE;
6437 break;
6439 case REQ_STATUS_REVERT:
6440 if (!stage_revert(view, line))
6441 return REQ_NONE;
6442 break;
6444 case REQ_STAGE_UPDATE_LINE:
6445 if (stage_line_type == LINE_STAT_UNTRACKED ||
6446 stage_status.status == 'A') {
6447 report("Staging single lines is not supported for new files");
6448 return REQ_NONE;
6450 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6451 report("Please select a change to stage");
6452 return REQ_NONE;
6454 if (!stage_update(view, line, TRUE))
6455 return REQ_NONE;
6456 break;
6458 case REQ_STAGE_NEXT:
6459 if (stage_line_type == LINE_STAT_UNTRACKED) {
6460 report("File is untracked; press %s to add",
6461 get_view_key(view, REQ_STATUS_UPDATE));
6462 return REQ_NONE;
6464 stage_next(view, line);
6465 return REQ_NONE;
6467 case REQ_EDIT:
6468 if (!stage_status.new.name[0])
6469 return request;
6470 if (stage_status.status == 'D') {
6471 report("File has been deleted.");
6472 return REQ_NONE;
6475 open_editor(stage_status.new.name);
6476 break;
6478 case REQ_REFRESH:
6479 /* Reload everything ... */
6480 break;
6482 case REQ_VIEW_BLAME:
6483 if (stage_status.new.name[0]) {
6484 string_copy(opt_file, stage_status.new.name);
6485 opt_ref[0] = 0;
6487 return request;
6489 case REQ_ENTER:
6490 return diff_common_enter(view, request, line);
6492 case REQ_DIFF_CONTEXT_UP:
6493 case REQ_DIFF_CONTEXT_DOWN:
6494 if (!update_diff_context(request))
6495 return REQ_NONE;
6496 break;
6498 default:
6499 return request;
6502 refresh_view(view->parent);
6504 /* Check whether the staged entry still exists, and close the
6505 * stage view if it doesn't. */
6506 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6507 status_restore(view->parent);
6508 return REQ_VIEW_CLOSE;
6511 refresh_view(view);
6513 return REQ_NONE;
6516 static bool
6517 stage_open(struct view *view, enum open_flags flags)
6519 static const char *no_head_diff_argv[] = {
6520 GIT_DIFF_STAGED_INITIAL(opt_diff_context_arg, opt_ignore_space_arg,
6521 stage_status.new.name)
6523 static const char *index_show_argv[] = {
6524 GIT_DIFF_STAGED(opt_diff_context_arg, opt_ignore_space_arg,
6525 stage_status.old.name, stage_status.new.name)
6527 static const char *files_show_argv[] = {
6528 GIT_DIFF_UNSTAGED(opt_diff_context_arg, opt_ignore_space_arg,
6529 stage_status.old.name, stage_status.new.name)
6531 /* Diffs for unmerged entries are empty when passing the new
6532 * path, so leave out the new path. */
6533 static const char *files_unmerged_argv[] = {
6534 "git", "diff-files", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6535 opt_diff_context_arg, opt_ignore_space_arg, "--",
6536 stage_status.old.name, NULL
6538 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6539 const char **argv = NULL;
6540 const char *info;
6542 view->encoding = NULL;
6544 switch (stage_line_type) {
6545 case LINE_STAT_STAGED:
6546 if (is_initial_commit()) {
6547 argv = no_head_diff_argv;
6548 } else {
6549 argv = index_show_argv;
6551 if (stage_status.status)
6552 info = "Staged changes to %s";
6553 else
6554 info = "Staged changes";
6555 break;
6557 case LINE_STAT_UNSTAGED:
6558 if (stage_status.status != 'U')
6559 argv = files_show_argv;
6560 else
6561 argv = files_unmerged_argv;
6562 if (stage_status.status)
6563 info = "Unstaged changes to %s";
6564 else
6565 info = "Unstaged changes";
6566 break;
6568 case LINE_STAT_UNTRACKED:
6569 info = "Untracked file %s";
6570 argv = file_argv;
6571 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
6572 break;
6574 case LINE_STAT_HEAD:
6575 default:
6576 die("line type %d not handled in switch", stage_line_type);
6579 string_format(view->ref, info, stage_status.new.name);
6580 view->vid[0] = 0;
6581 view->dir = opt_cdup;
6582 return argv_copy(&view->argv, argv)
6583 && begin_update(view, NULL, NULL, flags);
6586 static bool
6587 stage_read(struct view *view, char *data)
6589 struct stage_state *state = view->private;
6591 if (data && diff_common_read(view, data, &state->diff))
6592 return TRUE;
6594 return pager_read(view, data);
6597 static struct view_ops stage_ops = {
6598 "line",
6599 VIEW_DIFF_LIKE,
6600 sizeof(struct stage_state),
6601 stage_open,
6602 stage_read,
6603 diff_common_draw,
6604 stage_request,
6605 pager_grep,
6606 pager_select,
6611 * Revision graph
6614 static const enum line_type graph_colors[] = {
6615 LINE_PALETTE_0,
6616 LINE_PALETTE_1,
6617 LINE_PALETTE_2,
6618 LINE_PALETTE_3,
6619 LINE_PALETTE_4,
6620 LINE_PALETTE_5,
6621 LINE_PALETTE_6,
6624 static enum line_type get_graph_color(struct graph_symbol *symbol)
6626 if (symbol->commit)
6627 return LINE_GRAPH_COMMIT;
6628 assert(symbol->color < ARRAY_SIZE(graph_colors));
6629 return graph_colors[symbol->color];
6632 static bool
6633 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6635 const char *chars = graph_symbol_to_utf8(symbol);
6637 return draw_text(view, color, chars + !!first);
6640 static bool
6641 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6643 const char *chars = graph_symbol_to_ascii(symbol);
6645 return draw_text(view, color, chars + !!first);
6648 static bool
6649 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6651 const chtype *chars = graph_symbol_to_chtype(symbol);
6653 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6656 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6658 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6660 static const draw_graph_fn fns[] = {
6661 draw_graph_ascii,
6662 draw_graph_chtype,
6663 draw_graph_utf8
6665 draw_graph_fn fn = fns[opt_line_graphics];
6666 int i;
6668 for (i = 0; i < canvas->size; i++) {
6669 struct graph_symbol *symbol = &canvas->symbols[i];
6670 enum line_type color = get_graph_color(symbol);
6672 if (fn(view, symbol, color, i == 0))
6673 return TRUE;
6676 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6680 * Main view backend
6683 struct commit {
6684 char id[SIZEOF_REV]; /* SHA1 ID. */
6685 char title[128]; /* First line of the commit message. */
6686 const char *author; /* Author of the commit. */
6687 struct time time; /* Date from the author ident. */
6688 struct ref_list *refs; /* Repository references. */
6689 struct graph_canvas graph; /* Ancestry chain graphics. */
6692 static struct commit *
6693 main_add_commit(struct view *view, enum line_type type, const char *ids, bool is_boundary)
6695 struct graph *graph = view->private;
6696 struct commit *commit;
6698 commit = calloc(1, sizeof(struct commit));
6699 if (!commit)
6700 return NULL;
6702 string_copy_rev(commit->id, ids);
6703 commit->refs = get_ref_list(commit->id);
6704 add_line_data(view, commit, type);
6705 graph_add_commit(graph, &commit->graph, commit->id, ids, is_boundary);
6706 return commit;
6709 bool
6710 main_has_changes(const char *argv[])
6712 struct io io;
6714 if (!io_run(&io, IO_BG, NULL, argv, -1))
6715 return FALSE;
6716 io_done(&io);
6717 return io.status == 1;
6720 static void
6721 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
6723 char ids[SIZEOF_STR] = NULL_ID " ";
6724 struct graph *graph = view->private;
6725 struct commit *commit;
6726 struct timeval now;
6727 struct timezone tz;
6729 if (!parent)
6730 return;
6732 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
6734 commit = main_add_commit(view, type, ids, FALSE);
6735 if (!commit)
6736 return;
6738 if (!gettimeofday(&now, &tz)) {
6739 commit->time.tz = tz.tz_minuteswest * 60;
6740 commit->time.sec = now.tv_sec - commit->time.tz;
6743 commit->author = "";
6744 string_ncopy(commit->title, title, strlen(title));
6745 graph_render_parents(graph);
6748 static void
6749 main_add_changes_commits(struct view *view, const char *parent)
6751 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
6752 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
6753 const char *staged_parent = NULL_ID;
6754 const char *unstaged_parent = parent;
6756 if (!main_has_changes(unstaged_argv)) {
6757 unstaged_parent = NULL;
6758 staged_parent = parent;
6761 if (!main_has_changes(staged_argv)) {
6762 staged_parent = NULL;
6765 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
6766 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
6769 static bool
6770 main_open(struct view *view, enum open_flags flags)
6772 static const char *main_argv[] = {
6773 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw", "--parents",
6774 opt_commit_order_arg, "%(diffargs)", "%(revargs)",
6775 "--", "%(fileargs)", NULL
6778 return begin_update(view, NULL, main_argv, flags);
6781 static bool
6782 main_draw(struct view *view, struct line *line, unsigned int lineno)
6784 struct commit *commit = line->data;
6786 if (!commit->author)
6787 return FALSE;
6789 if (draw_lineno(view, lineno))
6790 return TRUE;
6792 if (draw_date(view, &commit->time))
6793 return TRUE;
6795 if (draw_author(view, commit->author))
6796 return TRUE;
6798 if (opt_rev_graph && draw_graph(view, &commit->graph))
6799 return TRUE;
6801 if (draw_refs(view, commit->refs))
6802 return TRUE;
6804 draw_text(view, LINE_DEFAULT, commit->title);
6805 return TRUE;
6808 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6809 static bool
6810 main_read(struct view *view, char *line)
6812 struct graph *graph = view->private;
6813 enum line_type type;
6814 struct commit *commit;
6815 static bool in_header;
6817 if (!line) {
6818 if (!view->lines && !view->prev)
6819 die("No revisions match the given arguments.");
6820 if (view->lines > 0) {
6821 commit = view->line[view->lines - 1].data;
6822 view->line[view->lines - 1].dirty = 1;
6823 if (!commit->author) {
6824 view->lines--;
6825 free(commit);
6829 done_graph(graph);
6830 return TRUE;
6833 type = get_line_type(line);
6834 if (type == LINE_COMMIT) {
6835 bool is_boundary;
6837 in_header = TRUE;
6838 line += STRING_SIZE("commit ");
6839 is_boundary = *line == '-';
6840 if (is_boundary)
6841 line++;
6843 if (opt_show_changes && opt_is_inside_work_tree && !view->lines)
6844 main_add_changes_commits(view, line);
6846 return main_add_commit(view, LINE_MAIN_COMMIT, line, is_boundary) != NULL;
6849 if (!view->lines)
6850 return TRUE;
6851 commit = view->line[view->lines - 1].data;
6853 /* Empty line separates the commit header from the log itself. */
6854 if (*line == '\0')
6855 in_header = FALSE;
6857 switch (type) {
6858 case LINE_PARENT:
6859 if (!graph->has_parents)
6860 graph_add_parent(graph, line + STRING_SIZE("parent "));
6861 break;
6863 case LINE_AUTHOR:
6864 parse_author_line(line + STRING_SIZE("author "),
6865 &commit->author, &commit->time);
6866 graph_render_parents(graph);
6867 break;
6869 default:
6870 /* Fill in the commit title if it has not already been set. */
6871 if (commit->title[0])
6872 break;
6874 /* Skip lines in the commit header. */
6875 if (in_header)
6876 break;
6878 /* Require titles to start with a non-space character at the
6879 * offset used by git log. */
6880 if (strncmp(line, " ", 4))
6881 break;
6882 line += 4;
6883 /* Well, if the title starts with a whitespace character,
6884 * try to be forgiving. Otherwise we end up with no title. */
6885 while (isspace(*line))
6886 line++;
6887 if (*line == '\0')
6888 break;
6889 /* FIXME: More graceful handling of titles; append "..." to
6890 * shortened titles, etc. */
6892 string_expand(commit->title, sizeof(commit->title), line, 1);
6893 view->line[view->lines - 1].dirty = 1;
6896 return TRUE;
6899 static enum request
6900 main_request(struct view *view, enum request request, struct line *line)
6902 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6904 switch (request) {
6905 case REQ_NEXT:
6906 case REQ_PREVIOUS:
6907 if (view_is_displayed(view) && display[0] != view)
6908 return request;
6909 /* Do not pass navigation requests to the branch view
6910 * when the main view is maximized. (GH #38) */
6911 move_view(view, request);
6912 break;
6914 case REQ_ENTER:
6915 if (view_is_displayed(view) && display[0] != view)
6916 maximize_view(view, TRUE);
6918 if (line->type == LINE_STAT_UNSTAGED
6919 || line->type == LINE_STAT_STAGED) {
6920 struct view *diff = VIEW(REQ_VIEW_DIFF);
6921 const char *diff_staged_argv[] = {
6922 GIT_DIFF_STAGED(opt_diff_context_arg,
6923 opt_ignore_space_arg, NULL, NULL)
6925 const char *diff_unstaged_argv[] = {
6926 GIT_DIFF_UNSTAGED(opt_diff_context_arg,
6927 opt_ignore_space_arg, NULL, NULL)
6929 const char **diff_argv = line->type == LINE_STAT_STAGED
6930 ? diff_staged_argv : diff_unstaged_argv;
6932 open_argv(view, diff, diff_argv, NULL, flags);
6933 break;
6936 open_view(view, REQ_VIEW_DIFF, flags);
6937 break;
6938 case REQ_REFRESH:
6939 load_refs();
6940 refresh_view(view);
6941 break;
6943 case REQ_JUMP_COMMIT:
6945 int lineno;
6947 for (lineno = 0; lineno < view->lines; lineno++) {
6948 struct commit *commit = view->line[lineno].data;
6950 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
6951 select_view_line(view, lineno);
6952 report("");
6953 return REQ_NONE;
6957 report("Unable to find commit '%s'", opt_search);
6958 break;
6960 default:
6961 return request;
6964 return REQ_NONE;
6967 static bool
6968 grep_refs(struct ref_list *list, regex_t *regex)
6970 regmatch_t pmatch;
6971 size_t i;
6973 if (!opt_show_refs || !list)
6974 return FALSE;
6976 for (i = 0; i < list->size; i++) {
6977 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
6978 return TRUE;
6981 return FALSE;
6984 static bool
6985 main_grep(struct view *view, struct line *line)
6987 struct commit *commit = line->data;
6988 const char *text[] = {
6989 commit->title,
6990 mkauthor(commit->author, opt_author_cols, opt_author),
6991 mkdate(&commit->time, opt_date),
6992 NULL
6995 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
6998 static void
6999 main_select(struct view *view, struct line *line)
7001 struct commit *commit = line->data;
7003 string_copy_rev(view->ref, commit->id);
7004 string_copy_rev(ref_commit, view->ref);
7007 static struct view_ops main_ops = {
7008 "commit",
7009 VIEW_NO_FLAGS,
7010 sizeof(struct graph),
7011 main_open,
7012 main_read,
7013 main_draw,
7014 main_request,
7015 main_grep,
7016 main_select,
7021 * Status management
7024 /* Whether or not the curses interface has been initialized. */
7025 static bool cursed = FALSE;
7027 /* Terminal hacks and workarounds. */
7028 static bool use_scroll_redrawwin;
7029 static bool use_scroll_status_wclear;
7031 /* The status window is used for polling keystrokes. */
7032 static WINDOW *status_win;
7034 /* Reading from the prompt? */
7035 static bool input_mode = FALSE;
7037 static bool status_empty = FALSE;
7039 /* Update status and title window. */
7040 static void
7041 report(const char *msg, ...)
7043 struct view *view = display[current_view];
7045 if (input_mode)
7046 return;
7048 if (!view) {
7049 char buf[SIZEOF_STR];
7050 int retval;
7052 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
7053 die("%s", buf);
7056 if (!status_empty || *msg) {
7057 va_list args;
7059 va_start(args, msg);
7061 wmove(status_win, 0, 0);
7062 if (view->has_scrolled && use_scroll_status_wclear)
7063 wclear(status_win);
7064 if (*msg) {
7065 vwprintw(status_win, msg, args);
7066 status_empty = FALSE;
7067 } else {
7068 status_empty = TRUE;
7070 wclrtoeol(status_win);
7071 wnoutrefresh(status_win);
7073 va_end(args);
7076 update_view_title(view);
7079 static void
7080 init_display(void)
7082 const char *term;
7083 int x, y;
7085 /* Initialize the curses library */
7086 if (isatty(STDIN_FILENO)) {
7087 cursed = !!initscr();
7088 opt_tty = stdin;
7089 } else {
7090 /* Leave stdin and stdout alone when acting as a pager. */
7091 opt_tty = fopen("/dev/tty", "r+");
7092 if (!opt_tty)
7093 die("Failed to open /dev/tty");
7094 cursed = !!newterm(NULL, opt_tty, opt_tty);
7097 if (!cursed)
7098 die("Failed to initialize curses");
7100 nonl(); /* Disable conversion and detect newlines from input. */
7101 cbreak(); /* Take input chars one at a time, no wait for \n */
7102 noecho(); /* Don't echo input */
7103 leaveok(stdscr, FALSE);
7105 if (has_colors())
7106 init_colors();
7108 getmaxyx(stdscr, y, x);
7109 status_win = newwin(1, x, y - 1, 0);
7110 if (!status_win)
7111 die("Failed to create status window");
7113 /* Enable keyboard mapping */
7114 keypad(status_win, TRUE);
7115 wbkgdset(status_win, get_line_attr(LINE_STATUS));
7117 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
7118 set_tabsize(opt_tab_size);
7119 #else
7120 TABSIZE = opt_tab_size;
7121 #endif
7123 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
7124 if (term && !strcmp(term, "gnome-terminal")) {
7125 /* In the gnome-terminal-emulator, the message from
7126 * scrolling up one line when impossible followed by
7127 * scrolling down one line causes corruption of the
7128 * status line. This is fixed by calling wclear. */
7129 use_scroll_status_wclear = TRUE;
7130 use_scroll_redrawwin = FALSE;
7132 } else if (term && !strcmp(term, "xrvt-xpm")) {
7133 /* No problems with full optimizations in xrvt-(unicode)
7134 * and aterm. */
7135 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
7137 } else {
7138 /* When scrolling in (u)xterm the last line in the
7139 * scrolling direction will update slowly. */
7140 use_scroll_redrawwin = TRUE;
7141 use_scroll_status_wclear = FALSE;
7145 static int
7146 get_input(int prompt_position)
7148 struct view *view;
7149 int i, key, cursor_y, cursor_x;
7151 if (prompt_position)
7152 input_mode = TRUE;
7154 while (TRUE) {
7155 bool loading = FALSE;
7157 foreach_view (view, i) {
7158 update_view(view);
7159 if (view_is_displayed(view) && view->has_scrolled &&
7160 use_scroll_redrawwin)
7161 redrawwin(view->win);
7162 view->has_scrolled = FALSE;
7163 if (view->pipe)
7164 loading = TRUE;
7167 /* Update the cursor position. */
7168 if (prompt_position) {
7169 getbegyx(status_win, cursor_y, cursor_x);
7170 cursor_x = prompt_position;
7171 } else {
7172 view = display[current_view];
7173 getbegyx(view->win, cursor_y, cursor_x);
7174 cursor_x = view->width - 1;
7175 cursor_y += view->pos.lineno - view->pos.offset;
7177 setsyx(cursor_y, cursor_x);
7179 /* Refresh, accept single keystroke of input */
7180 doupdate();
7181 nodelay(status_win, loading);
7182 key = wgetch(status_win);
7184 /* wgetch() with nodelay() enabled returns ERR when
7185 * there's no input. */
7186 if (key == ERR) {
7188 } else if (key == KEY_RESIZE) {
7189 int height, width;
7191 getmaxyx(stdscr, height, width);
7193 wresize(status_win, 1, width);
7194 mvwin(status_win, height - 1, 0);
7195 wnoutrefresh(status_win);
7196 resize_display();
7197 redraw_display(TRUE);
7199 } else {
7200 input_mode = FALSE;
7201 if (key == erasechar())
7202 key = KEY_BACKSPACE;
7203 return key;
7208 static char *
7209 prompt_input(const char *prompt, input_handler handler, void *data)
7211 enum input_status status = INPUT_OK;
7212 static char buf[SIZEOF_STR];
7213 size_t pos = 0;
7215 buf[pos] = 0;
7217 while (status == INPUT_OK || status == INPUT_SKIP) {
7218 int key;
7220 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
7221 wclrtoeol(status_win);
7223 key = get_input(pos + 1);
7224 switch (key) {
7225 case KEY_RETURN:
7226 case KEY_ENTER:
7227 case '\n':
7228 status = pos ? INPUT_STOP : INPUT_CANCEL;
7229 break;
7231 case KEY_BACKSPACE:
7232 if (pos > 0)
7233 buf[--pos] = 0;
7234 else
7235 status = INPUT_CANCEL;
7236 break;
7238 case KEY_ESC:
7239 status = INPUT_CANCEL;
7240 break;
7242 default:
7243 if (pos >= sizeof(buf)) {
7244 report("Input string too long");
7245 return NULL;
7248 status = handler(data, buf, key);
7249 if (status == INPUT_OK)
7250 buf[pos++] = (char) key;
7254 /* Clear the status window */
7255 status_empty = FALSE;
7256 report("");
7258 if (status == INPUT_CANCEL)
7259 return NULL;
7261 buf[pos++] = 0;
7263 return buf;
7266 static enum input_status
7267 prompt_yesno_handler(void *data, char *buf, int c)
7269 if (c == 'y' || c == 'Y')
7270 return INPUT_STOP;
7271 if (c == 'n' || c == 'N')
7272 return INPUT_CANCEL;
7273 return INPUT_SKIP;
7276 static bool
7277 prompt_yesno(const char *prompt)
7279 char prompt2[SIZEOF_STR];
7281 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7282 return FALSE;
7284 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7287 static enum input_status
7288 read_prompt_handler(void *data, char *buf, int c)
7290 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7293 static char *
7294 read_prompt(const char *prompt)
7296 return prompt_input(prompt, read_prompt_handler, NULL);
7299 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7301 enum input_status status = INPUT_OK;
7302 int size = 0;
7304 while (items[size].text)
7305 size++;
7307 while (status == INPUT_OK) {
7308 const struct menu_item *item = &items[*selected];
7309 int key;
7310 int i;
7312 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7313 prompt, *selected + 1, size);
7314 if (item->hotkey)
7315 wprintw(status_win, "[%c] ", (char) item->hotkey);
7316 wprintw(status_win, "%s", item->text);
7317 wclrtoeol(status_win);
7319 key = get_input(COLS - 1);
7320 switch (key) {
7321 case KEY_RETURN:
7322 case KEY_ENTER:
7323 case '\n':
7324 status = INPUT_STOP;
7325 break;
7327 case KEY_LEFT:
7328 case KEY_UP:
7329 *selected = *selected - 1;
7330 if (*selected < 0)
7331 *selected = size - 1;
7332 break;
7334 case KEY_RIGHT:
7335 case KEY_DOWN:
7336 *selected = (*selected + 1) % size;
7337 break;
7339 case KEY_ESC:
7340 status = INPUT_CANCEL;
7341 break;
7343 default:
7344 for (i = 0; items[i].text; i++)
7345 if (items[i].hotkey == key) {
7346 *selected = i;
7347 status = INPUT_STOP;
7348 break;
7353 /* Clear the status window */
7354 status_empty = FALSE;
7355 report("");
7357 return status != INPUT_CANCEL;
7361 * Repository properties
7364 static struct ref **refs = NULL;
7365 static size_t refs_size = 0;
7366 static struct ref *refs_head = NULL;
7368 static struct ref_list **ref_lists = NULL;
7369 static size_t ref_lists_size = 0;
7371 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
7372 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
7373 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
7375 static int
7376 compare_refs(const void *ref1_, const void *ref2_)
7378 const struct ref *ref1 = *(const struct ref **)ref1_;
7379 const struct ref *ref2 = *(const struct ref **)ref2_;
7381 if (ref1->tag != ref2->tag)
7382 return ref2->tag - ref1->tag;
7383 if (ref1->ltag != ref2->ltag)
7384 return ref2->ltag - ref1->ltag;
7385 if (ref1->head != ref2->head)
7386 return ref2->head - ref1->head;
7387 if (ref1->tracked != ref2->tracked)
7388 return ref2->tracked - ref1->tracked;
7389 if (ref1->replace != ref2->replace)
7390 return ref2->replace - ref1->replace;
7391 /* Order remotes last. */
7392 if (ref1->remote != ref2->remote)
7393 return ref1->remote - ref2->remote;
7394 return strcmp(ref1->name, ref2->name);
7397 static void
7398 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
7400 size_t i;
7402 for (i = 0; i < refs_size; i++)
7403 if (!visitor(data, refs[i]))
7404 break;
7407 static struct ref *
7408 get_ref_head()
7410 return refs_head;
7413 static struct ref_list *
7414 get_ref_list(const char *id)
7416 struct ref_list *list;
7417 size_t i;
7419 for (i = 0; i < ref_lists_size; i++)
7420 if (!strcmp(id, ref_lists[i]->id))
7421 return ref_lists[i];
7423 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
7424 return NULL;
7425 list = calloc(1, sizeof(*list));
7426 if (!list)
7427 return NULL;
7429 for (i = 0; i < refs_size; i++) {
7430 if (!strcmp(id, refs[i]->id) &&
7431 realloc_refs_list(&list->refs, list->size, 1))
7432 list->refs[list->size++] = refs[i];
7435 if (!list->refs) {
7436 free(list);
7437 return NULL;
7440 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
7441 ref_lists[ref_lists_size++] = list;
7442 return list;
7445 static int
7446 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
7448 struct ref *ref = NULL;
7449 bool tag = FALSE;
7450 bool ltag = FALSE;
7451 bool remote = FALSE;
7452 bool replace = FALSE;
7453 bool tracked = FALSE;
7454 bool head = FALSE;
7455 int pos;
7457 if (!prefixcmp(name, "refs/tags/")) {
7458 if (!suffixcmp(name, namelen, "^{}")) {
7459 namelen -= 3;
7460 name[namelen] = 0;
7461 } else {
7462 ltag = TRUE;
7465 tag = TRUE;
7466 namelen -= STRING_SIZE("refs/tags/");
7467 name += STRING_SIZE("refs/tags/");
7469 } else if (!prefixcmp(name, "refs/remotes/")) {
7470 remote = TRUE;
7471 namelen -= STRING_SIZE("refs/remotes/");
7472 name += STRING_SIZE("refs/remotes/");
7473 tracked = !strcmp(opt_remote, name);
7475 } else if (!prefixcmp(name, "refs/replace/")) {
7476 replace = TRUE;
7477 id = name + strlen("refs/replace/");
7478 idlen = namelen - strlen("refs/replace/");
7479 name = "replaced";
7480 namelen = strlen(name);
7482 } else if (!prefixcmp(name, "refs/heads/")) {
7483 namelen -= STRING_SIZE("refs/heads/");
7484 name += STRING_SIZE("refs/heads/");
7485 if (strlen(opt_head) == namelen
7486 && !strncmp(opt_head, name, namelen))
7487 return OK;
7489 } else if (!strcmp(name, "HEAD")) {
7490 head = TRUE;
7491 if (*opt_head) {
7492 namelen = strlen(opt_head);
7493 name = opt_head;
7497 /* If we are reloading or it's an annotated tag, replace the
7498 * previous SHA1 with the resolved commit id; relies on the fact
7499 * git-ls-remote lists the commit id of an annotated tag right
7500 * before the commit id it points to. */
7501 for (pos = 0; pos < refs_size; pos++) {
7502 int cmp = replace ? strcmp(id, refs[pos]->id) : strcmp(name, refs[pos]->name);
7504 if (!cmp) {
7505 ref = refs[pos];
7506 break;
7510 if (!ref) {
7511 if (!realloc_refs(&refs, refs_size, 1))
7512 return ERR;
7513 ref = calloc(1, sizeof(*ref) + namelen);
7514 if (!ref)
7515 return ERR;
7516 refs[refs_size++] = ref;
7517 strncpy(ref->name, name, namelen);
7520 ref->head = head;
7521 ref->tag = tag;
7522 ref->ltag = ltag;
7523 ref->remote = remote;
7524 ref->replace = replace;
7525 ref->tracked = tracked;
7526 string_copy_rev(ref->id, id);
7528 if (head)
7529 refs_head = ref;
7530 return OK;
7533 static int
7534 load_refs(void)
7536 const char *head_argv[] = {
7537 "git", "symbolic-ref", "HEAD", NULL
7539 static const char *ls_remote_argv[SIZEOF_ARG] = {
7540 "git", "ls-remote", opt_git_dir, NULL
7542 static bool init = FALSE;
7543 size_t i;
7545 if (!init) {
7546 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
7547 die("TIG_LS_REMOTE contains too many arguments");
7548 init = TRUE;
7551 if (!*opt_git_dir)
7552 return OK;
7554 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
7555 !prefixcmp(opt_head, "refs/heads/")) {
7556 char *offset = opt_head + STRING_SIZE("refs/heads/");
7558 memmove(opt_head, offset, strlen(offset) + 1);
7561 refs_head = NULL;
7562 for (i = 0; i < refs_size; i++)
7563 refs[i]->id[0] = 0;
7565 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
7566 return ERR;
7568 /* Update the ref lists to reflect changes. */
7569 for (i = 0; i < ref_lists_size; i++) {
7570 struct ref_list *list = ref_lists[i];
7571 size_t old, new;
7573 for (old = new = 0; old < list->size; old++)
7574 if (!strcmp(list->id, list->refs[old]->id))
7575 list->refs[new++] = list->refs[old];
7576 list->size = new;
7579 qsort(refs, refs_size, sizeof(*refs), compare_refs);
7581 return OK;
7584 static void
7585 set_remote_branch(const char *name, const char *value, size_t valuelen)
7587 if (!strcmp(name, ".remote")) {
7588 string_ncopy(opt_remote, value, valuelen);
7590 } else if (*opt_remote && !strcmp(name, ".merge")) {
7591 size_t from = strlen(opt_remote);
7593 if (!prefixcmp(value, "refs/heads/"))
7594 value += STRING_SIZE("refs/heads/");
7596 if (!string_format_from(opt_remote, &from, "/%s", value))
7597 opt_remote[0] = 0;
7601 static void
7602 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7604 const char *argv[SIZEOF_ARG] = { name, "=" };
7605 int argc = 1 + (cmd == option_set_command);
7606 enum option_code error;
7608 if (!argv_from_string(argv, &argc, value))
7609 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7610 else
7611 error = cmd(argc, argv);
7613 if (error != OPT_OK)
7614 warn("Option 'tig.%s': %s", name, option_errors[error]);
7617 static bool
7618 set_environment_variable(const char *name, const char *value)
7620 size_t len = strlen(name) + 1 + strlen(value) + 1;
7621 char *env = malloc(len);
7623 if (env &&
7624 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7625 putenv(env) == 0)
7626 return TRUE;
7627 free(env);
7628 return FALSE;
7631 static void
7632 set_work_tree(const char *value)
7634 char cwd[SIZEOF_STR];
7636 if (!getcwd(cwd, sizeof(cwd)))
7637 die("Failed to get cwd path: %s", strerror(errno));
7638 if (chdir(opt_git_dir) < 0)
7639 die("Failed to chdir(%s): %s", strerror(errno));
7640 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7641 die("Failed to get git path: %s", strerror(errno));
7642 if (chdir(cwd) < 0)
7643 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7644 if (chdir(value) < 0)
7645 die("Failed to chdir(%s): %s", value, strerror(errno));
7646 if (!getcwd(cwd, sizeof(cwd)))
7647 die("Failed to get cwd path: %s", strerror(errno));
7648 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7649 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7650 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7651 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7652 opt_is_inside_work_tree = TRUE;
7655 static void
7656 parse_git_color_option(enum line_type type, char *value)
7658 struct line_info *info = &line_info[type];
7659 const char *argv[SIZEOF_ARG];
7660 int argc = 0;
7661 bool first_color = TRUE;
7662 int i;
7664 if (!argv_from_string(argv, &argc, value))
7665 return;
7667 info->fg = COLOR_DEFAULT;
7668 info->bg = COLOR_DEFAULT;
7669 info->attr = 0;
7671 for (i = 0; i < argc; i++) {
7672 int attr = 0;
7674 if (set_attribute(&attr, argv[i])) {
7675 info->attr |= attr;
7677 } else if (set_color(&attr, argv[i])) {
7678 if (first_color)
7679 info->fg = attr;
7680 else
7681 info->bg = attr;
7682 first_color = FALSE;
7687 static void
7688 set_git_color_option(const char *name, char *value)
7690 static const struct enum_map color_option_map[] = {
7691 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
7692 ENUM_MAP("branch.local", LINE_MAIN_REF),
7693 ENUM_MAP("branch.plain", LINE_MAIN_REF),
7694 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
7696 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
7697 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
7698 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
7699 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
7700 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
7701 ENUM_MAP("diff.old", LINE_DIFF_DEL),
7702 ENUM_MAP("diff.new", LINE_DIFF_ADD),
7704 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
7706 ENUM_MAP("status.branch", LINE_STAT_HEAD),
7707 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
7708 ENUM_MAP("status.added", LINE_STAT_STAGED),
7709 ENUM_MAP("status.updated", LINE_STAT_STAGED),
7710 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
7711 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
7714 int type = LINE_NONE;
7716 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
7717 parse_git_color_option(type, value);
7721 static int
7722 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7724 if (!strcmp(name, "gui.encoding"))
7725 parse_encoding(&opt_encoding, value, TRUE);
7727 else if (!strcmp(name, "core.editor"))
7728 string_ncopy(opt_editor, value, valuelen);
7730 else if (!strcmp(name, "core.worktree"))
7731 set_work_tree(value);
7733 else if (!prefixcmp(name, "tig.color."))
7734 set_repo_config_option(name + 10, value, option_color_command);
7736 else if (!prefixcmp(name, "tig.bind."))
7737 set_repo_config_option(name + 9, value, option_bind_command);
7739 else if (!prefixcmp(name, "tig."))
7740 set_repo_config_option(name + 4, value, option_set_command);
7742 else if (!prefixcmp(name, "color."))
7743 set_git_color_option(name + STRING_SIZE("color."), value);
7745 else if (*opt_head && !prefixcmp(name, "branch.") &&
7746 !strncmp(name + 7, opt_head, strlen(opt_head)))
7747 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7749 return OK;
7752 static int
7753 load_git_config(void)
7755 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7757 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7760 static int
7761 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7763 if (!opt_git_dir[0]) {
7764 string_ncopy(opt_git_dir, name, namelen);
7766 } else if (opt_is_inside_work_tree == -1) {
7767 /* This can be 3 different values depending on the
7768 * version of git being used. If git-rev-parse does not
7769 * understand --is-inside-work-tree it will simply echo
7770 * the option else either "true" or "false" is printed.
7771 * Default to true for the unknown case. */
7772 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7774 } else if (*name == '.') {
7775 string_ncopy(opt_cdup, name, namelen);
7777 } else {
7778 string_ncopy(opt_prefix, name, namelen);
7781 return OK;
7784 static int
7785 load_repo_info(void)
7787 const char *rev_parse_argv[] = {
7788 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7789 "--show-cdup", "--show-prefix", NULL
7792 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7797 * Main
7800 static const char usage[] =
7801 "tig " TIG_VERSION " (" __DATE__ ")\n"
7802 "\n"
7803 "Usage: tig [options] [revs] [--] [paths]\n"
7804 " or: tig show [options] [revs] [--] [paths]\n"
7805 " or: tig blame [options] [rev] [--] path\n"
7806 " or: tig status\n"
7807 " or: tig < [git command output]\n"
7808 "\n"
7809 "Options:\n"
7810 " +<number> Select line <number> in the first view\n"
7811 " -v, --version Show version and exit\n"
7812 " -h, --help Show help message and exit";
7814 static void __NORETURN
7815 quit(int sig)
7817 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7818 if (cursed)
7819 endwin();
7820 exit(0);
7823 static void __NORETURN
7824 die(const char *err, ...)
7826 va_list args;
7828 endwin();
7830 va_start(args, err);
7831 fputs("tig: ", stderr);
7832 vfprintf(stderr, err, args);
7833 fputs("\n", stderr);
7834 va_end(args);
7836 exit(1);
7839 static void
7840 warn(const char *msg, ...)
7842 va_list args;
7844 va_start(args, msg);
7845 fputs("tig warning: ", stderr);
7846 vfprintf(stderr, msg, args);
7847 fputs("\n", stderr);
7848 va_end(args);
7851 static int
7852 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7854 const char ***filter_args = data;
7856 return argv_append(filter_args, name) ? OK : ERR;
7859 static void
7860 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7862 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7863 const char **all_argv = NULL;
7865 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7866 !argv_append_array(&all_argv, argv) ||
7867 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7868 die("Failed to split arguments");
7869 argv_free(all_argv);
7870 free(all_argv);
7873 static void
7874 filter_options(const char *argv[], bool blame)
7876 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7878 if (blame)
7879 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7880 else
7881 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7883 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7886 static enum request
7887 parse_options(int argc, const char *argv[])
7889 enum request request = REQ_VIEW_MAIN;
7890 const char *subcommand;
7891 bool seen_dashdash = FALSE;
7892 const char **filter_argv = NULL;
7893 int i;
7895 if (!isatty(STDIN_FILENO))
7896 return REQ_VIEW_PAGER;
7898 if (argc <= 1)
7899 return REQ_VIEW_MAIN;
7901 subcommand = argv[1];
7902 if (!strcmp(subcommand, "status")) {
7903 if (argc > 2)
7904 warn("ignoring arguments after `%s'", subcommand);
7905 return REQ_VIEW_STATUS;
7907 } else if (!strcmp(subcommand, "blame")) {
7908 request = REQ_VIEW_BLAME;
7910 } else if (!strcmp(subcommand, "show")) {
7911 request = REQ_VIEW_DIFF;
7913 } else {
7914 subcommand = NULL;
7917 for (i = 1 + !!subcommand; i < argc; i++) {
7918 const char *opt = argv[i];
7920 // stop parsing our options after -- and let rev-parse handle the rest
7921 if (!seen_dashdash) {
7922 if (!strcmp(opt, "--")) {
7923 seen_dashdash = TRUE;
7924 continue;
7926 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7927 printf("tig version %s\n", TIG_VERSION);
7928 quit(0);
7930 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7931 printf("%s\n", usage);
7932 quit(0);
7934 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7935 opt_lineno = atoi(opt + 1);
7936 continue;
7941 if (!argv_append(&filter_argv, opt))
7942 die("command too long");
7945 if (filter_argv)
7946 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7948 /* Finish validating and setting up blame options */
7949 if (request == REQ_VIEW_BLAME) {
7950 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7951 die("invalid number of options to blame\n\n%s", usage);
7953 if (opt_rev_argv) {
7954 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7957 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7960 return request;
7964 main(int argc, const char *argv[])
7966 const char *codeset = ENCODING_UTF8;
7967 enum request request = parse_options(argc, argv);
7968 struct view *view;
7970 signal(SIGINT, quit);
7971 signal(SIGPIPE, SIG_IGN);
7973 if (setlocale(LC_ALL, "")) {
7974 codeset = nl_langinfo(CODESET);
7977 if (load_repo_info() == ERR)
7978 die("Failed to load repo info.");
7980 if (load_options() == ERR)
7981 die("Failed to load user config.");
7983 if (load_git_config() == ERR)
7984 die("Failed to load repo config.");
7986 /* Require a git repository unless when running in pager mode. */
7987 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7988 die("Not a git repository");
7990 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
7991 char translit[SIZEOF_STR];
7993 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
7994 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
7995 else
7996 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
7997 if (opt_iconv_out == ICONV_NONE)
7998 die("Failed to initialize character set conversion");
8001 if (load_refs() == ERR)
8002 die("Failed to load refs.");
8004 init_display();
8006 while (view_driver(display[current_view], request)) {
8007 int key = get_input(0);
8009 view = display[current_view];
8010 request = get_keybinding(view->keymap, key);
8012 /* Some low-level request handling. This keeps access to
8013 * status_win restricted. */
8014 switch (request) {
8015 case REQ_NONE:
8016 report("Unknown key, press %s for help",
8017 get_view_key(view, REQ_VIEW_HELP));
8018 break;
8019 case REQ_PROMPT:
8021 char *cmd = read_prompt(":");
8023 if (cmd && string_isnumber(cmd)) {
8024 int lineno = view->pos.lineno + 1;
8026 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
8027 select_view_line(view, lineno - 1);
8028 report("");
8029 } else {
8030 report("Unable to parse '%s' as a line number", cmd);
8032 } else if (cmd && iscommit(cmd)) {
8033 string_ncopy(opt_search, cmd, strlen(cmd));
8035 request = view_request(view, REQ_JUMP_COMMIT);
8036 if (request == REQ_JUMP_COMMIT) {
8037 report("Jumping to commits is not supported by the '%s' view", view->name);
8040 } else if (cmd) {
8041 struct view *next = VIEW(REQ_VIEW_PAGER);
8042 const char *argv[SIZEOF_ARG] = { "git" };
8043 int argc = 1;
8045 /* When running random commands, initially show the
8046 * command in the title. However, it maybe later be
8047 * overwritten if a commit line is selected. */
8048 string_ncopy(next->ref, cmd, strlen(cmd));
8050 if (!argv_from_string(argv, &argc, cmd)) {
8051 report("Too many arguments");
8052 } else if (!format_argv(&next->argv, argv, FALSE)) {
8053 report("Argument formatting failed");
8054 } else {
8055 next->dir = NULL;
8056 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
8060 request = REQ_NONE;
8061 break;
8063 case REQ_SEARCH:
8064 case REQ_SEARCH_BACK:
8066 const char *prompt = request == REQ_SEARCH ? "/" : "?";
8067 char *search = read_prompt(prompt);
8069 if (search)
8070 string_ncopy(opt_search, search, strlen(search));
8071 else if (*opt_search)
8072 request = request == REQ_SEARCH ?
8073 REQ_FIND_NEXT :
8074 REQ_FIND_PREV;
8075 else
8076 request = REQ_NONE;
8077 break;
8079 default:
8080 break;
8084 quit(0);
8086 return 0;