Move keymap to view ops and change to use a struct
[tig.git] / tig.c
blobeff5acd67662a7c836a6864f70911d785a057682
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 dont_free:1;
789 unsigned int other:16;
791 void *data; /* User data */
796 * Keys
799 struct keybinding {
800 int alias;
801 enum request request;
804 static struct keybinding default_keybindings[] = {
805 /* View switching */
806 { 'm', REQ_VIEW_MAIN },
807 { 'd', REQ_VIEW_DIFF },
808 { 'l', REQ_VIEW_LOG },
809 { 't', REQ_VIEW_TREE },
810 { 'f', REQ_VIEW_BLOB },
811 { 'B', REQ_VIEW_BLAME },
812 { 'H', REQ_VIEW_BRANCH },
813 { 'p', REQ_VIEW_PAGER },
814 { 'h', REQ_VIEW_HELP },
815 { 'S', REQ_VIEW_STATUS },
816 { 'c', REQ_VIEW_STAGE },
818 /* View manipulation */
819 { 'q', REQ_VIEW_CLOSE },
820 { KEY_TAB, REQ_VIEW_NEXT },
821 { KEY_RETURN, REQ_ENTER },
822 { KEY_UP, REQ_PREVIOUS },
823 { KEY_CTL('P'), REQ_PREVIOUS },
824 { KEY_DOWN, REQ_NEXT },
825 { KEY_CTL('N'), REQ_NEXT },
826 { 'R', REQ_REFRESH },
827 { KEY_F(5), REQ_REFRESH },
828 { 'O', REQ_MAXIMIZE },
829 { ',', REQ_PARENT },
831 /* View specific */
832 { 'u', REQ_STATUS_UPDATE },
833 { '!', REQ_STATUS_REVERT },
834 { 'M', REQ_STATUS_MERGE },
835 { '1', REQ_STAGE_UPDATE_LINE },
836 { '@', REQ_STAGE_NEXT },
837 { '[', REQ_DIFF_CONTEXT_DOWN },
838 { ']', REQ_DIFF_CONTEXT_UP },
840 /* Cursor navigation */
841 { 'k', REQ_MOVE_UP },
842 { 'j', REQ_MOVE_DOWN },
843 { KEY_HOME, REQ_MOVE_FIRST_LINE },
844 { KEY_END, REQ_MOVE_LAST_LINE },
845 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
846 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
847 { ' ', REQ_MOVE_PAGE_DOWN },
848 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
849 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
850 { 'b', REQ_MOVE_PAGE_UP },
851 { '-', REQ_MOVE_PAGE_UP },
853 /* Scrolling */
854 { '|', REQ_SCROLL_FIRST_COL },
855 { KEY_LEFT, REQ_SCROLL_LEFT },
856 { KEY_RIGHT, REQ_SCROLL_RIGHT },
857 { KEY_IC, REQ_SCROLL_LINE_UP },
858 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
859 { KEY_DC, REQ_SCROLL_LINE_DOWN },
860 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
861 { 'w', REQ_SCROLL_PAGE_UP },
862 { 's', REQ_SCROLL_PAGE_DOWN },
864 /* Searching */
865 { '/', REQ_SEARCH },
866 { '?', REQ_SEARCH_BACK },
867 { 'n', REQ_FIND_NEXT },
868 { 'N', REQ_FIND_PREV },
870 /* Misc */
871 { 'Q', REQ_QUIT },
872 { 'z', REQ_STOP_LOADING },
873 { 'v', REQ_SHOW_VERSION },
874 { 'r', REQ_SCREEN_REDRAW },
875 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
876 { 'o', REQ_OPTIONS },
877 { '.', REQ_TOGGLE_LINENO },
878 { 'D', REQ_TOGGLE_DATE },
879 { 'A', REQ_TOGGLE_AUTHOR },
880 { 'g', REQ_TOGGLE_REV_GRAPH },
881 { '~', REQ_TOGGLE_GRAPHIC },
882 { '#', REQ_TOGGLE_FILENAME },
883 { 'F', REQ_TOGGLE_REFS },
884 { 'I', REQ_TOGGLE_SORT_ORDER },
885 { 'i', REQ_TOGGLE_SORT_FIELD },
886 { 'W', REQ_TOGGLE_IGNORE_SPACE },
887 { ':', REQ_PROMPT },
888 { 'e', REQ_EDIT },
891 struct keymap {
892 const char *name;
893 struct keymap *next;
894 struct keybinding *data;
895 size_t size;
896 bool hidden;
899 static struct keymap generic_keymap = { "generic" };
900 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
902 static struct keymap *keymaps = &generic_keymap;
904 static void
905 add_keymap(struct keymap *keymap)
907 keymap->next = keymaps;
908 keymaps = keymap;
911 static struct keymap *
912 get_keymap(const char *name)
914 struct keymap *keymap = keymaps;
916 while (keymap) {
917 if (!strcasecmp(keymap->name, name))
918 return keymap;
919 keymap = keymap->next;
922 return NULL;
926 static void
927 add_keybinding(struct keymap *table, enum request request, int key)
929 size_t i;
931 for (i = 0; i < table->size; i++) {
932 if (table->data[i].alias == key) {
933 table->data[i].request = request;
934 return;
938 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
939 if (!table->data)
940 die("Failed to allocate keybinding");
941 table->data[table->size].alias = key;
942 table->data[table->size++].request = request;
944 if (request == REQ_NONE && is_generic_keymap(table)) {
945 int i;
947 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
948 if (default_keybindings[i].alias == key)
949 default_keybindings[i].request = REQ_NONE;
953 /* Looks for a key binding first in the given map, then in the generic map, and
954 * lastly in the default keybindings. */
955 static enum request
956 get_keybinding(struct keymap *keymap, int key)
958 size_t i;
960 for (i = 0; i < keymap->size; i++)
961 if (keymap->data[i].alias == key)
962 return keymap->data[i].request;
964 for (i = 0; i < generic_keymap.size; i++)
965 if (generic_keymap.data[i].alias == key)
966 return generic_keymap.data[i].request;
968 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
969 if (default_keybindings[i].alias == key)
970 return default_keybindings[i].request;
972 return (enum request) key;
976 struct key {
977 const char *name;
978 int value;
981 static const struct key key_table[] = {
982 { "Enter", KEY_RETURN },
983 { "Space", ' ' },
984 { "Backspace", KEY_BACKSPACE },
985 { "Tab", KEY_TAB },
986 { "Escape", KEY_ESC },
987 { "Left", KEY_LEFT },
988 { "Right", KEY_RIGHT },
989 { "Up", KEY_UP },
990 { "Down", KEY_DOWN },
991 { "Insert", KEY_IC },
992 { "Delete", KEY_DC },
993 { "Hash", '#' },
994 { "Home", KEY_HOME },
995 { "End", KEY_END },
996 { "PageUp", KEY_PPAGE },
997 { "PageDown", KEY_NPAGE },
998 { "F1", KEY_F(1) },
999 { "F2", KEY_F(2) },
1000 { "F3", KEY_F(3) },
1001 { "F4", KEY_F(4) },
1002 { "F5", KEY_F(5) },
1003 { "F6", KEY_F(6) },
1004 { "F7", KEY_F(7) },
1005 { "F8", KEY_F(8) },
1006 { "F9", KEY_F(9) },
1007 { "F10", KEY_F(10) },
1008 { "F11", KEY_F(11) },
1009 { "F12", KEY_F(12) },
1012 static int
1013 get_key_value(const char *name)
1015 int i;
1017 for (i = 0; i < ARRAY_SIZE(key_table); i++)
1018 if (!strcasecmp(key_table[i].name, name))
1019 return key_table[i].value;
1021 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1022 return (int)name[1] & 0x1f;
1023 if (strlen(name) == 1 && isprint(*name))
1024 return (int) *name;
1025 return ERR;
1028 static const char *
1029 get_key_name(int key_value)
1031 static char key_char[] = "'X'\0";
1032 const char *seq = NULL;
1033 int key;
1035 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1036 if (key_table[key].value == key_value)
1037 seq = key_table[key].name;
1039 if (seq == NULL && key_value < 0x7f) {
1040 char *s = key_char + 1;
1042 if (key_value >= 0x20) {
1043 *s++ = key_value;
1044 } else {
1045 *s++ = '^';
1046 *s++ = 0x40 | (key_value & 0x1f);
1048 *s++ = '\'';
1049 *s++ = '\0';
1050 seq = key_char;
1053 return seq ? seq : "(no key)";
1056 static bool
1057 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1059 const char *sep = *pos > 0 ? ", " : "";
1060 const char *keyname = get_key_name(keybinding->alias);
1062 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1065 static bool
1066 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1067 struct keymap *keymap, bool all)
1069 int i;
1071 for (i = 0; i < keymap->size; i++) {
1072 if (keymap->data[i].request == request) {
1073 if (!append_key(buf, pos, &keymap->data[i]))
1074 return FALSE;
1075 if (!all)
1076 break;
1080 return TRUE;
1083 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1085 static const char *
1086 get_keys(struct keymap *keymap, enum request request, bool all)
1088 static char buf[BUFSIZ];
1089 size_t pos = 0;
1090 int i;
1092 buf[pos] = 0;
1094 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1095 return "Too many keybindings!";
1096 if (pos > 0 && !all)
1097 return buf;
1099 if (!is_generic_keymap(keymap)) {
1100 /* Only the generic keymap includes the default keybindings when
1101 * listing all keys. */
1102 if (all)
1103 return buf;
1105 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1106 return "Too many keybindings!";
1107 if (pos)
1108 return buf;
1111 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1112 if (default_keybindings[i].request == request) {
1113 if (!append_key(buf, &pos, &default_keybindings[i]))
1114 return "Too many keybindings!";
1115 if (!all)
1116 return buf;
1120 return buf;
1123 struct run_request {
1124 struct keymap *keymap;
1125 int key;
1126 const char **argv;
1127 bool silent;
1130 static struct run_request *run_request;
1131 static size_t run_requests;
1133 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1135 static bool
1136 add_run_request(struct keymap *keymap, int key, const char **argv, bool silent, bool force)
1138 struct run_request *req;
1140 if (!force && get_keybinding(keymap, key) != key)
1141 return TRUE;
1143 if (!realloc_run_requests(&run_request, run_requests, 1))
1144 return FALSE;
1146 if (!argv_copy(&run_request[run_requests].argv, argv))
1147 return FALSE;
1149 req = &run_request[run_requests++];
1150 req->silent = silent;
1151 req->keymap = keymap;
1152 req->key = key;
1154 add_keybinding(keymap, REQ_NONE + run_requests, key);
1155 return TRUE;
1158 static struct run_request *
1159 get_run_request(enum request request)
1161 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1162 return NULL;
1163 return &run_request[request - REQ_NONE - 1];
1166 static void
1167 add_builtin_run_requests(void)
1169 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1170 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1171 const char *commit[] = { "git", "commit", NULL };
1172 const char *gc[] = { "git", "gc", NULL };
1174 add_run_request(get_keymap("main"), 'C', cherry_pick, FALSE, FALSE);
1175 add_run_request(get_keymap("status"), 'C', commit, FALSE, FALSE);
1176 add_run_request(get_keymap("branch"), 'C', checkout, FALSE, FALSE);
1177 add_run_request(get_keymap("generic"), 'G', gc, FALSE, FALSE);
1181 * User config file handling.
1184 #define OPT_ERR_INFO \
1185 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1186 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1187 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1188 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1189 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1190 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1191 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1192 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1193 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1194 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1195 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1196 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1197 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1198 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1199 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1200 OPT_ERR_(OBSOLETE_VARIABLE_NAME, "Obsolete variable name"), \
1201 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1202 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1203 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1205 enum option_code {
1206 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1207 OPT_ERR_INFO
1208 #undef OPT_ERR_
1209 OPT_OK
1212 static const char *option_errors[] = {
1213 #define OPT_ERR_(name, msg) msg
1214 OPT_ERR_INFO
1215 #undef OPT_ERR_
1218 static const struct enum_map color_map[] = {
1219 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1220 COLOR_MAP(DEFAULT),
1221 COLOR_MAP(BLACK),
1222 COLOR_MAP(BLUE),
1223 COLOR_MAP(CYAN),
1224 COLOR_MAP(GREEN),
1225 COLOR_MAP(MAGENTA),
1226 COLOR_MAP(RED),
1227 COLOR_MAP(WHITE),
1228 COLOR_MAP(YELLOW),
1231 static const struct enum_map attr_map[] = {
1232 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1233 ATTR_MAP(NORMAL),
1234 ATTR_MAP(BLINK),
1235 ATTR_MAP(BOLD),
1236 ATTR_MAP(DIM),
1237 ATTR_MAP(REVERSE),
1238 ATTR_MAP(STANDOUT),
1239 ATTR_MAP(UNDERLINE),
1242 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1244 static enum option_code
1245 parse_step(double *opt, const char *arg)
1247 *opt = atoi(arg);
1248 if (!strchr(arg, '%'))
1249 return OPT_OK;
1251 /* "Shift down" so 100% and 1 does not conflict. */
1252 *opt = (*opt - 1) / 100;
1253 if (*opt >= 1.0) {
1254 *opt = 0.99;
1255 return OPT_ERR_INVALID_STEP_VALUE;
1257 if (*opt < 0.0) {
1258 *opt = 1;
1259 return OPT_ERR_INVALID_STEP_VALUE;
1261 return OPT_OK;
1264 static enum option_code
1265 parse_int(int *opt, const char *arg, int min, int max)
1267 int value = atoi(arg);
1269 if (min <= value && value <= max) {
1270 *opt = value;
1271 return OPT_OK;
1274 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1277 static bool
1278 set_color(int *color, const char *name)
1280 if (map_enum(color, color_map, name))
1281 return TRUE;
1282 if (!prefixcmp(name, "color"))
1283 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1284 return FALSE;
1287 /* Wants: object fgcolor bgcolor [attribute] */
1288 static enum option_code
1289 option_color_command(int argc, const char *argv[])
1291 struct line_info *info;
1293 if (argc < 3)
1294 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1296 if (*argv[0] == '"' || *argv[0] == '\'') {
1297 info = add_custom_color(argv[0]);
1298 } else {
1299 info = get_line_info(argv[0]);
1301 if (!info) {
1302 static const struct enum_map obsolete[] = {
1303 ENUM_MAP("main-delim", LINE_DELIMITER),
1304 ENUM_MAP("main-date", LINE_DATE),
1305 ENUM_MAP("main-author", LINE_AUTHOR),
1307 int index;
1309 if (!map_enum(&index, obsolete, argv[0]))
1310 return OPT_ERR_UNKNOWN_COLOR_NAME;
1311 info = &line_info[index];
1314 if (!set_color(&info->fg, argv[1]) ||
1315 !set_color(&info->bg, argv[2]))
1316 return OPT_ERR_UNKNOWN_COLOR;
1318 info->attr = 0;
1319 while (argc-- > 3) {
1320 int attr;
1322 if (!set_attribute(&attr, argv[argc]))
1323 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1324 info->attr |= attr;
1327 return OPT_OK;
1330 static enum option_code
1331 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1333 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1334 ? TRUE : FALSE;
1335 if (matched)
1336 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1337 return OPT_OK;
1340 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1342 static enum option_code
1343 parse_enum_do(unsigned int *opt, const char *arg,
1344 const struct enum_map *map, size_t map_size)
1346 bool is_true;
1348 assert(map_size > 1);
1350 if (map_enum_do(map, map_size, (int *) opt, arg))
1351 return OPT_OK;
1353 parse_bool(&is_true, arg);
1354 *opt = is_true ? map[1].value : map[0].value;
1355 return OPT_OK;
1358 #define parse_enum(opt, arg, map) \
1359 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1361 static enum option_code
1362 parse_string(char *opt, const char *arg, size_t optsize)
1364 int arglen = strlen(arg);
1366 switch (arg[0]) {
1367 case '\"':
1368 case '\'':
1369 if (arglen == 1 || arg[arglen - 1] != arg[0])
1370 return OPT_ERR_UNMATCHED_QUOTATION;
1371 arg += 1; arglen -= 2;
1372 default:
1373 string_ncopy_do(opt, optsize, arg, arglen);
1374 return OPT_OK;
1378 static enum option_code
1379 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1381 char buf[SIZEOF_STR];
1382 enum option_code code = parse_string(buf, arg, sizeof(buf));
1384 if (code == OPT_OK) {
1385 struct encoding *encoding = *encoding_ref;
1387 if (encoding && !priority)
1388 return code;
1389 encoding = encoding_open(buf);
1390 if (encoding)
1391 *encoding_ref = encoding;
1394 return code;
1397 static enum option_code
1398 parse_args(const char ***args, const char *argv[])
1400 if (*args == NULL && !argv_copy(args, argv))
1401 return OPT_ERR_OUT_OF_MEMORY;
1402 return OPT_OK;
1405 /* Wants: name = value */
1406 static enum option_code
1407 option_set_command(int argc, const char *argv[])
1409 if (argc < 3)
1410 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1412 if (strcmp(argv[1], "="))
1413 return OPT_ERR_NO_VALUE_ASSIGNED;
1415 if (!strcmp(argv[0], "blame-options"))
1416 return parse_args(&opt_blame_argv, argv + 2);
1418 if (argc != 3)
1419 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1421 if (!strcmp(argv[0], "show-author"))
1422 return parse_enum(&opt_author, argv[2], author_map);
1424 if (!strcmp(argv[0], "show-date"))
1425 return parse_enum(&opt_date, argv[2], date_map);
1427 if (!strcmp(argv[0], "show-rev-graph"))
1428 return parse_bool(&opt_rev_graph, argv[2]);
1430 if (!strcmp(argv[0], "show-refs"))
1431 return parse_bool(&opt_show_refs, argv[2]);
1433 if (!strcmp(argv[0], "show-changes"))
1434 return parse_bool(&opt_show_changes, argv[2]);
1436 if (!strcmp(argv[0], "show-notes")) {
1437 bool matched = FALSE;
1438 enum option_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1440 if (res == OPT_OK && matched) {
1441 update_notes_arg();
1442 return res;
1445 opt_notes = TRUE;
1446 strcpy(opt_notes_arg, "--show-notes=");
1447 res = parse_string(opt_notes_arg + 8, argv[2],
1448 sizeof(opt_notes_arg) - 8);
1449 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1450 opt_notes_arg[7] = '\0';
1451 return res;
1454 if (!strcmp(argv[0], "show-line-numbers"))
1455 return parse_bool(&opt_line_number, argv[2]);
1457 if (!strcmp(argv[0], "line-graphics"))
1458 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1460 if (!strcmp(argv[0], "line-number-interval"))
1461 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1463 if (!strcmp(argv[0], "author-width"))
1464 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1466 if (!strcmp(argv[0], "filename-width"))
1467 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1469 if (!strcmp(argv[0], "show-filename"))
1470 return parse_enum(&opt_filename, argv[2], filename_map);
1472 if (!strcmp(argv[0], "horizontal-scroll"))
1473 return parse_step(&opt_hscroll, argv[2]);
1475 if (!strcmp(argv[0], "split-view-height"))
1476 return parse_step(&opt_scale_split_view, argv[2]);
1478 if (!strcmp(argv[0], "tab-size"))
1479 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1481 if (!strcmp(argv[0], "diff-context")) {
1482 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1484 if (code == OPT_OK)
1485 update_diff_context_arg(opt_diff_context);
1486 return code;
1489 if (!strcmp(argv[0], "ignore-space")) {
1490 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1492 if (code == OPT_OK)
1493 update_ignore_space_arg();
1494 return code;
1497 if (!strcmp(argv[0], "commit-order")) {
1498 enum option_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1500 if (code == OPT_OK)
1501 update_commit_order_arg();
1502 return code;
1505 if (!strcmp(argv[0], "status-untracked-dirs"))
1506 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1508 if (!strcmp(argv[0], "use-git-colors"))
1509 return parse_bool(&opt_read_git_colors, argv[2]);
1511 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1514 /* Wants: mode request key */
1515 static enum option_code
1516 option_bind_command(int argc, const char *argv[])
1518 enum request request;
1519 struct keymap *keymap;
1520 int key;
1522 if (argc < 3)
1523 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1525 if (!(keymap = get_keymap(argv[0])))
1526 return OPT_ERR_UNKNOWN_KEY_MAP;
1528 key = get_key_value(argv[1]);
1529 if (key == ERR)
1530 return OPT_ERR_UNKNOWN_KEY;
1532 request = get_request(argv[2]);
1533 if (request == REQ_UNKNOWN) {
1534 static const struct enum_map obsolete[] = {
1535 ENUM_MAP("cherry-pick", REQ_NONE),
1536 ENUM_MAP("screen-resize", REQ_NONE),
1537 ENUM_MAP("tree-parent", REQ_PARENT),
1539 int alias;
1541 if (map_enum(&alias, obsolete, argv[2])) {
1542 if (alias != REQ_NONE)
1543 add_keybinding(keymap, alias, key);
1544 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1547 if (request == REQ_UNKNOWN && *argv[2]++ == '!') {
1548 bool silent = *argv[2] == '@';
1550 if (silent)
1551 argv[2]++;
1552 return add_run_request(keymap, key, argv + 2, silent, TRUE)
1553 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1555 if (request == REQ_UNKNOWN)
1556 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1558 add_keybinding(keymap, request, key);
1560 return OPT_OK;
1564 static enum option_code load_option_file(const char *path);
1566 static enum option_code
1567 option_source_command(int argc, const char *argv[])
1569 if (argc < 1)
1570 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1572 return load_option_file(argv[0]);
1575 static enum option_code
1576 set_option(const char *opt, char *value)
1578 const char *argv[SIZEOF_ARG];
1579 int argc = 0;
1581 if (!argv_from_string(argv, &argc, value))
1582 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1584 if (!strcmp(opt, "color"))
1585 return option_color_command(argc, argv);
1587 if (!strcmp(opt, "set"))
1588 return option_set_command(argc, argv);
1590 if (!strcmp(opt, "bind"))
1591 return option_bind_command(argc, argv);
1593 if (!strcmp(opt, "source"))
1594 return option_source_command(argc, argv);
1596 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1599 struct config_state {
1600 const char *path;
1601 int lineno;
1602 bool errors;
1605 static int
1606 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1608 struct config_state *config = data;
1609 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1611 config->lineno++;
1613 /* Check for comment markers, since read_properties() will
1614 * only ensure opt and value are split at first " \t". */
1615 optlen = strcspn(opt, "#");
1616 if (optlen == 0)
1617 return OK;
1619 if (opt[optlen] == 0) {
1620 /* Look for comment endings in the value. */
1621 size_t len = strcspn(value, "#");
1623 if (len < valuelen) {
1624 valuelen = len;
1625 value[valuelen] = 0;
1628 status = set_option(opt, value);
1631 if (status != OPT_OK) {
1632 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1633 option_errors[status], (int) optlen, opt);
1634 config->errors = TRUE;
1637 /* Always keep going if errors are encountered. */
1638 return OK;
1641 static enum option_code
1642 load_option_file(const char *path)
1644 struct config_state config = { path, 0, FALSE };
1645 struct io io;
1647 /* Do not read configuration from stdin if set to "" */
1648 if (!path || !strlen(path))
1649 return OPT_OK;
1651 /* It's OK that the file doesn't exist. */
1652 if (!io_open(&io, "%s", path))
1653 return OPT_ERR_FILE_DOES_NOT_EXIST;
1655 if (io_load(&io, " \t", read_option, &config) == ERR ||
1656 config.errors == TRUE)
1657 warn("Errors while loading %s.", path);
1658 return OPT_OK;
1661 static int
1662 load_options(void)
1664 const char *home = getenv("HOME");
1665 const char *tigrc_user = getenv("TIGRC_USER");
1666 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1667 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1668 char buf[SIZEOF_STR];
1670 if (!tigrc_system)
1671 tigrc_system = SYSCONFDIR "/tigrc";
1672 load_option_file(tigrc_system);
1674 if (!tigrc_user) {
1675 if (!home || !string_format(buf, "%s/.tigrc", home))
1676 return ERR;
1677 tigrc_user = buf;
1679 load_option_file(tigrc_user);
1681 /* Add _after_ loading config files to avoid adding run requests
1682 * that conflict with keybindings. */
1683 add_builtin_run_requests();
1685 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1686 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1687 int argc = 0;
1689 if (!string_format(buf, "%s", tig_diff_opts) ||
1690 !argv_from_string(diff_opts, &argc, buf))
1691 die("TIG_DIFF_OPTS contains too many arguments");
1692 else if (!argv_copy(&opt_diff_argv, diff_opts))
1693 die("Failed to format TIG_DIFF_OPTS arguments");
1696 return OK;
1701 * The viewer
1704 struct view;
1705 struct view_ops;
1707 /* The display array of active views and the index of the current view. */
1708 static struct view *display[2];
1709 static WINDOW *display_win[2];
1710 static WINDOW *display_title[2];
1711 static unsigned int current_view;
1713 #define foreach_displayed_view(view, i) \
1714 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1716 #define displayed_views() (display[1] != NULL ? 2 : 1)
1718 /* Current head and commit ID */
1719 static char ref_blob[SIZEOF_REF] = "";
1720 static char ref_commit[SIZEOF_REF] = "HEAD";
1721 static char ref_head[SIZEOF_REF] = "HEAD";
1722 static char ref_branch[SIZEOF_REF] = "";
1724 enum view_flag {
1725 VIEW_NO_FLAGS = 0,
1726 VIEW_ALWAYS_LINENO = 1 << 0,
1727 VIEW_CUSTOM_STATUS = 1 << 1,
1728 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1729 VIEW_ADD_PAGER_REFS = 1 << 3,
1730 VIEW_OPEN_DIFF = 1 << 4,
1731 VIEW_NO_REF = 1 << 5,
1732 VIEW_NO_GIT_DIR = 1 << 6,
1733 VIEW_DIFF_LIKE = 1 << 7,
1736 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1738 struct position {
1739 unsigned long offset; /* Offset of the window top */
1740 unsigned long col; /* Offset from the window side. */
1741 unsigned long lineno; /* Current line number */
1744 struct view {
1745 const char *name; /* View name */
1746 const char *id; /* Points to either of ref_{head,commit,blob} */
1748 struct view_ops *ops; /* View operations */
1750 char ref[SIZEOF_REF]; /* Hovered commit reference */
1751 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1753 int height, width; /* The width and height of the main window */
1754 WINDOW *win; /* The main window */
1756 /* Navigation */
1757 struct position pos; /* Current position. */
1758 struct position prev_pos; /* Previous position. */
1760 /* Searching */
1761 char grep[SIZEOF_STR]; /* Search string */
1762 regex_t *regex; /* Pre-compiled regexp */
1764 /* If non-NULL, points to the view that opened this view. If this view
1765 * is closed tig will switch back to the parent view. */
1766 struct view *parent;
1767 struct view *prev;
1769 /* Buffering */
1770 size_t lines; /* Total number of lines */
1771 struct line *line; /* Line index */
1772 unsigned int digits; /* Number of digits in the lines member. */
1774 /* Drawing */
1775 struct line *curline; /* Line currently being drawn. */
1776 enum line_type curtype; /* Attribute currently used for drawing. */
1777 unsigned long col; /* Column when drawing. */
1778 bool has_scrolled; /* View was scrolled. */
1780 /* Loading */
1781 const char **argv; /* Shell command arguments. */
1782 const char *dir; /* Directory from which to execute. */
1783 struct io io;
1784 struct io *pipe;
1785 time_t start_time;
1786 time_t update_secs;
1787 struct encoding *encoding;
1789 /* Private data */
1790 void *private;
1793 enum open_flags {
1794 OPEN_DEFAULT = 0, /* Use default view switching. */
1795 OPEN_SPLIT = 1, /* Split current view. */
1796 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1797 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1798 OPEN_PREPARED = 32, /* Open already prepared command. */
1799 OPEN_EXTRA = 64, /* Open extra data from command. */
1802 struct view_ops {
1803 /* What type of content being displayed. Used in the title bar. */
1804 const char *type;
1805 /* What keymap does this view have */
1806 struct keymap keymap;
1807 /* Flags to control the view behavior. */
1808 enum view_flag flags;
1809 /* Size of private data. */
1810 size_t private_size;
1811 /* Open and reads in all view content. */
1812 bool (*open)(struct view *view, enum open_flags flags);
1813 /* Read one line; updates view->line. */
1814 bool (*read)(struct view *view, char *data);
1815 /* Draw one line; @lineno must be < view->height. */
1816 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1817 /* Depending on view handle a special requests. */
1818 enum request (*request)(struct view *view, enum request request, struct line *line);
1819 /* Search for regexp in a line. */
1820 bool (*grep)(struct view *view, struct line *line);
1821 /* Select line */
1822 void (*select)(struct view *view, struct line *line);
1825 #define VIEW_OPS(id, name, ref) name##_ops
1826 static struct view_ops VIEW_INFO(VIEW_OPS);
1828 static struct view views[] = {
1829 #define VIEW_DATA(id, name, ref) \
1830 { #name, ref, &name##_ops }
1831 VIEW_INFO(VIEW_DATA)
1834 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1836 #define foreach_view(view, i) \
1837 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1839 #define view_is_displayed(view) \
1840 (view == display[0] || view == display[1])
1842 static enum request
1843 view_request(struct view *view, enum request request)
1845 if (!view || !view->lines)
1846 return request;
1847 return view->ops->request(view, request, &view->line[view->pos.lineno]);
1851 * View drawing.
1854 static inline void
1855 set_view_attr(struct view *view, enum line_type type)
1857 if (!view->curline->selected && view->curtype != type) {
1858 (void) wattrset(view->win, get_line_attr(type));
1859 wchgat(view->win, -1, 0, get_line_color(type), NULL);
1860 view->curtype = type;
1864 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
1866 static bool
1867 draw_chars(struct view *view, enum line_type type, const char *string,
1868 int max_len, bool use_tilde)
1870 static char out_buffer[BUFSIZ * 2];
1871 int len = 0;
1872 int col = 0;
1873 int trimmed = FALSE;
1874 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1876 if (max_len <= 0)
1877 return VIEW_MAX_LEN(view) <= 0;
1879 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1881 set_view_attr(view, type);
1882 if (len > 0) {
1883 if (opt_iconv_out != ICONV_NONE) {
1884 size_t inlen = len + 1;
1885 char *instr = calloc(1, inlen);
1886 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1887 if (!instr)
1888 return VIEW_MAX_LEN(view) <= 0;
1890 strncpy(instr, string, len);
1892 char *outbuf = out_buffer;
1893 size_t outlen = sizeof(out_buffer);
1895 size_t ret;
1897 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1898 if (ret != (size_t) -1) {
1899 string = out_buffer;
1900 len = sizeof(out_buffer) - outlen;
1902 free(instr);
1905 waddnstr(view->win, string, len);
1907 if (trimmed && use_tilde) {
1908 set_view_attr(view, LINE_DELIMITER);
1909 waddch(view->win, '~');
1910 col++;
1914 view->col += col;
1915 return VIEW_MAX_LEN(view) <= 0;
1918 static bool
1919 draw_space(struct view *view, enum line_type type, int max, int spaces)
1921 static char space[] = " ";
1923 spaces = MIN(max, spaces);
1925 while (spaces > 0) {
1926 int len = MIN(spaces, sizeof(space) - 1);
1928 if (draw_chars(view, type, space, len, FALSE))
1929 return TRUE;
1930 spaces -= len;
1933 return VIEW_MAX_LEN(view) <= 0;
1936 static bool
1937 draw_text(struct view *view, enum line_type type, const char *string)
1939 static char text[SIZEOF_STR];
1941 do {
1942 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1944 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1945 return TRUE;
1946 string += pos;
1947 } while (*string);
1949 return VIEW_MAX_LEN(view) <= 0;
1952 static bool
1953 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
1955 char text[SIZEOF_STR];
1956 int retval;
1958 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
1959 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
1962 static bool
1963 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1965 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
1966 int max = VIEW_MAX_LEN(view);
1967 int i;
1969 if (max < size)
1970 size = max;
1972 set_view_attr(view, type);
1973 /* Using waddch() instead of waddnstr() ensures that
1974 * they'll be rendered correctly for the cursor line. */
1975 for (i = skip; i < size; i++)
1976 waddch(view->win, graphic[i]);
1978 view->col += size;
1979 if (separator) {
1980 if (size < max && skip <= size)
1981 waddch(view->win, ' ');
1982 view->col++;
1985 return VIEW_MAX_LEN(view) <= 0;
1988 static bool
1989 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1991 int max = MIN(VIEW_MAX_LEN(view), len);
1992 int col = view->col;
1994 if (!text)
1995 return draw_space(view, type, max, max);
1997 return draw_chars(view, type, text, max - 1, trim)
1998 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2001 static bool
2002 draw_date(struct view *view, struct time *time)
2004 const char *date = mkdate(time, opt_date);
2005 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
2007 if (opt_date == DATE_NO)
2008 return FALSE;
2010 return draw_field(view, LINE_DATE, date, cols, FALSE);
2013 static bool
2014 draw_author(struct view *view, const char *author)
2016 bool trim = author_trim(opt_author_cols);
2017 const char *text = mkauthor(author, opt_author_cols, opt_author);
2019 if (opt_author == AUTHOR_NO)
2020 return FALSE;
2022 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
2025 static bool
2026 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2028 bool trim = filename && strlen(filename) >= opt_filename_cols;
2030 if (opt_filename == FILENAME_NO)
2031 return FALSE;
2033 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2034 return FALSE;
2036 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
2039 static bool
2040 draw_mode(struct view *view, mode_t mode)
2042 const char *str = mkmode(mode);
2044 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
2047 static bool
2048 draw_lineno(struct view *view, unsigned int lineno)
2050 char number[10];
2051 int digits3 = view->digits < 3 ? 3 : view->digits;
2052 int max = MIN(VIEW_MAX_LEN(view), digits3);
2053 char *text = NULL;
2054 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2056 if (!opt_line_number)
2057 return FALSE;
2059 lineno += view->pos.offset + 1;
2060 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2061 static char fmt[] = "%1ld";
2063 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2064 if (string_format(number, fmt, lineno))
2065 text = number;
2067 if (text)
2068 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2069 else
2070 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2071 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2074 static bool
2075 draw_refs(struct view *view, struct ref_list *refs)
2077 size_t i;
2079 if (!opt_show_refs || !refs)
2080 return FALSE;
2082 for (i = 0; i < refs->size; i++) {
2083 struct ref *ref = refs->refs[i];
2084 enum line_type type = get_line_type_from_ref(ref);
2086 if (draw_formatted(view, type, "[%s]", ref->name))
2087 return TRUE;
2089 if (draw_text(view, LINE_DEFAULT, " "))
2090 return TRUE;
2093 return FALSE;
2096 static bool
2097 draw_view_line(struct view *view, unsigned int lineno)
2099 struct line *line;
2100 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2102 assert(view_is_displayed(view));
2104 if (view->pos.offset + lineno >= view->lines)
2105 return FALSE;
2107 line = &view->line[view->pos.offset + lineno];
2109 wmove(view->win, lineno, 0);
2110 if (line->cleareol)
2111 wclrtoeol(view->win);
2112 view->col = 0;
2113 view->curline = line;
2114 view->curtype = LINE_NONE;
2115 line->selected = FALSE;
2116 line->dirty = line->cleareol = 0;
2118 if (selected) {
2119 set_view_attr(view, LINE_CURSOR);
2120 line->selected = TRUE;
2121 view->ops->select(view, line);
2124 return view->ops->draw(view, line, lineno);
2127 static void
2128 redraw_view_dirty(struct view *view)
2130 bool dirty = FALSE;
2131 int lineno;
2133 for (lineno = 0; lineno < view->height; lineno++) {
2134 if (view->pos.offset + lineno >= view->lines)
2135 break;
2136 if (!view->line[view->pos.offset + lineno].dirty)
2137 continue;
2138 dirty = TRUE;
2139 if (!draw_view_line(view, lineno))
2140 break;
2143 if (!dirty)
2144 return;
2145 wnoutrefresh(view->win);
2148 static void
2149 redraw_view_from(struct view *view, int lineno)
2151 assert(0 <= lineno && lineno < view->height);
2153 for (; lineno < view->height; lineno++) {
2154 if (!draw_view_line(view, lineno))
2155 break;
2158 wnoutrefresh(view->win);
2161 static void
2162 redraw_view(struct view *view)
2164 werase(view->win);
2165 redraw_view_from(view, 0);
2169 static void
2170 update_view_title(struct view *view)
2172 char buf[SIZEOF_STR];
2173 char state[SIZEOF_STR];
2174 size_t bufpos = 0, statelen = 0;
2175 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2177 assert(view_is_displayed(view));
2179 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view->lines) {
2180 unsigned int view_lines = view->pos.offset + view->height;
2181 unsigned int lines = view->lines
2182 ? MIN(view_lines, view->lines) * 100 / view->lines
2183 : 0;
2185 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
2186 view->ops->type,
2187 view->pos.lineno + 1,
2188 view->lines,
2189 lines);
2193 if (view->pipe) {
2194 time_t secs = time(NULL) - view->start_time;
2196 /* Three git seconds are a long time ... */
2197 if (secs > 2)
2198 string_format_from(state, &statelen, " loading %lds", secs);
2201 string_format_from(buf, &bufpos, "[%s]", view->name);
2202 if (*view->ref && bufpos < view->width) {
2203 size_t refsize = strlen(view->ref);
2204 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2206 if (minsize < view->width)
2207 refsize = view->width - minsize + 7;
2208 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2211 if (statelen && bufpos < view->width) {
2212 string_format_from(buf, &bufpos, "%s", state);
2215 if (view == display[current_view])
2216 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2217 else
2218 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2220 mvwaddnstr(window, 0, 0, buf, bufpos);
2221 wclrtoeol(window);
2222 wnoutrefresh(window);
2225 static int
2226 apply_step(double step, int value)
2228 if (step >= 1)
2229 return (int) step;
2230 value *= step + 0.01;
2231 return value ? value : 1;
2234 static void
2235 resize_display(void)
2237 int offset, i;
2238 struct view *base = display[0];
2239 struct view *view = display[1] ? display[1] : display[0];
2241 /* Setup window dimensions */
2243 getmaxyx(stdscr, base->height, base->width);
2245 /* Make room for the status window. */
2246 base->height -= 1;
2248 if (view != base) {
2249 /* Horizontal split. */
2250 view->width = base->width;
2251 view->height = apply_step(opt_scale_split_view, base->height);
2252 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2253 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2254 base->height -= view->height;
2256 /* Make room for the title bar. */
2257 view->height -= 1;
2260 /* Make room for the title bar. */
2261 base->height -= 1;
2263 offset = 0;
2265 foreach_displayed_view (view, i) {
2266 if (!display_win[i]) {
2267 display_win[i] = newwin(view->height, view->width, offset, 0);
2268 if (!display_win[i])
2269 die("Failed to create %s view", view->name);
2271 scrollok(display_win[i], FALSE);
2273 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2274 if (!display_title[i])
2275 die("Failed to create title window");
2277 } else {
2278 wresize(display_win[i], view->height, view->width);
2279 mvwin(display_win[i], offset, 0);
2280 mvwin(display_title[i], offset + view->height, 0);
2283 view->win = display_win[i];
2285 offset += view->height + 1;
2289 static void
2290 redraw_display(bool clear)
2292 struct view *view;
2293 int i;
2295 foreach_displayed_view (view, i) {
2296 if (clear)
2297 wclear(view->win);
2298 redraw_view(view);
2299 update_view_title(view);
2305 * Option management
2308 #define TOGGLE_MENU \
2309 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2310 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2311 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2312 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2313 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2314 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2315 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2316 TOGGLE_(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map) \
2317 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL) \
2318 TOGGLE_(CHANGES, 'C', "local change display", &opt_show_changes, NULL)
2320 static bool
2321 toggle_option(enum request request)
2323 const struct {
2324 enum request request;
2325 const struct enum_map *map;
2326 size_t map_size;
2327 } data[] = {
2328 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2329 TOGGLE_MENU
2330 #undef TOGGLE_
2332 const struct menu_item menu[] = {
2333 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2334 TOGGLE_MENU
2335 #undef TOGGLE_
2336 { 0 }
2338 int i = 0;
2340 if (request == REQ_OPTIONS) {
2341 if (!prompt_menu("Toggle option", menu, &i))
2342 return FALSE;
2343 } else {
2344 while (i < ARRAY_SIZE(data) && data[i].request != request)
2345 i++;
2346 if (i >= ARRAY_SIZE(data))
2347 die("Invalid request (%d)", request);
2350 if (data[i].map != NULL) {
2351 unsigned int *opt = menu[i].data;
2353 *opt = (*opt + 1) % data[i].map_size;
2354 if (data[i].map == ignore_space_map) {
2355 update_ignore_space_arg();
2356 report("Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2357 return TRUE;
2359 } else if (data[i].map == commit_order_map) {
2360 update_commit_order_arg();
2361 report("Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2362 return TRUE;
2365 redraw_display(FALSE);
2366 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2368 } else {
2369 bool *option = menu[i].data;
2371 *option = !*option;
2372 redraw_display(FALSE);
2373 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2376 return FALSE;
2379 static void
2380 maximize_view(struct view *view, bool redraw)
2382 memset(display, 0, sizeof(display));
2383 current_view = 0;
2384 display[current_view] = view;
2385 resize_display();
2386 if (redraw) {
2387 redraw_display(FALSE);
2388 report("");
2394 * Navigation
2397 static bool
2398 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2400 if (lineno >= view->lines)
2401 lineno = view->lines > 0 ? view->lines - 1 : 0;
2403 if (offset > lineno || offset + view->height <= lineno) {
2404 unsigned long half = view->height / 2;
2406 if (lineno > half)
2407 offset = lineno - half;
2408 else
2409 offset = 0;
2412 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2413 view->pos.offset = offset;
2414 view->pos.lineno = lineno;
2415 return TRUE;
2418 return FALSE;
2421 /* Scrolling backend */
2422 static void
2423 do_scroll_view(struct view *view, int lines)
2425 bool redraw_current_line = FALSE;
2427 /* The rendering expects the new offset. */
2428 view->pos.offset += lines;
2430 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2431 assert(lines);
2433 /* Move current line into the view. */
2434 if (view->pos.lineno < view->pos.offset) {
2435 view->pos.lineno = view->pos.offset;
2436 redraw_current_line = TRUE;
2437 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2438 view->pos.lineno = view->pos.offset + view->height - 1;
2439 redraw_current_line = TRUE;
2442 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2444 /* Redraw the whole screen if scrolling is pointless. */
2445 if (view->height < ABS(lines)) {
2446 redraw_view(view);
2448 } else {
2449 int line = lines > 0 ? view->height - lines : 0;
2450 int end = line + ABS(lines);
2452 scrollok(view->win, TRUE);
2453 wscrl(view->win, lines);
2454 scrollok(view->win, FALSE);
2456 while (line < end && draw_view_line(view, line))
2457 line++;
2459 if (redraw_current_line)
2460 draw_view_line(view, view->pos.lineno - view->pos.offset);
2461 wnoutrefresh(view->win);
2464 view->has_scrolled = TRUE;
2465 report("");
2468 /* Scroll frontend */
2469 static void
2470 scroll_view(struct view *view, enum request request)
2472 int lines = 1;
2474 assert(view_is_displayed(view));
2476 switch (request) {
2477 case REQ_SCROLL_FIRST_COL:
2478 view->pos.col = 0;
2479 redraw_view_from(view, 0);
2480 report("");
2481 return;
2482 case REQ_SCROLL_LEFT:
2483 if (view->pos.col == 0) {
2484 report("Cannot scroll beyond the first column");
2485 return;
2487 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2488 view->pos.col = 0;
2489 else
2490 view->pos.col -= apply_step(opt_hscroll, view->width);
2491 redraw_view_from(view, 0);
2492 report("");
2493 return;
2494 case REQ_SCROLL_RIGHT:
2495 view->pos.col += apply_step(opt_hscroll, view->width);
2496 redraw_view(view);
2497 report("");
2498 return;
2499 case REQ_SCROLL_PAGE_DOWN:
2500 lines = view->height;
2501 case REQ_SCROLL_LINE_DOWN:
2502 if (view->pos.offset + lines > view->lines)
2503 lines = view->lines - view->pos.offset;
2505 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2506 report("Cannot scroll beyond the last line");
2507 return;
2509 break;
2511 case REQ_SCROLL_PAGE_UP:
2512 lines = view->height;
2513 case REQ_SCROLL_LINE_UP:
2514 if (lines > view->pos.offset)
2515 lines = view->pos.offset;
2517 if (lines == 0) {
2518 report("Cannot scroll beyond the first line");
2519 return;
2522 lines = -lines;
2523 break;
2525 default:
2526 die("request %d not handled in switch", request);
2529 do_scroll_view(view, lines);
2532 /* Cursor moving */
2533 static void
2534 move_view(struct view *view, enum request request)
2536 int scroll_steps = 0;
2537 int steps;
2539 switch (request) {
2540 case REQ_MOVE_FIRST_LINE:
2541 steps = -view->pos.lineno;
2542 break;
2544 case REQ_MOVE_LAST_LINE:
2545 steps = view->lines - view->pos.lineno - 1;
2546 break;
2548 case REQ_MOVE_PAGE_UP:
2549 steps = view->height > view->pos.lineno
2550 ? -view->pos.lineno : -view->height;
2551 break;
2553 case REQ_MOVE_PAGE_DOWN:
2554 steps = view->pos.lineno + view->height >= view->lines
2555 ? view->lines - view->pos.lineno - 1 : view->height;
2556 break;
2558 case REQ_MOVE_UP:
2559 case REQ_PREVIOUS:
2560 steps = -1;
2561 break;
2563 case REQ_MOVE_DOWN:
2564 case REQ_NEXT:
2565 steps = 1;
2566 break;
2568 default:
2569 die("request %d not handled in switch", request);
2572 if (steps <= 0 && view->pos.lineno == 0) {
2573 report("Cannot move beyond the first line");
2574 return;
2576 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2577 report("Cannot move beyond the last line");
2578 return;
2581 /* Move the current line */
2582 view->pos.lineno += steps;
2583 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2585 /* Check whether the view needs to be scrolled */
2586 if (view->pos.lineno < view->pos.offset ||
2587 view->pos.lineno >= view->pos.offset + view->height) {
2588 scroll_steps = steps;
2589 if (steps < 0 && -steps > view->pos.offset) {
2590 scroll_steps = -view->pos.offset;
2592 } else if (steps > 0) {
2593 if (view->pos.lineno == view->lines - 1 &&
2594 view->lines > view->height) {
2595 scroll_steps = view->lines - view->pos.offset - 1;
2596 if (scroll_steps >= view->height)
2597 scroll_steps -= view->height - 1;
2602 if (!view_is_displayed(view)) {
2603 view->pos.offset += scroll_steps;
2604 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2605 view->ops->select(view, &view->line[view->pos.lineno]);
2606 return;
2609 /* Repaint the old "current" line if we be scrolling */
2610 if (ABS(steps) < view->height)
2611 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2613 if (scroll_steps) {
2614 do_scroll_view(view, scroll_steps);
2615 return;
2618 /* Draw the current line */
2619 draw_view_line(view, view->pos.lineno - view->pos.offset);
2621 wnoutrefresh(view->win);
2622 report("");
2627 * Searching
2630 static void search_view(struct view *view, enum request request);
2632 static bool
2633 grep_text(struct view *view, const char *text[])
2635 regmatch_t pmatch;
2636 size_t i;
2638 for (i = 0; text[i]; i++)
2639 if (*text[i] &&
2640 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2641 return TRUE;
2642 return FALSE;
2645 static void
2646 select_view_line(struct view *view, unsigned long lineno)
2648 struct position old = view->pos;
2650 if (goto_view_line(view, view->pos.offset, lineno)) {
2651 if (view_is_displayed(view)) {
2652 if (old.offset != view->pos.offset) {
2653 redraw_view(view);
2654 } else {
2655 draw_view_line(view, old.lineno - view->pos.offset);
2656 draw_view_line(view, view->pos.lineno - view->pos.offset);
2657 wnoutrefresh(view->win);
2659 } else {
2660 view->ops->select(view, &view->line[view->pos.lineno]);
2665 static void
2666 find_next(struct view *view, enum request request)
2668 unsigned long lineno = view->pos.lineno;
2669 int direction;
2671 if (!*view->grep) {
2672 if (!*opt_search)
2673 report("No previous search");
2674 else
2675 search_view(view, request);
2676 return;
2679 switch (request) {
2680 case REQ_SEARCH:
2681 case REQ_FIND_NEXT:
2682 direction = 1;
2683 break;
2685 case REQ_SEARCH_BACK:
2686 case REQ_FIND_PREV:
2687 direction = -1;
2688 break;
2690 default:
2691 return;
2694 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2695 lineno += direction;
2697 /* Note, lineno is unsigned long so will wrap around in which case it
2698 * will become bigger than view->lines. */
2699 for (; lineno < view->lines; lineno += direction) {
2700 if (view->ops->grep(view, &view->line[lineno])) {
2701 select_view_line(view, lineno);
2702 report("Line %ld matches '%s'", lineno + 1, view->grep);
2703 return;
2707 report("No match found for '%s'", view->grep);
2710 static void
2711 search_view(struct view *view, enum request request)
2713 int regex_err;
2715 if (view->regex) {
2716 regfree(view->regex);
2717 *view->grep = 0;
2718 } else {
2719 view->regex = calloc(1, sizeof(*view->regex));
2720 if (!view->regex)
2721 return;
2724 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2725 if (regex_err != 0) {
2726 char buf[SIZEOF_STR] = "unknown error";
2728 regerror(regex_err, view->regex, buf, sizeof(buf));
2729 report("Search failed: %s", buf);
2730 return;
2733 string_copy(view->grep, opt_search);
2735 find_next(view, request);
2739 * Incremental updating
2742 static inline bool
2743 check_position(struct position *pos)
2745 return pos->lineno || pos->col || pos->offset;
2748 static inline void
2749 clear_position(struct position *pos)
2751 memset(pos, 0, sizeof(*pos));
2754 static void
2755 reset_view(struct view *view)
2757 int i;
2759 for (i = 0; i < view->lines; i++)
2760 if (!view->line[i].dont_free)
2761 free(view->line[i].data);
2762 free(view->line);
2764 view->prev_pos = view->pos;
2765 clear_position(&view->pos);
2767 view->line = NULL;
2768 view->lines = 0;
2769 view->vid[0] = 0;
2770 view->update_secs = 0;
2773 static const char *
2774 format_arg(const char *name)
2776 static struct {
2777 const char *name;
2778 size_t namelen;
2779 const char *value;
2780 const char *value_if_empty;
2781 } vars[] = {
2782 #define FORMAT_VAR(name, value, value_if_empty) \
2783 { name, STRING_SIZE(name), value, value_if_empty }
2784 FORMAT_VAR("%(directory)", opt_path, "."),
2785 FORMAT_VAR("%(file)", opt_file, ""),
2786 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2787 FORMAT_VAR("%(head)", ref_head, ""),
2788 FORMAT_VAR("%(commit)", ref_commit, ""),
2789 FORMAT_VAR("%(blob)", ref_blob, ""),
2790 FORMAT_VAR("%(branch)", ref_branch, ""),
2792 int i;
2794 if (!prefixcmp(name, "%(prompt"))
2795 return read_prompt("Command argument: ");
2797 for (i = 0; i < ARRAY_SIZE(vars); i++)
2798 if (!strncmp(name, vars[i].name, vars[i].namelen))
2799 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2801 report("Unknown replacement: `%s`", name);
2802 return NULL;
2805 static bool
2806 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2808 char buf[SIZEOF_STR];
2809 int argc;
2811 argv_free(*dst_argv);
2813 for (argc = 0; src_argv[argc]; argc++) {
2814 const char *arg = src_argv[argc];
2815 size_t bufpos = 0;
2817 if (!strcmp(arg, "%(fileargs)")) {
2818 if (!argv_append_array(dst_argv, opt_file_argv))
2819 break;
2820 continue;
2822 } else if (!strcmp(arg, "%(diffargs)")) {
2823 if (!argv_append_array(dst_argv, opt_diff_argv))
2824 break;
2825 continue;
2827 } else if (!strcmp(arg, "%(blameargs)")) {
2828 if (!argv_append_array(dst_argv, opt_blame_argv))
2829 break;
2830 continue;
2832 } else if (!strcmp(arg, "%(revargs)") ||
2833 (first && !strcmp(arg, "%(commit)"))) {
2834 if (!argv_append_array(dst_argv, opt_rev_argv))
2835 break;
2836 continue;
2839 while (arg) {
2840 char *next = strstr(arg, "%(");
2841 int len = next - arg;
2842 const char *value;
2844 if (!next) {
2845 len = strlen(arg);
2846 value = "";
2848 } else {
2849 value = format_arg(next);
2851 if (!value) {
2852 return FALSE;
2856 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2857 return FALSE;
2859 arg = next ? strchr(next, ')') + 1 : NULL;
2862 if (!argv_append(dst_argv, buf))
2863 break;
2866 return src_argv[argc] == NULL;
2869 static bool
2870 restore_view_position(struct view *view)
2872 /* A view without a previous view is the first view */
2873 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2874 select_view_line(view, opt_lineno - 1);
2875 opt_lineno = 0;
2878 /* Ensure that the view position is in a valid state. */
2879 if (!check_position(&view->prev_pos) ||
2880 (view->pipe && view->lines <= view->prev_pos.lineno))
2881 return goto_view_line(view, view->pos.offset, view->pos.lineno);
2883 /* Changing the view position cancels the restoring. */
2884 /* FIXME: Changing back to the first line is not detected. */
2885 if (check_position(&view->pos)) {
2886 clear_position(&view->prev_pos);
2887 return FALSE;
2890 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
2891 view_is_displayed(view))
2892 werase(view->win);
2894 view->pos.col = view->prev_pos.col;
2895 clear_position(&view->prev_pos);
2897 return TRUE;
2900 static void
2901 end_update(struct view *view, bool force)
2903 if (!view->pipe)
2904 return;
2905 while (!view->ops->read(view, NULL))
2906 if (!force)
2907 return;
2908 if (force)
2909 io_kill(view->pipe);
2910 io_done(view->pipe);
2911 view->pipe = NULL;
2914 static void
2915 setup_update(struct view *view, const char *vid)
2917 reset_view(view);
2918 string_copy_rev(view->vid, vid);
2919 view->pipe = &view->io;
2920 view->start_time = time(NULL);
2923 static bool
2924 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2926 bool extra = !!(flags & (OPEN_EXTRA));
2927 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2928 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2930 if (!reload && !strcmp(view->vid, view->id))
2931 return TRUE;
2933 if (view->pipe) {
2934 if (extra)
2935 io_done(view->pipe);
2936 else
2937 end_update(view, TRUE);
2940 if (!refresh && argv) {
2941 view->dir = dir;
2942 if (!format_argv(&view->argv, argv, !view->prev))
2943 return FALSE;
2945 /* Put the current ref_* value to the view title ref
2946 * member. This is needed by the blob view. Most other
2947 * views sets it automatically after loading because the
2948 * first line is a commit line. */
2949 string_copy_rev(view->ref, view->id);
2952 if (view->argv && view->argv[0] &&
2953 !io_run(&view->io, IO_RD, view->dir, view->argv))
2954 return FALSE;
2956 if (!extra)
2957 setup_update(view, view->id);
2959 return TRUE;
2962 static bool
2963 update_view(struct view *view)
2965 char *line;
2966 /* Clear the view and redraw everything since the tree sorting
2967 * might have rearranged things. */
2968 bool redraw = view->lines == 0;
2969 bool can_read = TRUE;
2971 if (!view->pipe)
2972 return TRUE;
2974 if (!io_can_read(view->pipe, FALSE)) {
2975 if (view->lines == 0 && view_is_displayed(view)) {
2976 time_t secs = time(NULL) - view->start_time;
2978 if (secs > 1 && secs > view->update_secs) {
2979 if (view->update_secs == 0)
2980 redraw_view(view);
2981 update_view_title(view);
2982 view->update_secs = secs;
2985 return TRUE;
2988 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2989 if (view->encoding) {
2990 line = encoding_convert(view->encoding, line);
2993 if (!view->ops->read(view, line)) {
2994 report("Allocation failure");
2995 end_update(view, TRUE);
2996 return FALSE;
3001 unsigned long lines = view->lines;
3002 int digits;
3004 for (digits = 0; lines; digits++)
3005 lines /= 10;
3007 /* Keep the displayed view in sync with line number scaling. */
3008 if (digits != view->digits) {
3009 view->digits = digits;
3010 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3011 redraw = TRUE;
3015 if (io_error(view->pipe)) {
3016 report("Failed to read: %s", io_strerror(view->pipe));
3017 end_update(view, TRUE);
3019 } else if (io_eof(view->pipe)) {
3020 if (view_is_displayed(view))
3021 report("");
3022 end_update(view, FALSE);
3025 if (restore_view_position(view))
3026 redraw = TRUE;
3028 if (!view_is_displayed(view))
3029 return TRUE;
3031 if (redraw)
3032 redraw_view_from(view, 0);
3033 else
3034 redraw_view_dirty(view);
3036 /* Update the title _after_ the redraw so that if the redraw picks up a
3037 * commit reference in view->ref it'll be available here. */
3038 update_view_title(view);
3039 return TRUE;
3042 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3044 static struct line *
3045 add_line_data(struct view *view, void *data, enum line_type type)
3047 struct line *line;
3049 if (!realloc_lines(&view->line, view->lines, 1))
3050 return NULL;
3052 line = &view->line[view->lines++];
3053 memset(line, 0, sizeof(*line));
3054 line->type = type;
3055 line->data = data;
3056 line->dirty = 1;
3058 return line;
3061 static struct line *
3062 add_line_static_data(struct view *view, void *data, enum line_type type)
3064 struct line *line = add_line_data(view, data, type);
3066 if (line)
3067 line->dont_free = TRUE;
3068 return line;
3071 static struct line *
3072 add_line_text(struct view *view, const char *text, enum line_type type)
3074 char *data = text ? strdup(text) : NULL;
3076 return data ? add_line_data(view, data, type) : NULL;
3079 static struct line *
3080 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3082 char buf[SIZEOF_STR];
3083 int retval;
3085 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3086 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3090 * View opening
3093 static void
3094 load_view(struct view *view, enum open_flags flags)
3096 if (view->pipe)
3097 end_update(view, TRUE);
3098 if (view->ops->private_size) {
3099 if (!view->private)
3100 view->private = calloc(1, view->ops->private_size);
3101 else
3102 memset(view->private, 0, view->ops->private_size);
3104 if (!view->ops->open(view, flags)) {
3105 report("Failed to load %s view", view->name);
3106 return;
3108 restore_view_position(view);
3110 if (view->pipe && view->lines == 0) {
3111 /* Clear the old view and let the incremental updating refill
3112 * the screen. */
3113 werase(view->win);
3114 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3115 clear_position(&view->prev_pos);
3116 report("");
3117 } else if (view_is_displayed(view)) {
3118 redraw_view(view);
3119 report("");
3123 #define refresh_view(view) load_view(view, OPEN_REFRESH)
3124 #define reload_view(view) load_view(view, OPEN_RELOAD)
3126 static void
3127 split_view(struct view *prev, struct view *view)
3129 display[1] = view;
3130 current_view = 1;
3131 view->parent = prev;
3132 resize_display();
3134 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3135 /* Take the title line into account. */
3136 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3138 /* Scroll the view that was split if the current line is
3139 * outside the new limited view. */
3140 do_scroll_view(prev, lines);
3143 if (view != prev && view_is_displayed(prev)) {
3144 /* "Blur" the previous view. */
3145 update_view_title(prev);
3149 static void
3150 open_view(struct view *prev, enum request request, enum open_flags flags)
3152 bool split = !!(flags & OPEN_SPLIT);
3153 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3154 struct view *view = VIEW(request);
3155 int nviews = displayed_views();
3157 assert(flags ^ OPEN_REFRESH);
3159 if (view == prev && nviews == 1 && !reload) {
3160 report("Already in %s view", view->name);
3161 return;
3164 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3165 report("The %s view is disabled in pager view", view->name);
3166 return;
3169 if (split) {
3170 split_view(prev, view);
3171 } else {
3172 maximize_view(view, FALSE);
3175 /* No prev signals that this is the first loaded view. */
3176 if (prev && view != prev) {
3177 view->prev = prev;
3180 load_view(view, flags);
3183 static void
3184 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3186 enum request request = view - views + REQ_OFFSET + 1;
3188 if (view->pipe)
3189 end_update(view, TRUE);
3190 view->dir = dir;
3192 if (!argv_copy(&view->argv, argv)) {
3193 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3194 } else {
3195 open_view(prev, request, flags | OPEN_PREPARED);
3199 static void
3200 open_external_viewer(const char *argv[], const char *dir)
3202 def_prog_mode(); /* save current tty modes */
3203 endwin(); /* restore original tty modes */
3204 io_run_fg(argv, dir);
3205 fprintf(stderr, "Press Enter to continue");
3206 getc(opt_tty);
3207 reset_prog_mode();
3208 redraw_display(TRUE);
3211 static void
3212 open_mergetool(const char *file)
3214 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3216 open_external_viewer(mergetool_argv, opt_cdup);
3219 static void
3220 open_editor(const char *file)
3222 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3223 char editor_cmd[SIZEOF_STR];
3224 const char *editor;
3225 int argc = 0;
3227 editor = getenv("GIT_EDITOR");
3228 if (!editor && *opt_editor)
3229 editor = opt_editor;
3230 if (!editor)
3231 editor = getenv("VISUAL");
3232 if (!editor)
3233 editor = getenv("EDITOR");
3234 if (!editor)
3235 editor = "vi";
3237 string_ncopy(editor_cmd, editor, strlen(editor));
3238 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3239 report("Failed to read editor command");
3240 return;
3243 editor_argv[argc] = file;
3244 open_external_viewer(editor_argv, opt_cdup);
3247 static void
3248 open_run_request(enum request request)
3250 struct run_request *req = get_run_request(request);
3251 const char **argv = NULL;
3253 if (!req) {
3254 report("Unknown run request");
3255 return;
3258 if (format_argv(&argv, req->argv, FALSE)) {
3259 if (req->silent)
3260 io_run_bg(argv);
3261 else
3262 open_external_viewer(argv, NULL);
3264 if (argv)
3265 argv_free(argv);
3266 free(argv);
3270 * User request switch noodle
3273 static int
3274 view_driver(struct view *view, enum request request)
3276 int i;
3278 if (request == REQ_NONE)
3279 return TRUE;
3281 if (request > REQ_NONE) {
3282 open_run_request(request);
3283 view_request(view, REQ_REFRESH);
3284 return TRUE;
3287 request = view_request(view, request);
3288 if (request == REQ_NONE)
3289 return TRUE;
3291 switch (request) {
3292 case REQ_MOVE_UP:
3293 case REQ_MOVE_DOWN:
3294 case REQ_MOVE_PAGE_UP:
3295 case REQ_MOVE_PAGE_DOWN:
3296 case REQ_MOVE_FIRST_LINE:
3297 case REQ_MOVE_LAST_LINE:
3298 move_view(view, request);
3299 break;
3301 case REQ_SCROLL_FIRST_COL:
3302 case REQ_SCROLL_LEFT:
3303 case REQ_SCROLL_RIGHT:
3304 case REQ_SCROLL_LINE_DOWN:
3305 case REQ_SCROLL_LINE_UP:
3306 case REQ_SCROLL_PAGE_DOWN:
3307 case REQ_SCROLL_PAGE_UP:
3308 scroll_view(view, request);
3309 break;
3311 case REQ_VIEW_BLAME:
3312 if (!opt_file[0]) {
3313 report("No file chosen, press %s to open tree view",
3314 get_view_key(view, REQ_VIEW_TREE));
3315 break;
3317 open_view(view, request, OPEN_DEFAULT);
3318 break;
3320 case REQ_VIEW_BLOB:
3321 if (!ref_blob[0]) {
3322 report("No file chosen, press %s to open tree view",
3323 get_view_key(view, REQ_VIEW_TREE));
3324 break;
3326 open_view(view, request, OPEN_DEFAULT);
3327 break;
3329 case REQ_VIEW_PAGER:
3330 if (view == NULL) {
3331 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
3332 die("Failed to open stdin");
3333 open_view(view, request, OPEN_PREPARED);
3334 break;
3337 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
3338 report("No pager content, press %s to run command from prompt",
3339 get_view_key(view, REQ_PROMPT));
3340 break;
3342 open_view(view, request, OPEN_DEFAULT);
3343 break;
3345 case REQ_VIEW_STAGE:
3346 if (!VIEW(REQ_VIEW_STAGE)->lines) {
3347 report("No stage content, press %s to open the status view and choose file",
3348 get_view_key(view, REQ_VIEW_STATUS));
3349 break;
3351 open_view(view, request, OPEN_DEFAULT);
3352 break;
3354 case REQ_VIEW_STATUS:
3355 if (opt_is_inside_work_tree == FALSE) {
3356 report("The status view requires a working tree");
3357 break;
3359 open_view(view, request, OPEN_DEFAULT);
3360 break;
3362 case REQ_VIEW_MAIN:
3363 case REQ_VIEW_DIFF:
3364 case REQ_VIEW_LOG:
3365 case REQ_VIEW_TREE:
3366 case REQ_VIEW_HELP:
3367 case REQ_VIEW_BRANCH:
3368 open_view(view, request, OPEN_DEFAULT);
3369 break;
3371 case REQ_NEXT:
3372 case REQ_PREVIOUS:
3373 if (view->parent) {
3374 int line;
3376 view = view->parent;
3377 line = view->pos.lineno;
3378 move_view(view, request);
3379 if (view_is_displayed(view))
3380 update_view_title(view);
3381 if (line != view->pos.lineno)
3382 view_request(view, REQ_ENTER);
3383 } else {
3384 move_view(view, request);
3386 break;
3388 case REQ_VIEW_NEXT:
3390 int nviews = displayed_views();
3391 int next_view = (current_view + 1) % nviews;
3393 if (next_view == current_view) {
3394 report("Only one view is displayed");
3395 break;
3398 current_view = next_view;
3399 /* Blur out the title of the previous view. */
3400 update_view_title(view);
3401 report("");
3402 break;
3404 case REQ_REFRESH:
3405 report("Refreshing is not yet supported for the %s view", view->name);
3406 break;
3408 case REQ_MAXIMIZE:
3409 if (displayed_views() == 2)
3410 maximize_view(view, TRUE);
3411 break;
3413 case REQ_OPTIONS:
3414 case REQ_TOGGLE_LINENO:
3415 case REQ_TOGGLE_DATE:
3416 case REQ_TOGGLE_AUTHOR:
3417 case REQ_TOGGLE_FILENAME:
3418 case REQ_TOGGLE_GRAPHIC:
3419 case REQ_TOGGLE_REV_GRAPH:
3420 case REQ_TOGGLE_REFS:
3421 case REQ_TOGGLE_CHANGES:
3422 case REQ_TOGGLE_IGNORE_SPACE:
3423 if (toggle_option(request) && view_has_flags(view, VIEW_DIFF_LIKE))
3424 reload_view(view);
3425 break;
3427 case REQ_TOGGLE_SORT_FIELD:
3428 case REQ_TOGGLE_SORT_ORDER:
3429 report("Sorting is not yet supported for the %s view", view->name);
3430 break;
3432 case REQ_DIFF_CONTEXT_UP:
3433 case REQ_DIFF_CONTEXT_DOWN:
3434 report("Changing the diff context is not yet supported for the %s view", view->name);
3435 break;
3437 case REQ_SEARCH:
3438 case REQ_SEARCH_BACK:
3439 search_view(view, request);
3440 break;
3442 case REQ_FIND_NEXT:
3443 case REQ_FIND_PREV:
3444 find_next(view, request);
3445 break;
3447 case REQ_STOP_LOADING:
3448 foreach_view(view, i) {
3449 if (view->pipe)
3450 report("Stopped loading the %s view", view->name),
3451 end_update(view, TRUE);
3453 break;
3455 case REQ_SHOW_VERSION:
3456 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3457 return TRUE;
3459 case REQ_SCREEN_REDRAW:
3460 redraw_display(TRUE);
3461 break;
3463 case REQ_EDIT:
3464 report("Nothing to edit");
3465 break;
3467 case REQ_ENTER:
3468 report("Nothing to enter");
3469 break;
3471 case REQ_VIEW_CLOSE:
3472 /* XXX: Mark closed views by letting view->prev point to the
3473 * view itself. Parents to closed view should never be
3474 * followed. */
3475 if (view->prev && view->prev != view) {
3476 maximize_view(view->prev, TRUE);
3477 view->prev = view;
3478 break;
3480 /* Fall-through */
3481 case REQ_QUIT:
3482 return FALSE;
3484 default:
3485 report("Unknown key, press %s for help",
3486 get_view_key(view, REQ_VIEW_HELP));
3487 return TRUE;
3490 return TRUE;
3495 * View backend utilities
3498 enum sort_field {
3499 ORDERBY_NAME,
3500 ORDERBY_DATE,
3501 ORDERBY_AUTHOR,
3504 struct sort_state {
3505 const enum sort_field *fields;
3506 size_t size, current;
3507 bool reverse;
3510 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3511 #define get_sort_field(state) ((state).fields[(state).current])
3512 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3514 static void
3515 sort_view(struct view *view, enum request request, struct sort_state *state,
3516 int (*compare)(const void *, const void *))
3518 switch (request) {
3519 case REQ_TOGGLE_SORT_FIELD:
3520 state->current = (state->current + 1) % state->size;
3521 break;
3523 case REQ_TOGGLE_SORT_ORDER:
3524 state->reverse = !state->reverse;
3525 break;
3526 default:
3527 die("Not a sort request");
3530 qsort(view->line, view->lines, sizeof(*view->line), compare);
3531 redraw_view(view);
3534 static bool
3535 update_diff_context(enum request request)
3537 int diff_context = opt_diff_context;
3539 switch (request) {
3540 case REQ_DIFF_CONTEXT_UP:
3541 opt_diff_context += 1;
3542 update_diff_context_arg(opt_diff_context);
3543 break;
3545 case REQ_DIFF_CONTEXT_DOWN:
3546 if (opt_diff_context == 0) {
3547 report("Diff context cannot be less than zero");
3548 break;
3550 opt_diff_context -= 1;
3551 update_diff_context_arg(opt_diff_context);
3552 break;
3554 default:
3555 die("Not a diff context request");
3558 return diff_context != opt_diff_context;
3561 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3563 /* Small author cache to reduce memory consumption. It uses binary
3564 * search to lookup or find place to position new entries. No entries
3565 * are ever freed. */
3566 static const char *
3567 get_author(const char *name)
3569 static const char **authors;
3570 static size_t authors_size;
3571 int from = 0, to = authors_size - 1;
3573 while (from <= to) {
3574 size_t pos = (to + from) / 2;
3575 int cmp = strcmp(name, authors[pos]);
3577 if (!cmp)
3578 return authors[pos];
3580 if (cmp < 0)
3581 to = pos - 1;
3582 else
3583 from = pos + 1;
3586 if (!realloc_authors(&authors, authors_size, 1))
3587 return NULL;
3588 name = strdup(name);
3589 if (!name)
3590 return NULL;
3592 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3593 authors[from] = name;
3594 authors_size++;
3596 return name;
3599 static void
3600 parse_timesec(struct time *time, const char *sec)
3602 time->sec = (time_t) atol(sec);
3605 static void
3606 parse_timezone(struct time *time, const char *zone)
3608 long tz;
3610 tz = ('0' - zone[1]) * 60 * 60 * 10;
3611 tz += ('0' - zone[2]) * 60 * 60;
3612 tz += ('0' - zone[3]) * 60 * 10;
3613 tz += ('0' - zone[4]) * 60;
3615 if (zone[0] == '-')
3616 tz = -tz;
3618 time->tz = tz;
3619 time->sec -= tz;
3622 /* Parse author lines where the name may be empty:
3623 * author <email@address.tld> 1138474660 +0100
3625 static void
3626 parse_author_line(char *ident, const char **author, struct time *time)
3628 char *nameend = strchr(ident, '<');
3629 char *emailend = strchr(ident, '>');
3631 if (nameend && emailend)
3632 *nameend = *emailend = 0;
3633 ident = chomp_string(ident);
3634 if (!*ident) {
3635 if (nameend)
3636 ident = chomp_string(nameend + 1);
3637 if (!*ident)
3638 ident = "Unknown";
3641 *author = get_author(ident);
3643 /* Parse epoch and timezone */
3644 if (emailend && emailend[1] == ' ') {
3645 char *secs = emailend + 2;
3646 char *zone = strchr(secs, ' ');
3648 parse_timesec(time, secs);
3650 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3651 parse_timezone(time, zone + 1);
3655 static struct line *
3656 find_prev_line_by_type(struct view *view, struct line *line, enum line_type type)
3658 for (; view->line < line; line--)
3659 if (line->type == type)
3660 return line;
3662 return NULL;
3666 * Blame
3669 struct blame_commit {
3670 char id[SIZEOF_REV]; /* SHA1 ID. */
3671 char title[128]; /* First line of the commit message. */
3672 const char *author; /* Author of the commit. */
3673 struct time time; /* Date from the author ident. */
3674 char filename[128]; /* Name of file. */
3675 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3676 char parent_filename[128]; /* Parent/previous name of file. */
3679 struct blame_header {
3680 char id[SIZEOF_REV]; /* SHA1 ID. */
3681 size_t orig_lineno;
3682 size_t lineno;
3683 size_t group;
3686 static bool
3687 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3689 const char *pos = *posref;
3691 *posref = NULL;
3692 pos = strchr(pos + 1, ' ');
3693 if (!pos || !isdigit(pos[1]))
3694 return FALSE;
3695 *number = atoi(pos + 1);
3696 if (*number < min || *number > max)
3697 return FALSE;
3699 *posref = pos;
3700 return TRUE;
3703 static bool
3704 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3706 const char *pos = text + SIZEOF_REV - 2;
3708 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3709 return FALSE;
3711 string_ncopy(header->id, text, SIZEOF_REV);
3713 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3714 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3715 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3716 return FALSE;
3718 return TRUE;
3721 static bool
3722 match_blame_header(const char *name, char **line)
3724 size_t namelen = strlen(name);
3725 bool matched = !strncmp(name, *line, namelen);
3727 if (matched)
3728 *line += namelen;
3730 return matched;
3733 static bool
3734 parse_blame_info(struct blame_commit *commit, char *line)
3736 if (match_blame_header("author ", &line)) {
3737 commit->author = get_author(line);
3739 } else if (match_blame_header("author-time ", &line)) {
3740 parse_timesec(&commit->time, line);
3742 } else if (match_blame_header("author-tz ", &line)) {
3743 parse_timezone(&commit->time, line);
3745 } else if (match_blame_header("summary ", &line)) {
3746 string_ncopy(commit->title, line, strlen(line));
3748 } else if (match_blame_header("previous ", &line)) {
3749 if (strlen(line) <= SIZEOF_REV)
3750 return FALSE;
3751 string_copy_rev(commit->parent_id, line);
3752 line += SIZEOF_REV;
3753 string_ncopy(commit->parent_filename, line, strlen(line));
3755 } else if (match_blame_header("filename ", &line)) {
3756 string_ncopy(commit->filename, line, strlen(line));
3757 return TRUE;
3760 return FALSE;
3764 * Pager backend
3767 static bool
3768 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3770 if (draw_lineno(view, lineno))
3771 return TRUE;
3773 draw_text(view, line->type, line->data);
3774 return TRUE;
3777 static bool
3778 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3780 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3781 char ref[SIZEOF_STR];
3783 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3784 return TRUE;
3786 /* This is the only fatal call, since it can "corrupt" the buffer. */
3787 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3788 return FALSE;
3790 return TRUE;
3793 static void
3794 add_pager_refs(struct view *view, struct line *line)
3796 char buf[SIZEOF_STR];
3797 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3798 struct ref_list *list;
3799 size_t bufpos = 0, i;
3800 const char *sep = "Refs: ";
3801 bool is_tag = FALSE;
3803 assert(line->type == LINE_COMMIT);
3805 list = get_ref_list(commit_id);
3806 if (!list) {
3807 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3808 goto try_add_describe_ref;
3809 return;
3812 for (i = 0; i < list->size; i++) {
3813 struct ref *ref = list->refs[i];
3814 const char *fmt = ref->tag ? "%s[%s]" :
3815 ref->remote ? "%s<%s>" : "%s%s";
3817 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3818 return;
3819 sep = ", ";
3820 if (ref->tag)
3821 is_tag = TRUE;
3824 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3825 try_add_describe_ref:
3826 /* Add <tag>-g<commit_id> "fake" reference. */
3827 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3828 return;
3831 if (bufpos == 0)
3832 return;
3834 add_line_text(view, buf, LINE_PP_REFS);
3837 static bool
3838 pager_common_read(struct view *view, char *data, enum line_type type)
3840 struct line *line;
3842 if (!data)
3843 return TRUE;
3845 line = add_line_text(view, data, type);
3846 if (!line)
3847 return FALSE;
3849 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
3850 add_pager_refs(view, line);
3852 return TRUE;
3855 static bool
3856 pager_read(struct view *view, char *data)
3858 if (!data)
3859 return TRUE;
3861 return pager_common_read(view, data, get_line_type(data));
3864 static enum request
3865 pager_request(struct view *view, enum request request, struct line *line)
3867 int split = 0;
3869 if (request != REQ_ENTER)
3870 return request;
3872 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
3873 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3874 split = 1;
3877 /* Always scroll the view even if it was split. That way
3878 * you can use Enter to scroll through the log view and
3879 * split open each commit diff. */
3880 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3882 /* FIXME: A minor workaround. Scrolling the view will call report("")
3883 * but if we are scrolling a non-current view this won't properly
3884 * update the view title. */
3885 if (split)
3886 update_view_title(view);
3888 return REQ_NONE;
3891 static bool
3892 pager_grep(struct view *view, struct line *line)
3894 const char *text[] = { line->data, NULL };
3896 return grep_text(view, text);
3899 static void
3900 pager_select(struct view *view, struct line *line)
3902 if (line->type == LINE_COMMIT) {
3903 char *text = (char *)line->data + STRING_SIZE("commit ");
3905 if (!view_has_flags(view, VIEW_NO_REF))
3906 string_copy_rev(view->ref, text);
3907 string_copy_rev(ref_commit, text);
3911 static bool
3912 pager_open(struct view *view, enum open_flags flags)
3914 return begin_update(view, NULL, NULL, flags);
3917 static struct view_ops pager_ops = {
3918 "line",
3919 { "pager" },
3920 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
3922 pager_open,
3923 pager_read,
3924 pager_draw,
3925 pager_request,
3926 pager_grep,
3927 pager_select,
3930 static bool
3931 log_open(struct view *view, enum open_flags flags)
3933 static const char *log_argv[] = {
3934 "git", "log", ENCODING_ARG, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3937 return begin_update(view, NULL, log_argv, flags);
3940 static enum request
3941 log_request(struct view *view, enum request request, struct line *line)
3943 switch (request) {
3944 case REQ_REFRESH:
3945 load_refs();
3946 refresh_view(view);
3947 return REQ_NONE;
3948 default:
3949 return pager_request(view, request, line);
3953 static struct view_ops log_ops = {
3954 "line",
3955 { "log" },
3956 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
3958 log_open,
3959 pager_read,
3960 pager_draw,
3961 log_request,
3962 pager_grep,
3963 pager_select,
3966 struct diff_state {
3967 bool reading_diff_stat;
3968 bool combined_diff;
3971 static bool
3972 diff_open(struct view *view, enum open_flags flags)
3974 static const char *diff_argv[] = {
3975 "git", "show", ENCODING_ARG, "--pretty=fuller", "--no-color", "--root",
3976 "--patch-with-stat", "--find-copies-harder", "-C",
3977 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
3978 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3981 return begin_update(view, NULL, diff_argv, flags);
3984 static bool
3985 diff_common_read(struct view *view, char *data, struct diff_state *state)
3987 enum line_type type;
3989 if (state->reading_diff_stat) {
3990 size_t len = strlen(data);
3991 char *pipe = strchr(data, '|');
3992 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3993 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3995 if (pipe && (has_histogram || has_bin_diff)) {
3996 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3997 } else {
3998 state->reading_diff_stat = FALSE;
4001 } else if (!strcmp(data, "---")) {
4002 state->reading_diff_stat = TRUE;
4005 type = get_line_type(data);
4007 if (type == LINE_DIFF_HEADER) {
4008 const int len = line_info[LINE_DIFF_HEADER].linelen;
4010 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4011 !strncmp(data + len, "cc ", strlen("cc ")))
4012 state->combined_diff = TRUE;
4015 /* ADD2 and DEL2 are only valid in combined diff hunks */
4016 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4017 type = LINE_DEFAULT;
4019 return pager_common_read(view, data, type);
4022 static enum request
4023 diff_common_enter(struct view *view, enum request request, struct line *line)
4025 if (line->type == LINE_DIFF_STAT) {
4026 int file_number = 0;
4028 while (line >= view->line && line->type == LINE_DIFF_STAT) {
4029 file_number++;
4030 line--;
4033 while (line < view->line + view->lines) {
4034 if (line->type == LINE_DIFF_HEADER) {
4035 if (file_number == 1) {
4036 break;
4038 file_number--;
4040 line++;
4044 select_view_line(view, line - view->line);
4045 report("");
4046 return REQ_NONE;
4048 } else {
4049 return pager_request(view, request, line);
4053 static bool
4054 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4056 char *sep = strchr(*text, c);
4058 if (sep != NULL) {
4059 *sep = 0;
4060 draw_text(view, *type, *text);
4061 *sep = c;
4062 *text = sep;
4063 *type = next_type;
4066 return sep != NULL;
4069 static bool
4070 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4072 char *text = line->data;
4073 enum line_type type = line->type;
4075 if (draw_lineno(view, lineno))
4076 return TRUE;
4078 if (type == LINE_DIFF_STAT) {
4079 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4080 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4081 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4082 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4083 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4084 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4085 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4087 } else {
4088 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4089 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4093 draw_text(view, type, text);
4094 return TRUE;
4097 static bool
4098 diff_read(struct view *view, char *data)
4100 struct diff_state *state = view->private;
4102 if (!data) {
4103 /* Fall back to retry if no diff will be shown. */
4104 if (view->lines == 0 && opt_file_argv) {
4105 int pos = argv_size(view->argv)
4106 - argv_size(opt_file_argv) - 1;
4108 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4109 for (; view->argv[pos]; pos++) {
4110 free((void *) view->argv[pos]);
4111 view->argv[pos] = NULL;
4114 if (view->pipe)
4115 io_done(view->pipe);
4116 if (io_run(&view->io, IO_RD, view->dir, view->argv))
4117 return FALSE;
4120 return TRUE;
4123 return diff_common_read(view, data, state);
4126 static bool
4127 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4128 struct blame_header *header, struct blame_commit *commit)
4130 char line_arg[SIZEOF_STR];
4131 const char *blame_argv[] = {
4132 "git", "blame", ENCODING_ARG, "-p", line_arg, ref, "--", file, NULL
4134 struct io io;
4135 bool ok = FALSE;
4136 char *buf;
4138 if (!string_format(line_arg, "-L%d,+1", lineno))
4139 return FALSE;
4141 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
4142 return FALSE;
4144 while ((buf = io_get(&io, '\n', TRUE))) {
4145 if (header) {
4146 if (!parse_blame_header(header, buf, 9999999))
4147 break;
4148 header = NULL;
4150 } else if (parse_blame_info(commit, buf)) {
4151 ok = TRUE;
4152 break;
4156 if (io_error(&io))
4157 ok = FALSE;
4159 io_done(&io);
4160 return ok;
4163 static bool
4164 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4166 return prefixcmp(chunk, "@@ -") ||
4167 !(chunk = strchr(chunk, marker)) ||
4168 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4171 static enum request
4172 diff_trace_origin(struct view *view, struct line *line)
4174 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4175 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4176 const char *chunk_data;
4177 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4178 int lineno = 0;
4179 const char *file = NULL;
4180 char ref[SIZEOF_REF];
4181 struct blame_header header;
4182 struct blame_commit commit;
4184 if (!diff || !chunk || chunk == line) {
4185 report("The line to trace must be inside a diff chunk");
4186 return REQ_NONE;
4189 for (; diff < line && !file; diff++) {
4190 const char *data = diff->data;
4192 if (!prefixcmp(data, "--- a/")) {
4193 file = data + STRING_SIZE("--- a/");
4194 break;
4198 if (diff == line || !file) {
4199 report("Failed to read the file name");
4200 return REQ_NONE;
4203 chunk_data = chunk->data;
4205 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4206 report("Failed to read the line number");
4207 return REQ_NONE;
4210 if (lineno == 0) {
4211 report("This is the origin of the line");
4212 return REQ_NONE;
4215 for (chunk += 1; chunk < line; chunk++) {
4216 if (chunk->type == LINE_DIFF_ADD) {
4217 lineno += chunk_marker == '+';
4218 } else if (chunk->type == LINE_DIFF_DEL) {
4219 lineno += chunk_marker == '-';
4220 } else {
4221 lineno++;
4225 if (chunk_marker == '+')
4226 string_copy(ref, view->vid);
4227 else
4228 string_format(ref, "%s^", view->vid);
4230 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4231 report("Failed to read blame data");
4232 return REQ_NONE;
4235 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4236 string_copy(opt_ref, header.id);
4237 opt_goto_line = header.orig_lineno - 1;
4239 return REQ_VIEW_BLAME;
4242 static enum request
4243 diff_request(struct view *view, enum request request, struct line *line)
4245 switch (request) {
4246 case REQ_VIEW_BLAME:
4247 return diff_trace_origin(view, line);
4249 case REQ_DIFF_CONTEXT_UP:
4250 case REQ_DIFF_CONTEXT_DOWN:
4251 if (!update_diff_context(request))
4252 return REQ_NONE;
4253 reload_view(view);
4254 return REQ_NONE;
4257 case REQ_ENTER:
4258 return diff_common_enter(view, request, line);
4260 default:
4261 return pager_request(view, request, line);
4265 static void
4266 diff_select(struct view *view, struct line *line)
4268 if (line->type == LINE_DIFF_STAT) {
4269 const char *key = get_view_key(view, REQ_ENTER);
4271 string_format(view->ref, "Press '%s' to jump to file diff", key);
4272 } else {
4273 string_ncopy(view->ref, view->id, strlen(view->id));
4274 return pager_select(view, line);
4278 static struct view_ops diff_ops = {
4279 "line",
4280 { "diff" },
4281 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS,
4282 sizeof(struct diff_state),
4283 diff_open,
4284 diff_read,
4285 diff_common_draw,
4286 diff_request,
4287 pager_grep,
4288 diff_select,
4292 * Help backend
4295 static bool
4296 help_draw(struct view *view, struct line *line, unsigned int lineno)
4298 if (line->type == LINE_HELP_KEYMAP) {
4299 struct keymap *keymap = line->data;
4301 draw_formatted(view, line->type, "[%c] %s bindings",
4302 keymap->hidden ? '+' : '-', keymap->name);
4303 return TRUE;
4304 } else {
4305 return pager_draw(view, line, lineno);
4309 static bool
4310 help_open_keymap_title(struct view *view, struct keymap *keymap)
4312 add_line_static_data(view, keymap, LINE_HELP_KEYMAP);
4313 return keymap->hidden;
4316 static void
4317 help_open_keymap(struct view *view, struct keymap *keymap)
4319 const char *group = NULL;
4320 char buf[SIZEOF_STR];
4321 size_t bufpos;
4322 bool add_title = TRUE;
4323 int i;
4325 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4326 const char *key = NULL;
4328 if (req_info[i].request == REQ_NONE)
4329 continue;
4331 if (!req_info[i].request) {
4332 group = req_info[i].help;
4333 continue;
4336 key = get_keys(keymap, req_info[i].request, TRUE);
4337 if (!key || !*key)
4338 continue;
4340 if (add_title && help_open_keymap_title(view, keymap))
4341 return;
4342 add_title = FALSE;
4344 if (group) {
4345 add_line_text(view, group, LINE_HELP_GROUP);
4346 group = NULL;
4349 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4350 enum_name(req_info[i]), req_info[i].help);
4353 group = "External commands:";
4355 for (i = 0; i < run_requests; i++) {
4356 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4357 const char *key;
4358 int argc;
4360 if (!req || req->keymap != keymap)
4361 continue;
4363 key = get_key_name(req->key);
4364 if (!*key)
4365 key = "(no key defined)";
4367 if (add_title && help_open_keymap_title(view, keymap))
4368 return;
4369 add_title = FALSE;
4371 if (group) {
4372 add_line_text(view, group, LINE_HELP_GROUP);
4373 group = NULL;
4376 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
4377 if (!string_format_from(buf, &bufpos, "%s%s",
4378 argc ? " " : "", req->argv[argc]))
4379 return;
4381 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4385 static bool
4386 help_open(struct view *view, enum open_flags flags)
4388 struct keymap *keymap;
4390 reset_view(view);
4391 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4392 add_line_text(view, "", LINE_DEFAULT);
4394 for (keymap = keymaps; keymap; keymap = keymap->next)
4395 help_open_keymap(view, keymap);
4397 return TRUE;
4400 static enum request
4401 help_request(struct view *view, enum request request, struct line *line)
4403 switch (request) {
4404 case REQ_ENTER:
4405 if (line->type == LINE_HELP_KEYMAP) {
4406 struct keymap *keymap = line->data;
4408 keymap->hidden = !keymap->hidden;
4409 refresh_view(view);
4412 return REQ_NONE;
4413 default:
4414 return pager_request(view, request, line);
4418 static struct view_ops help_ops = {
4419 "line",
4420 { "help" },
4421 VIEW_NO_GIT_DIR,
4423 help_open,
4424 NULL,
4425 help_draw,
4426 help_request,
4427 pager_grep,
4428 pager_select,
4433 * Tree backend
4436 struct tree_stack_entry {
4437 struct tree_stack_entry *prev; /* Entry below this in the stack */
4438 unsigned long lineno; /* Line number to restore */
4439 char *name; /* Position of name in opt_path */
4442 /* The top of the path stack. */
4443 static struct tree_stack_entry *tree_stack = NULL;
4444 unsigned long tree_lineno = 0;
4446 static void
4447 pop_tree_stack_entry(void)
4449 struct tree_stack_entry *entry = tree_stack;
4451 tree_lineno = entry->lineno;
4452 entry->name[0] = 0;
4453 tree_stack = entry->prev;
4454 free(entry);
4457 static void
4458 push_tree_stack_entry(const char *name, unsigned long lineno)
4460 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4461 size_t pathlen = strlen(opt_path);
4463 if (!entry)
4464 return;
4466 entry->prev = tree_stack;
4467 entry->name = opt_path + pathlen;
4468 tree_stack = entry;
4470 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4471 pop_tree_stack_entry();
4472 return;
4475 /* Move the current line to the first tree entry. */
4476 tree_lineno = 1;
4477 entry->lineno = lineno;
4480 /* Parse output from git-ls-tree(1):
4482 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4485 #define SIZEOF_TREE_ATTR \
4486 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4488 #define SIZEOF_TREE_MODE \
4489 STRING_SIZE("100644 ")
4491 #define TREE_ID_OFFSET \
4492 STRING_SIZE("100644 blob ")
4494 struct tree_entry {
4495 char id[SIZEOF_REV];
4496 mode_t mode;
4497 struct time time; /* Date from the author ident. */
4498 const char *author; /* Author of the commit. */
4499 char name[1];
4502 struct tree_state {
4503 const char *author_name;
4504 struct time author_time;
4505 bool read_date;
4508 static const char *
4509 tree_path(const struct line *line)
4511 return ((struct tree_entry *) line->data)->name;
4514 static int
4515 tree_compare_entry(const struct line *line1, const struct line *line2)
4517 if (line1->type != line2->type)
4518 return line1->type == LINE_TREE_DIR ? -1 : 1;
4519 return strcmp(tree_path(line1), tree_path(line2));
4522 static const enum sort_field tree_sort_fields[] = {
4523 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4525 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4527 static int
4528 tree_compare(const void *l1, const void *l2)
4530 const struct line *line1 = (const struct line *) l1;
4531 const struct line *line2 = (const struct line *) l2;
4532 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4533 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4535 if (line1->type == LINE_TREE_HEAD)
4536 return -1;
4537 if (line2->type == LINE_TREE_HEAD)
4538 return 1;
4540 switch (get_sort_field(tree_sort_state)) {
4541 case ORDERBY_DATE:
4542 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4544 case ORDERBY_AUTHOR:
4545 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4547 case ORDERBY_NAME:
4548 default:
4549 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4554 static struct line *
4555 tree_entry(struct view *view, enum line_type type, const char *path,
4556 const char *mode, const char *id)
4558 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4559 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4561 if (!entry || !line) {
4562 free(entry);
4563 return NULL;
4566 strncpy(entry->name, path, strlen(path));
4567 if (mode)
4568 entry->mode = strtoul(mode, NULL, 8);
4569 if (id)
4570 string_copy_rev(entry->id, id);
4572 return line;
4575 static bool
4576 tree_read_date(struct view *view, char *text, struct tree_state *state)
4578 if (!text && state->read_date) {
4579 state->read_date = FALSE;
4580 return TRUE;
4582 } else if (!text) {
4583 /* Find next entry to process */
4584 const char *log_file[] = {
4585 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
4586 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4589 if (!view->lines) {
4590 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4591 report("Tree is empty");
4592 return TRUE;
4595 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4596 report("Failed to load tree data");
4597 return TRUE;
4600 state->read_date = TRUE;
4601 return FALSE;
4603 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4604 parse_author_line(text + STRING_SIZE("author "),
4605 &state->author_name, &state->author_time);
4607 } else if (*text == ':') {
4608 char *pos;
4609 size_t annotated = 1;
4610 size_t i;
4612 pos = strchr(text, '\t');
4613 if (!pos)
4614 return TRUE;
4615 text = pos + 1;
4616 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4617 text += strlen(opt_path);
4618 pos = strchr(text, '/');
4619 if (pos)
4620 *pos = 0;
4622 for (i = 1; i < view->lines; i++) {
4623 struct line *line = &view->line[i];
4624 struct tree_entry *entry = line->data;
4626 annotated += !!entry->author;
4627 if (entry->author || strcmp(entry->name, text))
4628 continue;
4630 entry->author = state->author_name;
4631 entry->time = state->author_time;
4632 line->dirty = 1;
4633 break;
4636 if (annotated == view->lines)
4637 io_kill(view->pipe);
4639 return TRUE;
4642 static bool
4643 tree_read(struct view *view, char *text)
4645 struct tree_state *state = view->private;
4646 struct tree_entry *data;
4647 struct line *entry, *line;
4648 enum line_type type;
4649 size_t textlen = text ? strlen(text) : 0;
4650 char *path = text + SIZEOF_TREE_ATTR;
4652 if (state->read_date || !text)
4653 return tree_read_date(view, text, state);
4655 if (textlen <= SIZEOF_TREE_ATTR)
4656 return FALSE;
4657 if (view->lines == 0 &&
4658 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4659 return FALSE;
4661 /* Strip the path part ... */
4662 if (*opt_path) {
4663 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4664 size_t striplen = strlen(opt_path);
4666 if (pathlen > striplen)
4667 memmove(path, path + striplen,
4668 pathlen - striplen + 1);
4670 /* Insert "link" to parent directory. */
4671 if (view->lines == 1 &&
4672 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4673 return FALSE;
4676 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4677 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4678 if (!entry)
4679 return FALSE;
4680 data = entry->data;
4682 /* Skip "Directory ..." and ".." line. */
4683 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4684 if (tree_compare_entry(line, entry) <= 0)
4685 continue;
4687 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4689 line->data = data;
4690 line->type = type;
4691 for (; line <= entry; line++)
4692 line->dirty = line->cleareol = 1;
4693 return TRUE;
4696 if (tree_lineno > view->pos.lineno) {
4697 view->pos.lineno = tree_lineno;
4698 tree_lineno = 0;
4701 return TRUE;
4704 static bool
4705 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4707 struct tree_entry *entry = line->data;
4709 if (line->type == LINE_TREE_HEAD) {
4710 if (draw_text(view, line->type, "Directory path /"))
4711 return TRUE;
4712 } else {
4713 if (draw_mode(view, entry->mode))
4714 return TRUE;
4716 if (draw_author(view, entry->author))
4717 return TRUE;
4719 if (draw_date(view, &entry->time))
4720 return TRUE;
4723 draw_text(view, line->type, entry->name);
4724 return TRUE;
4727 static void
4728 open_blob_editor(const char *id)
4730 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4731 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4732 int fd = mkstemp(file);
4734 if (fd == -1)
4735 report("Failed to create temporary file");
4736 else if (!io_run_append(blob_argv, fd))
4737 report("Failed to save blob data to file");
4738 else
4739 open_editor(file);
4740 if (fd != -1)
4741 unlink(file);
4744 static enum request
4745 tree_request(struct view *view, enum request request, struct line *line)
4747 enum open_flags flags;
4748 struct tree_entry *entry = line->data;
4750 switch (request) {
4751 case REQ_VIEW_BLAME:
4752 if (line->type != LINE_TREE_FILE) {
4753 report("Blame only supported for files");
4754 return REQ_NONE;
4757 string_copy(opt_ref, view->vid);
4758 return request;
4760 case REQ_EDIT:
4761 if (line->type != LINE_TREE_FILE) {
4762 report("Edit only supported for files");
4763 } else if (!is_head_commit(view->vid)) {
4764 open_blob_editor(entry->id);
4765 } else {
4766 open_editor(opt_file);
4768 return REQ_NONE;
4770 case REQ_TOGGLE_SORT_FIELD:
4771 case REQ_TOGGLE_SORT_ORDER:
4772 sort_view(view, request, &tree_sort_state, tree_compare);
4773 return REQ_NONE;
4775 case REQ_PARENT:
4776 if (!*opt_path) {
4777 /* quit view if at top of tree */
4778 return REQ_VIEW_CLOSE;
4780 /* fake 'cd ..' */
4781 line = &view->line[1];
4782 break;
4784 case REQ_ENTER:
4785 break;
4787 default:
4788 return request;
4791 /* Cleanup the stack if the tree view is at a different tree. */
4792 while (!*opt_path && tree_stack)
4793 pop_tree_stack_entry();
4795 switch (line->type) {
4796 case LINE_TREE_DIR:
4797 /* Depending on whether it is a subdirectory or parent link
4798 * mangle the path buffer. */
4799 if (line == &view->line[1] && *opt_path) {
4800 pop_tree_stack_entry();
4802 } else {
4803 const char *basename = tree_path(line);
4805 push_tree_stack_entry(basename, view->pos.lineno);
4808 /* Trees and subtrees share the same ID, so they are not not
4809 * unique like blobs. */
4810 flags = OPEN_RELOAD;
4811 request = REQ_VIEW_TREE;
4812 break;
4814 case LINE_TREE_FILE:
4815 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4816 request = REQ_VIEW_BLOB;
4817 break;
4819 default:
4820 return REQ_NONE;
4823 open_view(view, request, flags);
4824 if (request == REQ_VIEW_TREE)
4825 view->pos.lineno = tree_lineno;
4827 return REQ_NONE;
4830 static bool
4831 tree_grep(struct view *view, struct line *line)
4833 struct tree_entry *entry = line->data;
4834 const char *text[] = {
4835 entry->name,
4836 mkauthor(entry->author, opt_author_cols, opt_author),
4837 mkdate(&entry->time, opt_date),
4838 NULL
4841 return grep_text(view, text);
4844 static void
4845 tree_select(struct view *view, struct line *line)
4847 struct tree_entry *entry = line->data;
4849 if (line->type == LINE_TREE_FILE) {
4850 string_copy_rev(ref_blob, entry->id);
4851 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4853 } else if (line->type != LINE_TREE_DIR) {
4854 return;
4857 string_copy_rev(view->ref, entry->id);
4860 static bool
4861 tree_open(struct view *view, enum open_flags flags)
4863 static const char *tree_argv[] = {
4864 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4867 if (view->lines == 0 && opt_prefix[0]) {
4868 char *pos = opt_prefix;
4870 while (pos && *pos) {
4871 char *end = strchr(pos, '/');
4873 if (end)
4874 *end = 0;
4875 push_tree_stack_entry(pos, 0);
4876 pos = end;
4877 if (end) {
4878 *end = '/';
4879 pos++;
4883 } else if (strcmp(view->vid, view->id)) {
4884 opt_path[0] = 0;
4887 return begin_update(view, opt_cdup, tree_argv, flags);
4890 static struct view_ops tree_ops = {
4891 "file",
4892 { "tree" },
4893 VIEW_NO_FLAGS,
4894 sizeof(struct tree_state),
4895 tree_open,
4896 tree_read,
4897 tree_draw,
4898 tree_request,
4899 tree_grep,
4900 tree_select,
4903 static bool
4904 blob_open(struct view *view, enum open_flags flags)
4906 static const char *blob_argv[] = {
4907 "git", "cat-file", "blob", "%(blob)", NULL
4910 view->encoding = get_path_encoding(opt_file, opt_encoding);
4912 return begin_update(view, NULL, blob_argv, flags);
4915 static bool
4916 blob_read(struct view *view, char *line)
4918 if (!line)
4919 return TRUE;
4920 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4923 static enum request
4924 blob_request(struct view *view, enum request request, struct line *line)
4926 switch (request) {
4927 case REQ_EDIT:
4928 open_blob_editor(view->vid);
4929 return REQ_NONE;
4930 default:
4931 return pager_request(view, request, line);
4935 static struct view_ops blob_ops = {
4936 "line",
4937 { "blob" },
4938 VIEW_NO_FLAGS,
4940 blob_open,
4941 blob_read,
4942 pager_draw,
4943 blob_request,
4944 pager_grep,
4945 pager_select,
4949 * Blame backend
4951 * Loading the blame view is a two phase job:
4953 * 1. File content is read either using opt_file from the
4954 * filesystem or using git-cat-file.
4955 * 2. Then blame information is incrementally added by
4956 * reading output from git-blame.
4959 struct blame {
4960 struct blame_commit *commit;
4961 unsigned long lineno;
4962 char text[1];
4965 struct blame_state {
4966 struct blame_commit *commit;
4967 int blamed;
4968 bool done_reading;
4969 bool auto_filename_display;
4972 static bool
4973 blame_detect_filename_display(struct view *view)
4975 bool show_filenames = FALSE;
4976 const char *filename = NULL;
4977 int i;
4979 if (opt_blame_argv) {
4980 for (i = 0; opt_blame_argv[i]; i++) {
4981 if (prefixcmp(opt_blame_argv[i], "-C"))
4982 continue;
4984 show_filenames = TRUE;
4988 for (i = 0; i < view->lines; i++) {
4989 struct blame *blame = view->line[i].data;
4991 if (blame->commit && blame->commit->id[0]) {
4992 if (!filename)
4993 filename = blame->commit->filename;
4994 else if (strcmp(filename, blame->commit->filename))
4995 show_filenames = TRUE;
4999 return show_filenames;
5002 static bool
5003 blame_open(struct view *view, enum open_flags flags)
5005 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5006 char path[SIZEOF_STR];
5007 size_t i;
5009 if (!view->prev && *opt_prefix) {
5010 string_copy(path, opt_file);
5011 if (!string_format(opt_file, "%s%s", opt_prefix, path))
5012 return FALSE;
5015 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5016 const char *blame_cat_file_argv[] = {
5017 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5020 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5021 return FALSE;
5024 /* First pass: remove multiple references to the same commit. */
5025 for (i = 0; i < view->lines; i++) {
5026 struct blame *blame = view->line[i].data;
5028 if (blame->commit && blame->commit->id[0])
5029 blame->commit->id[0] = 0;
5030 else
5031 blame->commit = NULL;
5034 /* Second pass: free existing references. */
5035 for (i = 0; i < view->lines; i++) {
5036 struct blame *blame = view->line[i].data;
5038 if (blame->commit)
5039 free(blame->commit);
5042 string_format(view->vid, "%s", opt_file);
5043 string_format(view->ref, "%s ...", opt_file);
5045 return TRUE;
5048 static struct blame_commit *
5049 get_blame_commit(struct view *view, const char *id)
5051 size_t i;
5053 for (i = 0; i < view->lines; i++) {
5054 struct blame *blame = view->line[i].data;
5056 if (!blame->commit)
5057 continue;
5059 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5060 return blame->commit;
5064 struct blame_commit *commit = calloc(1, sizeof(*commit));
5066 if (commit)
5067 string_ncopy(commit->id, id, SIZEOF_REV);
5068 return commit;
5072 static struct blame_commit *
5073 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5075 struct blame_header header;
5076 struct blame_commit *commit;
5077 struct blame *blame;
5079 if (!parse_blame_header(&header, text, view->lines))
5080 return NULL;
5082 commit = get_blame_commit(view, text);
5083 if (!commit)
5084 return NULL;
5086 state->blamed += header.group;
5087 while (header.group--) {
5088 struct line *line = &view->line[header.lineno + header.group - 1];
5090 blame = line->data;
5091 blame->commit = commit;
5092 blame->lineno = header.orig_lineno + header.group - 1;
5093 line->dirty = 1;
5096 return commit;
5099 static bool
5100 blame_read_file(struct view *view, const char *line, struct blame_state *state)
5102 if (!line) {
5103 const char *blame_argv[] = {
5104 "git", "blame", ENCODING_ARG, "%(blameargs)", "--incremental",
5105 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5108 if (view->lines == 0 && !view->prev)
5109 die("No blame exist for %s", view->vid);
5111 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5112 report("Failed to load blame data");
5113 return TRUE;
5116 if (opt_goto_line > 0) {
5117 select_view_line(view, opt_goto_line);
5118 opt_goto_line = 0;
5121 state->done_reading = TRUE;
5122 return FALSE;
5124 } else {
5125 size_t linelen = strlen(line);
5126 struct blame *blame = malloc(sizeof(*blame) + linelen);
5128 if (!blame)
5129 return FALSE;
5131 blame->commit = NULL;
5132 strncpy(blame->text, line, linelen);
5133 blame->text[linelen] = 0;
5134 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
5138 static bool
5139 blame_read(struct view *view, char *line)
5141 struct blame_state *state = view->private;
5143 if (!state->done_reading)
5144 return blame_read_file(view, line, state);
5146 if (!line) {
5147 state->auto_filename_display = blame_detect_filename_display(view);
5148 string_format(view->ref, "%s", view->vid);
5149 if (view_is_displayed(view)) {
5150 update_view_title(view);
5151 redraw_view_from(view, 0);
5153 return TRUE;
5156 if (!state->commit) {
5157 state->commit = read_blame_commit(view, line, state);
5158 string_format(view->ref, "%s %2d%%", view->vid,
5159 view->lines ? state->blamed * 100 / view->lines : 0);
5161 } else if (parse_blame_info(state->commit, line)) {
5162 state->commit = NULL;
5165 return TRUE;
5168 static bool
5169 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5171 struct blame_state *state = view->private;
5172 struct blame *blame = line->data;
5173 struct time *time = NULL;
5174 const char *id = NULL, *author = NULL, *filename = NULL;
5175 enum line_type id_type = LINE_BLAME_ID;
5176 static const enum line_type blame_colors[] = {
5177 LINE_PALETTE_0,
5178 LINE_PALETTE_1,
5179 LINE_PALETTE_2,
5180 LINE_PALETTE_3,
5181 LINE_PALETTE_4,
5182 LINE_PALETTE_5,
5183 LINE_PALETTE_6,
5186 #define BLAME_COLOR(i) \
5187 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5189 if (blame->commit && *blame->commit->filename) {
5190 id = blame->commit->id;
5191 author = blame->commit->author;
5192 filename = blame->commit->filename;
5193 time = &blame->commit->time;
5194 id_type = BLAME_COLOR((long) blame->commit);
5197 if (draw_date(view, time))
5198 return TRUE;
5200 if (draw_author(view, author))
5201 return TRUE;
5203 if (draw_filename(view, filename, state->auto_filename_display))
5204 return TRUE;
5206 if (draw_field(view, id_type, id, ID_COLS, FALSE))
5207 return TRUE;
5209 if (draw_lineno(view, lineno))
5210 return TRUE;
5212 draw_text(view, LINE_DEFAULT, blame->text);
5213 return TRUE;
5216 static bool
5217 check_blame_commit(struct blame *blame, bool check_null_id)
5219 if (!blame->commit)
5220 report("Commit data not loaded yet");
5221 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
5222 report("No commit exist for the selected line");
5223 else
5224 return TRUE;
5225 return FALSE;
5228 static void
5229 setup_blame_parent_line(struct view *view, struct blame *blame)
5231 char from[SIZEOF_REF + SIZEOF_STR];
5232 char to[SIZEOF_REF + SIZEOF_STR];
5233 const char *diff_tree_argv[] = {
5234 "git", "diff", ENCODING_ARG, "--no-textconv", "--no-extdiff",
5235 "--no-color", "-U0", from, to, "--", NULL
5237 struct io io;
5238 int parent_lineno = -1;
5239 int blamed_lineno = -1;
5240 char *line;
5242 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5243 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5244 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5245 return;
5247 while ((line = io_get(&io, '\n', TRUE))) {
5248 if (*line == '@') {
5249 char *pos = strchr(line, '+');
5251 parent_lineno = atoi(line + 4);
5252 if (pos)
5253 blamed_lineno = atoi(pos + 1);
5255 } else if (*line == '+' && parent_lineno != -1) {
5256 if (blame->lineno == blamed_lineno - 1 &&
5257 !strcmp(blame->text, line + 1)) {
5258 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
5259 break;
5261 blamed_lineno++;
5265 io_done(&io);
5268 static enum request
5269 blame_request(struct view *view, enum request request, struct line *line)
5271 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5272 struct blame *blame = line->data;
5274 switch (request) {
5275 case REQ_VIEW_BLAME:
5276 if (check_blame_commit(blame, TRUE)) {
5277 string_copy(opt_ref, blame->commit->id);
5278 string_copy(opt_file, blame->commit->filename);
5279 if (blame->lineno)
5280 view->pos.lineno = blame->lineno;
5281 reload_view(view);
5283 break;
5285 case REQ_PARENT:
5286 if (!check_blame_commit(blame, TRUE))
5287 break;
5288 if (!*blame->commit->parent_id) {
5289 report("The selected commit has no parents");
5290 } else {
5291 string_copy_rev(opt_ref, blame->commit->parent_id);
5292 string_copy(opt_file, blame->commit->parent_filename);
5293 setup_blame_parent_line(view, blame);
5294 opt_goto_line = blame->lineno;
5295 reload_view(view);
5297 break;
5299 case REQ_ENTER:
5300 if (!check_blame_commit(blame, FALSE))
5301 break;
5303 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5304 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5305 break;
5307 if (!strcmp(blame->commit->id, NULL_ID)) {
5308 struct view *diff = VIEW(REQ_VIEW_DIFF);
5309 const char *diff_parent_argv[] = {
5310 GIT_DIFF_BLAME(opt_diff_context_arg,
5311 opt_ignore_space_arg, view->vid)
5313 const char *diff_no_parent_argv[] = {
5314 GIT_DIFF_BLAME_NO_PARENT(opt_diff_context_arg,
5315 opt_ignore_space_arg, view->vid)
5317 const char **diff_index_argv = *blame->commit->parent_id
5318 ? diff_parent_argv : diff_no_parent_argv;
5320 open_argv(view, diff, diff_index_argv, NULL, flags);
5321 if (diff->pipe)
5322 string_copy_rev(diff->ref, NULL_ID);
5323 } else {
5324 open_view(view, REQ_VIEW_DIFF, flags);
5326 break;
5328 default:
5329 return request;
5332 return REQ_NONE;
5335 static bool
5336 blame_grep(struct view *view, struct line *line)
5338 struct blame *blame = line->data;
5339 struct blame_commit *commit = blame->commit;
5340 const char *text[] = {
5341 blame->text,
5342 commit ? commit->title : "",
5343 commit ? commit->id : "",
5344 commit && opt_author ? commit->author : "",
5345 commit ? mkdate(&commit->time, opt_date) : "",
5346 NULL
5349 return grep_text(view, text);
5352 static void
5353 blame_select(struct view *view, struct line *line)
5355 struct blame *blame = line->data;
5356 struct blame_commit *commit = blame->commit;
5358 if (!commit)
5359 return;
5361 if (!strcmp(commit->id, NULL_ID))
5362 string_ncopy(ref_commit, "HEAD", 4);
5363 else
5364 string_copy_rev(ref_commit, commit->id);
5367 static struct view_ops blame_ops = {
5368 "line",
5369 { "blame" },
5370 VIEW_ALWAYS_LINENO,
5371 sizeof(struct blame_state),
5372 blame_open,
5373 blame_read,
5374 blame_draw,
5375 blame_request,
5376 blame_grep,
5377 blame_select,
5381 * Branch backend
5384 struct branch {
5385 const char *author; /* Author of the last commit. */
5386 struct time time; /* Date of the last activity. */
5387 const struct ref *ref; /* Name and commit ID information. */
5390 static const struct ref branch_all;
5392 static const enum sort_field branch_sort_fields[] = {
5393 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5395 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5397 struct branch_state {
5398 char id[SIZEOF_REV];
5401 static int
5402 branch_compare(const void *l1, const void *l2)
5404 const struct branch *branch1 = ((const struct line *) l1)->data;
5405 const struct branch *branch2 = ((const struct line *) l2)->data;
5407 if (branch1->ref == &branch_all)
5408 return -1;
5409 else if (branch2->ref == &branch_all)
5410 return 1;
5412 switch (get_sort_field(branch_sort_state)) {
5413 case ORDERBY_DATE:
5414 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5416 case ORDERBY_AUTHOR:
5417 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5419 case ORDERBY_NAME:
5420 default:
5421 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5425 static bool
5426 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5428 struct branch *branch = line->data;
5429 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5431 if (draw_date(view, &branch->time))
5432 return TRUE;
5434 if (draw_author(view, branch->author))
5435 return TRUE;
5437 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
5438 return TRUE;
5441 static enum request
5442 branch_request(struct view *view, enum request request, struct line *line)
5444 struct branch *branch = line->data;
5446 switch (request) {
5447 case REQ_REFRESH:
5448 load_refs();
5449 refresh_view(view);
5450 return REQ_NONE;
5452 case REQ_TOGGLE_SORT_FIELD:
5453 case REQ_TOGGLE_SORT_ORDER:
5454 sort_view(view, request, &branch_sort_state, branch_compare);
5455 return REQ_NONE;
5457 case REQ_ENTER:
5459 const struct ref *ref = branch->ref;
5460 const char *all_branches_argv[] = {
5461 "git", "log", ENCODING_ARG, "--no-color",
5462 "--pretty=raw", "--parents", opt_commit_order_arg,
5463 ref == &branch_all ? "--all" : ref->name, NULL
5465 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5467 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5468 return REQ_NONE;
5470 case REQ_JUMP_COMMIT:
5472 int lineno;
5474 for (lineno = 0; lineno < view->lines; lineno++) {
5475 struct branch *branch = view->line[lineno].data;
5477 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5478 select_view_line(view, lineno);
5479 report("");
5480 return REQ_NONE;
5484 default:
5485 return request;
5489 static bool
5490 branch_read(struct view *view, char *line)
5492 struct branch_state *state = view->private;
5493 struct branch *reference;
5494 size_t i;
5496 if (!line)
5497 return TRUE;
5499 switch (get_line_type(line)) {
5500 case LINE_COMMIT:
5501 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5502 return TRUE;
5504 case LINE_AUTHOR:
5505 for (i = 0, reference = NULL; i < view->lines; i++) {
5506 struct branch *branch = view->line[i].data;
5508 if (strcmp(branch->ref->id, state->id))
5509 continue;
5511 view->line[i].dirty = TRUE;
5512 if (reference) {
5513 branch->author = reference->author;
5514 branch->time = reference->time;
5515 continue;
5518 parse_author_line(line + STRING_SIZE("author "),
5519 &branch->author, &branch->time);
5520 reference = branch;
5522 return TRUE;
5524 default:
5525 return TRUE;
5530 static bool
5531 branch_open_visitor(void *data, const struct ref *ref)
5533 struct view *view = data;
5534 struct branch *branch;
5536 if (ref->tag || ref->ltag)
5537 return TRUE;
5539 branch = calloc(1, sizeof(*branch));
5540 if (!branch)
5541 return FALSE;
5543 branch->ref = ref;
5544 return !!add_line_data(view, branch, LINE_DEFAULT);
5547 static bool
5548 branch_open(struct view *view, enum open_flags flags)
5550 const char *branch_log[] = {
5551 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
5552 "--simplify-by-decoration", "--all", NULL
5555 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
5556 report("Failed to load branch data");
5557 return TRUE;
5560 branch_open_visitor(view, &branch_all);
5561 foreach_ref(branch_open_visitor, view);
5563 return TRUE;
5566 static bool
5567 branch_grep(struct view *view, struct line *line)
5569 struct branch *branch = line->data;
5570 const char *text[] = {
5571 branch->ref->name,
5572 mkauthor(branch->author, opt_author_cols, opt_author),
5573 NULL
5576 return grep_text(view, text);
5579 static void
5580 branch_select(struct view *view, struct line *line)
5582 struct branch *branch = line->data;
5584 string_copy_rev(view->ref, branch->ref->id);
5585 string_copy_rev(ref_commit, branch->ref->id);
5586 string_copy_rev(ref_head, branch->ref->id);
5587 string_copy_rev(ref_branch, branch->ref->name);
5590 static struct view_ops branch_ops = {
5591 "branch",
5592 { "branch" },
5593 VIEW_NO_FLAGS,
5594 sizeof(struct branch_state),
5595 branch_open,
5596 branch_read,
5597 branch_draw,
5598 branch_request,
5599 branch_grep,
5600 branch_select,
5604 * Status backend
5607 struct status {
5608 char status;
5609 struct {
5610 mode_t mode;
5611 char rev[SIZEOF_REV];
5612 char name[SIZEOF_STR];
5613 } old;
5614 struct {
5615 mode_t mode;
5616 char rev[SIZEOF_REV];
5617 char name[SIZEOF_STR];
5618 } new;
5621 static char status_onbranch[SIZEOF_STR];
5622 static struct status stage_status;
5623 static enum line_type stage_line_type;
5625 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5627 /* This should work even for the "On branch" line. */
5628 static inline bool
5629 status_has_none(struct view *view, struct line *line)
5631 return line < view->line + view->lines && !line[1].data;
5634 /* Get fields from the diff line:
5635 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5637 static inline bool
5638 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5640 const char *old_mode = buf + 1;
5641 const char *new_mode = buf + 8;
5642 const char *old_rev = buf + 15;
5643 const char *new_rev = buf + 56;
5644 const char *status = buf + 97;
5646 if (bufsize < 98 ||
5647 old_mode[-1] != ':' ||
5648 new_mode[-1] != ' ' ||
5649 old_rev[-1] != ' ' ||
5650 new_rev[-1] != ' ' ||
5651 status[-1] != ' ')
5652 return FALSE;
5654 file->status = *status;
5656 string_copy_rev(file->old.rev, old_rev);
5657 string_copy_rev(file->new.rev, new_rev);
5659 file->old.mode = strtoul(old_mode, NULL, 8);
5660 file->new.mode = strtoul(new_mode, NULL, 8);
5662 file->old.name[0] = file->new.name[0] = 0;
5664 return TRUE;
5667 static bool
5668 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5670 struct status *unmerged = NULL;
5671 char *buf;
5672 struct io io;
5674 if (!io_run(&io, IO_RD, opt_cdup, argv))
5675 return FALSE;
5677 add_line_data(view, NULL, type);
5679 while ((buf = io_get(&io, 0, TRUE))) {
5680 struct status *file = unmerged;
5682 if (!file) {
5683 file = calloc(1, sizeof(*file));
5684 if (!file || !add_line_data(view, file, type))
5685 goto error_out;
5688 /* Parse diff info part. */
5689 if (status) {
5690 file->status = status;
5691 if (status == 'A')
5692 string_copy(file->old.rev, NULL_ID);
5694 } else if (!file->status || file == unmerged) {
5695 if (!status_get_diff(file, buf, strlen(buf)))
5696 goto error_out;
5698 buf = io_get(&io, 0, TRUE);
5699 if (!buf)
5700 break;
5702 /* Collapse all modified entries that follow an
5703 * associated unmerged entry. */
5704 if (unmerged == file) {
5705 unmerged->status = 'U';
5706 unmerged = NULL;
5707 } else if (file->status == 'U') {
5708 unmerged = file;
5712 /* Grab the old name for rename/copy. */
5713 if (!*file->old.name &&
5714 (file->status == 'R' || file->status == 'C')) {
5715 string_ncopy(file->old.name, buf, strlen(buf));
5717 buf = io_get(&io, 0, TRUE);
5718 if (!buf)
5719 break;
5722 /* git-ls-files just delivers a NUL separated list of
5723 * file names similar to the second half of the
5724 * git-diff-* output. */
5725 string_ncopy(file->new.name, buf, strlen(buf));
5726 if (!*file->old.name)
5727 string_copy(file->old.name, file->new.name);
5728 file = NULL;
5731 if (io_error(&io)) {
5732 error_out:
5733 io_done(&io);
5734 return FALSE;
5737 if (!view->line[view->lines - 1].data)
5738 add_line_data(view, NULL, LINE_STAT_NONE);
5740 io_done(&io);
5741 return TRUE;
5744 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
5745 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
5747 static const char *status_list_other_argv[] = {
5748 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5751 static const char *status_list_no_head_argv[] = {
5752 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5755 static const char *update_index_argv[] = {
5756 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5759 /* Restore the previous line number to stay in the context or select a
5760 * line with something that can be updated. */
5761 static void
5762 status_restore(struct view *view)
5764 if (view->prev_pos.lineno >= view->lines)
5765 view->prev_pos.lineno = view->lines - 1;
5766 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
5767 view->prev_pos.lineno++;
5768 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
5769 view->prev_pos.lineno--;
5771 /* If the above fails, always skip the "On branch" line. */
5772 if (view->prev_pos.lineno < view->lines)
5773 view->pos.lineno = view->prev_pos.lineno;
5774 else
5775 view->pos.lineno = 1;
5777 if (view->prev_pos.offset > view->pos.lineno)
5778 view->pos.offset = view->pos.lineno;
5779 else if (view->prev_pos.offset < view->lines)
5780 view->pos.offset = view->prev_pos.offset;
5782 clear_position(&view->prev_pos);
5785 static void
5786 status_update_onbranch(void)
5788 static const char *paths[][2] = {
5789 { "rebase-apply/rebasing", "Rebasing" },
5790 { "rebase-apply/applying", "Applying mailbox" },
5791 { "rebase-apply/", "Rebasing mailbox" },
5792 { "rebase-merge/interactive", "Interactive rebase" },
5793 { "rebase-merge/", "Rebase merge" },
5794 { "MERGE_HEAD", "Merging" },
5795 { "BISECT_LOG", "Bisecting" },
5796 { "HEAD", "On branch" },
5798 char buf[SIZEOF_STR];
5799 struct stat stat;
5800 int i;
5802 if (is_initial_commit()) {
5803 string_copy(status_onbranch, "Initial commit");
5804 return;
5807 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5808 char *head = opt_head;
5810 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5811 lstat(buf, &stat) < 0)
5812 continue;
5814 if (!*opt_head) {
5815 struct io io;
5817 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5818 io_read_buf(&io, buf, sizeof(buf))) {
5819 head = buf;
5820 if (!prefixcmp(head, "refs/heads/"))
5821 head += STRING_SIZE("refs/heads/");
5825 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5826 string_copy(status_onbranch, opt_head);
5827 return;
5830 string_copy(status_onbranch, "Not currently on any branch");
5833 /* First parse staged info using git-diff-index(1), then parse unstaged
5834 * info using git-diff-files(1), and finally untracked files using
5835 * git-ls-files(1). */
5836 static bool
5837 status_open(struct view *view, enum open_flags flags)
5839 reset_view(view);
5841 add_line_data(view, NULL, LINE_STAT_HEAD);
5842 status_update_onbranch();
5844 io_run_bg(update_index_argv);
5846 if (is_initial_commit()) {
5847 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5848 return FALSE;
5849 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5850 return FALSE;
5853 if (!opt_untracked_dirs_content)
5854 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5856 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5857 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5858 return FALSE;
5860 /* Restore the exact position or use the specialized restore
5861 * mode? */
5862 status_restore(view);
5863 return TRUE;
5866 static bool
5867 status_draw(struct view *view, struct line *line, unsigned int lineno)
5869 struct status *status = line->data;
5870 enum line_type type;
5871 const char *text;
5873 if (!status) {
5874 switch (line->type) {
5875 case LINE_STAT_STAGED:
5876 type = LINE_STAT_SECTION;
5877 text = "Changes to be committed:";
5878 break;
5880 case LINE_STAT_UNSTAGED:
5881 type = LINE_STAT_SECTION;
5882 text = "Changed but not updated:";
5883 break;
5885 case LINE_STAT_UNTRACKED:
5886 type = LINE_STAT_SECTION;
5887 text = "Untracked files:";
5888 break;
5890 case LINE_STAT_NONE:
5891 type = LINE_DEFAULT;
5892 text = " (no files)";
5893 break;
5895 case LINE_STAT_HEAD:
5896 type = LINE_STAT_HEAD;
5897 text = status_onbranch;
5898 break;
5900 default:
5901 return FALSE;
5903 } else {
5904 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5906 buf[0] = status->status;
5907 if (draw_text(view, line->type, buf))
5908 return TRUE;
5909 type = LINE_DEFAULT;
5910 text = status->new.name;
5913 draw_text(view, type, text);
5914 return TRUE;
5917 static enum request
5918 status_enter(struct view *view, struct line *line)
5920 struct status *status = line->data;
5921 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5923 if (line->type == LINE_STAT_NONE ||
5924 (!status && line[1].type == LINE_STAT_NONE)) {
5925 report("No file to diff");
5926 return REQ_NONE;
5929 switch (line->type) {
5930 case LINE_STAT_STAGED:
5931 case LINE_STAT_UNSTAGED:
5932 break;
5934 case LINE_STAT_UNTRACKED:
5935 if (!status) {
5936 report("No file to show");
5937 return REQ_NONE;
5940 if (!suffixcmp(status->new.name, -1, "/")) {
5941 report("Cannot display a directory");
5942 return REQ_NONE;
5944 break;
5946 case LINE_STAT_HEAD:
5947 return REQ_NONE;
5949 default:
5950 die("line type %d not handled in switch", line->type);
5953 if (status) {
5954 stage_status = *status;
5955 } else {
5956 memset(&stage_status, 0, sizeof(stage_status));
5959 stage_line_type = line->type;
5961 open_view(view, REQ_VIEW_STAGE, flags);
5962 return REQ_NONE;
5965 static bool
5966 status_exists(struct view *view, struct status *status, enum line_type type)
5968 unsigned long lineno;
5970 for (lineno = 0; lineno < view->lines; lineno++) {
5971 struct line *line = &view->line[lineno];
5972 struct status *pos = line->data;
5974 if (line->type != type)
5975 continue;
5976 if (!pos && (!status || !status->status) && line[1].data) {
5977 select_view_line(view, lineno);
5978 return TRUE;
5980 if (pos && !strcmp(status->new.name, pos->new.name)) {
5981 select_view_line(view, lineno);
5982 return TRUE;
5986 return FALSE;
5990 static bool
5991 status_update_prepare(struct io *io, enum line_type type)
5993 const char *staged_argv[] = {
5994 "git", "update-index", "-z", "--index-info", NULL
5996 const char *others_argv[] = {
5997 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
6000 switch (type) {
6001 case LINE_STAT_STAGED:
6002 return io_run(io, IO_WR, opt_cdup, staged_argv);
6004 case LINE_STAT_UNSTAGED:
6005 case LINE_STAT_UNTRACKED:
6006 return io_run(io, IO_WR, opt_cdup, others_argv);
6008 default:
6009 die("line type %d not handled in switch", type);
6010 return FALSE;
6014 static bool
6015 status_update_write(struct io *io, struct status *status, enum line_type type)
6017 switch (type) {
6018 case LINE_STAT_STAGED:
6019 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
6020 status->old.rev, status->old.name, 0);
6022 case LINE_STAT_UNSTAGED:
6023 case LINE_STAT_UNTRACKED:
6024 return io_printf(io, "%s%c", status->new.name, 0);
6026 default:
6027 die("line type %d not handled in switch", type);
6028 return FALSE;
6032 static bool
6033 status_update_file(struct status *status, enum line_type type)
6035 struct io io;
6036 bool result;
6038 if (!status_update_prepare(&io, type))
6039 return FALSE;
6041 result = status_update_write(&io, status, type);
6042 return io_done(&io) && result;
6045 static bool
6046 status_update_files(struct view *view, struct line *line)
6048 char buf[sizeof(view->ref)];
6049 struct io io;
6050 bool result = TRUE;
6051 struct line *pos = view->line + view->lines;
6052 int files = 0;
6053 int file, done;
6054 int cursor_y = -1, cursor_x = -1;
6056 if (!status_update_prepare(&io, line->type))
6057 return FALSE;
6059 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
6060 files++;
6062 string_copy(buf, view->ref);
6063 getsyx(cursor_y, cursor_x);
6064 for (file = 0, done = 5; result && file < files; line++, file++) {
6065 int almost_done = file * 100 / files;
6067 if (almost_done > done) {
6068 done = almost_done;
6069 string_format(view->ref, "updating file %u of %u (%d%% done)",
6070 file, files, done);
6071 update_view_title(view);
6072 setsyx(cursor_y, cursor_x);
6073 doupdate();
6075 result = status_update_write(&io, line->data, line->type);
6077 string_copy(view->ref, buf);
6079 return io_done(&io) && result;
6082 static bool
6083 status_update(struct view *view)
6085 struct line *line = &view->line[view->pos.lineno];
6087 assert(view->lines);
6089 if (!line->data) {
6090 /* This should work even for the "On branch" line. */
6091 if (line < view->line + view->lines && !line[1].data) {
6092 report("Nothing to update");
6093 return FALSE;
6096 if (!status_update_files(view, line + 1)) {
6097 report("Failed to update file status");
6098 return FALSE;
6101 } else if (!status_update_file(line->data, line->type)) {
6102 report("Failed to update file status");
6103 return FALSE;
6106 return TRUE;
6109 static bool
6110 status_revert(struct status *status, enum line_type type, bool has_none)
6112 if (!status || type != LINE_STAT_UNSTAGED) {
6113 if (type == LINE_STAT_STAGED) {
6114 report("Cannot revert changes to staged files");
6115 } else if (type == LINE_STAT_UNTRACKED) {
6116 report("Cannot revert changes to untracked files");
6117 } else if (has_none) {
6118 report("Nothing to revert");
6119 } else {
6120 report("Cannot revert changes to multiple files");
6123 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6124 char mode[10] = "100644";
6125 const char *reset_argv[] = {
6126 "git", "update-index", "--cacheinfo", mode,
6127 status->old.rev, status->old.name, NULL
6129 const char *checkout_argv[] = {
6130 "git", "checkout", "--", status->old.name, NULL
6133 if (status->status == 'U') {
6134 string_format(mode, "%5o", status->old.mode);
6136 if (status->old.mode == 0 && status->new.mode == 0) {
6137 reset_argv[2] = "--force-remove";
6138 reset_argv[3] = status->old.name;
6139 reset_argv[4] = NULL;
6142 if (!io_run_fg(reset_argv, opt_cdup))
6143 return FALSE;
6144 if (status->old.mode == 0 && status->new.mode == 0)
6145 return TRUE;
6148 return io_run_fg(checkout_argv, opt_cdup);
6151 return FALSE;
6154 static enum request
6155 status_request(struct view *view, enum request request, struct line *line)
6157 struct status *status = line->data;
6159 switch (request) {
6160 case REQ_STATUS_UPDATE:
6161 if (!status_update(view))
6162 return REQ_NONE;
6163 break;
6165 case REQ_STATUS_REVERT:
6166 if (!status_revert(status, line->type, status_has_none(view, line)))
6167 return REQ_NONE;
6168 break;
6170 case REQ_STATUS_MERGE:
6171 if (!status || status->status != 'U') {
6172 report("Merging only possible for files with unmerged status ('U').");
6173 return REQ_NONE;
6175 open_mergetool(status->new.name);
6176 break;
6178 case REQ_EDIT:
6179 if (!status)
6180 return request;
6181 if (status->status == 'D') {
6182 report("File has been deleted.");
6183 return REQ_NONE;
6186 open_editor(status->new.name);
6187 break;
6189 case REQ_VIEW_BLAME:
6190 if (status)
6191 opt_ref[0] = 0;
6192 return request;
6194 case REQ_ENTER:
6195 /* After returning the status view has been split to
6196 * show the stage view. No further reloading is
6197 * necessary. */
6198 return status_enter(view, line);
6200 case REQ_REFRESH:
6201 /* Simply reload the view. */
6202 break;
6204 default:
6205 return request;
6208 refresh_view(view);
6210 return REQ_NONE;
6213 static void
6214 status_select(struct view *view, struct line *line)
6216 struct status *status = line->data;
6217 char file[SIZEOF_STR] = "all files";
6218 const char *text;
6219 const char *key;
6221 if (status && !string_format(file, "'%s'", status->new.name))
6222 return;
6224 if (!status && line[1].type == LINE_STAT_NONE)
6225 line++;
6227 switch (line->type) {
6228 case LINE_STAT_STAGED:
6229 text = "Press %s to unstage %s for commit";
6230 break;
6232 case LINE_STAT_UNSTAGED:
6233 text = "Press %s to stage %s for commit";
6234 break;
6236 case LINE_STAT_UNTRACKED:
6237 text = "Press %s to stage %s for addition";
6238 break;
6240 case LINE_STAT_HEAD:
6241 case LINE_STAT_NONE:
6242 text = "Nothing to update";
6243 break;
6245 default:
6246 die("line type %d not handled in switch", line->type);
6249 if (status && status->status == 'U') {
6250 text = "Press %s to resolve conflict in %s";
6251 key = get_view_key(view, REQ_STATUS_MERGE);
6253 } else {
6254 key = get_view_key(view, REQ_STATUS_UPDATE);
6257 string_format(view->ref, text, key, file);
6258 if (status)
6259 string_copy(opt_file, status->new.name);
6262 static bool
6263 status_grep(struct view *view, struct line *line)
6265 struct status *status = line->data;
6267 if (status) {
6268 const char buf[2] = { status->status, 0 };
6269 const char *text[] = { status->new.name, buf, NULL };
6271 return grep_text(view, text);
6274 return FALSE;
6277 static struct view_ops status_ops = {
6278 "file",
6279 { "status" },
6280 VIEW_CUSTOM_STATUS,
6282 status_open,
6283 NULL,
6284 status_draw,
6285 status_request,
6286 status_grep,
6287 status_select,
6291 struct stage_state {
6292 struct diff_state diff;
6293 size_t chunks;
6294 int *chunk;
6297 static bool
6298 stage_diff_write(struct io *io, struct line *line, struct line *end)
6300 while (line < end) {
6301 if (!io_write(io, line->data, strlen(line->data)) ||
6302 !io_write(io, "\n", 1))
6303 return FALSE;
6304 line++;
6305 if (line->type == LINE_DIFF_CHUNK ||
6306 line->type == LINE_DIFF_HEADER)
6307 break;
6310 return TRUE;
6313 static bool
6314 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6316 const char *apply_argv[SIZEOF_ARG] = {
6317 "git", "apply", "--whitespace=nowarn", NULL
6319 struct line *diff_hdr;
6320 struct io io;
6321 int argc = 3;
6323 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6324 if (!diff_hdr)
6325 return FALSE;
6327 if (!revert)
6328 apply_argv[argc++] = "--cached";
6329 if (line != NULL)
6330 apply_argv[argc++] = "--unidiff-zero";
6331 if (revert || stage_line_type == LINE_STAT_STAGED)
6332 apply_argv[argc++] = "-R";
6333 apply_argv[argc++] = "-";
6334 apply_argv[argc++] = NULL;
6335 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6336 return FALSE;
6338 if (line != NULL) {
6339 int lineno = 0;
6340 struct line *context = chunk + 1;
6341 const char *markers[] = {
6342 line->type == LINE_DIFF_DEL ? "" : ",0",
6343 line->type == LINE_DIFF_DEL ? ",0" : "",
6346 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6348 while (context < line) {
6349 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6350 break;
6351 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6352 lineno++;
6354 context++;
6357 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6358 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6359 lineno, markers[0], lineno, markers[1]) ||
6360 !stage_diff_write(&io, line, line + 1)) {
6361 chunk = NULL;
6363 } else {
6364 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6365 !stage_diff_write(&io, chunk, view->line + view->lines))
6366 chunk = NULL;
6369 io_done(&io);
6370 io_run_bg(update_index_argv);
6372 return chunk ? TRUE : FALSE;
6375 static bool
6376 stage_update(struct view *view, struct line *line, bool single)
6378 struct line *chunk = NULL;
6380 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6381 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6383 if (chunk) {
6384 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6385 report("Failed to apply chunk");
6386 return FALSE;
6389 } else if (!stage_status.status) {
6390 view = view->parent;
6392 for (line = view->line; line < view->line + view->lines; line++)
6393 if (line->type == stage_line_type)
6394 break;
6396 if (!status_update_files(view, line + 1)) {
6397 report("Failed to update files");
6398 return FALSE;
6401 } else if (!status_update_file(&stage_status, stage_line_type)) {
6402 report("Failed to update file");
6403 return FALSE;
6406 return TRUE;
6409 static bool
6410 stage_revert(struct view *view, struct line *line)
6412 struct line *chunk = NULL;
6414 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6415 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6417 if (chunk) {
6418 if (!prompt_yesno("Are you sure you want to revert changes?"))
6419 return FALSE;
6421 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6422 report("Failed to revert chunk");
6423 return FALSE;
6425 return TRUE;
6427 } else {
6428 return status_revert(stage_status.status ? &stage_status : NULL,
6429 stage_line_type, FALSE);
6434 static void
6435 stage_next(struct view *view, struct line *line)
6437 struct stage_state *state = view->private;
6438 int i;
6440 if (!state->chunks) {
6441 for (line = view->line; line < view->line + view->lines; line++) {
6442 if (line->type != LINE_DIFF_CHUNK)
6443 continue;
6445 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6446 report("Allocation failure");
6447 return;
6450 state->chunk[state->chunks++] = line - view->line;
6454 for (i = 0; i < state->chunks; i++) {
6455 if (state->chunk[i] > view->pos.lineno) {
6456 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
6457 report("Chunk %d of %d", i + 1, state->chunks);
6458 return;
6462 report("No next chunk found");
6465 static enum request
6466 stage_request(struct view *view, enum request request, struct line *line)
6468 switch (request) {
6469 case REQ_STATUS_UPDATE:
6470 if (!stage_update(view, line, FALSE))
6471 return REQ_NONE;
6472 break;
6474 case REQ_STATUS_REVERT:
6475 if (!stage_revert(view, line))
6476 return REQ_NONE;
6477 break;
6479 case REQ_STAGE_UPDATE_LINE:
6480 if (stage_line_type == LINE_STAT_UNTRACKED ||
6481 stage_status.status == 'A') {
6482 report("Staging single lines is not supported for new files");
6483 return REQ_NONE;
6485 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6486 report("Please select a change to stage");
6487 return REQ_NONE;
6489 if (!stage_update(view, line, TRUE))
6490 return REQ_NONE;
6491 break;
6493 case REQ_STAGE_NEXT:
6494 if (stage_line_type == LINE_STAT_UNTRACKED) {
6495 report("File is untracked; press %s to add",
6496 get_view_key(view, REQ_STATUS_UPDATE));
6497 return REQ_NONE;
6499 stage_next(view, line);
6500 return REQ_NONE;
6502 case REQ_EDIT:
6503 if (!stage_status.new.name[0])
6504 return request;
6505 if (stage_status.status == 'D') {
6506 report("File has been deleted.");
6507 return REQ_NONE;
6510 open_editor(stage_status.new.name);
6511 break;
6513 case REQ_REFRESH:
6514 /* Reload everything ... */
6515 break;
6517 case REQ_VIEW_BLAME:
6518 if (stage_status.new.name[0]) {
6519 string_copy(opt_file, stage_status.new.name);
6520 opt_ref[0] = 0;
6522 return request;
6524 case REQ_ENTER:
6525 return diff_common_enter(view, request, line);
6527 case REQ_DIFF_CONTEXT_UP:
6528 case REQ_DIFF_CONTEXT_DOWN:
6529 if (!update_diff_context(request))
6530 return REQ_NONE;
6531 break;
6533 default:
6534 return request;
6537 refresh_view(view->parent);
6539 /* Check whether the staged entry still exists, and close the
6540 * stage view if it doesn't. */
6541 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6542 status_restore(view->parent);
6543 return REQ_VIEW_CLOSE;
6546 refresh_view(view);
6548 return REQ_NONE;
6551 static bool
6552 stage_open(struct view *view, enum open_flags flags)
6554 static const char *no_head_diff_argv[] = {
6555 GIT_DIFF_STAGED_INITIAL(opt_diff_context_arg, opt_ignore_space_arg,
6556 stage_status.new.name)
6558 static const char *index_show_argv[] = {
6559 GIT_DIFF_STAGED(opt_diff_context_arg, opt_ignore_space_arg,
6560 stage_status.old.name, stage_status.new.name)
6562 static const char *files_show_argv[] = {
6563 GIT_DIFF_UNSTAGED(opt_diff_context_arg, opt_ignore_space_arg,
6564 stage_status.old.name, stage_status.new.name)
6566 /* Diffs for unmerged entries are empty when passing the new
6567 * path, so leave out the new path. */
6568 static const char *files_unmerged_argv[] = {
6569 "git", "diff-files", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6570 opt_diff_context_arg, opt_ignore_space_arg, "--",
6571 stage_status.old.name, NULL
6573 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6574 const char **argv = NULL;
6575 const char *info;
6577 view->encoding = NULL;
6579 switch (stage_line_type) {
6580 case LINE_STAT_STAGED:
6581 if (is_initial_commit()) {
6582 argv = no_head_diff_argv;
6583 } else {
6584 argv = index_show_argv;
6586 if (stage_status.status)
6587 info = "Staged changes to %s";
6588 else
6589 info = "Staged changes";
6590 break;
6592 case LINE_STAT_UNSTAGED:
6593 if (stage_status.status != 'U')
6594 argv = files_show_argv;
6595 else
6596 argv = files_unmerged_argv;
6597 if (stage_status.status)
6598 info = "Unstaged changes to %s";
6599 else
6600 info = "Unstaged changes";
6601 break;
6603 case LINE_STAT_UNTRACKED:
6604 info = "Untracked file %s";
6605 argv = file_argv;
6606 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
6607 break;
6609 case LINE_STAT_HEAD:
6610 default:
6611 die("line type %d not handled in switch", stage_line_type);
6614 string_format(view->ref, info, stage_status.new.name);
6615 view->vid[0] = 0;
6616 view->dir = opt_cdup;
6617 return argv_copy(&view->argv, argv)
6618 && begin_update(view, NULL, NULL, flags);
6621 static bool
6622 stage_read(struct view *view, char *data)
6624 struct stage_state *state = view->private;
6626 if (data && diff_common_read(view, data, &state->diff))
6627 return TRUE;
6629 return pager_read(view, data);
6632 static struct view_ops stage_ops = {
6633 "line",
6634 { "stage" },
6635 VIEW_DIFF_LIKE,
6636 sizeof(struct stage_state),
6637 stage_open,
6638 stage_read,
6639 diff_common_draw,
6640 stage_request,
6641 pager_grep,
6642 pager_select,
6647 * Revision graph
6650 static const enum line_type graph_colors[] = {
6651 LINE_PALETTE_0,
6652 LINE_PALETTE_1,
6653 LINE_PALETTE_2,
6654 LINE_PALETTE_3,
6655 LINE_PALETTE_4,
6656 LINE_PALETTE_5,
6657 LINE_PALETTE_6,
6660 static enum line_type get_graph_color(struct graph_symbol *symbol)
6662 if (symbol->commit)
6663 return LINE_GRAPH_COMMIT;
6664 assert(symbol->color < ARRAY_SIZE(graph_colors));
6665 return graph_colors[symbol->color];
6668 static bool
6669 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6671 const char *chars = graph_symbol_to_utf8(symbol);
6673 return draw_text(view, color, chars + !!first);
6676 static bool
6677 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6679 const char *chars = graph_symbol_to_ascii(symbol);
6681 return draw_text(view, color, chars + !!first);
6684 static bool
6685 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6687 const chtype *chars = graph_symbol_to_chtype(symbol);
6689 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6692 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6694 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6696 static const draw_graph_fn fns[] = {
6697 draw_graph_ascii,
6698 draw_graph_chtype,
6699 draw_graph_utf8
6701 draw_graph_fn fn = fns[opt_line_graphics];
6702 int i;
6704 for (i = 0; i < canvas->size; i++) {
6705 struct graph_symbol *symbol = &canvas->symbols[i];
6706 enum line_type color = get_graph_color(symbol);
6708 if (fn(view, symbol, color, i == 0))
6709 return TRUE;
6712 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6716 * Main view backend
6719 struct commit {
6720 char id[SIZEOF_REV]; /* SHA1 ID. */
6721 char title[128]; /* First line of the commit message. */
6722 const char *author; /* Author of the commit. */
6723 struct time time; /* Date from the author ident. */
6724 struct ref_list *refs; /* Repository references. */
6725 struct graph_canvas graph; /* Ancestry chain graphics. */
6728 static struct commit *
6729 main_add_commit(struct view *view, enum line_type type, const char *ids, bool is_boundary)
6731 struct graph *graph = view->private;
6732 struct commit *commit;
6734 commit = calloc(1, sizeof(struct commit));
6735 if (!commit)
6736 return NULL;
6738 string_copy_rev(commit->id, ids);
6739 commit->refs = get_ref_list(commit->id);
6740 add_line_data(view, commit, type);
6741 graph_add_commit(graph, &commit->graph, commit->id, ids, is_boundary);
6742 return commit;
6745 bool
6746 main_has_changes(const char *argv[])
6748 struct io io;
6750 if (!io_run(&io, IO_BG, NULL, argv, -1))
6751 return FALSE;
6752 io_done(&io);
6753 return io.status == 1;
6756 static void
6757 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
6759 char ids[SIZEOF_STR] = NULL_ID " ";
6760 struct graph *graph = view->private;
6761 struct commit *commit;
6762 struct timeval now;
6763 struct timezone tz;
6765 if (!parent)
6766 return;
6768 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
6770 commit = main_add_commit(view, type, ids, FALSE);
6771 if (!commit)
6772 return;
6774 if (!gettimeofday(&now, &tz)) {
6775 commit->time.tz = tz.tz_minuteswest * 60;
6776 commit->time.sec = now.tv_sec - commit->time.tz;
6779 commit->author = "";
6780 string_ncopy(commit->title, title, strlen(title));
6781 graph_render_parents(graph);
6784 static void
6785 main_add_changes_commits(struct view *view, const char *parent)
6787 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
6788 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
6789 const char *staged_parent = NULL_ID;
6790 const char *unstaged_parent = parent;
6792 if (!main_has_changes(unstaged_argv)) {
6793 unstaged_parent = NULL;
6794 staged_parent = parent;
6797 if (!main_has_changes(staged_argv)) {
6798 staged_parent = NULL;
6801 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
6802 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
6805 static bool
6806 main_open(struct view *view, enum open_flags flags)
6808 static const char *main_argv[] = {
6809 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw", "--parents",
6810 opt_commit_order_arg, "%(diffargs)", "%(revargs)",
6811 "--", "%(fileargs)", NULL
6814 return begin_update(view, NULL, main_argv, flags);
6817 static bool
6818 main_draw(struct view *view, struct line *line, unsigned int lineno)
6820 struct commit *commit = line->data;
6822 if (!commit->author)
6823 return FALSE;
6825 if (draw_lineno(view, lineno))
6826 return TRUE;
6828 if (draw_date(view, &commit->time))
6829 return TRUE;
6831 if (draw_author(view, commit->author))
6832 return TRUE;
6834 if (opt_rev_graph && draw_graph(view, &commit->graph))
6835 return TRUE;
6837 if (draw_refs(view, commit->refs))
6838 return TRUE;
6840 draw_text(view, LINE_DEFAULT, commit->title);
6841 return TRUE;
6844 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6845 static bool
6846 main_read(struct view *view, char *line)
6848 struct graph *graph = view->private;
6849 enum line_type type;
6850 struct commit *commit;
6851 static bool in_header;
6853 if (!line) {
6854 if (!view->lines && !view->prev)
6855 die("No revisions match the given arguments.");
6856 if (view->lines > 0) {
6857 commit = view->line[view->lines - 1].data;
6858 view->line[view->lines - 1].dirty = 1;
6859 if (!commit->author) {
6860 view->lines--;
6861 free(commit);
6865 done_graph(graph);
6866 return TRUE;
6869 type = get_line_type(line);
6870 if (type == LINE_COMMIT) {
6871 bool is_boundary;
6873 in_header = TRUE;
6874 line += STRING_SIZE("commit ");
6875 is_boundary = *line == '-';
6876 if (is_boundary)
6877 line++;
6879 if (opt_show_changes && opt_is_inside_work_tree && !view->lines)
6880 main_add_changes_commits(view, line);
6882 return main_add_commit(view, LINE_MAIN_COMMIT, line, is_boundary) != NULL;
6885 if (!view->lines)
6886 return TRUE;
6887 commit = view->line[view->lines - 1].data;
6889 /* Empty line separates the commit header from the log itself. */
6890 if (*line == '\0')
6891 in_header = FALSE;
6893 switch (type) {
6894 case LINE_PARENT:
6895 if (!graph->has_parents)
6896 graph_add_parent(graph, line + STRING_SIZE("parent "));
6897 break;
6899 case LINE_AUTHOR:
6900 parse_author_line(line + STRING_SIZE("author "),
6901 &commit->author, &commit->time);
6902 graph_render_parents(graph);
6903 break;
6905 default:
6906 /* Fill in the commit title if it has not already been set. */
6907 if (commit->title[0])
6908 break;
6910 /* Skip lines in the commit header. */
6911 if (in_header)
6912 break;
6914 /* Require titles to start with a non-space character at the
6915 * offset used by git log. */
6916 if (strncmp(line, " ", 4))
6917 break;
6918 line += 4;
6919 /* Well, if the title starts with a whitespace character,
6920 * try to be forgiving. Otherwise we end up with no title. */
6921 while (isspace(*line))
6922 line++;
6923 if (*line == '\0')
6924 break;
6925 /* FIXME: More graceful handling of titles; append "..." to
6926 * shortened titles, etc. */
6928 string_expand(commit->title, sizeof(commit->title), line, 1);
6929 view->line[view->lines - 1].dirty = 1;
6932 return TRUE;
6935 static enum request
6936 main_request(struct view *view, enum request request, struct line *line)
6938 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6940 switch (request) {
6941 case REQ_NEXT:
6942 case REQ_PREVIOUS:
6943 if (view_is_displayed(view) && display[0] != view)
6944 return request;
6945 /* Do not pass navigation requests to the branch view
6946 * when the main view is maximized. (GH #38) */
6947 move_view(view, request);
6948 break;
6950 case REQ_ENTER:
6951 if (view_is_displayed(view) && display[0] != view)
6952 maximize_view(view, TRUE);
6954 if (line->type == LINE_STAT_UNSTAGED
6955 || line->type == LINE_STAT_STAGED) {
6956 struct view *diff = VIEW(REQ_VIEW_DIFF);
6957 const char *diff_staged_argv[] = {
6958 GIT_DIFF_STAGED(opt_diff_context_arg,
6959 opt_ignore_space_arg, NULL, NULL)
6961 const char *diff_unstaged_argv[] = {
6962 GIT_DIFF_UNSTAGED(opt_diff_context_arg,
6963 opt_ignore_space_arg, NULL, NULL)
6965 const char **diff_argv = line->type == LINE_STAT_STAGED
6966 ? diff_staged_argv : diff_unstaged_argv;
6968 open_argv(view, diff, diff_argv, NULL, flags);
6969 break;
6972 open_view(view, REQ_VIEW_DIFF, flags);
6973 break;
6974 case REQ_REFRESH:
6975 load_refs();
6976 refresh_view(view);
6977 break;
6979 case REQ_JUMP_COMMIT:
6981 int lineno;
6983 for (lineno = 0; lineno < view->lines; lineno++) {
6984 struct commit *commit = view->line[lineno].data;
6986 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
6987 select_view_line(view, lineno);
6988 report("");
6989 return REQ_NONE;
6993 report("Unable to find commit '%s'", opt_search);
6994 break;
6996 default:
6997 return request;
7000 return REQ_NONE;
7003 static bool
7004 grep_refs(struct ref_list *list, regex_t *regex)
7006 regmatch_t pmatch;
7007 size_t i;
7009 if (!opt_show_refs || !list)
7010 return FALSE;
7012 for (i = 0; i < list->size; i++) {
7013 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
7014 return TRUE;
7017 return FALSE;
7020 static bool
7021 main_grep(struct view *view, struct line *line)
7023 struct commit *commit = line->data;
7024 const char *text[] = {
7025 commit->title,
7026 mkauthor(commit->author, opt_author_cols, opt_author),
7027 mkdate(&commit->time, opt_date),
7028 NULL
7031 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
7034 static void
7035 main_select(struct view *view, struct line *line)
7037 struct commit *commit = line->data;
7039 string_copy_rev(view->ref, commit->id);
7040 string_copy_rev(ref_commit, view->ref);
7043 static struct view_ops main_ops = {
7044 "commit",
7045 { "main" },
7046 VIEW_NO_FLAGS,
7047 sizeof(struct graph),
7048 main_open,
7049 main_read,
7050 main_draw,
7051 main_request,
7052 main_grep,
7053 main_select,
7058 * Status management
7061 /* Whether or not the curses interface has been initialized. */
7062 static bool cursed = FALSE;
7064 /* Terminal hacks and workarounds. */
7065 static bool use_scroll_redrawwin;
7066 static bool use_scroll_status_wclear;
7068 /* The status window is used for polling keystrokes. */
7069 static WINDOW *status_win;
7071 /* Reading from the prompt? */
7072 static bool input_mode = FALSE;
7074 static bool status_empty = FALSE;
7076 /* Update status and title window. */
7077 static void
7078 report(const char *msg, ...)
7080 struct view *view = display[current_view];
7082 if (input_mode)
7083 return;
7085 if (!view) {
7086 char buf[SIZEOF_STR];
7087 int retval;
7089 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
7090 die("%s", buf);
7093 if (!status_empty || *msg) {
7094 va_list args;
7096 va_start(args, msg);
7098 wmove(status_win, 0, 0);
7099 if (view->has_scrolled && use_scroll_status_wclear)
7100 wclear(status_win);
7101 if (*msg) {
7102 vwprintw(status_win, msg, args);
7103 status_empty = FALSE;
7104 } else {
7105 status_empty = TRUE;
7107 wclrtoeol(status_win);
7108 wnoutrefresh(status_win);
7110 va_end(args);
7113 update_view_title(view);
7116 static void
7117 init_display(void)
7119 const char *term;
7120 int x, y;
7122 /* Initialize the curses library */
7123 if (isatty(STDIN_FILENO)) {
7124 cursed = !!initscr();
7125 opt_tty = stdin;
7126 } else {
7127 /* Leave stdin and stdout alone when acting as a pager. */
7128 opt_tty = fopen("/dev/tty", "r+");
7129 if (!opt_tty)
7130 die("Failed to open /dev/tty");
7131 cursed = !!newterm(NULL, opt_tty, opt_tty);
7134 if (!cursed)
7135 die("Failed to initialize curses");
7137 nonl(); /* Disable conversion and detect newlines from input. */
7138 cbreak(); /* Take input chars one at a time, no wait for \n */
7139 noecho(); /* Don't echo input */
7140 leaveok(stdscr, FALSE);
7142 if (has_colors())
7143 init_colors();
7145 getmaxyx(stdscr, y, x);
7146 status_win = newwin(1, x, y - 1, 0);
7147 if (!status_win)
7148 die("Failed to create status window");
7150 /* Enable keyboard mapping */
7151 keypad(status_win, TRUE);
7152 wbkgdset(status_win, get_line_attr(LINE_STATUS));
7154 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
7155 set_tabsize(opt_tab_size);
7156 #else
7157 TABSIZE = opt_tab_size;
7158 #endif
7160 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
7161 if (term && !strcmp(term, "gnome-terminal")) {
7162 /* In the gnome-terminal-emulator, the message from
7163 * scrolling up one line when impossible followed by
7164 * scrolling down one line causes corruption of the
7165 * status line. This is fixed by calling wclear. */
7166 use_scroll_status_wclear = TRUE;
7167 use_scroll_redrawwin = FALSE;
7169 } else if (term && !strcmp(term, "xrvt-xpm")) {
7170 /* No problems with full optimizations in xrvt-(unicode)
7171 * and aterm. */
7172 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
7174 } else {
7175 /* When scrolling in (u)xterm the last line in the
7176 * scrolling direction will update slowly. */
7177 use_scroll_redrawwin = TRUE;
7178 use_scroll_status_wclear = FALSE;
7182 static int
7183 get_input(int prompt_position)
7185 struct view *view;
7186 int i, key, cursor_y, cursor_x;
7188 if (prompt_position)
7189 input_mode = TRUE;
7191 while (TRUE) {
7192 bool loading = FALSE;
7194 foreach_view (view, i) {
7195 update_view(view);
7196 if (view_is_displayed(view) && view->has_scrolled &&
7197 use_scroll_redrawwin)
7198 redrawwin(view->win);
7199 view->has_scrolled = FALSE;
7200 if (view->pipe)
7201 loading = TRUE;
7204 /* Update the cursor position. */
7205 if (prompt_position) {
7206 getbegyx(status_win, cursor_y, cursor_x);
7207 cursor_x = prompt_position;
7208 } else {
7209 view = display[current_view];
7210 getbegyx(view->win, cursor_y, cursor_x);
7211 cursor_x = view->width - 1;
7212 cursor_y += view->pos.lineno - view->pos.offset;
7214 setsyx(cursor_y, cursor_x);
7216 /* Refresh, accept single keystroke of input */
7217 doupdate();
7218 nodelay(status_win, loading);
7219 key = wgetch(status_win);
7221 /* wgetch() with nodelay() enabled returns ERR when
7222 * there's no input. */
7223 if (key == ERR) {
7225 } else if (key == KEY_RESIZE) {
7226 int height, width;
7228 getmaxyx(stdscr, height, width);
7230 wresize(status_win, 1, width);
7231 mvwin(status_win, height - 1, 0);
7232 wnoutrefresh(status_win);
7233 resize_display();
7234 redraw_display(TRUE);
7236 } else {
7237 input_mode = FALSE;
7238 if (key == erasechar())
7239 key = KEY_BACKSPACE;
7240 return key;
7245 static char *
7246 prompt_input(const char *prompt, input_handler handler, void *data)
7248 enum input_status status = INPUT_OK;
7249 static char buf[SIZEOF_STR];
7250 size_t pos = 0;
7252 buf[pos] = 0;
7254 while (status == INPUT_OK || status == INPUT_SKIP) {
7255 int key;
7257 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
7258 wclrtoeol(status_win);
7260 key = get_input(pos + 1);
7261 switch (key) {
7262 case KEY_RETURN:
7263 case KEY_ENTER:
7264 case '\n':
7265 status = pos ? INPUT_STOP : INPUT_CANCEL;
7266 break;
7268 case KEY_BACKSPACE:
7269 if (pos > 0)
7270 buf[--pos] = 0;
7271 else
7272 status = INPUT_CANCEL;
7273 break;
7275 case KEY_ESC:
7276 status = INPUT_CANCEL;
7277 break;
7279 default:
7280 if (pos >= sizeof(buf)) {
7281 report("Input string too long");
7282 return NULL;
7285 status = handler(data, buf, key);
7286 if (status == INPUT_OK)
7287 buf[pos++] = (char) key;
7291 /* Clear the status window */
7292 status_empty = FALSE;
7293 report("");
7295 if (status == INPUT_CANCEL)
7296 return NULL;
7298 buf[pos++] = 0;
7300 return buf;
7303 static enum input_status
7304 prompt_yesno_handler(void *data, char *buf, int c)
7306 if (c == 'y' || c == 'Y')
7307 return INPUT_STOP;
7308 if (c == 'n' || c == 'N')
7309 return INPUT_CANCEL;
7310 return INPUT_SKIP;
7313 static bool
7314 prompt_yesno(const char *prompt)
7316 char prompt2[SIZEOF_STR];
7318 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7319 return FALSE;
7321 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7324 static enum input_status
7325 read_prompt_handler(void *data, char *buf, int c)
7327 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7330 static char *
7331 read_prompt(const char *prompt)
7333 return prompt_input(prompt, read_prompt_handler, NULL);
7336 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7338 enum input_status status = INPUT_OK;
7339 int size = 0;
7341 while (items[size].text)
7342 size++;
7344 while (status == INPUT_OK) {
7345 const struct menu_item *item = &items[*selected];
7346 int key;
7347 int i;
7349 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7350 prompt, *selected + 1, size);
7351 if (item->hotkey)
7352 wprintw(status_win, "[%c] ", (char) item->hotkey);
7353 wprintw(status_win, "%s", item->text);
7354 wclrtoeol(status_win);
7356 key = get_input(COLS - 1);
7357 switch (key) {
7358 case KEY_RETURN:
7359 case KEY_ENTER:
7360 case '\n':
7361 status = INPUT_STOP;
7362 break;
7364 case KEY_LEFT:
7365 case KEY_UP:
7366 *selected = *selected - 1;
7367 if (*selected < 0)
7368 *selected = size - 1;
7369 break;
7371 case KEY_RIGHT:
7372 case KEY_DOWN:
7373 *selected = (*selected + 1) % size;
7374 break;
7376 case KEY_ESC:
7377 status = INPUT_CANCEL;
7378 break;
7380 default:
7381 for (i = 0; items[i].text; i++)
7382 if (items[i].hotkey == key) {
7383 *selected = i;
7384 status = INPUT_STOP;
7385 break;
7390 /* Clear the status window */
7391 status_empty = FALSE;
7392 report("");
7394 return status != INPUT_CANCEL;
7398 * Repository properties
7401 static struct ref **refs = NULL;
7402 static size_t refs_size = 0;
7403 static struct ref *refs_head = NULL;
7405 static struct ref_list **ref_lists = NULL;
7406 static size_t ref_lists_size = 0;
7408 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
7409 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
7410 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
7412 static int
7413 compare_refs(const void *ref1_, const void *ref2_)
7415 const struct ref *ref1 = *(const struct ref **)ref1_;
7416 const struct ref *ref2 = *(const struct ref **)ref2_;
7418 if (ref1->tag != ref2->tag)
7419 return ref2->tag - ref1->tag;
7420 if (ref1->ltag != ref2->ltag)
7421 return ref2->ltag - ref1->ltag;
7422 if (ref1->head != ref2->head)
7423 return ref2->head - ref1->head;
7424 if (ref1->tracked != ref2->tracked)
7425 return ref2->tracked - ref1->tracked;
7426 if (ref1->replace != ref2->replace)
7427 return ref2->replace - ref1->replace;
7428 /* Order remotes last. */
7429 if (ref1->remote != ref2->remote)
7430 return ref1->remote - ref2->remote;
7431 return strcmp(ref1->name, ref2->name);
7434 static void
7435 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
7437 size_t i;
7439 for (i = 0; i < refs_size; i++)
7440 if (!visitor(data, refs[i]))
7441 break;
7444 static struct ref *
7445 get_ref_head()
7447 return refs_head;
7450 static struct ref_list *
7451 get_ref_list(const char *id)
7453 struct ref_list *list;
7454 size_t i;
7456 for (i = 0; i < ref_lists_size; i++)
7457 if (!strcmp(id, ref_lists[i]->id))
7458 return ref_lists[i];
7460 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
7461 return NULL;
7462 list = calloc(1, sizeof(*list));
7463 if (!list)
7464 return NULL;
7466 for (i = 0; i < refs_size; i++) {
7467 if (!strcmp(id, refs[i]->id) &&
7468 realloc_refs_list(&list->refs, list->size, 1))
7469 list->refs[list->size++] = refs[i];
7472 if (!list->refs) {
7473 free(list);
7474 return NULL;
7477 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
7478 ref_lists[ref_lists_size++] = list;
7479 return list;
7482 static int
7483 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
7485 struct ref *ref = NULL;
7486 bool tag = FALSE;
7487 bool ltag = FALSE;
7488 bool remote = FALSE;
7489 bool replace = FALSE;
7490 bool tracked = FALSE;
7491 bool head = FALSE;
7492 int pos;
7494 if (!prefixcmp(name, "refs/tags/")) {
7495 if (!suffixcmp(name, namelen, "^{}")) {
7496 namelen -= 3;
7497 name[namelen] = 0;
7498 } else {
7499 ltag = TRUE;
7502 tag = TRUE;
7503 namelen -= STRING_SIZE("refs/tags/");
7504 name += STRING_SIZE("refs/tags/");
7506 } else if (!prefixcmp(name, "refs/remotes/")) {
7507 remote = TRUE;
7508 namelen -= STRING_SIZE("refs/remotes/");
7509 name += STRING_SIZE("refs/remotes/");
7510 tracked = !strcmp(opt_remote, name);
7512 } else if (!prefixcmp(name, "refs/replace/")) {
7513 replace = TRUE;
7514 id = name + strlen("refs/replace/");
7515 idlen = namelen - strlen("refs/replace/");
7516 name = "replaced";
7517 namelen = strlen(name);
7519 } else if (!prefixcmp(name, "refs/heads/")) {
7520 namelen -= STRING_SIZE("refs/heads/");
7521 name += STRING_SIZE("refs/heads/");
7522 if (strlen(opt_head) == namelen
7523 && !strncmp(opt_head, name, namelen))
7524 return OK;
7526 } else if (!strcmp(name, "HEAD")) {
7527 head = TRUE;
7528 if (*opt_head) {
7529 namelen = strlen(opt_head);
7530 name = opt_head;
7534 /* If we are reloading or it's an annotated tag, replace the
7535 * previous SHA1 with the resolved commit id; relies on the fact
7536 * git-ls-remote lists the commit id of an annotated tag right
7537 * before the commit id it points to. */
7538 for (pos = 0; pos < refs_size; pos++) {
7539 int cmp = replace ? strcmp(id, refs[pos]->id) : strcmp(name, refs[pos]->name);
7541 if (!cmp) {
7542 ref = refs[pos];
7543 break;
7547 if (!ref) {
7548 if (!realloc_refs(&refs, refs_size, 1))
7549 return ERR;
7550 ref = calloc(1, sizeof(*ref) + namelen);
7551 if (!ref)
7552 return ERR;
7553 refs[refs_size++] = ref;
7554 strncpy(ref->name, name, namelen);
7557 ref->head = head;
7558 ref->tag = tag;
7559 ref->ltag = ltag;
7560 ref->remote = remote;
7561 ref->replace = replace;
7562 ref->tracked = tracked;
7563 string_copy_rev(ref->id, id);
7565 if (head)
7566 refs_head = ref;
7567 return OK;
7570 static int
7571 load_refs(void)
7573 const char *head_argv[] = {
7574 "git", "symbolic-ref", "HEAD", NULL
7576 static const char *ls_remote_argv[SIZEOF_ARG] = {
7577 "git", "ls-remote", opt_git_dir, NULL
7579 static bool init = FALSE;
7580 size_t i;
7582 if (!init) {
7583 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
7584 die("TIG_LS_REMOTE contains too many arguments");
7585 init = TRUE;
7588 if (!*opt_git_dir)
7589 return OK;
7591 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
7592 !prefixcmp(opt_head, "refs/heads/")) {
7593 char *offset = opt_head + STRING_SIZE("refs/heads/");
7595 memmove(opt_head, offset, strlen(offset) + 1);
7598 refs_head = NULL;
7599 for (i = 0; i < refs_size; i++)
7600 refs[i]->id[0] = 0;
7602 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
7603 return ERR;
7605 /* Update the ref lists to reflect changes. */
7606 for (i = 0; i < ref_lists_size; i++) {
7607 struct ref_list *list = ref_lists[i];
7608 size_t old, new;
7610 for (old = new = 0; old < list->size; old++)
7611 if (!strcmp(list->id, list->refs[old]->id))
7612 list->refs[new++] = list->refs[old];
7613 list->size = new;
7616 qsort(refs, refs_size, sizeof(*refs), compare_refs);
7618 return OK;
7621 static void
7622 set_remote_branch(const char *name, const char *value, size_t valuelen)
7624 if (!strcmp(name, ".remote")) {
7625 string_ncopy(opt_remote, value, valuelen);
7627 } else if (*opt_remote && !strcmp(name, ".merge")) {
7628 size_t from = strlen(opt_remote);
7630 if (!prefixcmp(value, "refs/heads/"))
7631 value += STRING_SIZE("refs/heads/");
7633 if (!string_format_from(opt_remote, &from, "/%s", value))
7634 opt_remote[0] = 0;
7638 static void
7639 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7641 const char *argv[SIZEOF_ARG] = { name, "=" };
7642 int argc = 1 + (cmd == option_set_command);
7643 enum option_code error;
7645 if (!argv_from_string(argv, &argc, value))
7646 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7647 else
7648 error = cmd(argc, argv);
7650 if (error != OPT_OK)
7651 warn("Option 'tig.%s': %s", name, option_errors[error]);
7654 static bool
7655 set_environment_variable(const char *name, const char *value)
7657 size_t len = strlen(name) + 1 + strlen(value) + 1;
7658 char *env = malloc(len);
7660 if (env &&
7661 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7662 putenv(env) == 0)
7663 return TRUE;
7664 free(env);
7665 return FALSE;
7668 static void
7669 set_work_tree(const char *value)
7671 char cwd[SIZEOF_STR];
7673 if (!getcwd(cwd, sizeof(cwd)))
7674 die("Failed to get cwd path: %s", strerror(errno));
7675 if (chdir(opt_git_dir) < 0)
7676 die("Failed to chdir(%s): %s", strerror(errno));
7677 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7678 die("Failed to get git path: %s", strerror(errno));
7679 if (chdir(cwd) < 0)
7680 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7681 if (chdir(value) < 0)
7682 die("Failed to chdir(%s): %s", value, strerror(errno));
7683 if (!getcwd(cwd, sizeof(cwd)))
7684 die("Failed to get cwd path: %s", strerror(errno));
7685 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7686 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7687 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7688 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7689 opt_is_inside_work_tree = TRUE;
7692 static void
7693 parse_git_color_option(enum line_type type, char *value)
7695 struct line_info *info = &line_info[type];
7696 const char *argv[SIZEOF_ARG];
7697 int argc = 0;
7698 bool first_color = TRUE;
7699 int i;
7701 if (!argv_from_string(argv, &argc, value))
7702 return;
7704 info->fg = COLOR_DEFAULT;
7705 info->bg = COLOR_DEFAULT;
7706 info->attr = 0;
7708 for (i = 0; i < argc; i++) {
7709 int attr = 0;
7711 if (set_attribute(&attr, argv[i])) {
7712 info->attr |= attr;
7714 } else if (set_color(&attr, argv[i])) {
7715 if (first_color)
7716 info->fg = attr;
7717 else
7718 info->bg = attr;
7719 first_color = FALSE;
7724 static void
7725 set_git_color_option(const char *name, char *value)
7727 static const struct enum_map color_option_map[] = {
7728 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
7729 ENUM_MAP("branch.local", LINE_MAIN_REF),
7730 ENUM_MAP("branch.plain", LINE_MAIN_REF),
7731 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
7733 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
7734 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
7735 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
7736 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
7737 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
7738 ENUM_MAP("diff.old", LINE_DIFF_DEL),
7739 ENUM_MAP("diff.new", LINE_DIFF_ADD),
7741 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
7743 ENUM_MAP("status.branch", LINE_STAT_HEAD),
7744 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
7745 ENUM_MAP("status.added", LINE_STAT_STAGED),
7746 ENUM_MAP("status.updated", LINE_STAT_STAGED),
7747 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
7748 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
7751 int type = LINE_NONE;
7753 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
7754 parse_git_color_option(type, value);
7758 static int
7759 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7761 if (!strcmp(name, "gui.encoding"))
7762 parse_encoding(&opt_encoding, value, TRUE);
7764 else if (!strcmp(name, "core.editor"))
7765 string_ncopy(opt_editor, value, valuelen);
7767 else if (!strcmp(name, "core.worktree"))
7768 set_work_tree(value);
7770 else if (!prefixcmp(name, "tig.color."))
7771 set_repo_config_option(name + 10, value, option_color_command);
7773 else if (!prefixcmp(name, "tig.bind."))
7774 set_repo_config_option(name + 9, value, option_bind_command);
7776 else if (!prefixcmp(name, "tig."))
7777 set_repo_config_option(name + 4, value, option_set_command);
7779 else if (!prefixcmp(name, "color."))
7780 set_git_color_option(name + STRING_SIZE("color."), value);
7782 else if (*opt_head && !prefixcmp(name, "branch.") &&
7783 !strncmp(name + 7, opt_head, strlen(opt_head)))
7784 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7786 return OK;
7789 static int
7790 load_git_config(void)
7792 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7794 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7797 static int
7798 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7800 if (!opt_git_dir[0]) {
7801 string_ncopy(opt_git_dir, name, namelen);
7803 } else if (opt_is_inside_work_tree == -1) {
7804 /* This can be 3 different values depending on the
7805 * version of git being used. If git-rev-parse does not
7806 * understand --is-inside-work-tree it will simply echo
7807 * the option else either "true" or "false" is printed.
7808 * Default to true for the unknown case. */
7809 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7811 } else if (*name == '.') {
7812 string_ncopy(opt_cdup, name, namelen);
7814 } else {
7815 string_ncopy(opt_prefix, name, namelen);
7818 return OK;
7821 static int
7822 load_repo_info(void)
7824 const char *rev_parse_argv[] = {
7825 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7826 "--show-cdup", "--show-prefix", NULL
7829 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7834 * Main
7837 static const char usage[] =
7838 "tig " TIG_VERSION " (" __DATE__ ")\n"
7839 "\n"
7840 "Usage: tig [options] [revs] [--] [paths]\n"
7841 " or: tig show [options] [revs] [--] [paths]\n"
7842 " or: tig blame [options] [rev] [--] path\n"
7843 " or: tig status\n"
7844 " or: tig < [git command output]\n"
7845 "\n"
7846 "Options:\n"
7847 " +<number> Select line <number> in the first view\n"
7848 " -v, --version Show version and exit\n"
7849 " -h, --help Show help message and exit";
7851 static void __NORETURN
7852 quit(int sig)
7854 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7855 if (cursed)
7856 endwin();
7857 exit(0);
7860 static void __NORETURN
7861 die(const char *err, ...)
7863 va_list args;
7865 endwin();
7867 va_start(args, err);
7868 fputs("tig: ", stderr);
7869 vfprintf(stderr, err, args);
7870 fputs("\n", stderr);
7871 va_end(args);
7873 exit(1);
7876 static void
7877 warn(const char *msg, ...)
7879 va_list args;
7881 va_start(args, msg);
7882 fputs("tig warning: ", stderr);
7883 vfprintf(stderr, msg, args);
7884 fputs("\n", stderr);
7885 va_end(args);
7888 static int
7889 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7891 const char ***filter_args = data;
7893 return argv_append(filter_args, name) ? OK : ERR;
7896 static void
7897 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7899 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7900 const char **all_argv = NULL;
7902 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7903 !argv_append_array(&all_argv, argv) ||
7904 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7905 die("Failed to split arguments");
7906 argv_free(all_argv);
7907 free(all_argv);
7910 static void
7911 filter_options(const char *argv[], bool blame)
7913 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7915 if (blame)
7916 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7917 else
7918 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7920 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7923 static enum request
7924 parse_options(int argc, const char *argv[])
7926 enum request request = REQ_VIEW_MAIN;
7927 const char *subcommand;
7928 bool seen_dashdash = FALSE;
7929 const char **filter_argv = NULL;
7930 int i;
7932 if (!isatty(STDIN_FILENO))
7933 return REQ_VIEW_PAGER;
7935 if (argc <= 1)
7936 return REQ_VIEW_MAIN;
7938 subcommand = argv[1];
7939 if (!strcmp(subcommand, "status")) {
7940 if (argc > 2)
7941 warn("ignoring arguments after `%s'", subcommand);
7942 return REQ_VIEW_STATUS;
7944 } else if (!strcmp(subcommand, "blame")) {
7945 request = REQ_VIEW_BLAME;
7947 } else if (!strcmp(subcommand, "show")) {
7948 request = REQ_VIEW_DIFF;
7950 } else {
7951 subcommand = NULL;
7954 for (i = 1 + !!subcommand; i < argc; i++) {
7955 const char *opt = argv[i];
7957 // stop parsing our options after -- and let rev-parse handle the rest
7958 if (!seen_dashdash) {
7959 if (!strcmp(opt, "--")) {
7960 seen_dashdash = TRUE;
7961 continue;
7963 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7964 printf("tig version %s\n", TIG_VERSION);
7965 quit(0);
7967 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7968 printf("%s\n", usage);
7969 quit(0);
7971 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7972 opt_lineno = atoi(opt + 1);
7973 continue;
7978 if (!argv_append(&filter_argv, opt))
7979 die("command too long");
7982 if (filter_argv)
7983 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7985 /* Finish validating and setting up blame options */
7986 if (request == REQ_VIEW_BLAME) {
7987 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7988 die("invalid number of options to blame\n\n%s", usage);
7990 if (opt_rev_argv) {
7991 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7994 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7997 return request;
8001 main(int argc, const char *argv[])
8003 const char *codeset = ENCODING_UTF8;
8004 enum request request = parse_options(argc, argv);
8005 struct view *view;
8006 int i;
8008 signal(SIGINT, quit);
8009 signal(SIGPIPE, SIG_IGN);
8011 if (setlocale(LC_ALL, "")) {
8012 codeset = nl_langinfo(CODESET);
8015 foreach_view(view, i) {
8016 add_keymap(&view->ops->keymap);
8019 if (load_repo_info() == ERR)
8020 die("Failed to load repo info.");
8022 if (load_options() == ERR)
8023 die("Failed to load user config.");
8025 if (load_git_config() == ERR)
8026 die("Failed to load repo config.");
8028 /* Require a git repository unless when running in pager mode. */
8029 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
8030 die("Not a git repository");
8032 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
8033 char translit[SIZEOF_STR];
8035 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
8036 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
8037 else
8038 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
8039 if (opt_iconv_out == ICONV_NONE)
8040 die("Failed to initialize character set conversion");
8043 if (load_refs() == ERR)
8044 die("Failed to load refs.");
8046 init_display();
8048 while (view_driver(display[current_view], request)) {
8049 int key = get_input(0);
8051 view = display[current_view];
8052 request = get_keybinding(&view->ops->keymap, key);
8054 /* Some low-level request handling. This keeps access to
8055 * status_win restricted. */
8056 switch (request) {
8057 case REQ_NONE:
8058 report("Unknown key, press %s for help",
8059 get_view_key(view, REQ_VIEW_HELP));
8060 break;
8061 case REQ_PROMPT:
8063 char *cmd = read_prompt(":");
8065 if (cmd && string_isnumber(cmd)) {
8066 int lineno = view->pos.lineno + 1;
8068 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
8069 select_view_line(view, lineno - 1);
8070 report("");
8071 } else {
8072 report("Unable to parse '%s' as a line number", cmd);
8074 } else if (cmd && iscommit(cmd)) {
8075 string_ncopy(opt_search, cmd, strlen(cmd));
8077 request = view_request(view, REQ_JUMP_COMMIT);
8078 if (request == REQ_JUMP_COMMIT) {
8079 report("Jumping to commits is not supported by the '%s' view", view->name);
8082 } else if (cmd) {
8083 struct view *next = VIEW(REQ_VIEW_PAGER);
8084 const char *argv[SIZEOF_ARG] = { "git" };
8085 int argc = 1;
8087 /* When running random commands, initially show the
8088 * command in the title. However, it maybe later be
8089 * overwritten if a commit line is selected. */
8090 string_ncopy(next->ref, cmd, strlen(cmd));
8092 if (!argv_from_string(argv, &argc, cmd)) {
8093 report("Too many arguments");
8094 } else if (!format_argv(&next->argv, argv, FALSE)) {
8095 report("Argument formatting failed");
8096 } else {
8097 next->dir = NULL;
8098 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
8102 request = REQ_NONE;
8103 break;
8105 case REQ_SEARCH:
8106 case REQ_SEARCH_BACK:
8108 const char *prompt = request == REQ_SEARCH ? "/" : "?";
8109 char *search = read_prompt(prompt);
8111 if (search)
8112 string_ncopy(opt_search, search, strlen(search));
8113 else if (*opt_search)
8114 request = request == REQ_SEARCH ?
8115 REQ_FIND_NEXT :
8116 REQ_FIND_PREV;
8117 else
8118 request = REQ_NONE;
8119 break;
8121 default:
8122 break;
8126 quit(0);
8128 return 0;