Only set LINES and COLUMNS environment variables for external commands
[tig.git] / tig.c
blob42415380a621489d62844578b6af7d5fb6e020d0
1 /* Copyright (c) 2006-2013 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 "refs.h"
17 #include "graph.h"
18 #include "git.h"
20 static void TIG_NORETURN die(const char *err, ...) PRINTF_LIKE(1, 2);
21 static void warn(const char *msg, ...) PRINTF_LIKE(1, 2);
22 static void report(const char *msg, ...) PRINTF_LIKE(1, 2);
23 #define report_clear() report("%s", "")
25 static bool set_environment_variable(const char *name, const char *value);
28 enum input_status {
29 INPUT_OK,
30 INPUT_SKIP,
31 INPUT_STOP,
32 INPUT_CANCEL
35 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
37 static char *prompt_input(const char *prompt, input_handler handler, void *data);
38 static bool prompt_yesno(const char *prompt);
39 static char *read_prompt(const char *prompt);
41 struct menu_item {
42 int hotkey;
43 const char *text;
44 void *data;
47 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
49 #define GRAPHIC_ENUM(_) \
50 _(GRAPHIC, ASCII), \
51 _(GRAPHIC, DEFAULT), \
52 _(GRAPHIC, UTF_8)
54 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
56 #define DATE_ENUM(_) \
57 _(DATE, NO), \
58 _(DATE, DEFAULT), \
59 _(DATE, LOCAL), \
60 _(DATE, RELATIVE), \
61 _(DATE, SHORT)
63 DEFINE_ENUM(date, DATE_ENUM);
65 struct time {
66 time_t sec;
67 int tz;
70 static inline int timecmp(const struct time *t1, const struct time *t2)
72 return t1->sec - t2->sec;
75 static const char *
76 mkdate(const struct time *time, enum date date)
78 static char buf[DATE_WIDTH + 1];
79 static const struct enum_map reldate[] = {
80 { "second", 1, 60 * 2 },
81 { "minute", 60, 60 * 60 * 2 },
82 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
83 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
84 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
85 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 365 },
86 { "year", 60 * 60 * 24 * 365, 0 },
88 struct tm tm;
90 if (!date || !time || !time->sec)
91 return "";
93 if (date == DATE_RELATIVE) {
94 struct timeval now;
95 time_t date = time->sec + time->tz;
96 time_t seconds;
97 int i;
99 gettimeofday(&now, NULL);
100 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
101 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
102 if (seconds >= reldate[i].value && reldate[i].value)
103 continue;
105 seconds /= reldate[i].namelen;
106 if (!string_format(buf, "%ld %s%s %s",
107 seconds, reldate[i].name,
108 seconds > 1 ? "s" : "",
109 now.tv_sec >= date ? "ago" : "ahead"))
110 break;
111 return buf;
115 if (date == DATE_LOCAL) {
116 time_t date = time->sec + time->tz;
117 localtime_r(&date, &tm);
119 else {
120 gmtime_r(&time->sec, &tm);
122 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
126 #define AUTHOR_ENUM(_) \
127 _(AUTHOR, NO), \
128 _(AUTHOR, FULL), \
129 _(AUTHOR, ABBREVIATED), \
130 _(AUTHOR, EMAIL), \
131 _(AUTHOR, EMAIL_USER)
133 DEFINE_ENUM(author, AUTHOR_ENUM);
135 struct ident {
136 const char *name;
137 const char *email;
140 static const struct ident unknown_ident = { "Unknown", "unknown@localhost" };
142 static inline int
143 ident_compare(const struct ident *i1, const struct ident *i2)
145 if (!i1 || !i2)
146 return (!!i1) - (!!i2);
147 if (!i1->name || !i2->name)
148 return (!!i1->name) - (!!i2->name);
149 return strcmp(i1->name, i2->name);
152 static const char *
153 get_author_initials(const char *author)
155 static char initials[AUTHOR_WIDTH * 6 + 1];
156 size_t pos = 0;
157 const char *end = strchr(author, '\0');
159 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
161 memset(initials, 0, sizeof(initials));
162 while (author < end) {
163 unsigned char bytes;
164 size_t i;
166 while (author < end && is_initial_sep(*author))
167 author++;
169 bytes = utf8_char_length(author, end);
170 if (bytes >= sizeof(initials) - 1 - pos)
171 break;
172 while (bytes--) {
173 initials[pos++] = *author++;
176 i = pos;
177 while (author < end && !is_initial_sep(*author)) {
178 bytes = utf8_char_length(author, end);
179 if (bytes >= sizeof(initials) - 1 - i) {
180 while (author < end && !is_initial_sep(*author))
181 author++;
182 break;
184 while (bytes--) {
185 initials[i++] = *author++;
189 initials[i++] = 0;
192 return initials;
195 static const char *
196 get_email_user(const char *email)
198 static char user[AUTHOR_WIDTH * 6 + 1];
199 const char *end = strchr(email, '@');
200 int length = end ? end - email : strlen(email);
202 string_format(user, "%.*s%c", length, email, 0);
203 return user;
206 #define author_trim(cols) (cols == 0 || cols > 10)
208 static const char *
209 mkauthor(const struct ident *ident, int cols, enum author author)
211 bool trim = author_trim(cols);
212 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
214 if (author == AUTHOR_NO || !ident)
215 return "";
216 if (author == AUTHOR_EMAIL && ident->email)
217 return ident->email;
218 if (author == AUTHOR_EMAIL_USER && ident->email)
219 return get_email_user(ident->email);
220 if (abbreviate && ident->name)
221 return get_author_initials(ident->name);
222 return ident->name;
225 static const char *
226 mkmode(mode_t mode)
228 if (S_ISDIR(mode))
229 return "drwxr-xr-x";
230 else if (S_ISLNK(mode))
231 return "lrwxrwxrwx";
232 else if (S_ISGITLINK(mode))
233 return "m---------";
234 else if (S_ISREG(mode) && mode & S_IXUSR)
235 return "-rwxr-xr-x";
236 else if (S_ISREG(mode))
237 return "-rw-r--r--";
238 else
239 return "----------";
242 static char *
243 get_temp_dir(void)
245 static char *tmp;
247 if (tmp)
248 return tmp;
250 if (!tmp)
251 tmp = getenv("TMPDIR");
252 if (!tmp)
253 tmp = getenv("TEMP");
254 if (!tmp)
255 tmp = getenv("TMP");
257 if (tmp)
258 tmp = strdup(tmp);
259 if (!tmp)
260 tmp = "/tmp";
262 return tmp;
265 #define FILENAME_ENUM(_) \
266 _(FILENAME, NO), \
267 _(FILENAME, ALWAYS), \
268 _(FILENAME, AUTO)
270 DEFINE_ENUM(filename, FILENAME_ENUM);
272 #define IGNORE_SPACE_ENUM(_) \
273 _(IGNORE_SPACE, NO), \
274 _(IGNORE_SPACE, ALL), \
275 _(IGNORE_SPACE, SOME), \
276 _(IGNORE_SPACE, AT_EOL)
278 DEFINE_ENUM(ignore_space, IGNORE_SPACE_ENUM);
280 #define COMMIT_ORDER_ENUM(_) \
281 _(COMMIT_ORDER, DEFAULT), \
282 _(COMMIT_ORDER, TOPO), \
283 _(COMMIT_ORDER, DATE), \
284 _(COMMIT_ORDER, REVERSE)
286 DEFINE_ENUM(commit_order, COMMIT_ORDER_ENUM);
288 #define VIEW_INFO(_) \
289 _(MAIN, main, ref_head), \
290 _(DIFF, diff, ref_commit), \
291 _(LOG, log, ref_head), \
292 _(TREE, tree, ref_commit), \
293 _(BLOB, blob, ref_blob), \
294 _(BLAME, blame, ref_commit), \
295 _(BRANCH, branch, ref_head), \
296 _(HELP, help, ""), \
297 _(PAGER, pager, ""), \
298 _(STATUS, status, "status"), \
299 _(STAGE, stage, ref_status), \
300 _(STASH, stash, ref_stash)
302 static struct encoding *
303 get_path_encoding(const char *path, struct encoding *default_encoding)
305 const char *check_attr_argv[] = {
306 "git", "check-attr", "encoding", "--", path, NULL
308 char buf[SIZEOF_STR];
309 char *encoding;
311 /* <path>: encoding: <encoding> */
313 if (!*path || !io_run_buf(check_attr_argv, buf, sizeof(buf))
314 || !(encoding = strstr(buf, ENCODING_SEP)))
315 return default_encoding;
317 encoding += STRING_SIZE(ENCODING_SEP);
318 if (!strcmp(encoding, ENCODING_UTF8)
319 || !strcmp(encoding, "unspecified")
320 || !strcmp(encoding, "set"))
321 return default_encoding;
323 return encoding_open(encoding);
327 * User requests
330 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
332 #define REQ_INFO \
333 REQ_GROUP("View switching") \
334 VIEW_INFO(VIEW_REQ), \
336 REQ_GROUP("View manipulation") \
337 REQ_(ENTER, "Enter current line and scroll"), \
338 REQ_(NEXT, "Move to next"), \
339 REQ_(PREVIOUS, "Move to previous"), \
340 REQ_(PARENT, "Move to parent"), \
341 REQ_(VIEW_NEXT, "Move focus to next view"), \
342 REQ_(REFRESH, "Reload and refresh"), \
343 REQ_(MAXIMIZE, "Maximize the current view"), \
344 REQ_(VIEW_CLOSE, "Close the current view"), \
345 REQ_(QUIT, "Close all views and quit"), \
347 REQ_GROUP("View specific requests") \
348 REQ_(STATUS_UPDATE, "Update file status"), \
349 REQ_(STATUS_REVERT, "Revert file changes"), \
350 REQ_(STATUS_MERGE, "Merge file using external tool"), \
351 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
352 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
353 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
354 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
356 REQ_GROUP("Cursor navigation") \
357 REQ_(MOVE_UP, "Move cursor one line up"), \
358 REQ_(MOVE_DOWN, "Move cursor one line down"), \
359 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
360 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
361 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
362 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
364 REQ_GROUP("Scrolling") \
365 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
366 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
367 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
368 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
369 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
370 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
371 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
373 REQ_GROUP("Searching") \
374 REQ_(SEARCH, "Search the view"), \
375 REQ_(SEARCH_BACK, "Search backwards in the view"), \
376 REQ_(FIND_NEXT, "Find next search match"), \
377 REQ_(FIND_PREV, "Find previous search match"), \
379 REQ_GROUP("Option manipulation") \
380 REQ_(OPTIONS, "Open option menu"), \
381 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
382 REQ_(TOGGLE_DATE, "Toggle date display"), \
383 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
384 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
385 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
386 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
387 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
388 REQ_(TOGGLE_CHANGES, "Toggle local changes display in the main view"), \
389 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
390 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
391 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
392 REQ_(TOGGLE_COMMIT_ORDER, "Toggle commit ordering"), \
393 REQ_(TOGGLE_ID, "Toggle commit ID display"), \
394 REQ_(TOGGLE_FILES, "Toggle file filtering"), \
395 REQ_(TOGGLE_TITLE_OVERFLOW, "Toggle highlighting of commit title overflow"), \
397 REQ_GROUP("Misc") \
398 REQ_(PROMPT, "Bring up the prompt"), \
399 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
400 REQ_(SHOW_VERSION, "Show version information"), \
401 REQ_(STOP_LOADING, "Stop all loading views"), \
402 REQ_(EDIT, "Open in editor"), \
403 REQ_(NONE, "Do nothing")
406 /* User action requests. */
407 enum request {
408 #define REQ_GROUP(help)
409 #define REQ_(req, help) REQ_##req
411 /* Offset all requests to avoid conflicts with ncurses getch values. */
412 REQ_UNKNOWN = KEY_MAX + 1,
413 REQ_OFFSET,
414 REQ_INFO,
416 /* Internal requests. */
417 REQ_JUMP_COMMIT,
419 #undef REQ_GROUP
420 #undef REQ_
423 struct request_info {
424 enum request request;
425 const char *name;
426 int namelen;
427 const char *help;
430 static const struct request_info req_info[] = {
431 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
432 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
433 REQ_INFO
434 #undef REQ_GROUP
435 #undef REQ_
438 static enum request
439 get_request(const char *name)
441 int namelen = strlen(name);
442 int i;
444 for (i = 0; i < ARRAY_SIZE(req_info); i++)
445 if (enum_equals(req_info[i], name, namelen))
446 return req_info[i].request;
448 return REQ_UNKNOWN;
453 * Options
456 /* Option and state variables. */
457 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
458 static enum date opt_date = DATE_DEFAULT;
459 static enum author opt_author = AUTHOR_FULL;
460 static enum filename opt_filename = FILENAME_AUTO;
461 static bool opt_rev_graph = TRUE;
462 static bool opt_line_number = FALSE;
463 static bool opt_show_refs = TRUE;
464 static bool opt_show_changes = TRUE;
465 static bool opt_untracked_dirs_content = TRUE;
466 static bool opt_read_git_colors = TRUE;
467 static bool opt_wrap_lines = FALSE;
468 static bool opt_ignore_case = FALSE;
469 static bool opt_stdin = FALSE;
470 static bool opt_focus_child = TRUE;
471 static int opt_diff_context = 3;
472 static char opt_diff_context_arg[9] = "";
473 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
474 static char opt_ignore_space_arg[22] = "";
475 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
476 static char opt_commit_order_arg[22] = "";
477 static bool opt_notes = TRUE;
478 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
479 static int opt_num_interval = 5;
480 static double opt_hscroll = 0.50;
481 static double opt_scale_split_view = 2.0 / 3.0;
482 static double opt_scale_vsplit_view = 0.5;
483 static bool opt_vsplit = FALSE;
484 static int opt_tab_size = 8;
485 static int opt_author_width = AUTHOR_WIDTH;
486 static int opt_filename_width = FILENAME_WIDTH;
487 static char opt_path[SIZEOF_STR] = "";
488 static char opt_file[SIZEOF_STR] = "";
489 static char opt_ref[SIZEOF_REF] = "";
490 static unsigned long opt_goto_line = 0;
491 static char opt_head[SIZEOF_REF] = "";
492 static char opt_remote[SIZEOF_REF] = "";
493 static struct encoding *opt_encoding = NULL;
494 static char opt_encoding_arg[SIZEOF_STR] = ENCODING_ARG;
495 static iconv_t opt_iconv_out = ICONV_NONE;
496 static char opt_search[SIZEOF_STR] = "";
497 static char opt_cdup[SIZEOF_STR] = "";
498 static char opt_prefix[SIZEOF_STR] = "";
499 static char opt_git_dir[SIZEOF_STR] = "";
500 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
501 static char opt_editor[SIZEOF_STR] = "";
502 static bool opt_editor_lineno = TRUE;
503 static FILE *opt_tty = NULL;
504 static const char **opt_diff_argv = NULL;
505 static const char **opt_rev_argv = NULL;
506 static const char **opt_file_argv = NULL;
507 static const char **opt_blame_argv = NULL;
508 static int opt_lineno = 0;
509 static bool opt_show_id = FALSE;
510 static int opt_id_cols = ID_WIDTH;
511 static bool opt_file_filter = TRUE;
512 static bool opt_show_title_overflow = FALSE;
513 static int opt_title_overflow = 50;
514 static char opt_env_lines[64] = "";
515 static char opt_env_columns[64] = "";
516 static char *opt_env[] = { opt_env_lines, opt_env_columns, NULL };
518 #define is_initial_commit() (!get_ref_head())
519 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strncmp(rev, get_ref_head()->id, SIZEOF_REV - 1)))
520 #define load_refs() reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head))
522 static inline void
523 update_diff_context_arg(int diff_context)
525 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
526 string_ncopy(opt_diff_context_arg, "-U3", 3);
529 static inline void
530 update_ignore_space_arg()
532 if (opt_ignore_space == IGNORE_SPACE_ALL) {
533 string_copy(opt_ignore_space_arg, "--ignore-all-space");
534 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
535 string_copy(opt_ignore_space_arg, "--ignore-space-change");
536 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
537 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
538 } else {
539 string_copy(opt_ignore_space_arg, "");
543 static inline void
544 update_commit_order_arg()
546 if (opt_commit_order == COMMIT_ORDER_TOPO) {
547 string_copy(opt_commit_order_arg, "--topo-order");
548 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
549 string_copy(opt_commit_order_arg, "--date-order");
550 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
551 string_copy(opt_commit_order_arg, "--reverse");
552 } else {
553 string_copy(opt_commit_order_arg, "");
557 static inline void
558 update_notes_arg()
560 if (opt_notes) {
561 string_copy(opt_notes_arg, "--show-notes");
562 } else {
563 /* Notes are disabled by default when passing --pretty args. */
564 string_copy(opt_notes_arg, "");
569 * Line-oriented content detection.
572 #define LINE_INFO \
573 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
574 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
575 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
576 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
577 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
578 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
579 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
580 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
581 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
582 LINE(DIFF_DELETED_FILE_MODE, \
583 "deleted file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
584 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
585 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
586 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
587 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
588 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
589 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
590 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
591 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
592 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
593 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
594 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
595 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
596 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
597 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
598 LINE(STASH, "stash@{", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
599 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
600 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
601 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
602 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
603 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
604 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
605 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
606 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
607 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
608 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
609 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
610 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
611 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
612 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
613 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
614 LINE(ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
615 LINE(OVERFLOW, "", COLOR_RED, COLOR_DEFAULT, 0), \
616 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
617 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
618 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
619 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
620 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
621 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
622 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
623 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
624 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
625 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
626 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
627 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
628 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
629 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
630 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
631 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
632 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
633 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
634 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
635 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
636 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
637 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
638 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
639 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
640 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
641 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
642 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
643 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
644 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
645 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
646 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
647 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
648 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
650 enum line_type {
651 #define LINE(type, line, fg, bg, attr) \
652 LINE_##type
653 LINE_INFO,
654 LINE_NONE
655 #undef LINE
658 struct line_info {
659 const char *name; /* Option name. */
660 int namelen; /* Size of option name. */
661 const char *line; /* The start of line to match. */
662 int linelen; /* Size of string to match. */
663 int fg, bg, attr; /* Color and text attributes for the lines. */
664 int color_pair;
667 static struct line_info line_info[] = {
668 #define LINE(type, line, fg, bg, attr) \
669 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
670 LINE_INFO
671 #undef LINE
674 static struct line_info **color_pair;
675 static size_t color_pairs;
677 static struct line_info *custom_color;
678 static size_t custom_colors;
680 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
681 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
683 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
684 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
686 /* Color IDs must be 1 or higher. [GH #15] */
687 #define COLOR_ID(line_type) ((line_type) + 1)
689 static enum line_type
690 get_line_type(const char *line)
692 int linelen = strlen(line);
693 enum line_type type;
695 for (type = 0; type < custom_colors; type++)
696 /* Case insensitive search matches Signed-off-by lines better. */
697 if (linelen >= custom_color[type].linelen &&
698 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
699 return TO_CUSTOM_COLOR_TYPE(type);
701 for (type = 0; type < ARRAY_SIZE(line_info); type++)
702 /* Case insensitive search matches Signed-off-by lines better. */
703 if (linelen >= line_info[type].linelen &&
704 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
705 return type;
707 return LINE_DEFAULT;
710 static enum line_type
711 get_line_type_from_ref(const struct ref *ref)
713 if (ref->head)
714 return LINE_MAIN_HEAD;
715 else if (ref->ltag)
716 return LINE_MAIN_LOCAL_TAG;
717 else if (ref->tag)
718 return LINE_MAIN_TAG;
719 else if (ref->tracked)
720 return LINE_MAIN_TRACKED;
721 else if (ref->remote)
722 return LINE_MAIN_REMOTE;
723 else if (ref->replace)
724 return LINE_MAIN_REPLACE;
726 return LINE_MAIN_REF;
729 static inline struct line_info *
730 get_line(enum line_type type)
732 if (type > LINE_NONE) {
733 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
734 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
735 } else {
736 assert(type < ARRAY_SIZE(line_info));
737 return &line_info[type];
741 static inline int
742 get_line_color(enum line_type type)
744 return COLOR_ID(get_line(type)->color_pair);
747 static inline int
748 get_line_attr(enum line_type type)
750 struct line_info *info = get_line(type);
752 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
755 static struct line_info *
756 get_line_info(const char *name)
758 size_t namelen = strlen(name);
759 enum line_type type;
761 for (type = 0; type < ARRAY_SIZE(line_info); type++)
762 if (enum_equals(line_info[type], name, namelen))
763 return &line_info[type];
765 return NULL;
768 static struct line_info *
769 add_custom_color(const char *quoted_line)
771 struct line_info *info;
772 char *line;
773 size_t linelen;
775 if (!realloc_custom_color(&custom_color, custom_colors, 1))
776 die("Failed to alloc custom line info");
778 linelen = strlen(quoted_line) - 1;
779 line = malloc(linelen);
780 if (!line)
781 return NULL;
783 strncpy(line, quoted_line + 1, linelen);
784 line[linelen - 1] = 0;
786 info = &custom_color[custom_colors++];
787 info->name = info->line = line;
788 info->namelen = info->linelen = strlen(line);
790 return info;
793 static void
794 init_line_info_color_pair(struct line_info *info, enum line_type type,
795 int default_bg, int default_fg)
797 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
798 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
799 int i;
801 for (i = 0; i < color_pairs; i++) {
802 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
803 info->color_pair = i;
804 return;
808 if (!realloc_color_pair(&color_pair, color_pairs, 1))
809 die("Failed to alloc color pair");
811 color_pair[color_pairs] = info;
812 info->color_pair = color_pairs++;
813 init_pair(COLOR_ID(info->color_pair), fg, bg);
816 static void
817 init_colors(void)
819 int default_bg = line_info[LINE_DEFAULT].bg;
820 int default_fg = line_info[LINE_DEFAULT].fg;
821 enum line_type type;
823 start_color();
825 if (assume_default_colors(default_fg, default_bg) == ERR) {
826 default_bg = COLOR_BLACK;
827 default_fg = COLOR_WHITE;
830 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
831 struct line_info *info = &line_info[type];
833 init_line_info_color_pair(info, type, default_bg, default_fg);
836 for (type = 0; type < custom_colors; type++) {
837 struct line_info *info = &custom_color[type];
839 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
840 default_bg, default_fg);
844 struct line {
845 enum line_type type;
846 unsigned int lineno:24;
848 /* State flags */
849 unsigned int selected:1;
850 unsigned int dirty:1;
851 unsigned int cleareol:1;
852 unsigned int dont_free:1;
853 unsigned int wrapped:1;
855 unsigned int user_flags:6;
856 void *data; /* User data */
861 * Keys
864 struct keybinding {
865 int alias;
866 enum request request;
869 static struct keybinding default_keybindings[] = {
870 /* View switching */
871 { 'm', REQ_VIEW_MAIN },
872 { 'd', REQ_VIEW_DIFF },
873 { 'l', REQ_VIEW_LOG },
874 { 't', REQ_VIEW_TREE },
875 { 'f', REQ_VIEW_BLOB },
876 { 'B', REQ_VIEW_BLAME },
877 { 'H', REQ_VIEW_BRANCH },
878 { 'p', REQ_VIEW_PAGER },
879 { 'h', REQ_VIEW_HELP },
880 { 'S', REQ_VIEW_STATUS },
881 { 'c', REQ_VIEW_STAGE },
882 { 'y', REQ_VIEW_STASH },
884 /* View manipulation */
885 { 'q', REQ_VIEW_CLOSE },
886 { KEY_TAB, REQ_VIEW_NEXT },
887 { KEY_RETURN, REQ_ENTER },
888 { KEY_UP, REQ_PREVIOUS },
889 { KEY_CTL('P'), REQ_PREVIOUS },
890 { KEY_DOWN, REQ_NEXT },
891 { KEY_CTL('N'), REQ_NEXT },
892 { 'R', REQ_REFRESH },
893 { KEY_F(5), REQ_REFRESH },
894 { 'O', REQ_MAXIMIZE },
895 { ',', REQ_PARENT },
897 /* View specific */
898 { 'u', REQ_STATUS_UPDATE },
899 { '!', REQ_STATUS_REVERT },
900 { 'M', REQ_STATUS_MERGE },
901 { '1', REQ_STAGE_UPDATE_LINE },
902 { '@', REQ_STAGE_NEXT },
903 { '[', REQ_DIFF_CONTEXT_DOWN },
904 { ']', REQ_DIFF_CONTEXT_UP },
906 /* Cursor navigation */
907 { 'k', REQ_MOVE_UP },
908 { 'j', REQ_MOVE_DOWN },
909 { KEY_HOME, REQ_MOVE_FIRST_LINE },
910 { KEY_END, REQ_MOVE_LAST_LINE },
911 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
912 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
913 { ' ', REQ_MOVE_PAGE_DOWN },
914 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
915 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
916 { 'b', REQ_MOVE_PAGE_UP },
917 { '-', REQ_MOVE_PAGE_UP },
919 /* Scrolling */
920 { '|', REQ_SCROLL_FIRST_COL },
921 { KEY_LEFT, REQ_SCROLL_LEFT },
922 { KEY_RIGHT, REQ_SCROLL_RIGHT },
923 { KEY_IC, REQ_SCROLL_LINE_UP },
924 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
925 { KEY_DC, REQ_SCROLL_LINE_DOWN },
926 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
927 { 'w', REQ_SCROLL_PAGE_UP },
928 { 's', REQ_SCROLL_PAGE_DOWN },
930 /* Searching */
931 { '/', REQ_SEARCH },
932 { '?', REQ_SEARCH_BACK },
933 { 'n', REQ_FIND_NEXT },
934 { 'N', REQ_FIND_PREV },
936 /* Misc */
937 { 'Q', REQ_QUIT },
938 { 'z', REQ_STOP_LOADING },
939 { 'v', REQ_SHOW_VERSION },
940 { 'r', REQ_SCREEN_REDRAW },
941 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
942 { 'o', REQ_OPTIONS },
943 { '.', REQ_TOGGLE_LINENO },
944 { 'D', REQ_TOGGLE_DATE },
945 { 'A', REQ_TOGGLE_AUTHOR },
946 { 'g', REQ_TOGGLE_REV_GRAPH },
947 { '~', REQ_TOGGLE_GRAPHIC },
948 { '#', REQ_TOGGLE_FILENAME },
949 { 'F', REQ_TOGGLE_REFS },
950 { 'I', REQ_TOGGLE_SORT_ORDER },
951 { 'i', REQ_TOGGLE_SORT_FIELD },
952 { 'W', REQ_TOGGLE_IGNORE_SPACE },
953 { 'X', REQ_TOGGLE_ID },
954 { '%', REQ_TOGGLE_FILES },
955 { '$', REQ_TOGGLE_TITLE_OVERFLOW },
956 { ':', REQ_PROMPT },
957 { 'e', REQ_EDIT },
960 struct keymap {
961 const char *name;
962 struct keymap *next;
963 struct keybinding *data;
964 size_t size;
965 bool hidden;
968 static struct keymap generic_keymap = { "generic" };
969 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
971 static struct keymap *keymaps = &generic_keymap;
973 static void
974 add_keymap(struct keymap *keymap)
976 keymap->next = keymaps;
977 keymaps = keymap;
980 static struct keymap *
981 get_keymap(const char *name)
983 struct keymap *keymap = keymaps;
985 while (keymap) {
986 if (!strcasecmp(keymap->name, name))
987 return keymap;
988 keymap = keymap->next;
991 return NULL;
995 static void
996 add_keybinding(struct keymap *table, enum request request, int key)
998 size_t i;
1000 for (i = 0; i < table->size; i++) {
1001 if (table->data[i].alias == key) {
1002 table->data[i].request = request;
1003 return;
1007 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
1008 if (!table->data)
1009 die("Failed to allocate keybinding");
1010 table->data[table->size].alias = key;
1011 table->data[table->size++].request = request;
1013 if (request == REQ_NONE && is_generic_keymap(table)) {
1014 int i;
1016 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1017 if (default_keybindings[i].alias == key)
1018 default_keybindings[i].request = REQ_NONE;
1022 /* Looks for a key binding first in the given map, then in the generic map, and
1023 * lastly in the default keybindings. */
1024 static enum request
1025 get_keybinding(struct keymap *keymap, int key)
1027 size_t i;
1029 for (i = 0; i < keymap->size; i++)
1030 if (keymap->data[i].alias == key)
1031 return keymap->data[i].request;
1033 for (i = 0; i < generic_keymap.size; i++)
1034 if (generic_keymap.data[i].alias == key)
1035 return generic_keymap.data[i].request;
1037 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1038 if (default_keybindings[i].alias == key)
1039 return default_keybindings[i].request;
1041 return (enum request) key;
1045 struct key {
1046 const char *name;
1047 int value;
1050 static const struct key key_table[] = {
1051 { "Enter", KEY_RETURN },
1052 { "Space", ' ' },
1053 { "Backspace", KEY_BACKSPACE },
1054 { "Tab", KEY_TAB },
1055 { "Escape", KEY_ESC },
1056 { "Left", KEY_LEFT },
1057 { "Right", KEY_RIGHT },
1058 { "Up", KEY_UP },
1059 { "Down", KEY_DOWN },
1060 { "Insert", KEY_IC },
1061 { "Delete", KEY_DC },
1062 { "Hash", '#' },
1063 { "Home", KEY_HOME },
1064 { "End", KEY_END },
1065 { "PageUp", KEY_PPAGE },
1066 { "PageDown", KEY_NPAGE },
1067 { "F1", KEY_F(1) },
1068 { "F2", KEY_F(2) },
1069 { "F3", KEY_F(3) },
1070 { "F4", KEY_F(4) },
1071 { "F5", KEY_F(5) },
1072 { "F6", KEY_F(6) },
1073 { "F7", KEY_F(7) },
1074 { "F8", KEY_F(8) },
1075 { "F9", KEY_F(9) },
1076 { "F10", KEY_F(10) },
1077 { "F11", KEY_F(11) },
1078 { "F12", KEY_F(12) },
1081 static int
1082 get_key_value(const char *name)
1084 int i;
1086 for (i = 0; i < ARRAY_SIZE(key_table); i++)
1087 if (!strcasecmp(key_table[i].name, name))
1088 return key_table[i].value;
1090 if (strlen(name) == 3 && name[0] == '^' && name[1] == '[' && isprint(*name))
1091 return (int)name[2] + 0x80;
1092 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1093 return (int)name[1] & 0x1f;
1094 if (strlen(name) == 1 && isprint(*name))
1095 return (int) *name;
1096 return ERR;
1099 static const char *
1100 get_key_name(int key_value)
1102 static char key_char[] = "'X'\0";
1103 const char *seq = NULL;
1104 int key;
1106 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1107 if (key_table[key].value == key_value)
1108 seq = key_table[key].name;
1110 if (seq == NULL && key_value < 0x7f) {
1111 char *s = key_char + 1;
1113 if (key_value >= 0x20) {
1114 *s++ = key_value;
1115 } else {
1116 *s++ = '^';
1117 *s++ = 0x40 | (key_value & 0x1f);
1119 *s++ = '\'';
1120 *s++ = '\0';
1121 seq = key_char;
1124 return seq ? seq : "(no key)";
1127 static bool
1128 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1130 const char *sep = *pos > 0 ? ", " : "";
1131 const char *keyname = get_key_name(keybinding->alias);
1133 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1136 static bool
1137 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1138 struct keymap *keymap, bool all)
1140 int i;
1142 for (i = 0; i < keymap->size; i++) {
1143 if (keymap->data[i].request == request) {
1144 if (!append_key(buf, pos, &keymap->data[i]))
1145 return FALSE;
1146 if (!all)
1147 break;
1151 return TRUE;
1154 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1156 static const char *
1157 get_keys(struct keymap *keymap, enum request request, bool all)
1159 static char buf[BUFSIZ];
1160 size_t pos = 0;
1161 int i;
1163 buf[pos] = 0;
1165 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1166 return "Too many keybindings!";
1167 if (pos > 0 && !all)
1168 return buf;
1170 if (!is_generic_keymap(keymap)) {
1171 /* Only the generic keymap includes the default keybindings when
1172 * listing all keys. */
1173 if (all)
1174 return buf;
1176 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1177 return "Too many keybindings!";
1178 if (pos)
1179 return buf;
1182 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1183 if (default_keybindings[i].request == request) {
1184 if (!append_key(buf, &pos, &default_keybindings[i]))
1185 return "Too many keybindings!";
1186 if (!all)
1187 return buf;
1191 return buf;
1194 enum run_request_flag {
1195 RUN_REQUEST_DEFAULT = 0,
1196 RUN_REQUEST_FORCE = 1,
1197 RUN_REQUEST_SILENT = 2,
1198 RUN_REQUEST_CONFIRM = 4,
1199 RUN_REQUEST_EXIT = 8,
1200 RUN_REQUEST_INTERNAL = 16,
1203 struct run_request {
1204 struct keymap *keymap;
1205 int key;
1206 const char **argv;
1207 bool silent;
1208 bool confirm;
1209 bool exit;
1210 bool internal;
1213 static struct run_request *run_request;
1214 static size_t run_requests;
1216 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1218 static bool
1219 add_run_request(struct keymap *keymap, int key, const char **argv, enum run_request_flag flags)
1221 bool force = flags & RUN_REQUEST_FORCE;
1222 struct run_request *req;
1224 if (!force && get_keybinding(keymap, key) != key)
1225 return TRUE;
1227 if (!realloc_run_requests(&run_request, run_requests, 1))
1228 return FALSE;
1230 if (!argv_copy(&run_request[run_requests].argv, argv))
1231 return FALSE;
1233 req = &run_request[run_requests++];
1234 req->silent = flags & RUN_REQUEST_SILENT;
1235 req->confirm = flags & RUN_REQUEST_CONFIRM;
1236 req->exit = flags & RUN_REQUEST_EXIT;
1237 req->internal = flags & RUN_REQUEST_INTERNAL;
1238 req->keymap = keymap;
1239 req->key = key;
1241 add_keybinding(keymap, REQ_NONE + run_requests, key);
1242 return TRUE;
1245 static struct run_request *
1246 get_run_request(enum request request)
1248 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1249 return NULL;
1250 return &run_request[request - REQ_NONE - 1];
1253 static void
1254 add_builtin_run_requests(void)
1256 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1257 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1258 const char *commit[] = { "git", "commit", NULL };
1259 const char *gc[] = { "git", "gc", NULL };
1260 const char *stash_pop[] = { "git", "stash", "pop", "%(stash)", NULL };
1262 add_run_request(get_keymap("main"), 'C', cherry_pick, RUN_REQUEST_CONFIRM);
1263 add_run_request(get_keymap("status"), 'C', commit, RUN_REQUEST_DEFAULT);
1264 add_run_request(get_keymap("branch"), 'C', checkout, RUN_REQUEST_CONFIRM);
1265 add_run_request(get_keymap("generic"), 'G', gc, RUN_REQUEST_CONFIRM);
1266 add_run_request(get_keymap("stash"), 'P', stash_pop, RUN_REQUEST_CONFIRM);
1270 * User config file handling.
1273 #define OPT_ERR_INFO \
1274 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1275 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1276 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1277 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1278 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1279 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1280 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1281 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1282 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1283 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1284 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1285 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1286 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1287 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1288 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1289 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1290 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1291 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"), \
1292 OPT_ERR_(HOME_UNRESOLVABLE, "HOME environment variable could not be resolved"),
1294 enum option_code {
1295 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1296 OPT_ERR_INFO
1297 #undef OPT_ERR_
1298 OPT_OK
1301 static const char *option_errors[] = {
1302 #define OPT_ERR_(name, msg) msg
1303 OPT_ERR_INFO
1304 #undef OPT_ERR_
1307 static const struct enum_map color_map[] = {
1308 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1309 COLOR_MAP(DEFAULT),
1310 COLOR_MAP(BLACK),
1311 COLOR_MAP(BLUE),
1312 COLOR_MAP(CYAN),
1313 COLOR_MAP(GREEN),
1314 COLOR_MAP(MAGENTA),
1315 COLOR_MAP(RED),
1316 COLOR_MAP(WHITE),
1317 COLOR_MAP(YELLOW),
1320 static const struct enum_map attr_map[] = {
1321 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1322 ATTR_MAP(NORMAL),
1323 ATTR_MAP(BLINK),
1324 ATTR_MAP(BOLD),
1325 ATTR_MAP(DIM),
1326 ATTR_MAP(REVERSE),
1327 ATTR_MAP(STANDOUT),
1328 ATTR_MAP(UNDERLINE),
1331 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1333 static enum option_code
1334 parse_step(double *opt, const char *arg)
1336 *opt = atoi(arg);
1337 if (!strchr(arg, '%'))
1338 return OPT_OK;
1340 /* "Shift down" so 100% and 1 does not conflict. */
1341 *opt = (*opt - 1) / 100;
1342 if (*opt >= 1.0) {
1343 *opt = 0.99;
1344 return OPT_ERR_INVALID_STEP_VALUE;
1346 if (*opt < 0.0) {
1347 *opt = 1;
1348 return OPT_ERR_INVALID_STEP_VALUE;
1350 return OPT_OK;
1353 static enum option_code
1354 parse_int(int *opt, const char *arg, int min, int max)
1356 int value = atoi(arg);
1358 if (min <= value && value <= max) {
1359 *opt = value;
1360 return OPT_OK;
1363 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1366 #define parse_id(opt, arg) \
1367 parse_int(opt, arg, 4, SIZEOF_REV - 1)
1369 static bool
1370 set_color(int *color, const char *name)
1372 if (map_enum(color, color_map, name))
1373 return TRUE;
1374 if (!prefixcmp(name, "color"))
1375 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1376 /* Used when reading git colors. Git expects a plain int w/o prefix. */
1377 return parse_int(color, name, 0, 255) == OPT_OK;
1380 /* Wants: object fgcolor bgcolor [attribute] */
1381 static enum option_code
1382 option_color_command(int argc, const char *argv[])
1384 struct line_info *info;
1386 if (argc < 3)
1387 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1389 if (*argv[0] == '"' || *argv[0] == '\'') {
1390 info = add_custom_color(argv[0]);
1391 } else {
1392 info = get_line_info(argv[0]);
1394 if (!info) {
1395 static const struct enum_map obsolete[] = {
1396 ENUM_MAP("main-delim", LINE_DELIMITER),
1397 ENUM_MAP("main-date", LINE_DATE),
1398 ENUM_MAP("main-author", LINE_AUTHOR),
1399 ENUM_MAP("blame-id", LINE_ID),
1401 int index;
1403 if (!map_enum(&index, obsolete, argv[0]))
1404 return OPT_ERR_UNKNOWN_COLOR_NAME;
1405 info = &line_info[index];
1408 if (!set_color(&info->fg, argv[1]) ||
1409 !set_color(&info->bg, argv[2]))
1410 return OPT_ERR_UNKNOWN_COLOR;
1412 info->attr = 0;
1413 while (argc-- > 3) {
1414 int attr;
1416 if (!set_attribute(&attr, argv[argc]))
1417 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1418 info->attr |= attr;
1421 return OPT_OK;
1424 static enum option_code
1425 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1427 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1428 ? TRUE : FALSE;
1429 if (matched)
1430 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1431 return OPT_OK;
1434 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1436 static enum option_code
1437 parse_enum_do(unsigned int *opt, const char *arg,
1438 const struct enum_map *map, size_t map_size)
1440 bool is_true;
1442 assert(map_size > 1);
1444 if (map_enum_do(map, map_size, (int *) opt, arg))
1445 return OPT_OK;
1447 parse_bool(&is_true, arg);
1448 *opt = is_true ? map[1].value : map[0].value;
1449 return OPT_OK;
1452 #define parse_enum(opt, arg, map) \
1453 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1455 static enum option_code
1456 parse_string(char *opt, const char *arg, size_t optsize)
1458 int arglen = strlen(arg);
1460 switch (arg[0]) {
1461 case '\"':
1462 case '\'':
1463 if (arglen == 1 || arg[arglen - 1] != arg[0])
1464 return OPT_ERR_UNMATCHED_QUOTATION;
1465 arg += 1; arglen -= 2;
1466 default:
1467 string_ncopy_do(opt, optsize, arg, arglen);
1468 return OPT_OK;
1472 static enum option_code
1473 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1475 char buf[SIZEOF_STR];
1476 enum option_code code = parse_string(buf, arg, sizeof(buf));
1478 if (code == OPT_OK) {
1479 struct encoding *encoding = *encoding_ref;
1481 if (encoding && !priority)
1482 return code;
1483 encoding = encoding_open(buf);
1484 if (encoding)
1485 *encoding_ref = encoding;
1488 return code;
1491 static enum option_code
1492 parse_args(const char ***args, const char *argv[])
1494 if (!argv_copy(args, argv))
1495 return OPT_ERR_OUT_OF_MEMORY;
1496 return OPT_OK;
1499 /* Wants: name = value */
1500 static enum option_code
1501 option_set_command(int argc, const char *argv[])
1503 if (argc < 3)
1504 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1506 if (strcmp(argv[1], "="))
1507 return OPT_ERR_NO_VALUE_ASSIGNED;
1509 if (!strcmp(argv[0], "blame-options"))
1510 return parse_args(&opt_blame_argv, argv + 2);
1512 if (!strcmp(argv[0], "diff-options"))
1513 return parse_args(&opt_diff_argv, argv + 2);
1515 if (argc != 3)
1516 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1518 if (!strcmp(argv[0], "show-author"))
1519 return parse_enum(&opt_author, argv[2], author_map);
1521 if (!strcmp(argv[0], "show-date"))
1522 return parse_enum(&opt_date, argv[2], date_map);
1524 if (!strcmp(argv[0], "show-rev-graph"))
1525 return parse_bool(&opt_rev_graph, argv[2]);
1527 if (!strcmp(argv[0], "show-refs"))
1528 return parse_bool(&opt_show_refs, argv[2]);
1530 if (!strcmp(argv[0], "show-changes"))
1531 return parse_bool(&opt_show_changes, argv[2]);
1533 if (!strcmp(argv[0], "show-notes")) {
1534 bool matched = FALSE;
1535 enum option_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1537 if (res == OPT_OK && matched) {
1538 update_notes_arg();
1539 return res;
1542 opt_notes = TRUE;
1543 strcpy(opt_notes_arg, "--show-notes=");
1544 res = parse_string(opt_notes_arg + 8, argv[2],
1545 sizeof(opt_notes_arg) - 8);
1546 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1547 opt_notes_arg[7] = '\0';
1548 return res;
1551 if (!strcmp(argv[0], "show-line-numbers"))
1552 return parse_bool(&opt_line_number, argv[2]);
1554 if (!strcmp(argv[0], "line-graphics"))
1555 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1557 if (!strcmp(argv[0], "line-number-interval"))
1558 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1560 if (!strcmp(argv[0], "author-width"))
1561 return parse_int(&opt_author_width, argv[2], 0, 1024);
1563 if (!strcmp(argv[0], "filename-width"))
1564 return parse_int(&opt_filename_width, argv[2], 0, 1024);
1566 if (!strcmp(argv[0], "show-filename"))
1567 return parse_enum(&opt_filename, argv[2], filename_map);
1569 if (!strcmp(argv[0], "horizontal-scroll"))
1570 return parse_step(&opt_hscroll, argv[2]);
1572 if (!strcmp(argv[0], "split-view-height"))
1573 return parse_step(&opt_scale_split_view, argv[2]);
1575 if (!strcmp(argv[0], "vertical-split"))
1576 return parse_bool(&opt_vsplit, argv[2]);
1578 if (!strcmp(argv[0], "tab-size"))
1579 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1581 if (!strcmp(argv[0], "diff-context")) {
1582 enum option_code code = parse_int(&opt_diff_context, argv[2], 0, 999999);
1584 if (code == OPT_OK)
1585 update_diff_context_arg(opt_diff_context);
1586 return code;
1589 if (!strcmp(argv[0], "ignore-space")) {
1590 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1592 if (code == OPT_OK)
1593 update_ignore_space_arg();
1594 return code;
1597 if (!strcmp(argv[0], "commit-order")) {
1598 enum option_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1600 if (code == OPT_OK)
1601 update_commit_order_arg();
1602 return code;
1605 if (!strcmp(argv[0], "status-untracked-dirs"))
1606 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1608 if (!strcmp(argv[0], "read-git-colors"))
1609 return parse_bool(&opt_read_git_colors, argv[2]);
1611 if (!strcmp(argv[0], "ignore-case"))
1612 return parse_bool(&opt_ignore_case, argv[2]);
1614 if (!strcmp(argv[0], "focus-child"))
1615 return parse_bool(&opt_focus_child, argv[2]);
1617 if (!strcmp(argv[0], "wrap-lines"))
1618 return parse_bool(&opt_wrap_lines, argv[2]);
1620 if (!strcmp(argv[0], "show-id"))
1621 return parse_bool(&opt_show_id, argv[2]);
1623 if (!strcmp(argv[0], "id-width"))
1624 return parse_id(&opt_id_cols, argv[2]);
1626 if (!strcmp(argv[0], "title-overflow")) {
1627 bool matched;
1628 enum option_code code;
1631 * "title-overflow" is considered a boolint.
1632 * We try to parse it as a boolean (and set the value to 50 if true),
1633 * otherwise we parse it as an integer and use the given value.
1635 code = parse_bool_matched(&opt_show_title_overflow, argv[2], &matched);
1636 if (code == OPT_OK && matched) {
1637 if (opt_show_title_overflow)
1638 opt_title_overflow = 50;
1639 } else {
1640 code = parse_int(&opt_title_overflow, argv[2], 2, 1024);
1641 if (code == OPT_OK)
1642 opt_show_title_overflow = TRUE;
1645 return code;
1648 if (!strcmp(argv[0], "editor-line-number"))
1649 return parse_bool(&opt_editor_lineno, argv[2]);
1651 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1654 /* Wants: mode request key */
1655 static enum option_code
1656 option_bind_command(int argc, const char *argv[])
1658 enum request request;
1659 struct keymap *keymap;
1660 int key;
1662 if (argc < 3)
1663 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1665 if (!(keymap = get_keymap(argv[0])))
1666 return OPT_ERR_UNKNOWN_KEY_MAP;
1668 key = get_key_value(argv[1]);
1669 if (key == ERR)
1670 return OPT_ERR_UNKNOWN_KEY;
1672 request = get_request(argv[2]);
1673 if (request == REQ_UNKNOWN) {
1674 static const struct enum_map obsolete[] = {
1675 ENUM_MAP("cherry-pick", REQ_NONE),
1676 ENUM_MAP("screen-resize", REQ_NONE),
1677 ENUM_MAP("tree-parent", REQ_PARENT),
1679 int alias;
1681 if (map_enum(&alias, obsolete, argv[2])) {
1682 if (alias != REQ_NONE)
1683 add_keybinding(keymap, alias, key);
1684 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1688 if (request == REQ_UNKNOWN) {
1689 char first = *argv[2]++;
1691 if (first == '!') {
1692 enum run_request_flag flags = RUN_REQUEST_FORCE;
1694 while (*argv[2]) {
1695 if (*argv[2] == '@') {
1696 flags |= RUN_REQUEST_SILENT;
1697 } else if (*argv[2] == '?') {
1698 flags |= RUN_REQUEST_CONFIRM;
1699 } else if (*argv[2] == '<') {
1700 flags |= RUN_REQUEST_EXIT;
1701 } else {
1702 break;
1704 argv[2]++;
1707 return add_run_request(keymap, key, argv + 2, flags)
1708 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1709 } else if (first == ':') {
1710 return add_run_request(keymap, key, argv + 2, RUN_REQUEST_FORCE | RUN_REQUEST_INTERNAL)
1711 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1712 } else {
1713 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1717 add_keybinding(keymap, request, key);
1719 return OPT_OK;
1723 static enum option_code load_option_file(const char *path);
1725 static enum option_code
1726 option_source_command(int argc, const char *argv[])
1728 if (argc < 1)
1729 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1731 return load_option_file(argv[0]);
1734 static enum option_code
1735 set_option(const char *opt, char *value)
1737 const char *argv[SIZEOF_ARG];
1738 int argc = 0;
1740 if (!argv_from_string(argv, &argc, value))
1741 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1743 if (!strcmp(opt, "color"))
1744 return option_color_command(argc, argv);
1746 if (!strcmp(opt, "set"))
1747 return option_set_command(argc, argv);
1749 if (!strcmp(opt, "bind"))
1750 return option_bind_command(argc, argv);
1752 if (!strcmp(opt, "source"))
1753 return option_source_command(argc, argv);
1755 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1758 struct config_state {
1759 const char *path;
1760 int lineno;
1761 bool errors;
1764 static int
1765 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1767 struct config_state *config = data;
1768 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1770 config->lineno++;
1772 /* Check for comment markers, since read_properties() will
1773 * only ensure opt and value are split at first " \t". */
1774 optlen = strcspn(opt, "#");
1775 if (optlen == 0)
1776 return OK;
1778 if (opt[optlen] == 0) {
1779 /* Look for comment endings in the value. */
1780 size_t len = strcspn(value, "#");
1782 if (len < valuelen) {
1783 valuelen = len;
1784 value[valuelen] = 0;
1787 status = set_option(opt, value);
1790 if (status != OPT_OK) {
1791 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1792 option_errors[status], (int) optlen, opt);
1793 config->errors = TRUE;
1796 /* Always keep going if errors are encountered. */
1797 return OK;
1800 static enum option_code
1801 load_option_file(const char *path)
1803 struct config_state config = { path, 0, FALSE };
1804 struct io io;
1805 char buf[SIZEOF_STR];
1807 /* Do not read configuration from stdin if set to "" */
1808 if (!path || !strlen(path))
1809 return OPT_OK;
1811 if (!prefixcmp(path, "~/")) {
1812 const char *home = getenv("HOME");
1814 if (!home || !string_format(buf, "%s/%s", home, path + 2))
1815 return OPT_ERR_HOME_UNRESOLVABLE;
1816 path = buf;
1819 /* It's OK that the file doesn't exist. */
1820 if (!io_open(&io, "%s", path))
1821 return OPT_ERR_FILE_DOES_NOT_EXIST;
1823 if (io_load(&io, " \t", read_option, &config) == ERR ||
1824 config.errors == TRUE)
1825 warn("Errors while loading %s.", path);
1826 return OPT_OK;
1829 static int
1830 load_options(void)
1832 const char *tigrc_user = getenv("TIGRC_USER");
1833 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1834 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1835 const bool diff_opts_from_args = !!opt_diff_argv;
1837 if (!tigrc_system)
1838 tigrc_system = SYSCONFDIR "/tigrc";
1839 load_option_file(tigrc_system);
1841 if (!tigrc_user)
1842 tigrc_user = "~/.tigrc";
1843 load_option_file(tigrc_user);
1845 /* Add _after_ loading config files to avoid adding run requests
1846 * that conflict with keybindings. */
1847 add_builtin_run_requests();
1849 if (!diff_opts_from_args && tig_diff_opts && *tig_diff_opts) {
1850 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1851 char buf[SIZEOF_STR];
1852 int argc = 0;
1854 if (!string_format(buf, "%s", tig_diff_opts) ||
1855 !argv_from_string(diff_opts, &argc, buf))
1856 die("TIG_DIFF_OPTS contains too many arguments");
1857 else if (!argv_copy(&opt_diff_argv, diff_opts))
1858 die("Failed to format TIG_DIFF_OPTS arguments");
1861 return OK;
1866 * The viewer
1869 struct view;
1870 struct view_ops;
1872 /* The display array of active views and the index of the current view. */
1873 static struct view *display[2];
1874 static WINDOW *display_win[2];
1875 static WINDOW *display_title[2];
1876 static WINDOW *display_sep;
1878 static unsigned int current_view;
1880 #define foreach_displayed_view(view, i) \
1881 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1883 #define displayed_views() (display[1] != NULL ? 2 : 1)
1885 /* Current head and commit ID */
1886 static char ref_blob[SIZEOF_REF] = "";
1887 static char ref_commit[SIZEOF_REF] = "HEAD";
1888 static char ref_head[SIZEOF_REF] = "HEAD";
1889 static char ref_branch[SIZEOF_REF] = "";
1890 static char ref_status[SIZEOF_STR] = "";
1891 static char ref_stash[SIZEOF_REF] = "";
1893 enum view_flag {
1894 VIEW_NO_FLAGS = 0,
1895 VIEW_ALWAYS_LINENO = 1 << 0,
1896 VIEW_CUSTOM_STATUS = 1 << 1,
1897 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1898 VIEW_ADD_PAGER_REFS = 1 << 3,
1899 VIEW_OPEN_DIFF = 1 << 4,
1900 VIEW_NO_REF = 1 << 5,
1901 VIEW_NO_GIT_DIR = 1 << 6,
1902 VIEW_DIFF_LIKE = 1 << 7,
1903 VIEW_STDIN = 1 << 8,
1904 VIEW_SEND_CHILD_ENTER = 1 << 9,
1905 VIEW_FILE_FILTER = 1 << 10,
1906 VIEW_NO_PARENT_NAV = 1 << 11,
1909 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1911 struct position {
1912 unsigned long offset; /* Offset of the window top */
1913 unsigned long col; /* Offset from the window side. */
1914 unsigned long lineno; /* Current line number */
1917 struct view {
1918 const char *name; /* View name */
1919 const char *id; /* Points to either of ref_{head,commit,blob} */
1921 struct view_ops *ops; /* View operations */
1923 char ref[SIZEOF_REF]; /* Hovered commit reference */
1924 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1926 int height, width; /* The width and height of the main window */
1927 WINDOW *win; /* The main window */
1929 /* Navigation */
1930 struct position pos; /* Current position. */
1931 struct position prev_pos; /* Previous position. */
1933 /* Searching */
1934 char grep[SIZEOF_STR]; /* Search string */
1935 regex_t *regex; /* Pre-compiled regexp */
1937 /* If non-NULL, points to the view that opened this view. If this view
1938 * is closed tig will switch back to the parent view. */
1939 struct view *parent;
1940 struct view *prev;
1942 /* Buffering */
1943 size_t lines; /* Total number of lines */
1944 struct line *line; /* Line index */
1945 unsigned int digits; /* Number of digits in the lines member. */
1947 /* Number of lines with custom status, not to be counted in the
1948 * view title. */
1949 unsigned int custom_lines;
1951 /* Drawing */
1952 struct line *curline; /* Line currently being drawn. */
1953 enum line_type curtype; /* Attribute currently used for drawing. */
1954 unsigned long col; /* Column when drawing. */
1955 bool has_scrolled; /* View was scrolled. */
1957 /* Loading */
1958 const char **argv; /* Shell command arguments. */
1959 const char *dir; /* Directory from which to execute. */
1960 struct io io;
1961 struct io *pipe;
1962 time_t start_time;
1963 time_t update_secs;
1964 struct encoding *encoding;
1965 bool unrefreshable;
1967 /* Private data */
1968 void *private;
1971 enum open_flags {
1972 OPEN_DEFAULT = 0, /* Use default view switching. */
1973 OPEN_SPLIT = 1, /* Split current view. */
1974 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1975 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1976 OPEN_PREPARED = 32, /* Open already prepared command. */
1977 OPEN_EXTRA = 64, /* Open extra data from command. */
1980 struct view_ops {
1981 /* What type of content being displayed. Used in the title bar. */
1982 const char *type;
1983 /* What keymap does this view have */
1984 struct keymap keymap;
1985 /* Flags to control the view behavior. */
1986 enum view_flag flags;
1987 /* Size of private data. */
1988 size_t private_size;
1989 /* Open and reads in all view content. */
1990 bool (*open)(struct view *view, enum open_flags flags);
1991 /* Read one line; updates view->line. */
1992 bool (*read)(struct view *view, char *data);
1993 /* Draw one line; @lineno must be < view->height. */
1994 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1995 /* Depending on view handle a special requests. */
1996 enum request (*request)(struct view *view, enum request request, struct line *line);
1997 /* Search for regexp in a line. */
1998 bool (*grep)(struct view *view, struct line *line);
1999 /* Select line */
2000 void (*select)(struct view *view, struct line *line);
2003 #define VIEW_OPS(id, name, ref) name##_ops
2004 static struct view_ops VIEW_INFO(VIEW_OPS);
2006 static struct view views[] = {
2007 #define VIEW_DATA(id, name, ref) \
2008 { #name, ref, &name##_ops }
2009 VIEW_INFO(VIEW_DATA)
2012 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
2014 #define foreach_view(view, i) \
2015 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2017 #define view_is_displayed(view) \
2018 (view == display[0] || view == display[1])
2020 #define view_has_line(view, line_) \
2021 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
2023 static bool
2024 forward_request_to_child(struct view *child, enum request request)
2026 return displayed_views() == 2 && view_is_displayed(child) &&
2027 !strcmp(child->vid, child->id);
2030 static enum request
2031 view_request(struct view *view, enum request request)
2033 if (!view || !view->lines)
2034 return request;
2036 if (request == REQ_ENTER && !opt_focus_child &&
2037 view_has_flags(view, VIEW_SEND_CHILD_ENTER)) {
2038 struct view *child = display[1];
2040 if (forward_request_to_child(child, request)) {
2041 view_request(child, request);
2042 return REQ_NONE;
2046 if (request == REQ_REFRESH && view->unrefreshable) {
2047 report("This view can not be refreshed");
2048 return REQ_NONE;
2051 return view->ops->request(view, request, &view->line[view->pos.lineno]);
2055 * View drawing.
2058 static inline void
2059 set_view_attr(struct view *view, enum line_type type)
2061 if (!view->curline->selected && view->curtype != type) {
2062 (void) wattrset(view->win, get_line_attr(type));
2063 wchgat(view->win, -1, 0, get_line_color(type), NULL);
2064 view->curtype = type;
2068 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
2070 static bool
2071 draw_chars(struct view *view, enum line_type type, const char *string,
2072 int max_len, bool use_tilde)
2074 static char out_buffer[BUFSIZ * 2];
2075 int len = 0;
2076 int col = 0;
2077 int trimmed = FALSE;
2078 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2080 if (max_len <= 0)
2081 return VIEW_MAX_LEN(view) <= 0;
2083 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
2085 set_view_attr(view, type);
2086 if (len > 0) {
2087 if (opt_iconv_out != ICONV_NONE) {
2088 size_t inlen = len + 1;
2089 char *instr = calloc(1, inlen);
2090 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
2091 if (!instr)
2092 return VIEW_MAX_LEN(view) <= 0;
2094 strncpy(instr, string, len);
2096 char *outbuf = out_buffer;
2097 size_t outlen = sizeof(out_buffer);
2099 size_t ret;
2101 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
2102 if (ret != (size_t) -1) {
2103 string = out_buffer;
2104 len = sizeof(out_buffer) - outlen;
2106 free(instr);
2109 waddnstr(view->win, string, len);
2111 if (trimmed && use_tilde) {
2112 set_view_attr(view, LINE_DELIMITER);
2113 waddch(view->win, '~');
2114 col++;
2118 view->col += col;
2119 return VIEW_MAX_LEN(view) <= 0;
2122 static bool
2123 draw_space(struct view *view, enum line_type type, int max, int spaces)
2125 static char space[] = " ";
2127 spaces = MIN(max, spaces);
2129 while (spaces > 0) {
2130 int len = MIN(spaces, sizeof(space) - 1);
2132 if (draw_chars(view, type, space, len, FALSE))
2133 return TRUE;
2134 spaces -= len;
2137 return VIEW_MAX_LEN(view) <= 0;
2140 static bool
2141 draw_text_expanded(struct view *view, enum line_type type, const char *string, int max_len, bool use_tilde)
2143 static char text[SIZEOF_STR];
2145 do {
2146 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
2148 if (draw_chars(view, type, text, max_len, use_tilde))
2149 return TRUE;
2150 string += pos;
2151 } while (*string);
2153 return VIEW_MAX_LEN(view) <= 0;
2156 static bool
2157 draw_text(struct view *view, enum line_type type, const char *string)
2159 return draw_text_expanded(view, type, string, VIEW_MAX_LEN(view), TRUE);
2162 static bool
2163 draw_text_overflow(struct view *view, const char *text, bool on, int overflow, enum line_type type)
2165 if (on) {
2166 int max = MIN(VIEW_MAX_LEN(view), overflow);
2167 int len = strlen(text);
2169 if (draw_text_expanded(view, type, text, max, max < overflow))
2170 return TRUE;
2172 text = len > overflow ? text + overflow : "";
2173 type = LINE_OVERFLOW;
2176 if (*text && draw_text(view, type, text))
2177 return TRUE;
2179 return VIEW_MAX_LEN(view) <= 0;
2182 #define draw_commit_title(view, text, offset) \
2183 draw_text_overflow(view, text, opt_show_title_overflow, opt_title_overflow + offset, LINE_DEFAULT)
2185 static bool PRINTF_LIKE(3, 4)
2186 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
2188 char text[SIZEOF_STR];
2189 int retval;
2191 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
2192 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
2195 static bool
2196 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
2198 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2199 int max = VIEW_MAX_LEN(view);
2200 int i;
2202 if (max < size)
2203 size = max;
2205 set_view_attr(view, type);
2206 /* Using waddch() instead of waddnstr() ensures that
2207 * they'll be rendered correctly for the cursor line. */
2208 for (i = skip; i < size; i++)
2209 waddch(view->win, graphic[i]);
2211 view->col += size;
2212 if (separator) {
2213 if (size < max && skip <= size)
2214 waddch(view->win, ' ');
2215 view->col++;
2218 return VIEW_MAX_LEN(view) <= 0;
2221 static bool
2222 draw_field(struct view *view, enum line_type type, const char *text, int width, bool trim)
2224 int max = MIN(VIEW_MAX_LEN(view), width + 1);
2225 int col = view->col;
2227 if (!text)
2228 return draw_space(view, type, max, max);
2230 return draw_chars(view, type, text, max - 1, trim)
2231 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2234 static bool
2235 draw_date(struct view *view, struct time *time)
2237 const char *date = mkdate(time, opt_date);
2238 int cols = opt_date == DATE_SHORT ? DATE_SHORT_WIDTH : DATE_WIDTH;
2240 if (opt_date == DATE_NO)
2241 return FALSE;
2243 return draw_field(view, LINE_DATE, date, cols, FALSE);
2246 static bool
2247 draw_author(struct view *view, const struct ident *author)
2249 bool trim = author_trim(opt_author_width);
2250 const char *text = mkauthor(author, opt_author_width, opt_author);
2252 if (opt_author == AUTHOR_NO)
2253 return FALSE;
2255 return draw_field(view, LINE_AUTHOR, text, opt_author_width, trim);
2258 static bool
2259 draw_id(struct view *view, enum line_type type, const char *id)
2261 return draw_field(view, type, id, opt_id_cols, FALSE);
2264 static bool
2265 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2267 bool trim = filename && strlen(filename) >= opt_filename_width;
2269 if (opt_filename == FILENAME_NO)
2270 return FALSE;
2272 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2273 return FALSE;
2275 return draw_field(view, LINE_FILENAME, filename, opt_filename_width, trim);
2278 static bool
2279 draw_mode(struct view *view, mode_t mode)
2281 const char *str = mkmode(mode);
2283 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r--"), FALSE);
2286 static bool
2287 draw_lineno(struct view *view, unsigned int lineno)
2289 char number[10];
2290 int digits3 = view->digits < 3 ? 3 : view->digits;
2291 int max = MIN(VIEW_MAX_LEN(view), digits3);
2292 char *text = NULL;
2293 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2295 if (!opt_line_number)
2296 return FALSE;
2298 lineno += view->pos.offset + 1;
2299 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2300 static char fmt[] = "%1ld";
2302 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2303 if (string_format(number, fmt, lineno))
2304 text = number;
2306 if (text)
2307 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2308 else
2309 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2310 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2313 static bool
2314 draw_refs(struct view *view, struct ref_list *refs)
2316 size_t i;
2318 if (!opt_show_refs || !refs)
2319 return FALSE;
2321 for (i = 0; i < refs->size; i++) {
2322 struct ref *ref = refs->refs[i];
2323 enum line_type type = get_line_type_from_ref(ref);
2325 if (draw_formatted(view, type, "[%s]", ref->name))
2326 return TRUE;
2328 if (draw_text(view, LINE_DEFAULT, " "))
2329 return TRUE;
2332 return FALSE;
2335 static bool
2336 draw_view_line(struct view *view, unsigned int lineno)
2338 struct line *line;
2339 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2341 assert(view_is_displayed(view));
2343 if (view->pos.offset + lineno >= view->lines)
2344 return FALSE;
2346 line = &view->line[view->pos.offset + lineno];
2348 wmove(view->win, lineno, 0);
2349 if (line->cleareol)
2350 wclrtoeol(view->win);
2351 view->col = 0;
2352 view->curline = line;
2353 view->curtype = LINE_NONE;
2354 line->selected = FALSE;
2355 line->dirty = line->cleareol = 0;
2357 if (selected) {
2358 set_view_attr(view, LINE_CURSOR);
2359 line->selected = TRUE;
2360 view->ops->select(view, line);
2363 return view->ops->draw(view, line, lineno);
2366 static void
2367 redraw_view_dirty(struct view *view)
2369 bool dirty = FALSE;
2370 int lineno;
2372 for (lineno = 0; lineno < view->height; lineno++) {
2373 if (view->pos.offset + lineno >= view->lines)
2374 break;
2375 if (!view->line[view->pos.offset + lineno].dirty)
2376 continue;
2377 dirty = TRUE;
2378 if (!draw_view_line(view, lineno))
2379 break;
2382 if (!dirty)
2383 return;
2384 wnoutrefresh(view->win);
2387 static void
2388 redraw_view_from(struct view *view, int lineno)
2390 assert(0 <= lineno && lineno < view->height);
2392 for (; lineno < view->height; lineno++) {
2393 if (!draw_view_line(view, lineno))
2394 break;
2397 wnoutrefresh(view->win);
2400 static void
2401 redraw_view(struct view *view)
2403 werase(view->win);
2404 redraw_view_from(view, 0);
2408 static void
2409 update_view_title(struct view *view)
2411 char buf[SIZEOF_STR];
2412 char state[SIZEOF_STR];
2413 size_t bufpos = 0, statelen = 0;
2414 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2415 struct line *line = &view->line[view->pos.lineno];
2417 assert(view_is_displayed(view));
2419 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view_has_line(view, line) &&
2420 line->lineno) {
2421 unsigned int view_lines = view->pos.offset + view->height;
2422 unsigned int lines = view->lines
2423 ? MIN(view_lines, view->lines) * 100 / view->lines
2424 : 0;
2426 string_format_from(state, &statelen, " - %s %d of %zd (%d%%)",
2427 view->ops->type,
2428 line->lineno,
2429 view->lines - view->custom_lines,
2430 lines);
2434 if (view->pipe) {
2435 time_t secs = time(NULL) - view->start_time;
2437 /* Three git seconds are a long time ... */
2438 if (secs > 2)
2439 string_format_from(state, &statelen, " loading %lds", secs);
2442 string_format_from(buf, &bufpos, "[%s]", view->name);
2443 if (*view->ref && bufpos < view->width) {
2444 size_t refsize = strlen(view->ref);
2445 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2447 if (minsize < view->width)
2448 refsize = view->width - minsize + 7;
2449 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2452 if (statelen && bufpos < view->width) {
2453 string_format_from(buf, &bufpos, "%s", state);
2456 if (view == display[current_view])
2457 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2458 else
2459 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2461 mvwaddnstr(window, 0, 0, buf, bufpos);
2462 wclrtoeol(window);
2463 wnoutrefresh(window);
2466 static int
2467 apply_step(double step, int value)
2469 if (step >= 1)
2470 return (int) step;
2471 value *= step + 0.01;
2472 return value ? value : 1;
2475 static void
2476 apply_horizontal_split(struct view *base, struct view *view)
2478 view->width = base->width;
2479 view->height = apply_step(opt_scale_split_view, base->height);
2480 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2481 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2482 base->height -= view->height;
2485 static void
2486 apply_vertical_split(struct view *base, struct view *view)
2488 view->height = base->height;
2489 view->width = apply_step(opt_scale_vsplit_view, base->width);
2490 view->width = MAX(view->width, MIN_VIEW_WIDTH);
2491 view->width = MIN(view->width, base->width - MIN_VIEW_WIDTH);
2492 base->width -= view->width;
2495 static void
2496 redraw_display_separator(bool clear)
2498 if (displayed_views() > 1 && opt_vsplit) {
2499 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2501 if (clear)
2502 wclear(display_sep);
2503 wbkgd(display_sep, separator + get_line_attr(LINE_TITLE_BLUR));
2504 wnoutrefresh(display_sep);
2508 static void
2509 resize_display(void)
2511 int x, y, i;
2512 struct view *base = display[0];
2513 struct view *view = display[1] ? display[1] : display[0];
2515 /* Setup window dimensions */
2517 getmaxyx(stdscr, base->height, base->width);
2518 string_format(opt_env_columns, "COLUMNS=%d", base->width);
2519 string_format(opt_env_lines, "LINES=%d", base->height);
2521 /* Make room for the status window. */
2522 base->height -= 1;
2524 if (view != base) {
2525 if (opt_vsplit) {
2526 apply_vertical_split(base, view);
2528 /* Make room for the separator bar. */
2529 view->width -= 1;
2530 } else {
2531 apply_horizontal_split(base, view);
2534 /* Make room for the title bar. */
2535 view->height -= 1;
2538 /* Make room for the title bar. */
2539 base->height -= 1;
2541 x = y = 0;
2543 foreach_displayed_view (view, i) {
2544 if (!display_win[i]) {
2545 display_win[i] = newwin(view->height, view->width, y, x);
2546 if (!display_win[i])
2547 die("Failed to create %s view", view->name);
2549 scrollok(display_win[i], FALSE);
2551 display_title[i] = newwin(1, view->width, y + view->height, x);
2552 if (!display_title[i])
2553 die("Failed to create title window");
2555 } else {
2556 wresize(display_win[i], view->height, view->width);
2557 mvwin(display_win[i], y, x);
2558 wresize(display_title[i], 1, view->width);
2559 mvwin(display_title[i], y + view->height, x);
2562 if (i > 0 && opt_vsplit) {
2563 if (!display_sep) {
2564 display_sep = newwin(view->height, 1, 0, x - 1);
2565 if (!display_sep)
2566 die("Failed to create separator window");
2568 } else {
2569 wresize(display_sep, view->height, 1);
2570 mvwin(display_sep, 0, x - 1);
2574 view->win = display_win[i];
2576 if (opt_vsplit)
2577 x += view->width + 1;
2578 else
2579 y += view->height + 1;
2582 redraw_display_separator(FALSE);
2585 static void
2586 redraw_display(bool clear)
2588 struct view *view;
2589 int i;
2591 foreach_displayed_view (view, i) {
2592 if (clear)
2593 wclear(view->win);
2594 redraw_view(view);
2595 update_view_title(view);
2598 redraw_display_separator(clear);
2602 * Option management
2605 #define TOGGLE_MENU \
2606 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2607 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2608 TOGGLE_(AUTHOR, 'A', "author", &opt_author, author_map) \
2609 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2610 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2611 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2612 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2613 TOGGLE_(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map) \
2614 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL) \
2615 TOGGLE_(CHANGES, 'C', "local change display", &opt_show_changes, NULL) \
2616 TOGGLE_(ID, 'X', "commit ID display", &opt_show_id, NULL) \
2617 TOGGLE_(FILES, '%', "file filtering", &opt_file_filter, NULL) \
2618 TOGGLE_(TITLE_OVERFLOW, '$', "commit title overflow display", &opt_show_title_overflow, NULL) \
2620 static bool
2621 toggle_option(struct view *view, enum request request, char msg[SIZEOF_STR])
2623 const struct {
2624 enum request request;
2625 const struct enum_map *map;
2626 size_t map_size;
2627 } data[] = {
2628 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, (map != NULL ? ARRAY_SIZE(map) : 0) },
2629 TOGGLE_MENU
2630 #undef TOGGLE_
2632 const struct menu_item menu[] = {
2633 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2634 TOGGLE_MENU
2635 #undef TOGGLE_
2636 { 0 }
2638 int i = 0;
2640 if (request == REQ_OPTIONS) {
2641 if (!prompt_menu("Toggle option", menu, &i))
2642 return FALSE;
2643 } else {
2644 while (i < ARRAY_SIZE(data) && data[i].request != request)
2645 i++;
2646 if (i >= ARRAY_SIZE(data))
2647 die("Invalid request (%d)", request);
2650 if (data[i].map != NULL) {
2651 unsigned int *opt = menu[i].data;
2653 *opt = (*opt + 1) % data[i].map_size;
2654 if (data[i].map == ignore_space_map) {
2655 update_ignore_space_arg();
2656 string_format_size(msg, SIZEOF_STR,
2657 "Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2658 return TRUE;
2660 } else if (data[i].map == commit_order_map) {
2661 update_commit_order_arg();
2662 string_format_size(msg, SIZEOF_STR,
2663 "Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2664 return TRUE;
2667 string_format_size(msg, SIZEOF_STR,
2668 "Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2670 } else {
2671 bool *option = menu[i].data;
2673 *option = !*option;
2674 string_format_size(msg, SIZEOF_STR,
2675 "%sabling %s", *option ? "En" : "Dis", menu[i].text);
2677 if (option == &opt_file_filter)
2678 return TRUE;
2681 return FALSE;
2686 * Navigation
2689 static bool
2690 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2692 if (lineno >= view->lines)
2693 lineno = view->lines > 0 ? view->lines - 1 : 0;
2695 if (offset > lineno || offset + view->height <= lineno) {
2696 unsigned long half = view->height / 2;
2698 if (lineno > half)
2699 offset = lineno - half;
2700 else
2701 offset = 0;
2704 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2705 view->pos.offset = offset;
2706 view->pos.lineno = lineno;
2707 return TRUE;
2710 return FALSE;
2713 /* Scrolling backend */
2714 static void
2715 do_scroll_view(struct view *view, int lines)
2717 bool redraw_current_line = FALSE;
2719 /* The rendering expects the new offset. */
2720 view->pos.offset += lines;
2722 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2723 assert(lines);
2725 /* Move current line into the view. */
2726 if (view->pos.lineno < view->pos.offset) {
2727 view->pos.lineno = view->pos.offset;
2728 redraw_current_line = TRUE;
2729 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2730 view->pos.lineno = view->pos.offset + view->height - 1;
2731 redraw_current_line = TRUE;
2734 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2736 /* Redraw the whole screen if scrolling is pointless. */
2737 if (view->height < ABS(lines)) {
2738 redraw_view(view);
2740 } else {
2741 int line = lines > 0 ? view->height - lines : 0;
2742 int end = line + ABS(lines);
2744 scrollok(view->win, TRUE);
2745 wscrl(view->win, lines);
2746 scrollok(view->win, FALSE);
2748 while (line < end && draw_view_line(view, line))
2749 line++;
2751 if (redraw_current_line)
2752 draw_view_line(view, view->pos.lineno - view->pos.offset);
2753 wnoutrefresh(view->win);
2756 view->has_scrolled = TRUE;
2757 report_clear();
2760 /* Scroll frontend */
2761 static void
2762 scroll_view(struct view *view, enum request request)
2764 int lines = 1;
2766 assert(view_is_displayed(view));
2768 switch (request) {
2769 case REQ_SCROLL_FIRST_COL:
2770 view->pos.col = 0;
2771 redraw_view_from(view, 0);
2772 report_clear();
2773 return;
2774 case REQ_SCROLL_LEFT:
2775 if (view->pos.col == 0) {
2776 report("Cannot scroll beyond the first column");
2777 return;
2779 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2780 view->pos.col = 0;
2781 else
2782 view->pos.col -= apply_step(opt_hscroll, view->width);
2783 redraw_view_from(view, 0);
2784 report_clear();
2785 return;
2786 case REQ_SCROLL_RIGHT:
2787 view->pos.col += apply_step(opt_hscroll, view->width);
2788 redraw_view(view);
2789 report_clear();
2790 return;
2791 case REQ_SCROLL_PAGE_DOWN:
2792 lines = view->height;
2793 case REQ_SCROLL_LINE_DOWN:
2794 if (view->pos.offset + lines > view->lines)
2795 lines = view->lines - view->pos.offset;
2797 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2798 report("Cannot scroll beyond the last line");
2799 return;
2801 break;
2803 case REQ_SCROLL_PAGE_UP:
2804 lines = view->height;
2805 case REQ_SCROLL_LINE_UP:
2806 if (lines > view->pos.offset)
2807 lines = view->pos.offset;
2809 if (lines == 0) {
2810 report("Cannot scroll beyond the first line");
2811 return;
2814 lines = -lines;
2815 break;
2817 default:
2818 die("request %d not handled in switch", request);
2821 do_scroll_view(view, lines);
2824 /* Cursor moving */
2825 static void
2826 move_view(struct view *view, enum request request)
2828 int scroll_steps = 0;
2829 int steps;
2831 switch (request) {
2832 case REQ_MOVE_FIRST_LINE:
2833 steps = -view->pos.lineno;
2834 break;
2836 case REQ_MOVE_LAST_LINE:
2837 steps = view->lines - view->pos.lineno - 1;
2838 break;
2840 case REQ_MOVE_PAGE_UP:
2841 steps = view->height > view->pos.lineno
2842 ? -view->pos.lineno : -view->height;
2843 break;
2845 case REQ_MOVE_PAGE_DOWN:
2846 steps = view->pos.lineno + view->height >= view->lines
2847 ? view->lines - view->pos.lineno - 1 : view->height;
2848 break;
2850 case REQ_MOVE_UP:
2851 case REQ_PREVIOUS:
2852 steps = -1;
2853 break;
2855 case REQ_MOVE_DOWN:
2856 case REQ_NEXT:
2857 steps = 1;
2858 break;
2860 default:
2861 die("request %d not handled in switch", request);
2864 if (steps <= 0 && view->pos.lineno == 0) {
2865 report("Cannot move beyond the first line");
2866 return;
2868 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2869 report("Cannot move beyond the last line");
2870 return;
2873 /* Move the current line */
2874 view->pos.lineno += steps;
2875 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2877 /* Check whether the view needs to be scrolled */
2878 if (view->pos.lineno < view->pos.offset ||
2879 view->pos.lineno >= view->pos.offset + view->height) {
2880 scroll_steps = steps;
2881 if (steps < 0 && -steps > view->pos.offset) {
2882 scroll_steps = -view->pos.offset;
2884 } else if (steps > 0) {
2885 if (view->pos.lineno == view->lines - 1 &&
2886 view->lines > view->height) {
2887 scroll_steps = view->lines - view->pos.offset - 1;
2888 if (scroll_steps >= view->height)
2889 scroll_steps -= view->height - 1;
2894 if (!view_is_displayed(view)) {
2895 view->pos.offset += scroll_steps;
2896 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2897 view->ops->select(view, &view->line[view->pos.lineno]);
2898 return;
2901 /* Repaint the old "current" line if we be scrolling */
2902 if (ABS(steps) < view->height)
2903 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2905 if (scroll_steps) {
2906 do_scroll_view(view, scroll_steps);
2907 return;
2910 /* Draw the current line */
2911 draw_view_line(view, view->pos.lineno - view->pos.offset);
2913 wnoutrefresh(view->win);
2914 report_clear();
2919 * Searching
2922 static void search_view(struct view *view, enum request request);
2924 static bool
2925 grep_text(struct view *view, const char *text[])
2927 regmatch_t pmatch;
2928 size_t i;
2930 for (i = 0; text[i]; i++)
2931 if (*text[i] && !regexec(view->regex, text[i], 1, &pmatch, 0))
2932 return TRUE;
2933 return FALSE;
2936 static void
2937 select_view_line(struct view *view, unsigned long lineno)
2939 struct position old = view->pos;
2941 if (goto_view_line(view, view->pos.offset, lineno)) {
2942 if (view_is_displayed(view)) {
2943 if (old.offset != view->pos.offset) {
2944 redraw_view(view);
2945 } else {
2946 draw_view_line(view, old.lineno - view->pos.offset);
2947 draw_view_line(view, view->pos.lineno - view->pos.offset);
2948 wnoutrefresh(view->win);
2950 } else {
2951 view->ops->select(view, &view->line[view->pos.lineno]);
2956 static void
2957 find_next(struct view *view, enum request request)
2959 unsigned long lineno = view->pos.lineno;
2960 int direction;
2962 if (!*view->grep) {
2963 if (!*opt_search)
2964 report("No previous search");
2965 else
2966 search_view(view, request);
2967 return;
2970 switch (request) {
2971 case REQ_SEARCH:
2972 case REQ_FIND_NEXT:
2973 direction = 1;
2974 break;
2976 case REQ_SEARCH_BACK:
2977 case REQ_FIND_PREV:
2978 direction = -1;
2979 break;
2981 default:
2982 return;
2985 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2986 lineno += direction;
2988 /* Note, lineno is unsigned long so will wrap around in which case it
2989 * will become bigger than view->lines. */
2990 for (; lineno < view->lines; lineno += direction) {
2991 if (view->ops->grep(view, &view->line[lineno])) {
2992 select_view_line(view, lineno);
2993 report("Line %ld matches '%s'", lineno + 1, view->grep);
2994 return;
2998 report("No match found for '%s'", view->grep);
3001 static void
3002 search_view(struct view *view, enum request request)
3004 int regex_err;
3005 int regex_flags = opt_ignore_case ? REG_ICASE : 0;
3007 if (view->regex) {
3008 regfree(view->regex);
3009 *view->grep = 0;
3010 } else {
3011 view->regex = calloc(1, sizeof(*view->regex));
3012 if (!view->regex)
3013 return;
3016 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED | regex_flags);
3017 if (regex_err != 0) {
3018 char buf[SIZEOF_STR] = "unknown error";
3020 regerror(regex_err, view->regex, buf, sizeof(buf));
3021 report("Search failed: %s", buf);
3022 return;
3025 string_copy(view->grep, opt_search);
3027 find_next(view, request);
3031 * Incremental updating
3034 static inline bool
3035 check_position(struct position *pos)
3037 return pos->lineno || pos->col || pos->offset;
3040 static inline void
3041 clear_position(struct position *pos)
3043 memset(pos, 0, sizeof(*pos));
3046 static void
3047 reset_view(struct view *view)
3049 int i;
3051 for (i = 0; i < view->lines; i++)
3052 if (!view->line[i].dont_free)
3053 free(view->line[i].data);
3054 free(view->line);
3056 view->prev_pos = view->pos;
3057 clear_position(&view->pos);
3059 view->line = NULL;
3060 view->lines = 0;
3061 view->vid[0] = 0;
3062 view->custom_lines = 0;
3063 view->update_secs = 0;
3066 struct format_context {
3067 struct view *view;
3068 char buf[SIZEOF_STR];
3069 size_t bufpos;
3070 bool file_filter;
3073 static bool
3074 format_expand_arg(struct format_context *format, const char *name)
3076 static struct {
3077 const char *name;
3078 size_t namelen;
3079 const char *value;
3080 const char *value_if_empty;
3081 } vars[] = {
3082 #define FORMAT_VAR(name, value, value_if_empty) \
3083 { name, STRING_SIZE(name), value, value_if_empty }
3084 FORMAT_VAR("%(directory)", opt_path, "."),
3085 FORMAT_VAR("%(file)", opt_file, ""),
3086 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
3087 FORMAT_VAR("%(head)", ref_head, ""),
3088 FORMAT_VAR("%(commit)", ref_commit, ""),
3089 FORMAT_VAR("%(blob)", ref_blob, ""),
3090 FORMAT_VAR("%(branch)", ref_branch, ""),
3091 FORMAT_VAR("%(stash)", ref_stash, ""),
3093 int i;
3095 if (!prefixcmp(name, "%(prompt")) {
3096 const char *value = read_prompt("Command argument: ");
3098 return string_format_from(format->buf, &format->bufpos, "%s", value);
3101 for (i = 0; i < ARRAY_SIZE(vars); i++) {
3102 const char *value;
3104 if (strncmp(name, vars[i].name, vars[i].namelen))
3105 continue;
3107 if (vars[i].value == opt_file && !format->file_filter)
3108 return TRUE;
3110 value = *vars[i].value ? vars[i].value : vars[i].value_if_empty;
3111 if (!*value)
3112 return TRUE;
3114 return string_format_from(format->buf, &format->bufpos, "%s", value);
3117 report("Unknown replacement: `%s`", name);
3118 return NULL;
3121 static bool
3122 format_append_arg(struct format_context *format, const char ***dst_argv, const char *arg)
3124 int i;
3126 for (i = 0; i < sizeof(format->buf); i++)
3127 format->buf[i] = 0;
3128 format->bufpos = 0;
3130 while (arg) {
3131 char *next = strstr(arg, "%(");
3132 int len = next ? next - arg : strlen(arg);
3134 if (len && !string_format_from(format->buf, &format->bufpos, "%.*s", len, arg))
3135 return FALSE;
3137 if (next && !format_expand_arg(format, next))
3138 return FALSE;
3140 arg = next ? strchr(next, ')') + 1 : NULL;
3143 return argv_append(dst_argv, format->buf);
3146 static bool
3147 format_append_argv(struct format_context *format, const char ***dst_argv, const char *src_argv[])
3149 int argc;
3151 if (!src_argv)
3152 return TRUE;
3154 for (argc = 0; src_argv[argc]; argc++)
3155 if (!format_append_arg(format, dst_argv, src_argv[argc]))
3156 return FALSE;
3158 return src_argv[argc] == NULL;
3161 static bool
3162 format_argv(struct view *view, const char ***dst_argv, const char *src_argv[], bool first, bool file_filter)
3164 struct format_context format = { view, "", 0, file_filter };
3165 int argc;
3167 argv_free(*dst_argv);
3169 for (argc = 0; src_argv[argc]; argc++) {
3170 const char *arg = src_argv[argc];
3172 if (!strcmp(arg, "%(fileargs)")) {
3173 if (file_filter && !argv_append_array(dst_argv, opt_file_argv))
3174 break;
3176 } else if (!strcmp(arg, "%(diffargs)")) {
3177 if (!format_append_argv(&format, dst_argv, opt_diff_argv))
3178 break;
3180 } else if (!strcmp(arg, "%(blameargs)")) {
3181 if (!format_append_argv(&format, dst_argv, opt_blame_argv))
3182 break;
3184 } else if (!strcmp(arg, "%(revargs)") ||
3185 (first && !strcmp(arg, "%(commit)"))) {
3186 if (!argv_append_array(dst_argv, opt_rev_argv))
3187 break;
3189 } else if (!format_append_arg(&format, dst_argv, arg)) {
3190 break;
3194 return src_argv[argc] == NULL;
3197 static bool
3198 restore_view_position(struct view *view)
3200 /* A view without a previous view is the first view */
3201 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
3202 select_view_line(view, opt_lineno - 1);
3203 opt_lineno = 0;
3206 /* Ensure that the view position is in a valid state. */
3207 if (!check_position(&view->prev_pos) ||
3208 (view->pipe && view->lines <= view->prev_pos.lineno))
3209 return goto_view_line(view, view->pos.offset, view->pos.lineno);
3211 /* Changing the view position cancels the restoring. */
3212 /* FIXME: Changing back to the first line is not detected. */
3213 if (check_position(&view->pos)) {
3214 clear_position(&view->prev_pos);
3215 return FALSE;
3218 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
3219 view_is_displayed(view))
3220 werase(view->win);
3222 view->pos.col = view->prev_pos.col;
3223 clear_position(&view->prev_pos);
3225 return TRUE;
3228 static void
3229 end_update(struct view *view, bool force)
3231 if (!view->pipe)
3232 return;
3233 while (!view->ops->read(view, NULL))
3234 if (!force)
3235 return;
3236 if (force)
3237 io_kill(view->pipe);
3238 io_done(view->pipe);
3239 view->pipe = NULL;
3242 static void
3243 setup_update(struct view *view, const char *vid)
3245 reset_view(view);
3246 /* XXX: Do not use string_copy_rev(), it copies until first space. */
3247 string_ncopy(view->vid, vid, strlen(vid));
3248 view->pipe = &view->io;
3249 view->start_time = time(NULL);
3252 static bool
3253 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
3255 bool use_stdin = view_has_flags(view, VIEW_STDIN) && opt_stdin;
3256 bool extra = !!(flags & (OPEN_EXTRA));
3257 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
3258 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
3259 enum io_type io_type = use_stdin ? IO_RD_STDIN : IO_RD;
3261 opt_stdin = FALSE;
3263 if ((!reload && !strcmp(view->vid, view->id)) ||
3264 ((flags & OPEN_REFRESH) && view->unrefreshable))
3265 return TRUE;
3267 if (view->pipe) {
3268 if (extra)
3269 io_done(view->pipe);
3270 else
3271 end_update(view, TRUE);
3274 view->unrefreshable = use_stdin;
3276 if (!refresh && argv) {
3277 bool file_filter = !view_has_flags(view, VIEW_FILE_FILTER) || opt_file_filter;
3279 view->dir = dir;
3280 if (!format_argv(view, &view->argv, argv, !view->prev, file_filter)) {
3281 report("Failed to format %s arguments", view->name);
3282 return FALSE;
3285 /* Put the current ref_* value to the view title ref
3286 * member. This is needed by the blob view. Most other
3287 * views sets it automatically after loading because the
3288 * first line is a commit line. */
3289 string_copy_rev(view->ref, view->id);
3292 if (view->argv && view->argv[0] &&
3293 !io_run(&view->io, io_type, view->dir, opt_env, view->argv)) {
3294 report("Failed to open %s view", view->name);
3295 return FALSE;
3298 if (!extra)
3299 setup_update(view, view->id);
3301 return TRUE;
3304 static bool
3305 update_view(struct view *view)
3307 char *line;
3308 /* Clear the view and redraw everything since the tree sorting
3309 * might have rearranged things. */
3310 bool redraw = view->lines == 0;
3311 bool can_read = TRUE;
3312 struct encoding *encoding = view->encoding ? view->encoding : opt_encoding;
3314 if (!view->pipe)
3315 return TRUE;
3317 if (!io_can_read(view->pipe, FALSE)) {
3318 if (view->lines == 0 && view_is_displayed(view)) {
3319 time_t secs = time(NULL) - view->start_time;
3321 if (secs > 1 && secs > view->update_secs) {
3322 if (view->update_secs == 0)
3323 redraw_view(view);
3324 update_view_title(view);
3325 view->update_secs = secs;
3328 return TRUE;
3331 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
3332 if (encoding) {
3333 line = encoding_convert(encoding, line);
3336 if (!view->ops->read(view, line)) {
3337 report("Allocation failure");
3338 end_update(view, TRUE);
3339 return FALSE;
3344 unsigned long lines = view->lines;
3345 int digits;
3347 for (digits = 0; lines; digits++)
3348 lines /= 10;
3350 /* Keep the displayed view in sync with line number scaling. */
3351 if (digits != view->digits) {
3352 view->digits = digits;
3353 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3354 redraw = TRUE;
3358 if (io_error(view->pipe)) {
3359 report("Failed to read: %s", io_strerror(view->pipe));
3360 end_update(view, TRUE);
3362 } else if (io_eof(view->pipe)) {
3363 end_update(view, FALSE);
3366 if (restore_view_position(view))
3367 redraw = TRUE;
3369 if (!view_is_displayed(view))
3370 return TRUE;
3372 if (redraw)
3373 redraw_view_from(view, 0);
3374 else
3375 redraw_view_dirty(view);
3377 /* Update the title _after_ the redraw so that if the redraw picks up a
3378 * commit reference in view->ref it'll be available here. */
3379 update_view_title(view);
3380 return TRUE;
3383 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3385 static struct line *
3386 add_line(struct view *view, const void *data, enum line_type type, size_t data_size, bool custom)
3388 struct line *line;
3390 if (!realloc_lines(&view->line, view->lines, 1))
3391 return NULL;
3393 if (data_size) {
3394 void *alloc_data = calloc(1, data_size);
3396 if (!alloc_data)
3397 return NULL;
3399 if (data)
3400 memcpy(alloc_data, data, data_size);
3401 data = alloc_data;
3404 line = &view->line[view->lines++];
3405 memset(line, 0, sizeof(*line));
3406 line->type = type;
3407 line->data = (void *) data;
3408 line->dirty = 1;
3410 if (custom)
3411 view->custom_lines++;
3412 else
3413 line->lineno = view->lines - view->custom_lines;
3415 return line;
3418 static struct line *
3419 add_line_alloc_(struct view *view, void **ptr, enum line_type type, size_t data_size, bool custom)
3421 struct line *line = add_line(view, NULL, type, data_size, custom);
3423 if (line)
3424 *ptr = line->data;
3425 return line;
3428 #define add_line_alloc(view, data_ptr, type, extra_size, custom) \
3429 add_line_alloc_(view, (void **) data_ptr, type, sizeof(**data_ptr) + extra_size, custom)
3431 static struct line *
3432 add_line_nodata(struct view *view, enum line_type type)
3434 return add_line(view, NULL, type, 0, FALSE);
3437 static struct line *
3438 add_line_static_data(struct view *view, const void *data, enum line_type type)
3440 struct line *line = add_line(view, data, type, 0, FALSE);
3442 if (line)
3443 line->dont_free = TRUE;
3444 return line;
3447 static struct line *
3448 add_line_text(struct view *view, const char *text, enum line_type type)
3450 return add_line(view, text, type, strlen(text) + 1, FALSE);
3453 static struct line * PRINTF_LIKE(3, 4)
3454 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3456 char buf[SIZEOF_STR];
3457 int retval;
3459 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3460 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3464 * View opening
3467 static void
3468 split_view(struct view *prev, struct view *view)
3470 display[1] = view;
3471 current_view = opt_focus_child ? 1 : 0;
3472 view->parent = prev;
3473 resize_display();
3475 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3476 /* Take the title line into account. */
3477 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3479 /* Scroll the view that was split if the current line is
3480 * outside the new limited view. */
3481 do_scroll_view(prev, lines);
3484 if (view != prev && view_is_displayed(prev)) {
3485 /* "Blur" the previous view. */
3486 update_view_title(prev);
3490 static void
3491 maximize_view(struct view *view, bool redraw)
3493 memset(display, 0, sizeof(display));
3494 current_view = 0;
3495 display[current_view] = view;
3496 resize_display();
3497 if (redraw) {
3498 redraw_display(FALSE);
3499 report_clear();
3503 static void
3504 load_view(struct view *view, struct view *prev, enum open_flags flags)
3506 if (view->pipe)
3507 end_update(view, TRUE);
3508 if (view->ops->private_size) {
3509 if (!view->private)
3510 view->private = calloc(1, view->ops->private_size);
3511 else
3512 memset(view->private, 0, view->ops->private_size);
3515 /* When prev == view it means this is the first loaded view. */
3516 if (prev && view != prev) {
3517 view->prev = prev;
3520 if (!view->ops->open(view, flags))
3521 return;
3523 if (prev) {
3524 bool split = !!(flags & OPEN_SPLIT);
3526 if (split) {
3527 split_view(prev, view);
3528 } else {
3529 maximize_view(view, FALSE);
3533 restore_view_position(view);
3535 if (view->pipe && view->lines == 0) {
3536 /* Clear the old view and let the incremental updating refill
3537 * the screen. */
3538 werase(view->win);
3539 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3540 clear_position(&view->prev_pos);
3541 report_clear();
3542 } else if (view_is_displayed(view)) {
3543 redraw_view(view);
3544 report_clear();
3548 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3549 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3551 static void
3552 open_view(struct view *prev, enum request request, enum open_flags flags)
3554 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3555 struct view *view = VIEW(request);
3556 int nviews = displayed_views();
3558 assert(flags ^ OPEN_REFRESH);
3560 if (view == prev && nviews == 1 && !reload) {
3561 report("Already in %s view", view->name);
3562 return;
3565 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3566 report("The %s view is disabled in pager view", view->name);
3567 return;
3570 load_view(view, prev ? prev : view, flags);
3573 static void
3574 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3576 enum request request = view - views + REQ_OFFSET + 1;
3578 if (view->pipe)
3579 end_update(view, TRUE);
3580 view->dir = dir;
3582 if (!argv_copy(&view->argv, argv)) {
3583 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3584 } else {
3585 open_view(prev, request, flags | OPEN_PREPARED);
3589 static bool
3590 open_external_viewer(const char *argv[], const char *dir, bool confirm, const char *notice)
3592 bool ok;
3594 def_prog_mode(); /* save current tty modes */
3595 endwin(); /* restore original tty modes */
3596 ok = io_run_fg(argv, dir);
3597 if (confirm) {
3598 if (!ok && *notice)
3599 fprintf(stderr, "%s", notice);
3600 fprintf(stderr, "Press Enter to continue");
3601 getc(opt_tty);
3603 reset_prog_mode();
3604 redraw_display(TRUE);
3605 return ok;
3608 static void
3609 open_mergetool(const char *file)
3611 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3613 open_external_viewer(mergetool_argv, opt_cdup, TRUE, "");
3616 #define EDITOR_LINENO_MSG \
3617 "*** Your editor reported an error while opening the file.\n" \
3618 "*** This is probably because it doesn't support the line\n" \
3619 "*** number argument added automatically. The line number\n" \
3620 "*** has been disabled for now. You can permanently disable\n" \
3621 "*** it by adding the following line to ~/.tigrc\n" \
3622 "*** set editor-line-number = no\n"
3624 static void
3625 open_editor(const char *file, unsigned int lineno)
3627 const char *editor_argv[SIZEOF_ARG + 3] = { "vi", file, NULL };
3628 char editor_cmd[SIZEOF_STR];
3629 char lineno_cmd[SIZEOF_STR];
3630 const char *editor;
3631 int argc = 0;
3633 editor = getenv("GIT_EDITOR");
3634 if (!editor && *opt_editor)
3635 editor = opt_editor;
3636 if (!editor)
3637 editor = getenv("VISUAL");
3638 if (!editor)
3639 editor = getenv("EDITOR");
3640 if (!editor)
3641 editor = "vi";
3643 string_ncopy(editor_cmd, editor, strlen(editor));
3644 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3645 report("Failed to read editor command");
3646 return;
3649 if (lineno && opt_editor_lineno && string_format(lineno_cmd, "+%u", lineno))
3650 editor_argv[argc++] = lineno_cmd;
3651 editor_argv[argc] = file;
3652 if (!open_external_viewer(editor_argv, opt_cdup, TRUE, EDITOR_LINENO_MSG))
3653 opt_editor_lineno = FALSE;
3656 static enum request run_prompt_command(struct view *view, char *cmd);
3658 static enum request
3659 open_run_request(struct view *view, enum request request)
3661 struct run_request *req = get_run_request(request);
3662 const char **argv = NULL;
3663 bool confirmed = FALSE;
3665 request = REQ_NONE;
3667 if (!req) {
3668 report("Unknown run request");
3669 return request;
3672 if (format_argv(view, &argv, req->argv, FALSE, TRUE)) {
3673 if (req->internal) {
3674 char cmd[SIZEOF_STR];
3676 if (argv_to_string(argv, cmd, sizeof(cmd), " ")) {
3677 request = run_prompt_command(view, cmd);
3680 else {
3681 confirmed = !req->confirm;
3683 if (req->confirm) {
3684 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
3686 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
3687 string_format(prompt, "Run `%s`?", cmd) &&
3688 prompt_yesno(prompt)) {
3689 confirmed = TRUE;
3693 if (confirmed && argv_remove_quotes(argv)) {
3694 if (req->silent)
3695 io_run_bg(argv);
3696 else
3697 open_external_viewer(argv, NULL, !req->exit, "");
3702 if (argv)
3703 argv_free(argv);
3704 free(argv);
3706 if (request == REQ_NONE) {
3707 if (req->confirm && !confirmed)
3708 request = REQ_NONE;
3710 else if (req->exit)
3711 request = REQ_QUIT;
3713 else if (!view->unrefreshable)
3714 request = REQ_REFRESH;
3716 return request;
3720 * User request switch noodle
3723 static int
3724 view_driver(struct view *view, enum request request)
3726 int i;
3728 if (request == REQ_NONE)
3729 return TRUE;
3731 if (request > REQ_NONE) {
3732 request = open_run_request(view, request);
3734 // exit quickly rather than going through view_request and back
3735 if (request == REQ_QUIT)
3736 return FALSE;
3739 request = view_request(view, request);
3740 if (request == REQ_NONE)
3741 return TRUE;
3743 switch (request) {
3744 case REQ_MOVE_UP:
3745 case REQ_MOVE_DOWN:
3746 case REQ_MOVE_PAGE_UP:
3747 case REQ_MOVE_PAGE_DOWN:
3748 case REQ_MOVE_FIRST_LINE:
3749 case REQ_MOVE_LAST_LINE:
3750 move_view(view, request);
3751 break;
3753 case REQ_SCROLL_FIRST_COL:
3754 case REQ_SCROLL_LEFT:
3755 case REQ_SCROLL_RIGHT:
3756 case REQ_SCROLL_LINE_DOWN:
3757 case REQ_SCROLL_LINE_UP:
3758 case REQ_SCROLL_PAGE_DOWN:
3759 case REQ_SCROLL_PAGE_UP:
3760 scroll_view(view, request);
3761 break;
3763 case REQ_VIEW_MAIN:
3764 case REQ_VIEW_DIFF:
3765 case REQ_VIEW_LOG:
3766 case REQ_VIEW_TREE:
3767 case REQ_VIEW_HELP:
3768 case REQ_VIEW_BRANCH:
3769 case REQ_VIEW_BLAME:
3770 case REQ_VIEW_BLOB:
3771 case REQ_VIEW_STATUS:
3772 case REQ_VIEW_STAGE:
3773 case REQ_VIEW_PAGER:
3774 case REQ_VIEW_STASH:
3775 open_view(view, request, OPEN_DEFAULT);
3776 break;
3778 case REQ_NEXT:
3779 case REQ_PREVIOUS:
3780 if (view->parent && !view_has_flags(view->parent, VIEW_NO_PARENT_NAV)) {
3781 int line;
3783 view = view->parent;
3784 line = view->pos.lineno;
3785 move_view(view, request);
3786 if (view_is_displayed(view))
3787 update_view_title(view);
3788 if (line != view->pos.lineno)
3789 view_request(view, REQ_ENTER);
3790 } else {
3791 move_view(view, request);
3793 break;
3795 case REQ_VIEW_NEXT:
3797 int nviews = displayed_views();
3798 int next_view = (current_view + 1) % nviews;
3800 if (next_view == current_view) {
3801 report("Only one view is displayed");
3802 break;
3805 current_view = next_view;
3806 /* Blur out the title of the previous view. */
3807 update_view_title(view);
3808 report_clear();
3809 break;
3811 case REQ_REFRESH:
3812 report("Refreshing is not yet supported for the %s view", view->name);
3813 break;
3815 case REQ_MAXIMIZE:
3816 if (displayed_views() == 2)
3817 maximize_view(view, TRUE);
3818 break;
3820 case REQ_OPTIONS:
3821 case REQ_TOGGLE_LINENO:
3822 case REQ_TOGGLE_DATE:
3823 case REQ_TOGGLE_AUTHOR:
3824 case REQ_TOGGLE_FILENAME:
3825 case REQ_TOGGLE_GRAPHIC:
3826 case REQ_TOGGLE_REV_GRAPH:
3827 case REQ_TOGGLE_REFS:
3828 case REQ_TOGGLE_CHANGES:
3829 case REQ_TOGGLE_IGNORE_SPACE:
3830 case REQ_TOGGLE_ID:
3831 case REQ_TOGGLE_FILES:
3832 case REQ_TOGGLE_TITLE_OVERFLOW:
3834 char action[SIZEOF_STR] = "";
3835 bool reload = toggle_option(view, request, action);
3837 if (reload && view_has_flags(view, VIEW_DIFF_LIKE))
3838 reload_view(view);
3839 else
3840 redraw_display(FALSE);
3842 if (*action)
3843 report("%s", action);
3845 break;
3847 case REQ_TOGGLE_SORT_FIELD:
3848 case REQ_TOGGLE_SORT_ORDER:
3849 report("Sorting is not yet supported for the %s view", view->name);
3850 break;
3852 case REQ_DIFF_CONTEXT_UP:
3853 case REQ_DIFF_CONTEXT_DOWN:
3854 report("Changing the diff context is not yet supported for the %s view", view->name);
3855 break;
3857 case REQ_SEARCH:
3858 case REQ_SEARCH_BACK:
3859 search_view(view, request);
3860 break;
3862 case REQ_FIND_NEXT:
3863 case REQ_FIND_PREV:
3864 find_next(view, request);
3865 break;
3867 case REQ_STOP_LOADING:
3868 foreach_view(view, i) {
3869 if (view->pipe)
3870 report("Stopped loading the %s view", view->name),
3871 end_update(view, TRUE);
3873 break;
3875 case REQ_SHOW_VERSION:
3876 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3877 return TRUE;
3879 case REQ_SCREEN_REDRAW:
3880 redraw_display(TRUE);
3881 break;
3883 case REQ_EDIT:
3884 report("Nothing to edit");
3885 break;
3887 case REQ_ENTER:
3888 report("Nothing to enter");
3889 break;
3891 case REQ_VIEW_CLOSE:
3892 /* XXX: Mark closed views by letting view->prev point to the
3893 * view itself. Parents to closed view should never be
3894 * followed. */
3895 if (view->prev && view->prev != view) {
3896 maximize_view(view->prev, TRUE);
3897 view->prev = view;
3898 break;
3900 /* Fall-through */
3901 case REQ_QUIT:
3902 return FALSE;
3904 default:
3905 report("Unknown key, press %s for help",
3906 get_view_key(view, REQ_VIEW_HELP));
3907 return TRUE;
3910 return TRUE;
3915 * View backend utilities
3918 enum sort_field {
3919 ORDERBY_NAME,
3920 ORDERBY_DATE,
3921 ORDERBY_AUTHOR,
3924 struct sort_state {
3925 const enum sort_field *fields;
3926 size_t size, current;
3927 bool reverse;
3930 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3931 #define get_sort_field(state) ((state).fields[(state).current])
3932 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3934 static void
3935 sort_view(struct view *view, enum request request, struct sort_state *state,
3936 int (*compare)(const void *, const void *))
3938 switch (request) {
3939 case REQ_TOGGLE_SORT_FIELD:
3940 state->current = (state->current + 1) % state->size;
3941 break;
3943 case REQ_TOGGLE_SORT_ORDER:
3944 state->reverse = !state->reverse;
3945 break;
3946 default:
3947 die("Not a sort request");
3950 qsort(view->line, view->lines, sizeof(*view->line), compare);
3951 redraw_view(view);
3954 static bool
3955 update_diff_context(enum request request)
3957 int diff_context = opt_diff_context;
3959 switch (request) {
3960 case REQ_DIFF_CONTEXT_UP:
3961 opt_diff_context += 1;
3962 update_diff_context_arg(opt_diff_context);
3963 break;
3965 case REQ_DIFF_CONTEXT_DOWN:
3966 if (opt_diff_context == 0) {
3967 report("Diff context cannot be less than zero");
3968 break;
3970 opt_diff_context -= 1;
3971 update_diff_context_arg(opt_diff_context);
3972 break;
3974 default:
3975 die("Not a diff context request");
3978 return diff_context != opt_diff_context;
3981 DEFINE_ALLOCATOR(realloc_authors, struct ident *, 256)
3983 /* Small author cache to reduce memory consumption. It uses binary
3984 * search to lookup or find place to position new entries. No entries
3985 * are ever freed. */
3986 static struct ident *
3987 get_author(const char *name, const char *email)
3989 static struct ident **authors;
3990 static size_t authors_size;
3991 int from = 0, to = authors_size - 1;
3992 struct ident *ident;
3994 while (from <= to) {
3995 size_t pos = (to + from) / 2;
3996 int cmp = strcmp(name, authors[pos]->name);
3998 if (!cmp)
3999 return authors[pos];
4001 if (cmp < 0)
4002 to = pos - 1;
4003 else
4004 from = pos + 1;
4007 if (!realloc_authors(&authors, authors_size, 1))
4008 return NULL;
4009 ident = calloc(1, sizeof(*ident));
4010 if (!ident)
4011 return NULL;
4012 ident->name = strdup(name);
4013 ident->email = strdup(email);
4014 if (!ident->name || !ident->email) {
4015 free((void *) ident->name);
4016 free(ident);
4017 return NULL;
4020 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
4021 authors[from] = ident;
4022 authors_size++;
4024 return ident;
4027 static void
4028 parse_timesec(struct time *time, const char *sec)
4030 time->sec = (time_t) atol(sec);
4033 static void
4034 parse_timezone(struct time *time, const char *zone)
4036 long tz;
4038 tz = ('0' - zone[1]) * 60 * 60 * 10;
4039 tz += ('0' - zone[2]) * 60 * 60;
4040 tz += ('0' - zone[3]) * 60 * 10;
4041 tz += ('0' - zone[4]) * 60;
4043 if (zone[0] == '-')
4044 tz = -tz;
4046 time->tz = tz;
4047 time->sec -= tz;
4050 /* Parse author lines where the name may be empty:
4051 * author <email@address.tld> 1138474660 +0100
4053 static void
4054 parse_author_line(char *ident, const struct ident **author, struct time *time)
4056 char *nameend = strchr(ident, '<');
4057 char *emailend = strchr(ident, '>');
4058 const char *name, *email = "";
4060 if (nameend && emailend)
4061 *nameend = *emailend = 0;
4062 name = chomp_string(ident);
4063 if (nameend)
4064 email = chomp_string(nameend + 1);
4065 if (!*name)
4066 name = *email ? email : unknown_ident.name;
4067 if (!*email)
4068 email = *name ? name : unknown_ident.email;
4070 *author = get_author(name, email);
4072 /* Parse epoch and timezone */
4073 if (time && emailend && emailend[1] == ' ') {
4074 char *secs = emailend + 2;
4075 char *zone = strchr(secs, ' ');
4077 parse_timesec(time, secs);
4079 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
4080 parse_timezone(time, zone + 1);
4084 static struct line *
4085 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
4087 for (; view_has_line(view, line); line += direction)
4088 if (line->type == type)
4089 return line;
4091 return NULL;
4094 #define find_prev_line_by_type(view, line, type) \
4095 find_line_by_type(view, line, type, -1)
4097 #define find_next_line_by_type(view, line, type) \
4098 find_line_by_type(view, line, type, 1)
4101 * Blame
4104 struct blame_commit {
4105 char id[SIZEOF_REV]; /* SHA1 ID. */
4106 char title[128]; /* First line of the commit message. */
4107 const struct ident *author; /* Author of the commit. */
4108 struct time time; /* Date from the author ident. */
4109 char filename[128]; /* Name of file. */
4110 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
4111 char parent_filename[128]; /* Parent/previous name of file. */
4114 struct blame_header {
4115 char id[SIZEOF_REV]; /* SHA1 ID. */
4116 size_t orig_lineno;
4117 size_t lineno;
4118 size_t group;
4121 static bool
4122 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4124 const char *pos = *posref;
4126 *posref = NULL;
4127 pos = strchr(pos + 1, ' ');
4128 if (!pos || !isdigit(pos[1]))
4129 return FALSE;
4130 *number = atoi(pos + 1);
4131 if (*number < min || *number > max)
4132 return FALSE;
4134 *posref = pos;
4135 return TRUE;
4138 static bool
4139 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
4141 const char *pos = text + SIZEOF_REV - 2;
4143 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4144 return FALSE;
4146 string_ncopy(header->id, text, SIZEOF_REV);
4148 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
4149 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
4150 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
4151 return FALSE;
4153 return TRUE;
4156 static bool
4157 match_blame_header(const char *name, char **line)
4159 size_t namelen = strlen(name);
4160 bool matched = !strncmp(name, *line, namelen);
4162 if (matched)
4163 *line += namelen;
4165 return matched;
4168 static bool
4169 parse_blame_info(struct blame_commit *commit, char *line)
4171 if (match_blame_header("author ", &line)) {
4172 parse_author_line(line, &commit->author, NULL);
4174 } else if (match_blame_header("author-time ", &line)) {
4175 parse_timesec(&commit->time, line);
4177 } else if (match_blame_header("author-tz ", &line)) {
4178 parse_timezone(&commit->time, line);
4180 } else if (match_blame_header("summary ", &line)) {
4181 string_ncopy(commit->title, line, strlen(line));
4183 } else if (match_blame_header("previous ", &line)) {
4184 if (strlen(line) <= SIZEOF_REV)
4185 return FALSE;
4186 string_copy_rev(commit->parent_id, line);
4187 line += SIZEOF_REV;
4188 string_ncopy(commit->parent_filename, line, strlen(line));
4190 } else if (match_blame_header("filename ", &line)) {
4191 string_ncopy(commit->filename, line, strlen(line));
4192 return TRUE;
4195 return FALSE;
4199 * Pager backend
4202 static bool
4203 pager_draw(struct view *view, struct line *line, unsigned int lineno)
4205 if (draw_lineno(view, lineno))
4206 return TRUE;
4208 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4209 return TRUE;
4211 draw_text(view, line->type, line->data);
4212 return TRUE;
4215 static bool
4216 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
4218 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
4219 char ref[SIZEOF_STR];
4221 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
4222 return TRUE;
4224 /* This is the only fatal call, since it can "corrupt" the buffer. */
4225 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
4226 return FALSE;
4228 return TRUE;
4231 static void
4232 add_pager_refs(struct view *view, const char *commit_id)
4234 char buf[SIZEOF_STR];
4235 struct ref_list *list;
4236 size_t bufpos = 0, i;
4237 const char *sep = "Refs: ";
4238 bool is_tag = FALSE;
4240 list = get_ref_list(commit_id);
4241 if (!list) {
4242 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
4243 goto try_add_describe_ref;
4244 return;
4247 for (i = 0; i < list->size; i++) {
4248 struct ref *ref = list->refs[i];
4249 const char *fmt = ref->tag ? "%s[%s]" :
4250 ref->remote ? "%s<%s>" : "%s%s";
4252 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
4253 return;
4254 sep = ", ";
4255 if (ref->tag)
4256 is_tag = TRUE;
4259 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
4260 try_add_describe_ref:
4261 /* Add <tag>-g<commit_id> "fake" reference. */
4262 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
4263 return;
4266 if (bufpos == 0)
4267 return;
4269 add_line_text(view, buf, LINE_PP_REFS);
4272 static struct line *
4273 pager_wrap_line(struct view *view, const char *data, enum line_type type)
4275 size_t first_line = 0;
4276 bool has_first_line = FALSE;
4277 size_t datalen = strlen(data);
4278 size_t lineno = 0;
4280 while (datalen > 0 || !has_first_line) {
4281 bool wrapped = !!first_line;
4282 size_t linelen = string_expanded_length(data, datalen, opt_tab_size, view->width - !!wrapped);
4283 struct line *line;
4284 char *text;
4286 line = add_line(view, NULL, type, linelen + 1, wrapped);
4287 if (!line)
4288 break;
4289 if (!has_first_line) {
4290 first_line = view->lines - 1;
4291 has_first_line = TRUE;
4294 if (!wrapped)
4295 lineno = line->lineno;
4297 line->wrapped = wrapped;
4298 line->lineno = lineno;
4299 text = line->data;
4300 if (linelen)
4301 strncpy(text, data, linelen);
4302 text[linelen] = 0;
4304 datalen -= linelen;
4305 data += linelen;
4308 return has_first_line ? &view->line[first_line] : NULL;
4311 static bool
4312 pager_common_read(struct view *view, const char *data, enum line_type type)
4314 struct line *line;
4316 if (!data)
4317 return TRUE;
4319 if (opt_wrap_lines) {
4320 line = pager_wrap_line(view, data, type);
4321 } else {
4322 line = add_line_text(view, data, type);
4325 if (!line)
4326 return FALSE;
4328 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
4329 add_pager_refs(view, data + STRING_SIZE("commit "));
4331 return TRUE;
4334 static bool
4335 pager_read(struct view *view, char *data)
4337 if (!data)
4338 return TRUE;
4340 return pager_common_read(view, data, get_line_type(data));
4343 static enum request
4344 pager_request(struct view *view, enum request request, struct line *line)
4346 int split = 0;
4348 if (request != REQ_ENTER)
4349 return request;
4351 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
4352 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4353 split = 1;
4356 /* Always scroll the view even if it was split. That way
4357 * you can use Enter to scroll through the log view and
4358 * split open each commit diff. */
4359 scroll_view(view, REQ_SCROLL_LINE_DOWN);
4361 /* FIXME: A minor workaround. Scrolling the view will call report_clear()
4362 * but if we are scrolling a non-current view this won't properly
4363 * update the view title. */
4364 if (split)
4365 update_view_title(view);
4367 return REQ_NONE;
4370 static bool
4371 pager_grep(struct view *view, struct line *line)
4373 const char *text[] = { line->data, NULL };
4375 return grep_text(view, text);
4378 static void
4379 pager_select(struct view *view, struct line *line)
4381 if (line->type == LINE_COMMIT) {
4382 char *text = (char *)line->data + STRING_SIZE("commit ");
4384 if (!view_has_flags(view, VIEW_NO_REF))
4385 string_copy_rev(view->ref, text);
4386 string_copy_rev(ref_commit, text);
4390 static bool
4391 pager_open(struct view *view, enum open_flags flags)
4393 if (display[0] == NULL) {
4394 if (!io_open(&view->io, "%s", ""))
4395 die("Failed to open stdin");
4396 flags = OPEN_PREPARED;
4398 } else if (!view->pipe && !view->lines && !(flags & OPEN_PREPARED)) {
4399 report("No pager content, press %s to run command from prompt",
4400 get_view_key(view, REQ_PROMPT));
4401 return FALSE;
4404 return begin_update(view, NULL, NULL, flags);
4407 static struct view_ops pager_ops = {
4408 "line",
4409 { "pager" },
4410 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
4412 pager_open,
4413 pager_read,
4414 pager_draw,
4415 pager_request,
4416 pager_grep,
4417 pager_select,
4420 static bool
4421 log_open(struct view *view, enum open_flags flags)
4423 static const char *log_argv[] = {
4424 "git", "log", opt_encoding_arg, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
4427 return begin_update(view, NULL, log_argv, flags);
4430 static enum request
4431 log_request(struct view *view, enum request request, struct line *line)
4433 switch (request) {
4434 case REQ_REFRESH:
4435 load_refs();
4436 refresh_view(view);
4437 return REQ_NONE;
4438 default:
4439 return pager_request(view, request, line);
4443 static struct view_ops log_ops = {
4444 "line",
4445 { "log" },
4446 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF | VIEW_SEND_CHILD_ENTER | VIEW_NO_PARENT_NAV,
4448 log_open,
4449 pager_read,
4450 pager_draw,
4451 log_request,
4452 pager_grep,
4453 pager_select,
4456 struct diff_state {
4457 bool after_commit_title;
4458 bool reading_diff_stat;
4459 bool combined_diff;
4462 #define DIFF_LINE_COMMIT_TITLE 1
4464 static bool
4465 diff_open(struct view *view, enum open_flags flags)
4467 static const char *diff_argv[] = {
4468 "git", "show", opt_encoding_arg, "--pretty=fuller", "--no-color", "--root",
4469 "--patch-with-stat",
4470 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
4471 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
4474 return begin_update(view, NULL, diff_argv, flags);
4477 static bool
4478 diff_common_read(struct view *view, const char *data, struct diff_state *state)
4480 enum line_type type = get_line_type(data);
4482 if (!view->lines && type != LINE_COMMIT)
4483 state->reading_diff_stat = TRUE;
4485 if (state->reading_diff_stat) {
4486 size_t len = strlen(data);
4487 char *pipe = strchr(data, '|');
4488 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
4489 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
4490 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
4492 if (pipe && (has_histogram || has_bin_diff || has_rename)) {
4493 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
4494 } else {
4495 state->reading_diff_stat = FALSE;
4498 } else if (!strcmp(data, "---")) {
4499 state->reading_diff_stat = TRUE;
4502 if (!state->after_commit_title && !prefixcmp(data, " ")) {
4503 struct line *line = add_line_text(view, data, LINE_COMMIT);
4505 if (line)
4506 line->user_flags |= DIFF_LINE_COMMIT_TITLE;
4507 state->after_commit_title = TRUE;
4508 return line != NULL;
4511 if (type == LINE_DIFF_HEADER) {
4512 const int len = line_info[LINE_DIFF_HEADER].linelen;
4514 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4515 !strncmp(data + len, "cc ", strlen("cc ")))
4516 state->combined_diff = TRUE;
4519 /* ADD2 and DEL2 are only valid in combined diff hunks */
4520 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4521 type = LINE_DEFAULT;
4523 return pager_common_read(view, data, type);
4526 static bool
4527 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
4529 struct line *marker = find_next_line_by_type(view, line, type);
4531 return marker &&
4532 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
4535 static enum request
4536 diff_common_enter(struct view *view, enum request request, struct line *line)
4538 if (line->type == LINE_DIFF_STAT) {
4539 int file_number = 0;
4541 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4542 file_number++;
4543 line--;
4546 for (line = view->line; view_has_line(view, line); line++) {
4547 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4548 if (!line)
4549 break;
4551 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4552 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4553 if (file_number == 1) {
4554 break;
4556 file_number--;
4560 if (!line) {
4561 report("Failed to find file diff");
4562 return REQ_NONE;
4565 select_view_line(view, line - view->line);
4566 report_clear();
4567 return REQ_NONE;
4569 } else {
4570 return pager_request(view, request, line);
4574 static bool
4575 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4577 char *sep = strchr(*text, c);
4579 if (sep != NULL) {
4580 *sep = 0;
4581 draw_text(view, *type, *text);
4582 *sep = c;
4583 *text = sep;
4584 *type = next_type;
4587 return sep != NULL;
4590 static bool
4591 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4593 char *text = line->data;
4594 enum line_type type = line->type;
4596 if (draw_lineno(view, lineno))
4597 return TRUE;
4599 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4600 return TRUE;
4602 if (type == LINE_DIFF_STAT) {
4603 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4604 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4605 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4606 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4607 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4608 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4609 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4611 } else {
4612 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4613 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4617 if (line->user_flags & DIFF_LINE_COMMIT_TITLE)
4618 draw_commit_title(view, text, 4);
4619 else
4620 draw_text(view, type, text);
4621 return TRUE;
4624 static bool
4625 diff_read(struct view *view, char *data)
4627 struct diff_state *state = view->private;
4629 if (!data) {
4630 /* Fall back to retry if no diff will be shown. */
4631 if (view->lines == 0 && opt_file_argv) {
4632 int pos = argv_size(view->argv)
4633 - argv_size(opt_file_argv) - 1;
4635 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4636 for (; view->argv[pos]; pos++) {
4637 free((void *) view->argv[pos]);
4638 view->argv[pos] = NULL;
4641 if (view->pipe)
4642 io_done(view->pipe);
4643 if (io_run(&view->io, IO_RD, view->dir, opt_env, view->argv))
4644 return FALSE;
4647 return TRUE;
4650 return diff_common_read(view, data, state);
4653 static bool
4654 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4655 struct blame_header *header, struct blame_commit *commit)
4657 char line_arg[SIZEOF_STR];
4658 const char *blame_argv[] = {
4659 "git", "blame", opt_encoding_arg, "-p", line_arg, ref, "--", file, NULL
4661 struct io io;
4662 bool ok = FALSE;
4663 char *buf;
4665 if (!string_format(line_arg, "-L%ld,+1", lineno))
4666 return FALSE;
4668 if (!io_run(&io, IO_RD, opt_cdup, opt_env, blame_argv))
4669 return FALSE;
4671 while ((buf = io_get(&io, '\n', TRUE))) {
4672 if (header) {
4673 if (!parse_blame_header(header, buf, 9999999))
4674 break;
4675 header = NULL;
4677 } else if (parse_blame_info(commit, buf)) {
4678 ok = TRUE;
4679 break;
4683 if (io_error(&io))
4684 ok = FALSE;
4686 io_done(&io);
4687 return ok;
4690 static unsigned int
4691 diff_get_lineno(struct view *view, struct line *line)
4693 const struct line *header, *chunk;
4694 const char *data;
4695 unsigned int lineno;
4697 /* Verify that we are after a diff header and one of its chunks */
4698 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4699 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4700 if (!header || !chunk || chunk < header)
4701 return 0;
4704 * In a chunk header, the number after the '+' sign is the number of its
4705 * following line, in the new version of the file. We increment this
4706 * number for each non-deletion line, until the given line position.
4708 data = strchr(chunk->data, '+');
4709 if (!data)
4710 return 0;
4712 lineno = atoi(data);
4713 chunk++;
4714 while (chunk++ < line)
4715 if (chunk->type != LINE_DIFF_DEL)
4716 lineno++;
4718 return lineno;
4721 static bool
4722 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4724 return prefixcmp(chunk, "@@ -") ||
4725 !(chunk = strchr(chunk, marker)) ||
4726 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4729 static enum request
4730 diff_trace_origin(struct view *view, struct line *line)
4732 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4733 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4734 const char *chunk_data;
4735 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4736 int lineno = 0;
4737 const char *file = NULL;
4738 char ref[SIZEOF_REF];
4739 struct blame_header header;
4740 struct blame_commit commit;
4742 if (!diff || !chunk || chunk == line) {
4743 report("The line to trace must be inside a diff chunk");
4744 return REQ_NONE;
4747 for (; diff < line && !file; diff++) {
4748 const char *data = diff->data;
4750 if (!prefixcmp(data, "--- a/")) {
4751 file = data + STRING_SIZE("--- a/");
4752 break;
4756 if (diff == line || !file) {
4757 report("Failed to read the file name");
4758 return REQ_NONE;
4761 chunk_data = chunk->data;
4763 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4764 report("Failed to read the line number");
4765 return REQ_NONE;
4768 if (lineno == 0) {
4769 report("This is the origin of the line");
4770 return REQ_NONE;
4773 for (chunk += 1; chunk < line; chunk++) {
4774 if (chunk->type == LINE_DIFF_ADD) {
4775 lineno += chunk_marker == '+';
4776 } else if (chunk->type == LINE_DIFF_DEL) {
4777 lineno += chunk_marker == '-';
4778 } else {
4779 lineno++;
4783 if (chunk_marker == '+')
4784 string_copy(ref, view->vid);
4785 else
4786 string_format(ref, "%s^", view->vid);
4788 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4789 report("Failed to read blame data");
4790 return REQ_NONE;
4793 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4794 string_copy(opt_ref, header.id);
4795 opt_goto_line = header.orig_lineno - 1;
4797 return REQ_VIEW_BLAME;
4800 static const char *
4801 diff_get_pathname(struct view *view, struct line *line)
4803 const struct line *header;
4804 const char *dst = NULL;
4805 const char *prefixes[] = { " b/", "cc ", "combined " };
4806 int i;
4808 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4809 if (!header)
4810 return NULL;
4812 for (i = 0; i < ARRAY_SIZE(prefixes) && !dst; i++)
4813 dst = strstr(header->data, prefixes[i]);
4815 return dst ? dst + strlen(prefixes[--i]) : NULL;
4818 static enum request
4819 diff_common_edit(struct view *view, enum request request, struct line *line)
4821 const char *file = diff_get_pathname(view, line);
4822 char path[SIZEOF_STR];
4823 bool has_path = file && string_format(path, "%s%s", opt_cdup, file);
4825 if (has_path && access(path, R_OK)) {
4826 report("Failed to open file: %s", file);
4827 return REQ_NONE;
4830 open_editor(file, diff_get_lineno(view, line));
4831 return REQ_NONE;
4834 static enum request
4835 diff_request(struct view *view, enum request request, struct line *line)
4837 switch (request) {
4838 case REQ_VIEW_BLAME:
4839 return diff_trace_origin(view, line);
4841 case REQ_DIFF_CONTEXT_UP:
4842 case REQ_DIFF_CONTEXT_DOWN:
4843 if (!update_diff_context(request))
4844 return REQ_NONE;
4845 reload_view(view);
4846 return REQ_NONE;
4849 case REQ_EDIT:
4850 return diff_common_edit(view, request, line);
4852 case REQ_ENTER:
4853 return diff_common_enter(view, request, line);
4855 case REQ_REFRESH:
4856 reload_view(view);
4857 return REQ_NONE;
4859 default:
4860 return pager_request(view, request, line);
4864 static void
4865 diff_select(struct view *view, struct line *line)
4867 if (line->type == LINE_DIFF_STAT) {
4868 string_format(view->ref, "Press '%s' to jump to file diff",
4869 get_view_key(view, REQ_ENTER));
4870 } else {
4871 const char *file = diff_get_pathname(view, line);
4873 if (file) {
4874 string_format(view->ref, "Changes to '%s'", file);
4875 string_format(opt_file, "%s", file);
4876 ref_blob[0] = 0;
4877 } else {
4878 string_ncopy(view->ref, view->id, strlen(view->id));
4879 pager_select(view, line);
4884 static struct view_ops diff_ops = {
4885 "line",
4886 { "diff" },
4887 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS | VIEW_STDIN | VIEW_FILE_FILTER,
4888 sizeof(struct diff_state),
4889 diff_open,
4890 diff_read,
4891 diff_common_draw,
4892 diff_request,
4893 pager_grep,
4894 diff_select,
4898 * Help backend
4901 static bool
4902 help_draw(struct view *view, struct line *line, unsigned int lineno)
4904 if (line->type == LINE_HELP_KEYMAP) {
4905 struct keymap *keymap = line->data;
4907 draw_formatted(view, line->type, "[%c] %s bindings",
4908 keymap->hidden ? '+' : '-', keymap->name);
4909 return TRUE;
4910 } else {
4911 return pager_draw(view, line, lineno);
4915 static bool
4916 help_open_keymap_title(struct view *view, struct keymap *keymap)
4918 add_line_static_data(view, keymap, LINE_HELP_KEYMAP);
4919 return keymap->hidden;
4922 static void
4923 help_open_keymap(struct view *view, struct keymap *keymap)
4925 const char *group = NULL;
4926 char buf[SIZEOF_STR];
4927 bool add_title = TRUE;
4928 int i;
4930 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4931 const char *key = NULL;
4933 if (req_info[i].request == REQ_NONE)
4934 continue;
4936 if (!req_info[i].request) {
4937 group = req_info[i].help;
4938 continue;
4941 key = get_keys(keymap, req_info[i].request, TRUE);
4942 if (!key || !*key)
4943 continue;
4945 if (add_title && help_open_keymap_title(view, keymap))
4946 return;
4947 add_title = FALSE;
4949 if (group) {
4950 add_line_text(view, group, LINE_HELP_GROUP);
4951 group = NULL;
4954 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4955 enum_name(req_info[i]), req_info[i].help);
4958 group = "External commands:";
4960 for (i = 0; i < run_requests; i++) {
4961 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4962 const char *key;
4964 if (!req || req->keymap != keymap)
4965 continue;
4967 key = get_key_name(req->key);
4968 if (!*key)
4969 key = "(no key defined)";
4971 if (add_title && help_open_keymap_title(view, keymap))
4972 return;
4973 add_title = FALSE;
4975 if (group) {
4976 add_line_text(view, group, LINE_HELP_GROUP);
4977 group = NULL;
4980 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
4981 return;
4983 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4987 static bool
4988 help_open(struct view *view, enum open_flags flags)
4990 struct keymap *keymap;
4992 reset_view(view);
4993 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4994 add_line_text(view, "", LINE_DEFAULT);
4996 for (keymap = keymaps; keymap; keymap = keymap->next)
4997 help_open_keymap(view, keymap);
4999 return TRUE;
5002 static enum request
5003 help_request(struct view *view, enum request request, struct line *line)
5005 switch (request) {
5006 case REQ_ENTER:
5007 if (line->type == LINE_HELP_KEYMAP) {
5008 struct keymap *keymap = line->data;
5010 keymap->hidden = !keymap->hidden;
5011 refresh_view(view);
5014 return REQ_NONE;
5015 default:
5016 return pager_request(view, request, line);
5020 static struct view_ops help_ops = {
5021 "line",
5022 { "help" },
5023 VIEW_NO_GIT_DIR,
5025 help_open,
5026 NULL,
5027 help_draw,
5028 help_request,
5029 pager_grep,
5030 pager_select,
5035 * Tree backend
5038 struct tree_stack_entry {
5039 struct tree_stack_entry *prev; /* Entry below this in the stack */
5040 unsigned long lineno; /* Line number to restore */
5041 char *name; /* Position of name in opt_path */
5044 /* The top of the path stack. */
5045 static struct tree_stack_entry *tree_stack = NULL;
5046 unsigned long tree_lineno = 0;
5048 static void
5049 pop_tree_stack_entry(void)
5051 struct tree_stack_entry *entry = tree_stack;
5053 tree_lineno = entry->lineno;
5054 entry->name[0] = 0;
5055 tree_stack = entry->prev;
5056 free(entry);
5059 static void
5060 push_tree_stack_entry(const char *name, unsigned long lineno)
5062 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
5063 size_t pathlen = strlen(opt_path);
5065 if (!entry)
5066 return;
5068 entry->prev = tree_stack;
5069 entry->name = opt_path + pathlen;
5070 tree_stack = entry;
5072 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
5073 pop_tree_stack_entry();
5074 return;
5077 /* Move the current line to the first tree entry. */
5078 tree_lineno = 1;
5079 entry->lineno = lineno;
5082 /* Parse output from git-ls-tree(1):
5084 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
5087 #define SIZEOF_TREE_ATTR \
5088 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
5090 #define SIZEOF_TREE_MODE \
5091 STRING_SIZE("100644 ")
5093 #define TREE_ID_OFFSET \
5094 STRING_SIZE("100644 blob ")
5096 #define tree_path_is_parent(path) (!strcmp("..", (path)))
5098 struct tree_entry {
5099 char id[SIZEOF_REV];
5100 char commit[SIZEOF_REV];
5101 mode_t mode;
5102 struct time time; /* Date from the author ident. */
5103 const struct ident *author; /* Author of the commit. */
5104 char name[1];
5107 struct tree_state {
5108 char commit[SIZEOF_REV];
5109 const struct ident *author;
5110 struct time author_time;
5111 bool read_date;
5114 static const char *
5115 tree_path(const struct line *line)
5117 return ((struct tree_entry *) line->data)->name;
5120 static int
5121 tree_compare_entry(const struct line *line1, const struct line *line2)
5123 if (line1->type != line2->type)
5124 return line1->type == LINE_TREE_DIR ? -1 : 1;
5125 return strcmp(tree_path(line1), tree_path(line2));
5128 static const enum sort_field tree_sort_fields[] = {
5129 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5131 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
5133 static int
5134 tree_compare(const void *l1, const void *l2)
5136 const struct line *line1 = (const struct line *) l1;
5137 const struct line *line2 = (const struct line *) l2;
5138 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
5139 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
5141 if (line1->type == LINE_TREE_HEAD)
5142 return -1;
5143 if (line2->type == LINE_TREE_HEAD)
5144 return 1;
5146 switch (get_sort_field(tree_sort_state)) {
5147 case ORDERBY_DATE:
5148 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
5150 case ORDERBY_AUTHOR:
5151 return sort_order(tree_sort_state, ident_compare(entry1->author, entry2->author));
5153 case ORDERBY_NAME:
5154 default:
5155 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
5160 static struct line *
5161 tree_entry(struct view *view, enum line_type type, const char *path,
5162 const char *mode, const char *id)
5164 bool custom = type == LINE_TREE_HEAD || tree_path_is_parent(path);
5165 struct tree_entry *entry;
5166 struct line *line = add_line_alloc(view, &entry, type, strlen(path), custom);
5168 if (!line)
5169 return NULL;
5171 strncpy(entry->name, path, strlen(path));
5172 if (mode)
5173 entry->mode = strtoul(mode, NULL, 8);
5174 if (id)
5175 string_copy_rev(entry->id, id);
5177 return line;
5180 static bool
5181 tree_read_date(struct view *view, char *text, struct tree_state *state)
5183 if (!text && state->read_date) {
5184 state->read_date = FALSE;
5185 return TRUE;
5187 } else if (!text) {
5188 /* Find next entry to process */
5189 const char *log_file[] = {
5190 "git", "log", opt_encoding_arg, "--no-color", "--pretty=raw",
5191 "--cc", "--raw", view->id, "--", "%(directory)", NULL
5194 if (!view->lines) {
5195 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
5196 tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref);
5197 report("Tree is empty");
5198 return TRUE;
5201 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
5202 report("Failed to load tree data");
5203 return TRUE;
5206 state->read_date = TRUE;
5207 return FALSE;
5209 } else if (*text == 'c' && get_line_type(text) == LINE_COMMIT) {
5210 string_copy_rev(state->commit, text + STRING_SIZE("commit "));
5212 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
5213 parse_author_line(text + STRING_SIZE("author "),
5214 &state->author, &state->author_time);
5216 } else if (*text == ':') {
5217 char *pos;
5218 size_t annotated = 1;
5219 size_t i;
5221 pos = strchr(text, '\t');
5222 if (!pos)
5223 return TRUE;
5224 text = pos + 1;
5225 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
5226 text += strlen(opt_path);
5227 pos = strchr(text, '/');
5228 if (pos)
5229 *pos = 0;
5231 for (i = 1; i < view->lines; i++) {
5232 struct line *line = &view->line[i];
5233 struct tree_entry *entry = line->data;
5235 annotated += !!entry->author;
5236 if (entry->author || strcmp(entry->name, text))
5237 continue;
5239 string_copy_rev(entry->commit, state->commit);
5240 entry->author = state->author;
5241 entry->time = state->author_time;
5242 line->dirty = 1;
5243 break;
5246 if (annotated == view->lines)
5247 io_kill(view->pipe);
5249 return TRUE;
5252 static bool
5253 tree_read(struct view *view, char *text)
5255 struct tree_state *state = view->private;
5256 struct tree_entry *data;
5257 struct line *entry, *line;
5258 enum line_type type;
5259 size_t textlen = text ? strlen(text) : 0;
5260 char *path = text + SIZEOF_TREE_ATTR;
5262 if (state->read_date || !text)
5263 return tree_read_date(view, text, state);
5265 if (textlen <= SIZEOF_TREE_ATTR)
5266 return FALSE;
5267 if (view->lines == 0 &&
5268 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
5269 return FALSE;
5271 /* Strip the path part ... */
5272 if (*opt_path) {
5273 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
5274 size_t striplen = strlen(opt_path);
5276 if (pathlen > striplen)
5277 memmove(path, path + striplen,
5278 pathlen - striplen + 1);
5280 /* Insert "link" to parent directory. */
5281 if (view->lines == 1 &&
5282 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
5283 return FALSE;
5286 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
5287 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
5288 if (!entry)
5289 return FALSE;
5290 data = entry->data;
5292 /* Skip "Directory ..." and ".." line. */
5293 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
5294 if (tree_compare_entry(line, entry) <= 0)
5295 continue;
5297 memmove(line + 1, line, (entry - line) * sizeof(*entry));
5299 line->data = data;
5300 line->type = type;
5301 for (; line <= entry; line++)
5302 line->dirty = line->cleareol = 1;
5303 return TRUE;
5306 if (tree_lineno <= view->pos.lineno)
5307 tree_lineno = view->custom_lines;
5309 if (tree_lineno > view->pos.lineno) {
5310 view->pos.lineno = tree_lineno;
5311 tree_lineno = 0;
5314 return TRUE;
5317 static bool
5318 tree_draw(struct view *view, struct line *line, unsigned int lineno)
5320 struct tree_entry *entry = line->data;
5322 if (line->type == LINE_TREE_HEAD) {
5323 if (draw_text(view, line->type, "Directory path /"))
5324 return TRUE;
5325 } else {
5326 if (draw_mode(view, entry->mode))
5327 return TRUE;
5329 if (draw_author(view, entry->author))
5330 return TRUE;
5332 if (draw_date(view, &entry->time))
5333 return TRUE;
5335 if (opt_show_id && draw_id(view, LINE_ID, entry->commit))
5336 return TRUE;
5339 draw_text(view, line->type, entry->name);
5340 return TRUE;
5343 static void
5344 open_blob_editor(const char *id, const char *name, unsigned int lineno)
5346 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
5347 char file[SIZEOF_STR];
5348 int fd;
5350 if (!name)
5351 name = "unknown";
5353 if (!string_format(file, "%s/tigblob.XXXXXX.%s", get_temp_dir(), name)) {
5354 report("Temporary file name is too long");
5355 return;
5358 fd = mkstemps(file, strlen(name) + 1);
5360 if (fd == -1)
5361 report("Failed to create temporary file");
5362 else if (!io_run_append(blob_argv, fd))
5363 report("Failed to save blob data to file");
5364 else
5365 open_editor(file, lineno);
5366 if (fd != -1)
5367 unlink(file);
5370 static enum request
5371 tree_request(struct view *view, enum request request, struct line *line)
5373 enum open_flags flags;
5374 struct tree_entry *entry = line->data;
5376 switch (request) {
5377 case REQ_VIEW_BLAME:
5378 if (line->type != LINE_TREE_FILE) {
5379 report("Blame only supported for files");
5380 return REQ_NONE;
5383 string_copy(opt_ref, view->vid);
5384 return request;
5386 case REQ_EDIT:
5387 if (line->type != LINE_TREE_FILE) {
5388 report("Edit only supported for files");
5389 } else if (!is_head_commit(view->vid)) {
5390 open_blob_editor(entry->id, entry->name, 0);
5391 } else {
5392 open_editor(opt_file, 0);
5394 return REQ_NONE;
5396 case REQ_TOGGLE_SORT_FIELD:
5397 case REQ_TOGGLE_SORT_ORDER:
5398 sort_view(view, request, &tree_sort_state, tree_compare);
5399 return REQ_NONE;
5401 case REQ_PARENT:
5402 if (!*opt_path) {
5403 /* quit view if at top of tree */
5404 return REQ_VIEW_CLOSE;
5406 /* fake 'cd ..' */
5407 line = &view->line[1];
5408 break;
5410 case REQ_ENTER:
5411 break;
5413 default:
5414 return request;
5417 /* Cleanup the stack if the tree view is at a different tree. */
5418 while (!*opt_path && tree_stack)
5419 pop_tree_stack_entry();
5421 switch (line->type) {
5422 case LINE_TREE_DIR:
5423 /* Depending on whether it is a subdirectory or parent link
5424 * mangle the path buffer. */
5425 if (line == &view->line[1] && *opt_path) {
5426 pop_tree_stack_entry();
5428 } else {
5429 const char *basename = tree_path(line);
5431 push_tree_stack_entry(basename, view->pos.lineno);
5434 /* Trees and subtrees share the same ID, so they are not not
5435 * unique like blobs. */
5436 flags = OPEN_RELOAD;
5437 request = REQ_VIEW_TREE;
5438 break;
5440 case LINE_TREE_FILE:
5441 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5442 request = REQ_VIEW_BLOB;
5443 break;
5445 default:
5446 return REQ_NONE;
5449 open_view(view, request, flags);
5450 if (request == REQ_VIEW_TREE)
5451 view->pos.lineno = tree_lineno;
5453 return REQ_NONE;
5456 static bool
5457 tree_grep(struct view *view, struct line *line)
5459 struct tree_entry *entry = line->data;
5460 const char *text[] = {
5461 entry->name,
5462 mkauthor(entry->author, opt_author_width, opt_author),
5463 mkdate(&entry->time, opt_date),
5464 NULL
5467 return grep_text(view, text);
5470 static void
5471 tree_select(struct view *view, struct line *line)
5473 struct tree_entry *entry = line->data;
5475 if (line->type == LINE_TREE_HEAD) {
5476 string_format(view->ref, "Files in /%s", opt_path);
5477 return;
5480 if (line->type == LINE_TREE_DIR && tree_path_is_parent(entry->name)) {
5481 string_copy(view->ref, "Open parent directory");
5482 ref_blob[0] = 0;
5483 return;
5486 if (line->type == LINE_TREE_FILE) {
5487 string_copy_rev(ref_blob, entry->id);
5488 string_format(opt_file, "%s%s", opt_path, tree_path(line));
5491 string_copy_rev(view->ref, entry->id);
5494 static bool
5495 tree_open(struct view *view, enum open_flags flags)
5497 static const char *tree_argv[] = {
5498 "git", "ls-tree", "%(commit)", "%(directory)", NULL
5501 if (string_rev_is_null(ref_commit)) {
5502 report("No tree exists for this commit");
5503 return FALSE;
5506 if (view->lines == 0 && opt_prefix[0]) {
5507 char *pos = opt_prefix;
5509 while (pos && *pos) {
5510 char *end = strchr(pos, '/');
5512 if (end)
5513 *end = 0;
5514 push_tree_stack_entry(pos, 0);
5515 pos = end;
5516 if (end) {
5517 *end = '/';
5518 pos++;
5522 } else if (strcmp(view->vid, view->id)) {
5523 opt_path[0] = 0;
5526 return begin_update(view, opt_cdup, tree_argv, flags);
5529 static struct view_ops tree_ops = {
5530 "file",
5531 { "tree" },
5532 VIEW_SEND_CHILD_ENTER,
5533 sizeof(struct tree_state),
5534 tree_open,
5535 tree_read,
5536 tree_draw,
5537 tree_request,
5538 tree_grep,
5539 tree_select,
5542 static bool
5543 blob_open(struct view *view, enum open_flags flags)
5545 static const char *blob_argv[] = {
5546 "git", "cat-file", "blob", "%(blob)", NULL
5549 if (!ref_blob[0] && opt_file[0]) {
5550 const char *commit = ref_commit[0] ? ref_commit : "HEAD";
5551 char blob_spec[SIZEOF_STR];
5552 const char *rev_parse_argv[] = {
5553 "git", "rev-parse", blob_spec, NULL
5556 if (!string_format(blob_spec, "%s:%s", commit, opt_file) ||
5557 !io_run_buf(rev_parse_argv, ref_blob, sizeof(ref_blob))) {
5558 report("Failed to resolve blob from file name");
5559 return FALSE;
5563 if (!ref_blob[0]) {
5564 report("No file chosen, press %s to open tree view",
5565 get_view_key(view, REQ_VIEW_TREE));
5566 return FALSE;
5569 view->encoding = get_path_encoding(opt_file, opt_encoding);
5571 return begin_update(view, NULL, blob_argv, flags);
5574 static bool
5575 blob_read(struct view *view, char *line)
5577 if (!line)
5578 return TRUE;
5579 return add_line_text(view, line, LINE_DEFAULT) != NULL;
5582 static enum request
5583 blob_request(struct view *view, enum request request, struct line *line)
5585 switch (request) {
5586 case REQ_EDIT:
5587 open_blob_editor(view->vid, NULL, (line - view->line) + 1);
5588 return REQ_NONE;
5589 default:
5590 return pager_request(view, request, line);
5594 static struct view_ops blob_ops = {
5595 "line",
5596 { "blob" },
5597 VIEW_NO_FLAGS,
5599 blob_open,
5600 blob_read,
5601 pager_draw,
5602 blob_request,
5603 pager_grep,
5604 pager_select,
5608 * Blame backend
5610 * Loading the blame view is a two phase job:
5612 * 1. File content is read either using opt_file from the
5613 * filesystem or using git-cat-file.
5614 * 2. Then blame information is incrementally added by
5615 * reading output from git-blame.
5618 struct blame {
5619 struct blame_commit *commit;
5620 unsigned long lineno;
5621 char text[1];
5624 struct blame_state {
5625 struct blame_commit *commit;
5626 int blamed;
5627 bool done_reading;
5628 bool auto_filename_display;
5631 static bool
5632 blame_detect_filename_display(struct view *view)
5634 bool show_filenames = FALSE;
5635 const char *filename = NULL;
5636 int i;
5638 if (opt_blame_argv) {
5639 for (i = 0; opt_blame_argv[i]; i++) {
5640 if (prefixcmp(opt_blame_argv[i], "-C"))
5641 continue;
5643 show_filenames = TRUE;
5647 for (i = 0; i < view->lines; i++) {
5648 struct blame *blame = view->line[i].data;
5650 if (blame->commit && blame->commit->id[0]) {
5651 if (!filename)
5652 filename = blame->commit->filename;
5653 else if (strcmp(filename, blame->commit->filename))
5654 show_filenames = TRUE;
5658 return show_filenames;
5661 static bool
5662 blame_open(struct view *view, enum open_flags flags)
5664 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5665 char path[SIZEOF_STR];
5666 size_t i;
5668 if (!opt_file[0]) {
5669 report("No file chosen, press %s to open tree view",
5670 get_view_key(view, REQ_VIEW_TREE));
5671 return FALSE;
5674 if (!view->prev && *opt_prefix && !(flags & (OPEN_RELOAD | OPEN_REFRESH))) {
5675 string_copy(path, opt_file);
5676 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
5677 report("Failed to setup the blame view");
5678 return FALSE;
5682 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5683 const char *blame_cat_file_argv[] = {
5684 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5687 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5688 return FALSE;
5691 /* First pass: remove multiple references to the same commit. */
5692 for (i = 0; i < view->lines; i++) {
5693 struct blame *blame = view->line[i].data;
5695 if (blame->commit && blame->commit->id[0])
5696 blame->commit->id[0] = 0;
5697 else
5698 blame->commit = NULL;
5701 /* Second pass: free existing references. */
5702 for (i = 0; i < view->lines; i++) {
5703 struct blame *blame = view->line[i].data;
5705 if (blame->commit)
5706 free(blame->commit);
5709 string_format(view->vid, "%s", opt_file);
5710 string_format(view->ref, "%s ...", opt_file);
5712 return TRUE;
5715 static struct blame_commit *
5716 get_blame_commit(struct view *view, const char *id)
5718 size_t i;
5720 for (i = 0; i < view->lines; i++) {
5721 struct blame *blame = view->line[i].data;
5723 if (!blame->commit)
5724 continue;
5726 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5727 return blame->commit;
5731 struct blame_commit *commit = calloc(1, sizeof(*commit));
5733 if (commit)
5734 string_ncopy(commit->id, id, SIZEOF_REV);
5735 return commit;
5739 static struct blame_commit *
5740 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5742 struct blame_header header;
5743 struct blame_commit *commit;
5744 struct blame *blame;
5746 if (!parse_blame_header(&header, text, view->lines))
5747 return NULL;
5749 commit = get_blame_commit(view, text);
5750 if (!commit)
5751 return NULL;
5753 state->blamed += header.group;
5754 while (header.group--) {
5755 struct line *line = &view->line[header.lineno + header.group - 1];
5757 blame = line->data;
5758 blame->commit = commit;
5759 blame->lineno = header.orig_lineno + header.group - 1;
5760 line->dirty = 1;
5763 return commit;
5766 static bool
5767 blame_read_file(struct view *view, const char *text, struct blame_state *state)
5769 if (!text) {
5770 const char *blame_argv[] = {
5771 "git", "blame", opt_encoding_arg, "%(blameargs)", "--incremental",
5772 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5775 if (view->lines == 0 && !view->prev)
5776 die("No blame exist for %s", view->vid);
5778 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5779 report("Failed to load blame data");
5780 return TRUE;
5783 if (opt_goto_line > 0) {
5784 select_view_line(view, opt_goto_line);
5785 opt_goto_line = 0;
5788 state->done_reading = TRUE;
5789 return FALSE;
5791 } else {
5792 size_t textlen = strlen(text);
5793 struct blame *blame;
5795 if (!add_line_alloc(view, &blame, LINE_ID, textlen, FALSE))
5796 return FALSE;
5798 blame->commit = NULL;
5799 strncpy(blame->text, text, textlen);
5800 blame->text[textlen] = 0;
5801 return TRUE;
5805 static bool
5806 blame_read(struct view *view, char *line)
5808 struct blame_state *state = view->private;
5810 if (!state->done_reading)
5811 return blame_read_file(view, line, state);
5813 if (!line) {
5814 state->auto_filename_display = blame_detect_filename_display(view);
5815 string_format(view->ref, "%s", view->vid);
5816 if (view_is_displayed(view)) {
5817 update_view_title(view);
5818 redraw_view_from(view, 0);
5820 return TRUE;
5823 if (!state->commit) {
5824 state->commit = read_blame_commit(view, line, state);
5825 string_format(view->ref, "%s %2zd%%", view->vid,
5826 view->lines ? state->blamed * 100 / view->lines : 0);
5828 } else if (parse_blame_info(state->commit, line)) {
5829 state->commit = NULL;
5832 return TRUE;
5835 static bool
5836 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5838 struct blame_state *state = view->private;
5839 struct blame *blame = line->data;
5840 struct time *time = NULL;
5841 const char *id = NULL, *filename = NULL;
5842 const struct ident *author = NULL;
5843 enum line_type id_type = LINE_ID;
5844 static const enum line_type blame_colors[] = {
5845 LINE_PALETTE_0,
5846 LINE_PALETTE_1,
5847 LINE_PALETTE_2,
5848 LINE_PALETTE_3,
5849 LINE_PALETTE_4,
5850 LINE_PALETTE_5,
5851 LINE_PALETTE_6,
5854 #define BLAME_COLOR(i) \
5855 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5857 if (blame->commit && *blame->commit->filename) {
5858 id = blame->commit->id;
5859 author = blame->commit->author;
5860 filename = blame->commit->filename;
5861 time = &blame->commit->time;
5862 id_type = BLAME_COLOR((long) blame->commit);
5865 if (draw_date(view, time))
5866 return TRUE;
5868 if (draw_author(view, author))
5869 return TRUE;
5871 if (draw_filename(view, filename, state->auto_filename_display))
5872 return TRUE;
5874 if (draw_id(view, id_type, id))
5875 return TRUE;
5877 if (draw_lineno(view, lineno))
5878 return TRUE;
5880 draw_text(view, LINE_DEFAULT, blame->text);
5881 return TRUE;
5884 static bool
5885 check_blame_commit(struct blame *blame, bool check_null_id)
5887 if (!blame->commit)
5888 report("Commit data not loaded yet");
5889 else if (check_null_id && string_rev_is_null(blame->commit->id))
5890 report("No commit exist for the selected line");
5891 else
5892 return TRUE;
5893 return FALSE;
5896 static void
5897 setup_blame_parent_line(struct view *view, struct blame *blame)
5899 char from[SIZEOF_REF + SIZEOF_STR];
5900 char to[SIZEOF_REF + SIZEOF_STR];
5901 const char *diff_tree_argv[] = {
5902 "git", "diff", opt_encoding_arg, "--no-textconv", "--no-extdiff",
5903 "--no-color", "-U0", from, to, "--", NULL
5905 struct io io;
5906 int parent_lineno = -1;
5907 int blamed_lineno = -1;
5908 char *line;
5910 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5911 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5912 !io_run(&io, IO_RD, NULL, opt_env, diff_tree_argv))
5913 return;
5915 while ((line = io_get(&io, '\n', TRUE))) {
5916 if (*line == '@') {
5917 char *pos = strchr(line, '+');
5919 parent_lineno = atoi(line + 4);
5920 if (pos)
5921 blamed_lineno = atoi(pos + 1);
5923 } else if (*line == '+' && parent_lineno != -1) {
5924 if (blame->lineno == blamed_lineno - 1 &&
5925 !strcmp(blame->text, line + 1)) {
5926 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
5927 break;
5929 blamed_lineno++;
5933 io_done(&io);
5936 static enum request
5937 blame_request(struct view *view, enum request request, struct line *line)
5939 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5940 struct blame *blame = line->data;
5942 switch (request) {
5943 case REQ_VIEW_BLAME:
5944 if (check_blame_commit(blame, TRUE)) {
5945 string_copy(opt_ref, blame->commit->id);
5946 string_copy(opt_file, blame->commit->filename);
5947 if (blame->lineno)
5948 view->pos.lineno = blame->lineno;
5949 reload_view(view);
5951 break;
5953 case REQ_PARENT:
5954 if (!check_blame_commit(blame, TRUE))
5955 break;
5956 if (!*blame->commit->parent_id) {
5957 report("The selected commit has no parents");
5958 } else {
5959 string_copy_rev(opt_ref, blame->commit->parent_id);
5960 string_copy(opt_file, blame->commit->parent_filename);
5961 setup_blame_parent_line(view, blame);
5962 opt_goto_line = blame->lineno;
5963 reload_view(view);
5965 break;
5967 case REQ_ENTER:
5968 if (!check_blame_commit(blame, FALSE))
5969 break;
5971 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5972 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5973 break;
5975 if (string_rev_is_null(blame->commit->id)) {
5976 struct view *diff = VIEW(REQ_VIEW_DIFF);
5977 const char *diff_parent_argv[] = {
5978 GIT_DIFF_BLAME(opt_encoding_arg,
5979 opt_diff_context_arg,
5980 opt_ignore_space_arg, view->vid)
5982 const char *diff_no_parent_argv[] = {
5983 GIT_DIFF_BLAME_NO_PARENT(opt_encoding_arg,
5984 opt_diff_context_arg,
5985 opt_ignore_space_arg, view->vid)
5987 const char **diff_index_argv = *blame->commit->parent_id
5988 ? diff_parent_argv : diff_no_parent_argv;
5990 open_argv(view, diff, diff_index_argv, NULL, flags);
5991 if (diff->pipe)
5992 string_copy_rev(diff->ref, NULL_ID);
5993 } else {
5994 open_view(view, REQ_VIEW_DIFF, flags);
5996 break;
5998 default:
5999 return request;
6002 return REQ_NONE;
6005 static bool
6006 blame_grep(struct view *view, struct line *line)
6008 struct blame *blame = line->data;
6009 struct blame_commit *commit = blame->commit;
6010 const char *text[] = {
6011 blame->text,
6012 commit ? commit->title : "",
6013 commit ? commit->id : "",
6014 commit ? mkauthor(commit->author, opt_author_width, opt_author) : "",
6015 commit ? mkdate(&commit->time, opt_date) : "",
6016 NULL
6019 return grep_text(view, text);
6022 static void
6023 blame_select(struct view *view, struct line *line)
6025 struct blame *blame = line->data;
6026 struct blame_commit *commit = blame->commit;
6028 if (!commit)
6029 return;
6031 if (string_rev_is_null(commit->id))
6032 string_ncopy(ref_commit, "HEAD", 4);
6033 else
6034 string_copy_rev(ref_commit, commit->id);
6037 static struct view_ops blame_ops = {
6038 "line",
6039 { "blame" },
6040 VIEW_ALWAYS_LINENO | VIEW_SEND_CHILD_ENTER,
6041 sizeof(struct blame_state),
6042 blame_open,
6043 blame_read,
6044 blame_draw,
6045 blame_request,
6046 blame_grep,
6047 blame_select,
6051 * Branch backend
6054 struct branch {
6055 const struct ident *author; /* Author of the last commit. */
6056 struct time time; /* Date of the last activity. */
6057 char title[128]; /* First line of the commit message. */
6058 const struct ref *ref; /* Name and commit ID information. */
6061 static const struct ref branch_all;
6062 #define BRANCH_ALL_NAME "All branches"
6063 #define branch_is_all(branch) ((branch)->ref == &branch_all)
6065 static const enum sort_field branch_sort_fields[] = {
6066 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
6068 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
6070 struct branch_state {
6071 char id[SIZEOF_REV];
6072 size_t max_ref_length;
6075 static int
6076 branch_compare(const void *l1, const void *l2)
6078 const struct branch *branch1 = ((const struct line *) l1)->data;
6079 const struct branch *branch2 = ((const struct line *) l2)->data;
6081 if (branch_is_all(branch1))
6082 return -1;
6083 else if (branch_is_all(branch2))
6084 return 1;
6086 switch (get_sort_field(branch_sort_state)) {
6087 case ORDERBY_DATE:
6088 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
6090 case ORDERBY_AUTHOR:
6091 return sort_order(branch_sort_state, ident_compare(branch1->author, branch2->author));
6093 case ORDERBY_NAME:
6094 default:
6095 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
6099 static bool
6100 branch_draw(struct view *view, struct line *line, unsigned int lineno)
6102 struct branch_state *state = view->private;
6103 struct branch *branch = line->data;
6104 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
6105 const char *branch_name = branch_is_all(branch) ? BRANCH_ALL_NAME : branch->ref->name;
6107 if (draw_lineno(view, lineno))
6108 return TRUE;
6110 if (draw_date(view, &branch->time))
6111 return TRUE;
6113 if (draw_author(view, branch->author))
6114 return TRUE;
6116 if (draw_field(view, type, branch_name, state->max_ref_length, FALSE))
6117 return TRUE;
6119 if (opt_show_id && draw_id(view, LINE_ID, branch->ref->id))
6120 return TRUE;
6122 draw_text(view, LINE_DEFAULT, branch->title);
6123 return TRUE;
6126 static enum request
6127 branch_request(struct view *view, enum request request, struct line *line)
6129 struct branch *branch = line->data;
6131 switch (request) {
6132 case REQ_REFRESH:
6133 load_refs();
6134 refresh_view(view);
6135 return REQ_NONE;
6137 case REQ_TOGGLE_SORT_FIELD:
6138 case REQ_TOGGLE_SORT_ORDER:
6139 sort_view(view, request, &branch_sort_state, branch_compare);
6140 return REQ_NONE;
6142 case REQ_ENTER:
6144 const struct ref *ref = branch->ref;
6145 const char *all_branches_argv[] = {
6146 GIT_MAIN_LOG(opt_encoding_arg, "", branch_is_all(branch) ? "--all" : ref->name, "")
6148 struct view *main_view = VIEW(REQ_VIEW_MAIN);
6150 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
6151 return REQ_NONE;
6153 case REQ_JUMP_COMMIT:
6155 int lineno;
6157 for (lineno = 0; lineno < view->lines; lineno++) {
6158 struct branch *branch = view->line[lineno].data;
6160 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
6161 select_view_line(view, lineno);
6162 report_clear();
6163 return REQ_NONE;
6167 default:
6168 return request;
6172 static bool
6173 branch_read(struct view *view, char *line)
6175 struct branch_state *state = view->private;
6176 const char *title = NULL;
6177 const struct ident *author = NULL;
6178 struct time time = {};
6179 size_t i;
6181 if (!line)
6182 return TRUE;
6184 switch (get_line_type(line)) {
6185 case LINE_COMMIT:
6186 string_copy_rev(state->id, line + STRING_SIZE("commit "));
6187 return TRUE;
6189 case LINE_AUTHOR:
6190 parse_author_line(line + STRING_SIZE("author "), &author, &time);
6191 break;
6193 default:
6194 title = line + STRING_SIZE("title ");
6197 for (i = 0; i < view->lines; i++) {
6198 struct branch *branch = view->line[i].data;
6200 if (strcmp(branch->ref->id, state->id))
6201 continue;
6203 if (author) {
6204 branch->author = author;
6205 branch->time = time;
6208 if (title)
6209 string_expand(branch->title, sizeof(branch->title), title, 1);
6211 view->line[i].dirty = TRUE;
6214 return TRUE;
6217 static bool
6218 branch_open_visitor(void *data, const struct ref *ref)
6220 struct view *view = data;
6221 struct branch_state *state = view->private;
6222 struct branch *branch;
6223 bool is_all = ref == &branch_all;
6224 size_t ref_length;
6226 if (ref->tag || ref->ltag)
6227 return TRUE;
6229 if (!add_line_alloc(view, &branch, LINE_DEFAULT, 0, is_all))
6230 return FALSE;
6232 ref_length = is_all ? STRING_SIZE(BRANCH_ALL_NAME) : strlen(ref->name);
6233 if (ref_length > state->max_ref_length)
6234 state->max_ref_length = ref_length;
6236 branch->ref = ref;
6237 return TRUE;
6240 static bool
6241 branch_open(struct view *view, enum open_flags flags)
6243 const char *branch_log[] = {
6244 "git", "log", opt_encoding_arg, "--no-color", "--date=raw",
6245 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
6246 "--all", "--simplify-by-decoration", NULL
6249 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
6250 report("Failed to load branch data");
6251 return FALSE;
6254 branch_open_visitor(view, &branch_all);
6255 foreach_ref(branch_open_visitor, view);
6257 return TRUE;
6260 static bool
6261 branch_grep(struct view *view, struct line *line)
6263 struct branch *branch = line->data;
6264 const char *text[] = {
6265 branch->ref->name,
6266 mkauthor(branch->author, opt_author_width, opt_author),
6267 NULL
6270 return grep_text(view, text);
6273 static void
6274 branch_select(struct view *view, struct line *line)
6276 struct branch *branch = line->data;
6278 if (branch_is_all(branch)) {
6279 string_copy(view->ref, BRANCH_ALL_NAME);
6280 return;
6282 string_copy_rev(view->ref, branch->ref->id);
6283 string_copy_rev(ref_commit, branch->ref->id);
6284 string_copy_rev(ref_head, branch->ref->id);
6285 string_copy_rev(ref_branch, branch->ref->name);
6288 static struct view_ops branch_ops = {
6289 "branch",
6290 { "branch" },
6291 VIEW_NO_FLAGS,
6292 sizeof(struct branch_state),
6293 branch_open,
6294 branch_read,
6295 branch_draw,
6296 branch_request,
6297 branch_grep,
6298 branch_select,
6302 * Status backend
6305 struct status {
6306 char status;
6307 struct {
6308 mode_t mode;
6309 char rev[SIZEOF_REV];
6310 char name[SIZEOF_STR];
6311 } old;
6312 struct {
6313 mode_t mode;
6314 char rev[SIZEOF_REV];
6315 char name[SIZEOF_STR];
6316 } new;
6319 static char status_onbranch[SIZEOF_STR];
6320 static struct status stage_status;
6321 static enum line_type stage_line_type;
6323 DEFINE_ALLOCATOR(realloc_ints, int, 32)
6325 /* This should work even for the "On branch" line. */
6326 static inline bool
6327 status_has_none(struct view *view, struct line *line)
6329 return view_has_line(view, line) && !line[1].data;
6332 /* Get fields from the diff line:
6333 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
6335 static inline bool
6336 status_get_diff(struct status *file, const char *buf, size_t bufsize)
6338 const char *old_mode = buf + 1;
6339 const char *new_mode = buf + 8;
6340 const char *old_rev = buf + 15;
6341 const char *new_rev = buf + 56;
6342 const char *status = buf + 97;
6344 if (bufsize < 98 ||
6345 old_mode[-1] != ':' ||
6346 new_mode[-1] != ' ' ||
6347 old_rev[-1] != ' ' ||
6348 new_rev[-1] != ' ' ||
6349 status[-1] != ' ')
6350 return FALSE;
6352 file->status = *status;
6354 string_copy_rev(file->old.rev, old_rev);
6355 string_copy_rev(file->new.rev, new_rev);
6357 file->old.mode = strtoul(old_mode, NULL, 8);
6358 file->new.mode = strtoul(new_mode, NULL, 8);
6360 file->old.name[0] = file->new.name[0] = 0;
6362 return TRUE;
6365 static bool
6366 status_run(struct view *view, const char *argv[], char status, enum line_type type)
6368 struct status *unmerged = NULL;
6369 char *buf;
6370 struct io io;
6372 if (!io_run(&io, IO_RD, opt_cdup, opt_env, argv))
6373 return FALSE;
6375 add_line_nodata(view, type);
6377 while ((buf = io_get(&io, 0, TRUE))) {
6378 struct status *file = unmerged;
6380 if (!file) {
6381 if (!add_line_alloc(view, &file, type, 0, FALSE))
6382 goto error_out;
6385 /* Parse diff info part. */
6386 if (status) {
6387 file->status = status;
6388 if (status == 'A')
6389 string_copy(file->old.rev, NULL_ID);
6391 } else if (!file->status || file == unmerged) {
6392 if (!status_get_diff(file, buf, strlen(buf)))
6393 goto error_out;
6395 buf = io_get(&io, 0, TRUE);
6396 if (!buf)
6397 break;
6399 /* Collapse all modified entries that follow an
6400 * associated unmerged entry. */
6401 if (unmerged == file) {
6402 unmerged->status = 'U';
6403 unmerged = NULL;
6404 } else if (file->status == 'U') {
6405 unmerged = file;
6409 /* Grab the old name for rename/copy. */
6410 if (!*file->old.name &&
6411 (file->status == 'R' || file->status == 'C')) {
6412 string_ncopy(file->old.name, buf, strlen(buf));
6414 buf = io_get(&io, 0, TRUE);
6415 if (!buf)
6416 break;
6419 /* git-ls-files just delivers a NUL separated list of
6420 * file names similar to the second half of the
6421 * git-diff-* output. */
6422 string_ncopy(file->new.name, buf, strlen(buf));
6423 if (!*file->old.name)
6424 string_copy(file->old.name, file->new.name);
6425 file = NULL;
6428 if (io_error(&io)) {
6429 error_out:
6430 io_done(&io);
6431 return FALSE;
6434 if (!view->line[view->lines - 1].data)
6435 add_line_nodata(view, LINE_STAT_NONE);
6437 io_done(&io);
6438 return TRUE;
6441 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
6442 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
6444 static const char *status_list_other_argv[] = {
6445 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
6448 static const char *status_list_no_head_argv[] = {
6449 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
6452 static const char *update_index_argv[] = {
6453 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
6456 /* Restore the previous line number to stay in the context or select a
6457 * line with something that can be updated. */
6458 static void
6459 status_restore(struct view *view)
6461 if (!check_position(&view->prev_pos))
6462 return;
6464 if (view->prev_pos.lineno >= view->lines)
6465 view->prev_pos.lineno = view->lines - 1;
6466 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
6467 view->prev_pos.lineno++;
6468 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
6469 view->prev_pos.lineno--;
6471 /* If the above fails, always skip the "On branch" line. */
6472 if (view->prev_pos.lineno < view->lines)
6473 view->pos.lineno = view->prev_pos.lineno;
6474 else
6475 view->pos.lineno = 1;
6477 if (view->prev_pos.offset > view->pos.lineno)
6478 view->pos.offset = view->pos.lineno;
6479 else if (view->prev_pos.offset < view->lines)
6480 view->pos.offset = view->prev_pos.offset;
6482 clear_position(&view->prev_pos);
6485 static void
6486 status_update_onbranch(void)
6488 static const char *paths[][2] = {
6489 { "rebase-apply/rebasing", "Rebasing" },
6490 { "rebase-apply/applying", "Applying mailbox" },
6491 { "rebase-apply/", "Rebasing mailbox" },
6492 { "rebase-merge/interactive", "Interactive rebase" },
6493 { "rebase-merge/", "Rebase merge" },
6494 { "MERGE_HEAD", "Merging" },
6495 { "BISECT_LOG", "Bisecting" },
6496 { "HEAD", "On branch" },
6498 char buf[SIZEOF_STR];
6499 struct stat stat;
6500 int i;
6502 if (is_initial_commit()) {
6503 string_copy(status_onbranch, "Initial commit");
6504 return;
6507 for (i = 0; i < ARRAY_SIZE(paths); i++) {
6508 char *head = opt_head;
6510 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
6511 lstat(buf, &stat) < 0)
6512 continue;
6514 if (!*opt_head) {
6515 struct io io;
6517 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
6518 io_read_buf(&io, buf, sizeof(buf))) {
6519 head = buf;
6520 if (!prefixcmp(head, "refs/heads/"))
6521 head += STRING_SIZE("refs/heads/");
6525 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
6526 string_copy(status_onbranch, opt_head);
6527 return;
6530 string_copy(status_onbranch, "Not currently on any branch");
6533 /* First parse staged info using git-diff-index(1), then parse unstaged
6534 * info using git-diff-files(1), and finally untracked files using
6535 * git-ls-files(1). */
6536 static bool
6537 status_open(struct view *view, enum open_flags flags)
6539 const char **staged_argv = is_initial_commit() ?
6540 status_list_no_head_argv : status_diff_index_argv;
6541 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
6543 if (opt_is_inside_work_tree == FALSE) {
6544 report("The status view requires a working tree");
6545 return FALSE;
6548 reset_view(view);
6550 add_line_nodata(view, LINE_STAT_HEAD);
6551 status_update_onbranch();
6553 io_run_bg(update_index_argv);
6555 if (!opt_untracked_dirs_content)
6556 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
6558 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
6559 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
6560 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
6561 report("Failed to load status data");
6562 return FALSE;
6565 /* Restore the exact position or use the specialized restore
6566 * mode? */
6567 status_restore(view);
6568 return TRUE;
6571 static bool
6572 status_draw(struct view *view, struct line *line, unsigned int lineno)
6574 struct status *status = line->data;
6575 enum line_type type;
6576 const char *text;
6578 if (!status) {
6579 switch (line->type) {
6580 case LINE_STAT_STAGED:
6581 type = LINE_STAT_SECTION;
6582 text = "Changes to be committed:";
6583 break;
6585 case LINE_STAT_UNSTAGED:
6586 type = LINE_STAT_SECTION;
6587 text = "Changed but not updated:";
6588 break;
6590 case LINE_STAT_UNTRACKED:
6591 type = LINE_STAT_SECTION;
6592 text = "Untracked files:";
6593 break;
6595 case LINE_STAT_NONE:
6596 type = LINE_DEFAULT;
6597 text = " (no files)";
6598 break;
6600 case LINE_STAT_HEAD:
6601 type = LINE_STAT_HEAD;
6602 text = status_onbranch;
6603 break;
6605 default:
6606 return FALSE;
6608 } else {
6609 static char buf[] = { '?', ' ', ' ', ' ', 0 };
6611 buf[0] = status->status;
6612 if (draw_text(view, line->type, buf))
6613 return TRUE;
6614 type = LINE_DEFAULT;
6615 text = status->new.name;
6618 draw_text(view, type, text);
6619 return TRUE;
6622 static enum request
6623 status_enter(struct view *view, struct line *line)
6625 struct status *status = line->data;
6626 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6628 if (line->type == LINE_STAT_NONE ||
6629 (!status && line[1].type == LINE_STAT_NONE)) {
6630 report("No file to diff");
6631 return REQ_NONE;
6634 switch (line->type) {
6635 case LINE_STAT_STAGED:
6636 case LINE_STAT_UNSTAGED:
6637 break;
6639 case LINE_STAT_UNTRACKED:
6640 if (!status) {
6641 report("No file to show");
6642 return REQ_NONE;
6645 if (!suffixcmp(status->new.name, -1, "/")) {
6646 report("Cannot display a directory");
6647 return REQ_NONE;
6649 break;
6651 case LINE_STAT_HEAD:
6652 return REQ_NONE;
6654 default:
6655 die("line type %d not handled in switch", line->type);
6658 if (status) {
6659 stage_status = *status;
6660 } else {
6661 memset(&stage_status, 0, sizeof(stage_status));
6664 stage_line_type = line->type;
6666 open_view(view, REQ_VIEW_STAGE, flags);
6667 return REQ_NONE;
6670 static bool
6671 status_exists(struct view *view, struct status *status, enum line_type type)
6673 unsigned long lineno;
6675 for (lineno = 0; lineno < view->lines; lineno++) {
6676 struct line *line = &view->line[lineno];
6677 struct status *pos = line->data;
6679 if (line->type != type)
6680 continue;
6681 if (!pos && (!status || !status->status) && line[1].data) {
6682 select_view_line(view, lineno);
6683 return TRUE;
6685 if (pos && !strcmp(status->new.name, pos->new.name)) {
6686 select_view_line(view, lineno);
6687 return TRUE;
6691 return FALSE;
6695 static bool
6696 status_update_prepare(struct io *io, enum line_type type)
6698 const char *staged_argv[] = {
6699 "git", "update-index", "-z", "--index-info", NULL
6701 const char *others_argv[] = {
6702 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
6705 switch (type) {
6706 case LINE_STAT_STAGED:
6707 return io_run(io, IO_WR, opt_cdup, opt_env, staged_argv);
6709 case LINE_STAT_UNSTAGED:
6710 case LINE_STAT_UNTRACKED:
6711 return io_run(io, IO_WR, opt_cdup, opt_env, others_argv);
6713 default:
6714 die("line type %d not handled in switch", type);
6715 return FALSE;
6719 static bool
6720 status_update_write(struct io *io, struct status *status, enum line_type type)
6722 switch (type) {
6723 case LINE_STAT_STAGED:
6724 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
6725 status->old.rev, status->old.name, 0);
6727 case LINE_STAT_UNSTAGED:
6728 case LINE_STAT_UNTRACKED:
6729 return io_printf(io, "%s%c", status->new.name, 0);
6731 default:
6732 die("line type %d not handled in switch", type);
6733 return FALSE;
6737 static bool
6738 status_update_file(struct status *status, enum line_type type)
6740 struct io io;
6741 bool result;
6743 if (!status_update_prepare(&io, type))
6744 return FALSE;
6746 result = status_update_write(&io, status, type);
6747 return io_done(&io) && result;
6750 static bool
6751 status_update_files(struct view *view, struct line *line)
6753 char buf[sizeof(view->ref)];
6754 struct io io;
6755 bool result = TRUE;
6756 struct line *pos;
6757 int files = 0;
6758 int file, done;
6759 int cursor_y = -1, cursor_x = -1;
6761 if (!status_update_prepare(&io, line->type))
6762 return FALSE;
6764 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
6765 files++;
6767 string_copy(buf, view->ref);
6768 getsyx(cursor_y, cursor_x);
6769 for (file = 0, done = 5; result && file < files; line++, file++) {
6770 int almost_done = file * 100 / files;
6772 if (almost_done > done) {
6773 done = almost_done;
6774 string_format(view->ref, "updating file %u of %u (%d%% done)",
6775 file, files, done);
6776 update_view_title(view);
6777 setsyx(cursor_y, cursor_x);
6778 doupdate();
6780 result = status_update_write(&io, line->data, line->type);
6782 string_copy(view->ref, buf);
6784 return io_done(&io) && result;
6787 static bool
6788 status_update(struct view *view)
6790 struct line *line = &view->line[view->pos.lineno];
6792 assert(view->lines);
6794 if (!line->data) {
6795 if (status_has_none(view, line)) {
6796 report("Nothing to update");
6797 return FALSE;
6800 if (!status_update_files(view, line + 1)) {
6801 report("Failed to update file status");
6802 return FALSE;
6805 } else if (!status_update_file(line->data, line->type)) {
6806 report("Failed to update file status");
6807 return FALSE;
6810 return TRUE;
6813 static bool
6814 status_revert(struct status *status, enum line_type type, bool has_none)
6816 if (!status || type != LINE_STAT_UNSTAGED) {
6817 if (type == LINE_STAT_STAGED) {
6818 report("Cannot revert changes to staged files");
6819 } else if (type == LINE_STAT_UNTRACKED) {
6820 report("Cannot revert changes to untracked files");
6821 } else if (has_none) {
6822 report("Nothing to revert");
6823 } else {
6824 report("Cannot revert changes to multiple files");
6827 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6828 char mode[10] = "100644";
6829 const char *reset_argv[] = {
6830 "git", "update-index", "--cacheinfo", mode,
6831 status->old.rev, status->old.name, NULL
6833 const char *checkout_argv[] = {
6834 "git", "checkout", "--", status->old.name, NULL
6837 if (status->status == 'U') {
6838 string_format(mode, "%5o", status->old.mode);
6840 if (status->old.mode == 0 && status->new.mode == 0) {
6841 reset_argv[2] = "--force-remove";
6842 reset_argv[3] = status->old.name;
6843 reset_argv[4] = NULL;
6846 if (!io_run_fg(reset_argv, opt_cdup))
6847 return FALSE;
6848 if (status->old.mode == 0 && status->new.mode == 0)
6849 return TRUE;
6852 return io_run_fg(checkout_argv, opt_cdup);
6855 return FALSE;
6858 static enum request
6859 status_request(struct view *view, enum request request, struct line *line)
6861 struct status *status = line->data;
6863 switch (request) {
6864 case REQ_STATUS_UPDATE:
6865 if (!status_update(view))
6866 return REQ_NONE;
6867 break;
6869 case REQ_STATUS_REVERT:
6870 if (!status_revert(status, line->type, status_has_none(view, line)))
6871 return REQ_NONE;
6872 break;
6874 case REQ_STATUS_MERGE:
6875 if (!status || status->status != 'U') {
6876 report("Merging only possible for files with unmerged status ('U').");
6877 return REQ_NONE;
6879 open_mergetool(status->new.name);
6880 break;
6882 case REQ_EDIT:
6883 if (!status)
6884 return request;
6885 if (status->status == 'D') {
6886 report("File has been deleted.");
6887 return REQ_NONE;
6890 open_editor(status->new.name, 0);
6891 break;
6893 case REQ_VIEW_BLAME:
6894 if (status)
6895 opt_ref[0] = 0;
6896 return request;
6898 case REQ_ENTER:
6899 /* After returning the status view has been split to
6900 * show the stage view. No further reloading is
6901 * necessary. */
6902 return status_enter(view, line);
6904 case REQ_REFRESH:
6905 /* Load the current branch information and then the view. */
6906 load_refs();
6907 break;
6909 default:
6910 return request;
6913 refresh_view(view);
6915 return REQ_NONE;
6918 static bool
6919 status_stage_info_(char *buf, size_t bufsize,
6920 enum line_type type, struct status *status)
6922 const char *file = status ? status->new.name : "";
6923 const char *info;
6925 switch (type) {
6926 case LINE_STAT_STAGED:
6927 if (status && status->status)
6928 info = "Staged changes to %s";
6929 else
6930 info = "Staged changes";
6931 break;
6933 case LINE_STAT_UNSTAGED:
6934 if (status && status->status)
6935 info = "Unstaged changes to %s";
6936 else
6937 info = "Unstaged changes";
6938 break;
6940 case LINE_STAT_UNTRACKED:
6941 info = "Untracked file %s";
6942 break;
6944 case LINE_STAT_HEAD:
6945 default:
6946 info = "";
6949 return string_nformat(buf, bufsize, NULL, info, file);
6951 #define status_stage_info(buf, type, status) \
6952 status_stage_info_(buf, sizeof(buf), type, status)
6954 static void
6955 status_select(struct view *view, struct line *line)
6957 struct status *status = line->data;
6958 char file[SIZEOF_STR] = "all files";
6959 const char *text;
6960 const char *key;
6962 if (status && !string_format(file, "'%s'", status->new.name))
6963 return;
6965 if (!status && line[1].type == LINE_STAT_NONE)
6966 line++;
6968 switch (line->type) {
6969 case LINE_STAT_STAGED:
6970 text = "Press %s to unstage %s for commit";
6971 break;
6973 case LINE_STAT_UNSTAGED:
6974 text = "Press %s to stage %s for commit";
6975 break;
6977 case LINE_STAT_UNTRACKED:
6978 text = "Press %s to stage %s for addition";
6979 break;
6981 case LINE_STAT_HEAD:
6982 case LINE_STAT_NONE:
6983 text = "Nothing to update";
6984 break;
6986 default:
6987 die("line type %d not handled in switch", line->type);
6990 if (status && status->status == 'U') {
6991 text = "Press %s to resolve conflict in %s";
6992 key = get_view_key(view, REQ_STATUS_MERGE);
6994 } else {
6995 key = get_view_key(view, REQ_STATUS_UPDATE);
6998 string_format(view->ref, text, key, file);
6999 status_stage_info(ref_status, line->type, status);
7000 if (status)
7001 string_copy(opt_file, status->new.name);
7004 static bool
7005 status_grep(struct view *view, struct line *line)
7007 struct status *status = line->data;
7009 if (status) {
7010 const char buf[2] = { status->status, 0 };
7011 const char *text[] = { status->new.name, buf, NULL };
7013 return grep_text(view, text);
7016 return FALSE;
7019 static struct view_ops status_ops = {
7020 "file",
7021 { "status" },
7022 VIEW_CUSTOM_STATUS | VIEW_SEND_CHILD_ENTER,
7024 status_open,
7025 NULL,
7026 status_draw,
7027 status_request,
7028 status_grep,
7029 status_select,
7033 struct stage_state {
7034 struct diff_state diff;
7035 size_t chunks;
7036 int *chunk;
7039 static bool
7040 stage_diff_write(struct io *io, struct line *line, struct line *end)
7042 while (line < end) {
7043 if (!io_write(io, line->data, strlen(line->data)) ||
7044 !io_write(io, "\n", 1))
7045 return FALSE;
7046 line++;
7047 if (line->type == LINE_DIFF_CHUNK ||
7048 line->type == LINE_DIFF_HEADER)
7049 break;
7052 return TRUE;
7055 static bool
7056 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
7058 const char *apply_argv[SIZEOF_ARG] = {
7059 "git", "apply", "--whitespace=nowarn", NULL
7061 struct line *diff_hdr;
7062 struct io io;
7063 int argc = 3;
7065 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
7066 if (!diff_hdr)
7067 return FALSE;
7069 if (!revert)
7070 apply_argv[argc++] = "--cached";
7071 if (line != NULL)
7072 apply_argv[argc++] = "--unidiff-zero";
7073 if (revert || stage_line_type == LINE_STAT_STAGED)
7074 apply_argv[argc++] = "-R";
7075 apply_argv[argc++] = "-";
7076 apply_argv[argc++] = NULL;
7077 if (!io_run(&io, IO_WR, opt_cdup, opt_env, apply_argv))
7078 return FALSE;
7080 if (line != NULL) {
7081 int lineno = 0;
7082 struct line *context = chunk + 1;
7083 const char *markers[] = {
7084 line->type == LINE_DIFF_DEL ? "" : ",0",
7085 line->type == LINE_DIFF_DEL ? ",0" : "",
7088 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
7090 while (context < line) {
7091 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
7092 break;
7093 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
7094 lineno++;
7096 context++;
7099 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7100 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
7101 lineno, markers[0], lineno, markers[1]) ||
7102 !stage_diff_write(&io, line, line + 1)) {
7103 chunk = NULL;
7105 } else {
7106 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7107 !stage_diff_write(&io, chunk, view->line + view->lines))
7108 chunk = NULL;
7111 io_done(&io);
7113 return chunk ? TRUE : FALSE;
7116 static bool
7117 stage_update(struct view *view, struct line *line, bool single)
7119 struct line *chunk = NULL;
7121 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
7122 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7124 if (chunk) {
7125 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
7126 report("Failed to apply chunk");
7127 return FALSE;
7130 } else if (!stage_status.status) {
7131 view = view->parent;
7133 for (line = view->line; view_has_line(view, line); line++)
7134 if (line->type == stage_line_type)
7135 break;
7137 if (!status_update_files(view, line + 1)) {
7138 report("Failed to update files");
7139 return FALSE;
7142 } else if (!status_update_file(&stage_status, stage_line_type)) {
7143 report("Failed to update file");
7144 return FALSE;
7147 return TRUE;
7150 static bool
7151 stage_revert(struct view *view, struct line *line)
7153 struct line *chunk = NULL;
7155 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
7156 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7158 if (chunk) {
7159 if (!prompt_yesno("Are you sure you want to revert changes?"))
7160 return FALSE;
7162 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
7163 report("Failed to revert chunk");
7164 return FALSE;
7166 return TRUE;
7168 } else {
7169 return status_revert(stage_status.status ? &stage_status : NULL,
7170 stage_line_type, FALSE);
7175 static void
7176 stage_next(struct view *view, struct line *line)
7178 struct stage_state *state = view->private;
7179 int i;
7181 if (!state->chunks) {
7182 for (line = view->line; view_has_line(view, line); line++) {
7183 if (line->type != LINE_DIFF_CHUNK)
7184 continue;
7186 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
7187 report("Allocation failure");
7188 return;
7191 state->chunk[state->chunks++] = line - view->line;
7195 for (i = 0; i < state->chunks; i++) {
7196 if (state->chunk[i] > view->pos.lineno) {
7197 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
7198 report("Chunk %d of %zd", i + 1, state->chunks);
7199 return;
7203 report("No next chunk found");
7206 static enum request
7207 stage_request(struct view *view, enum request request, struct line *line)
7209 switch (request) {
7210 case REQ_STATUS_UPDATE:
7211 if (!stage_update(view, line, FALSE))
7212 return REQ_NONE;
7213 break;
7215 case REQ_STATUS_REVERT:
7216 if (!stage_revert(view, line))
7217 return REQ_NONE;
7218 break;
7220 case REQ_STAGE_UPDATE_LINE:
7221 if (stage_line_type == LINE_STAT_UNTRACKED ||
7222 stage_status.status == 'A') {
7223 report("Staging single lines is not supported for new files");
7224 return REQ_NONE;
7226 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
7227 report("Please select a change to stage");
7228 return REQ_NONE;
7230 if (!stage_update(view, line, TRUE))
7231 return REQ_NONE;
7232 break;
7234 case REQ_STAGE_NEXT:
7235 if (stage_line_type == LINE_STAT_UNTRACKED) {
7236 report("File is untracked; press %s to add",
7237 get_view_key(view, REQ_STATUS_UPDATE));
7238 return REQ_NONE;
7240 stage_next(view, line);
7241 return REQ_NONE;
7243 case REQ_EDIT:
7244 if (!stage_status.new.name[0])
7245 return diff_common_edit(view, request, line);
7247 if (stage_status.status == 'D') {
7248 report("File has been deleted.");
7249 return REQ_NONE;
7252 if (stage_line_type == LINE_STAT_UNTRACKED) {
7253 open_editor(stage_status.new.name, (line - view->line) + 1);
7254 } else {
7255 open_editor(stage_status.new.name, diff_get_lineno(view, line));
7257 break;
7259 case REQ_REFRESH:
7260 /* Reload everything(including current branch information) ... */
7261 load_refs();
7262 break;
7264 case REQ_VIEW_BLAME:
7265 if (stage_status.new.name[0]) {
7266 string_copy(opt_file, stage_status.new.name);
7267 opt_ref[0] = 0;
7269 return request;
7271 case REQ_ENTER:
7272 return diff_common_enter(view, request, line);
7274 case REQ_DIFF_CONTEXT_UP:
7275 case REQ_DIFF_CONTEXT_DOWN:
7276 if (!update_diff_context(request))
7277 return REQ_NONE;
7278 break;
7280 default:
7281 return request;
7284 refresh_view(view->parent);
7286 /* Check whether the staged entry still exists, and close the
7287 * stage view if it doesn't. */
7288 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
7289 status_restore(view->parent);
7290 return REQ_VIEW_CLOSE;
7293 refresh_view(view);
7295 return REQ_NONE;
7298 static bool
7299 stage_open(struct view *view, enum open_flags flags)
7301 static const char *no_head_diff_argv[] = {
7302 GIT_DIFF_STAGED_INITIAL(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7303 stage_status.new.name)
7305 static const char *index_show_argv[] = {
7306 GIT_DIFF_STAGED(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7307 stage_status.old.name, stage_status.new.name)
7309 static const char *files_show_argv[] = {
7310 GIT_DIFF_UNSTAGED(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7311 stage_status.old.name, stage_status.new.name)
7313 /* Diffs for unmerged entries are empty when passing the new
7314 * path, so leave out the new path. */
7315 static const char *files_unmerged_argv[] = {
7316 "git", "diff-files", opt_encoding_arg, "--root", "--patch-with-stat",
7317 opt_diff_context_arg, opt_ignore_space_arg, "--",
7318 stage_status.old.name, NULL
7320 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
7321 const char **argv = NULL;
7323 if (!stage_line_type) {
7324 report("No stage content, press %s to open the status view and choose file",
7325 get_view_key(view, REQ_VIEW_STATUS));
7326 return FALSE;
7329 view->encoding = NULL;
7331 switch (stage_line_type) {
7332 case LINE_STAT_STAGED:
7333 if (is_initial_commit()) {
7334 argv = no_head_diff_argv;
7335 } else {
7336 argv = index_show_argv;
7338 break;
7340 case LINE_STAT_UNSTAGED:
7341 if (stage_status.status != 'U')
7342 argv = files_show_argv;
7343 else
7344 argv = files_unmerged_argv;
7345 break;
7347 case LINE_STAT_UNTRACKED:
7348 argv = file_argv;
7349 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
7350 break;
7352 case LINE_STAT_HEAD:
7353 default:
7354 die("line type %d not handled in switch", stage_line_type);
7357 if (!status_stage_info(view->ref, stage_line_type, &stage_status)
7358 || !argv_copy(&view->argv, argv)) {
7359 report("Failed to open staged view");
7360 return FALSE;
7363 view->vid[0] = 0;
7364 view->dir = opt_cdup;
7365 return begin_update(view, NULL, NULL, flags);
7368 static bool
7369 stage_read(struct view *view, char *data)
7371 struct stage_state *state = view->private;
7373 if (stage_line_type == LINE_STAT_UNTRACKED)
7374 return pager_common_read(view, data, LINE_DEFAULT);
7376 if (data && diff_common_read(view, data, &state->diff))
7377 return TRUE;
7379 return pager_read(view, data);
7382 static struct view_ops stage_ops = {
7383 "line",
7384 { "stage" },
7385 VIEW_DIFF_LIKE,
7386 sizeof(struct stage_state),
7387 stage_open,
7388 stage_read,
7389 diff_common_draw,
7390 stage_request,
7391 pager_grep,
7392 pager_select,
7397 * Revision graph
7400 static const enum line_type graph_colors[] = {
7401 LINE_PALETTE_0,
7402 LINE_PALETTE_1,
7403 LINE_PALETTE_2,
7404 LINE_PALETTE_3,
7405 LINE_PALETTE_4,
7406 LINE_PALETTE_5,
7407 LINE_PALETTE_6,
7410 static enum line_type get_graph_color(struct graph_symbol *symbol)
7412 if (symbol->commit)
7413 return LINE_GRAPH_COMMIT;
7414 assert(symbol->color < ARRAY_SIZE(graph_colors));
7415 return graph_colors[symbol->color];
7418 static bool
7419 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7421 const char *chars = graph_symbol_to_utf8(symbol);
7423 return draw_text(view, color, chars + !!first);
7426 static bool
7427 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7429 const char *chars = graph_symbol_to_ascii(symbol);
7431 return draw_text(view, color, chars + !!first);
7434 static bool
7435 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7437 const chtype *chars = graph_symbol_to_chtype(symbol);
7439 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
7442 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
7444 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
7446 static const draw_graph_fn fns[] = {
7447 draw_graph_ascii,
7448 draw_graph_chtype,
7449 draw_graph_utf8
7451 draw_graph_fn fn = fns[opt_line_graphics];
7452 int i;
7454 for (i = 0; i < canvas->size; i++) {
7455 struct graph_symbol *symbol = &canvas->symbols[i];
7456 enum line_type color = get_graph_color(symbol);
7458 if (fn(view, symbol, color, i == 0))
7459 return TRUE;
7462 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
7466 * Main view backend
7469 struct commit {
7470 char id[SIZEOF_REV]; /* SHA1 ID. */
7471 char title[128]; /* First line of the commit message. */
7472 const struct ident *author; /* Author of the commit. */
7473 struct time time; /* Date from the author ident. */
7474 struct ref_list *refs; /* Repository references. */
7475 struct graph_canvas graph; /* Ancestry chain graphics. */
7478 struct main_state {
7479 struct graph graph;
7480 struct commit *current;
7481 bool in_header;
7482 bool added_changes_commits;
7485 static struct commit *
7486 main_add_commit(struct view *view, enum line_type type, const char *ids,
7487 bool is_boundary, bool custom)
7489 struct main_state *state = view->private;
7490 struct commit *commit;
7492 if (!add_line_alloc(view, &commit, type, 0, custom))
7493 return NULL;
7495 string_copy_rev(commit->id, ids);
7496 commit->refs = get_ref_list(commit->id);
7497 graph_add_commit(&state->graph, &commit->graph, commit->id, ids, is_boundary);
7498 return commit;
7501 bool
7502 main_has_changes(const char *argv[])
7504 struct io io;
7506 if (!io_run(&io, IO_BG, NULL, opt_env, argv, -1))
7507 return FALSE;
7508 io_done(&io);
7509 return io.status == 1;
7512 static void
7513 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
7515 char ids[SIZEOF_STR] = NULL_ID " ";
7516 struct main_state *state = view->private;
7517 struct commit *commit;
7518 struct timeval now;
7519 struct timezone tz;
7521 if (!parent)
7522 return;
7524 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
7526 commit = main_add_commit(view, type, ids, FALSE, TRUE);
7527 if (!commit)
7528 return;
7530 if (!gettimeofday(&now, &tz)) {
7531 commit->time.tz = tz.tz_minuteswest * 60;
7532 commit->time.sec = now.tv_sec - commit->time.tz;
7535 commit->author = &unknown_ident;
7536 string_ncopy(commit->title, title, strlen(title));
7537 graph_render_parents(&state->graph);
7540 static void
7541 main_add_changes_commits(struct view *view, struct main_state *state, const char *parent)
7543 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
7544 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
7545 const char *staged_parent = NULL_ID;
7546 const char *unstaged_parent = parent;
7548 if (!is_head_commit(parent))
7549 return;
7551 state->added_changes_commits = TRUE;
7553 io_run_bg(update_index_argv);
7555 if (!main_has_changes(unstaged_argv)) {
7556 unstaged_parent = NULL;
7557 staged_parent = parent;
7560 if (!main_has_changes(staged_argv)) {
7561 staged_parent = NULL;
7564 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
7565 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
7568 static bool
7569 main_open(struct view *view, enum open_flags flags)
7571 static const char *main_argv[] = {
7572 GIT_MAIN_LOG(opt_encoding_arg, "%(diffargs)", "%(revargs)", "%(fileargs)")
7575 return begin_update(view, NULL, main_argv, flags);
7578 static bool
7579 main_draw(struct view *view, struct line *line, unsigned int lineno)
7581 struct commit *commit = line->data;
7583 if (!commit->author)
7584 return FALSE;
7586 if (draw_lineno(view, lineno))
7587 return TRUE;
7589 if (opt_show_id && draw_id(view, LINE_ID, commit->id))
7590 return TRUE;
7592 if (draw_date(view, &commit->time))
7593 return TRUE;
7595 if (draw_author(view, commit->author))
7596 return TRUE;
7598 if (opt_rev_graph && draw_graph(view, &commit->graph))
7599 return TRUE;
7601 if (draw_refs(view, commit->refs))
7602 return TRUE;
7604 draw_commit_title(view, commit->title, 0);
7605 return TRUE;
7608 /* Reads git log --pretty=raw output and parses it into the commit struct. */
7609 static bool
7610 main_read(struct view *view, char *line)
7612 struct main_state *state = view->private;
7613 struct graph *graph = &state->graph;
7614 enum line_type type;
7615 struct commit *commit = state->current;
7617 if (!line) {
7618 if (!view->lines && !view->prev)
7619 die("No revisions match the given arguments.");
7620 if (view->lines > 0) {
7621 commit = view->line[view->lines - 1].data;
7622 view->line[view->lines - 1].dirty = 1;
7623 if (!commit->author) {
7624 view->lines--;
7625 free(commit);
7629 done_graph(graph);
7630 return TRUE;
7633 type = get_line_type(line);
7634 if (type == LINE_COMMIT) {
7635 bool is_boundary;
7637 state->in_header = TRUE;
7638 line += STRING_SIZE("commit ");
7639 is_boundary = *line == '-';
7640 if (is_boundary || !isalnum(*line))
7641 line++;
7643 if (!state->added_changes_commits && opt_show_changes && opt_is_inside_work_tree)
7644 main_add_changes_commits(view, state, line);
7646 state->current = main_add_commit(view, LINE_MAIN_COMMIT, line, is_boundary, FALSE);
7647 return state->current != NULL;
7650 if (!view->lines || !commit)
7651 return TRUE;
7653 /* Empty line separates the commit header from the log itself. */
7654 if (*line == '\0')
7655 state->in_header = FALSE;
7657 switch (type) {
7658 case LINE_PARENT:
7659 if (!graph->has_parents)
7660 graph_add_parent(graph, line + STRING_SIZE("parent "));
7661 break;
7663 case LINE_AUTHOR:
7664 parse_author_line(line + STRING_SIZE("author "),
7665 &commit->author, &commit->time);
7666 graph_render_parents(graph);
7667 break;
7669 default:
7670 /* Fill in the commit title if it has not already been set. */
7671 if (commit->title[0])
7672 break;
7674 /* Skip lines in the commit header. */
7675 if (state->in_header)
7676 break;
7678 /* Require titles to start with a non-space character at the
7679 * offset used by git log. */
7680 if (strncmp(line, " ", 4))
7681 break;
7682 line += 4;
7683 /* Well, if the title starts with a whitespace character,
7684 * try to be forgiving. Otherwise we end up with no title. */
7685 while (isspace(*line))
7686 line++;
7687 if (*line == '\0')
7688 break;
7689 /* FIXME: More graceful handling of titles; append "..." to
7690 * shortened titles, etc. */
7692 string_expand(commit->title, sizeof(commit->title), line, 1);
7693 view->line[view->lines - 1].dirty = 1;
7696 return TRUE;
7699 static enum request
7700 main_request(struct view *view, enum request request, struct line *line)
7702 enum open_flags flags = (view_is_displayed(view) && request != REQ_VIEW_DIFF)
7703 ? OPEN_SPLIT : OPEN_DEFAULT;
7705 switch (request) {
7706 case REQ_NEXT:
7707 case REQ_PREVIOUS:
7708 if (view_is_displayed(view) && display[0] != view)
7709 return request;
7710 /* Do not pass navigation requests to the branch view
7711 * when the main view is maximized. (GH #38) */
7712 move_view(view, request);
7713 break;
7715 case REQ_VIEW_DIFF:
7716 case REQ_ENTER:
7717 if (view_is_displayed(view) && display[0] != view)
7718 maximize_view(view, TRUE);
7720 if (line->type == LINE_STAT_UNSTAGED
7721 || line->type == LINE_STAT_STAGED) {
7722 struct view *diff = VIEW(REQ_VIEW_DIFF);
7723 const char *diff_staged_argv[] = {
7724 GIT_DIFF_STAGED(opt_encoding_arg,
7725 opt_diff_context_arg,
7726 opt_ignore_space_arg, NULL, NULL)
7728 const char *diff_unstaged_argv[] = {
7729 GIT_DIFF_UNSTAGED(opt_encoding_arg,
7730 opt_diff_context_arg,
7731 opt_ignore_space_arg, NULL, NULL)
7733 const char **diff_argv = line->type == LINE_STAT_STAGED
7734 ? diff_staged_argv : diff_unstaged_argv;
7736 open_argv(view, diff, diff_argv, NULL, flags);
7737 break;
7740 open_view(view, REQ_VIEW_DIFF, flags);
7741 break;
7743 case REQ_REFRESH:
7744 load_refs();
7745 refresh_view(view);
7746 break;
7748 case REQ_JUMP_COMMIT:
7750 int lineno;
7752 for (lineno = 0; lineno < view->lines; lineno++) {
7753 struct commit *commit = view->line[lineno].data;
7755 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
7756 select_view_line(view, lineno);
7757 report_clear();
7758 return REQ_NONE;
7762 report("Unable to find commit '%s'", opt_search);
7763 break;
7765 default:
7766 return request;
7769 return REQ_NONE;
7772 static bool
7773 grep_refs(struct ref_list *list, regex_t *regex)
7775 regmatch_t pmatch;
7776 size_t i;
7778 if (!opt_show_refs || !list)
7779 return FALSE;
7781 for (i = 0; i < list->size; i++) {
7782 if (!regexec(regex, list->refs[i]->name, 1, &pmatch, 0))
7783 return TRUE;
7786 return FALSE;
7789 static bool
7790 main_grep(struct view *view, struct line *line)
7792 struct commit *commit = line->data;
7793 const char *text[] = {
7794 commit->id,
7795 commit->title,
7796 mkauthor(commit->author, opt_author_width, opt_author),
7797 mkdate(&commit->time, opt_date),
7798 NULL
7801 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
7804 static void
7805 main_select(struct view *view, struct line *line)
7807 struct commit *commit = line->data;
7809 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED)
7810 string_copy(view->ref, commit->title);
7811 else
7812 string_copy_rev(view->ref, commit->id);
7813 string_copy_rev(ref_commit, commit->id);
7816 static struct view_ops main_ops = {
7817 "commit",
7818 { "main" },
7819 VIEW_STDIN | VIEW_SEND_CHILD_ENTER | VIEW_FILE_FILTER,
7820 sizeof(struct main_state),
7821 main_open,
7822 main_read,
7823 main_draw,
7824 main_request,
7825 main_grep,
7826 main_select,
7829 static bool
7830 stash_open(struct view *view, enum open_flags flags)
7832 static const char *stash_argv[] = { "git", "stash", "list",
7833 opt_encoding_arg, "--no-color", NULL };
7835 return begin_update(view, NULL, stash_argv, flags | OPEN_RELOAD);
7838 static void
7839 stash_select(struct view *view, struct line *line)
7841 if (line->type == LINE_STASH) {
7842 /* A stash line currently begins with "stash@{x}: ..." */
7843 const char *colon = strchr(line->data, ':');
7844 unsigned int len;
7846 if (!colon)
7847 return;
7849 len = colon - (char *) line->data;
7851 string_ncopy(ref_stash, line->data, len);
7852 string_copy(ref_commit, ref_stash); /* For the diff view */
7853 string_copy(view->ref, ref_stash);
7857 static enum request
7858 stash_request(struct view *view, enum request request, struct line *line)
7860 switch (request) {
7861 case REQ_ENTER:
7862 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
7863 break;
7864 case REQ_REFRESH:
7865 refresh_view(view);
7866 break;
7867 default:
7868 return pager_request(view, request, line);
7871 return REQ_NONE;
7874 static struct view_ops stash_ops = {
7875 "stash",
7876 { "stash" },
7877 VIEW_SEND_CHILD_ENTER,
7879 stash_open,
7880 pager_read,
7881 pager_draw,
7882 stash_request,
7883 pager_grep,
7884 stash_select,
7888 * Status management
7891 /* Whether or not the curses interface has been initialized. */
7892 static bool cursed = FALSE;
7894 /* Terminal hacks and workarounds. */
7895 static bool use_scroll_redrawwin;
7896 static bool use_scroll_status_wclear;
7898 /* The status window is used for polling keystrokes. */
7899 static WINDOW *status_win;
7901 /* Reading from the prompt? */
7902 static bool input_mode = FALSE;
7904 static bool status_empty = FALSE;
7906 /* Update status and title window. */
7907 static void
7908 report(const char *msg, ...)
7910 struct view *view = display[current_view];
7912 if (input_mode)
7913 return;
7915 if (!view) {
7916 char buf[SIZEOF_STR];
7917 int retval;
7919 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
7920 die("%s", buf);
7923 if (!status_empty || *msg) {
7924 va_list args;
7926 va_start(args, msg);
7928 wmove(status_win, 0, 0);
7929 if (view->has_scrolled && use_scroll_status_wclear)
7930 wclear(status_win);
7931 if (*msg) {
7932 vwprintw(status_win, msg, args);
7933 status_empty = FALSE;
7934 } else {
7935 status_empty = TRUE;
7937 wclrtoeol(status_win);
7938 wnoutrefresh(status_win);
7940 va_end(args);
7943 update_view_title(view);
7946 static void
7947 init_display(void)
7949 const char *term;
7950 int x, y;
7952 /* Initialize the curses library */
7953 if (isatty(STDIN_FILENO)) {
7954 cursed = !!initscr();
7955 opt_tty = stdin;
7956 } else {
7957 /* Leave stdin and stdout alone when acting as a pager. */
7958 opt_tty = fopen("/dev/tty", "r+");
7959 if (!opt_tty)
7960 die("Failed to open /dev/tty");
7961 cursed = !!newterm(NULL, opt_tty, opt_tty);
7964 if (!cursed)
7965 die("Failed to initialize curses");
7967 nonl(); /* Disable conversion and detect newlines from input. */
7968 cbreak(); /* Take input chars one at a time, no wait for \n */
7969 noecho(); /* Don't echo input */
7970 leaveok(stdscr, FALSE);
7972 if (has_colors())
7973 init_colors();
7975 getmaxyx(stdscr, y, x);
7976 status_win = newwin(1, x, y - 1, 0);
7977 if (!status_win)
7978 die("Failed to create status window");
7980 /* Enable keyboard mapping */
7981 keypad(status_win, TRUE);
7982 wbkgdset(status_win, get_line_attr(LINE_STATUS));
7984 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
7985 set_tabsize(opt_tab_size);
7986 #else
7987 TABSIZE = opt_tab_size;
7988 #endif
7990 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
7991 if (term && !strcmp(term, "gnome-terminal")) {
7992 /* In the gnome-terminal-emulator, the message from
7993 * scrolling up one line when impossible followed by
7994 * scrolling down one line causes corruption of the
7995 * status line. This is fixed by calling wclear. */
7996 use_scroll_status_wclear = TRUE;
7997 use_scroll_redrawwin = FALSE;
7999 } else if (term && !strcmp(term, "xrvt-xpm")) {
8000 /* No problems with full optimizations in xrvt-(unicode)
8001 * and aterm. */
8002 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
8004 } else {
8005 /* When scrolling in (u)xterm the last line in the
8006 * scrolling direction will update slowly. */
8007 use_scroll_redrawwin = TRUE;
8008 use_scroll_status_wclear = FALSE;
8012 static int
8013 get_input(int prompt_position)
8015 struct view *view;
8016 int i, key, cursor_y, cursor_x;
8018 if (prompt_position)
8019 input_mode = TRUE;
8021 while (TRUE) {
8022 bool loading = FALSE;
8024 foreach_view (view, i) {
8025 update_view(view);
8026 if (view_is_displayed(view) && view->has_scrolled &&
8027 use_scroll_redrawwin)
8028 redrawwin(view->win);
8029 view->has_scrolled = FALSE;
8030 if (view->pipe)
8031 loading = TRUE;
8034 /* Update the cursor position. */
8035 if (prompt_position) {
8036 getbegyx(status_win, cursor_y, cursor_x);
8037 cursor_x = prompt_position;
8038 } else {
8039 view = display[current_view];
8040 getbegyx(view->win, cursor_y, cursor_x);
8041 cursor_x = view->width - 1;
8042 cursor_y += view->pos.lineno - view->pos.offset;
8044 setsyx(cursor_y, cursor_x);
8046 /* Refresh, accept single keystroke of input */
8047 doupdate();
8048 nodelay(status_win, loading);
8049 key = wgetch(status_win);
8051 /* wgetch() with nodelay() enabled returns ERR when
8052 * there's no input. */
8053 if (key == ERR) {
8055 } else if (key == KEY_RESIZE) {
8056 int height, width;
8058 getmaxyx(stdscr, height, width);
8060 wresize(status_win, 1, width);
8061 mvwin(status_win, height - 1, 0);
8062 wnoutrefresh(status_win);
8063 resize_display();
8064 redraw_display(TRUE);
8066 } else {
8067 input_mode = FALSE;
8068 if (key == erasechar())
8069 key = KEY_BACKSPACE;
8070 return key;
8075 static char *
8076 prompt_input(const char *prompt, input_handler handler, void *data)
8078 enum input_status status = INPUT_OK;
8079 static char buf[SIZEOF_STR];
8080 size_t pos = 0;
8082 buf[pos] = 0;
8084 while (status == INPUT_OK || status == INPUT_SKIP) {
8085 int key;
8087 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
8088 wclrtoeol(status_win);
8090 key = get_input(pos + 1);
8091 switch (key) {
8092 case KEY_RETURN:
8093 case KEY_ENTER:
8094 case '\n':
8095 status = pos ? INPUT_STOP : INPUT_CANCEL;
8096 break;
8098 case KEY_BACKSPACE:
8099 if (pos > 0)
8100 buf[--pos] = 0;
8101 else
8102 status = INPUT_CANCEL;
8103 break;
8105 case KEY_ESC:
8106 status = INPUT_CANCEL;
8107 break;
8109 default:
8110 if (pos >= sizeof(buf)) {
8111 report("Input string too long");
8112 return NULL;
8115 status = handler(data, buf, key);
8116 if (status == INPUT_OK)
8117 buf[pos++] = (char) key;
8121 /* Clear the status window */
8122 status_empty = FALSE;
8123 report_clear();
8125 if (status == INPUT_CANCEL)
8126 return NULL;
8128 buf[pos++] = 0;
8130 return buf;
8133 static enum input_status
8134 prompt_yesno_handler(void *data, char *buf, int c)
8136 if (c == 'y' || c == 'Y')
8137 return INPUT_STOP;
8138 if (c == 'n' || c == 'N')
8139 return INPUT_CANCEL;
8140 return INPUT_SKIP;
8143 static bool
8144 prompt_yesno(const char *prompt)
8146 char prompt2[SIZEOF_STR];
8148 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
8149 return FALSE;
8151 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
8154 static enum input_status
8155 read_prompt_handler(void *data, char *buf, int c)
8157 return isprint(c) ? INPUT_OK : INPUT_SKIP;
8160 static char *
8161 read_prompt(const char *prompt)
8163 return prompt_input(prompt, read_prompt_handler, NULL);
8166 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
8168 enum input_status status = INPUT_OK;
8169 int size = 0;
8171 while (items[size].text)
8172 size++;
8174 assert(size > 0);
8176 while (status == INPUT_OK) {
8177 const struct menu_item *item = &items[*selected];
8178 int key;
8179 int i;
8181 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
8182 prompt, *selected + 1, size);
8183 if (item->hotkey)
8184 wprintw(status_win, "[%c] ", (char) item->hotkey);
8185 wprintw(status_win, "%s", item->text);
8186 wclrtoeol(status_win);
8188 key = get_input(COLS - 1);
8189 switch (key) {
8190 case KEY_RETURN:
8191 case KEY_ENTER:
8192 case '\n':
8193 status = INPUT_STOP;
8194 break;
8196 case KEY_LEFT:
8197 case KEY_UP:
8198 *selected = *selected - 1;
8199 if (*selected < 0)
8200 *selected = size - 1;
8201 break;
8203 case KEY_RIGHT:
8204 case KEY_DOWN:
8205 *selected = (*selected + 1) % size;
8206 break;
8208 case KEY_ESC:
8209 status = INPUT_CANCEL;
8210 break;
8212 default:
8213 for (i = 0; items[i].text; i++)
8214 if (items[i].hotkey == key) {
8215 *selected = i;
8216 status = INPUT_STOP;
8217 break;
8222 /* Clear the status window */
8223 status_empty = FALSE;
8224 report_clear();
8226 return status != INPUT_CANCEL;
8230 * Repository properties
8234 static void
8235 set_remote_branch(const char *name, const char *value, size_t valuelen)
8237 if (!strcmp(name, ".remote")) {
8238 string_ncopy(opt_remote, value, valuelen);
8240 } else if (*opt_remote && !strcmp(name, ".merge")) {
8241 size_t from = strlen(opt_remote);
8243 if (!prefixcmp(value, "refs/heads/"))
8244 value += STRING_SIZE("refs/heads/");
8246 if (!string_format_from(opt_remote, &from, "/%s", value))
8247 opt_remote[0] = 0;
8251 static void
8252 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
8254 const char *argv[SIZEOF_ARG] = { name, "=" };
8255 int argc = 1 + (cmd == option_set_command);
8256 enum option_code error;
8258 if (!argv_from_string(argv, &argc, value))
8259 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
8260 else
8261 error = cmd(argc, argv);
8263 if (error != OPT_OK)
8264 warn("Option 'tig.%s': %s", name, option_errors[error]);
8267 static bool
8268 set_environment_variable(const char *name, const char *value)
8270 size_t len = strlen(name) + 1 + strlen(value) + 1;
8271 char *env = malloc(len);
8273 if (env &&
8274 string_nformat(env, len, NULL, "%s=%s", name, value) &&
8275 putenv(env) == 0)
8276 return TRUE;
8277 free(env);
8278 return FALSE;
8281 static void
8282 set_work_tree(const char *value)
8284 char cwd[SIZEOF_STR];
8286 if (!getcwd(cwd, sizeof(cwd)))
8287 die("Failed to get cwd path: %s", strerror(errno));
8288 if (chdir(cwd) < 0)
8289 die("Failed to chdir(%s): %s", cwd, strerror(errno));
8290 if (chdir(opt_git_dir) < 0)
8291 die("Failed to chdir(%s): %s", opt_git_dir, strerror(errno));
8292 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
8293 die("Failed to get git path: %s", strerror(errno));
8294 if (chdir(value) < 0)
8295 die("Failed to chdir(%s): %s", value, strerror(errno));
8296 if (!getcwd(cwd, sizeof(cwd)))
8297 die("Failed to get cwd path: %s", strerror(errno));
8298 if (!set_environment_variable("GIT_WORK_TREE", cwd))
8299 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
8300 if (!set_environment_variable("GIT_DIR", opt_git_dir))
8301 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
8302 opt_is_inside_work_tree = TRUE;
8305 static void
8306 parse_git_color_option(enum line_type type, char *value)
8308 struct line_info *info = &line_info[type];
8309 const char *argv[SIZEOF_ARG];
8310 int argc = 0;
8311 bool first_color = TRUE;
8312 int i;
8314 if (!argv_from_string(argv, &argc, value))
8315 return;
8317 info->fg = COLOR_DEFAULT;
8318 info->bg = COLOR_DEFAULT;
8319 info->attr = 0;
8321 for (i = 0; i < argc; i++) {
8322 int attr = 0;
8324 if (set_attribute(&attr, argv[i])) {
8325 info->attr |= attr;
8327 } else if (set_color(&attr, argv[i])) {
8328 if (first_color)
8329 info->fg = attr;
8330 else
8331 info->bg = attr;
8332 first_color = FALSE;
8337 static void
8338 set_git_color_option(const char *name, char *value)
8340 static const struct enum_map color_option_map[] = {
8341 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
8342 ENUM_MAP("branch.local", LINE_MAIN_REF),
8343 ENUM_MAP("branch.plain", LINE_MAIN_REF),
8344 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
8346 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
8347 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
8348 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
8349 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
8350 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
8351 ENUM_MAP("diff.old", LINE_DIFF_DEL),
8352 ENUM_MAP("diff.new", LINE_DIFF_ADD),
8354 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
8356 ENUM_MAP("status.branch", LINE_STAT_HEAD),
8357 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
8358 ENUM_MAP("status.added", LINE_STAT_STAGED),
8359 ENUM_MAP("status.updated", LINE_STAT_STAGED),
8360 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
8361 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
8364 int type = LINE_NONE;
8366 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
8367 parse_git_color_option(type, value);
8371 static void
8372 set_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
8374 if (parse_encoding(encoding_ref, arg, priority) == OPT_OK)
8375 opt_encoding_arg[0] = 0;
8378 static int
8379 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8381 if (!strcmp(name, "i18n.commitencoding"))
8382 set_encoding(&opt_encoding, value, FALSE);
8384 else if (!strcmp(name, "gui.encoding"))
8385 set_encoding(&opt_encoding, value, TRUE);
8387 else if (!strcmp(name, "core.editor"))
8388 string_ncopy(opt_editor, value, valuelen);
8390 else if (!strcmp(name, "core.worktree"))
8391 set_work_tree(value);
8393 else if (!strcmp(name, "core.abbrev"))
8394 parse_id(&opt_id_cols, value);
8396 else if (!prefixcmp(name, "tig.color."))
8397 set_repo_config_option(name + 10, value, option_color_command);
8399 else if (!prefixcmp(name, "tig.bind."))
8400 set_repo_config_option(name + 9, value, option_bind_command);
8402 else if (!prefixcmp(name, "tig."))
8403 set_repo_config_option(name + 4, value, option_set_command);
8405 else if (!prefixcmp(name, "color."))
8406 set_git_color_option(name + STRING_SIZE("color."), value);
8408 else if (*opt_head && !prefixcmp(name, "branch.") &&
8409 !strncmp(name + 7, opt_head, strlen(opt_head)))
8410 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
8412 return OK;
8415 static int
8416 load_git_config(void)
8418 const char *config_list_argv[] = { "git", "config", "--list", NULL };
8420 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
8423 #define REPO_INFO_GIT_DIR "--git-dir"
8424 #define REPO_INFO_WORK_TREE "--is-inside-work-tree"
8425 #define REPO_INFO_SHOW_CDUP "--show-cdup"
8426 #define REPO_INFO_SHOW_PREFIX "--show-prefix"
8428 struct repo_info_state {
8429 const char **argv;
8432 static int
8433 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8435 struct repo_info_state *state = data;
8436 const char *arg = *state->argv ? *state->argv++ : "";
8438 if (!strcmp(arg, REPO_INFO_GIT_DIR)) {
8439 string_ncopy(opt_git_dir, name, namelen);
8441 } else if (!strcmp(arg, REPO_INFO_WORK_TREE)) {
8442 /* This can be 3 different values depending on the
8443 * version of git being used. If git-rev-parse does not
8444 * understand --is-inside-work-tree it will simply echo
8445 * the option else either "true" or "false" is printed.
8446 * Default to true for the unknown case. */
8447 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
8449 } else if (!strcmp(arg, REPO_INFO_SHOW_CDUP)) {
8450 string_ncopy(opt_cdup, name, namelen);
8452 } else if (!strcmp(arg, REPO_INFO_SHOW_PREFIX)) {
8453 string_ncopy(opt_prefix, name, namelen);
8456 return OK;
8459 static int
8460 load_repo_info(void)
8462 const char *rev_parse_argv[] = {
8463 "git", "rev-parse", REPO_INFO_GIT_DIR, REPO_INFO_WORK_TREE,
8464 REPO_INFO_SHOW_CDUP, REPO_INFO_SHOW_PREFIX, NULL
8466 struct repo_info_state state = { rev_parse_argv + 2};
8468 return io_run_load(rev_parse_argv, "=", read_repo_info, &state);
8473 * Main
8476 static const char usage[] =
8477 "tig " TIG_VERSION " (" __DATE__ ")\n"
8478 "\n"
8479 "Usage: tig [options] [revs] [--] [paths]\n"
8480 " or: tig log [options] [revs] [--] [paths]\n"
8481 " or: tig show [options] [revs] [--] [paths]\n"
8482 " or: tig blame [options] [rev] [--] path\n"
8483 " or: tig stash\n"
8484 " or: tig status\n"
8485 " or: tig < [git command output]\n"
8486 "\n"
8487 "Options:\n"
8488 " +<number> Select line <number> in the first view\n"
8489 " -v, --version Show version and exit\n"
8490 " -h, --help Show help message and exit";
8492 static void TIG_NORETURN
8493 quit(int sig)
8495 if (sig)
8496 signal(sig, SIG_DFL);
8498 /* XXX: Restore tty modes and let the OS cleanup the rest! */
8499 if (cursed)
8500 endwin();
8501 exit(0);
8504 static void TIG_NORETURN
8505 die(const char *err, ...)
8507 va_list args;
8509 endwin();
8511 va_start(args, err);
8512 fputs("tig: ", stderr);
8513 vfprintf(stderr, err, args);
8514 fputs("\n", stderr);
8515 va_end(args);
8517 exit(1);
8520 static void
8521 warn(const char *msg, ...)
8523 va_list args;
8525 va_start(args, msg);
8526 fputs("tig warning: ", stderr);
8527 vfprintf(stderr, msg, args);
8528 fputs("\n", stderr);
8529 va_end(args);
8532 static int
8533 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8535 const char ***filter_args = data;
8537 return argv_append(filter_args, name) ? OK : ERR;
8540 static void
8541 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
8543 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
8544 const char **all_argv = NULL;
8546 if (!argv_append_array(&all_argv, rev_parse_argv) ||
8547 !argv_append_array(&all_argv, argv) ||
8548 io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
8549 die("Failed to split arguments");
8550 argv_free(all_argv);
8551 free(all_argv);
8554 static bool
8555 is_rev_flag(const char *flag)
8557 static const char *rev_flags[] = { GIT_REV_FLAGS };
8558 int i;
8560 for (i = 0; i < ARRAY_SIZE(rev_flags); i++)
8561 if (!strcmp(flag, rev_flags[i]))
8562 return TRUE;
8564 return FALSE;
8567 static void
8568 filter_options(const char *argv[], bool blame)
8570 const char **flags = NULL;
8572 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
8573 filter_rev_parse(&flags, "--flags", "--no-revs", argv);
8575 if (flags) {
8576 int next, flags_pos;
8578 for (next = flags_pos = 0; flags && flags[next]; next++) {
8579 const char *flag = flags[next];
8581 if (is_rev_flag(flag))
8582 argv_append(&opt_rev_argv, flag);
8583 else
8584 flags[flags_pos++] = flag;
8587 flags[flags_pos] = NULL;
8589 if (blame)
8590 opt_blame_argv = flags;
8591 else
8592 opt_diff_argv = flags;
8595 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
8598 static enum request
8599 parse_options(int argc, const char *argv[])
8601 enum request request;
8602 const char *subcommand;
8603 bool seen_dashdash = FALSE;
8604 const char **filter_argv = NULL;
8605 int i;
8607 opt_stdin = !isatty(STDIN_FILENO);
8608 request = opt_stdin ? REQ_VIEW_PAGER : REQ_VIEW_MAIN;
8610 if (argc <= 1)
8611 return request;
8613 subcommand = argv[1];
8614 if (!strcmp(subcommand, "status")) {
8615 request = REQ_VIEW_STATUS;
8617 } else if (!strcmp(subcommand, "blame")) {
8618 request = REQ_VIEW_BLAME;
8620 } else if (!strcmp(subcommand, "show")) {
8621 request = REQ_VIEW_DIFF;
8623 } else if (!strcmp(subcommand, "log")) {
8624 request = REQ_VIEW_LOG;
8626 } else if (!strcmp(subcommand, "stash")) {
8627 request = REQ_VIEW_STASH;
8629 } else {
8630 subcommand = NULL;
8633 for (i = 1 + !!subcommand; i < argc; i++) {
8634 const char *opt = argv[i];
8636 // stop parsing our options after -- and let rev-parse handle the rest
8637 if (!seen_dashdash) {
8638 if (!strcmp(opt, "--")) {
8639 seen_dashdash = TRUE;
8640 continue;
8642 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
8643 printf("tig version %s\n", TIG_VERSION);
8644 quit(0);
8646 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
8647 printf("%s\n", usage);
8648 quit(0);
8650 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
8651 opt_lineno = atoi(opt + 1);
8652 continue;
8657 if (!argv_append(&filter_argv, opt))
8658 die("command too long");
8661 if (filter_argv)
8662 filter_options(filter_argv, request == REQ_VIEW_BLAME);
8664 /* Finish validating and setting up blame options */
8665 if (request == REQ_VIEW_BLAME) {
8666 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
8667 die("invalid number of options to blame\n\n%s", usage);
8669 if (opt_rev_argv) {
8670 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
8673 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
8675 } else if (request == REQ_VIEW_PAGER) {
8676 for (i = 0; opt_rev_argv && opt_rev_argv[i]; i++) {
8677 if (!strcmp("--stdin", opt_rev_argv[i])) {
8678 request = REQ_VIEW_MAIN;
8679 break;
8684 return request;
8687 static enum request
8688 run_prompt_command(struct view *view, char *cmd) {
8689 enum request request;
8691 if (cmd && string_isnumber(cmd)) {
8692 int lineno = view->pos.lineno + 1;
8694 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
8695 select_view_line(view, lineno - 1);
8696 report_clear();
8697 } else {
8698 report("Unable to parse '%s' as a line number", cmd);
8700 } else if (cmd && iscommit(cmd)) {
8701 string_ncopy(opt_search, cmd, strlen(cmd));
8703 request = view_request(view, REQ_JUMP_COMMIT);
8704 if (request == REQ_JUMP_COMMIT) {
8705 report("Jumping to commits is not supported by the '%s' view", view->name);
8708 } else if (cmd && strlen(cmd) == 1) {
8709 request = get_keybinding(&view->ops->keymap, cmd[0]);
8710 return request;
8712 } else if (cmd && cmd[0] == '!') {
8713 struct view *next = VIEW(REQ_VIEW_PAGER);
8714 const char *argv[SIZEOF_ARG];
8715 int argc = 0;
8717 cmd++;
8718 /* When running random commands, initially show the
8719 * command in the title. However, it maybe later be
8720 * overwritten if a commit line is selected. */
8721 string_ncopy(next->ref, cmd, strlen(cmd));
8723 if (!argv_from_string(argv, &argc, cmd)) {
8724 report("Too many arguments");
8725 } else if (!format_argv(view, &next->argv, argv, FALSE, TRUE)) {
8726 report("Argument formatting failed");
8727 } else {
8728 next->dir = NULL;
8729 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
8732 } else if (cmd) {
8733 request = get_request(cmd);
8734 if (request != REQ_UNKNOWN)
8735 return request;
8737 char *args = strchr(cmd, ' ');
8738 if (args) {
8739 *args++ = 0;
8740 if (set_option(cmd, args) == OPT_OK) {
8741 request = !view->unrefreshable ? REQ_REFRESH : REQ_SCREEN_REDRAW;
8742 if (!strcmp(cmd, "color"))
8743 init_colors();
8746 return request;
8748 return REQ_NONE;
8752 main(int argc, const char *argv[])
8754 const char *codeset = ENCODING_UTF8;
8755 enum request request = parse_options(argc, argv);
8756 struct view *view;
8757 int i;
8759 signal(SIGINT, quit);
8760 signal(SIGQUIT, quit);
8761 signal(SIGPIPE, SIG_IGN);
8763 if (setlocale(LC_ALL, "")) {
8764 codeset = nl_langinfo(CODESET);
8767 foreach_view(view, i) {
8768 add_keymap(&view->ops->keymap);
8771 if (load_repo_info() == ERR)
8772 die("Failed to load repo info.");
8774 if (load_options() == ERR)
8775 die("Failed to load user config.");
8777 if (load_git_config() == ERR)
8778 die("Failed to load repo config.");
8780 /* Require a git repository unless when running in pager mode. */
8781 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
8782 die("Not a git repository");
8784 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
8785 char translit[SIZEOF_STR];
8787 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
8788 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
8789 else
8790 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
8791 if (opt_iconv_out == ICONV_NONE)
8792 die("Failed to initialize character set conversion");
8795 if (load_refs() == ERR)
8796 die("Failed to load refs.");
8798 init_display();
8800 while (view_driver(display[current_view], request)) {
8801 int key = get_input(0);
8803 if (key == KEY_ESC)
8804 key = get_input(0) + 0x80;
8806 view = display[current_view];
8807 request = get_keybinding(&view->ops->keymap, key);
8809 /* Some low-level request handling. This keeps access to
8810 * status_win restricted. */
8811 switch (request) {
8812 case REQ_NONE:
8813 report("Unknown key, press %s for help",
8814 get_view_key(view, REQ_VIEW_HELP));
8815 break;
8816 case REQ_PROMPT:
8818 char *cmd = read_prompt(":");
8819 request = run_prompt_command(view, cmd);
8820 break;
8822 case REQ_SEARCH:
8823 case REQ_SEARCH_BACK:
8825 const char *prompt = request == REQ_SEARCH ? "/" : "?";
8826 char *search = read_prompt(prompt);
8828 if (search)
8829 string_ncopy(opt_search, search, strlen(search));
8830 else if (*opt_search)
8831 request = request == REQ_SEARCH ?
8832 REQ_FIND_NEXT :
8833 REQ_FIND_PREV;
8834 else
8835 request = REQ_NONE;
8836 break;
8838 default:
8839 break;
8843 quit(0);
8845 return 0;
8848 /* vim: set ts=8 sw=8 noexpandtab: */