Fix regression causing incorect coloring of the commit title
[tig.git] / tig.c
blob3991207d3bfaf11e1cdb9185e009d7447f9562cb
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", "")
26 enum input_status {
27 INPUT_OK,
28 INPUT_SKIP,
29 INPUT_STOP,
30 INPUT_CANCEL
33 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
35 static char *prompt_input(const char *prompt, input_handler handler, void *data);
36 static bool prompt_yesno(const char *prompt);
37 static char *read_prompt(const char *prompt);
39 struct menu_item {
40 int hotkey;
41 const char *text;
42 void *data;
45 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
47 #define GRAPHIC_ENUM(_) \
48 _(GRAPHIC, ASCII), \
49 _(GRAPHIC, DEFAULT), \
50 _(GRAPHIC, UTF_8)
52 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
54 #define DATE_ENUM(_) \
55 _(DATE, NO), \
56 _(DATE, DEFAULT), \
57 _(DATE, LOCAL), \
58 _(DATE, RELATIVE), \
59 _(DATE, SHORT)
61 DEFINE_ENUM(date, DATE_ENUM);
63 struct time {
64 time_t sec;
65 int tz;
68 static inline int timecmp(const struct time *t1, const struct time *t2)
70 return t1->sec - t2->sec;
73 static const char *
74 mkdate(const struct time *time, enum date date)
76 static char buf[DATE_WIDTH + 1];
77 static const struct enum_map reldate[] = {
78 { "second", 1, 60 * 2 },
79 { "minute", 60, 60 * 60 * 2 },
80 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
81 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
82 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
83 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 365 },
84 { "year", 60 * 60 * 24 * 365, 0 },
86 struct tm tm;
88 if (!date || !time || !time->sec)
89 return "";
91 if (date == DATE_RELATIVE) {
92 struct timeval now;
93 time_t date = time->sec + time->tz;
94 time_t seconds;
95 int i;
97 gettimeofday(&now, NULL);
98 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
99 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
100 if (seconds >= reldate[i].value && reldate[i].value)
101 continue;
103 seconds /= reldate[i].namelen;
104 if (!string_format(buf, "%ld %s%s %s",
105 seconds, reldate[i].name,
106 seconds > 1 ? "s" : "",
107 now.tv_sec >= date ? "ago" : "ahead"))
108 break;
109 return buf;
113 if (date == DATE_LOCAL) {
114 time_t date = time->sec + time->tz;
115 localtime_r(&date, &tm);
117 else {
118 gmtime_r(&time->sec, &tm);
120 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
124 #define AUTHOR_ENUM(_) \
125 _(AUTHOR, NO), \
126 _(AUTHOR, FULL), \
127 _(AUTHOR, ABBREVIATED), \
128 _(AUTHOR, EMAIL), \
129 _(AUTHOR, EMAIL_USER)
131 DEFINE_ENUM(author, AUTHOR_ENUM);
133 struct ident {
134 const char *name;
135 const char *email;
138 static const struct ident unknown_ident = { "Unknown", "unknown@localhost" };
140 static inline int
141 ident_compare(const struct ident *i1, const struct ident *i2)
143 if (!i1 || !i2)
144 return (!!i1) - (!!i2);
145 if (!i1->name || !i2->name)
146 return (!!i1->name) - (!!i2->name);
147 return strcmp(i1->name, i2->name);
150 static const char *
151 get_author_initials(const char *author)
153 static char initials[AUTHOR_WIDTH * 6 + 1];
154 size_t pos = 0;
155 const char *end = strchr(author, '\0');
157 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
159 memset(initials, 0, sizeof(initials));
160 while (author < end) {
161 unsigned char bytes;
162 size_t i;
164 while (author < end && is_initial_sep(*author))
165 author++;
167 bytes = utf8_char_length(author, end);
168 if (bytes >= sizeof(initials) - 1 - pos)
169 break;
170 while (bytes--) {
171 initials[pos++] = *author++;
174 i = pos;
175 while (author < end && !is_initial_sep(*author)) {
176 bytes = utf8_char_length(author, end);
177 if (bytes >= sizeof(initials) - 1 - i) {
178 while (author < end && !is_initial_sep(*author))
179 author++;
180 break;
182 while (bytes--) {
183 initials[i++] = *author++;
187 initials[i++] = 0;
190 return initials;
193 static const char *
194 get_email_user(const char *email)
196 static char user[AUTHOR_WIDTH * 6 + 1];
197 const char *end = strchr(email, '@');
198 int length = end ? end - email : strlen(email);
200 string_format(user, "%.*s%c", length, email, 0);
201 return user;
204 #define author_trim(cols) (cols == 0 || cols > 10)
206 static const char *
207 mkauthor(const struct ident *ident, int cols, enum author author)
209 bool trim = author_trim(cols);
210 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
212 if (author == AUTHOR_NO || !ident)
213 return "";
214 if (author == AUTHOR_EMAIL && ident->email)
215 return ident->email;
216 if (author == AUTHOR_EMAIL_USER && ident->email)
217 return get_email_user(ident->email);
218 if (abbreviate && ident->name)
219 return get_author_initials(ident->name);
220 return ident->name;
223 static const char *
224 mkmode(mode_t mode)
226 if (S_ISDIR(mode))
227 return "drwxr-xr-x";
228 else if (S_ISLNK(mode))
229 return "lrwxrwxrwx";
230 else if (S_ISGITLINK(mode))
231 return "m---------";
232 else if (S_ISREG(mode) && mode & S_IXUSR)
233 return "-rwxr-xr-x";
234 else if (S_ISREG(mode))
235 return "-rw-r--r--";
236 else
237 return "----------";
240 #define FILENAME_ENUM(_) \
241 _(FILENAME, NO), \
242 _(FILENAME, ALWAYS), \
243 _(FILENAME, AUTO)
245 DEFINE_ENUM(filename, FILENAME_ENUM);
247 #define IGNORE_SPACE_ENUM(_) \
248 _(IGNORE_SPACE, NO), \
249 _(IGNORE_SPACE, ALL), \
250 _(IGNORE_SPACE, SOME), \
251 _(IGNORE_SPACE, AT_EOL)
253 DEFINE_ENUM(ignore_space, IGNORE_SPACE_ENUM);
255 #define COMMIT_ORDER_ENUM(_) \
256 _(COMMIT_ORDER, DEFAULT), \
257 _(COMMIT_ORDER, TOPO), \
258 _(COMMIT_ORDER, DATE), \
259 _(COMMIT_ORDER, REVERSE)
261 DEFINE_ENUM(commit_order, COMMIT_ORDER_ENUM);
263 #define VIEW_INFO(_) \
264 _(MAIN, main, ref_head), \
265 _(DIFF, diff, ref_commit), \
266 _(LOG, log, ref_head), \
267 _(TREE, tree, ref_commit), \
268 _(BLOB, blob, ref_blob), \
269 _(BLAME, blame, ref_commit), \
270 _(BRANCH, branch, ref_head), \
271 _(HELP, help, ""), \
272 _(PAGER, pager, ""), \
273 _(STATUS, status, "status"), \
274 _(STAGE, stage, ref_status)
276 static struct encoding *
277 get_path_encoding(const char *path, struct encoding *default_encoding)
279 const char *check_attr_argv[] = {
280 "git", "check-attr", "encoding", "--", path, NULL
282 char buf[SIZEOF_STR];
283 char *encoding;
285 /* <path>: encoding: <encoding> */
287 if (!*path || !io_run_buf(check_attr_argv, buf, sizeof(buf))
288 || !(encoding = strstr(buf, ENCODING_SEP)))
289 return default_encoding;
291 encoding += STRING_SIZE(ENCODING_SEP);
292 if (!strcmp(encoding, ENCODING_UTF8)
293 || !strcmp(encoding, "unspecified")
294 || !strcmp(encoding, "set"))
295 return default_encoding;
297 return encoding_open(encoding);
301 * User requests
304 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
306 #define REQ_INFO \
307 REQ_GROUP("View switching") \
308 VIEW_INFO(VIEW_REQ), \
310 REQ_GROUP("View manipulation") \
311 REQ_(ENTER, "Enter current line and scroll"), \
312 REQ_(NEXT, "Move to next"), \
313 REQ_(PREVIOUS, "Move to previous"), \
314 REQ_(PARENT, "Move to parent"), \
315 REQ_(VIEW_NEXT, "Move focus to next view"), \
316 REQ_(REFRESH, "Reload and refresh"), \
317 REQ_(MAXIMIZE, "Maximize the current view"), \
318 REQ_(VIEW_CLOSE, "Close the current view"), \
319 REQ_(QUIT, "Close all views and quit"), \
321 REQ_GROUP("View specific requests") \
322 REQ_(STATUS_UPDATE, "Update file status"), \
323 REQ_(STATUS_REVERT, "Revert file changes"), \
324 REQ_(STATUS_MERGE, "Merge file using external tool"), \
325 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
326 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
327 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
328 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
330 REQ_GROUP("Cursor navigation") \
331 REQ_(MOVE_UP, "Move cursor one line up"), \
332 REQ_(MOVE_DOWN, "Move cursor one line down"), \
333 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
334 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
335 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
336 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
338 REQ_GROUP("Scrolling") \
339 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
340 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
341 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
342 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
343 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
344 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
345 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
347 REQ_GROUP("Searching") \
348 REQ_(SEARCH, "Search the view"), \
349 REQ_(SEARCH_BACK, "Search backwards in the view"), \
350 REQ_(FIND_NEXT, "Find next search match"), \
351 REQ_(FIND_PREV, "Find previous search match"), \
353 REQ_GROUP("Option manipulation") \
354 REQ_(OPTIONS, "Open option menu"), \
355 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
356 REQ_(TOGGLE_DATE, "Toggle date display"), \
357 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
358 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
359 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
360 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
361 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
362 REQ_(TOGGLE_CHANGES, "Toggle local changes display in the main view"), \
363 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
364 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
365 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
366 REQ_(TOGGLE_COMMIT_ORDER, "Toggle commit ordering"), \
367 REQ_(TOGGLE_ID, "Toggle commit ID display"), \
368 REQ_(TOGGLE_FILES, "Toggle file filtering"), \
369 REQ_(TOGGLE_TITLE_OVERFLOW, "Toggle highlighting of commit title overflow"), \
371 REQ_GROUP("Misc") \
372 REQ_(PROMPT, "Bring up the prompt"), \
373 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
374 REQ_(SHOW_VERSION, "Show version information"), \
375 REQ_(STOP_LOADING, "Stop all loading views"), \
376 REQ_(EDIT, "Open in editor"), \
377 REQ_(NONE, "Do nothing")
380 /* User action requests. */
381 enum request {
382 #define REQ_GROUP(help)
383 #define REQ_(req, help) REQ_##req
385 /* Offset all requests to avoid conflicts with ncurses getch values. */
386 REQ_UNKNOWN = KEY_MAX + 1,
387 REQ_OFFSET,
388 REQ_INFO,
390 /* Internal requests. */
391 REQ_JUMP_COMMIT,
393 #undef REQ_GROUP
394 #undef REQ_
397 struct request_info {
398 enum request request;
399 const char *name;
400 int namelen;
401 const char *help;
404 static const struct request_info req_info[] = {
405 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
406 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
407 REQ_INFO
408 #undef REQ_GROUP
409 #undef REQ_
412 static enum request
413 get_request(const char *name)
415 int namelen = strlen(name);
416 int i;
418 for (i = 0; i < ARRAY_SIZE(req_info); i++)
419 if (enum_equals(req_info[i], name, namelen))
420 return req_info[i].request;
422 return REQ_UNKNOWN;
427 * Options
430 /* Option and state variables. */
431 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
432 static enum date opt_date = DATE_DEFAULT;
433 static enum author opt_author = AUTHOR_FULL;
434 static enum filename opt_filename = FILENAME_AUTO;
435 static bool opt_rev_graph = TRUE;
436 static bool opt_line_number = FALSE;
437 static bool opt_show_refs = TRUE;
438 static bool opt_show_changes = TRUE;
439 static bool opt_untracked_dirs_content = TRUE;
440 static bool opt_read_git_colors = TRUE;
441 static bool opt_wrap_lines = FALSE;
442 static bool opt_ignore_case = FALSE;
443 static bool opt_stdin = FALSE;
444 static bool opt_focus_child = TRUE;
445 static int opt_diff_context = 3;
446 static char opt_diff_context_arg[9] = "";
447 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
448 static char opt_ignore_space_arg[22] = "";
449 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
450 static char opt_commit_order_arg[22] = "";
451 static bool opt_notes = TRUE;
452 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
453 static int opt_num_interval = 5;
454 static double opt_hscroll = 0.50;
455 static double opt_scale_split_view = 2.0 / 3.0;
456 static double opt_scale_vsplit_view = 0.5;
457 static bool opt_vsplit = FALSE;
458 static int opt_tab_size = 8;
459 static int opt_author_width = AUTHOR_WIDTH;
460 static int opt_filename_width = FILENAME_WIDTH;
461 static char opt_path[SIZEOF_STR] = "";
462 static char opt_file[SIZEOF_STR] = "";
463 static char opt_ref[SIZEOF_REF] = "";
464 static unsigned long opt_goto_line = 0;
465 static char opt_head[SIZEOF_REF] = "";
466 static char opt_remote[SIZEOF_REF] = "";
467 static struct encoding *opt_encoding = NULL;
468 static char opt_encoding_arg[SIZEOF_STR] = ENCODING_ARG;
469 static iconv_t opt_iconv_out = ICONV_NONE;
470 static char opt_search[SIZEOF_STR] = "";
471 static char opt_cdup[SIZEOF_STR] = "";
472 static char opt_prefix[SIZEOF_STR] = "";
473 static char opt_git_dir[SIZEOF_STR] = "";
474 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
475 static char opt_editor[SIZEOF_STR] = "";
476 static bool opt_editor_lineno = TRUE;
477 static FILE *opt_tty = NULL;
478 static const char **opt_diff_argv = NULL;
479 static const char **opt_rev_argv = NULL;
480 static const char **opt_file_argv = NULL;
481 static const char **opt_blame_argv = NULL;
482 static int opt_lineno = 0;
483 static bool opt_show_id = FALSE;
484 static int opt_id_cols = ID_WIDTH;
485 static bool opt_file_filter = TRUE;
486 static bool opt_show_title_overflow = FALSE;
487 static int opt_title_overflow = 50;
489 #define is_initial_commit() (!get_ref_head())
490 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strncmp(rev, get_ref_head()->id, SIZEOF_REV - 1)))
491 #define load_refs() reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head))
493 static inline void
494 update_diff_context_arg(int diff_context)
496 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
497 string_ncopy(opt_diff_context_arg, "-U3", 3);
500 static inline void
501 update_ignore_space_arg()
503 if (opt_ignore_space == IGNORE_SPACE_ALL) {
504 string_copy(opt_ignore_space_arg, "--ignore-all-space");
505 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
506 string_copy(opt_ignore_space_arg, "--ignore-space-change");
507 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
508 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
509 } else {
510 string_copy(opt_ignore_space_arg, "");
514 static inline void
515 update_commit_order_arg()
517 if (opt_commit_order == COMMIT_ORDER_TOPO) {
518 string_copy(opt_commit_order_arg, "--topo-order");
519 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
520 string_copy(opt_commit_order_arg, "--date-order");
521 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
522 string_copy(opt_commit_order_arg, "--reverse");
523 } else {
524 string_copy(opt_commit_order_arg, "");
528 static inline void
529 update_notes_arg()
531 if (opt_notes) {
532 string_copy(opt_notes_arg, "--show-notes");
533 } else {
534 /* Notes are disabled by default when passing --pretty args. */
535 string_copy(opt_notes_arg, "");
540 * Line-oriented content detection.
543 #define LINE_INFO \
544 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
545 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
546 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
547 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
548 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
549 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
550 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
551 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
552 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
553 LINE(DIFF_DELETED_FILE_MODE, \
554 "deleted file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
555 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
556 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
557 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
558 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
559 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
560 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
561 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
562 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
563 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
564 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
565 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
566 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
567 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
568 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
569 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
570 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
571 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
572 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
573 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
574 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
575 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
576 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
577 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
578 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
579 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
580 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
581 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
582 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
583 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
584 LINE(ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
585 LINE(OVERFLOW, "", COLOR_RED, COLOR_DEFAULT, 0), \
586 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
587 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
588 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
589 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
590 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
591 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
592 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
593 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
594 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
595 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
596 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
597 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
598 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
599 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
600 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
601 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
602 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
603 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
604 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
605 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
606 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
607 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
608 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
609 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
610 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
611 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
612 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
613 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
614 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
615 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
616 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
617 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
618 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
620 enum line_type {
621 #define LINE(type, line, fg, bg, attr) \
622 LINE_##type
623 LINE_INFO,
624 LINE_NONE
625 #undef LINE
628 struct line_info {
629 const char *name; /* Option name. */
630 int namelen; /* Size of option name. */
631 const char *line; /* The start of line to match. */
632 int linelen; /* Size of string to match. */
633 int fg, bg, attr; /* Color and text attributes for the lines. */
634 int color_pair;
637 static struct line_info line_info[] = {
638 #define LINE(type, line, fg, bg, attr) \
639 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
640 LINE_INFO
641 #undef LINE
644 static struct line_info **color_pair;
645 static size_t color_pairs;
647 static struct line_info *custom_color;
648 static size_t custom_colors;
650 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
651 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
653 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
654 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
656 /* Color IDs must be 1 or higher. [GH #15] */
657 #define COLOR_ID(line_type) ((line_type) + 1)
659 static enum line_type
660 get_line_type(const char *line)
662 int linelen = strlen(line);
663 enum line_type type;
665 for (type = 0; type < custom_colors; type++)
666 /* Case insensitive search matches Signed-off-by lines better. */
667 if (linelen >= custom_color[type].linelen &&
668 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
669 return TO_CUSTOM_COLOR_TYPE(type);
671 for (type = 0; type < ARRAY_SIZE(line_info); type++)
672 /* Case insensitive search matches Signed-off-by lines better. */
673 if (linelen >= line_info[type].linelen &&
674 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
675 return type;
677 return LINE_DEFAULT;
680 static enum line_type
681 get_line_type_from_ref(const struct ref *ref)
683 if (ref->head)
684 return LINE_MAIN_HEAD;
685 else if (ref->ltag)
686 return LINE_MAIN_LOCAL_TAG;
687 else if (ref->tag)
688 return LINE_MAIN_TAG;
689 else if (ref->tracked)
690 return LINE_MAIN_TRACKED;
691 else if (ref->remote)
692 return LINE_MAIN_REMOTE;
693 else if (ref->replace)
694 return LINE_MAIN_REPLACE;
696 return LINE_MAIN_REF;
699 static inline struct line_info *
700 get_line(enum line_type type)
702 if (type > LINE_NONE) {
703 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
704 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
705 } else {
706 assert(type < ARRAY_SIZE(line_info));
707 return &line_info[type];
711 static inline int
712 get_line_color(enum line_type type)
714 return COLOR_ID(get_line(type)->color_pair);
717 static inline int
718 get_line_attr(enum line_type type)
720 struct line_info *info = get_line(type);
722 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
725 static struct line_info *
726 get_line_info(const char *name)
728 size_t namelen = strlen(name);
729 enum line_type type;
731 for (type = 0; type < ARRAY_SIZE(line_info); type++)
732 if (enum_equals(line_info[type], name, namelen))
733 return &line_info[type];
735 return NULL;
738 static struct line_info *
739 add_custom_color(const char *quoted_line)
741 struct line_info *info;
742 char *line;
743 size_t linelen;
745 if (!realloc_custom_color(&custom_color, custom_colors, 1))
746 die("Failed to alloc custom line info");
748 linelen = strlen(quoted_line) - 1;
749 line = malloc(linelen);
750 if (!line)
751 return NULL;
753 strncpy(line, quoted_line + 1, linelen);
754 line[linelen - 1] = 0;
756 info = &custom_color[custom_colors++];
757 info->name = info->line = line;
758 info->namelen = info->linelen = strlen(line);
760 return info;
763 static void
764 init_line_info_color_pair(struct line_info *info, enum line_type type,
765 int default_bg, int default_fg)
767 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
768 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
769 int i;
771 for (i = 0; i < color_pairs; i++) {
772 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
773 info->color_pair = i;
774 return;
778 if (!realloc_color_pair(&color_pair, color_pairs, 1))
779 die("Failed to alloc color pair");
781 color_pair[color_pairs] = info;
782 info->color_pair = color_pairs++;
783 init_pair(COLOR_ID(info->color_pair), fg, bg);
786 static void
787 init_colors(void)
789 int default_bg = line_info[LINE_DEFAULT].bg;
790 int default_fg = line_info[LINE_DEFAULT].fg;
791 enum line_type type;
793 start_color();
795 if (assume_default_colors(default_fg, default_bg) == ERR) {
796 default_bg = COLOR_BLACK;
797 default_fg = COLOR_WHITE;
800 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
801 struct line_info *info = &line_info[type];
803 init_line_info_color_pair(info, type, default_bg, default_fg);
806 for (type = 0; type < custom_colors; type++) {
807 struct line_info *info = &custom_color[type];
809 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
810 default_bg, default_fg);
814 struct line {
815 enum line_type type;
816 unsigned int lineno:24;
818 /* State flags */
819 unsigned int selected:1;
820 unsigned int dirty:1;
821 unsigned int cleareol:1;
822 unsigned int dont_free:1;
823 unsigned int wrapped:1;
825 unsigned int user_flags:6;
826 void *data; /* User data */
831 * Keys
834 struct keybinding {
835 int alias;
836 enum request request;
839 static struct keybinding default_keybindings[] = {
840 /* View switching */
841 { 'm', REQ_VIEW_MAIN },
842 { 'd', REQ_VIEW_DIFF },
843 { 'l', REQ_VIEW_LOG },
844 { 't', REQ_VIEW_TREE },
845 { 'f', REQ_VIEW_BLOB },
846 { 'B', REQ_VIEW_BLAME },
847 { 'H', REQ_VIEW_BRANCH },
848 { 'p', REQ_VIEW_PAGER },
849 { 'h', REQ_VIEW_HELP },
850 { 'S', REQ_VIEW_STATUS },
851 { 'c', REQ_VIEW_STAGE },
853 /* View manipulation */
854 { 'q', REQ_VIEW_CLOSE },
855 { KEY_TAB, REQ_VIEW_NEXT },
856 { KEY_RETURN, REQ_ENTER },
857 { KEY_UP, REQ_PREVIOUS },
858 { KEY_CTL('P'), REQ_PREVIOUS },
859 { KEY_DOWN, REQ_NEXT },
860 { KEY_CTL('N'), REQ_NEXT },
861 { 'R', REQ_REFRESH },
862 { KEY_F(5), REQ_REFRESH },
863 { 'O', REQ_MAXIMIZE },
864 { ',', REQ_PARENT },
866 /* View specific */
867 { 'u', REQ_STATUS_UPDATE },
868 { '!', REQ_STATUS_REVERT },
869 { 'M', REQ_STATUS_MERGE },
870 { '1', REQ_STAGE_UPDATE_LINE },
871 { '@', REQ_STAGE_NEXT },
872 { '[', REQ_DIFF_CONTEXT_DOWN },
873 { ']', REQ_DIFF_CONTEXT_UP },
875 /* Cursor navigation */
876 { 'k', REQ_MOVE_UP },
877 { 'j', REQ_MOVE_DOWN },
878 { KEY_HOME, REQ_MOVE_FIRST_LINE },
879 { KEY_END, REQ_MOVE_LAST_LINE },
880 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
881 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
882 { ' ', REQ_MOVE_PAGE_DOWN },
883 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
884 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
885 { 'b', REQ_MOVE_PAGE_UP },
886 { '-', REQ_MOVE_PAGE_UP },
888 /* Scrolling */
889 { '|', REQ_SCROLL_FIRST_COL },
890 { KEY_LEFT, REQ_SCROLL_LEFT },
891 { KEY_RIGHT, REQ_SCROLL_RIGHT },
892 { KEY_IC, REQ_SCROLL_LINE_UP },
893 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
894 { KEY_DC, REQ_SCROLL_LINE_DOWN },
895 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
896 { 'w', REQ_SCROLL_PAGE_UP },
897 { 's', REQ_SCROLL_PAGE_DOWN },
899 /* Searching */
900 { '/', REQ_SEARCH },
901 { '?', REQ_SEARCH_BACK },
902 { 'n', REQ_FIND_NEXT },
903 { 'N', REQ_FIND_PREV },
905 /* Misc */
906 { 'Q', REQ_QUIT },
907 { 'z', REQ_STOP_LOADING },
908 { 'v', REQ_SHOW_VERSION },
909 { 'r', REQ_SCREEN_REDRAW },
910 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
911 { 'o', REQ_OPTIONS },
912 { '.', REQ_TOGGLE_LINENO },
913 { 'D', REQ_TOGGLE_DATE },
914 { 'A', REQ_TOGGLE_AUTHOR },
915 { 'g', REQ_TOGGLE_REV_GRAPH },
916 { '~', REQ_TOGGLE_GRAPHIC },
917 { '#', REQ_TOGGLE_FILENAME },
918 { 'F', REQ_TOGGLE_REFS },
919 { 'I', REQ_TOGGLE_SORT_ORDER },
920 { 'i', REQ_TOGGLE_SORT_FIELD },
921 { 'W', REQ_TOGGLE_IGNORE_SPACE },
922 { 'X', REQ_TOGGLE_ID },
923 { '%', REQ_TOGGLE_FILES },
924 { '$', REQ_TOGGLE_TITLE_OVERFLOW },
925 { ':', REQ_PROMPT },
926 { 'e', REQ_EDIT },
929 struct keymap {
930 const char *name;
931 struct keymap *next;
932 struct keybinding *data;
933 size_t size;
934 bool hidden;
937 static struct keymap generic_keymap = { "generic" };
938 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
940 static struct keymap *keymaps = &generic_keymap;
942 static void
943 add_keymap(struct keymap *keymap)
945 keymap->next = keymaps;
946 keymaps = keymap;
949 static struct keymap *
950 get_keymap(const char *name)
952 struct keymap *keymap = keymaps;
954 while (keymap) {
955 if (!strcasecmp(keymap->name, name))
956 return keymap;
957 keymap = keymap->next;
960 return NULL;
964 static void
965 add_keybinding(struct keymap *table, enum request request, int key)
967 size_t i;
969 for (i = 0; i < table->size; i++) {
970 if (table->data[i].alias == key) {
971 table->data[i].request = request;
972 return;
976 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
977 if (!table->data)
978 die("Failed to allocate keybinding");
979 table->data[table->size].alias = key;
980 table->data[table->size++].request = request;
982 if (request == REQ_NONE && is_generic_keymap(table)) {
983 int i;
985 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
986 if (default_keybindings[i].alias == key)
987 default_keybindings[i].request = REQ_NONE;
991 /* Looks for a key binding first in the given map, then in the generic map, and
992 * lastly in the default keybindings. */
993 static enum request
994 get_keybinding(struct keymap *keymap, int key)
996 size_t i;
998 for (i = 0; i < keymap->size; i++)
999 if (keymap->data[i].alias == key)
1000 return keymap->data[i].request;
1002 for (i = 0; i < generic_keymap.size; i++)
1003 if (generic_keymap.data[i].alias == key)
1004 return generic_keymap.data[i].request;
1006 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1007 if (default_keybindings[i].alias == key)
1008 return default_keybindings[i].request;
1010 return (enum request) key;
1014 struct key {
1015 const char *name;
1016 int value;
1019 static const struct key key_table[] = {
1020 { "Enter", KEY_RETURN },
1021 { "Space", ' ' },
1022 { "Backspace", KEY_BACKSPACE },
1023 { "Tab", KEY_TAB },
1024 { "Escape", KEY_ESC },
1025 { "Left", KEY_LEFT },
1026 { "Right", KEY_RIGHT },
1027 { "Up", KEY_UP },
1028 { "Down", KEY_DOWN },
1029 { "Insert", KEY_IC },
1030 { "Delete", KEY_DC },
1031 { "Hash", '#' },
1032 { "Home", KEY_HOME },
1033 { "End", KEY_END },
1034 { "PageUp", KEY_PPAGE },
1035 { "PageDown", KEY_NPAGE },
1036 { "F1", KEY_F(1) },
1037 { "F2", KEY_F(2) },
1038 { "F3", KEY_F(3) },
1039 { "F4", KEY_F(4) },
1040 { "F5", KEY_F(5) },
1041 { "F6", KEY_F(6) },
1042 { "F7", KEY_F(7) },
1043 { "F8", KEY_F(8) },
1044 { "F9", KEY_F(9) },
1045 { "F10", KEY_F(10) },
1046 { "F11", KEY_F(11) },
1047 { "F12", KEY_F(12) },
1050 static int
1051 get_key_value(const char *name)
1053 int i;
1055 for (i = 0; i < ARRAY_SIZE(key_table); i++)
1056 if (!strcasecmp(key_table[i].name, name))
1057 return key_table[i].value;
1059 if (strlen(name) == 3 && name[0] == '^' && name[1] == '[' && isprint(*name))
1060 return (int)name[2] + 0x80;
1061 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1062 return (int)name[1] & 0x1f;
1063 if (strlen(name) == 1 && isprint(*name))
1064 return (int) *name;
1065 return ERR;
1068 static const char *
1069 get_key_name(int key_value)
1071 static char key_char[] = "'X'\0";
1072 const char *seq = NULL;
1073 int key;
1075 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1076 if (key_table[key].value == key_value)
1077 seq = key_table[key].name;
1079 if (seq == NULL && key_value < 0x7f) {
1080 char *s = key_char + 1;
1082 if (key_value >= 0x20) {
1083 *s++ = key_value;
1084 } else {
1085 *s++ = '^';
1086 *s++ = 0x40 | (key_value & 0x1f);
1088 *s++ = '\'';
1089 *s++ = '\0';
1090 seq = key_char;
1093 return seq ? seq : "(no key)";
1096 static bool
1097 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1099 const char *sep = *pos > 0 ? ", " : "";
1100 const char *keyname = get_key_name(keybinding->alias);
1102 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1105 static bool
1106 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1107 struct keymap *keymap, bool all)
1109 int i;
1111 for (i = 0; i < keymap->size; i++) {
1112 if (keymap->data[i].request == request) {
1113 if (!append_key(buf, pos, &keymap->data[i]))
1114 return FALSE;
1115 if (!all)
1116 break;
1120 return TRUE;
1123 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1125 static const char *
1126 get_keys(struct keymap *keymap, enum request request, bool all)
1128 static char buf[BUFSIZ];
1129 size_t pos = 0;
1130 int i;
1132 buf[pos] = 0;
1134 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1135 return "Too many keybindings!";
1136 if (pos > 0 && !all)
1137 return buf;
1139 if (!is_generic_keymap(keymap)) {
1140 /* Only the generic keymap includes the default keybindings when
1141 * listing all keys. */
1142 if (all)
1143 return buf;
1145 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1146 return "Too many keybindings!";
1147 if (pos)
1148 return buf;
1151 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1152 if (default_keybindings[i].request == request) {
1153 if (!append_key(buf, &pos, &default_keybindings[i]))
1154 return "Too many keybindings!";
1155 if (!all)
1156 return buf;
1160 return buf;
1163 enum run_request_flag {
1164 RUN_REQUEST_DEFAULT = 0,
1165 RUN_REQUEST_FORCE = 1,
1166 RUN_REQUEST_SILENT = 2,
1167 RUN_REQUEST_CONFIRM = 4,
1168 RUN_REQUEST_EXIT = 8,
1169 RUN_REQUEST_INTERNAL = 16,
1172 struct run_request {
1173 struct keymap *keymap;
1174 int key;
1175 const char **argv;
1176 bool silent;
1177 bool confirm;
1178 bool exit;
1179 bool internal;
1182 static struct run_request *run_request;
1183 static size_t run_requests;
1185 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1187 static bool
1188 add_run_request(struct keymap *keymap, int key, const char **argv, enum run_request_flag flags)
1190 bool force = flags & RUN_REQUEST_FORCE;
1191 struct run_request *req;
1193 if (!force && get_keybinding(keymap, key) != key)
1194 return TRUE;
1196 if (!realloc_run_requests(&run_request, run_requests, 1))
1197 return FALSE;
1199 if (!argv_copy(&run_request[run_requests].argv, argv))
1200 return FALSE;
1202 req = &run_request[run_requests++];
1203 req->silent = flags & RUN_REQUEST_SILENT;
1204 req->confirm = flags & RUN_REQUEST_CONFIRM;
1205 req->exit = flags & RUN_REQUEST_EXIT;
1206 req->internal = flags & RUN_REQUEST_INTERNAL;
1207 req->keymap = keymap;
1208 req->key = key;
1210 add_keybinding(keymap, REQ_NONE + run_requests, key);
1211 return TRUE;
1214 static struct run_request *
1215 get_run_request(enum request request)
1217 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1218 return NULL;
1219 return &run_request[request - REQ_NONE - 1];
1222 static void
1223 add_builtin_run_requests(void)
1225 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1226 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1227 const char *commit[] = { "git", "commit", NULL };
1228 const char *gc[] = { "git", "gc", NULL };
1230 add_run_request(get_keymap("main"), 'C', cherry_pick, RUN_REQUEST_CONFIRM);
1231 add_run_request(get_keymap("status"), 'C', commit, RUN_REQUEST_DEFAULT);
1232 add_run_request(get_keymap("branch"), 'C', checkout, RUN_REQUEST_CONFIRM);
1233 add_run_request(get_keymap("generic"), 'G', gc, RUN_REQUEST_CONFIRM);
1237 * User config file handling.
1240 #define OPT_ERR_INFO \
1241 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1242 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1243 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1244 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1245 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1246 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1247 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1248 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1249 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1250 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1251 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1252 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1253 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1254 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1255 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1256 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1257 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1258 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1260 enum option_code {
1261 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1262 OPT_ERR_INFO
1263 #undef OPT_ERR_
1264 OPT_OK
1267 static const char *option_errors[] = {
1268 #define OPT_ERR_(name, msg) msg
1269 OPT_ERR_INFO
1270 #undef OPT_ERR_
1273 static const struct enum_map color_map[] = {
1274 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1275 COLOR_MAP(DEFAULT),
1276 COLOR_MAP(BLACK),
1277 COLOR_MAP(BLUE),
1278 COLOR_MAP(CYAN),
1279 COLOR_MAP(GREEN),
1280 COLOR_MAP(MAGENTA),
1281 COLOR_MAP(RED),
1282 COLOR_MAP(WHITE),
1283 COLOR_MAP(YELLOW),
1286 static const struct enum_map attr_map[] = {
1287 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1288 ATTR_MAP(NORMAL),
1289 ATTR_MAP(BLINK),
1290 ATTR_MAP(BOLD),
1291 ATTR_MAP(DIM),
1292 ATTR_MAP(REVERSE),
1293 ATTR_MAP(STANDOUT),
1294 ATTR_MAP(UNDERLINE),
1297 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1299 static enum option_code
1300 parse_step(double *opt, const char *arg)
1302 *opt = atoi(arg);
1303 if (!strchr(arg, '%'))
1304 return OPT_OK;
1306 /* "Shift down" so 100% and 1 does not conflict. */
1307 *opt = (*opt - 1) / 100;
1308 if (*opt >= 1.0) {
1309 *opt = 0.99;
1310 return OPT_ERR_INVALID_STEP_VALUE;
1312 if (*opt < 0.0) {
1313 *opt = 1;
1314 return OPT_ERR_INVALID_STEP_VALUE;
1316 return OPT_OK;
1319 static enum option_code
1320 parse_int(int *opt, const char *arg, int min, int max)
1322 int value = atoi(arg);
1324 if (min <= value && value <= max) {
1325 *opt = value;
1326 return OPT_OK;
1329 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1332 #define parse_id(opt, arg) \
1333 parse_int(opt, arg, 4, SIZEOF_REV - 1)
1335 static bool
1336 set_color(int *color, const char *name)
1338 if (map_enum(color, color_map, name))
1339 return TRUE;
1340 if (!prefixcmp(name, "color"))
1341 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1342 /* Used when reading git colors. Git expects a plain int w/o prefix. */
1343 return parse_int(color, name, 0, 255) == OPT_OK;
1346 /* Wants: object fgcolor bgcolor [attribute] */
1347 static enum option_code
1348 option_color_command(int argc, const char *argv[])
1350 struct line_info *info;
1352 if (argc < 3)
1353 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1355 if (*argv[0] == '"' || *argv[0] == '\'') {
1356 info = add_custom_color(argv[0]);
1357 } else {
1358 info = get_line_info(argv[0]);
1360 if (!info) {
1361 static const struct enum_map obsolete[] = {
1362 ENUM_MAP("main-delim", LINE_DELIMITER),
1363 ENUM_MAP("main-date", LINE_DATE),
1364 ENUM_MAP("main-author", LINE_AUTHOR),
1365 ENUM_MAP("blame-id", LINE_ID),
1367 int index;
1369 if (!map_enum(&index, obsolete, argv[0]))
1370 return OPT_ERR_UNKNOWN_COLOR_NAME;
1371 info = &line_info[index];
1374 if (!set_color(&info->fg, argv[1]) ||
1375 !set_color(&info->bg, argv[2]))
1376 return OPT_ERR_UNKNOWN_COLOR;
1378 info->attr = 0;
1379 while (argc-- > 3) {
1380 int attr;
1382 if (!set_attribute(&attr, argv[argc]))
1383 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1384 info->attr |= attr;
1387 return OPT_OK;
1390 static enum option_code
1391 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1393 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1394 ? TRUE : FALSE;
1395 if (matched)
1396 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1397 return OPT_OK;
1400 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1402 static enum option_code
1403 parse_enum_do(unsigned int *opt, const char *arg,
1404 const struct enum_map *map, size_t map_size)
1406 bool is_true;
1408 assert(map_size > 1);
1410 if (map_enum_do(map, map_size, (int *) opt, arg))
1411 return OPT_OK;
1413 parse_bool(&is_true, arg);
1414 *opt = is_true ? map[1].value : map[0].value;
1415 return OPT_OK;
1418 #define parse_enum(opt, arg, map) \
1419 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1421 static enum option_code
1422 parse_string(char *opt, const char *arg, size_t optsize)
1424 int arglen = strlen(arg);
1426 switch (arg[0]) {
1427 case '\"':
1428 case '\'':
1429 if (arglen == 1 || arg[arglen - 1] != arg[0])
1430 return OPT_ERR_UNMATCHED_QUOTATION;
1431 arg += 1; arglen -= 2;
1432 default:
1433 string_ncopy_do(opt, optsize, arg, arglen);
1434 return OPT_OK;
1438 static enum option_code
1439 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1441 char buf[SIZEOF_STR];
1442 enum option_code code = parse_string(buf, arg, sizeof(buf));
1444 if (code == OPT_OK) {
1445 struct encoding *encoding = *encoding_ref;
1447 if (encoding && !priority)
1448 return code;
1449 encoding = encoding_open(buf);
1450 if (encoding)
1451 *encoding_ref = encoding;
1454 return code;
1457 static enum option_code
1458 parse_args(const char ***args, const char *argv[])
1460 if (!argv_copy(args, argv))
1461 return OPT_ERR_OUT_OF_MEMORY;
1462 return OPT_OK;
1465 /* Wants: name = value */
1466 static enum option_code
1467 option_set_command(int argc, const char *argv[])
1469 if (argc < 3)
1470 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1472 if (strcmp(argv[1], "="))
1473 return OPT_ERR_NO_VALUE_ASSIGNED;
1475 if (!strcmp(argv[0], "blame-options"))
1476 return parse_args(&opt_blame_argv, argv + 2);
1478 if (!strcmp(argv[0], "diff-options"))
1479 return parse_args(&opt_diff_argv, argv + 2);
1481 if (argc != 3)
1482 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1484 if (!strcmp(argv[0], "show-author"))
1485 return parse_enum(&opt_author, argv[2], author_map);
1487 if (!strcmp(argv[0], "show-date"))
1488 return parse_enum(&opt_date, argv[2], date_map);
1490 if (!strcmp(argv[0], "show-rev-graph"))
1491 return parse_bool(&opt_rev_graph, argv[2]);
1493 if (!strcmp(argv[0], "show-refs"))
1494 return parse_bool(&opt_show_refs, argv[2]);
1496 if (!strcmp(argv[0], "show-changes"))
1497 return parse_bool(&opt_show_changes, argv[2]);
1499 if (!strcmp(argv[0], "show-notes")) {
1500 bool matched = FALSE;
1501 enum option_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1503 if (res == OPT_OK && matched) {
1504 update_notes_arg();
1505 return res;
1508 opt_notes = TRUE;
1509 strcpy(opt_notes_arg, "--show-notes=");
1510 res = parse_string(opt_notes_arg + 8, argv[2],
1511 sizeof(opt_notes_arg) - 8);
1512 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1513 opt_notes_arg[7] = '\0';
1514 return res;
1517 if (!strcmp(argv[0], "show-line-numbers"))
1518 return parse_bool(&opt_line_number, argv[2]);
1520 if (!strcmp(argv[0], "line-graphics"))
1521 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1523 if (!strcmp(argv[0], "line-number-interval"))
1524 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1526 if (!strcmp(argv[0], "author-width"))
1527 return parse_int(&opt_author_width, argv[2], 0, 1024);
1529 if (!strcmp(argv[0], "filename-width"))
1530 return parse_int(&opt_filename_width, argv[2], 0, 1024);
1532 if (!strcmp(argv[0], "show-filename"))
1533 return parse_enum(&opt_filename, argv[2], filename_map);
1535 if (!strcmp(argv[0], "horizontal-scroll"))
1536 return parse_step(&opt_hscroll, argv[2]);
1538 if (!strcmp(argv[0], "split-view-height"))
1539 return parse_step(&opt_scale_split_view, argv[2]);
1541 if (!strcmp(argv[0], "vertical-split"))
1542 return parse_bool(&opt_vsplit, argv[2]);
1544 if (!strcmp(argv[0], "tab-size"))
1545 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1547 if (!strcmp(argv[0], "diff-context")) {
1548 enum option_code code = parse_int(&opt_diff_context, argv[2], 0, 999999);
1550 if (code == OPT_OK)
1551 update_diff_context_arg(opt_diff_context);
1552 return code;
1555 if (!strcmp(argv[0], "ignore-space")) {
1556 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1558 if (code == OPT_OK)
1559 update_ignore_space_arg();
1560 return code;
1563 if (!strcmp(argv[0], "commit-order")) {
1564 enum option_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1566 if (code == OPT_OK)
1567 update_commit_order_arg();
1568 return code;
1571 if (!strcmp(argv[0], "status-untracked-dirs"))
1572 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1574 if (!strcmp(argv[0], "read-git-colors"))
1575 return parse_bool(&opt_read_git_colors, argv[2]);
1577 if (!strcmp(argv[0], "ignore-case"))
1578 return parse_bool(&opt_ignore_case, argv[2]);
1580 if (!strcmp(argv[0], "focus-child"))
1581 return parse_bool(&opt_focus_child, argv[2]);
1583 if (!strcmp(argv[0], "wrap-lines"))
1584 return parse_bool(&opt_wrap_lines, argv[2]);
1586 if (!strcmp(argv[0], "show-id"))
1587 return parse_bool(&opt_show_id, argv[2]);
1589 if (!strcmp(argv[0], "id-width"))
1590 return parse_id(&opt_id_cols, argv[2]);
1592 if (!strcmp(argv[0], "title-overflow")) {
1593 bool matched;
1594 enum option_code code;
1597 * "title-overflow" is considered a boolint.
1598 * We try to parse it as a boolean (and set the value to 50 if true),
1599 * otherwise we parse it as an integer and use the given value.
1601 code = parse_bool_matched(&opt_show_title_overflow, argv[2], &matched);
1602 if (code == OPT_OK && matched) {
1603 if (opt_show_title_overflow)
1604 opt_title_overflow = 50;
1605 } else {
1606 code = parse_int(&opt_title_overflow, argv[2], 2, 1024);
1607 if (code == OPT_OK)
1608 opt_show_title_overflow = TRUE;
1611 return code;
1614 if (!strcmp(argv[0], "editor-line-number"))
1615 return parse_bool(&opt_editor_lineno, argv[2]);
1617 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1620 /* Wants: mode request key */
1621 static enum option_code
1622 option_bind_command(int argc, const char *argv[])
1624 enum request request;
1625 struct keymap *keymap;
1626 int key;
1628 if (argc < 3)
1629 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1631 if (!(keymap = get_keymap(argv[0])))
1632 return OPT_ERR_UNKNOWN_KEY_MAP;
1634 key = get_key_value(argv[1]);
1635 if (key == ERR)
1636 return OPT_ERR_UNKNOWN_KEY;
1638 request = get_request(argv[2]);
1639 if (request == REQ_UNKNOWN) {
1640 static const struct enum_map obsolete[] = {
1641 ENUM_MAP("cherry-pick", REQ_NONE),
1642 ENUM_MAP("screen-resize", REQ_NONE),
1643 ENUM_MAP("tree-parent", REQ_PARENT),
1645 int alias;
1647 if (map_enum(&alias, obsolete, argv[2])) {
1648 if (alias != REQ_NONE)
1649 add_keybinding(keymap, alias, key);
1650 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1654 if (request == REQ_UNKNOWN) {
1655 char first = *argv[2]++;
1657 if (first == '!') {
1658 enum run_request_flag flags = RUN_REQUEST_FORCE;
1660 while (*argv[2]) {
1661 if (*argv[2] == '@') {
1662 flags |= RUN_REQUEST_SILENT;
1663 } else if (*argv[2] == '?') {
1664 flags |= RUN_REQUEST_CONFIRM;
1665 } else if (*argv[2] == '<') {
1666 flags |= RUN_REQUEST_EXIT;
1667 } else {
1668 break;
1670 argv[2]++;
1673 return add_run_request(keymap, key, argv + 2, flags)
1674 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1675 } else if (first == ':') {
1676 return add_run_request(keymap, key, argv + 2, RUN_REQUEST_FORCE | RUN_REQUEST_INTERNAL)
1677 ? OPT_OK : OPT_ERR_OUT_OF_MEMORY;
1678 } else {
1679 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1683 add_keybinding(keymap, request, key);
1685 return OPT_OK;
1689 static enum option_code load_option_file(const char *path);
1691 static enum option_code
1692 option_source_command(int argc, const char *argv[])
1694 if (argc < 1)
1695 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1697 return load_option_file(argv[0]);
1700 static enum option_code
1701 set_option(const char *opt, char *value)
1703 const char *argv[SIZEOF_ARG];
1704 int argc = 0;
1706 if (!argv_from_string(argv, &argc, value))
1707 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1709 if (!strcmp(opt, "color"))
1710 return option_color_command(argc, argv);
1712 if (!strcmp(opt, "set"))
1713 return option_set_command(argc, argv);
1715 if (!strcmp(opt, "bind"))
1716 return option_bind_command(argc, argv);
1718 if (!strcmp(opt, "source"))
1719 return option_source_command(argc, argv);
1721 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1724 struct config_state {
1725 const char *path;
1726 int lineno;
1727 bool errors;
1730 static int
1731 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1733 struct config_state *config = data;
1734 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1736 config->lineno++;
1738 /* Check for comment markers, since read_properties() will
1739 * only ensure opt and value are split at first " \t". */
1740 optlen = strcspn(opt, "#");
1741 if (optlen == 0)
1742 return OK;
1744 if (opt[optlen] == 0) {
1745 /* Look for comment endings in the value. */
1746 size_t len = strcspn(value, "#");
1748 if (len < valuelen) {
1749 valuelen = len;
1750 value[valuelen] = 0;
1753 status = set_option(opt, value);
1756 if (status != OPT_OK) {
1757 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1758 option_errors[status], (int) optlen, opt);
1759 config->errors = TRUE;
1762 /* Always keep going if errors are encountered. */
1763 return OK;
1766 static enum option_code
1767 load_option_file(const char *path)
1769 struct config_state config = { path, 0, FALSE };
1770 struct io io;
1772 /* Do not read configuration from stdin if set to "" */
1773 if (!path || !strlen(path))
1774 return OPT_OK;
1776 /* It's OK that the file doesn't exist. */
1777 if (!io_open(&io, "%s", path))
1778 return OPT_ERR_FILE_DOES_NOT_EXIST;
1780 if (io_load(&io, " \t", read_option, &config) == ERR ||
1781 config.errors == TRUE)
1782 warn("Errors while loading %s.", path);
1783 return OPT_OK;
1786 static int
1787 load_options(void)
1789 const char *home = getenv("HOME");
1790 const char *tigrc_user = getenv("TIGRC_USER");
1791 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1792 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1793 const bool diff_opts_from_args = !!opt_diff_argv;
1794 char buf[SIZEOF_STR];
1796 if (!tigrc_system)
1797 tigrc_system = SYSCONFDIR "/tigrc";
1798 load_option_file(tigrc_system);
1800 if (!tigrc_user) {
1801 if (!home || !string_format(buf, "%s/.tigrc", home))
1802 return ERR;
1803 tigrc_user = buf;
1805 load_option_file(tigrc_user);
1807 /* Add _after_ loading config files to avoid adding run requests
1808 * that conflict with keybindings. */
1809 add_builtin_run_requests();
1811 if (!diff_opts_from_args && tig_diff_opts && *tig_diff_opts) {
1812 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1813 int argc = 0;
1815 if (!string_format(buf, "%s", tig_diff_opts) ||
1816 !argv_from_string(diff_opts, &argc, buf))
1817 die("TIG_DIFF_OPTS contains too many arguments");
1818 else if (!argv_copy(&opt_diff_argv, diff_opts))
1819 die("Failed to format TIG_DIFF_OPTS arguments");
1822 return OK;
1827 * The viewer
1830 struct view;
1831 struct view_ops;
1833 /* The display array of active views and the index of the current view. */
1834 static struct view *display[2];
1835 static WINDOW *display_win[2];
1836 static WINDOW *display_title[2];
1837 static WINDOW *display_sep;
1839 static unsigned int current_view;
1841 #define foreach_displayed_view(view, i) \
1842 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1844 #define displayed_views() (display[1] != NULL ? 2 : 1)
1846 /* Current head and commit ID */
1847 static char ref_blob[SIZEOF_REF] = "";
1848 static char ref_commit[SIZEOF_REF] = "HEAD";
1849 static char ref_head[SIZEOF_REF] = "HEAD";
1850 static char ref_branch[SIZEOF_REF] = "";
1851 static char ref_status[SIZEOF_STR] = "";
1853 enum view_flag {
1854 VIEW_NO_FLAGS = 0,
1855 VIEW_ALWAYS_LINENO = 1 << 0,
1856 VIEW_CUSTOM_STATUS = 1 << 1,
1857 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1858 VIEW_ADD_PAGER_REFS = 1 << 3,
1859 VIEW_OPEN_DIFF = 1 << 4,
1860 VIEW_NO_REF = 1 << 5,
1861 VIEW_NO_GIT_DIR = 1 << 6,
1862 VIEW_DIFF_LIKE = 1 << 7,
1863 VIEW_STDIN = 1 << 8,
1864 VIEW_SEND_CHILD_ENTER = 1 << 9,
1865 VIEW_FILE_FILTER = 1 << 10,
1868 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1870 struct position {
1871 unsigned long offset; /* Offset of the window top */
1872 unsigned long col; /* Offset from the window side. */
1873 unsigned long lineno; /* Current line number */
1876 struct view {
1877 const char *name; /* View name */
1878 const char *id; /* Points to either of ref_{head,commit,blob} */
1880 struct view_ops *ops; /* View operations */
1882 char ref[SIZEOF_REF]; /* Hovered commit reference */
1883 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1885 int height, width; /* The width and height of the main window */
1886 WINDOW *win; /* The main window */
1888 /* Navigation */
1889 struct position pos; /* Current position. */
1890 struct position prev_pos; /* Previous position. */
1892 /* Searching */
1893 char grep[SIZEOF_STR]; /* Search string */
1894 regex_t *regex; /* Pre-compiled regexp */
1896 /* If non-NULL, points to the view that opened this view. If this view
1897 * is closed tig will switch back to the parent view. */
1898 struct view *parent;
1899 struct view *prev;
1901 /* Buffering */
1902 size_t lines; /* Total number of lines */
1903 struct line *line; /* Line index */
1904 unsigned int digits; /* Number of digits in the lines member. */
1906 /* Number of lines with custom status, not to be counted in the
1907 * view title. */
1908 unsigned int custom_lines;
1910 /* Drawing */
1911 struct line *curline; /* Line currently being drawn. */
1912 enum line_type curtype; /* Attribute currently used for drawing. */
1913 unsigned long col; /* Column when drawing. */
1914 bool has_scrolled; /* View was scrolled. */
1916 /* Loading */
1917 const char **argv; /* Shell command arguments. */
1918 const char *dir; /* Directory from which to execute. */
1919 struct io io;
1920 struct io *pipe;
1921 time_t start_time;
1922 time_t update_secs;
1923 struct encoding *encoding;
1924 bool unrefreshable;
1926 /* Private data */
1927 void *private;
1930 enum open_flags {
1931 OPEN_DEFAULT = 0, /* Use default view switching. */
1932 OPEN_SPLIT = 1, /* Split current view. */
1933 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1934 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1935 OPEN_PREPARED = 32, /* Open already prepared command. */
1936 OPEN_EXTRA = 64, /* Open extra data from command. */
1939 struct view_ops {
1940 /* What type of content being displayed. Used in the title bar. */
1941 const char *type;
1942 /* What keymap does this view have */
1943 struct keymap keymap;
1944 /* Flags to control the view behavior. */
1945 enum view_flag flags;
1946 /* Size of private data. */
1947 size_t private_size;
1948 /* Open and reads in all view content. */
1949 bool (*open)(struct view *view, enum open_flags flags);
1950 /* Read one line; updates view->line. */
1951 bool (*read)(struct view *view, char *data);
1952 /* Draw one line; @lineno must be < view->height. */
1953 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1954 /* Depending on view handle a special requests. */
1955 enum request (*request)(struct view *view, enum request request, struct line *line);
1956 /* Search for regexp in a line. */
1957 bool (*grep)(struct view *view, struct line *line);
1958 /* Select line */
1959 void (*select)(struct view *view, struct line *line);
1962 #define VIEW_OPS(id, name, ref) name##_ops
1963 static struct view_ops VIEW_INFO(VIEW_OPS);
1965 static struct view views[] = {
1966 #define VIEW_DATA(id, name, ref) \
1967 { #name, ref, &name##_ops }
1968 VIEW_INFO(VIEW_DATA)
1971 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1973 #define foreach_view(view, i) \
1974 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1976 #define view_is_displayed(view) \
1977 (view == display[0] || view == display[1])
1979 #define view_has_line(view, line_) \
1980 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
1982 static bool
1983 forward_request_to_child(struct view *child, enum request request)
1985 return displayed_views() == 2 && view_is_displayed(child) &&
1986 !strcmp(child->vid, child->id);
1989 static enum request
1990 view_request(struct view *view, enum request request)
1992 if (!view || !view->lines)
1993 return request;
1995 if (request == REQ_ENTER && !opt_focus_child &&
1996 view_has_flags(view, VIEW_SEND_CHILD_ENTER)) {
1997 struct view *child = display[1];
1999 if (forward_request_to_child(child, request)) {
2000 view_request(child, request);
2001 return REQ_NONE;
2005 if (request == REQ_REFRESH && view->unrefreshable) {
2006 report("This view can not be refreshed");
2007 return REQ_NONE;
2010 return view->ops->request(view, request, &view->line[view->pos.lineno]);
2014 * View drawing.
2017 static inline void
2018 set_view_attr(struct view *view, enum line_type type)
2020 if (!view->curline->selected && view->curtype != type) {
2021 (void) wattrset(view->win, get_line_attr(type));
2022 wchgat(view->win, -1, 0, get_line_color(type), NULL);
2023 view->curtype = type;
2027 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
2029 static bool
2030 draw_chars(struct view *view, enum line_type type, const char *string,
2031 int max_len, bool use_tilde)
2033 static char out_buffer[BUFSIZ * 2];
2034 int len = 0;
2035 int col = 0;
2036 int trimmed = FALSE;
2037 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2039 if (max_len <= 0)
2040 return VIEW_MAX_LEN(view) <= 0;
2042 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
2044 set_view_attr(view, type);
2045 if (len > 0) {
2046 if (opt_iconv_out != ICONV_NONE) {
2047 size_t inlen = len + 1;
2048 char *instr = calloc(1, inlen);
2049 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
2050 if (!instr)
2051 return VIEW_MAX_LEN(view) <= 0;
2053 strncpy(instr, string, len);
2055 char *outbuf = out_buffer;
2056 size_t outlen = sizeof(out_buffer);
2058 size_t ret;
2060 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
2061 if (ret != (size_t) -1) {
2062 string = out_buffer;
2063 len = sizeof(out_buffer) - outlen;
2065 free(instr);
2068 waddnstr(view->win, string, len);
2070 if (trimmed && use_tilde) {
2071 set_view_attr(view, LINE_DELIMITER);
2072 waddch(view->win, '~');
2073 col++;
2077 view->col += col;
2078 return VIEW_MAX_LEN(view) <= 0;
2081 static bool
2082 draw_space(struct view *view, enum line_type type, int max, int spaces)
2084 static char space[] = " ";
2086 spaces = MIN(max, spaces);
2088 while (spaces > 0) {
2089 int len = MIN(spaces, sizeof(space) - 1);
2091 if (draw_chars(view, type, space, len, FALSE))
2092 return TRUE;
2093 spaces -= len;
2096 return VIEW_MAX_LEN(view) <= 0;
2099 static bool
2100 draw_text_expanded(struct view *view, enum line_type type, const char *string, int max_len, bool use_tilde)
2102 static char text[SIZEOF_STR];
2104 do {
2105 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
2107 if (draw_chars(view, type, text, max_len, use_tilde))
2108 return TRUE;
2109 string += pos;
2110 } while (*string);
2112 return VIEW_MAX_LEN(view) <= 0;
2115 static bool
2116 draw_text(struct view *view, enum line_type type, const char *string)
2118 return draw_text_expanded(view, type, string, VIEW_MAX_LEN(view), TRUE);
2121 static bool
2122 draw_text_overflow(struct view *view, const char *text, bool on, int overflow, enum line_type type)
2124 if (on) {
2125 int len = strlen(text);
2127 if (draw_text_expanded(view, type, text, overflow, FALSE))
2128 return TRUE;
2130 text = len > overflow ? text + overflow : "";
2131 type = LINE_OVERFLOW;
2134 if (*text && draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
2135 return TRUE;
2137 return VIEW_MAX_LEN(view) <= 0;
2140 #define draw_commit_title(view, text, offset) \
2141 draw_text_overflow(view, text, opt_show_title_overflow, opt_title_overflow + offset, LINE_DEFAULT)
2143 static bool PRINTF_LIKE(3, 4)
2144 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
2146 char text[SIZEOF_STR];
2147 int retval;
2149 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
2150 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
2153 static bool
2154 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
2156 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2157 int max = VIEW_MAX_LEN(view);
2158 int i;
2160 if (max < size)
2161 size = max;
2163 set_view_attr(view, type);
2164 /* Using waddch() instead of waddnstr() ensures that
2165 * they'll be rendered correctly for the cursor line. */
2166 for (i = skip; i < size; i++)
2167 waddch(view->win, graphic[i]);
2169 view->col += size;
2170 if (separator) {
2171 if (size < max && skip <= size)
2172 waddch(view->win, ' ');
2173 view->col++;
2176 return VIEW_MAX_LEN(view) <= 0;
2179 static bool
2180 draw_field(struct view *view, enum line_type type, const char *text, int width, bool trim)
2182 int max = MIN(VIEW_MAX_LEN(view), width + 1);
2183 int col = view->col;
2185 if (!text)
2186 return draw_space(view, type, max, max);
2188 return draw_chars(view, type, text, max - 1, trim)
2189 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2192 static bool
2193 draw_date(struct view *view, struct time *time)
2195 const char *date = mkdate(time, opt_date);
2196 int cols = opt_date == DATE_SHORT ? DATE_SHORT_WIDTH : DATE_WIDTH;
2198 if (opt_date == DATE_NO)
2199 return FALSE;
2201 return draw_field(view, LINE_DATE, date, cols, FALSE);
2204 static bool
2205 draw_author(struct view *view, const struct ident *author)
2207 bool trim = author_trim(opt_author_width);
2208 const char *text = mkauthor(author, opt_author_width, opt_author);
2210 if (opt_author == AUTHOR_NO)
2211 return FALSE;
2213 return draw_field(view, LINE_AUTHOR, text, opt_author_width, trim);
2216 static bool
2217 draw_id(struct view *view, enum line_type type, const char *id)
2219 return draw_field(view, type, id, opt_id_cols, FALSE);
2222 static bool
2223 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2225 bool trim = filename && strlen(filename) >= opt_filename_width;
2227 if (opt_filename == FILENAME_NO)
2228 return FALSE;
2230 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2231 return FALSE;
2233 return draw_field(view, LINE_FILENAME, filename, opt_filename_width, trim);
2236 static bool
2237 draw_mode(struct view *view, mode_t mode)
2239 const char *str = mkmode(mode);
2241 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r--"), FALSE);
2244 static bool
2245 draw_lineno(struct view *view, unsigned int lineno)
2247 char number[10];
2248 int digits3 = view->digits < 3 ? 3 : view->digits;
2249 int max = MIN(VIEW_MAX_LEN(view), digits3);
2250 char *text = NULL;
2251 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2253 if (!opt_line_number)
2254 return FALSE;
2256 lineno += view->pos.offset + 1;
2257 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2258 static char fmt[] = "%1ld";
2260 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2261 if (string_format(number, fmt, lineno))
2262 text = number;
2264 if (text)
2265 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2266 else
2267 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2268 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2271 static bool
2272 draw_refs(struct view *view, struct ref_list *refs)
2274 size_t i;
2276 if (!opt_show_refs || !refs)
2277 return FALSE;
2279 for (i = 0; i < refs->size; i++) {
2280 struct ref *ref = refs->refs[i];
2281 enum line_type type = get_line_type_from_ref(ref);
2283 if (draw_formatted(view, type, "[%s]", ref->name))
2284 return TRUE;
2286 if (draw_text(view, LINE_DEFAULT, " "))
2287 return TRUE;
2290 return FALSE;
2293 static bool
2294 draw_view_line(struct view *view, unsigned int lineno)
2296 struct line *line;
2297 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2299 assert(view_is_displayed(view));
2301 if (view->pos.offset + lineno >= view->lines)
2302 return FALSE;
2304 line = &view->line[view->pos.offset + lineno];
2306 wmove(view->win, lineno, 0);
2307 if (line->cleareol)
2308 wclrtoeol(view->win);
2309 view->col = 0;
2310 view->curline = line;
2311 view->curtype = LINE_NONE;
2312 line->selected = FALSE;
2313 line->dirty = line->cleareol = 0;
2315 if (selected) {
2316 set_view_attr(view, LINE_CURSOR);
2317 line->selected = TRUE;
2318 view->ops->select(view, line);
2321 return view->ops->draw(view, line, lineno);
2324 static void
2325 redraw_view_dirty(struct view *view)
2327 bool dirty = FALSE;
2328 int lineno;
2330 for (lineno = 0; lineno < view->height; lineno++) {
2331 if (view->pos.offset + lineno >= view->lines)
2332 break;
2333 if (!view->line[view->pos.offset + lineno].dirty)
2334 continue;
2335 dirty = TRUE;
2336 if (!draw_view_line(view, lineno))
2337 break;
2340 if (!dirty)
2341 return;
2342 wnoutrefresh(view->win);
2345 static void
2346 redraw_view_from(struct view *view, int lineno)
2348 assert(0 <= lineno && lineno < view->height);
2350 for (; lineno < view->height; lineno++) {
2351 if (!draw_view_line(view, lineno))
2352 break;
2355 wnoutrefresh(view->win);
2358 static void
2359 redraw_view(struct view *view)
2361 werase(view->win);
2362 redraw_view_from(view, 0);
2366 static void
2367 update_view_title(struct view *view)
2369 char buf[SIZEOF_STR];
2370 char state[SIZEOF_STR];
2371 size_t bufpos = 0, statelen = 0;
2372 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2373 struct line *line = &view->line[view->pos.lineno];
2375 assert(view_is_displayed(view));
2377 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view_has_line(view, line) &&
2378 line->lineno) {
2379 unsigned int view_lines = view->pos.offset + view->height;
2380 unsigned int lines = view->lines
2381 ? MIN(view_lines, view->lines) * 100 / view->lines
2382 : 0;
2384 string_format_from(state, &statelen, " - %s %d of %zd (%d%%)",
2385 view->ops->type,
2386 line->lineno,
2387 view->lines - view->custom_lines,
2388 lines);
2392 if (view->pipe) {
2393 time_t secs = time(NULL) - view->start_time;
2395 /* Three git seconds are a long time ... */
2396 if (secs > 2)
2397 string_format_from(state, &statelen, " loading %lds", secs);
2400 string_format_from(buf, &bufpos, "[%s]", view->name);
2401 if (*view->ref && bufpos < view->width) {
2402 size_t refsize = strlen(view->ref);
2403 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2405 if (minsize < view->width)
2406 refsize = view->width - minsize + 7;
2407 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2410 if (statelen && bufpos < view->width) {
2411 string_format_from(buf, &bufpos, "%s", state);
2414 if (view == display[current_view])
2415 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2416 else
2417 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2419 mvwaddnstr(window, 0, 0, buf, bufpos);
2420 wclrtoeol(window);
2421 wnoutrefresh(window);
2424 static int
2425 apply_step(double step, int value)
2427 if (step >= 1)
2428 return (int) step;
2429 value *= step + 0.01;
2430 return value ? value : 1;
2433 static void
2434 apply_horizontal_split(struct view *base, struct view *view)
2436 view->width = base->width;
2437 view->height = apply_step(opt_scale_split_view, base->height);
2438 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2439 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2440 base->height -= view->height;
2443 static void
2444 apply_vertical_split(struct view *base, struct view *view)
2446 view->height = base->height;
2447 view->width = apply_step(opt_scale_vsplit_view, base->width);
2448 view->width = MAX(view->width, MIN_VIEW_WIDTH);
2449 view->width = MIN(view->width, base->width - MIN_VIEW_WIDTH);
2450 base->width -= view->width;
2453 static void
2454 redraw_display_separator(bool clear)
2456 if (displayed_views() > 1 && opt_vsplit) {
2457 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2459 if (clear)
2460 wclear(display_sep);
2461 wbkgd(display_sep, separator + get_line_attr(LINE_TITLE_BLUR));
2462 wnoutrefresh(display_sep);
2466 static void
2467 resize_display(void)
2469 int x, y, i;
2470 struct view *base = display[0];
2471 struct view *view = display[1] ? display[1] : display[0];
2473 /* Setup window dimensions */
2475 getmaxyx(stdscr, base->height, base->width);
2477 /* Make room for the status window. */
2478 base->height -= 1;
2480 if (view != base) {
2481 if (opt_vsplit) {
2482 apply_vertical_split(base, view);
2484 /* Make room for the separator bar. */
2485 view->width -= 1;
2486 } else {
2487 apply_horizontal_split(base, view);
2490 /* Make room for the title bar. */
2491 view->height -= 1;
2494 /* Make room for the title bar. */
2495 base->height -= 1;
2497 x = y = 0;
2499 foreach_displayed_view (view, i) {
2500 if (!display_win[i]) {
2501 display_win[i] = newwin(view->height, view->width, y, x);
2502 if (!display_win[i])
2503 die("Failed to create %s view", view->name);
2505 scrollok(display_win[i], FALSE);
2507 display_title[i] = newwin(1, view->width, y + view->height, x);
2508 if (!display_title[i])
2509 die("Failed to create title window");
2511 } else {
2512 wresize(display_win[i], view->height, view->width);
2513 mvwin(display_win[i], y, x);
2514 wresize(display_title[i], 1, view->width);
2515 mvwin(display_title[i], y + view->height, x);
2518 if (i > 0 && opt_vsplit) {
2519 if (!display_sep) {
2520 display_sep = newwin(view->height, 1, 0, x - 1);
2521 if (!display_sep)
2522 die("Failed to create separator window");
2524 } else {
2525 wresize(display_sep, view->height, 1);
2526 mvwin(display_sep, 0, x - 1);
2530 view->win = display_win[i];
2532 if (opt_vsplit)
2533 x += view->width + 1;
2534 else
2535 y += view->height + 1;
2538 redraw_display_separator(FALSE);
2541 static void
2542 redraw_display(bool clear)
2544 struct view *view;
2545 int i;
2547 foreach_displayed_view (view, i) {
2548 if (clear)
2549 wclear(view->win);
2550 redraw_view(view);
2551 update_view_title(view);
2554 redraw_display_separator(clear);
2558 * Option management
2561 #define TOGGLE_MENU \
2562 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2563 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2564 TOGGLE_(AUTHOR, 'A', "author", &opt_author, author_map) \
2565 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2566 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2567 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2568 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2569 TOGGLE_(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map) \
2570 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL) \
2571 TOGGLE_(CHANGES, 'C', "local change display", &opt_show_changes, NULL) \
2572 TOGGLE_(ID, 'X', "commit ID display", &opt_show_id, NULL) \
2573 TOGGLE_(FILES, '%', "file filtering", &opt_file_filter, NULL) \
2574 TOGGLE_(TITLE_OVERFLOW, '$', "commit title overflow display", &opt_show_title_overflow, NULL) \
2576 static bool
2577 toggle_option(struct view *view, enum request request, char msg[SIZEOF_STR])
2579 const struct {
2580 enum request request;
2581 const struct enum_map *map;
2582 size_t map_size;
2583 } data[] = {
2584 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, (map != NULL ? ARRAY_SIZE(map) : 0) },
2585 TOGGLE_MENU
2586 #undef TOGGLE_
2588 const struct menu_item menu[] = {
2589 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2590 TOGGLE_MENU
2591 #undef TOGGLE_
2592 { 0 }
2594 int i = 0;
2596 if (request == REQ_OPTIONS) {
2597 if (!prompt_menu("Toggle option", menu, &i))
2598 return FALSE;
2599 } else {
2600 while (i < ARRAY_SIZE(data) && data[i].request != request)
2601 i++;
2602 if (i >= ARRAY_SIZE(data))
2603 die("Invalid request (%d)", request);
2606 if (data[i].map != NULL) {
2607 unsigned int *opt = menu[i].data;
2609 *opt = (*opt + 1) % data[i].map_size;
2610 if (data[i].map == ignore_space_map) {
2611 update_ignore_space_arg();
2612 string_format_size(msg, SIZEOF_STR,
2613 "Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2614 return TRUE;
2616 } else if (data[i].map == commit_order_map) {
2617 update_commit_order_arg();
2618 string_format_size(msg, SIZEOF_STR,
2619 "Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2620 return TRUE;
2623 string_format_size(msg, SIZEOF_STR,
2624 "Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2626 } else {
2627 bool *option = menu[i].data;
2629 *option = !*option;
2630 string_format_size(msg, SIZEOF_STR,
2631 "%sabling %s", *option ? "En" : "Dis", menu[i].text);
2633 if (option == &opt_file_filter)
2634 return TRUE;
2637 return FALSE;
2642 * Navigation
2645 static bool
2646 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2648 if (lineno >= view->lines)
2649 lineno = view->lines > 0 ? view->lines - 1 : 0;
2651 if (offset > lineno || offset + view->height <= lineno) {
2652 unsigned long half = view->height / 2;
2654 if (lineno > half)
2655 offset = lineno - half;
2656 else
2657 offset = 0;
2660 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2661 view->pos.offset = offset;
2662 view->pos.lineno = lineno;
2663 return TRUE;
2666 return FALSE;
2669 /* Scrolling backend */
2670 static void
2671 do_scroll_view(struct view *view, int lines)
2673 bool redraw_current_line = FALSE;
2675 /* The rendering expects the new offset. */
2676 view->pos.offset += lines;
2678 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2679 assert(lines);
2681 /* Move current line into the view. */
2682 if (view->pos.lineno < view->pos.offset) {
2683 view->pos.lineno = view->pos.offset;
2684 redraw_current_line = TRUE;
2685 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2686 view->pos.lineno = view->pos.offset + view->height - 1;
2687 redraw_current_line = TRUE;
2690 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2692 /* Redraw the whole screen if scrolling is pointless. */
2693 if (view->height < ABS(lines)) {
2694 redraw_view(view);
2696 } else {
2697 int line = lines > 0 ? view->height - lines : 0;
2698 int end = line + ABS(lines);
2700 scrollok(view->win, TRUE);
2701 wscrl(view->win, lines);
2702 scrollok(view->win, FALSE);
2704 while (line < end && draw_view_line(view, line))
2705 line++;
2707 if (redraw_current_line)
2708 draw_view_line(view, view->pos.lineno - view->pos.offset);
2709 wnoutrefresh(view->win);
2712 view->has_scrolled = TRUE;
2713 report_clear();
2716 /* Scroll frontend */
2717 static void
2718 scroll_view(struct view *view, enum request request)
2720 int lines = 1;
2722 assert(view_is_displayed(view));
2724 switch (request) {
2725 case REQ_SCROLL_FIRST_COL:
2726 view->pos.col = 0;
2727 redraw_view_from(view, 0);
2728 report_clear();
2729 return;
2730 case REQ_SCROLL_LEFT:
2731 if (view->pos.col == 0) {
2732 report("Cannot scroll beyond the first column");
2733 return;
2735 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2736 view->pos.col = 0;
2737 else
2738 view->pos.col -= apply_step(opt_hscroll, view->width);
2739 redraw_view_from(view, 0);
2740 report_clear();
2741 return;
2742 case REQ_SCROLL_RIGHT:
2743 view->pos.col += apply_step(opt_hscroll, view->width);
2744 redraw_view(view);
2745 report_clear();
2746 return;
2747 case REQ_SCROLL_PAGE_DOWN:
2748 lines = view->height;
2749 case REQ_SCROLL_LINE_DOWN:
2750 if (view->pos.offset + lines > view->lines)
2751 lines = view->lines - view->pos.offset;
2753 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2754 report("Cannot scroll beyond the last line");
2755 return;
2757 break;
2759 case REQ_SCROLL_PAGE_UP:
2760 lines = view->height;
2761 case REQ_SCROLL_LINE_UP:
2762 if (lines > view->pos.offset)
2763 lines = view->pos.offset;
2765 if (lines == 0) {
2766 report("Cannot scroll beyond the first line");
2767 return;
2770 lines = -lines;
2771 break;
2773 default:
2774 die("request %d not handled in switch", request);
2777 do_scroll_view(view, lines);
2780 /* Cursor moving */
2781 static void
2782 move_view(struct view *view, enum request request)
2784 int scroll_steps = 0;
2785 int steps;
2787 switch (request) {
2788 case REQ_MOVE_FIRST_LINE:
2789 steps = -view->pos.lineno;
2790 break;
2792 case REQ_MOVE_LAST_LINE:
2793 steps = view->lines - view->pos.lineno - 1;
2794 break;
2796 case REQ_MOVE_PAGE_UP:
2797 steps = view->height > view->pos.lineno
2798 ? -view->pos.lineno : -view->height;
2799 break;
2801 case REQ_MOVE_PAGE_DOWN:
2802 steps = view->pos.lineno + view->height >= view->lines
2803 ? view->lines - view->pos.lineno - 1 : view->height;
2804 break;
2806 case REQ_MOVE_UP:
2807 case REQ_PREVIOUS:
2808 steps = -1;
2809 break;
2811 case REQ_MOVE_DOWN:
2812 case REQ_NEXT:
2813 steps = 1;
2814 break;
2816 default:
2817 die("request %d not handled in switch", request);
2820 if (steps <= 0 && view->pos.lineno == 0) {
2821 report("Cannot move beyond the first line");
2822 return;
2824 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2825 report("Cannot move beyond the last line");
2826 return;
2829 /* Move the current line */
2830 view->pos.lineno += steps;
2831 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2833 /* Check whether the view needs to be scrolled */
2834 if (view->pos.lineno < view->pos.offset ||
2835 view->pos.lineno >= view->pos.offset + view->height) {
2836 scroll_steps = steps;
2837 if (steps < 0 && -steps > view->pos.offset) {
2838 scroll_steps = -view->pos.offset;
2840 } else if (steps > 0) {
2841 if (view->pos.lineno == view->lines - 1 &&
2842 view->lines > view->height) {
2843 scroll_steps = view->lines - view->pos.offset - 1;
2844 if (scroll_steps >= view->height)
2845 scroll_steps -= view->height - 1;
2850 if (!view_is_displayed(view)) {
2851 view->pos.offset += scroll_steps;
2852 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2853 view->ops->select(view, &view->line[view->pos.lineno]);
2854 return;
2857 /* Repaint the old "current" line if we be scrolling */
2858 if (ABS(steps) < view->height)
2859 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2861 if (scroll_steps) {
2862 do_scroll_view(view, scroll_steps);
2863 return;
2866 /* Draw the current line */
2867 draw_view_line(view, view->pos.lineno - view->pos.offset);
2869 wnoutrefresh(view->win);
2870 report_clear();
2875 * Searching
2878 static void search_view(struct view *view, enum request request);
2880 static bool
2881 grep_text(struct view *view, const char *text[])
2883 regmatch_t pmatch;
2884 size_t i;
2886 for (i = 0; text[i]; i++)
2887 if (*text[i] &&
2888 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2889 return TRUE;
2890 return FALSE;
2893 static void
2894 select_view_line(struct view *view, unsigned long lineno)
2896 struct position old = view->pos;
2898 if (goto_view_line(view, view->pos.offset, lineno)) {
2899 if (view_is_displayed(view)) {
2900 if (old.offset != view->pos.offset) {
2901 redraw_view(view);
2902 } else {
2903 draw_view_line(view, old.lineno - view->pos.offset);
2904 draw_view_line(view, view->pos.lineno - view->pos.offset);
2905 wnoutrefresh(view->win);
2907 } else {
2908 view->ops->select(view, &view->line[view->pos.lineno]);
2913 static void
2914 find_next(struct view *view, enum request request)
2916 unsigned long lineno = view->pos.lineno;
2917 int direction;
2919 if (!*view->grep) {
2920 if (!*opt_search)
2921 report("No previous search");
2922 else
2923 search_view(view, request);
2924 return;
2927 switch (request) {
2928 case REQ_SEARCH:
2929 case REQ_FIND_NEXT:
2930 direction = 1;
2931 break;
2933 case REQ_SEARCH_BACK:
2934 case REQ_FIND_PREV:
2935 direction = -1;
2936 break;
2938 default:
2939 return;
2942 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2943 lineno += direction;
2945 /* Note, lineno is unsigned long so will wrap around in which case it
2946 * will become bigger than view->lines. */
2947 for (; lineno < view->lines; lineno += direction) {
2948 if (view->ops->grep(view, &view->line[lineno])) {
2949 select_view_line(view, lineno);
2950 report("Line %ld matches '%s'", lineno + 1, view->grep);
2951 return;
2955 report("No match found for '%s'", view->grep);
2958 static void
2959 search_view(struct view *view, enum request request)
2961 int regex_err;
2962 int regex_flags = opt_ignore_case ? REG_ICASE : 0;
2964 if (view->regex) {
2965 regfree(view->regex);
2966 *view->grep = 0;
2967 } else {
2968 view->regex = calloc(1, sizeof(*view->regex));
2969 if (!view->regex)
2970 return;
2973 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED | regex_flags);
2974 if (regex_err != 0) {
2975 char buf[SIZEOF_STR] = "unknown error";
2977 regerror(regex_err, view->regex, buf, sizeof(buf));
2978 report("Search failed: %s", buf);
2979 return;
2982 string_copy(view->grep, opt_search);
2984 find_next(view, request);
2988 * Incremental updating
2991 static inline bool
2992 check_position(struct position *pos)
2994 return pos->lineno || pos->col || pos->offset;
2997 static inline void
2998 clear_position(struct position *pos)
3000 memset(pos, 0, sizeof(*pos));
3003 static void
3004 reset_view(struct view *view)
3006 int i;
3008 for (i = 0; i < view->lines; i++)
3009 if (!view->line[i].dont_free)
3010 free(view->line[i].data);
3011 free(view->line);
3013 view->prev_pos = view->pos;
3014 clear_position(&view->pos);
3016 view->line = NULL;
3017 view->lines = 0;
3018 view->vid[0] = 0;
3019 view->custom_lines = 0;
3020 view->update_secs = 0;
3023 struct format_context {
3024 struct view *view;
3025 char buf[SIZEOF_STR];
3026 size_t bufpos;
3027 bool file_filter;
3030 static bool
3031 format_expand_arg(struct format_context *format, const char *name)
3033 static struct {
3034 const char *name;
3035 size_t namelen;
3036 const char *value;
3037 const char *value_if_empty;
3038 } vars[] = {
3039 #define FORMAT_VAR(name, value, value_if_empty) \
3040 { name, STRING_SIZE(name), value, value_if_empty }
3041 FORMAT_VAR("%(directory)", opt_path, "."),
3042 FORMAT_VAR("%(file)", opt_file, ""),
3043 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
3044 FORMAT_VAR("%(head)", ref_head, ""),
3045 FORMAT_VAR("%(commit)", ref_commit, ""),
3046 FORMAT_VAR("%(blob)", ref_blob, ""),
3047 FORMAT_VAR("%(branch)", ref_branch, ""),
3049 int i;
3051 if (!prefixcmp(name, "%(prompt")) {
3052 const char *value = read_prompt("Command argument: ");
3054 return string_format_from(format->buf, &format->bufpos, "%s", value);
3057 if (!prefixcmp(name, "%(width)"))
3058 return string_format_from(format->buf, &format->bufpos, "%d", format->view->width);
3060 for (i = 0; i < ARRAY_SIZE(vars); i++) {
3061 const char *value;
3063 if (strncmp(name, vars[i].name, vars[i].namelen))
3064 continue;
3066 if (vars[i].value == opt_file && !format->file_filter)
3067 return TRUE;
3069 value = *vars[i].value ? vars[i].value : vars[i].value_if_empty;
3070 if (!*value)
3071 return TRUE;
3073 return string_format_from(format->buf, &format->bufpos, "%s", value);
3076 report("Unknown replacement: `%s`", name);
3077 return NULL;
3080 static bool
3081 format_append_arg(struct format_context *format, const char ***dst_argv, const char *arg)
3083 format->bufpos = 0;
3085 while (arg) {
3086 char *next = strstr(arg, "%(");
3087 int len = next ? next - arg : strlen(arg);
3089 if (len && !string_format_from(format->buf, &format->bufpos, "%.*s", len, arg))
3090 return FALSE;
3092 if (next && !format_expand_arg(format, next))
3093 return FALSE;
3095 arg = next ? strchr(next, ')') + 1 : NULL;
3098 return argv_append(dst_argv, format->buf);
3101 static bool
3102 format_append_argv(struct format_context *format, const char ***dst_argv, const char *src_argv[])
3104 int argc;
3106 if (!src_argv)
3107 return TRUE;
3109 for (argc = 0; src_argv[argc]; argc++)
3110 if (!format_append_arg(format, dst_argv, src_argv[argc]))
3111 return FALSE;
3113 return src_argv[argc] == NULL;
3116 static bool
3117 format_argv(struct view *view, const char ***dst_argv, const char *src_argv[], bool first, bool file_filter)
3119 struct format_context format = { view, "", 0, file_filter };
3120 int argc;
3122 argv_free(*dst_argv);
3124 for (argc = 0; src_argv[argc]; argc++) {
3125 const char *arg = src_argv[argc];
3127 if (!strcmp(arg, "%(fileargs)")) {
3128 if (file_filter && !argv_append_array(dst_argv, opt_file_argv))
3129 break;
3131 } else if (!strcmp(arg, "%(diffargs)")) {
3132 if (!format_append_argv(&format, dst_argv, opt_diff_argv))
3133 break;
3135 } else if (!strcmp(arg, "%(blameargs)")) {
3136 if (!format_append_argv(&format, dst_argv, opt_blame_argv))
3137 break;
3139 } else if (!strcmp(arg, "%(revargs)") ||
3140 (first && !strcmp(arg, "%(commit)"))) {
3141 if (!argv_append_array(dst_argv, opt_file_argv))
3142 break;
3144 } else if (!format_append_arg(&format, dst_argv, arg)) {
3145 break;
3149 return src_argv[argc] == NULL;
3152 static bool
3153 restore_view_position(struct view *view)
3155 /* A view without a previous view is the first view */
3156 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
3157 select_view_line(view, opt_lineno - 1);
3158 opt_lineno = 0;
3161 /* Ensure that the view position is in a valid state. */
3162 if (!check_position(&view->prev_pos) ||
3163 (view->pipe && view->lines <= view->prev_pos.lineno))
3164 return goto_view_line(view, view->pos.offset, view->pos.lineno);
3166 /* Changing the view position cancels the restoring. */
3167 /* FIXME: Changing back to the first line is not detected. */
3168 if (check_position(&view->pos)) {
3169 clear_position(&view->prev_pos);
3170 return FALSE;
3173 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
3174 view_is_displayed(view))
3175 werase(view->win);
3177 view->pos.col = view->prev_pos.col;
3178 clear_position(&view->prev_pos);
3180 return TRUE;
3183 static void
3184 end_update(struct view *view, bool force)
3186 if (!view->pipe)
3187 return;
3188 while (!view->ops->read(view, NULL))
3189 if (!force)
3190 return;
3191 if (force)
3192 io_kill(view->pipe);
3193 io_done(view->pipe);
3194 view->pipe = NULL;
3197 static void
3198 setup_update(struct view *view, const char *vid)
3200 reset_view(view);
3201 /* XXX: Do not use string_copy_rev(), it copies until first space. */
3202 string_ncopy(view->vid, vid, strlen(vid));
3203 view->pipe = &view->io;
3204 view->start_time = time(NULL);
3207 static bool
3208 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
3210 bool use_stdin = view_has_flags(view, VIEW_STDIN) && opt_stdin;
3211 bool extra = !!(flags & (OPEN_EXTRA));
3212 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
3213 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
3214 enum io_type io_type = use_stdin ? IO_RD_STDIN : IO_RD;
3216 opt_stdin = FALSE;
3218 if ((!reload && !strcmp(view->vid, view->id)) ||
3219 ((flags & OPEN_REFRESH) && view->unrefreshable))
3220 return TRUE;
3222 if (view->pipe) {
3223 if (extra)
3224 io_done(view->pipe);
3225 else
3226 end_update(view, TRUE);
3229 view->unrefreshable = use_stdin;
3231 if (!refresh && argv) {
3232 bool file_filter = !view_has_flags(view, VIEW_FILE_FILTER) || opt_file_filter;
3234 view->dir = dir;
3235 if (!format_argv(view, &view->argv, argv, !view->prev, file_filter)) {
3236 report("Failed to format %s arguments", view->name);
3237 return FALSE;
3240 /* Put the current ref_* value to the view title ref
3241 * member. This is needed by the blob view. Most other
3242 * views sets it automatically after loading because the
3243 * first line is a commit line. */
3244 string_copy_rev(view->ref, view->id);
3247 if (view->argv && view->argv[0] &&
3248 !io_run(&view->io, io_type, view->dir, view->argv)) {
3249 report("Failed to open %s view", view->name);
3250 return FALSE;
3253 if (!extra)
3254 setup_update(view, view->id);
3256 return TRUE;
3259 static bool
3260 update_view(struct view *view)
3262 char *line;
3263 /* Clear the view and redraw everything since the tree sorting
3264 * might have rearranged things. */
3265 bool redraw = view->lines == 0;
3266 bool can_read = TRUE;
3267 struct encoding *encoding = view->encoding ? view->encoding : opt_encoding;
3269 if (!view->pipe)
3270 return TRUE;
3272 if (!io_can_read(view->pipe, FALSE)) {
3273 if (view->lines == 0 && view_is_displayed(view)) {
3274 time_t secs = time(NULL) - view->start_time;
3276 if (secs > 1 && secs > view->update_secs) {
3277 if (view->update_secs == 0)
3278 redraw_view(view);
3279 update_view_title(view);
3280 view->update_secs = secs;
3283 return TRUE;
3286 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
3287 if (encoding) {
3288 line = encoding_convert(encoding, line);
3291 if (!view->ops->read(view, line)) {
3292 report("Allocation failure");
3293 end_update(view, TRUE);
3294 return FALSE;
3299 unsigned long lines = view->lines;
3300 int digits;
3302 for (digits = 0; lines; digits++)
3303 lines /= 10;
3305 /* Keep the displayed view in sync with line number scaling. */
3306 if (digits != view->digits) {
3307 view->digits = digits;
3308 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3309 redraw = TRUE;
3313 if (io_error(view->pipe)) {
3314 report("Failed to read: %s", io_strerror(view->pipe));
3315 end_update(view, TRUE);
3317 } else if (io_eof(view->pipe)) {
3318 end_update(view, FALSE);
3321 if (restore_view_position(view))
3322 redraw = TRUE;
3324 if (!view_is_displayed(view))
3325 return TRUE;
3327 if (redraw)
3328 redraw_view_from(view, 0);
3329 else
3330 redraw_view_dirty(view);
3332 /* Update the title _after_ the redraw so that if the redraw picks up a
3333 * commit reference in view->ref it'll be available here. */
3334 update_view_title(view);
3335 return TRUE;
3338 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3340 static struct line *
3341 add_line(struct view *view, const void *data, enum line_type type, size_t data_size, bool custom)
3343 struct line *line;
3345 if (!realloc_lines(&view->line, view->lines, 1))
3346 return NULL;
3348 if (data_size) {
3349 void *alloc_data = calloc(1, data_size);
3351 if (!alloc_data)
3352 return NULL;
3354 if (data)
3355 memcpy(alloc_data, data, data_size);
3356 data = alloc_data;
3359 line = &view->line[view->lines++];
3360 memset(line, 0, sizeof(*line));
3361 line->type = type;
3362 line->data = (void *) data;
3363 line->dirty = 1;
3365 if (custom)
3366 view->custom_lines++;
3367 else
3368 line->lineno = view->lines - view->custom_lines;
3370 return line;
3373 static struct line *
3374 add_line_alloc_(struct view *view, void **ptr, enum line_type type, size_t data_size, bool custom)
3376 struct line *line = add_line(view, NULL, type, data_size, custom);
3378 if (line)
3379 *ptr = line->data;
3380 return line;
3383 #define add_line_alloc(view, data_ptr, type, extra_size, custom) \
3384 add_line_alloc_(view, (void **) data_ptr, type, sizeof(**data_ptr) + extra_size, custom)
3386 static struct line *
3387 add_line_nodata(struct view *view, enum line_type type)
3389 return add_line(view, NULL, type, 0, FALSE);
3392 static struct line *
3393 add_line_static_data(struct view *view, const void *data, enum line_type type)
3395 struct line *line = add_line(view, data, type, 0, FALSE);
3397 if (line)
3398 line->dont_free = TRUE;
3399 return line;
3402 static struct line *
3403 add_line_text(struct view *view, const char *text, enum line_type type)
3405 return add_line(view, text, type, strlen(text) + 1, FALSE);
3408 static struct line * PRINTF_LIKE(3, 4)
3409 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3411 char buf[SIZEOF_STR];
3412 int retval;
3414 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3415 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3419 * View opening
3422 static void
3423 split_view(struct view *prev, struct view *view)
3425 display[1] = view;
3426 current_view = opt_focus_child ? 1 : 0;
3427 view->parent = prev;
3428 resize_display();
3430 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3431 /* Take the title line into account. */
3432 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3434 /* Scroll the view that was split if the current line is
3435 * outside the new limited view. */
3436 do_scroll_view(prev, lines);
3439 if (view != prev && view_is_displayed(prev)) {
3440 /* "Blur" the previous view. */
3441 update_view_title(prev);
3445 static void
3446 maximize_view(struct view *view, bool redraw)
3448 memset(display, 0, sizeof(display));
3449 current_view = 0;
3450 display[current_view] = view;
3451 resize_display();
3452 if (redraw) {
3453 redraw_display(FALSE);
3454 report_clear();
3458 static void
3459 load_view(struct view *view, struct view *prev, enum open_flags flags)
3461 if (view->pipe)
3462 end_update(view, TRUE);
3463 if (view->ops->private_size) {
3464 if (!view->private)
3465 view->private = calloc(1, view->ops->private_size);
3466 else
3467 memset(view->private, 0, view->ops->private_size);
3470 /* When prev == view it means this is the first loaded view. */
3471 if (prev && view != prev) {
3472 view->prev = prev;
3475 if (!view->ops->open(view, flags))
3476 return;
3478 if (prev) {
3479 bool split = !!(flags & OPEN_SPLIT);
3481 if (split) {
3482 split_view(prev, view);
3483 } else {
3484 maximize_view(view, FALSE);
3488 restore_view_position(view);
3490 if (view->pipe && view->lines == 0) {
3491 /* Clear the old view and let the incremental updating refill
3492 * the screen. */
3493 werase(view->win);
3494 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3495 clear_position(&view->prev_pos);
3496 report_clear();
3497 } else if (view_is_displayed(view)) {
3498 redraw_view(view);
3499 report_clear();
3503 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3504 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3506 static void
3507 open_view(struct view *prev, enum request request, enum open_flags flags)
3509 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3510 struct view *view = VIEW(request);
3511 int nviews = displayed_views();
3513 assert(flags ^ OPEN_REFRESH);
3515 if (view == prev && nviews == 1 && !reload) {
3516 report("Already in %s view", view->name);
3517 return;
3520 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3521 report("The %s view is disabled in pager view", view->name);
3522 return;
3525 load_view(view, prev ? prev : view, flags);
3528 static void
3529 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3531 enum request request = view - views + REQ_OFFSET + 1;
3533 if (view->pipe)
3534 end_update(view, TRUE);
3535 view->dir = dir;
3537 if (!argv_copy(&view->argv, argv)) {
3538 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3539 } else {
3540 open_view(prev, request, flags | OPEN_PREPARED);
3544 static bool
3545 open_external_viewer(const char *argv[], const char *dir, bool confirm, const char *notice)
3547 bool ok;
3549 def_prog_mode(); /* save current tty modes */
3550 endwin(); /* restore original tty modes */
3551 ok = io_run_fg(argv, dir);
3552 if (confirm) {
3553 if (!ok && *notice)
3554 fprintf(stderr, "%s", notice);
3555 fprintf(stderr, "Press Enter to continue");
3556 getc(opt_tty);
3558 reset_prog_mode();
3559 redraw_display(TRUE);
3560 return ok;
3563 static void
3564 open_mergetool(const char *file)
3566 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3568 open_external_viewer(mergetool_argv, opt_cdup, TRUE, "");
3571 #define EDITOR_LINENO_MSG \
3572 "*** Your editor reported an error while opening the file.\n" \
3573 "*** This is probably because it doesn't support the line\n" \
3574 "*** number argument added automatically. The line number\n" \
3575 "*** has been disabled for now. You can permanently disable\n" \
3576 "*** it by adding the following line to ~/.tigrc\n" \
3577 "*** set editor-line-number = no\n"
3579 static void
3580 open_editor(const char *file, unsigned int lineno)
3582 const char *editor_argv[SIZEOF_ARG + 3] = { "vi", file, NULL };
3583 char editor_cmd[SIZEOF_STR];
3584 char lineno_cmd[SIZEOF_STR];
3585 const char *editor;
3586 int argc = 0;
3588 editor = getenv("GIT_EDITOR");
3589 if (!editor && *opt_editor)
3590 editor = opt_editor;
3591 if (!editor)
3592 editor = getenv("VISUAL");
3593 if (!editor)
3594 editor = getenv("EDITOR");
3595 if (!editor)
3596 editor = "vi";
3598 string_ncopy(editor_cmd, editor, strlen(editor));
3599 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3600 report("Failed to read editor command");
3601 return;
3604 if (lineno && opt_editor_lineno && string_format(lineno_cmd, "+%u", lineno))
3605 editor_argv[argc++] = lineno_cmd;
3606 editor_argv[argc] = file;
3607 if (!open_external_viewer(editor_argv, opt_cdup, TRUE, EDITOR_LINENO_MSG))
3608 opt_editor_lineno = FALSE;
3611 static enum request run_prompt_command(struct view *view, char *cmd);
3613 static enum request
3614 open_run_request(struct view *view, enum request request)
3616 struct run_request *req = get_run_request(request);
3617 const char **argv = NULL;
3619 request = REQ_NONE;
3621 if (!req) {
3622 report("Unknown run request");
3623 return request;
3626 if (format_argv(view, &argv, req->argv, FALSE, TRUE)) {
3627 if (req->internal) {
3628 char cmd[SIZEOF_STR];
3630 if (argv_to_string(argv, cmd, sizeof(cmd), " ")) {
3631 request = run_prompt_command(view, cmd);
3634 else {
3635 bool confirmed = !req->confirm;
3637 if (req->confirm) {
3638 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
3640 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
3641 string_format(prompt, "Run `%s`?", cmd) &&
3642 prompt_yesno(prompt)) {
3643 confirmed = TRUE;
3647 if (confirmed && argv_remove_quotes(argv)) {
3648 if (req->silent)
3649 io_run_bg(argv);
3650 else
3651 open_external_viewer(argv, NULL, !req->exit, "");
3656 if (argv)
3657 argv_free(argv);
3658 free(argv);
3660 if (request == REQ_NONE) {
3661 if (req->exit)
3662 request = REQ_QUIT;
3664 else if (!view->unrefreshable)
3665 request = REQ_REFRESH;
3667 return request;
3671 * User request switch noodle
3674 static int
3675 view_driver(struct view *view, enum request request)
3677 int i;
3679 if (request == REQ_NONE)
3680 return TRUE;
3682 if (request > REQ_NONE) {
3683 request = open_run_request(view, request);
3685 // exit quickly rather than going through view_request and back
3686 if (request == REQ_QUIT)
3687 return FALSE;
3690 request = view_request(view, request);
3691 if (request == REQ_NONE)
3692 return TRUE;
3694 switch (request) {
3695 case REQ_MOVE_UP:
3696 case REQ_MOVE_DOWN:
3697 case REQ_MOVE_PAGE_UP:
3698 case REQ_MOVE_PAGE_DOWN:
3699 case REQ_MOVE_FIRST_LINE:
3700 case REQ_MOVE_LAST_LINE:
3701 move_view(view, request);
3702 break;
3704 case REQ_SCROLL_FIRST_COL:
3705 case REQ_SCROLL_LEFT:
3706 case REQ_SCROLL_RIGHT:
3707 case REQ_SCROLL_LINE_DOWN:
3708 case REQ_SCROLL_LINE_UP:
3709 case REQ_SCROLL_PAGE_DOWN:
3710 case REQ_SCROLL_PAGE_UP:
3711 scroll_view(view, request);
3712 break;
3714 case REQ_VIEW_MAIN:
3715 case REQ_VIEW_DIFF:
3716 case REQ_VIEW_LOG:
3717 case REQ_VIEW_TREE:
3718 case REQ_VIEW_HELP:
3719 case REQ_VIEW_BRANCH:
3720 case REQ_VIEW_BLAME:
3721 case REQ_VIEW_BLOB:
3722 case REQ_VIEW_STATUS:
3723 case REQ_VIEW_STAGE:
3724 case REQ_VIEW_PAGER:
3725 open_view(view, request, OPEN_DEFAULT);
3726 break;
3728 case REQ_NEXT:
3729 case REQ_PREVIOUS:
3730 if (view->parent) {
3731 int line;
3733 view = view->parent;
3734 line = view->pos.lineno;
3735 move_view(view, request);
3736 if (view_is_displayed(view))
3737 update_view_title(view);
3738 if (line != view->pos.lineno)
3739 view_request(view, REQ_ENTER);
3740 } else {
3741 move_view(view, request);
3743 break;
3745 case REQ_VIEW_NEXT:
3747 int nviews = displayed_views();
3748 int next_view = (current_view + 1) % nviews;
3750 if (next_view == current_view) {
3751 report("Only one view is displayed");
3752 break;
3755 current_view = next_view;
3756 /* Blur out the title of the previous view. */
3757 update_view_title(view);
3758 report_clear();
3759 break;
3761 case REQ_REFRESH:
3762 report("Refreshing is not yet supported for the %s view", view->name);
3763 break;
3765 case REQ_MAXIMIZE:
3766 if (displayed_views() == 2)
3767 maximize_view(view, TRUE);
3768 break;
3770 case REQ_OPTIONS:
3771 case REQ_TOGGLE_LINENO:
3772 case REQ_TOGGLE_DATE:
3773 case REQ_TOGGLE_AUTHOR:
3774 case REQ_TOGGLE_FILENAME:
3775 case REQ_TOGGLE_GRAPHIC:
3776 case REQ_TOGGLE_REV_GRAPH:
3777 case REQ_TOGGLE_REFS:
3778 case REQ_TOGGLE_CHANGES:
3779 case REQ_TOGGLE_IGNORE_SPACE:
3780 case REQ_TOGGLE_ID:
3781 case REQ_TOGGLE_FILES:
3782 case REQ_TOGGLE_TITLE_OVERFLOW:
3784 char action[SIZEOF_STR] = "";
3785 bool reload = toggle_option(view, request, action);
3787 if (reload && view_has_flags(view, VIEW_DIFF_LIKE))
3788 reload_view(view);
3789 else
3790 redraw_display(FALSE);
3792 if (*action)
3793 report("%s", action);
3795 break;
3797 case REQ_TOGGLE_SORT_FIELD:
3798 case REQ_TOGGLE_SORT_ORDER:
3799 report("Sorting is not yet supported for the %s view", view->name);
3800 break;
3802 case REQ_DIFF_CONTEXT_UP:
3803 case REQ_DIFF_CONTEXT_DOWN:
3804 report("Changing the diff context is not yet supported for the %s view", view->name);
3805 break;
3807 case REQ_SEARCH:
3808 case REQ_SEARCH_BACK:
3809 search_view(view, request);
3810 break;
3812 case REQ_FIND_NEXT:
3813 case REQ_FIND_PREV:
3814 find_next(view, request);
3815 break;
3817 case REQ_STOP_LOADING:
3818 foreach_view(view, i) {
3819 if (view->pipe)
3820 report("Stopped loading the %s view", view->name),
3821 end_update(view, TRUE);
3823 break;
3825 case REQ_SHOW_VERSION:
3826 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3827 return TRUE;
3829 case REQ_SCREEN_REDRAW:
3830 redraw_display(TRUE);
3831 break;
3833 case REQ_EDIT:
3834 report("Nothing to edit");
3835 break;
3837 case REQ_ENTER:
3838 report("Nothing to enter");
3839 break;
3841 case REQ_VIEW_CLOSE:
3842 /* XXX: Mark closed views by letting view->prev point to the
3843 * view itself. Parents to closed view should never be
3844 * followed. */
3845 if (view->prev && view->prev != view) {
3846 maximize_view(view->prev, TRUE);
3847 view->prev = view;
3848 break;
3850 /* Fall-through */
3851 case REQ_QUIT:
3852 return FALSE;
3854 default:
3855 report("Unknown key, press %s for help",
3856 get_view_key(view, REQ_VIEW_HELP));
3857 return TRUE;
3860 return TRUE;
3865 * View backend utilities
3868 enum sort_field {
3869 ORDERBY_NAME,
3870 ORDERBY_DATE,
3871 ORDERBY_AUTHOR,
3874 struct sort_state {
3875 const enum sort_field *fields;
3876 size_t size, current;
3877 bool reverse;
3880 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3881 #define get_sort_field(state) ((state).fields[(state).current])
3882 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3884 static void
3885 sort_view(struct view *view, enum request request, struct sort_state *state,
3886 int (*compare)(const void *, const void *))
3888 switch (request) {
3889 case REQ_TOGGLE_SORT_FIELD:
3890 state->current = (state->current + 1) % state->size;
3891 break;
3893 case REQ_TOGGLE_SORT_ORDER:
3894 state->reverse = !state->reverse;
3895 break;
3896 default:
3897 die("Not a sort request");
3900 qsort(view->line, view->lines, sizeof(*view->line), compare);
3901 redraw_view(view);
3904 static bool
3905 update_diff_context(enum request request)
3907 int diff_context = opt_diff_context;
3909 switch (request) {
3910 case REQ_DIFF_CONTEXT_UP:
3911 opt_diff_context += 1;
3912 update_diff_context_arg(opt_diff_context);
3913 break;
3915 case REQ_DIFF_CONTEXT_DOWN:
3916 if (opt_diff_context == 0) {
3917 report("Diff context cannot be less than zero");
3918 break;
3920 opt_diff_context -= 1;
3921 update_diff_context_arg(opt_diff_context);
3922 break;
3924 default:
3925 die("Not a diff context request");
3928 return diff_context != opt_diff_context;
3931 DEFINE_ALLOCATOR(realloc_authors, struct ident *, 256)
3933 /* Small author cache to reduce memory consumption. It uses binary
3934 * search to lookup or find place to position new entries. No entries
3935 * are ever freed. */
3936 static struct ident *
3937 get_author(const char *name, const char *email)
3939 static struct ident **authors;
3940 static size_t authors_size;
3941 int from = 0, to = authors_size - 1;
3942 struct ident *ident;
3944 while (from <= to) {
3945 size_t pos = (to + from) / 2;
3946 int cmp = strcmp(name, authors[pos]->name);
3948 if (!cmp)
3949 return authors[pos];
3951 if (cmp < 0)
3952 to = pos - 1;
3953 else
3954 from = pos + 1;
3957 if (!realloc_authors(&authors, authors_size, 1))
3958 return NULL;
3959 ident = calloc(1, sizeof(*ident));
3960 if (!ident)
3961 return NULL;
3962 ident->name = strdup(name);
3963 ident->email = strdup(email);
3964 if (!ident->name || !ident->email) {
3965 free((void *) ident->name);
3966 free(ident);
3967 return NULL;
3970 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3971 authors[from] = ident;
3972 authors_size++;
3974 return ident;
3977 static void
3978 parse_timesec(struct time *time, const char *sec)
3980 time->sec = (time_t) atol(sec);
3983 static void
3984 parse_timezone(struct time *time, const char *zone)
3986 long tz;
3988 tz = ('0' - zone[1]) * 60 * 60 * 10;
3989 tz += ('0' - zone[2]) * 60 * 60;
3990 tz += ('0' - zone[3]) * 60 * 10;
3991 tz += ('0' - zone[4]) * 60;
3993 if (zone[0] == '-')
3994 tz = -tz;
3996 time->tz = tz;
3997 time->sec -= tz;
4000 /* Parse author lines where the name may be empty:
4001 * author <email@address.tld> 1138474660 +0100
4003 static void
4004 parse_author_line(char *ident, const struct ident **author, struct time *time)
4006 char *nameend = strchr(ident, '<');
4007 char *emailend = strchr(ident, '>');
4008 const char *name, *email = "";
4010 if (nameend && emailend)
4011 *nameend = *emailend = 0;
4012 name = chomp_string(ident);
4013 if (nameend)
4014 email = chomp_string(nameend + 1);
4015 if (!*name)
4016 name = *email ? email : unknown_ident.name;
4017 if (!*email)
4018 email = *name ? name : unknown_ident.email;
4020 *author = get_author(name, email);
4022 /* Parse epoch and timezone */
4023 if (time && emailend && emailend[1] == ' ') {
4024 char *secs = emailend + 2;
4025 char *zone = strchr(secs, ' ');
4027 parse_timesec(time, secs);
4029 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
4030 parse_timezone(time, zone + 1);
4034 static struct line *
4035 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
4037 for (; view_has_line(view, line); line += direction)
4038 if (line->type == type)
4039 return line;
4041 return NULL;
4044 #define find_prev_line_by_type(view, line, type) \
4045 find_line_by_type(view, line, type, -1)
4047 #define find_next_line_by_type(view, line, type) \
4048 find_line_by_type(view, line, type, 1)
4051 * Blame
4054 struct blame_commit {
4055 char id[SIZEOF_REV]; /* SHA1 ID. */
4056 char title[128]; /* First line of the commit message. */
4057 const struct ident *author; /* Author of the commit. */
4058 struct time time; /* Date from the author ident. */
4059 char filename[128]; /* Name of file. */
4060 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
4061 char parent_filename[128]; /* Parent/previous name of file. */
4064 struct blame_header {
4065 char id[SIZEOF_REV]; /* SHA1 ID. */
4066 size_t orig_lineno;
4067 size_t lineno;
4068 size_t group;
4071 static bool
4072 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4074 const char *pos = *posref;
4076 *posref = NULL;
4077 pos = strchr(pos + 1, ' ');
4078 if (!pos || !isdigit(pos[1]))
4079 return FALSE;
4080 *number = atoi(pos + 1);
4081 if (*number < min || *number > max)
4082 return FALSE;
4084 *posref = pos;
4085 return TRUE;
4088 static bool
4089 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
4091 const char *pos = text + SIZEOF_REV - 2;
4093 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4094 return FALSE;
4096 string_ncopy(header->id, text, SIZEOF_REV);
4098 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
4099 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
4100 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
4101 return FALSE;
4103 return TRUE;
4106 static bool
4107 match_blame_header(const char *name, char **line)
4109 size_t namelen = strlen(name);
4110 bool matched = !strncmp(name, *line, namelen);
4112 if (matched)
4113 *line += namelen;
4115 return matched;
4118 static bool
4119 parse_blame_info(struct blame_commit *commit, char *line)
4121 if (match_blame_header("author ", &line)) {
4122 parse_author_line(line, &commit->author, NULL);
4124 } else if (match_blame_header("author-time ", &line)) {
4125 parse_timesec(&commit->time, line);
4127 } else if (match_blame_header("author-tz ", &line)) {
4128 parse_timezone(&commit->time, line);
4130 } else if (match_blame_header("summary ", &line)) {
4131 string_ncopy(commit->title, line, strlen(line));
4133 } else if (match_blame_header("previous ", &line)) {
4134 if (strlen(line) <= SIZEOF_REV)
4135 return FALSE;
4136 string_copy_rev(commit->parent_id, line);
4137 line += SIZEOF_REV;
4138 string_ncopy(commit->parent_filename, line, strlen(line));
4140 } else if (match_blame_header("filename ", &line)) {
4141 string_ncopy(commit->filename, line, strlen(line));
4142 return TRUE;
4145 return FALSE;
4149 * Pager backend
4152 static bool
4153 pager_draw(struct view *view, struct line *line, unsigned int lineno)
4155 if (draw_lineno(view, lineno))
4156 return TRUE;
4158 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4159 return TRUE;
4161 draw_text(view, line->type, line->data);
4162 return TRUE;
4165 static bool
4166 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
4168 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
4169 char ref[SIZEOF_STR];
4171 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
4172 return TRUE;
4174 /* This is the only fatal call, since it can "corrupt" the buffer. */
4175 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
4176 return FALSE;
4178 return TRUE;
4181 static void
4182 add_pager_refs(struct view *view, const char *commit_id)
4184 char buf[SIZEOF_STR];
4185 struct ref_list *list;
4186 size_t bufpos = 0, i;
4187 const char *sep = "Refs: ";
4188 bool is_tag = FALSE;
4190 list = get_ref_list(commit_id);
4191 if (!list) {
4192 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
4193 goto try_add_describe_ref;
4194 return;
4197 for (i = 0; i < list->size; i++) {
4198 struct ref *ref = list->refs[i];
4199 const char *fmt = ref->tag ? "%s[%s]" :
4200 ref->remote ? "%s<%s>" : "%s%s";
4202 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
4203 return;
4204 sep = ", ";
4205 if (ref->tag)
4206 is_tag = TRUE;
4209 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
4210 try_add_describe_ref:
4211 /* Add <tag>-g<commit_id> "fake" reference. */
4212 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
4213 return;
4216 if (bufpos == 0)
4217 return;
4219 add_line_text(view, buf, LINE_PP_REFS);
4222 static struct line *
4223 pager_wrap_line(struct view *view, const char *data, enum line_type type)
4225 size_t first_line = 0;
4226 bool has_first_line = FALSE;
4227 size_t datalen = strlen(data);
4228 size_t lineno = 0;
4230 while (datalen > 0 || !has_first_line) {
4231 bool wrapped = !!first_line;
4232 size_t linelen = string_expanded_length(data, datalen, opt_tab_size, view->width - !!wrapped);
4233 struct line *line;
4234 char *text;
4236 line = add_line(view, NULL, type, linelen + 1, wrapped);
4237 if (!line)
4238 break;
4239 if (!has_first_line) {
4240 first_line = view->lines - 1;
4241 has_first_line = TRUE;
4244 if (!wrapped)
4245 lineno = line->lineno;
4247 line->wrapped = wrapped;
4248 line->lineno = lineno;
4249 text = line->data;
4250 if (linelen)
4251 strncpy(text, data, linelen);
4252 text[linelen] = 0;
4254 datalen -= linelen;
4255 data += linelen;
4258 return has_first_line ? &view->line[first_line] : NULL;
4261 static bool
4262 pager_common_read(struct view *view, const char *data, enum line_type type)
4264 struct line *line;
4266 if (!data)
4267 return TRUE;
4269 if (opt_wrap_lines) {
4270 line = pager_wrap_line(view, data, type);
4271 } else {
4272 line = add_line_text(view, data, type);
4275 if (!line)
4276 return FALSE;
4278 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
4279 add_pager_refs(view, data + STRING_SIZE("commit "));
4281 return TRUE;
4284 static bool
4285 pager_read(struct view *view, char *data)
4287 if (!data)
4288 return TRUE;
4290 return pager_common_read(view, data, get_line_type(data));
4293 static enum request
4294 pager_request(struct view *view, enum request request, struct line *line)
4296 int split = 0;
4298 if (request != REQ_ENTER)
4299 return request;
4301 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
4302 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4303 split = 1;
4306 /* Always scroll the view even if it was split. That way
4307 * you can use Enter to scroll through the log view and
4308 * split open each commit diff. */
4309 scroll_view(view, REQ_SCROLL_LINE_DOWN);
4311 /* FIXME: A minor workaround. Scrolling the view will call report_clear()
4312 * but if we are scrolling a non-current view this won't properly
4313 * update the view title. */
4314 if (split)
4315 update_view_title(view);
4317 return REQ_NONE;
4320 static bool
4321 pager_grep(struct view *view, struct line *line)
4323 const char *text[] = { line->data, NULL };
4325 return grep_text(view, text);
4328 static void
4329 pager_select(struct view *view, struct line *line)
4331 if (line->type == LINE_COMMIT) {
4332 char *text = (char *)line->data + STRING_SIZE("commit ");
4334 if (!view_has_flags(view, VIEW_NO_REF))
4335 string_copy_rev(view->ref, text);
4336 string_copy_rev(ref_commit, text);
4340 static bool
4341 pager_open(struct view *view, enum open_flags flags)
4343 if (display[0] == NULL) {
4344 if (!io_open(&view->io, "%s", ""))
4345 die("Failed to open stdin");
4346 flags = OPEN_PREPARED;
4348 } else if (!view->pipe && !view->lines && !(flags & OPEN_PREPARED)) {
4349 report("No pager content, press %s to run command from prompt",
4350 get_view_key(view, REQ_PROMPT));
4351 return FALSE;
4354 return begin_update(view, NULL, NULL, flags);
4357 static struct view_ops pager_ops = {
4358 "line",
4359 { "pager" },
4360 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
4362 pager_open,
4363 pager_read,
4364 pager_draw,
4365 pager_request,
4366 pager_grep,
4367 pager_select,
4370 static bool
4371 log_open(struct view *view, enum open_flags flags)
4373 static const char *log_argv[] = {
4374 "git", "log", opt_encoding_arg, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
4377 return begin_update(view, NULL, log_argv, flags);
4380 static enum request
4381 log_request(struct view *view, enum request request, struct line *line)
4383 switch (request) {
4384 case REQ_REFRESH:
4385 load_refs();
4386 refresh_view(view);
4387 return REQ_NONE;
4388 default:
4389 return pager_request(view, request, line);
4393 static struct view_ops log_ops = {
4394 "line",
4395 { "log" },
4396 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF | VIEW_SEND_CHILD_ENTER,
4398 log_open,
4399 pager_read,
4400 pager_draw,
4401 log_request,
4402 pager_grep,
4403 pager_select,
4406 struct diff_state {
4407 bool after_commit_title;
4408 bool reading_diff_stat;
4409 bool combined_diff;
4412 #define DIFF_LINE_COMMIT_TITLE 1
4414 static bool
4415 diff_open(struct view *view, enum open_flags flags)
4417 static const char *diff_argv[] = {
4418 "git", "show", opt_encoding_arg, "--pretty=fuller", "--no-color", "--root",
4419 "--patch", "--stat=%(width)",
4420 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
4421 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
4424 return begin_update(view, NULL, diff_argv, flags);
4427 static bool
4428 diff_common_read(struct view *view, const char *data, struct diff_state *state)
4430 enum line_type type = get_line_type(data);
4432 if (!view->lines && type != LINE_COMMIT)
4433 state->reading_diff_stat = TRUE;
4435 if (state->reading_diff_stat) {
4436 size_t len = strlen(data);
4437 char *pipe = strchr(data, '|');
4438 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
4439 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
4440 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
4442 if (pipe && (has_histogram || has_bin_diff || has_rename)) {
4443 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
4444 } else {
4445 state->reading_diff_stat = FALSE;
4448 } else if (!strcmp(data, "---")) {
4449 state->reading_diff_stat = TRUE;
4452 if (!state->after_commit_title && !prefixcmp(data, " ")) {
4453 struct line *line = add_line_text(view, data, LINE_COMMIT);
4455 if (line)
4456 line->user_flags |= DIFF_LINE_COMMIT_TITLE;
4457 state->after_commit_title = TRUE;
4458 return line != NULL;
4461 if (type == LINE_DIFF_HEADER) {
4462 const int len = line_info[LINE_DIFF_HEADER].linelen;
4464 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4465 !strncmp(data + len, "cc ", strlen("cc ")))
4466 state->combined_diff = TRUE;
4469 /* ADD2 and DEL2 are only valid in combined diff hunks */
4470 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4471 type = LINE_DEFAULT;
4473 return pager_common_read(view, data, type);
4476 static bool
4477 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
4479 struct line *marker = find_next_line_by_type(view, line, type);
4481 return marker &&
4482 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
4485 static enum request
4486 diff_common_enter(struct view *view, enum request request, struct line *line)
4488 if (line->type == LINE_DIFF_STAT) {
4489 int file_number = 0;
4491 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4492 file_number++;
4493 line--;
4496 for (line = view->line; view_has_line(view, line); line++) {
4497 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4498 if (!line)
4499 break;
4501 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4502 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4503 if (file_number == 1) {
4504 break;
4506 file_number--;
4510 if (!line) {
4511 report("Failed to find file diff");
4512 return REQ_NONE;
4515 select_view_line(view, line - view->line);
4516 report_clear();
4517 return REQ_NONE;
4519 } else {
4520 return pager_request(view, request, line);
4524 static bool
4525 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4527 char *sep = strchr(*text, c);
4529 if (sep != NULL) {
4530 *sep = 0;
4531 draw_text(view, *type, *text);
4532 *sep = c;
4533 *text = sep;
4534 *type = next_type;
4537 return sep != NULL;
4540 static bool
4541 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4543 char *text = line->data;
4544 enum line_type type = line->type;
4546 if (draw_lineno(view, lineno))
4547 return TRUE;
4549 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4550 return TRUE;
4552 if (type == LINE_DIFF_STAT) {
4553 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4554 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4555 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4556 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4557 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4558 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4559 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4561 } else {
4562 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4563 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4567 if (line->user_flags & DIFF_LINE_COMMIT_TITLE)
4568 draw_commit_title(view, text, 4);
4569 else
4570 draw_text(view, type, text);
4571 return TRUE;
4574 static bool
4575 diff_read(struct view *view, char *data)
4577 struct diff_state *state = view->private;
4579 if (!data) {
4580 /* Fall back to retry if no diff will be shown. */
4581 if (view->lines == 0 && opt_file_argv) {
4582 int pos = argv_size(view->argv)
4583 - argv_size(opt_file_argv) - 1;
4585 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4586 for (; view->argv[pos]; pos++) {
4587 free((void *) view->argv[pos]);
4588 view->argv[pos] = NULL;
4591 if (view->pipe)
4592 io_done(view->pipe);
4593 if (io_run(&view->io, IO_RD, view->dir, view->argv))
4594 return FALSE;
4597 return TRUE;
4600 return diff_common_read(view, data, state);
4603 static bool
4604 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4605 struct blame_header *header, struct blame_commit *commit)
4607 char line_arg[SIZEOF_STR];
4608 const char *blame_argv[] = {
4609 "git", "blame", opt_encoding_arg, "-p", line_arg, ref, "--", file, NULL
4611 struct io io;
4612 bool ok = FALSE;
4613 char *buf;
4615 if (!string_format(line_arg, "-L%ld,+1", lineno))
4616 return FALSE;
4618 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
4619 return FALSE;
4621 while ((buf = io_get(&io, '\n', TRUE))) {
4622 if (header) {
4623 if (!parse_blame_header(header, buf, 9999999))
4624 break;
4625 header = NULL;
4627 } else if (parse_blame_info(commit, buf)) {
4628 ok = TRUE;
4629 break;
4633 if (io_error(&io))
4634 ok = FALSE;
4636 io_done(&io);
4637 return ok;
4640 static unsigned int
4641 diff_get_lineno(struct view *view, struct line *line)
4643 const struct line *header, *chunk;
4644 const char *data;
4645 unsigned int lineno;
4647 /* Verify that we are after a diff header and one of its chunks */
4648 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4649 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4650 if (!header || !chunk || chunk < header)
4651 return 0;
4654 * In a chunk header, the number after the '+' sign is the number of its
4655 * following line, in the new version of the file. We increment this
4656 * number for each non-deletion line, until the given line position.
4658 data = strchr(chunk->data, '+');
4659 if (!data)
4660 return 0;
4662 lineno = atoi(data);
4663 chunk++;
4664 while (chunk++ < line)
4665 if (chunk->type != LINE_DIFF_DEL)
4666 lineno++;
4668 return lineno;
4671 static bool
4672 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4674 return prefixcmp(chunk, "@@ -") ||
4675 !(chunk = strchr(chunk, marker)) ||
4676 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4679 static enum request
4680 diff_trace_origin(struct view *view, struct line *line)
4682 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4683 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4684 const char *chunk_data;
4685 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4686 int lineno = 0;
4687 const char *file = NULL;
4688 char ref[SIZEOF_REF];
4689 struct blame_header header;
4690 struct blame_commit commit;
4692 if (!diff || !chunk || chunk == line) {
4693 report("The line to trace must be inside a diff chunk");
4694 return REQ_NONE;
4697 for (; diff < line && !file; diff++) {
4698 const char *data = diff->data;
4700 if (!prefixcmp(data, "--- a/")) {
4701 file = data + STRING_SIZE("--- a/");
4702 break;
4706 if (diff == line || !file) {
4707 report("Failed to read the file name");
4708 return REQ_NONE;
4711 chunk_data = chunk->data;
4713 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4714 report("Failed to read the line number");
4715 return REQ_NONE;
4718 if (lineno == 0) {
4719 report("This is the origin of the line");
4720 return REQ_NONE;
4723 for (chunk += 1; chunk < line; chunk++) {
4724 if (chunk->type == LINE_DIFF_ADD) {
4725 lineno += chunk_marker == '+';
4726 } else if (chunk->type == LINE_DIFF_DEL) {
4727 lineno += chunk_marker == '-';
4728 } else {
4729 lineno++;
4733 if (chunk_marker == '+')
4734 string_copy(ref, view->vid);
4735 else
4736 string_format(ref, "%s^", view->vid);
4738 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4739 report("Failed to read blame data");
4740 return REQ_NONE;
4743 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4744 string_copy(opt_ref, header.id);
4745 opt_goto_line = header.orig_lineno - 1;
4747 return REQ_VIEW_BLAME;
4750 static const char *
4751 diff_get_pathname(struct view *view, struct line *line)
4753 const struct line *header;
4754 const char *dst = NULL;
4755 const char *prefixes[] = { " b/", "cc ", "combined " };
4756 int i;
4758 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4759 if (!header)
4760 return NULL;
4762 for (i = 0; i < ARRAY_SIZE(prefixes) && !dst; i++)
4763 dst = strstr(header->data, prefixes[i]);
4765 return dst ? dst + strlen(prefixes[--i]) : NULL;
4768 static enum request
4769 diff_request(struct view *view, enum request request, struct line *line)
4771 const char *file;
4773 switch (request) {
4774 case REQ_VIEW_BLAME:
4775 return diff_trace_origin(view, line);
4777 case REQ_DIFF_CONTEXT_UP:
4778 case REQ_DIFF_CONTEXT_DOWN:
4779 if (!update_diff_context(request))
4780 return REQ_NONE;
4781 reload_view(view);
4782 return REQ_NONE;
4785 case REQ_EDIT:
4786 file = diff_get_pathname(view, line);
4787 if (!file || access(file, R_OK))
4788 return pager_request(view, request, line);
4789 open_editor(file, diff_get_lineno(view, line));
4790 return REQ_NONE;
4792 case REQ_ENTER:
4793 return diff_common_enter(view, request, line);
4795 case REQ_REFRESH:
4796 reload_view(view);
4797 return REQ_NONE;
4799 default:
4800 return pager_request(view, request, line);
4804 static void
4805 diff_select(struct view *view, struct line *line)
4807 if (line->type == LINE_DIFF_STAT) {
4808 string_format(view->ref, "Press '%s' to jump to file diff",
4809 get_view_key(view, REQ_ENTER));
4810 } else {
4811 const char *file = diff_get_pathname(view, line);
4813 if (file) {
4814 string_format(view->ref, "Changes to '%s'", file);
4815 string_format(opt_file, "%s", file);
4816 ref_blob[0] = 0;
4817 } else {
4818 string_ncopy(view->ref, view->id, strlen(view->id));
4819 pager_select(view, line);
4824 static struct view_ops diff_ops = {
4825 "line",
4826 { "diff" },
4827 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS | VIEW_STDIN | VIEW_FILE_FILTER,
4828 sizeof(struct diff_state),
4829 diff_open,
4830 diff_read,
4831 diff_common_draw,
4832 diff_request,
4833 pager_grep,
4834 diff_select,
4838 * Help backend
4841 static bool
4842 help_draw(struct view *view, struct line *line, unsigned int lineno)
4844 if (line->type == LINE_HELP_KEYMAP) {
4845 struct keymap *keymap = line->data;
4847 draw_formatted(view, line->type, "[%c] %s bindings",
4848 keymap->hidden ? '+' : '-', keymap->name);
4849 return TRUE;
4850 } else {
4851 return pager_draw(view, line, lineno);
4855 static bool
4856 help_open_keymap_title(struct view *view, struct keymap *keymap)
4858 add_line_static_data(view, keymap, LINE_HELP_KEYMAP);
4859 return keymap->hidden;
4862 static void
4863 help_open_keymap(struct view *view, struct keymap *keymap)
4865 const char *group = NULL;
4866 char buf[SIZEOF_STR];
4867 bool add_title = TRUE;
4868 int i;
4870 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4871 const char *key = NULL;
4873 if (req_info[i].request == REQ_NONE)
4874 continue;
4876 if (!req_info[i].request) {
4877 group = req_info[i].help;
4878 continue;
4881 key = get_keys(keymap, req_info[i].request, TRUE);
4882 if (!key || !*key)
4883 continue;
4885 if (add_title && help_open_keymap_title(view, keymap))
4886 return;
4887 add_title = FALSE;
4889 if (group) {
4890 add_line_text(view, group, LINE_HELP_GROUP);
4891 group = NULL;
4894 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4895 enum_name(req_info[i]), req_info[i].help);
4898 group = "External commands:";
4900 for (i = 0; i < run_requests; i++) {
4901 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4902 const char *key;
4904 if (!req || req->keymap != keymap)
4905 continue;
4907 key = get_key_name(req->key);
4908 if (!*key)
4909 key = "(no key defined)";
4911 if (add_title && help_open_keymap_title(view, keymap))
4912 return;
4913 add_title = FALSE;
4915 if (group) {
4916 add_line_text(view, group, LINE_HELP_GROUP);
4917 group = NULL;
4920 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
4921 return;
4923 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4927 static bool
4928 help_open(struct view *view, enum open_flags flags)
4930 struct keymap *keymap;
4932 reset_view(view);
4933 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4934 add_line_text(view, "", LINE_DEFAULT);
4936 for (keymap = keymaps; keymap; keymap = keymap->next)
4937 help_open_keymap(view, keymap);
4939 return TRUE;
4942 static enum request
4943 help_request(struct view *view, enum request request, struct line *line)
4945 switch (request) {
4946 case REQ_ENTER:
4947 if (line->type == LINE_HELP_KEYMAP) {
4948 struct keymap *keymap = line->data;
4950 keymap->hidden = !keymap->hidden;
4951 refresh_view(view);
4954 return REQ_NONE;
4955 default:
4956 return pager_request(view, request, line);
4960 static struct view_ops help_ops = {
4961 "line",
4962 { "help" },
4963 VIEW_NO_GIT_DIR,
4965 help_open,
4966 NULL,
4967 help_draw,
4968 help_request,
4969 pager_grep,
4970 pager_select,
4975 * Tree backend
4978 struct tree_stack_entry {
4979 struct tree_stack_entry *prev; /* Entry below this in the stack */
4980 unsigned long lineno; /* Line number to restore */
4981 char *name; /* Position of name in opt_path */
4984 /* The top of the path stack. */
4985 static struct tree_stack_entry *tree_stack = NULL;
4986 unsigned long tree_lineno = 0;
4988 static void
4989 pop_tree_stack_entry(void)
4991 struct tree_stack_entry *entry = tree_stack;
4993 tree_lineno = entry->lineno;
4994 entry->name[0] = 0;
4995 tree_stack = entry->prev;
4996 free(entry);
4999 static void
5000 push_tree_stack_entry(const char *name, unsigned long lineno)
5002 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
5003 size_t pathlen = strlen(opt_path);
5005 if (!entry)
5006 return;
5008 entry->prev = tree_stack;
5009 entry->name = opt_path + pathlen;
5010 tree_stack = entry;
5012 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
5013 pop_tree_stack_entry();
5014 return;
5017 /* Move the current line to the first tree entry. */
5018 tree_lineno = 1;
5019 entry->lineno = lineno;
5022 /* Parse output from git-ls-tree(1):
5024 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
5027 #define SIZEOF_TREE_ATTR \
5028 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
5030 #define SIZEOF_TREE_MODE \
5031 STRING_SIZE("100644 ")
5033 #define TREE_ID_OFFSET \
5034 STRING_SIZE("100644 blob ")
5036 #define tree_path_is_parent(path) (!strcmp("..", (path)))
5038 struct tree_entry {
5039 char id[SIZEOF_REV];
5040 char commit[SIZEOF_REV];
5041 mode_t mode;
5042 struct time time; /* Date from the author ident. */
5043 const struct ident *author; /* Author of the commit. */
5044 char name[1];
5047 struct tree_state {
5048 char commit[SIZEOF_REV];
5049 const struct ident *author;
5050 struct time author_time;
5051 bool read_date;
5054 static const char *
5055 tree_path(const struct line *line)
5057 return ((struct tree_entry *) line->data)->name;
5060 static int
5061 tree_compare_entry(const struct line *line1, const struct line *line2)
5063 if (line1->type != line2->type)
5064 return line1->type == LINE_TREE_DIR ? -1 : 1;
5065 return strcmp(tree_path(line1), tree_path(line2));
5068 static const enum sort_field tree_sort_fields[] = {
5069 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5071 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
5073 static int
5074 tree_compare(const void *l1, const void *l2)
5076 const struct line *line1 = (const struct line *) l1;
5077 const struct line *line2 = (const struct line *) l2;
5078 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
5079 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
5081 if (line1->type == LINE_TREE_HEAD)
5082 return -1;
5083 if (line2->type == LINE_TREE_HEAD)
5084 return 1;
5086 switch (get_sort_field(tree_sort_state)) {
5087 case ORDERBY_DATE:
5088 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
5090 case ORDERBY_AUTHOR:
5091 return sort_order(tree_sort_state, ident_compare(entry1->author, entry2->author));
5093 case ORDERBY_NAME:
5094 default:
5095 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
5100 static struct line *
5101 tree_entry(struct view *view, enum line_type type, const char *path,
5102 const char *mode, const char *id)
5104 bool custom = type == LINE_TREE_HEAD || tree_path_is_parent(path);
5105 struct tree_entry *entry;
5106 struct line *line = add_line_alloc(view, &entry, type, strlen(path), custom);
5108 if (!line)
5109 return NULL;
5111 strncpy(entry->name, path, strlen(path));
5112 if (mode)
5113 entry->mode = strtoul(mode, NULL, 8);
5114 if (id)
5115 string_copy_rev(entry->id, id);
5117 return line;
5120 static bool
5121 tree_read_date(struct view *view, char *text, struct tree_state *state)
5123 if (!text && state->read_date) {
5124 state->read_date = FALSE;
5125 return TRUE;
5127 } else if (!text) {
5128 /* Find next entry to process */
5129 const char *log_file[] = {
5130 "git", "log", opt_encoding_arg, "--no-color", "--pretty=raw",
5131 "--cc", "--raw", view->id, "--", "%(directory)", NULL
5134 if (!view->lines) {
5135 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
5136 tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref);
5137 report("Tree is empty");
5138 return TRUE;
5141 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
5142 report("Failed to load tree data");
5143 return TRUE;
5146 state->read_date = TRUE;
5147 return FALSE;
5149 } else if (*text == 'c' && get_line_type(text) == LINE_COMMIT) {
5150 string_copy_rev(state->commit, text + STRING_SIZE("commit "));
5152 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
5153 parse_author_line(text + STRING_SIZE("author "),
5154 &state->author, &state->author_time);
5156 } else if (*text == ':') {
5157 char *pos;
5158 size_t annotated = 1;
5159 size_t i;
5161 pos = strchr(text, '\t');
5162 if (!pos)
5163 return TRUE;
5164 text = pos + 1;
5165 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
5166 text += strlen(opt_path);
5167 pos = strchr(text, '/');
5168 if (pos)
5169 *pos = 0;
5171 for (i = 1; i < view->lines; i++) {
5172 struct line *line = &view->line[i];
5173 struct tree_entry *entry = line->data;
5175 annotated += !!entry->author;
5176 if (entry->author || strcmp(entry->name, text))
5177 continue;
5179 string_copy_rev(entry->commit, state->commit);
5180 entry->author = state->author;
5181 entry->time = state->author_time;
5182 line->dirty = 1;
5183 break;
5186 if (annotated == view->lines)
5187 io_kill(view->pipe);
5189 return TRUE;
5192 static bool
5193 tree_read(struct view *view, char *text)
5195 struct tree_state *state = view->private;
5196 struct tree_entry *data;
5197 struct line *entry, *line;
5198 enum line_type type;
5199 size_t textlen = text ? strlen(text) : 0;
5200 char *path = text + SIZEOF_TREE_ATTR;
5202 if (state->read_date || !text)
5203 return tree_read_date(view, text, state);
5205 if (textlen <= SIZEOF_TREE_ATTR)
5206 return FALSE;
5207 if (view->lines == 0 &&
5208 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
5209 return FALSE;
5211 /* Strip the path part ... */
5212 if (*opt_path) {
5213 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
5214 size_t striplen = strlen(opt_path);
5216 if (pathlen > striplen)
5217 memmove(path, path + striplen,
5218 pathlen - striplen + 1);
5220 /* Insert "link" to parent directory. */
5221 if (view->lines == 1 &&
5222 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
5223 return FALSE;
5226 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
5227 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
5228 if (!entry)
5229 return FALSE;
5230 data = entry->data;
5232 /* Skip "Directory ..." and ".." line. */
5233 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
5234 if (tree_compare_entry(line, entry) <= 0)
5235 continue;
5237 memmove(line + 1, line, (entry - line) * sizeof(*entry));
5239 line->data = data;
5240 line->type = type;
5241 for (; line <= entry; line++)
5242 line->dirty = line->cleareol = 1;
5243 return TRUE;
5246 if (tree_lineno <= view->pos.lineno)
5247 tree_lineno = view->custom_lines;
5249 if (tree_lineno > view->pos.lineno) {
5250 view->pos.lineno = tree_lineno;
5251 tree_lineno = 0;
5254 return TRUE;
5257 static bool
5258 tree_draw(struct view *view, struct line *line, unsigned int lineno)
5260 struct tree_entry *entry = line->data;
5262 if (line->type == LINE_TREE_HEAD) {
5263 if (draw_text(view, line->type, "Directory path /"))
5264 return TRUE;
5265 } else {
5266 if (draw_mode(view, entry->mode))
5267 return TRUE;
5269 if (draw_author(view, entry->author))
5270 return TRUE;
5272 if (draw_date(view, &entry->time))
5273 return TRUE;
5275 if (opt_show_id && draw_id(view, LINE_ID, entry->commit))
5276 return TRUE;
5279 draw_text(view, line->type, entry->name);
5280 return TRUE;
5283 static void
5284 open_blob_editor(const char *id, unsigned int lineno)
5286 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
5287 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
5288 int fd = mkstemp(file);
5290 if (fd == -1)
5291 report("Failed to create temporary file");
5292 else if (!io_run_append(blob_argv, fd))
5293 report("Failed to save blob data to file");
5294 else
5295 open_editor(file, lineno);
5296 if (fd != -1)
5297 unlink(file);
5300 static enum request
5301 tree_request(struct view *view, enum request request, struct line *line)
5303 enum open_flags flags;
5304 struct tree_entry *entry = line->data;
5306 switch (request) {
5307 case REQ_VIEW_BLAME:
5308 if (line->type != LINE_TREE_FILE) {
5309 report("Blame only supported for files");
5310 return REQ_NONE;
5313 string_copy(opt_ref, view->vid);
5314 return request;
5316 case REQ_EDIT:
5317 if (line->type != LINE_TREE_FILE) {
5318 report("Edit only supported for files");
5319 } else if (!is_head_commit(view->vid)) {
5320 open_blob_editor(entry->id, 0);
5321 } else {
5322 open_editor(opt_file, 0);
5324 return REQ_NONE;
5326 case REQ_TOGGLE_SORT_FIELD:
5327 case REQ_TOGGLE_SORT_ORDER:
5328 sort_view(view, request, &tree_sort_state, tree_compare);
5329 return REQ_NONE;
5331 case REQ_PARENT:
5332 if (!*opt_path) {
5333 /* quit view if at top of tree */
5334 return REQ_VIEW_CLOSE;
5336 /* fake 'cd ..' */
5337 line = &view->line[1];
5338 break;
5340 case REQ_ENTER:
5341 break;
5343 default:
5344 return request;
5347 /* Cleanup the stack if the tree view is at a different tree. */
5348 while (!*opt_path && tree_stack)
5349 pop_tree_stack_entry();
5351 switch (line->type) {
5352 case LINE_TREE_DIR:
5353 /* Depending on whether it is a subdirectory or parent link
5354 * mangle the path buffer. */
5355 if (line == &view->line[1] && *opt_path) {
5356 pop_tree_stack_entry();
5358 } else {
5359 const char *basename = tree_path(line);
5361 push_tree_stack_entry(basename, view->pos.lineno);
5364 /* Trees and subtrees share the same ID, so they are not not
5365 * unique like blobs. */
5366 flags = OPEN_RELOAD;
5367 request = REQ_VIEW_TREE;
5368 break;
5370 case LINE_TREE_FILE:
5371 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5372 request = REQ_VIEW_BLOB;
5373 break;
5375 default:
5376 return REQ_NONE;
5379 open_view(view, request, flags);
5380 if (request == REQ_VIEW_TREE)
5381 view->pos.lineno = tree_lineno;
5383 return REQ_NONE;
5386 static bool
5387 tree_grep(struct view *view, struct line *line)
5389 struct tree_entry *entry = line->data;
5390 const char *text[] = {
5391 entry->name,
5392 mkauthor(entry->author, opt_author_width, opt_author),
5393 mkdate(&entry->time, opt_date),
5394 NULL
5397 return grep_text(view, text);
5400 static void
5401 tree_select(struct view *view, struct line *line)
5403 struct tree_entry *entry = line->data;
5405 if (line->type == LINE_TREE_HEAD) {
5406 string_format(view->ref, "Files in /%s", opt_path);
5407 return;
5410 if (line->type == LINE_TREE_DIR && tree_path_is_parent(entry->name)) {
5411 string_copy(view->ref, "Open parent directory");
5412 ref_blob[0] = 0;
5413 return;
5416 if (line->type == LINE_TREE_FILE) {
5417 string_copy_rev(ref_blob, entry->id);
5418 string_format(opt_file, "%s%s", opt_path, tree_path(line));
5421 string_copy_rev(view->ref, entry->id);
5424 static bool
5425 tree_open(struct view *view, enum open_flags flags)
5427 static const char *tree_argv[] = {
5428 "git", "ls-tree", "%(commit)", "%(directory)", NULL
5431 if (string_rev_is_null(ref_commit)) {
5432 report("No tree exists for this commit");
5433 return FALSE;
5436 if (view->lines == 0 && opt_prefix[0]) {
5437 char *pos = opt_prefix;
5439 while (pos && *pos) {
5440 char *end = strchr(pos, '/');
5442 if (end)
5443 *end = 0;
5444 push_tree_stack_entry(pos, 0);
5445 pos = end;
5446 if (end) {
5447 *end = '/';
5448 pos++;
5452 } else if (strcmp(view->vid, view->id)) {
5453 opt_path[0] = 0;
5456 return begin_update(view, opt_cdup, tree_argv, flags);
5459 static struct view_ops tree_ops = {
5460 "file",
5461 { "tree" },
5462 VIEW_SEND_CHILD_ENTER,
5463 sizeof(struct tree_state),
5464 tree_open,
5465 tree_read,
5466 tree_draw,
5467 tree_request,
5468 tree_grep,
5469 tree_select,
5472 static bool
5473 blob_open(struct view *view, enum open_flags flags)
5475 static const char *blob_argv[] = {
5476 "git", "cat-file", "blob", "%(blob)", NULL
5479 if (!ref_blob[0] && opt_file[0]) {
5480 const char *commit = ref_commit[0] ? ref_commit : "HEAD";
5481 char blob_spec[SIZEOF_STR];
5482 const char *rev_parse_argv[] = {
5483 "git", "rev-parse", blob_spec, NULL
5486 if (!string_format(blob_spec, "%s:%s", commit, opt_file) ||
5487 !io_run_buf(rev_parse_argv, ref_blob, sizeof(ref_blob))) {
5488 report("Failed to resolve blob from file name");
5489 return FALSE;
5493 if (!ref_blob[0]) {
5494 report("No file chosen, press %s to open tree view",
5495 get_view_key(view, REQ_VIEW_TREE));
5496 return FALSE;
5499 view->encoding = get_path_encoding(opt_file, opt_encoding);
5501 return begin_update(view, NULL, blob_argv, flags);
5504 static bool
5505 blob_read(struct view *view, char *line)
5507 if (!line)
5508 return TRUE;
5509 return add_line_text(view, line, LINE_DEFAULT) != NULL;
5512 static enum request
5513 blob_request(struct view *view, enum request request, struct line *line)
5515 switch (request) {
5516 case REQ_EDIT:
5517 open_blob_editor(view->vid, (line - view->line) + 1);
5518 return REQ_NONE;
5519 default:
5520 return pager_request(view, request, line);
5524 static struct view_ops blob_ops = {
5525 "line",
5526 { "blob" },
5527 VIEW_NO_FLAGS,
5529 blob_open,
5530 blob_read,
5531 pager_draw,
5532 blob_request,
5533 pager_grep,
5534 pager_select,
5538 * Blame backend
5540 * Loading the blame view is a two phase job:
5542 * 1. File content is read either using opt_file from the
5543 * filesystem or using git-cat-file.
5544 * 2. Then blame information is incrementally added by
5545 * reading output from git-blame.
5548 struct blame {
5549 struct blame_commit *commit;
5550 unsigned long lineno;
5551 char text[1];
5554 struct blame_state {
5555 struct blame_commit *commit;
5556 int blamed;
5557 bool done_reading;
5558 bool auto_filename_display;
5561 static bool
5562 blame_detect_filename_display(struct view *view)
5564 bool show_filenames = FALSE;
5565 const char *filename = NULL;
5566 int i;
5568 if (opt_blame_argv) {
5569 for (i = 0; opt_blame_argv[i]; i++) {
5570 if (prefixcmp(opt_blame_argv[i], "-C"))
5571 continue;
5573 show_filenames = TRUE;
5577 for (i = 0; i < view->lines; i++) {
5578 struct blame *blame = view->line[i].data;
5580 if (blame->commit && blame->commit->id[0]) {
5581 if (!filename)
5582 filename = blame->commit->filename;
5583 else if (strcmp(filename, blame->commit->filename))
5584 show_filenames = TRUE;
5588 return show_filenames;
5591 static bool
5592 blame_open(struct view *view, enum open_flags flags)
5594 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5595 char path[SIZEOF_STR];
5596 size_t i;
5598 if (!opt_file[0]) {
5599 report("No file chosen, press %s to open tree view",
5600 get_view_key(view, REQ_VIEW_TREE));
5601 return FALSE;
5604 if (!view->prev && *opt_prefix && !(flags & (OPEN_RELOAD | OPEN_REFRESH))) {
5605 string_copy(path, opt_file);
5606 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
5607 report("Failed to setup the blame view");
5608 return FALSE;
5612 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5613 const char *blame_cat_file_argv[] = {
5614 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5617 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5618 return FALSE;
5621 /* First pass: remove multiple references to the same commit. */
5622 for (i = 0; i < view->lines; i++) {
5623 struct blame *blame = view->line[i].data;
5625 if (blame->commit && blame->commit->id[0])
5626 blame->commit->id[0] = 0;
5627 else
5628 blame->commit = NULL;
5631 /* Second pass: free existing references. */
5632 for (i = 0; i < view->lines; i++) {
5633 struct blame *blame = view->line[i].data;
5635 if (blame->commit)
5636 free(blame->commit);
5639 string_format(view->vid, "%s", opt_file);
5640 string_format(view->ref, "%s ...", opt_file);
5642 return TRUE;
5645 static struct blame_commit *
5646 get_blame_commit(struct view *view, const char *id)
5648 size_t i;
5650 for (i = 0; i < view->lines; i++) {
5651 struct blame *blame = view->line[i].data;
5653 if (!blame->commit)
5654 continue;
5656 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5657 return blame->commit;
5661 struct blame_commit *commit = calloc(1, sizeof(*commit));
5663 if (commit)
5664 string_ncopy(commit->id, id, SIZEOF_REV);
5665 return commit;
5669 static struct blame_commit *
5670 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5672 struct blame_header header;
5673 struct blame_commit *commit;
5674 struct blame *blame;
5676 if (!parse_blame_header(&header, text, view->lines))
5677 return NULL;
5679 commit = get_blame_commit(view, text);
5680 if (!commit)
5681 return NULL;
5683 state->blamed += header.group;
5684 while (header.group--) {
5685 struct line *line = &view->line[header.lineno + header.group - 1];
5687 blame = line->data;
5688 blame->commit = commit;
5689 blame->lineno = header.orig_lineno + header.group - 1;
5690 line->dirty = 1;
5693 return commit;
5696 static bool
5697 blame_read_file(struct view *view, const char *text, struct blame_state *state)
5699 if (!text) {
5700 const char *blame_argv[] = {
5701 "git", "blame", opt_encoding_arg, "%(blameargs)", "--incremental",
5702 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5705 if (view->lines == 0 && !view->prev)
5706 die("No blame exist for %s", view->vid);
5708 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5709 report("Failed to load blame data");
5710 return TRUE;
5713 if (opt_goto_line > 0) {
5714 select_view_line(view, opt_goto_line);
5715 opt_goto_line = 0;
5718 state->done_reading = TRUE;
5719 return FALSE;
5721 } else {
5722 size_t textlen = strlen(text);
5723 struct blame *blame;
5725 if (!add_line_alloc(view, &blame, LINE_ID, textlen, FALSE))
5726 return FALSE;
5728 blame->commit = NULL;
5729 strncpy(blame->text, text, textlen);
5730 blame->text[textlen] = 0;
5731 return TRUE;
5735 static bool
5736 blame_read(struct view *view, char *line)
5738 struct blame_state *state = view->private;
5740 if (!state->done_reading)
5741 return blame_read_file(view, line, state);
5743 if (!line) {
5744 state->auto_filename_display = blame_detect_filename_display(view);
5745 string_format(view->ref, "%s", view->vid);
5746 if (view_is_displayed(view)) {
5747 update_view_title(view);
5748 redraw_view_from(view, 0);
5750 return TRUE;
5753 if (!state->commit) {
5754 state->commit = read_blame_commit(view, line, state);
5755 string_format(view->ref, "%s %2zd%%", view->vid,
5756 view->lines ? state->blamed * 100 / view->lines : 0);
5758 } else if (parse_blame_info(state->commit, line)) {
5759 state->commit = NULL;
5762 return TRUE;
5765 static bool
5766 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5768 struct blame_state *state = view->private;
5769 struct blame *blame = line->data;
5770 struct time *time = NULL;
5771 const char *id = NULL, *filename = NULL;
5772 const struct ident *author = NULL;
5773 enum line_type id_type = LINE_ID;
5774 static const enum line_type blame_colors[] = {
5775 LINE_PALETTE_0,
5776 LINE_PALETTE_1,
5777 LINE_PALETTE_2,
5778 LINE_PALETTE_3,
5779 LINE_PALETTE_4,
5780 LINE_PALETTE_5,
5781 LINE_PALETTE_6,
5784 #define BLAME_COLOR(i) \
5785 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5787 if (blame->commit && *blame->commit->filename) {
5788 id = blame->commit->id;
5789 author = blame->commit->author;
5790 filename = blame->commit->filename;
5791 time = &blame->commit->time;
5792 id_type = BLAME_COLOR((long) blame->commit);
5795 if (draw_date(view, time))
5796 return TRUE;
5798 if (draw_author(view, author))
5799 return TRUE;
5801 if (draw_filename(view, filename, state->auto_filename_display))
5802 return TRUE;
5804 if (draw_id(view, id_type, id))
5805 return TRUE;
5807 if (draw_lineno(view, lineno))
5808 return TRUE;
5810 draw_text(view, LINE_DEFAULT, blame->text);
5811 return TRUE;
5814 static bool
5815 check_blame_commit(struct blame *blame, bool check_null_id)
5817 if (!blame->commit)
5818 report("Commit data not loaded yet");
5819 else if (check_null_id && string_rev_is_null(blame->commit->id))
5820 report("No commit exist for the selected line");
5821 else
5822 return TRUE;
5823 return FALSE;
5826 static void
5827 setup_blame_parent_line(struct view *view, struct blame *blame)
5829 char from[SIZEOF_REF + SIZEOF_STR];
5830 char to[SIZEOF_REF + SIZEOF_STR];
5831 const char *diff_tree_argv[] = {
5832 "git", "diff", opt_encoding_arg, "--no-textconv", "--no-extdiff",
5833 "--no-color", "-U0", from, to, "--", NULL
5835 struct io io;
5836 int parent_lineno = -1;
5837 int blamed_lineno = -1;
5838 char *line;
5840 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5841 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5842 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5843 return;
5845 while ((line = io_get(&io, '\n', TRUE))) {
5846 if (*line == '@') {
5847 char *pos = strchr(line, '+');
5849 parent_lineno = atoi(line + 4);
5850 if (pos)
5851 blamed_lineno = atoi(pos + 1);
5853 } else if (*line == '+' && parent_lineno != -1) {
5854 if (blame->lineno == blamed_lineno - 1 &&
5855 !strcmp(blame->text, line + 1)) {
5856 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
5857 break;
5859 blamed_lineno++;
5863 io_done(&io);
5866 static enum request
5867 blame_request(struct view *view, enum request request, struct line *line)
5869 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5870 struct blame *blame = line->data;
5872 switch (request) {
5873 case REQ_VIEW_BLAME:
5874 if (check_blame_commit(blame, TRUE)) {
5875 string_copy(opt_ref, blame->commit->id);
5876 string_copy(opt_file, blame->commit->filename);
5877 if (blame->lineno)
5878 view->pos.lineno = blame->lineno;
5879 reload_view(view);
5881 break;
5883 case REQ_PARENT:
5884 if (!check_blame_commit(blame, TRUE))
5885 break;
5886 if (!*blame->commit->parent_id) {
5887 report("The selected commit has no parents");
5888 } else {
5889 string_copy_rev(opt_ref, blame->commit->parent_id);
5890 string_copy(opt_file, blame->commit->parent_filename);
5891 setup_blame_parent_line(view, blame);
5892 opt_goto_line = blame->lineno;
5893 reload_view(view);
5895 break;
5897 case REQ_ENTER:
5898 if (!check_blame_commit(blame, FALSE))
5899 break;
5901 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5902 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5903 break;
5905 if (string_rev_is_null(blame->commit->id)) {
5906 struct view *diff = VIEW(REQ_VIEW_DIFF);
5907 const char *diff_parent_argv[] = {
5908 GIT_DIFF_BLAME(opt_encoding_arg,
5909 opt_diff_context_arg,
5910 opt_ignore_space_arg, view->vid)
5912 const char *diff_no_parent_argv[] = {
5913 GIT_DIFF_BLAME_NO_PARENT(opt_encoding_arg,
5914 opt_diff_context_arg,
5915 opt_ignore_space_arg, view->vid)
5917 const char **diff_index_argv = *blame->commit->parent_id
5918 ? diff_parent_argv : diff_no_parent_argv;
5920 open_argv(view, diff, diff_index_argv, NULL, flags);
5921 if (diff->pipe)
5922 string_copy_rev(diff->ref, NULL_ID);
5923 } else {
5924 open_view(view, REQ_VIEW_DIFF, flags);
5926 break;
5928 default:
5929 return request;
5932 return REQ_NONE;
5935 static bool
5936 blame_grep(struct view *view, struct line *line)
5938 struct blame *blame = line->data;
5939 struct blame_commit *commit = blame->commit;
5940 const char *text[] = {
5941 blame->text,
5942 commit ? commit->title : "",
5943 commit ? commit->id : "",
5944 commit ? mkauthor(commit->author, opt_author_width, opt_author) : "",
5945 commit ? mkdate(&commit->time, opt_date) : "",
5946 NULL
5949 return grep_text(view, text);
5952 static void
5953 blame_select(struct view *view, struct line *line)
5955 struct blame *blame = line->data;
5956 struct blame_commit *commit = blame->commit;
5958 if (!commit)
5959 return;
5961 if (string_rev_is_null(commit->id))
5962 string_ncopy(ref_commit, "HEAD", 4);
5963 else
5964 string_copy_rev(ref_commit, commit->id);
5967 static struct view_ops blame_ops = {
5968 "line",
5969 { "blame" },
5970 VIEW_ALWAYS_LINENO | VIEW_SEND_CHILD_ENTER,
5971 sizeof(struct blame_state),
5972 blame_open,
5973 blame_read,
5974 blame_draw,
5975 blame_request,
5976 blame_grep,
5977 blame_select,
5981 * Branch backend
5984 struct branch {
5985 const struct ident *author; /* Author of the last commit. */
5986 struct time time; /* Date of the last activity. */
5987 char title[128]; /* First line of the commit message. */
5988 const struct ref *ref; /* Name and commit ID information. */
5991 static const struct ref branch_all;
5992 #define branch_is_all(branch) ((branch)->ref == &branch_all)
5994 static const enum sort_field branch_sort_fields[] = {
5995 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5997 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5999 struct branch_state {
6000 char id[SIZEOF_REV];
6001 size_t max_ref_length;
6004 static int
6005 branch_compare(const void *l1, const void *l2)
6007 const struct branch *branch1 = ((const struct line *) l1)->data;
6008 const struct branch *branch2 = ((const struct line *) l2)->data;
6010 if (branch_is_all(branch1))
6011 return -1;
6012 else if (branch_is_all(branch2))
6013 return 1;
6015 switch (get_sort_field(branch_sort_state)) {
6016 case ORDERBY_DATE:
6017 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
6019 case ORDERBY_AUTHOR:
6020 return sort_order(branch_sort_state, ident_compare(branch1->author, branch2->author));
6022 case ORDERBY_NAME:
6023 default:
6024 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
6028 static bool
6029 branch_draw(struct view *view, struct line *line, unsigned int lineno)
6031 struct branch_state *state = view->private;
6032 struct branch *branch = line->data;
6033 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
6034 const char *branch_name = branch_is_all(branch) ? "All branches" : branch->ref->name;
6036 if (draw_date(view, &branch->time))
6037 return TRUE;
6039 if (draw_author(view, branch->author))
6040 return TRUE;
6042 if (draw_field(view, type, branch_name, state->max_ref_length, FALSE))
6043 return TRUE;
6045 if (opt_show_id && draw_id(view, LINE_ID, branch->ref->id))
6046 return TRUE;
6048 draw_text(view, LINE_DEFAULT, branch->title);
6049 return TRUE;
6052 static enum request
6053 branch_request(struct view *view, enum request request, struct line *line)
6055 struct branch *branch = line->data;
6057 switch (request) {
6058 case REQ_REFRESH:
6059 load_refs();
6060 refresh_view(view);
6061 return REQ_NONE;
6063 case REQ_TOGGLE_SORT_FIELD:
6064 case REQ_TOGGLE_SORT_ORDER:
6065 sort_view(view, request, &branch_sort_state, branch_compare);
6066 return REQ_NONE;
6068 case REQ_ENTER:
6070 const struct ref *ref = branch->ref;
6071 const char *all_branches_argv[] = {
6072 GIT_MAIN_LOG(opt_encoding_arg, "", branch_is_all(branch) ? "--all" : ref->name, "")
6074 struct view *main_view = VIEW(REQ_VIEW_MAIN);
6076 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
6077 return REQ_NONE;
6079 case REQ_JUMP_COMMIT:
6081 int lineno;
6083 for (lineno = 0; lineno < view->lines; lineno++) {
6084 struct branch *branch = view->line[lineno].data;
6086 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
6087 select_view_line(view, lineno);
6088 report_clear();
6089 return REQ_NONE;
6093 default:
6094 return request;
6098 static bool
6099 branch_read(struct view *view, char *line)
6101 struct branch_state *state = view->private;
6102 const char *title = NULL;
6103 const struct ident *author = NULL;
6104 struct time time = {};
6105 size_t i;
6107 if (!line)
6108 return TRUE;
6110 switch (get_line_type(line)) {
6111 case LINE_COMMIT:
6112 string_copy_rev(state->id, line + STRING_SIZE("commit "));
6113 return TRUE;
6115 case LINE_AUTHOR:
6116 parse_author_line(line + STRING_SIZE("author "), &author, &time);
6118 default:
6119 title = line + STRING_SIZE("title ");
6122 for (i = 0; i < view->lines; i++) {
6123 struct branch *branch = view->line[i].data;
6125 if (strcmp(branch->ref->id, state->id))
6126 continue;
6128 if (author) {
6129 branch->author = author;
6130 branch->time = time;
6133 if (title)
6134 string_expand(branch->title, sizeof(branch->title), title, 1);
6136 view->line[i].dirty = TRUE;
6139 return TRUE;
6142 static bool
6143 branch_open_visitor(void *data, const struct ref *ref)
6145 struct view *view = data;
6146 struct branch_state *state = view->private;
6147 struct branch *branch;
6148 size_t ref_length;
6150 if (ref->tag || ref->ltag)
6151 return TRUE;
6153 if (!add_line_alloc(view, &branch, LINE_DEFAULT, 0, ref == &branch_all))
6154 return FALSE;
6156 ref_length = strlen(ref->name);
6157 if (ref_length > state->max_ref_length)
6158 state->max_ref_length = ref_length;
6160 branch->ref = ref;
6161 return TRUE;
6164 static bool
6165 branch_open(struct view *view, enum open_flags flags)
6167 const char *branch_log[] = {
6168 "git", "log", opt_encoding_arg, "--no-color", "--date=raw",
6169 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
6170 "--all", "--simplify-by-decoration", NULL
6173 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
6174 report("Failed to load branch data");
6175 return FALSE;
6178 branch_open_visitor(view, &branch_all);
6179 foreach_ref(branch_open_visitor, view);
6181 return TRUE;
6184 static bool
6185 branch_grep(struct view *view, struct line *line)
6187 struct branch *branch = line->data;
6188 const char *text[] = {
6189 branch->ref->name,
6190 mkauthor(branch->author, opt_author_width, opt_author),
6191 NULL
6194 return grep_text(view, text);
6197 static void
6198 branch_select(struct view *view, struct line *line)
6200 struct branch *branch = line->data;
6202 if (branch_is_all(branch)) {
6203 string_copy(view->ref, "All branches");
6204 return;
6206 string_copy_rev(view->ref, branch->ref->id);
6207 string_copy_rev(ref_commit, branch->ref->id);
6208 string_copy_rev(ref_head, branch->ref->id);
6209 string_copy_rev(ref_branch, branch->ref->name);
6212 static struct view_ops branch_ops = {
6213 "branch",
6214 { "branch" },
6215 VIEW_NO_FLAGS,
6216 sizeof(struct branch_state),
6217 branch_open,
6218 branch_read,
6219 branch_draw,
6220 branch_request,
6221 branch_grep,
6222 branch_select,
6226 * Status backend
6229 struct status {
6230 char status;
6231 struct {
6232 mode_t mode;
6233 char rev[SIZEOF_REV];
6234 char name[SIZEOF_STR];
6235 } old;
6236 struct {
6237 mode_t mode;
6238 char rev[SIZEOF_REV];
6239 char name[SIZEOF_STR];
6240 } new;
6243 static char status_onbranch[SIZEOF_STR];
6244 static struct status stage_status;
6245 static enum line_type stage_line_type;
6247 DEFINE_ALLOCATOR(realloc_ints, int, 32)
6249 /* This should work even for the "On branch" line. */
6250 static inline bool
6251 status_has_none(struct view *view, struct line *line)
6253 return view_has_line(view, line) && !line[1].data;
6256 /* Get fields from the diff line:
6257 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
6259 static inline bool
6260 status_get_diff(struct status *file, const char *buf, size_t bufsize)
6262 const char *old_mode = buf + 1;
6263 const char *new_mode = buf + 8;
6264 const char *old_rev = buf + 15;
6265 const char *new_rev = buf + 56;
6266 const char *status = buf + 97;
6268 if (bufsize < 98 ||
6269 old_mode[-1] != ':' ||
6270 new_mode[-1] != ' ' ||
6271 old_rev[-1] != ' ' ||
6272 new_rev[-1] != ' ' ||
6273 status[-1] != ' ')
6274 return FALSE;
6276 file->status = *status;
6278 string_copy_rev(file->old.rev, old_rev);
6279 string_copy_rev(file->new.rev, new_rev);
6281 file->old.mode = strtoul(old_mode, NULL, 8);
6282 file->new.mode = strtoul(new_mode, NULL, 8);
6284 file->old.name[0] = file->new.name[0] = 0;
6286 return TRUE;
6289 static bool
6290 status_run(struct view *view, const char *argv[], char status, enum line_type type)
6292 struct status *unmerged = NULL;
6293 char *buf;
6294 struct io io;
6296 if (!io_run(&io, IO_RD, opt_cdup, argv))
6297 return FALSE;
6299 add_line_nodata(view, type);
6301 while ((buf = io_get(&io, 0, TRUE))) {
6302 struct status *file = unmerged;
6304 if (!file) {
6305 if (!add_line_alloc(view, &file, type, 0, FALSE))
6306 goto error_out;
6309 /* Parse diff info part. */
6310 if (status) {
6311 file->status = status;
6312 if (status == 'A')
6313 string_copy(file->old.rev, NULL_ID);
6315 } else if (!file->status || file == unmerged) {
6316 if (!status_get_diff(file, buf, strlen(buf)))
6317 goto error_out;
6319 buf = io_get(&io, 0, TRUE);
6320 if (!buf)
6321 break;
6323 /* Collapse all modified entries that follow an
6324 * associated unmerged entry. */
6325 if (unmerged == file) {
6326 unmerged->status = 'U';
6327 unmerged = NULL;
6328 } else if (file->status == 'U') {
6329 unmerged = file;
6333 /* Grab the old name for rename/copy. */
6334 if (!*file->old.name &&
6335 (file->status == 'R' || file->status == 'C')) {
6336 string_ncopy(file->old.name, buf, strlen(buf));
6338 buf = io_get(&io, 0, TRUE);
6339 if (!buf)
6340 break;
6343 /* git-ls-files just delivers a NUL separated list of
6344 * file names similar to the second half of the
6345 * git-diff-* output. */
6346 string_ncopy(file->new.name, buf, strlen(buf));
6347 if (!*file->old.name)
6348 string_copy(file->old.name, file->new.name);
6349 file = NULL;
6352 if (io_error(&io)) {
6353 error_out:
6354 io_done(&io);
6355 return FALSE;
6358 if (!view->line[view->lines - 1].data)
6359 add_line_nodata(view, LINE_STAT_NONE);
6361 io_done(&io);
6362 return TRUE;
6365 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
6366 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
6368 static const char *status_list_other_argv[] = {
6369 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
6372 static const char *status_list_no_head_argv[] = {
6373 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
6376 static const char *update_index_argv[] = {
6377 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
6380 /* Restore the previous line number to stay in the context or select a
6381 * line with something that can be updated. */
6382 static void
6383 status_restore(struct view *view)
6385 if (!check_position(&view->prev_pos))
6386 return;
6388 if (view->prev_pos.lineno >= view->lines)
6389 view->prev_pos.lineno = view->lines - 1;
6390 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
6391 view->prev_pos.lineno++;
6392 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
6393 view->prev_pos.lineno--;
6395 /* If the above fails, always skip the "On branch" line. */
6396 if (view->prev_pos.lineno < view->lines)
6397 view->pos.lineno = view->prev_pos.lineno;
6398 else
6399 view->pos.lineno = 1;
6401 if (view->prev_pos.offset > view->pos.lineno)
6402 view->pos.offset = view->pos.lineno;
6403 else if (view->prev_pos.offset < view->lines)
6404 view->pos.offset = view->prev_pos.offset;
6406 clear_position(&view->prev_pos);
6409 static void
6410 status_update_onbranch(void)
6412 static const char *paths[][2] = {
6413 { "rebase-apply/rebasing", "Rebasing" },
6414 { "rebase-apply/applying", "Applying mailbox" },
6415 { "rebase-apply/", "Rebasing mailbox" },
6416 { "rebase-merge/interactive", "Interactive rebase" },
6417 { "rebase-merge/", "Rebase merge" },
6418 { "MERGE_HEAD", "Merging" },
6419 { "BISECT_LOG", "Bisecting" },
6420 { "HEAD", "On branch" },
6422 char buf[SIZEOF_STR];
6423 struct stat stat;
6424 int i;
6426 if (is_initial_commit()) {
6427 string_copy(status_onbranch, "Initial commit");
6428 return;
6431 for (i = 0; i < ARRAY_SIZE(paths); i++) {
6432 char *head = opt_head;
6434 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
6435 lstat(buf, &stat) < 0)
6436 continue;
6438 if (!*opt_head) {
6439 struct io io;
6441 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
6442 io_read_buf(&io, buf, sizeof(buf))) {
6443 head = buf;
6444 if (!prefixcmp(head, "refs/heads/"))
6445 head += STRING_SIZE("refs/heads/");
6449 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
6450 string_copy(status_onbranch, opt_head);
6451 return;
6454 string_copy(status_onbranch, "Not currently on any branch");
6457 /* First parse staged info using git-diff-index(1), then parse unstaged
6458 * info using git-diff-files(1), and finally untracked files using
6459 * git-ls-files(1). */
6460 static bool
6461 status_open(struct view *view, enum open_flags flags)
6463 const char **staged_argv = is_initial_commit() ?
6464 status_list_no_head_argv : status_diff_index_argv;
6465 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
6467 if (opt_is_inside_work_tree == FALSE) {
6468 report("The status view requires a working tree");
6469 return FALSE;
6472 reset_view(view);
6474 add_line_nodata(view, LINE_STAT_HEAD);
6475 status_update_onbranch();
6477 io_run_bg(update_index_argv);
6479 if (!opt_untracked_dirs_content)
6480 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
6482 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
6483 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
6484 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
6485 report("Failed to load status data");
6486 return FALSE;
6489 /* Restore the exact position or use the specialized restore
6490 * mode? */
6491 status_restore(view);
6492 return TRUE;
6495 static bool
6496 status_draw(struct view *view, struct line *line, unsigned int lineno)
6498 struct status *status = line->data;
6499 enum line_type type;
6500 const char *text;
6502 if (!status) {
6503 switch (line->type) {
6504 case LINE_STAT_STAGED:
6505 type = LINE_STAT_SECTION;
6506 text = "Changes to be committed:";
6507 break;
6509 case LINE_STAT_UNSTAGED:
6510 type = LINE_STAT_SECTION;
6511 text = "Changed but not updated:";
6512 break;
6514 case LINE_STAT_UNTRACKED:
6515 type = LINE_STAT_SECTION;
6516 text = "Untracked files:";
6517 break;
6519 case LINE_STAT_NONE:
6520 type = LINE_DEFAULT;
6521 text = " (no files)";
6522 break;
6524 case LINE_STAT_HEAD:
6525 type = LINE_STAT_HEAD;
6526 text = status_onbranch;
6527 break;
6529 default:
6530 return FALSE;
6532 } else {
6533 static char buf[] = { '?', ' ', ' ', ' ', 0 };
6535 buf[0] = status->status;
6536 if (draw_text(view, line->type, buf))
6537 return TRUE;
6538 type = LINE_DEFAULT;
6539 text = status->new.name;
6542 draw_text(view, type, text);
6543 return TRUE;
6546 static enum request
6547 status_enter(struct view *view, struct line *line)
6549 struct status *status = line->data;
6550 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6552 if (line->type == LINE_STAT_NONE ||
6553 (!status && line[1].type == LINE_STAT_NONE)) {
6554 report("No file to diff");
6555 return REQ_NONE;
6558 switch (line->type) {
6559 case LINE_STAT_STAGED:
6560 case LINE_STAT_UNSTAGED:
6561 break;
6563 case LINE_STAT_UNTRACKED:
6564 if (!status) {
6565 report("No file to show");
6566 return REQ_NONE;
6569 if (!suffixcmp(status->new.name, -1, "/")) {
6570 report("Cannot display a directory");
6571 return REQ_NONE;
6573 break;
6575 case LINE_STAT_HEAD:
6576 return REQ_NONE;
6578 default:
6579 die("line type %d not handled in switch", line->type);
6582 if (status) {
6583 stage_status = *status;
6584 } else {
6585 memset(&stage_status, 0, sizeof(stage_status));
6588 stage_line_type = line->type;
6590 open_view(view, REQ_VIEW_STAGE, flags);
6591 return REQ_NONE;
6594 static bool
6595 status_exists(struct view *view, struct status *status, enum line_type type)
6597 unsigned long lineno;
6599 for (lineno = 0; lineno < view->lines; lineno++) {
6600 struct line *line = &view->line[lineno];
6601 struct status *pos = line->data;
6603 if (line->type != type)
6604 continue;
6605 if (!pos && (!status || !status->status) && line[1].data) {
6606 select_view_line(view, lineno);
6607 return TRUE;
6609 if (pos && !strcmp(status->new.name, pos->new.name)) {
6610 select_view_line(view, lineno);
6611 return TRUE;
6615 return FALSE;
6619 static bool
6620 status_update_prepare(struct io *io, enum line_type type)
6622 const char *staged_argv[] = {
6623 "git", "update-index", "-z", "--index-info", NULL
6625 const char *others_argv[] = {
6626 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
6629 switch (type) {
6630 case LINE_STAT_STAGED:
6631 return io_run(io, IO_WR, opt_cdup, staged_argv);
6633 case LINE_STAT_UNSTAGED:
6634 case LINE_STAT_UNTRACKED:
6635 return io_run(io, IO_WR, opt_cdup, others_argv);
6637 default:
6638 die("line type %d not handled in switch", type);
6639 return FALSE;
6643 static bool
6644 status_update_write(struct io *io, struct status *status, enum line_type type)
6646 switch (type) {
6647 case LINE_STAT_STAGED:
6648 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
6649 status->old.rev, status->old.name, 0);
6651 case LINE_STAT_UNSTAGED:
6652 case LINE_STAT_UNTRACKED:
6653 return io_printf(io, "%s%c", status->new.name, 0);
6655 default:
6656 die("line type %d not handled in switch", type);
6657 return FALSE;
6661 static bool
6662 status_update_file(struct status *status, enum line_type type)
6664 struct io io;
6665 bool result;
6667 if (!status_update_prepare(&io, type))
6668 return FALSE;
6670 result = status_update_write(&io, status, type);
6671 return io_done(&io) && result;
6674 static bool
6675 status_update_files(struct view *view, struct line *line)
6677 char buf[sizeof(view->ref)];
6678 struct io io;
6679 bool result = TRUE;
6680 struct line *pos;
6681 int files = 0;
6682 int file, done;
6683 int cursor_y = -1, cursor_x = -1;
6685 if (!status_update_prepare(&io, line->type))
6686 return FALSE;
6688 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
6689 files++;
6691 string_copy(buf, view->ref);
6692 getsyx(cursor_y, cursor_x);
6693 for (file = 0, done = 5; result && file < files; line++, file++) {
6694 int almost_done = file * 100 / files;
6696 if (almost_done > done) {
6697 done = almost_done;
6698 string_format(view->ref, "updating file %u of %u (%d%% done)",
6699 file, files, done);
6700 update_view_title(view);
6701 setsyx(cursor_y, cursor_x);
6702 doupdate();
6704 result = status_update_write(&io, line->data, line->type);
6706 string_copy(view->ref, buf);
6708 return io_done(&io) && result;
6711 static bool
6712 status_update(struct view *view)
6714 struct line *line = &view->line[view->pos.lineno];
6716 assert(view->lines);
6718 if (!line->data) {
6719 if (status_has_none(view, line)) {
6720 report("Nothing to update");
6721 return FALSE;
6724 if (!status_update_files(view, line + 1)) {
6725 report("Failed to update file status");
6726 return FALSE;
6729 } else if (!status_update_file(line->data, line->type)) {
6730 report("Failed to update file status");
6731 return FALSE;
6734 return TRUE;
6737 static bool
6738 status_revert(struct status *status, enum line_type type, bool has_none)
6740 if (!status || type != LINE_STAT_UNSTAGED) {
6741 if (type == LINE_STAT_STAGED) {
6742 report("Cannot revert changes to staged files");
6743 } else if (type == LINE_STAT_UNTRACKED) {
6744 report("Cannot revert changes to untracked files");
6745 } else if (has_none) {
6746 report("Nothing to revert");
6747 } else {
6748 report("Cannot revert changes to multiple files");
6751 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6752 char mode[10] = "100644";
6753 const char *reset_argv[] = {
6754 "git", "update-index", "--cacheinfo", mode,
6755 status->old.rev, status->old.name, NULL
6757 const char *checkout_argv[] = {
6758 "git", "checkout", "--", status->old.name, NULL
6761 if (status->status == 'U') {
6762 string_format(mode, "%5o", status->old.mode);
6764 if (status->old.mode == 0 && status->new.mode == 0) {
6765 reset_argv[2] = "--force-remove";
6766 reset_argv[3] = status->old.name;
6767 reset_argv[4] = NULL;
6770 if (!io_run_fg(reset_argv, opt_cdup))
6771 return FALSE;
6772 if (status->old.mode == 0 && status->new.mode == 0)
6773 return TRUE;
6776 return io_run_fg(checkout_argv, opt_cdup);
6779 return FALSE;
6782 static enum request
6783 status_request(struct view *view, enum request request, struct line *line)
6785 struct status *status = line->data;
6787 switch (request) {
6788 case REQ_STATUS_UPDATE:
6789 if (!status_update(view))
6790 return REQ_NONE;
6791 break;
6793 case REQ_STATUS_REVERT:
6794 if (!status_revert(status, line->type, status_has_none(view, line)))
6795 return REQ_NONE;
6796 break;
6798 case REQ_STATUS_MERGE:
6799 if (!status || status->status != 'U') {
6800 report("Merging only possible for files with unmerged status ('U').");
6801 return REQ_NONE;
6803 open_mergetool(status->new.name);
6804 break;
6806 case REQ_EDIT:
6807 if (!status)
6808 return request;
6809 if (status->status == 'D') {
6810 report("File has been deleted.");
6811 return REQ_NONE;
6814 open_editor(status->new.name, 0);
6815 break;
6817 case REQ_VIEW_BLAME:
6818 if (status)
6819 opt_ref[0] = 0;
6820 return request;
6822 case REQ_ENTER:
6823 /* After returning the status view has been split to
6824 * show the stage view. No further reloading is
6825 * necessary. */
6826 return status_enter(view, line);
6828 case REQ_REFRESH:
6829 /* Load the current branch information and then the view. */
6830 load_refs();
6831 break;
6833 default:
6834 return request;
6837 refresh_view(view);
6839 return REQ_NONE;
6842 static bool
6843 status_stage_info_(char *buf, size_t bufsize,
6844 enum line_type type, struct status *status)
6846 const char *file = status ? status->new.name : "";
6847 const char *info;
6849 switch (type) {
6850 case LINE_STAT_STAGED:
6851 if (status && status->status)
6852 info = "Staged changes to %s";
6853 else
6854 info = "Staged changes";
6855 break;
6857 case LINE_STAT_UNSTAGED:
6858 if (status && status->status)
6859 info = "Unstaged changes to %s";
6860 else
6861 info = "Unstaged changes";
6862 break;
6864 case LINE_STAT_UNTRACKED:
6865 info = "Untracked file %s";
6866 break;
6868 case LINE_STAT_HEAD:
6869 default:
6870 info = "";
6873 return string_nformat(buf, bufsize, NULL, info, file);
6875 #define status_stage_info(buf, type, status) \
6876 status_stage_info_(buf, sizeof(buf), type, status)
6878 static void
6879 status_select(struct view *view, struct line *line)
6881 struct status *status = line->data;
6882 char file[SIZEOF_STR] = "all files";
6883 const char *text;
6884 const char *key;
6886 if (status && !string_format(file, "'%s'", status->new.name))
6887 return;
6889 if (!status && line[1].type == LINE_STAT_NONE)
6890 line++;
6892 switch (line->type) {
6893 case LINE_STAT_STAGED:
6894 text = "Press %s to unstage %s for commit";
6895 break;
6897 case LINE_STAT_UNSTAGED:
6898 text = "Press %s to stage %s for commit";
6899 break;
6901 case LINE_STAT_UNTRACKED:
6902 text = "Press %s to stage %s for addition";
6903 break;
6905 case LINE_STAT_HEAD:
6906 case LINE_STAT_NONE:
6907 text = "Nothing to update";
6908 break;
6910 default:
6911 die("line type %d not handled in switch", line->type);
6914 if (status && status->status == 'U') {
6915 text = "Press %s to resolve conflict in %s";
6916 key = get_view_key(view, REQ_STATUS_MERGE);
6918 } else {
6919 key = get_view_key(view, REQ_STATUS_UPDATE);
6922 string_format(view->ref, text, key, file);
6923 status_stage_info(ref_status, line->type, status);
6924 if (status)
6925 string_copy(opt_file, status->new.name);
6928 static bool
6929 status_grep(struct view *view, struct line *line)
6931 struct status *status = line->data;
6933 if (status) {
6934 const char buf[2] = { status->status, 0 };
6935 const char *text[] = { status->new.name, buf, NULL };
6937 return grep_text(view, text);
6940 return FALSE;
6943 static struct view_ops status_ops = {
6944 "file",
6945 { "status" },
6946 VIEW_CUSTOM_STATUS | VIEW_SEND_CHILD_ENTER,
6948 status_open,
6949 NULL,
6950 status_draw,
6951 status_request,
6952 status_grep,
6953 status_select,
6957 struct stage_state {
6958 struct diff_state diff;
6959 size_t chunks;
6960 int *chunk;
6963 static bool
6964 stage_diff_write(struct io *io, struct line *line, struct line *end)
6966 while (line < end) {
6967 if (!io_write(io, line->data, strlen(line->data)) ||
6968 !io_write(io, "\n", 1))
6969 return FALSE;
6970 line++;
6971 if (line->type == LINE_DIFF_CHUNK ||
6972 line->type == LINE_DIFF_HEADER)
6973 break;
6976 return TRUE;
6979 static bool
6980 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6982 const char *apply_argv[SIZEOF_ARG] = {
6983 "git", "apply", "--whitespace=nowarn", NULL
6985 struct line *diff_hdr;
6986 struct io io;
6987 int argc = 3;
6989 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6990 if (!diff_hdr)
6991 return FALSE;
6993 if (!revert)
6994 apply_argv[argc++] = "--cached";
6995 if (line != NULL)
6996 apply_argv[argc++] = "--unidiff-zero";
6997 if (revert || stage_line_type == LINE_STAT_STAGED)
6998 apply_argv[argc++] = "-R";
6999 apply_argv[argc++] = "-";
7000 apply_argv[argc++] = NULL;
7001 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
7002 return FALSE;
7004 if (line != NULL) {
7005 int lineno = 0;
7006 struct line *context = chunk + 1;
7007 const char *markers[] = {
7008 line->type == LINE_DIFF_DEL ? "" : ",0",
7009 line->type == LINE_DIFF_DEL ? ",0" : "",
7012 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
7014 while (context < line) {
7015 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
7016 break;
7017 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
7018 lineno++;
7020 context++;
7023 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7024 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
7025 lineno, markers[0], lineno, markers[1]) ||
7026 !stage_diff_write(&io, line, line + 1)) {
7027 chunk = NULL;
7029 } else {
7030 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7031 !stage_diff_write(&io, chunk, view->line + view->lines))
7032 chunk = NULL;
7035 io_done(&io);
7037 return chunk ? TRUE : FALSE;
7040 static bool
7041 stage_update(struct view *view, struct line *line, bool single)
7043 struct line *chunk = NULL;
7045 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
7046 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7048 if (chunk) {
7049 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
7050 report("Failed to apply chunk");
7051 return FALSE;
7054 } else if (!stage_status.status) {
7055 view = view->parent;
7057 for (line = view->line; view_has_line(view, line); line++)
7058 if (line->type == stage_line_type)
7059 break;
7061 if (!status_update_files(view, line + 1)) {
7062 report("Failed to update files");
7063 return FALSE;
7066 } else if (!status_update_file(&stage_status, stage_line_type)) {
7067 report("Failed to update file");
7068 return FALSE;
7071 return TRUE;
7074 static bool
7075 stage_revert(struct view *view, struct line *line)
7077 struct line *chunk = NULL;
7079 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
7080 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7082 if (chunk) {
7083 if (!prompt_yesno("Are you sure you want to revert changes?"))
7084 return FALSE;
7086 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
7087 report("Failed to revert chunk");
7088 return FALSE;
7090 return TRUE;
7092 } else {
7093 return status_revert(stage_status.status ? &stage_status : NULL,
7094 stage_line_type, FALSE);
7099 static void
7100 stage_next(struct view *view, struct line *line)
7102 struct stage_state *state = view->private;
7103 int i;
7105 if (!state->chunks) {
7106 for (line = view->line; view_has_line(view, line); line++) {
7107 if (line->type != LINE_DIFF_CHUNK)
7108 continue;
7110 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
7111 report("Allocation failure");
7112 return;
7115 state->chunk[state->chunks++] = line - view->line;
7119 for (i = 0; i < state->chunks; i++) {
7120 if (state->chunk[i] > view->pos.lineno) {
7121 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
7122 report("Chunk %d of %zd", i + 1, state->chunks);
7123 return;
7127 report("No next chunk found");
7130 static enum request
7131 stage_request(struct view *view, enum request request, struct line *line)
7133 switch (request) {
7134 case REQ_STATUS_UPDATE:
7135 if (!stage_update(view, line, FALSE))
7136 return REQ_NONE;
7137 break;
7139 case REQ_STATUS_REVERT:
7140 if (!stage_revert(view, line))
7141 return REQ_NONE;
7142 break;
7144 case REQ_STAGE_UPDATE_LINE:
7145 if (stage_line_type == LINE_STAT_UNTRACKED ||
7146 stage_status.status == 'A') {
7147 report("Staging single lines is not supported for new files");
7148 return REQ_NONE;
7150 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
7151 report("Please select a change to stage");
7152 return REQ_NONE;
7154 if (!stage_update(view, line, TRUE))
7155 return REQ_NONE;
7156 break;
7158 case REQ_STAGE_NEXT:
7159 if (stage_line_type == LINE_STAT_UNTRACKED) {
7160 report("File is untracked; press %s to add",
7161 get_view_key(view, REQ_STATUS_UPDATE));
7162 return REQ_NONE;
7164 stage_next(view, line);
7165 return REQ_NONE;
7167 case REQ_EDIT:
7168 if (!stage_status.new.name[0])
7169 return request;
7170 if (stage_status.status == 'D') {
7171 report("File has been deleted.");
7172 return REQ_NONE;
7175 if (stage_line_type == LINE_STAT_UNTRACKED) {
7176 open_editor(stage_status.new.name, (line - view->line) + 1);
7177 } else {
7178 open_editor(stage_status.new.name, diff_get_lineno(view, line));
7180 break;
7182 case REQ_REFRESH:
7183 /* Reload everything(including current branch information) ... */
7184 load_refs();
7185 break;
7187 case REQ_VIEW_BLAME:
7188 if (stage_status.new.name[0]) {
7189 string_copy(opt_file, stage_status.new.name);
7190 opt_ref[0] = 0;
7192 return request;
7194 case REQ_ENTER:
7195 return diff_common_enter(view, request, line);
7197 case REQ_DIFF_CONTEXT_UP:
7198 case REQ_DIFF_CONTEXT_DOWN:
7199 if (!update_diff_context(request))
7200 return REQ_NONE;
7201 break;
7203 default:
7204 return request;
7207 refresh_view(view->parent);
7209 /* Check whether the staged entry still exists, and close the
7210 * stage view if it doesn't. */
7211 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
7212 status_restore(view->parent);
7213 return REQ_VIEW_CLOSE;
7216 refresh_view(view);
7218 return REQ_NONE;
7221 static bool
7222 stage_open(struct view *view, enum open_flags flags)
7224 static const char *no_head_diff_argv[] = {
7225 GIT_DIFF_STAGED_INITIAL(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7226 stage_status.new.name)
7228 static const char *index_show_argv[] = {
7229 GIT_DIFF_STAGED(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7230 stage_status.old.name, stage_status.new.name)
7232 static const char *files_show_argv[] = {
7233 GIT_DIFF_UNSTAGED(opt_encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7234 stage_status.old.name, stage_status.new.name)
7236 /* Diffs for unmerged entries are empty when passing the new
7237 * path, so leave out the new path. */
7238 static const char *files_unmerged_argv[] = {
7239 "git", "diff-files", opt_encoding_arg, "--root", "--patch-with-stat",
7240 opt_diff_context_arg, opt_ignore_space_arg, "--",
7241 stage_status.old.name, NULL
7243 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
7244 const char **argv = NULL;
7246 if (!stage_line_type) {
7247 report("No stage content, press %s to open the status view and choose file",
7248 get_view_key(view, REQ_VIEW_STATUS));
7249 return FALSE;
7252 view->encoding = NULL;
7254 switch (stage_line_type) {
7255 case LINE_STAT_STAGED:
7256 if (is_initial_commit()) {
7257 argv = no_head_diff_argv;
7258 } else {
7259 argv = index_show_argv;
7261 break;
7263 case LINE_STAT_UNSTAGED:
7264 if (stage_status.status != 'U')
7265 argv = files_show_argv;
7266 else
7267 argv = files_unmerged_argv;
7268 break;
7270 case LINE_STAT_UNTRACKED:
7271 argv = file_argv;
7272 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
7273 break;
7275 case LINE_STAT_HEAD:
7276 default:
7277 die("line type %d not handled in switch", stage_line_type);
7280 if (!status_stage_info(view->ref, stage_line_type, &stage_status)
7281 || !argv_copy(&view->argv, argv)) {
7282 report("Failed to open staged view");
7283 return FALSE;
7286 view->vid[0] = 0;
7287 view->dir = opt_cdup;
7288 return begin_update(view, NULL, NULL, flags);
7291 static bool
7292 stage_read(struct view *view, char *data)
7294 struct stage_state *state = view->private;
7296 if (data && diff_common_read(view, data, &state->diff))
7297 return TRUE;
7299 return pager_read(view, data);
7302 static struct view_ops stage_ops = {
7303 "line",
7304 { "stage" },
7305 VIEW_DIFF_LIKE,
7306 sizeof(struct stage_state),
7307 stage_open,
7308 stage_read,
7309 diff_common_draw,
7310 stage_request,
7311 pager_grep,
7312 pager_select,
7317 * Revision graph
7320 static const enum line_type graph_colors[] = {
7321 LINE_PALETTE_0,
7322 LINE_PALETTE_1,
7323 LINE_PALETTE_2,
7324 LINE_PALETTE_3,
7325 LINE_PALETTE_4,
7326 LINE_PALETTE_5,
7327 LINE_PALETTE_6,
7330 static enum line_type get_graph_color(struct graph_symbol *symbol)
7332 if (symbol->commit)
7333 return LINE_GRAPH_COMMIT;
7334 assert(symbol->color < ARRAY_SIZE(graph_colors));
7335 return graph_colors[symbol->color];
7338 static bool
7339 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7341 const char *chars = graph_symbol_to_utf8(symbol);
7343 return draw_text(view, color, chars + !!first);
7346 static bool
7347 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7349 const char *chars = graph_symbol_to_ascii(symbol);
7351 return draw_text(view, color, chars + !!first);
7354 static bool
7355 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7357 const chtype *chars = graph_symbol_to_chtype(symbol);
7359 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
7362 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
7364 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
7366 static const draw_graph_fn fns[] = {
7367 draw_graph_ascii,
7368 draw_graph_chtype,
7369 draw_graph_utf8
7371 draw_graph_fn fn = fns[opt_line_graphics];
7372 int i;
7374 for (i = 0; i < canvas->size; i++) {
7375 struct graph_symbol *symbol = &canvas->symbols[i];
7376 enum line_type color = get_graph_color(symbol);
7378 if (fn(view, symbol, color, i == 0))
7379 return TRUE;
7382 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
7386 * Main view backend
7389 struct commit {
7390 char id[SIZEOF_REV]; /* SHA1 ID. */
7391 char title[128]; /* First line of the commit message. */
7392 const struct ident *author; /* Author of the commit. */
7393 struct time time; /* Date from the author ident. */
7394 struct ref_list *refs; /* Repository references. */
7395 struct graph_canvas graph; /* Ancestry chain graphics. */
7398 struct main_state {
7399 struct graph graph;
7400 struct commit *current;
7401 bool in_header;
7402 bool added_changes_commits;
7405 static struct commit *
7406 main_add_commit(struct view *view, enum line_type type, const char *ids,
7407 bool is_boundary, bool custom)
7409 struct main_state *state = view->private;
7410 struct commit *commit;
7412 if (!add_line_alloc(view, &commit, type, 0, custom))
7413 return NULL;
7415 string_copy_rev(commit->id, ids);
7416 commit->refs = get_ref_list(commit->id);
7417 graph_add_commit(&state->graph, &commit->graph, commit->id, ids, is_boundary);
7418 return commit;
7421 bool
7422 main_has_changes(const char *argv[])
7424 struct io io;
7426 if (!io_run(&io, IO_BG, NULL, argv, -1))
7427 return FALSE;
7428 io_done(&io);
7429 return io.status == 1;
7432 static void
7433 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
7435 char ids[SIZEOF_STR] = NULL_ID " ";
7436 struct main_state *state = view->private;
7437 struct commit *commit;
7438 struct timeval now;
7439 struct timezone tz;
7441 if (!parent)
7442 return;
7444 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
7446 commit = main_add_commit(view, type, ids, FALSE, TRUE);
7447 if (!commit)
7448 return;
7450 if (!gettimeofday(&now, &tz)) {
7451 commit->time.tz = tz.tz_minuteswest * 60;
7452 commit->time.sec = now.tv_sec - commit->time.tz;
7455 commit->author = &unknown_ident;
7456 string_ncopy(commit->title, title, strlen(title));
7457 graph_render_parents(&state->graph);
7460 static void
7461 main_add_changes_commits(struct view *view, struct main_state *state, const char *parent)
7463 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
7464 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
7465 const char *staged_parent = NULL_ID;
7466 const char *unstaged_parent = parent;
7468 if (!is_head_commit(parent))
7469 return;
7471 state->added_changes_commits = TRUE;
7473 io_run_bg(update_index_argv);
7475 if (!main_has_changes(unstaged_argv)) {
7476 unstaged_parent = NULL;
7477 staged_parent = parent;
7480 if (!main_has_changes(staged_argv)) {
7481 staged_parent = NULL;
7484 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
7485 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
7488 static bool
7489 main_open(struct view *view, enum open_flags flags)
7491 static const char *main_argv[] = {
7492 GIT_MAIN_LOG(opt_encoding_arg, "%(diffargs)", "%(revargs)", "%(fileargs)")
7495 return begin_update(view, NULL, main_argv, flags);
7498 static bool
7499 main_draw(struct view *view, struct line *line, unsigned int lineno)
7501 struct commit *commit = line->data;
7503 if (!commit->author)
7504 return FALSE;
7506 if (draw_lineno(view, lineno))
7507 return TRUE;
7509 if (opt_show_id && draw_id(view, LINE_ID, commit->id))
7510 return TRUE;
7512 if (draw_date(view, &commit->time))
7513 return TRUE;
7515 if (draw_author(view, commit->author))
7516 return TRUE;
7518 if (opt_rev_graph && draw_graph(view, &commit->graph))
7519 return TRUE;
7521 if (draw_refs(view, commit->refs))
7522 return TRUE;
7524 draw_commit_title(view, commit->title, 0);
7525 return TRUE;
7528 /* Reads git log --pretty=raw output and parses it into the commit struct. */
7529 static bool
7530 main_read(struct view *view, char *line)
7532 struct main_state *state = view->private;
7533 struct graph *graph = &state->graph;
7534 enum line_type type;
7535 struct commit *commit = state->current;
7537 if (!line) {
7538 if (!view->lines && !view->prev)
7539 die("No revisions match the given arguments.");
7540 if (view->lines > 0) {
7541 commit = view->line[view->lines - 1].data;
7542 view->line[view->lines - 1].dirty = 1;
7543 if (!commit->author) {
7544 view->lines--;
7545 free(commit);
7549 done_graph(graph);
7550 return TRUE;
7553 type = get_line_type(line);
7554 if (type == LINE_COMMIT) {
7555 bool is_boundary;
7557 state->in_header = TRUE;
7558 line += STRING_SIZE("commit ");
7559 is_boundary = *line == '-';
7560 if (is_boundary || !isalnum(*line))
7561 line++;
7563 if (!state->added_changes_commits && opt_show_changes && opt_is_inside_work_tree)
7564 main_add_changes_commits(view, state, line);
7566 state->current = main_add_commit(view, LINE_MAIN_COMMIT, line, is_boundary, FALSE);
7567 return state->current != NULL;
7570 if (!view->lines || !commit)
7571 return TRUE;
7573 /* Empty line separates the commit header from the log itself. */
7574 if (*line == '\0')
7575 state->in_header = FALSE;
7577 switch (type) {
7578 case LINE_PARENT:
7579 if (!graph->has_parents)
7580 graph_add_parent(graph, line + STRING_SIZE("parent "));
7581 break;
7583 case LINE_AUTHOR:
7584 parse_author_line(line + STRING_SIZE("author "),
7585 &commit->author, &commit->time);
7586 graph_render_parents(graph);
7587 break;
7589 default:
7590 /* Fill in the commit title if it has not already been set. */
7591 if (commit->title[0])
7592 break;
7594 /* Skip lines in the commit header. */
7595 if (state->in_header)
7596 break;
7598 /* Require titles to start with a non-space character at the
7599 * offset used by git log. */
7600 if (strncmp(line, " ", 4))
7601 break;
7602 line += 4;
7603 /* Well, if the title starts with a whitespace character,
7604 * try to be forgiving. Otherwise we end up with no title. */
7605 while (isspace(*line))
7606 line++;
7607 if (*line == '\0')
7608 break;
7609 /* FIXME: More graceful handling of titles; append "..." to
7610 * shortened titles, etc. */
7612 string_expand(commit->title, sizeof(commit->title), line, 1);
7613 view->line[view->lines - 1].dirty = 1;
7616 return TRUE;
7619 static enum request
7620 main_request(struct view *view, enum request request, struct line *line)
7622 enum open_flags flags = (view_is_displayed(view) && request != REQ_VIEW_DIFF)
7623 ? OPEN_SPLIT : OPEN_DEFAULT;
7625 switch (request) {
7626 case REQ_NEXT:
7627 case REQ_PREVIOUS:
7628 if (view_is_displayed(view) && display[0] != view)
7629 return request;
7630 /* Do not pass navigation requests to the branch view
7631 * when the main view is maximized. (GH #38) */
7632 move_view(view, request);
7633 break;
7635 case REQ_VIEW_DIFF:
7636 case REQ_ENTER:
7637 if (view_is_displayed(view) && display[0] != view)
7638 maximize_view(view, TRUE);
7640 if (line->type == LINE_STAT_UNSTAGED
7641 || line->type == LINE_STAT_STAGED) {
7642 struct view *diff = VIEW(REQ_VIEW_DIFF);
7643 const char *diff_staged_argv[] = {
7644 GIT_DIFF_STAGED(opt_encoding_arg,
7645 opt_diff_context_arg,
7646 opt_ignore_space_arg, NULL, NULL)
7648 const char *diff_unstaged_argv[] = {
7649 GIT_DIFF_UNSTAGED(opt_encoding_arg,
7650 opt_diff_context_arg,
7651 opt_ignore_space_arg, NULL, NULL)
7653 const char **diff_argv = line->type == LINE_STAT_STAGED
7654 ? diff_staged_argv : diff_unstaged_argv;
7656 open_argv(view, diff, diff_argv, NULL, flags);
7657 break;
7660 open_view(view, REQ_VIEW_DIFF, flags);
7661 break;
7663 case REQ_REFRESH:
7664 load_refs();
7665 refresh_view(view);
7666 break;
7668 case REQ_JUMP_COMMIT:
7670 int lineno;
7672 for (lineno = 0; lineno < view->lines; lineno++) {
7673 struct commit *commit = view->line[lineno].data;
7675 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
7676 select_view_line(view, lineno);
7677 report_clear();
7678 return REQ_NONE;
7682 report("Unable to find commit '%s'", opt_search);
7683 break;
7685 default:
7686 return request;
7689 return REQ_NONE;
7692 static bool
7693 grep_refs(struct ref_list *list, regex_t *regex)
7695 regmatch_t pmatch;
7696 size_t i;
7698 if (!opt_show_refs || !list)
7699 return FALSE;
7701 for (i = 0; i < list->size; i++) {
7702 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
7703 return TRUE;
7706 return FALSE;
7709 static bool
7710 main_grep(struct view *view, struct line *line)
7712 struct commit *commit = line->data;
7713 const char *text[] = {
7714 commit->id,
7715 commit->title,
7716 mkauthor(commit->author, opt_author_width, opt_author),
7717 mkdate(&commit->time, opt_date),
7718 NULL
7721 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
7724 static void
7725 main_select(struct view *view, struct line *line)
7727 struct commit *commit = line->data;
7729 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED)
7730 string_copy(view->ref, commit->title);
7731 else
7732 string_copy_rev(view->ref, commit->id);
7733 string_copy_rev(ref_commit, commit->id);
7736 static struct view_ops main_ops = {
7737 "commit",
7738 { "main" },
7739 VIEW_STDIN | VIEW_SEND_CHILD_ENTER | VIEW_FILE_FILTER,
7740 sizeof(struct main_state),
7741 main_open,
7742 main_read,
7743 main_draw,
7744 main_request,
7745 main_grep,
7746 main_select,
7751 * Status management
7754 /* Whether or not the curses interface has been initialized. */
7755 static bool cursed = FALSE;
7757 /* Terminal hacks and workarounds. */
7758 static bool use_scroll_redrawwin;
7759 static bool use_scroll_status_wclear;
7761 /* The status window is used for polling keystrokes. */
7762 static WINDOW *status_win;
7764 /* Reading from the prompt? */
7765 static bool input_mode = FALSE;
7767 static bool status_empty = FALSE;
7769 /* Update status and title window. */
7770 static void
7771 report(const char *msg, ...)
7773 struct view *view = display[current_view];
7775 if (input_mode)
7776 return;
7778 if (!view) {
7779 char buf[SIZEOF_STR];
7780 int retval;
7782 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
7783 die("%s", buf);
7786 if (!status_empty || *msg) {
7787 va_list args;
7789 va_start(args, msg);
7791 wmove(status_win, 0, 0);
7792 if (view->has_scrolled && use_scroll_status_wclear)
7793 wclear(status_win);
7794 if (*msg) {
7795 vwprintw(status_win, msg, args);
7796 status_empty = FALSE;
7797 } else {
7798 status_empty = TRUE;
7800 wclrtoeol(status_win);
7801 wnoutrefresh(status_win);
7803 va_end(args);
7806 update_view_title(view);
7809 static void
7810 init_display(void)
7812 const char *term;
7813 int x, y;
7815 /* Initialize the curses library */
7816 if (isatty(STDIN_FILENO)) {
7817 cursed = !!initscr();
7818 opt_tty = stdin;
7819 } else {
7820 /* Leave stdin and stdout alone when acting as a pager. */
7821 opt_tty = fopen("/dev/tty", "r+");
7822 if (!opt_tty)
7823 die("Failed to open /dev/tty");
7824 cursed = !!newterm(NULL, opt_tty, opt_tty);
7827 if (!cursed)
7828 die("Failed to initialize curses");
7830 nonl(); /* Disable conversion and detect newlines from input. */
7831 cbreak(); /* Take input chars one at a time, no wait for \n */
7832 noecho(); /* Don't echo input */
7833 leaveok(stdscr, FALSE);
7835 if (has_colors())
7836 init_colors();
7838 getmaxyx(stdscr, y, x);
7839 status_win = newwin(1, x, y - 1, 0);
7840 if (!status_win)
7841 die("Failed to create status window");
7843 /* Enable keyboard mapping */
7844 keypad(status_win, TRUE);
7845 wbkgdset(status_win, get_line_attr(LINE_STATUS));
7847 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
7848 set_tabsize(opt_tab_size);
7849 #else
7850 TABSIZE = opt_tab_size;
7851 #endif
7853 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
7854 if (term && !strcmp(term, "gnome-terminal")) {
7855 /* In the gnome-terminal-emulator, the message from
7856 * scrolling up one line when impossible followed by
7857 * scrolling down one line causes corruption of the
7858 * status line. This is fixed by calling wclear. */
7859 use_scroll_status_wclear = TRUE;
7860 use_scroll_redrawwin = FALSE;
7862 } else if (term && !strcmp(term, "xrvt-xpm")) {
7863 /* No problems with full optimizations in xrvt-(unicode)
7864 * and aterm. */
7865 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
7867 } else {
7868 /* When scrolling in (u)xterm the last line in the
7869 * scrolling direction will update slowly. */
7870 use_scroll_redrawwin = TRUE;
7871 use_scroll_status_wclear = FALSE;
7875 static int
7876 get_input(int prompt_position)
7878 struct view *view;
7879 int i, key, cursor_y, cursor_x;
7881 if (prompt_position)
7882 input_mode = TRUE;
7884 while (TRUE) {
7885 bool loading = FALSE;
7887 foreach_view (view, i) {
7888 update_view(view);
7889 if (view_is_displayed(view) && view->has_scrolled &&
7890 use_scroll_redrawwin)
7891 redrawwin(view->win);
7892 view->has_scrolled = FALSE;
7893 if (view->pipe)
7894 loading = TRUE;
7897 /* Update the cursor position. */
7898 if (prompt_position) {
7899 getbegyx(status_win, cursor_y, cursor_x);
7900 cursor_x = prompt_position;
7901 } else {
7902 view = display[current_view];
7903 getbegyx(view->win, cursor_y, cursor_x);
7904 cursor_x = view->width - 1;
7905 cursor_y += view->pos.lineno - view->pos.offset;
7907 setsyx(cursor_y, cursor_x);
7909 /* Refresh, accept single keystroke of input */
7910 doupdate();
7911 nodelay(status_win, loading);
7912 key = wgetch(status_win);
7914 /* wgetch() with nodelay() enabled returns ERR when
7915 * there's no input. */
7916 if (key == ERR) {
7918 } else if (key == KEY_RESIZE) {
7919 int height, width;
7921 getmaxyx(stdscr, height, width);
7923 wresize(status_win, 1, width);
7924 mvwin(status_win, height - 1, 0);
7925 wnoutrefresh(status_win);
7926 resize_display();
7927 redraw_display(TRUE);
7929 } else {
7930 input_mode = FALSE;
7931 if (key == erasechar())
7932 key = KEY_BACKSPACE;
7933 return key;
7938 static char *
7939 prompt_input(const char *prompt, input_handler handler, void *data)
7941 enum input_status status = INPUT_OK;
7942 static char buf[SIZEOF_STR];
7943 size_t pos = 0;
7945 buf[pos] = 0;
7947 while (status == INPUT_OK || status == INPUT_SKIP) {
7948 int key;
7950 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
7951 wclrtoeol(status_win);
7953 key = get_input(pos + 1);
7954 switch (key) {
7955 case KEY_RETURN:
7956 case KEY_ENTER:
7957 case '\n':
7958 status = pos ? INPUT_STOP : INPUT_CANCEL;
7959 break;
7961 case KEY_BACKSPACE:
7962 if (pos > 0)
7963 buf[--pos] = 0;
7964 else
7965 status = INPUT_CANCEL;
7966 break;
7968 case KEY_ESC:
7969 status = INPUT_CANCEL;
7970 break;
7972 default:
7973 if (pos >= sizeof(buf)) {
7974 report("Input string too long");
7975 return NULL;
7978 status = handler(data, buf, key);
7979 if (status == INPUT_OK)
7980 buf[pos++] = (char) key;
7984 /* Clear the status window */
7985 status_empty = FALSE;
7986 report_clear();
7988 if (status == INPUT_CANCEL)
7989 return NULL;
7991 buf[pos++] = 0;
7993 return buf;
7996 static enum input_status
7997 prompt_yesno_handler(void *data, char *buf, int c)
7999 if (c == 'y' || c == 'Y')
8000 return INPUT_STOP;
8001 if (c == 'n' || c == 'N')
8002 return INPUT_CANCEL;
8003 return INPUT_SKIP;
8006 static bool
8007 prompt_yesno(const char *prompt)
8009 char prompt2[SIZEOF_STR];
8011 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
8012 return FALSE;
8014 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
8017 static enum input_status
8018 read_prompt_handler(void *data, char *buf, int c)
8020 return isprint(c) ? INPUT_OK : INPUT_SKIP;
8023 static char *
8024 read_prompt(const char *prompt)
8026 return prompt_input(prompt, read_prompt_handler, NULL);
8029 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
8031 enum input_status status = INPUT_OK;
8032 int size = 0;
8034 while (items[size].text)
8035 size++;
8037 assert(size > 0);
8039 while (status == INPUT_OK) {
8040 const struct menu_item *item = &items[*selected];
8041 int key;
8042 int i;
8044 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
8045 prompt, *selected + 1, size);
8046 if (item->hotkey)
8047 wprintw(status_win, "[%c] ", (char) item->hotkey);
8048 wprintw(status_win, "%s", item->text);
8049 wclrtoeol(status_win);
8051 key = get_input(COLS - 1);
8052 switch (key) {
8053 case KEY_RETURN:
8054 case KEY_ENTER:
8055 case '\n':
8056 status = INPUT_STOP;
8057 break;
8059 case KEY_LEFT:
8060 case KEY_UP:
8061 *selected = *selected - 1;
8062 if (*selected < 0)
8063 *selected = size - 1;
8064 break;
8066 case KEY_RIGHT:
8067 case KEY_DOWN:
8068 *selected = (*selected + 1) % size;
8069 break;
8071 case KEY_ESC:
8072 status = INPUT_CANCEL;
8073 break;
8075 default:
8076 for (i = 0; items[i].text; i++)
8077 if (items[i].hotkey == key) {
8078 *selected = i;
8079 status = INPUT_STOP;
8080 break;
8085 /* Clear the status window */
8086 status_empty = FALSE;
8087 report_clear();
8089 return status != INPUT_CANCEL;
8093 * Repository properties
8097 static void
8098 set_remote_branch(const char *name, const char *value, size_t valuelen)
8100 if (!strcmp(name, ".remote")) {
8101 string_ncopy(opt_remote, value, valuelen);
8103 } else if (*opt_remote && !strcmp(name, ".merge")) {
8104 size_t from = strlen(opt_remote);
8106 if (!prefixcmp(value, "refs/heads/"))
8107 value += STRING_SIZE("refs/heads/");
8109 if (!string_format_from(opt_remote, &from, "/%s", value))
8110 opt_remote[0] = 0;
8114 static void
8115 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
8117 const char *argv[SIZEOF_ARG] = { name, "=" };
8118 int argc = 1 + (cmd == option_set_command);
8119 enum option_code error;
8121 if (!argv_from_string(argv, &argc, value))
8122 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
8123 else
8124 error = cmd(argc, argv);
8126 if (error != OPT_OK)
8127 warn("Option 'tig.%s': %s", name, option_errors[error]);
8130 static bool
8131 set_environment_variable(const char *name, const char *value)
8133 size_t len = strlen(name) + 1 + strlen(value) + 1;
8134 char *env = malloc(len);
8136 if (env &&
8137 string_nformat(env, len, NULL, "%s=%s", name, value) &&
8138 putenv(env) == 0)
8139 return TRUE;
8140 free(env);
8141 return FALSE;
8144 static void
8145 set_work_tree(const char *value)
8147 char cwd[SIZEOF_STR];
8149 if (!getcwd(cwd, sizeof(cwd)))
8150 die("Failed to get cwd path: %s", strerror(errno));
8151 if (chdir(cwd) < 0)
8152 die("Failed to chdir(%s): %s", cwd, strerror(errno));
8153 if (chdir(opt_git_dir) < 0)
8154 die("Failed to chdir(%s): %s", opt_git_dir, strerror(errno));
8155 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
8156 die("Failed to get git path: %s", strerror(errno));
8157 if (chdir(value) < 0)
8158 die("Failed to chdir(%s): %s", value, strerror(errno));
8159 if (!getcwd(cwd, sizeof(cwd)))
8160 die("Failed to get cwd path: %s", strerror(errno));
8161 if (!set_environment_variable("GIT_WORK_TREE", cwd))
8162 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
8163 if (!set_environment_variable("GIT_DIR", opt_git_dir))
8164 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
8165 opt_is_inside_work_tree = TRUE;
8168 static void
8169 parse_git_color_option(enum line_type type, char *value)
8171 struct line_info *info = &line_info[type];
8172 const char *argv[SIZEOF_ARG];
8173 int argc = 0;
8174 bool first_color = TRUE;
8175 int i;
8177 if (!argv_from_string(argv, &argc, value))
8178 return;
8180 info->fg = COLOR_DEFAULT;
8181 info->bg = COLOR_DEFAULT;
8182 info->attr = 0;
8184 for (i = 0; i < argc; i++) {
8185 int attr = 0;
8187 if (set_attribute(&attr, argv[i])) {
8188 info->attr |= attr;
8190 } else if (set_color(&attr, argv[i])) {
8191 if (first_color)
8192 info->fg = attr;
8193 else
8194 info->bg = attr;
8195 first_color = FALSE;
8200 static void
8201 set_git_color_option(const char *name, char *value)
8203 static const struct enum_map color_option_map[] = {
8204 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
8205 ENUM_MAP("branch.local", LINE_MAIN_REF),
8206 ENUM_MAP("branch.plain", LINE_MAIN_REF),
8207 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
8209 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
8210 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
8211 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
8212 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
8213 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
8214 ENUM_MAP("diff.old", LINE_DIFF_DEL),
8215 ENUM_MAP("diff.new", LINE_DIFF_ADD),
8217 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
8219 ENUM_MAP("status.branch", LINE_STAT_HEAD),
8220 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
8221 ENUM_MAP("status.added", LINE_STAT_STAGED),
8222 ENUM_MAP("status.updated", LINE_STAT_STAGED),
8223 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
8224 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
8227 int type = LINE_NONE;
8229 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
8230 parse_git_color_option(type, value);
8234 static void
8235 set_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
8237 if (parse_encoding(encoding_ref, arg, priority) == OPT_OK)
8238 opt_encoding_arg[0] = 0;
8241 static int
8242 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8244 if (!strcmp(name, "i18n.commitencoding"))
8245 set_encoding(&opt_encoding, value, FALSE);
8247 else if (!strcmp(name, "gui.encoding"))
8248 set_encoding(&opt_encoding, value, TRUE);
8250 else if (!strcmp(name, "core.editor"))
8251 string_ncopy(opt_editor, value, valuelen);
8253 else if (!strcmp(name, "core.worktree"))
8254 set_work_tree(value);
8256 else if (!strcmp(name, "core.abbrev"))
8257 parse_id(&opt_id_cols, value);
8259 else if (!prefixcmp(name, "tig.color."))
8260 set_repo_config_option(name + 10, value, option_color_command);
8262 else if (!prefixcmp(name, "tig.bind."))
8263 set_repo_config_option(name + 9, value, option_bind_command);
8265 else if (!prefixcmp(name, "tig."))
8266 set_repo_config_option(name + 4, value, option_set_command);
8268 else if (!prefixcmp(name, "color."))
8269 set_git_color_option(name + STRING_SIZE("color."), value);
8271 else if (*opt_head && !prefixcmp(name, "branch.") &&
8272 !strncmp(name + 7, opt_head, strlen(opt_head)))
8273 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
8275 return OK;
8278 static int
8279 load_git_config(void)
8281 const char *config_list_argv[] = { "git", "config", "--list", NULL };
8283 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
8286 static int
8287 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8289 if (!opt_git_dir[0]) {
8290 string_ncopy(opt_git_dir, name, namelen);
8292 } else if (opt_is_inside_work_tree == -1) {
8293 /* This can be 3 different values depending on the
8294 * version of git being used. If git-rev-parse does not
8295 * understand --is-inside-work-tree it will simply echo
8296 * the option else either "true" or "false" is printed.
8297 * Default to true for the unknown case. */
8298 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
8300 } else if (*name == '.') {
8301 string_ncopy(opt_cdup, name, namelen);
8303 } else {
8304 string_ncopy(opt_prefix, name, namelen);
8307 return OK;
8310 static int
8311 load_repo_info(void)
8313 const char *rev_parse_argv[] = {
8314 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
8315 "--show-cdup", "--show-prefix", NULL
8318 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
8323 * Main
8326 static const char usage[] =
8327 "tig " TIG_VERSION " (" __DATE__ ")\n"
8328 "\n"
8329 "Usage: tig [options] [revs] [--] [paths]\n"
8330 " or: tig show [options] [revs] [--] [paths]\n"
8331 " or: tig blame [options] [rev] [--] path\n"
8332 " or: tig status\n"
8333 " or: tig < [git command output]\n"
8334 "\n"
8335 "Options:\n"
8336 " +<number> Select line <number> in the first view\n"
8337 " -v, --version Show version and exit\n"
8338 " -h, --help Show help message and exit";
8340 static void TIG_NORETURN
8341 quit(int sig)
8343 if (sig)
8344 signal(sig, SIG_DFL);
8346 /* XXX: Restore tty modes and let the OS cleanup the rest! */
8347 if (cursed)
8348 endwin();
8349 exit(0);
8352 static void TIG_NORETURN
8353 die(const char *err, ...)
8355 va_list args;
8357 endwin();
8359 va_start(args, err);
8360 fputs("tig: ", stderr);
8361 vfprintf(stderr, err, args);
8362 fputs("\n", stderr);
8363 va_end(args);
8365 exit(1);
8368 static void
8369 warn(const char *msg, ...)
8371 va_list args;
8373 va_start(args, msg);
8374 fputs("tig warning: ", stderr);
8375 vfprintf(stderr, msg, args);
8376 fputs("\n", stderr);
8377 va_end(args);
8380 static int
8381 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8383 const char ***filter_args = data;
8385 return argv_append(filter_args, name) ? OK : ERR;
8388 static void
8389 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
8391 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
8392 const char **all_argv = NULL;
8394 if (!argv_append_array(&all_argv, rev_parse_argv) ||
8395 !argv_append_array(&all_argv, argv) ||
8396 io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
8397 die("Failed to split arguments");
8398 argv_free(all_argv);
8399 free(all_argv);
8402 static bool
8403 is_rev_flag(const char *flag)
8405 static const char *rev_flags[] = { GIT_REV_FLAGS };
8406 int i;
8408 for (i = 0; i < ARRAY_SIZE(rev_flags); i++)
8409 if (!strcmp(flag, rev_flags[i]))
8410 return TRUE;
8412 return FALSE;
8415 static void
8416 filter_options(const char *argv[], bool blame)
8418 const char **flags = NULL;
8420 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
8421 filter_rev_parse(&flags, "--flags", "--no-revs", argv);
8423 if (flags) {
8424 int next, flags_pos;
8426 for (next = flags_pos = 0; flags && flags[next]; next++) {
8427 const char *flag = flags[next];
8429 if (is_rev_flag(flag))
8430 argv_append(&opt_rev_argv, flag);
8431 else
8432 flags[flags_pos++] = flag;
8435 flags[flags_pos] = NULL;
8437 if (blame)
8438 opt_blame_argv = flags;
8439 else
8440 opt_diff_argv = flags;
8443 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
8446 static enum request
8447 parse_options(int argc, const char *argv[])
8449 enum request request;
8450 const char *subcommand;
8451 bool seen_dashdash = FALSE;
8452 const char **filter_argv = NULL;
8453 int i;
8455 opt_stdin = !isatty(STDIN_FILENO);
8456 request = opt_stdin ? REQ_VIEW_PAGER : REQ_VIEW_MAIN;
8458 if (argc <= 1)
8459 return request;
8461 subcommand = argv[1];
8462 if (!strcmp(subcommand, "status")) {
8463 request = REQ_VIEW_STATUS;
8465 } else if (!strcmp(subcommand, "blame")) {
8466 request = REQ_VIEW_BLAME;
8468 } else if (!strcmp(subcommand, "show")) {
8469 request = REQ_VIEW_DIFF;
8471 } else {
8472 subcommand = NULL;
8475 for (i = 1 + !!subcommand; i < argc; i++) {
8476 const char *opt = argv[i];
8478 // stop parsing our options after -- and let rev-parse handle the rest
8479 if (!seen_dashdash) {
8480 if (!strcmp(opt, "--")) {
8481 seen_dashdash = TRUE;
8482 continue;
8484 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
8485 printf("tig version %s\n", TIG_VERSION);
8486 quit(0);
8488 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
8489 printf("%s\n", usage);
8490 quit(0);
8492 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
8493 opt_lineno = atoi(opt + 1);
8494 continue;
8499 if (!argv_append(&filter_argv, opt))
8500 die("command too long");
8503 if (filter_argv)
8504 filter_options(filter_argv, request == REQ_VIEW_BLAME);
8506 /* Finish validating and setting up blame options */
8507 if (request == REQ_VIEW_BLAME) {
8508 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
8509 die("invalid number of options to blame\n\n%s", usage);
8511 if (opt_rev_argv) {
8512 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
8515 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
8517 } else if (request == REQ_VIEW_PAGER) {
8518 for (i = 0; opt_rev_argv && opt_rev_argv[i]; i++) {
8519 if (!strcmp("--stdin", opt_rev_argv[i])) {
8520 request = REQ_VIEW_MAIN;
8521 break;
8526 return request;
8529 static enum request
8530 run_prompt_command(struct view *view, char *cmd) {
8531 enum request request;
8533 if (cmd && string_isnumber(cmd)) {
8534 int lineno = view->pos.lineno + 1;
8536 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
8537 select_view_line(view, lineno - 1);
8538 report_clear();
8539 } else {
8540 report("Unable to parse '%s' as a line number", cmd);
8542 } else if (cmd && iscommit(cmd)) {
8543 string_ncopy(opt_search, cmd, strlen(cmd));
8545 request = view_request(view, REQ_JUMP_COMMIT);
8546 if (request == REQ_JUMP_COMMIT) {
8547 report("Jumping to commits is not supported by the '%s' view", view->name);
8550 } else if (cmd && strlen(cmd) == 1) {
8551 request = get_keybinding(&view->ops->keymap, cmd[0]);
8552 return request;
8554 } else if (cmd && cmd[0] == '!') {
8555 struct view *next = VIEW(REQ_VIEW_PAGER);
8556 const char *argv[SIZEOF_ARG];
8557 int argc = 0;
8559 cmd++;
8560 /* When running random commands, initially show the
8561 * command in the title. However, it maybe later be
8562 * overwritten if a commit line is selected. */
8563 string_ncopy(next->ref, cmd, strlen(cmd));
8565 if (!argv_from_string(argv, &argc, cmd)) {
8566 report("Too many arguments");
8567 } else if (!format_argv(view, &next->argv, argv, FALSE, TRUE)) {
8568 report("Argument formatting failed");
8569 } else {
8570 next->dir = NULL;
8571 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
8574 } else if (cmd) {
8575 request = get_request(cmd);
8576 if (request != REQ_UNKNOWN)
8577 return request;
8579 char *args = strchr(cmd, ' ');
8580 if (args) {
8581 *args++ = 0;
8582 if (set_option(cmd, args) == OPT_OK) {
8583 request = !view->unrefreshable ? REQ_REFRESH : REQ_SCREEN_REDRAW;
8584 if (!strcmp(cmd, "color"))
8585 init_colors();
8588 return request;
8590 return REQ_NONE;
8594 main(int argc, const char *argv[])
8596 const char *codeset = ENCODING_UTF8;
8597 enum request request = parse_options(argc, argv);
8598 struct view *view;
8599 int i;
8601 signal(SIGINT, quit);
8602 signal(SIGQUIT, quit);
8603 signal(SIGPIPE, SIG_IGN);
8605 if (setlocale(LC_ALL, "")) {
8606 codeset = nl_langinfo(CODESET);
8609 foreach_view(view, i) {
8610 add_keymap(&view->ops->keymap);
8613 if (load_repo_info() == ERR)
8614 die("Failed to load repo info.");
8616 if (load_options() == ERR)
8617 die("Failed to load user config.");
8619 if (load_git_config() == ERR)
8620 die("Failed to load repo config.");
8622 /* Require a git repository unless when running in pager mode. */
8623 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
8624 die("Not a git repository");
8626 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
8627 char translit[SIZEOF_STR];
8629 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
8630 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
8631 else
8632 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
8633 if (opt_iconv_out == ICONV_NONE)
8634 die("Failed to initialize character set conversion");
8637 if (load_refs() == ERR)
8638 die("Failed to load refs.");
8640 init_display();
8642 while (view_driver(display[current_view], request)) {
8643 int key = get_input(0);
8645 if (key == KEY_ESC)
8646 key = get_input(0) + 0x80;
8648 view = display[current_view];
8649 request = get_keybinding(&view->ops->keymap, key);
8651 /* Some low-level request handling. This keeps access to
8652 * status_win restricted. */
8653 switch (request) {
8654 case REQ_NONE:
8655 report("Unknown key, press %s for help",
8656 get_view_key(view, REQ_VIEW_HELP));
8657 break;
8658 case REQ_PROMPT:
8660 char *cmd = read_prompt(":");
8661 request = run_prompt_command(view, cmd);
8662 break;
8664 case REQ_SEARCH:
8665 case REQ_SEARCH_BACK:
8667 const char *prompt = request == REQ_SEARCH ? "/" : "?";
8668 char *search = read_prompt(prompt);
8670 if (search)
8671 string_ncopy(opt_search, search, strlen(search));
8672 else if (*opt_search)
8673 request = request == REQ_SEARCH ?
8674 REQ_FIND_NEXT :
8675 REQ_FIND_PREV;
8676 else
8677 request = REQ_NONE;
8678 break;
8680 default:
8681 break;
8685 quit(0);
8687 return 0;
8690 /* vim: set ts=8 sw=8 noexpandtab: */