Make blame_draw check if the filename is NULL instead of empty
[tig.git] / tig.c
blob9f9eb3866608922732957e3aa0e03925ea4fd79c
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 #define WARN_MISSING_CURSES_CONFIGURATION
16 #include "tig.h"
17 #include "util.h"
18 #include "io.h"
19 #include "refs.h"
20 #include "graph.h"
21 #include "git.h"
23 static void report(const char *msg, ...) PRINTF_LIKE(1, 2);
24 #define report_clear() report("%s", "")
27 enum input_status {
28 INPUT_OK,
29 INPUT_SKIP,
30 INPUT_STOP,
31 INPUT_CANCEL
34 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
36 static char *prompt_input(const char *prompt, input_handler handler, void *data);
37 static bool prompt_yesno(const char *prompt);
38 static char *read_prompt(const char *prompt);
40 struct menu_item {
41 int hotkey;
42 const char *text;
43 void *data;
46 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
48 #define GRAPHIC_ENUM(_) \
49 _(GRAPHIC, ASCII), \
50 _(GRAPHIC, DEFAULT), \
51 _(GRAPHIC, UTF_8)
53 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
55 #define DATE_ENUM(_) \
56 _(DATE, NO), \
57 _(DATE, DEFAULT), \
58 _(DATE, LOCAL), \
59 _(DATE, RELATIVE), \
60 _(DATE, SHORT)
62 DEFINE_ENUM(date, DATE_ENUM);
64 struct time {
65 time_t sec;
66 int tz;
69 static inline int timecmp(const struct time *t1, const struct time *t2)
71 return t1->sec - t2->sec;
74 static const char *
75 mkdate(const struct time *time, enum date date)
77 static char buf[DATE_WIDTH + 1];
78 static const struct enum_map reldate[] = {
79 { "second", 1, 60 * 2 },
80 { "minute", 60, 60 * 60 * 2 },
81 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
82 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
83 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
84 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 365 },
85 { "year", 60 * 60 * 24 * 365, 0 },
87 struct tm tm;
89 if (!date || !time || !time->sec)
90 return "";
92 if (date == DATE_RELATIVE) {
93 struct timeval now;
94 time_t date = time->sec + time->tz;
95 time_t seconds;
96 int i;
98 gettimeofday(&now, NULL);
99 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
100 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
101 if (seconds >= reldate[i].value && reldate[i].value)
102 continue;
104 seconds /= reldate[i].namelen;
105 if (!string_format(buf, "%ld %s%s %s",
106 seconds, reldate[i].name,
107 seconds > 1 ? "s" : "",
108 now.tv_sec >= date ? "ago" : "ahead"))
109 break;
110 return buf;
114 if (date == DATE_LOCAL) {
115 time_t date = time->sec + time->tz;
116 localtime_r(&date, &tm);
118 else {
119 gmtime_r(&time->sec, &tm);
121 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
124 #define FILE_SIZE_ENUM(_) \
125 _(FILE_SIZE, NO), \
126 _(FILE_SIZE, DEFAULT), \
127 _(FILE_SIZE, UNITS)
129 DEFINE_ENUM(file_size, FILE_SIZE_ENUM);
131 static const char *
132 mkfilesize(unsigned long size, enum file_size format)
134 static char buf[64 + 1];
135 static const char relsize[] = {
136 'B', 'K', 'M', 'G', 'T', 'P'
139 if (!format)
140 return "";
142 if (format == FILE_SIZE_UNITS) {
143 const char *fmt = "%.0f%c";
144 double rsize = size;
145 int i;
147 for (i = 0; i < ARRAY_SIZE(relsize); i++) {
148 if (rsize > 1024.0 && i + 1 < ARRAY_SIZE(relsize)) {
149 rsize /= 1024;
150 continue;
153 size = rsize * 10;
154 if (size % 10 > 0)
155 fmt = "%.1f%c";
157 return string_format(buf, fmt, rsize, relsize[i])
158 ? buf : NULL;
162 return string_format(buf, "%ld", size) ? buf : NULL;
165 #define AUTHOR_ENUM(_) \
166 _(AUTHOR, NO), \
167 _(AUTHOR, FULL), \
168 _(AUTHOR, ABBREVIATED), \
169 _(AUTHOR, EMAIL), \
170 _(AUTHOR, EMAIL_USER)
172 DEFINE_ENUM(author, AUTHOR_ENUM);
174 struct ident {
175 const char *name;
176 const char *email;
179 static const struct ident unknown_ident = { "Unknown", "unknown@localhost" };
181 static inline int
182 ident_compare(const struct ident *i1, const struct ident *i2)
184 if (!i1 || !i2)
185 return (!!i1) - (!!i2);
186 if (!i1->name || !i2->name)
187 return (!!i1->name) - (!!i2->name);
188 return strcmp(i1->name, i2->name);
191 static const char *
192 get_author_initials(const char *author)
194 static char initials[AUTHOR_WIDTH * 6 + 1];
195 size_t pos = 0;
196 const char *end = strchr(author, '\0');
198 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
200 memset(initials, 0, sizeof(initials));
201 while (author < end) {
202 unsigned char bytes;
203 size_t i;
205 while (author < end && is_initial_sep(*author))
206 author++;
208 bytes = utf8_char_length(author, end);
209 if (bytes >= sizeof(initials) - 1 - pos)
210 break;
211 while (bytes--) {
212 initials[pos++] = *author++;
215 i = pos;
216 while (author < end && !is_initial_sep(*author)) {
217 bytes = utf8_char_length(author, end);
218 if (bytes >= sizeof(initials) - 1 - i) {
219 while (author < end && !is_initial_sep(*author))
220 author++;
221 break;
223 while (bytes--) {
224 initials[i++] = *author++;
228 initials[i++] = 0;
231 return initials;
234 static const char *
235 get_email_user(const char *email)
237 static char user[AUTHOR_WIDTH * 6 + 1];
238 const char *end = strchr(email, '@');
239 int length = end ? end - email : strlen(email);
241 string_format(user, "%.*s%c", length, email, 0);
242 return user;
245 #define author_trim(cols) (cols == 0 || cols > 10)
247 static const char *
248 mkauthor(const struct ident *ident, int cols, enum author author)
250 bool trim = author_trim(cols);
251 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
253 if (author == AUTHOR_NO || !ident)
254 return "";
255 if (author == AUTHOR_EMAIL && ident->email)
256 return ident->email;
257 if (author == AUTHOR_EMAIL_USER && ident->email)
258 return get_email_user(ident->email);
259 if (abbreviate && ident->name)
260 return get_author_initials(ident->name);
261 return ident->name;
264 static const char *
265 mkmode(mode_t mode)
267 if (S_ISDIR(mode))
268 return "drwxr-xr-x";
269 else if (S_ISLNK(mode))
270 return "lrwxrwxrwx";
271 else if (S_ISGITLINK(mode))
272 return "m---------";
273 else if (S_ISREG(mode) && mode & S_IXUSR)
274 return "-rwxr-xr-x";
275 else if (S_ISREG(mode))
276 return "-rw-r--r--";
277 else
278 return "----------";
281 #define FILENAME_ENUM(_) \
282 _(FILENAME, NO), \
283 _(FILENAME, ALWAYS), \
284 _(FILENAME, AUTO)
286 DEFINE_ENUM(filename, FILENAME_ENUM);
288 #define IGNORE_SPACE_ENUM(_) \
289 _(IGNORE_SPACE, NO), \
290 _(IGNORE_SPACE, ALL), \
291 _(IGNORE_SPACE, SOME), \
292 _(IGNORE_SPACE, AT_EOL)
294 DEFINE_ENUM(ignore_space, IGNORE_SPACE_ENUM);
296 #define COMMIT_ORDER_ENUM(_) \
297 _(COMMIT_ORDER, DEFAULT), \
298 _(COMMIT_ORDER, TOPO), \
299 _(COMMIT_ORDER, DATE), \
300 _(COMMIT_ORDER, REVERSE)
302 DEFINE_ENUM(commit_order, COMMIT_ORDER_ENUM);
304 #define VIEW_INFO(_) \
305 _(MAIN, main, ref_head), \
306 _(DIFF, diff, ref_commit), \
307 _(LOG, log, ref_head), \
308 _(TREE, tree, ref_commit), \
309 _(BLOB, blob, ref_blob), \
310 _(BLAME, blame, ref_commit), \
311 _(BRANCH, branch, ref_head), \
312 _(HELP, help, ""), \
313 _(PAGER, pager, ""), \
314 _(STATUS, status, "status"), \
315 _(STAGE, stage, ref_status), \
316 _(STASH, stash, ref_stash)
319 * User requests
322 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
324 #define REQ_INFO \
325 REQ_GROUP("View switching") \
326 VIEW_INFO(VIEW_REQ), \
328 REQ_GROUP("View manipulation") \
329 REQ_(ENTER, "Enter current line and scroll"), \
330 REQ_(BACK, "Go back to the previous view state"), \
331 REQ_(NEXT, "Move to next"), \
332 REQ_(PREVIOUS, "Move to previous"), \
333 REQ_(PARENT, "Move to parent"), \
334 REQ_(VIEW_NEXT, "Move focus to next view"), \
335 REQ_(REFRESH, "Reload and refresh"), \
336 REQ_(MAXIMIZE, "Maximize the current view"), \
337 REQ_(VIEW_CLOSE, "Close the current view"), \
338 REQ_(QUIT, "Close all views and quit"), \
340 REQ_GROUP("View specific requests") \
341 REQ_(STATUS_UPDATE, "Update file status"), \
342 REQ_(STATUS_REVERT, "Revert file changes"), \
343 REQ_(STATUS_MERGE, "Merge file using external tool"), \
344 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
345 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
346 REQ_(STAGE_SPLIT_CHUNK, "Split the current chunk"), \
347 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
348 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
350 REQ_GROUP("Cursor navigation") \
351 REQ_(MOVE_UP, "Move cursor one line up"), \
352 REQ_(MOVE_DOWN, "Move cursor one line down"), \
353 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
354 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
355 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
356 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
358 REQ_GROUP("Scrolling") \
359 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
360 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
361 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
362 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
363 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
364 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
365 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
367 REQ_GROUP("Searching") \
368 REQ_(SEARCH, "Search the view"), \
369 REQ_(SEARCH_BACK, "Search backwards in the view"), \
370 REQ_(FIND_NEXT, "Find next search match"), \
371 REQ_(FIND_PREV, "Find previous search match"), \
373 REQ_GROUP("Option manipulation") \
374 REQ_(OPTIONS, "Open option menu"), \
375 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
376 REQ_(TOGGLE_DATE, "Toggle date display"), \
377 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
378 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
379 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
380 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
381 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
382 REQ_(TOGGLE_CHANGES, "Toggle local changes display in the main view"), \
383 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
384 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
385 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
386 REQ_(TOGGLE_COMMIT_ORDER, "Toggle commit ordering"), \
387 REQ_(TOGGLE_ID, "Toggle commit ID display"), \
388 REQ_(TOGGLE_FILES, "Toggle file filtering"), \
389 REQ_(TOGGLE_TITLE_OVERFLOW, "Toggle highlighting of commit title overflow"), \
390 REQ_(TOGGLE_FILE_SIZE, "Toggle file size format"), \
391 REQ_(TOGGLE_UNTRACKED_DIRS, "Toggle display of files in untracked directories"), \
393 REQ_GROUP("Misc") \
394 REQ_(PROMPT, "Bring up the prompt"), \
395 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
396 REQ_(SHOW_VERSION, "Show version information"), \
397 REQ_(STOP_LOADING, "Stop all loading views"), \
398 REQ_(EDIT, "Open in editor"), \
399 REQ_(NONE, "Do nothing")
402 /* User action requests. */
403 enum request {
404 #define REQ_GROUP(help)
405 #define REQ_(req, help) REQ_##req
407 /* Offset all requests to avoid conflicts with ncurses getch values. */
408 REQ_UNKNOWN = KEY_MAX + 1,
409 REQ_OFFSET,
410 REQ_INFO,
412 /* Internal requests. */
413 REQ_JUMP_COMMIT,
415 #undef REQ_GROUP
416 #undef REQ_
419 struct request_info {
420 enum request request;
421 const char *name;
422 int namelen;
423 const char *help;
426 static const struct request_info req_info[] = {
427 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
428 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
429 REQ_INFO
430 #undef REQ_GROUP
431 #undef REQ_
434 static enum request
435 get_request(const char *name)
437 int namelen = strlen(name);
438 int i;
440 for (i = 0; i < ARRAY_SIZE(req_info); i++)
441 if (enum_equals(req_info[i], name, namelen))
442 return req_info[i].request;
444 return REQ_UNKNOWN;
449 * Options
452 /* Option and state variables. */
453 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
454 static enum date opt_date = DATE_DEFAULT;
455 static enum author opt_author = AUTHOR_FULL;
456 static enum filename opt_filename = FILENAME_AUTO;
457 static enum file_size opt_file_size = FILE_SIZE_DEFAULT;
458 static bool opt_rev_graph = TRUE;
459 static bool opt_line_number = FALSE;
460 static bool opt_show_refs = TRUE;
461 static bool opt_show_changes = TRUE;
462 static bool opt_untracked_dirs_content = TRUE;
463 static bool opt_read_git_colors = TRUE;
464 static bool opt_wrap_lines = FALSE;
465 static bool opt_ignore_case = FALSE;
466 static bool opt_focus_child = TRUE;
467 static int opt_diff_context = 3;
468 static char opt_diff_context_arg[9] = "";
469 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
470 static char opt_ignore_space_arg[22] = "";
471 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
472 static char opt_commit_order_arg[22] = "";
473 static bool opt_notes = TRUE;
474 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
475 static int opt_num_interval = 5;
476 static double opt_hscroll = 0.50;
477 static double opt_scale_split_view = 2.0 / 3.0;
478 static double opt_scale_vsplit_view = 0.5;
479 static bool opt_vsplit = FALSE;
480 static int opt_tab_size = 8;
481 static int opt_author_width = AUTHOR_WIDTH;
482 static int opt_filename_width = FILENAME_WIDTH;
483 static char opt_path[SIZEOF_STR] = "";
484 static char opt_file[SIZEOF_STR] = "";
485 static char opt_ref[SIZEOF_REF] = "";
486 static unsigned long opt_goto_line = 0;
487 static char opt_head[SIZEOF_REF] = "";
488 static char opt_remote[SIZEOF_REF] = "";
489 static iconv_t opt_iconv_out = ICONV_NONE;
490 static char opt_search[SIZEOF_STR] = "";
491 static char opt_cdup[SIZEOF_STR] = "";
492 static char opt_prefix[SIZEOF_STR] = "";
493 static char opt_git_dir[SIZEOF_STR] = "";
494 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
495 static char opt_editor[SIZEOF_STR] = "";
496 static bool opt_editor_lineno = TRUE;
497 static FILE *opt_tty = NULL;
498 static const char **opt_diff_argv = NULL;
499 static const char **opt_rev_argv = NULL;
500 static const char **opt_file_argv = NULL;
501 static const char **opt_blame_argv = NULL;
502 static int opt_lineno = 0;
503 static bool opt_show_id = FALSE;
504 static int opt_id_cols = ID_WIDTH;
505 static bool opt_file_filter = TRUE;
506 static bool opt_show_title_overflow = FALSE;
507 static int opt_title_overflow = 50;
508 static char opt_env_lines[64] = "";
509 static char opt_env_columns[64] = "";
510 static char *opt_env[] = { opt_env_lines, opt_env_columns, NULL };
512 #define is_initial_commit() (!get_ref_head())
513 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strncmp(rev, get_ref_head()->id, SIZEOF_REV - 1)))
515 static inline int
516 load_refs(bool force)
518 static bool loaded = FALSE;
520 if (force)
521 opt_head[0] = 0;
522 else if (loaded)
523 return OK;
525 loaded = TRUE;
526 return reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head));
529 static inline void
530 update_diff_context_arg(int diff_context)
532 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
533 string_ncopy(opt_diff_context_arg, "-U3", 3);
536 static inline void
537 update_ignore_space_arg()
539 if (opt_ignore_space == IGNORE_SPACE_ALL) {
540 string_copy(opt_ignore_space_arg, "--ignore-all-space");
541 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
542 string_copy(opt_ignore_space_arg, "--ignore-space-change");
543 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
544 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
545 } else {
546 string_copy(opt_ignore_space_arg, "");
550 static inline void
551 update_commit_order_arg()
553 if (opt_commit_order == COMMIT_ORDER_TOPO) {
554 string_copy(opt_commit_order_arg, "--topo-order");
555 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
556 string_copy(opt_commit_order_arg, "--date-order");
557 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
558 string_copy(opt_commit_order_arg, "--reverse");
559 } else {
560 string_copy(opt_commit_order_arg, "");
564 static inline void
565 update_notes_arg()
567 if (opt_notes) {
568 string_copy(opt_notes_arg, "--show-notes");
569 } else {
570 /* Notes are disabled by default when passing --pretty args. */
571 string_copy(opt_notes_arg, "");
576 * Line-oriented content detection.
579 #define LINE_INFO \
580 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
581 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
582 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
583 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
584 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
585 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
586 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
587 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
588 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
589 LINE(DIFF_DELETED_FILE_MODE, \
590 "deleted file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
591 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
592 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
593 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
594 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
595 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
596 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
597 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
598 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
599 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
600 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
601 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
602 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
603 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
604 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
605 LINE(PP_REFLOG, "Reflog: ", COLOR_RED, COLOR_DEFAULT, 0), \
606 LINE(PP_REFLOGMSG, "Reflog message: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
607 LINE(STASH, "stash@{", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
608 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
609 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
610 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
611 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
612 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
613 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
614 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
615 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
616 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
617 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
618 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
619 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
620 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
621 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
622 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
623 LINE(ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
624 LINE(OVERFLOW, "", COLOR_RED, COLOR_DEFAULT, 0), \
625 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
626 LINE(FILE_SIZE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
627 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
628 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
629 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
630 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
631 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
632 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
633 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
634 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
635 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
636 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
637 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
638 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
639 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
640 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
641 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
642 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
643 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
644 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
645 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
646 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
647 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
648 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
649 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
650 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
651 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
652 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
653 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
654 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
655 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
656 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
657 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
658 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
660 enum line_type {
661 #define LINE(type, line, fg, bg, attr) \
662 LINE_##type
663 LINE_INFO,
664 LINE_NONE
665 #undef LINE
668 struct line_info {
669 const char *name; /* Option name. */
670 int namelen; /* Size of option name. */
671 const char *line; /* The start of line to match. */
672 int linelen; /* Size of string to match. */
673 int fg, bg, attr; /* Color and text attributes for the lines. */
674 int color_pair;
677 static struct line_info line_info[] = {
678 #define LINE(type, line, fg, bg, attr) \
679 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
680 LINE_INFO
681 #undef LINE
684 static struct line_info **color_pair;
685 static size_t color_pairs;
687 static struct line_info *custom_color;
688 static size_t custom_colors;
690 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
691 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
693 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
694 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
696 /* Color IDs must be 1 or higher. [GH #15] */
697 #define COLOR_ID(line_type) ((line_type) + 1)
699 static enum line_type
700 get_line_type(const char *line)
702 int linelen = strlen(line);
703 enum line_type type;
705 for (type = 0; type < custom_colors; type++)
706 /* Case insensitive search matches Signed-off-by lines better. */
707 if (linelen >= custom_color[type].linelen &&
708 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
709 return TO_CUSTOM_COLOR_TYPE(type);
711 for (type = 0; type < ARRAY_SIZE(line_info); type++)
712 /* Case insensitive search matches Signed-off-by lines better. */
713 if (linelen >= line_info[type].linelen &&
714 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
715 return type;
717 return LINE_DEFAULT;
720 static enum line_type
721 get_line_type_from_ref(const struct ref *ref)
723 if (ref->head)
724 return LINE_MAIN_HEAD;
725 else if (ref->ltag)
726 return LINE_MAIN_LOCAL_TAG;
727 else if (ref->tag)
728 return LINE_MAIN_TAG;
729 else if (ref->tracked)
730 return LINE_MAIN_TRACKED;
731 else if (ref->remote)
732 return LINE_MAIN_REMOTE;
733 else if (ref->replace)
734 return LINE_MAIN_REPLACE;
736 return LINE_MAIN_REF;
739 static inline struct line_info *
740 get_line(enum line_type type)
742 if (type > LINE_NONE) {
743 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
744 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
745 } else {
746 assert(type < ARRAY_SIZE(line_info));
747 return &line_info[type];
751 static inline int
752 get_line_color(enum line_type type)
754 return COLOR_ID(get_line(type)->color_pair);
757 static inline int
758 get_line_attr(enum line_type type)
760 struct line_info *info = get_line(type);
762 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
765 static struct line_info *
766 get_line_info(const char *name)
768 size_t namelen = strlen(name);
769 enum line_type type;
771 for (type = 0; type < ARRAY_SIZE(line_info); type++)
772 if (enum_equals(line_info[type], name, namelen))
773 return &line_info[type];
775 return NULL;
778 static struct line_info *
779 add_custom_color(const char *quoted_line)
781 struct line_info *info;
782 char *line;
783 size_t linelen;
785 if (!realloc_custom_color(&custom_color, custom_colors, 1))
786 die("Failed to alloc custom line info");
788 linelen = strlen(quoted_line) - 1;
789 line = malloc(linelen);
790 if (!line)
791 return NULL;
793 strncpy(line, quoted_line + 1, linelen);
794 line[linelen - 1] = 0;
796 info = &custom_color[custom_colors++];
797 info->name = info->line = line;
798 info->namelen = info->linelen = strlen(line);
800 return info;
803 static void
804 init_line_info_color_pair(struct line_info *info, enum line_type type,
805 int default_bg, int default_fg)
807 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
808 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
809 int i;
811 for (i = 0; i < color_pairs; i++) {
812 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
813 info->color_pair = i;
814 return;
818 if (!realloc_color_pair(&color_pair, color_pairs, 1))
819 die("Failed to alloc color pair");
821 color_pair[color_pairs] = info;
822 info->color_pair = color_pairs++;
823 init_pair(COLOR_ID(info->color_pair), fg, bg);
826 static void
827 init_colors(void)
829 int default_bg = line_info[LINE_DEFAULT].bg;
830 int default_fg = line_info[LINE_DEFAULT].fg;
831 enum line_type type;
833 start_color();
835 if (assume_default_colors(default_fg, default_bg) == ERR) {
836 default_bg = COLOR_BLACK;
837 default_fg = COLOR_WHITE;
840 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
841 struct line_info *info = &line_info[type];
843 init_line_info_color_pair(info, type, default_bg, default_fg);
846 for (type = 0; type < custom_colors; type++) {
847 struct line_info *info = &custom_color[type];
849 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
850 default_bg, default_fg);
854 struct line {
855 enum line_type type;
856 unsigned int lineno:24;
858 /* State flags */
859 unsigned int selected:1;
860 unsigned int dirty:1;
861 unsigned int cleareol:1;
862 unsigned int wrapped:1;
864 unsigned int user_flags:6;
865 void *data; /* User data */
870 * Keys
873 struct keybinding {
874 int alias;
875 enum request request;
878 static struct keybinding default_keybindings[] = {
879 /* View switching */
880 { 'm', REQ_VIEW_MAIN },
881 { 'd', REQ_VIEW_DIFF },
882 { 'l', REQ_VIEW_LOG },
883 { 't', REQ_VIEW_TREE },
884 { 'f', REQ_VIEW_BLOB },
885 { 'B', REQ_VIEW_BLAME },
886 { 'H', REQ_VIEW_BRANCH },
887 { 'p', REQ_VIEW_PAGER },
888 { 'h', REQ_VIEW_HELP },
889 { 'S', REQ_VIEW_STATUS },
890 { 'c', REQ_VIEW_STAGE },
891 { 'y', REQ_VIEW_STASH },
893 /* View manipulation */
894 { 'q', REQ_VIEW_CLOSE },
895 { KEY_TAB, REQ_VIEW_NEXT },
896 { KEY_RETURN, REQ_ENTER },
897 { KEY_UP, REQ_PREVIOUS },
898 { KEY_CTL('P'), REQ_PREVIOUS },
899 { KEY_DOWN, REQ_NEXT },
900 { KEY_CTL('N'), REQ_NEXT },
901 { 'R', REQ_REFRESH },
902 { KEY_F(5), REQ_REFRESH },
903 { 'O', REQ_MAXIMIZE },
904 { ',', REQ_PARENT },
905 { '<', REQ_BACK },
907 /* View specific */
908 { 'u', REQ_STATUS_UPDATE },
909 { '!', REQ_STATUS_REVERT },
910 { 'M', REQ_STATUS_MERGE },
911 { '1', REQ_STAGE_UPDATE_LINE },
912 { '@', REQ_STAGE_NEXT },
913 { '\\', REQ_STAGE_SPLIT_CHUNK },
914 { '[', REQ_DIFF_CONTEXT_DOWN },
915 { ']', REQ_DIFF_CONTEXT_UP },
917 /* Cursor navigation */
918 { 'k', REQ_MOVE_UP },
919 { 'j', REQ_MOVE_DOWN },
920 { KEY_HOME, REQ_MOVE_FIRST_LINE },
921 { KEY_END, REQ_MOVE_LAST_LINE },
922 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
923 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
924 { ' ', REQ_MOVE_PAGE_DOWN },
925 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
926 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
927 { 'b', REQ_MOVE_PAGE_UP },
928 { '-', REQ_MOVE_PAGE_UP },
930 /* Scrolling */
931 { '|', REQ_SCROLL_FIRST_COL },
932 { KEY_LEFT, REQ_SCROLL_LEFT },
933 { KEY_RIGHT, REQ_SCROLL_RIGHT },
934 { KEY_IC, REQ_SCROLL_LINE_UP },
935 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
936 { KEY_DC, REQ_SCROLL_LINE_DOWN },
937 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
938 { 'w', REQ_SCROLL_PAGE_UP },
939 { 's', REQ_SCROLL_PAGE_DOWN },
941 /* Searching */
942 { '/', REQ_SEARCH },
943 { '?', REQ_SEARCH_BACK },
944 { 'n', REQ_FIND_NEXT },
945 { 'N', REQ_FIND_PREV },
947 /* Misc */
948 { 'Q', REQ_QUIT },
949 { 'z', REQ_STOP_LOADING },
950 { 'v', REQ_SHOW_VERSION },
951 { 'r', REQ_SCREEN_REDRAW },
952 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
953 { 'o', REQ_OPTIONS },
954 { '.', REQ_TOGGLE_LINENO },
955 { 'D', REQ_TOGGLE_DATE },
956 { 'A', REQ_TOGGLE_AUTHOR },
957 { 'g', REQ_TOGGLE_REV_GRAPH },
958 { '~', REQ_TOGGLE_GRAPHIC },
959 { '#', REQ_TOGGLE_FILENAME },
960 { 'F', REQ_TOGGLE_REFS },
961 { 'I', REQ_TOGGLE_SORT_ORDER },
962 { 'i', REQ_TOGGLE_SORT_FIELD },
963 { 'W', REQ_TOGGLE_IGNORE_SPACE },
964 { 'X', REQ_TOGGLE_ID },
965 { '%', REQ_TOGGLE_FILES },
966 { '$', REQ_TOGGLE_TITLE_OVERFLOW },
967 { ':', REQ_PROMPT },
968 { 'e', REQ_EDIT },
971 struct keymap {
972 const char *name;
973 struct keymap *next;
974 struct keybinding *data;
975 size_t size;
976 bool hidden;
979 static struct keymap generic_keymap = { "generic" };
980 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
982 static struct keymap *keymaps = &generic_keymap;
984 static void
985 add_keymap(struct keymap *keymap)
987 keymap->next = keymaps;
988 keymaps = keymap;
991 static struct keymap *
992 get_keymap(const char *name)
994 struct keymap *keymap = keymaps;
996 while (keymap) {
997 if (!strcasecmp(keymap->name, name))
998 return keymap;
999 keymap = keymap->next;
1002 return NULL;
1006 static void
1007 add_keybinding(struct keymap *table, enum request request, int key)
1009 size_t i;
1011 for (i = 0; i < table->size; i++) {
1012 if (table->data[i].alias == key) {
1013 table->data[i].request = request;
1014 return;
1018 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
1019 if (!table->data)
1020 die("Failed to allocate keybinding");
1021 table->data[table->size].alias = key;
1022 table->data[table->size++].request = request;
1024 if (request == REQ_NONE && is_generic_keymap(table)) {
1025 int i;
1027 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1028 if (default_keybindings[i].alias == key)
1029 default_keybindings[i].request = REQ_NONE;
1033 /* Looks for a key binding first in the given map, then in the generic map, and
1034 * lastly in the default keybindings. */
1035 static enum request
1036 get_keybinding(struct keymap *keymap, int key)
1038 size_t i;
1040 for (i = 0; i < keymap->size; i++)
1041 if (keymap->data[i].alias == key)
1042 return keymap->data[i].request;
1044 for (i = 0; i < generic_keymap.size; i++)
1045 if (generic_keymap.data[i].alias == key)
1046 return generic_keymap.data[i].request;
1048 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1049 if (default_keybindings[i].alias == key)
1050 return default_keybindings[i].request;
1052 return (enum request) key;
1056 struct key {
1057 const char *name;
1058 int value;
1061 static const struct key key_table[] = {
1062 { "Enter", KEY_RETURN },
1063 { "Space", ' ' },
1064 { "Backspace", KEY_BACKSPACE },
1065 { "Tab", KEY_TAB },
1066 { "Escape", KEY_ESC },
1067 { "Left", KEY_LEFT },
1068 { "Right", KEY_RIGHT },
1069 { "Up", KEY_UP },
1070 { "Down", KEY_DOWN },
1071 { "Insert", KEY_IC },
1072 { "Delete", KEY_DC },
1073 { "Hash", '#' },
1074 { "Home", KEY_HOME },
1075 { "End", KEY_END },
1076 { "PageUp", KEY_PPAGE },
1077 { "PageDown", KEY_NPAGE },
1078 { "F1", KEY_F(1) },
1079 { "F2", KEY_F(2) },
1080 { "F3", KEY_F(3) },
1081 { "F4", KEY_F(4) },
1082 { "F5", KEY_F(5) },
1083 { "F6", KEY_F(6) },
1084 { "F7", KEY_F(7) },
1085 { "F8", KEY_F(8) },
1086 { "F9", KEY_F(9) },
1087 { "F10", KEY_F(10) },
1088 { "F11", KEY_F(11) },
1089 { "F12", KEY_F(12) },
1092 static int
1093 get_key_value(const char *name)
1095 int i;
1097 for (i = 0; i < ARRAY_SIZE(key_table); i++)
1098 if (!strcasecmp(key_table[i].name, name))
1099 return key_table[i].value;
1101 if (strlen(name) == 3 && name[0] == '^' && name[1] == '[' && isprint(*name))
1102 return (int)name[2] + 0x80;
1103 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1104 return (int)name[1] & 0x1f;
1105 if (strlen(name) == 1 && isprint(*name))
1106 return (int) *name;
1107 return ERR;
1110 static const char *
1111 get_key_name(int key_value)
1113 static char key_char[] = "'X'\0";
1114 const char *seq = NULL;
1115 int key;
1117 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1118 if (key_table[key].value == key_value)
1119 seq = key_table[key].name;
1121 if (seq == NULL && key_value < 0x7f) {
1122 char *s = key_char + 1;
1124 if (key_value >= 0x20) {
1125 *s++ = key_value;
1126 } else {
1127 *s++ = '^';
1128 *s++ = 0x40 | (key_value & 0x1f);
1130 *s++ = '\'';
1131 *s++ = '\0';
1132 seq = key_char;
1135 return seq ? seq : "(no key)";
1138 static bool
1139 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1141 const char *sep = *pos > 0 ? ", " : "";
1142 const char *keyname = get_key_name(keybinding->alias);
1144 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1147 static bool
1148 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1149 struct keymap *keymap, bool all)
1151 int i;
1153 for (i = 0; i < keymap->size; i++) {
1154 if (keymap->data[i].request == request) {
1155 if (!append_key(buf, pos, &keymap->data[i]))
1156 return FALSE;
1157 if (!all)
1158 break;
1162 return TRUE;
1165 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1167 static const char *
1168 get_keys(struct keymap *keymap, enum request request, bool all)
1170 static char buf[BUFSIZ];
1171 size_t pos = 0;
1172 int i;
1174 buf[pos] = 0;
1176 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1177 return "Too many keybindings!";
1178 if (pos > 0 && !all)
1179 return buf;
1181 if (!is_generic_keymap(keymap)) {
1182 /* Only the generic keymap includes the default keybindings when
1183 * listing all keys. */
1184 if (all)
1185 return buf;
1187 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1188 return "Too many keybindings!";
1189 if (pos)
1190 return buf;
1193 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1194 if (default_keybindings[i].request == request) {
1195 if (!append_key(buf, &pos, &default_keybindings[i]))
1196 return "Too many keybindings!";
1197 if (!all)
1198 return buf;
1202 return buf;
1205 enum run_request_flag {
1206 RUN_REQUEST_DEFAULT = 0,
1207 RUN_REQUEST_FORCE = 1,
1208 RUN_REQUEST_SILENT = 2,
1209 RUN_REQUEST_CONFIRM = 4,
1210 RUN_REQUEST_EXIT = 8,
1211 RUN_REQUEST_INTERNAL = 16,
1214 struct run_request {
1215 struct keymap *keymap;
1216 int key;
1217 const char **argv;
1218 bool silent;
1219 bool confirm;
1220 bool exit;
1221 bool internal;
1224 static struct run_request *run_request;
1225 static size_t run_requests;
1227 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1229 static bool
1230 add_run_request(struct keymap *keymap, int key, const char **argv, enum run_request_flag flags)
1232 bool force = flags & RUN_REQUEST_FORCE;
1233 struct run_request *req;
1235 if (!force && get_keybinding(keymap, key) != key)
1236 return TRUE;
1238 if (!realloc_run_requests(&run_request, run_requests, 1))
1239 return FALSE;
1241 if (!argv_copy(&run_request[run_requests].argv, argv))
1242 return FALSE;
1244 req = &run_request[run_requests++];
1245 req->silent = flags & RUN_REQUEST_SILENT;
1246 req->confirm = flags & RUN_REQUEST_CONFIRM;
1247 req->exit = flags & RUN_REQUEST_EXIT;
1248 req->internal = flags & RUN_REQUEST_INTERNAL;
1249 req->keymap = keymap;
1250 req->key = key;
1252 add_keybinding(keymap, REQ_NONE + run_requests, key);
1253 return TRUE;
1256 static struct run_request *
1257 get_run_request(enum request request)
1259 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1260 return NULL;
1261 return &run_request[request - REQ_NONE - 1];
1264 static void
1265 add_builtin_run_requests(void)
1267 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1268 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1269 const char *commit[] = { "git", "commit", NULL };
1270 const char *gc[] = { "git", "gc", NULL };
1271 const char *stash_pop[] = { "git", "stash", "pop", "%(stash)", NULL };
1273 add_run_request(get_keymap("main"), 'C', cherry_pick, RUN_REQUEST_CONFIRM);
1274 add_run_request(get_keymap("status"), 'C', commit, RUN_REQUEST_DEFAULT);
1275 add_run_request(get_keymap("branch"), 'C', checkout, RUN_REQUEST_CONFIRM);
1276 add_run_request(get_keymap("generic"), 'G', gc, RUN_REQUEST_CONFIRM);
1277 add_run_request(get_keymap("stash"), 'P', stash_pop, RUN_REQUEST_CONFIRM);
1281 * User config file handling.
1284 static const struct enum_map color_map[] = {
1285 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1286 COLOR_MAP(DEFAULT),
1287 COLOR_MAP(BLACK),
1288 COLOR_MAP(BLUE),
1289 COLOR_MAP(CYAN),
1290 COLOR_MAP(GREEN),
1291 COLOR_MAP(MAGENTA),
1292 COLOR_MAP(RED),
1293 COLOR_MAP(WHITE),
1294 COLOR_MAP(YELLOW),
1297 static const struct enum_map attr_map[] = {
1298 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1299 ATTR_MAP(NORMAL),
1300 ATTR_MAP(BLINK),
1301 ATTR_MAP(BOLD),
1302 ATTR_MAP(DIM),
1303 ATTR_MAP(REVERSE),
1304 ATTR_MAP(STANDOUT),
1305 ATTR_MAP(UNDERLINE),
1308 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1310 static enum status_code
1311 parse_step(double *opt, const char *arg)
1313 *opt = atoi(arg);
1314 if (!strchr(arg, '%'))
1315 return SUCCESS;
1317 /* "Shift down" so 100% and 1 does not conflict. */
1318 *opt = (*opt - 1) / 100;
1319 if (*opt >= 1.0) {
1320 *opt = 0.99;
1321 return ERROR_INVALID_STEP_VALUE;
1323 if (*opt < 0.0) {
1324 *opt = 1;
1325 return ERROR_INVALID_STEP_VALUE;
1327 return SUCCESS;
1330 static enum status_code
1331 parse_int(int *opt, const char *arg, int min, int max)
1333 int value = atoi(arg);
1335 if (min <= value && value <= max) {
1336 *opt = value;
1337 return SUCCESS;
1340 return ERROR_INTEGER_VALUE_OUT_OF_BOUND;
1343 #define parse_id(opt, arg) \
1344 parse_int(opt, arg, 4, SIZEOF_REV - 1)
1346 static bool
1347 set_color(int *color, const char *name)
1349 if (map_enum(color, color_map, name))
1350 return TRUE;
1351 if (!prefixcmp(name, "color"))
1352 return parse_int(color, name + 5, 0, 255) == SUCCESS;
1353 /* Used when reading git colors. Git expects a plain int w/o prefix. */
1354 return parse_int(color, name, 0, 255) == SUCCESS;
1357 /* Wants: object fgcolor bgcolor [attribute] */
1358 static enum status_code
1359 option_color_command(int argc, const char *argv[])
1361 struct line_info *info;
1363 if (argc < 3)
1364 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1366 if (*argv[0] == '"' || *argv[0] == '\'') {
1367 info = add_custom_color(argv[0]);
1368 } else {
1369 info = get_line_info(argv[0]);
1371 if (!info) {
1372 static const struct enum_map obsolete[] = {
1373 ENUM_MAP("main-delim", LINE_DELIMITER),
1374 ENUM_MAP("main-date", LINE_DATE),
1375 ENUM_MAP("main-author", LINE_AUTHOR),
1376 ENUM_MAP("blame-id", LINE_ID),
1378 int index;
1380 if (!map_enum(&index, obsolete, argv[0]))
1381 return ERROR_UNKNOWN_COLOR_NAME;
1382 info = &line_info[index];
1385 if (!set_color(&info->fg, argv[1]) ||
1386 !set_color(&info->bg, argv[2]))
1387 return ERROR_UNKNOWN_COLOR;
1389 info->attr = 0;
1390 while (argc-- > 3) {
1391 int attr;
1393 if (!set_attribute(&attr, argv[argc]))
1394 return ERROR_UNKNOWN_ATTRIBUTE;
1395 info->attr |= attr;
1398 return SUCCESS;
1401 static enum status_code
1402 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1404 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1405 ? TRUE : FALSE;
1406 if (matched)
1407 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1408 return SUCCESS;
1411 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1413 static enum status_code
1414 parse_enum_do(unsigned int *opt, const char *arg,
1415 const struct enum_map *map, size_t map_size)
1417 bool is_true;
1419 assert(map_size > 1);
1421 if (map_enum_do(map, map_size, (int *) opt, arg))
1422 return SUCCESS;
1424 parse_bool(&is_true, arg);
1425 *opt = is_true ? map[1].value : map[0].value;
1426 return SUCCESS;
1429 #define parse_enum(opt, arg, map) \
1430 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1432 static enum status_code
1433 parse_string(char *opt, const char *arg, size_t optsize)
1435 int arglen = strlen(arg);
1437 switch (arg[0]) {
1438 case '\"':
1439 case '\'':
1440 if (arglen == 1 || arg[arglen - 1] != arg[0])
1441 return ERROR_UNMATCHED_QUOTATION;
1442 arg += 1; arglen -= 2;
1443 default:
1444 string_ncopy_do(opt, optsize, arg, arglen);
1445 return SUCCESS;
1449 static enum status_code
1450 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1452 char buf[SIZEOF_STR];
1453 enum status_code code = parse_string(buf, arg, sizeof(buf));
1455 if (code == SUCCESS) {
1456 struct encoding *encoding = *encoding_ref;
1458 if (encoding && !priority)
1459 return code;
1460 encoding = encoding_open(buf);
1461 if (encoding)
1462 *encoding_ref = encoding;
1465 return code;
1468 static enum status_code
1469 parse_args(const char ***args, const char *argv[])
1471 if (!argv_copy(args, argv))
1472 return ERROR_OUT_OF_MEMORY;
1473 return SUCCESS;
1476 /* Wants: name = value */
1477 static enum status_code
1478 option_set_command(int argc, const char *argv[])
1480 if (argc < 3)
1481 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1483 if (strcmp(argv[1], "="))
1484 return ERROR_NO_VALUE_ASSIGNED;
1486 if (!strcmp(argv[0], "blame-options"))
1487 return parse_args(&opt_blame_argv, argv + 2);
1489 if (!strcmp(argv[0], "diff-options"))
1490 return parse_args(&opt_diff_argv, argv + 2);
1492 if (argc != 3)
1493 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1495 if (!strcmp(argv[0], "show-author"))
1496 return parse_enum(&opt_author, argv[2], author_map);
1498 if (!strcmp(argv[0], "show-date"))
1499 return parse_enum(&opt_date, argv[2], date_map);
1501 if (!strcmp(argv[0], "show-rev-graph"))
1502 return parse_bool(&opt_rev_graph, argv[2]);
1504 if (!strcmp(argv[0], "show-refs"))
1505 return parse_bool(&opt_show_refs, argv[2]);
1507 if (!strcmp(argv[0], "show-changes"))
1508 return parse_bool(&opt_show_changes, argv[2]);
1510 if (!strcmp(argv[0], "show-notes")) {
1511 bool matched = FALSE;
1512 enum status_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1514 if (res == SUCCESS && matched) {
1515 update_notes_arg();
1516 return res;
1519 opt_notes = TRUE;
1520 strcpy(opt_notes_arg, "--show-notes=");
1521 res = parse_string(opt_notes_arg + 8, argv[2],
1522 sizeof(opt_notes_arg) - 8);
1523 if (res == SUCCESS && opt_notes_arg[8] == '\0')
1524 opt_notes_arg[7] = '\0';
1525 return res;
1528 if (!strcmp(argv[0], "show-line-numbers"))
1529 return parse_bool(&opt_line_number, argv[2]);
1531 if (!strcmp(argv[0], "line-graphics"))
1532 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1534 if (!strcmp(argv[0], "line-number-interval"))
1535 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1537 if (!strcmp(argv[0], "author-width"))
1538 return parse_int(&opt_author_width, argv[2], 0, 1024);
1540 if (!strcmp(argv[0], "filename-width"))
1541 return parse_int(&opt_filename_width, argv[2], 0, 1024);
1543 if (!strcmp(argv[0], "show-filename"))
1544 return parse_enum(&opt_filename, argv[2], filename_map);
1546 if (!strcmp(argv[0], "show-file-size"))
1547 return parse_enum(&opt_file_size, argv[2], file_size_map);
1549 if (!strcmp(argv[0], "horizontal-scroll"))
1550 return parse_step(&opt_hscroll, argv[2]);
1552 if (!strcmp(argv[0], "split-view-height"))
1553 return parse_step(&opt_scale_split_view, argv[2]);
1555 if (!strcmp(argv[0], "vertical-split"))
1556 return parse_bool(&opt_vsplit, argv[2]);
1558 if (!strcmp(argv[0], "tab-size"))
1559 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1561 if (!strcmp(argv[0], "diff-context")) {
1562 enum status_code code = parse_int(&opt_diff_context, argv[2], 0, 999999);
1564 if (code == SUCCESS)
1565 update_diff_context_arg(opt_diff_context);
1566 return code;
1569 if (!strcmp(argv[0], "ignore-space")) {
1570 enum status_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1572 if (code == SUCCESS)
1573 update_ignore_space_arg();
1574 return code;
1577 if (!strcmp(argv[0], "commit-order")) {
1578 enum status_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1580 if (code == SUCCESS)
1581 update_commit_order_arg();
1582 return code;
1585 if (!strcmp(argv[0], "status-untracked-dirs"))
1586 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1588 if (!strcmp(argv[0], "read-git-colors"))
1589 return parse_bool(&opt_read_git_colors, argv[2]);
1591 if (!strcmp(argv[0], "ignore-case"))
1592 return parse_bool(&opt_ignore_case, argv[2]);
1594 if (!strcmp(argv[0], "focus-child"))
1595 return parse_bool(&opt_focus_child, argv[2]);
1597 if (!strcmp(argv[0], "wrap-lines"))
1598 return parse_bool(&opt_wrap_lines, argv[2]);
1600 if (!strcmp(argv[0], "show-id"))
1601 return parse_bool(&opt_show_id, argv[2]);
1603 if (!strcmp(argv[0], "id-width"))
1604 return parse_id(&opt_id_cols, argv[2]);
1606 if (!strcmp(argv[0], "title-overflow")) {
1607 bool matched;
1608 enum status_code code;
1611 * "title-overflow" is considered a boolint.
1612 * We try to parse it as a boolean (and set the value to 50 if true),
1613 * otherwise we parse it as an integer and use the given value.
1615 code = parse_bool_matched(&opt_show_title_overflow, argv[2], &matched);
1616 if (code == SUCCESS && matched) {
1617 if (opt_show_title_overflow)
1618 opt_title_overflow = 50;
1619 } else {
1620 code = parse_int(&opt_title_overflow, argv[2], 2, 1024);
1621 if (code == SUCCESS)
1622 opt_show_title_overflow = TRUE;
1625 return code;
1628 if (!strcmp(argv[0], "editor-line-number"))
1629 return parse_bool(&opt_editor_lineno, argv[2]);
1631 return ERROR_UNKNOWN_VARIABLE_NAME;
1634 /* Wants: mode request key */
1635 static enum status_code
1636 option_bind_command(int argc, const char *argv[])
1638 enum request request;
1639 struct keymap *keymap;
1640 int key;
1642 if (argc < 3)
1643 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1645 if (!(keymap = get_keymap(argv[0])))
1646 return ERROR_UNKNOWN_KEY_MAP;
1648 key = get_key_value(argv[1]);
1649 if (key == ERR)
1650 return ERROR_UNKNOWN_KEY;
1652 request = get_request(argv[2]);
1653 if (request == REQ_UNKNOWN) {
1654 static const struct enum_map obsolete[] = {
1655 ENUM_MAP("cherry-pick", REQ_NONE),
1656 ENUM_MAP("screen-resize", REQ_NONE),
1657 ENUM_MAP("tree-parent", REQ_PARENT),
1659 int alias;
1661 if (map_enum(&alias, obsolete, argv[2])) {
1662 if (alias != REQ_NONE)
1663 add_keybinding(keymap, alias, key);
1664 return ERROR_OBSOLETE_REQUEST_NAME;
1668 if (request == REQ_UNKNOWN) {
1669 enum run_request_flag flags = RUN_REQUEST_FORCE;
1671 if (strchr("!?@<", *argv[2])) {
1672 while (*argv[2]) {
1673 if (*argv[2] == '@') {
1674 flags |= RUN_REQUEST_SILENT;
1675 } else if (*argv[2] == '?') {
1676 flags |= RUN_REQUEST_CONFIRM;
1677 } else if (*argv[2] == '<') {
1678 flags |= RUN_REQUEST_EXIT;
1679 } else if (*argv[2] != '!') {
1680 break;
1682 argv[2]++;
1685 } else if (*argv[2] == ':') {
1686 argv[2]++;
1687 flags |= RUN_REQUEST_INTERNAL;
1689 } else {
1690 return ERROR_UNKNOWN_REQUEST_NAME;
1693 return add_run_request(keymap, key, argv + 2, flags)
1694 ? SUCCESS : ERROR_OUT_OF_MEMORY;
1697 add_keybinding(keymap, request, key);
1699 return SUCCESS;
1703 static enum status_code load_option_file(const char *path);
1705 static enum status_code
1706 option_source_command(int argc, const char *argv[])
1708 if (argc < 1)
1709 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1711 return load_option_file(argv[0]);
1714 static enum status_code
1715 set_option(const char *opt, char *value)
1717 const char *argv[SIZEOF_ARG];
1718 int argc = 0;
1720 if (!argv_from_string(argv, &argc, value))
1721 return ERROR_TOO_MANY_OPTION_ARGUMENTS;
1723 if (!strcmp(opt, "color"))
1724 return option_color_command(argc, argv);
1726 if (!strcmp(opt, "set"))
1727 return option_set_command(argc, argv);
1729 if (!strcmp(opt, "bind"))
1730 return option_bind_command(argc, argv);
1732 if (!strcmp(opt, "source"))
1733 return option_source_command(argc, argv);
1735 return ERROR_UNKNOWN_OPTION_COMMAND;
1738 struct config_state {
1739 const char *path;
1740 int lineno;
1741 bool errors;
1744 static int
1745 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1747 struct config_state *config = data;
1748 enum status_code status = ERROR_NO_OPTION_VALUE;
1750 config->lineno++;
1752 /* Check for comment markers, since read_properties() will
1753 * only ensure opt and value are split at first " \t". */
1754 optlen = strcspn(opt, "#");
1755 if (optlen == 0)
1756 return OK;
1758 if (opt[optlen] == 0) {
1759 /* Look for comment endings in the value. */
1760 size_t len = strcspn(value, "#");
1762 if (len < valuelen) {
1763 valuelen = len;
1764 value[valuelen] = 0;
1767 status = set_option(opt, value);
1770 if (status != SUCCESS) {
1771 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1772 get_status_message(status), (int) optlen, opt);
1773 config->errors = TRUE;
1776 /* Always keep going if errors are encountered. */
1777 return OK;
1780 static enum status_code
1781 load_option_file(const char *path)
1783 struct config_state config = { path, 0, FALSE };
1784 struct io io;
1785 char buf[SIZEOF_STR];
1787 /* Do not read configuration from stdin if set to "" */
1788 if (!path || !strlen(path))
1789 return SUCCESS;
1791 if (!prefixcmp(path, "~/")) {
1792 const char *home = getenv("HOME");
1794 if (!home || !string_format(buf, "%s/%s", home, path + 2))
1795 return ERROR_HOME_UNRESOLVABLE;
1796 path = buf;
1799 /* It's OK that the file doesn't exist. */
1800 if (!io_open(&io, "%s", path))
1801 return ERROR_FILE_DOES_NOT_EXIST;
1803 if (io_load(&io, " \t", read_option, &config) == ERR ||
1804 config.errors == TRUE)
1805 warn("Errors while loading %s.", path);
1806 return SUCCESS;
1809 static int
1810 load_options(void)
1812 const char *tigrc_user = getenv("TIGRC_USER");
1813 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1814 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1815 const bool diff_opts_from_args = !!opt_diff_argv;
1817 if (!tigrc_system)
1818 tigrc_system = SYSCONFDIR "/tigrc";
1819 load_option_file(tigrc_system);
1821 if (!tigrc_user)
1822 tigrc_user = "~/.tigrc";
1823 load_option_file(tigrc_user);
1825 /* Add _after_ loading config files to avoid adding run requests
1826 * that conflict with keybindings. */
1827 add_builtin_run_requests();
1829 if (!diff_opts_from_args && tig_diff_opts && *tig_diff_opts) {
1830 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1831 char buf[SIZEOF_STR];
1832 int argc = 0;
1834 if (!string_format(buf, "%s", tig_diff_opts) ||
1835 !argv_from_string(diff_opts, &argc, buf))
1836 die("TIG_DIFF_OPTS contains too many arguments");
1837 else if (!argv_copy(&opt_diff_argv, diff_opts))
1838 die("Failed to format TIG_DIFF_OPTS arguments");
1841 return OK;
1846 * The viewer
1849 struct view;
1850 struct view_ops;
1852 /* The display array of active views and the index of the current view. */
1853 static struct view *display[2];
1854 static WINDOW *display_win[2];
1855 static WINDOW *display_title[2];
1856 static WINDOW *display_sep;
1858 static unsigned int current_view;
1860 #define foreach_displayed_view(view, i) \
1861 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1863 #define displayed_views() (display[1] != NULL ? 2 : 1)
1865 /* Current head and commit ID */
1866 static char ref_blob[SIZEOF_REF] = "";
1867 static char ref_commit[SIZEOF_REF] = "HEAD";
1868 static char ref_head[SIZEOF_REF] = "HEAD";
1869 static char ref_branch[SIZEOF_REF] = "";
1870 static char ref_status[SIZEOF_STR] = "";
1871 static char ref_stash[SIZEOF_REF] = "";
1873 enum view_flag {
1874 VIEW_NO_FLAGS = 0,
1875 VIEW_ALWAYS_LINENO = 1 << 0,
1876 VIEW_CUSTOM_STATUS = 1 << 1,
1877 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1878 VIEW_ADD_PAGER_REFS = 1 << 3,
1879 VIEW_OPEN_DIFF = 1 << 4,
1880 VIEW_NO_REF = 1 << 5,
1881 VIEW_NO_GIT_DIR = 1 << 6,
1882 VIEW_DIFF_LIKE = 1 << 7,
1883 VIEW_SEND_CHILD_ENTER = 1 << 9,
1884 VIEW_FILE_FILTER = 1 << 10,
1885 VIEW_LOG_LIKE = 1 << 11,
1886 VIEW_STATUS_LIKE = 1 << 12,
1889 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1891 struct position {
1892 unsigned long offset; /* Offset of the window top */
1893 unsigned long col; /* Offset from the window side. */
1894 unsigned long lineno; /* Current line number */
1897 struct view {
1898 const char *name; /* View name */
1899 const char *id; /* Points to either of ref_{head,commit,blob} */
1901 struct view_ops *ops; /* View operations */
1903 char ref[SIZEOF_REF]; /* Hovered commit reference */
1904 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1906 int height, width; /* The width and height of the main window */
1907 WINDOW *win; /* The main window */
1909 /* Navigation */
1910 struct position pos; /* Current position. */
1911 struct position prev_pos; /* Previous position. */
1913 /* Searching */
1914 char grep[SIZEOF_STR]; /* Search string */
1915 regex_t *regex; /* Pre-compiled regexp */
1917 /* If non-NULL, points to the view that opened this view. If this view
1918 * is closed tig will switch back to the parent view. */
1919 struct view *parent;
1920 struct view *prev;
1922 /* Buffering */
1923 size_t lines; /* Total number of lines */
1924 struct line *line; /* Line index */
1925 unsigned int digits; /* Number of digits in the lines member. */
1927 /* Number of lines with custom status, not to be counted in the
1928 * view title. */
1929 unsigned int custom_lines;
1931 /* Drawing */
1932 struct line *curline; /* Line currently being drawn. */
1933 enum line_type curtype; /* Attribute currently used for drawing. */
1934 unsigned long col; /* Column when drawing. */
1935 bool has_scrolled; /* View was scrolled. */
1936 bool force_redraw; /* Whether to force a redraw after reading. */
1938 /* Loading */
1939 const char **argv; /* Shell command arguments. */
1940 const char *dir; /* Directory from which to execute. */
1941 struct io io;
1942 struct io *pipe;
1943 time_t start_time;
1944 time_t update_secs;
1945 struct encoding *encoding;
1946 bool unrefreshable;
1948 /* Private data */
1949 void *private;
1952 enum open_flags {
1953 OPEN_DEFAULT = 0, /* Use default view switching. */
1954 OPEN_STDIN = 1, /* Open in pager mode. */
1955 OPEN_FORWARD_STDIN = 2, /* Forward stdin to I/O process. */
1956 OPEN_SPLIT = 4, /* Split current view. */
1957 OPEN_RELOAD = 8, /* Reload view even if it is the current. */
1958 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1959 OPEN_PREPARED = 32, /* Open already prepared command. */
1960 OPEN_EXTRA = 64, /* Open extra data from command. */
1962 OPEN_PAGER_MODE = OPEN_STDIN | OPEN_FORWARD_STDIN,
1965 #define open_in_pager_mode(flags) ((flags) & OPEN_PAGER_MODE)
1966 #define open_from_stdin(flags) ((flags) & OPEN_STDIN)
1968 struct view_ops {
1969 /* What type of content being displayed. Used in the title bar. */
1970 const char *type;
1971 /* What keymap does this view have */
1972 struct keymap keymap;
1973 /* Flags to control the view behavior. */
1974 enum view_flag flags;
1975 /* Size of private data. */
1976 size_t private_size;
1977 /* Open and reads in all view content. */
1978 bool (*open)(struct view *view, enum open_flags flags);
1979 /* Read one line; updates view->line. */
1980 bool (*read)(struct view *view, char *data);
1981 /* Draw one line; @lineno must be < view->height. */
1982 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1983 /* Depending on view handle a special requests. */
1984 enum request (*request)(struct view *view, enum request request, struct line *line);
1985 /* Search for regexp in a line. */
1986 bool (*grep)(struct view *view, struct line *line);
1987 /* Select line */
1988 void (*select)(struct view *view, struct line *line);
1989 /* Release resources when reloading the view */
1990 void (*done)(struct view *view);
1993 #define VIEW_OPS(id, name, ref) name##_ops
1994 static struct view_ops VIEW_INFO(VIEW_OPS);
1996 static struct view views[] = {
1997 #define VIEW_DATA(id, name, ref) \
1998 { #name, ref, &name##_ops }
1999 VIEW_INFO(VIEW_DATA)
2002 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
2004 #define foreach_view(view, i) \
2005 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2007 #define view_is_displayed(view) \
2008 (view == display[0] || view == display[1])
2010 #define view_has_line(view, line_) \
2011 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
2013 static bool
2014 forward_request_to_child(struct view *child, enum request request)
2016 return displayed_views() == 2 && view_is_displayed(child) &&
2017 !strcmp(child->vid, child->id);
2020 static enum request
2021 view_request(struct view *view, enum request request)
2023 if (!view || !view->lines)
2024 return request;
2026 if (request == REQ_ENTER && !opt_focus_child &&
2027 view_has_flags(view, VIEW_SEND_CHILD_ENTER)) {
2028 struct view *child = display[1];
2030 if (forward_request_to_child(child, request)) {
2031 view_request(child, request);
2032 return REQ_NONE;
2036 if (request == REQ_REFRESH && view->unrefreshable) {
2037 report("This view can not be refreshed");
2038 return REQ_NONE;
2041 return view->ops->request(view, request, &view->line[view->pos.lineno]);
2045 * View drawing.
2048 static inline void
2049 set_view_attr(struct view *view, enum line_type type)
2051 if (!view->curline->selected && view->curtype != type) {
2052 (void) wattrset(view->win, get_line_attr(type));
2053 wchgat(view->win, -1, 0, get_line_color(type), NULL);
2054 view->curtype = type;
2058 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
2060 static bool
2061 draw_chars(struct view *view, enum line_type type, const char *string,
2062 int max_len, bool use_tilde)
2064 int len = 0;
2065 int col = 0;
2066 int trimmed = FALSE;
2067 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2069 if (max_len <= 0)
2070 return VIEW_MAX_LEN(view) <= 0;
2072 if (opt_iconv_out != ICONV_NONE) {
2073 string = encoding_iconv(opt_iconv_out, string);
2074 if (!string)
2075 return VIEW_MAX_LEN(view) <= 0;
2078 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
2080 set_view_attr(view, type);
2081 if (len > 0) {
2082 waddnstr(view->win, string, len);
2084 if (trimmed && use_tilde) {
2085 set_view_attr(view, LINE_DELIMITER);
2086 waddch(view->win, '~');
2087 col++;
2091 view->col += col;
2092 return VIEW_MAX_LEN(view) <= 0;
2095 static bool
2096 draw_space(struct view *view, enum line_type type, int max, int spaces)
2098 static char space[] = " ";
2100 spaces = MIN(max, spaces);
2102 while (spaces > 0) {
2103 int len = MIN(spaces, sizeof(space) - 1);
2105 if (draw_chars(view, type, space, len, FALSE))
2106 return TRUE;
2107 spaces -= len;
2110 return VIEW_MAX_LEN(view) <= 0;
2113 static bool
2114 draw_text_expanded(struct view *view, enum line_type type, const char *string, int max_len, bool use_tilde)
2116 static char text[SIZEOF_STR];
2118 do {
2119 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
2121 if (draw_chars(view, type, text, max_len, use_tilde))
2122 return TRUE;
2123 string += pos;
2124 } while (*string);
2126 return VIEW_MAX_LEN(view) <= 0;
2129 static bool
2130 draw_text(struct view *view, enum line_type type, const char *string)
2132 return draw_text_expanded(view, type, string, VIEW_MAX_LEN(view), TRUE);
2135 static bool
2136 draw_text_overflow(struct view *view, const char *text, bool on, int overflow, enum line_type type)
2138 if (on) {
2139 int max = MIN(VIEW_MAX_LEN(view), overflow);
2140 int len = strlen(text);
2142 if (draw_text_expanded(view, type, text, max, max < overflow))
2143 return TRUE;
2145 text = len > overflow ? text + overflow : "";
2146 type = LINE_OVERFLOW;
2149 if (*text && draw_text(view, type, text))
2150 return TRUE;
2152 return VIEW_MAX_LEN(view) <= 0;
2155 #define draw_commit_title(view, text, offset) \
2156 draw_text_overflow(view, text, opt_show_title_overflow, opt_title_overflow + offset, LINE_DEFAULT)
2158 static bool PRINTF_LIKE(3, 4)
2159 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
2161 char text[SIZEOF_STR];
2162 int retval;
2164 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
2165 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
2168 static bool
2169 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
2171 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2172 int max = VIEW_MAX_LEN(view);
2173 int i;
2175 if (max < size)
2176 size = max;
2178 set_view_attr(view, type);
2179 /* Using waddch() instead of waddnstr() ensures that
2180 * they'll be rendered correctly for the cursor line. */
2181 for (i = skip; i < size; i++)
2182 waddch(view->win, graphic[i]);
2184 view->col += size;
2185 if (separator) {
2186 if (size < max && skip <= size)
2187 waddch(view->win, ' ');
2188 view->col++;
2191 return VIEW_MAX_LEN(view) <= 0;
2194 enum align {
2195 ALIGN_LEFT,
2196 ALIGN_RIGHT
2199 static bool
2200 draw_field(struct view *view, enum line_type type, const char *text, int width, enum align align, bool trim)
2202 int max = MIN(VIEW_MAX_LEN(view), width + 1);
2203 int col = view->col;
2205 if (!text)
2206 return draw_space(view, type, max, max);
2208 if (align == ALIGN_RIGHT) {
2209 int textlen = strlen(text);
2210 int leftpad = max - textlen - 1;
2212 if (leftpad > 0) {
2213 if (draw_space(view, type, leftpad, leftpad))
2214 return TRUE;
2215 max -= leftpad;
2216 col += leftpad;;
2220 return draw_chars(view, type, text, max - 1, trim)
2221 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2224 static bool
2225 draw_date(struct view *view, struct time *time)
2227 const char *date = mkdate(time, opt_date);
2228 int cols = opt_date == DATE_SHORT ? DATE_SHORT_WIDTH : DATE_WIDTH;
2230 if (opt_date == DATE_NO)
2231 return FALSE;
2233 return draw_field(view, LINE_DATE, date, cols, ALIGN_LEFT, FALSE);
2236 static bool
2237 draw_author(struct view *view, const struct ident *author)
2239 bool trim = author_trim(opt_author_width);
2240 const char *text = mkauthor(author, opt_author_width, opt_author);
2242 if (opt_author == AUTHOR_NO)
2243 return FALSE;
2245 return draw_field(view, LINE_AUTHOR, text, opt_author_width, ALIGN_LEFT, trim);
2248 static bool
2249 draw_id_custom(struct view *view, enum line_type type, const char *id, int width)
2251 return draw_field(view, type, id, width, ALIGN_LEFT, FALSE);
2254 static bool
2255 draw_id(struct view *view, const char *id)
2257 if (!opt_show_id)
2258 return FALSE;
2260 return draw_id_custom(view, LINE_ID, id, opt_id_cols);
2263 static bool
2264 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2266 bool trim = filename && strlen(filename) >= opt_filename_width;
2268 if (opt_filename == FILENAME_NO)
2269 return FALSE;
2271 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2272 return FALSE;
2274 return draw_field(view, LINE_FILENAME, filename, opt_filename_width, ALIGN_LEFT, trim);
2277 static bool
2278 draw_file_size(struct view *view, unsigned long size, int width, bool pad)
2280 const char *str = pad ? NULL : mkfilesize(size, opt_file_size);
2282 if (!width || opt_file_size == FILE_SIZE_NO)
2283 return FALSE;
2285 return draw_field(view, LINE_FILE_SIZE, str, width, ALIGN_RIGHT, FALSE);
2288 static bool
2289 draw_mode(struct view *view, mode_t mode)
2291 const char *str = mkmode(mode);
2293 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r--"), ALIGN_LEFT, FALSE);
2296 static bool
2297 draw_lineno(struct view *view, unsigned int lineno)
2299 char number[10];
2300 int digits3 = view->digits < 3 ? 3 : view->digits;
2301 int max = MIN(VIEW_MAX_LEN(view), digits3);
2302 char *text = NULL;
2303 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2305 if (!opt_line_number)
2306 return FALSE;
2308 lineno += view->pos.offset + 1;
2309 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2310 static char fmt[] = "%1ld";
2312 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2313 if (string_format(number, fmt, lineno))
2314 text = number;
2316 if (text)
2317 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2318 else
2319 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2320 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2323 static bool
2324 draw_refs(struct view *view, struct ref_list *refs)
2326 size_t i;
2328 if (!opt_show_refs || !refs)
2329 return FALSE;
2331 for (i = 0; i < refs->size; i++) {
2332 struct ref *ref = refs->refs[i];
2333 enum line_type type = get_line_type_from_ref(ref);
2335 if (draw_formatted(view, type, "[%s]", ref->name))
2336 return TRUE;
2338 if (draw_text(view, LINE_DEFAULT, " "))
2339 return TRUE;
2342 return FALSE;
2345 static bool
2346 draw_view_line(struct view *view, unsigned int lineno)
2348 struct line *line;
2349 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2351 assert(view_is_displayed(view));
2353 if (view->pos.offset + lineno >= view->lines)
2354 return FALSE;
2356 line = &view->line[view->pos.offset + lineno];
2358 wmove(view->win, lineno, 0);
2359 if (line->cleareol)
2360 wclrtoeol(view->win);
2361 view->col = 0;
2362 view->curline = line;
2363 view->curtype = LINE_NONE;
2364 line->selected = FALSE;
2365 line->dirty = line->cleareol = 0;
2367 if (selected) {
2368 set_view_attr(view, LINE_CURSOR);
2369 line->selected = TRUE;
2370 view->ops->select(view, line);
2373 return view->ops->draw(view, line, lineno);
2376 static void
2377 redraw_view_dirty(struct view *view)
2379 bool dirty = FALSE;
2380 int lineno;
2382 for (lineno = 0; lineno < view->height; lineno++) {
2383 if (view->pos.offset + lineno >= view->lines)
2384 break;
2385 if (!view->line[view->pos.offset + lineno].dirty)
2386 continue;
2387 dirty = TRUE;
2388 if (!draw_view_line(view, lineno))
2389 break;
2392 if (!dirty)
2393 return;
2394 wnoutrefresh(view->win);
2397 static void
2398 redraw_view_from(struct view *view, int lineno)
2400 assert(0 <= lineno && lineno < view->height);
2402 for (; lineno < view->height; lineno++) {
2403 if (!draw_view_line(view, lineno))
2404 break;
2407 wnoutrefresh(view->win);
2410 static void
2411 redraw_view(struct view *view)
2413 werase(view->win);
2414 redraw_view_from(view, 0);
2418 static void
2419 update_view_title(struct view *view)
2421 char buf[SIZEOF_STR];
2422 char state[SIZEOF_STR];
2423 size_t bufpos = 0, statelen = 0;
2424 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2425 struct line *line = &view->line[view->pos.lineno];
2427 assert(view_is_displayed(view));
2429 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view_has_line(view, line) &&
2430 line->lineno) {
2431 unsigned int view_lines = view->pos.offset + view->height;
2432 unsigned int lines = view->lines
2433 ? MIN(view_lines, view->lines) * 100 / view->lines
2434 : 0;
2436 string_format_from(state, &statelen, " - %s %d of %zd (%d%%)",
2437 view->ops->type,
2438 line->lineno,
2439 view->lines - view->custom_lines,
2440 lines);
2444 if (view->pipe) {
2445 time_t secs = time(NULL) - view->start_time;
2447 /* Three git seconds are a long time ... */
2448 if (secs > 2)
2449 string_format_from(state, &statelen, " loading %lds", secs);
2452 string_format_from(buf, &bufpos, "[%s]", view->name);
2453 if (*view->ref && bufpos < view->width) {
2454 size_t refsize = strlen(view->ref);
2455 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2457 if (minsize < view->width)
2458 refsize = view->width - minsize + 7;
2459 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2462 if (statelen && bufpos < view->width) {
2463 string_format_from(buf, &bufpos, "%s", state);
2466 if (view == display[current_view])
2467 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2468 else
2469 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2471 mvwaddnstr(window, 0, 0, buf, bufpos);
2472 wclrtoeol(window);
2473 wnoutrefresh(window);
2476 static int
2477 apply_step(double step, int value)
2479 if (step >= 1)
2480 return (int) step;
2481 value *= step + 0.01;
2482 return value ? value : 1;
2485 static void
2486 apply_horizontal_split(struct view *base, struct view *view)
2488 view->width = base->width;
2489 view->height = apply_step(opt_scale_split_view, base->height);
2490 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2491 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2492 base->height -= view->height;
2495 static void
2496 apply_vertical_split(struct view *base, struct view *view)
2498 view->height = base->height;
2499 view->width = apply_step(opt_scale_vsplit_view, base->width);
2500 view->width = MAX(view->width, MIN_VIEW_WIDTH);
2501 view->width = MIN(view->width, base->width - MIN_VIEW_WIDTH);
2502 base->width -= view->width;
2505 static void
2506 redraw_display_separator(bool clear)
2508 if (displayed_views() > 1 && opt_vsplit) {
2509 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2511 if (clear)
2512 wclear(display_sep);
2513 wbkgd(display_sep, separator + get_line_attr(LINE_TITLE_BLUR));
2514 wnoutrefresh(display_sep);
2518 static void
2519 resize_display(void)
2521 int x, y, i;
2522 struct view *base = display[0];
2523 struct view *view = display[1] ? display[1] : display[0];
2525 /* Setup window dimensions */
2527 getmaxyx(stdscr, base->height, base->width);
2528 string_format(opt_env_columns, "COLUMNS=%d", base->width);
2529 string_format(opt_env_lines, "LINES=%d", base->height);
2531 /* Make room for the status window. */
2532 base->height -= 1;
2534 if (view != base) {
2535 if (opt_vsplit) {
2536 apply_vertical_split(base, view);
2538 /* Make room for the separator bar. */
2539 view->width -= 1;
2540 } else {
2541 apply_horizontal_split(base, view);
2544 /* Make room for the title bar. */
2545 view->height -= 1;
2548 /* Make room for the title bar. */
2549 base->height -= 1;
2551 x = y = 0;
2553 foreach_displayed_view (view, i) {
2554 if (!display_win[i]) {
2555 display_win[i] = newwin(view->height, view->width, y, x);
2556 if (!display_win[i])
2557 die("Failed to create %s view", view->name);
2559 scrollok(display_win[i], FALSE);
2561 display_title[i] = newwin(1, view->width, y + view->height, x);
2562 if (!display_title[i])
2563 die("Failed to create title window");
2565 } else {
2566 wresize(display_win[i], view->height, view->width);
2567 mvwin(display_win[i], y, x);
2568 wresize(display_title[i], 1, view->width);
2569 mvwin(display_title[i], y + view->height, x);
2572 if (i > 0 && opt_vsplit) {
2573 if (!display_sep) {
2574 display_sep = newwin(view->height, 1, 0, x - 1);
2575 if (!display_sep)
2576 die("Failed to create separator window");
2578 } else {
2579 wresize(display_sep, view->height, 1);
2580 mvwin(display_sep, 0, x - 1);
2584 view->win = display_win[i];
2586 if (opt_vsplit)
2587 x += view->width + 1;
2588 else
2589 y += view->height + 1;
2592 redraw_display_separator(FALSE);
2595 static void
2596 redraw_display(bool clear)
2598 struct view *view;
2599 int i;
2601 foreach_displayed_view (view, i) {
2602 if (clear)
2603 wclear(view->win);
2604 redraw_view(view);
2605 update_view_title(view);
2608 redraw_display_separator(clear);
2612 * Option management
2615 #define TOGGLE_MENU_INFO(_) \
2616 _(LINENO, '.', "line numbers", &opt_line_number, NULL, 0, VIEW_NO_FLAGS), \
2617 _(DATE, 'D', "dates", &opt_date, date_map, ARRAY_SIZE(date_map), VIEW_NO_FLAGS), \
2618 _(AUTHOR, 'A', "author", &opt_author, author_map, ARRAY_SIZE(author_map), VIEW_NO_FLAGS), \
2619 _(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map, ARRAY_SIZE(graphic_map), VIEW_NO_FLAGS), \
2620 _(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL, 0, VIEW_LOG_LIKE), \
2621 _(FILENAME, '#', "file names", &opt_filename, filename_map, ARRAY_SIZE(filename_map), VIEW_NO_FLAGS), \
2622 _(FILE_SIZE, '*', "file sizes", &opt_file_size, file_size_map, ARRAY_SIZE(file_size_map), VIEW_NO_FLAGS), \
2623 _(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map, ARRAY_SIZE(ignore_space_map), VIEW_DIFF_LIKE), \
2624 _(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map, ARRAY_SIZE(commit_order_map), VIEW_LOG_LIKE), \
2625 _(REFS, 'F', "reference display", &opt_show_refs, NULL, 0, VIEW_NO_FLAGS), \
2626 _(CHANGES, 'C', "local change display", &opt_show_changes, NULL, 0, VIEW_NO_FLAGS), \
2627 _(ID, 'X', "commit ID display", &opt_show_id, NULL, 0, VIEW_NO_FLAGS), \
2628 _(FILES, '%', "file filtering", &opt_file_filter, NULL, 0, VIEW_DIFF_LIKE | VIEW_LOG_LIKE), \
2629 _(TITLE_OVERFLOW, '$', "commit title overflow display", &opt_show_title_overflow, NULL, 0, VIEW_NO_FLAGS), \
2630 _(UNTRACKED_DIRS, 'd', "untracked directory info", &opt_untracked_dirs_content, NULL, 0, VIEW_STATUS_LIKE), \
2632 static enum view_flag
2633 toggle_option(struct view *view, enum request request, char msg[SIZEOF_STR])
2635 const struct {
2636 enum request request;
2637 const struct enum_map *map;
2638 size_t map_size;
2639 enum view_flag reload_flags;
2640 } data[] = {
2641 #define DEFINE_TOGGLE_DATA(id, key, help, value, map, map_size, vflags) { REQ_TOGGLE_ ## id, map, map_size, vflags }
2642 TOGGLE_MENU_INFO(DEFINE_TOGGLE_DATA)
2644 const struct menu_item menu[] = {
2645 #define DEFINE_TOGGLE_MENU(id, key, help, value, map, map_size, vflags) { key, help, value }
2646 TOGGLE_MENU_INFO(DEFINE_TOGGLE_MENU)
2647 { 0 }
2649 int i = 0;
2651 if (request == REQ_OPTIONS) {
2652 if (!prompt_menu("Toggle option", menu, &i))
2653 return VIEW_NO_FLAGS;
2654 } else {
2655 while (i < ARRAY_SIZE(data) && data[i].request != request)
2656 i++;
2657 if (i >= ARRAY_SIZE(data))
2658 die("Invalid request (%d)", request);
2661 if (data[i].map != NULL) {
2662 unsigned int *opt = menu[i].data;
2664 *opt = (*opt + 1) % data[i].map_size;
2665 if (data[i].map == ignore_space_map) {
2666 update_ignore_space_arg();
2667 string_format_size(msg, SIZEOF_STR,
2668 "Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2670 } else if (data[i].map == commit_order_map) {
2671 update_commit_order_arg();
2672 string_format_size(msg, SIZEOF_STR,
2673 "Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2675 } else {
2676 string_format_size(msg, SIZEOF_STR,
2677 "Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2680 } else {
2681 bool *option = menu[i].data;
2683 *option = !*option;
2684 string_format_size(msg, SIZEOF_STR,
2685 "%sabling %s", *option ? "En" : "Dis", menu[i].text);
2688 return data[i].reload_flags;
2693 * Navigation
2696 static bool
2697 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2699 if (lineno >= view->lines)
2700 lineno = view->lines > 0 ? view->lines - 1 : 0;
2702 if (offset > lineno || offset + view->height <= lineno) {
2703 unsigned long half = view->height / 2;
2705 if (lineno > half)
2706 offset = lineno - half;
2707 else
2708 offset = 0;
2711 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2712 view->pos.offset = offset;
2713 view->pos.lineno = lineno;
2714 return TRUE;
2717 return FALSE;
2720 /* Scrolling backend */
2721 static void
2722 do_scroll_view(struct view *view, int lines)
2724 bool redraw_current_line = FALSE;
2726 /* The rendering expects the new offset. */
2727 view->pos.offset += lines;
2729 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2730 assert(lines);
2732 /* Move current line into the view. */
2733 if (view->pos.lineno < view->pos.offset) {
2734 view->pos.lineno = view->pos.offset;
2735 redraw_current_line = TRUE;
2736 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2737 view->pos.lineno = view->pos.offset + view->height - 1;
2738 redraw_current_line = TRUE;
2741 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2743 /* Redraw the whole screen if scrolling is pointless. */
2744 if (view->height < ABS(lines)) {
2745 redraw_view(view);
2747 } else {
2748 int line = lines > 0 ? view->height - lines : 0;
2749 int end = line + ABS(lines);
2751 scrollok(view->win, TRUE);
2752 wscrl(view->win, lines);
2753 scrollok(view->win, FALSE);
2755 while (line < end && draw_view_line(view, line))
2756 line++;
2758 if (redraw_current_line)
2759 draw_view_line(view, view->pos.lineno - view->pos.offset);
2760 wnoutrefresh(view->win);
2763 view->has_scrolled = TRUE;
2764 report_clear();
2767 /* Scroll frontend */
2768 static void
2769 scroll_view(struct view *view, enum request request)
2771 int lines = 1;
2773 assert(view_is_displayed(view));
2775 switch (request) {
2776 case REQ_SCROLL_FIRST_COL:
2777 view->pos.col = 0;
2778 redraw_view_from(view, 0);
2779 report_clear();
2780 return;
2781 case REQ_SCROLL_LEFT:
2782 if (view->pos.col == 0) {
2783 report("Cannot scroll beyond the first column");
2784 return;
2786 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2787 view->pos.col = 0;
2788 else
2789 view->pos.col -= apply_step(opt_hscroll, view->width);
2790 redraw_view_from(view, 0);
2791 report_clear();
2792 return;
2793 case REQ_SCROLL_RIGHT:
2794 view->pos.col += apply_step(opt_hscroll, view->width);
2795 redraw_view(view);
2796 report_clear();
2797 return;
2798 case REQ_SCROLL_PAGE_DOWN:
2799 lines = view->height;
2800 case REQ_SCROLL_LINE_DOWN:
2801 if (view->pos.offset + lines > view->lines)
2802 lines = view->lines - view->pos.offset;
2804 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2805 report("Cannot scroll beyond the last line");
2806 return;
2808 break;
2810 case REQ_SCROLL_PAGE_UP:
2811 lines = view->height;
2812 case REQ_SCROLL_LINE_UP:
2813 if (lines > view->pos.offset)
2814 lines = view->pos.offset;
2816 if (lines == 0) {
2817 report("Cannot scroll beyond the first line");
2818 return;
2821 lines = -lines;
2822 break;
2824 default:
2825 die("request %d not handled in switch", request);
2828 do_scroll_view(view, lines);
2831 /* Cursor moving */
2832 static void
2833 move_view(struct view *view, enum request request)
2835 int scroll_steps = 0;
2836 int steps;
2838 switch (request) {
2839 case REQ_MOVE_FIRST_LINE:
2840 steps = -view->pos.lineno;
2841 break;
2843 case REQ_MOVE_LAST_LINE:
2844 steps = view->lines - view->pos.lineno - 1;
2845 break;
2847 case REQ_MOVE_PAGE_UP:
2848 steps = view->height > view->pos.lineno
2849 ? -view->pos.lineno : -view->height;
2850 break;
2852 case REQ_MOVE_PAGE_DOWN:
2853 steps = view->pos.lineno + view->height >= view->lines
2854 ? view->lines - view->pos.lineno - 1 : view->height;
2855 break;
2857 case REQ_MOVE_UP:
2858 case REQ_PREVIOUS:
2859 steps = -1;
2860 break;
2862 case REQ_MOVE_DOWN:
2863 case REQ_NEXT:
2864 steps = 1;
2865 break;
2867 default:
2868 die("request %d not handled in switch", request);
2871 if (steps <= 0 && view->pos.lineno == 0) {
2872 report("Cannot move beyond the first line");
2873 return;
2875 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2876 report("Cannot move beyond the last line");
2877 return;
2880 /* Move the current line */
2881 view->pos.lineno += steps;
2882 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2884 /* Check whether the view needs to be scrolled */
2885 if (view->pos.lineno < view->pos.offset ||
2886 view->pos.lineno >= view->pos.offset + view->height) {
2887 scroll_steps = steps;
2888 if (steps < 0 && -steps > view->pos.offset) {
2889 scroll_steps = -view->pos.offset;
2891 } else if (steps > 0) {
2892 if (view->pos.lineno == view->lines - 1 &&
2893 view->lines > view->height) {
2894 scroll_steps = view->lines - view->pos.offset - 1;
2895 if (scroll_steps >= view->height)
2896 scroll_steps -= view->height - 1;
2901 if (!view_is_displayed(view)) {
2902 view->pos.offset += scroll_steps;
2903 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2904 view->ops->select(view, &view->line[view->pos.lineno]);
2905 return;
2908 /* Repaint the old "current" line if we be scrolling */
2909 if (ABS(steps) < view->height)
2910 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2912 if (scroll_steps) {
2913 do_scroll_view(view, scroll_steps);
2914 return;
2917 /* Draw the current line */
2918 draw_view_line(view, view->pos.lineno - view->pos.offset);
2920 wnoutrefresh(view->win);
2921 report_clear();
2926 * Searching
2929 static void search_view(struct view *view, enum request request);
2931 static bool
2932 grep_text(struct view *view, const char *text[])
2934 regmatch_t pmatch;
2935 size_t i;
2937 for (i = 0; text[i]; i++)
2938 if (*text[i] && !regexec(view->regex, text[i], 1, &pmatch, 0))
2939 return TRUE;
2940 return FALSE;
2943 static void
2944 select_view_line(struct view *view, unsigned long lineno)
2946 struct position old = view->pos;
2948 if (goto_view_line(view, view->pos.offset, lineno)) {
2949 if (view_is_displayed(view)) {
2950 if (old.offset != view->pos.offset) {
2951 redraw_view(view);
2952 } else {
2953 draw_view_line(view, old.lineno - view->pos.offset);
2954 draw_view_line(view, view->pos.lineno - view->pos.offset);
2955 wnoutrefresh(view->win);
2957 } else {
2958 view->ops->select(view, &view->line[view->pos.lineno]);
2963 static void
2964 find_next(struct view *view, enum request request)
2966 unsigned long lineno = view->pos.lineno;
2967 int direction;
2969 if (!*view->grep) {
2970 if (!*opt_search)
2971 report("No previous search");
2972 else
2973 search_view(view, request);
2974 return;
2977 switch (request) {
2978 case REQ_SEARCH:
2979 case REQ_FIND_NEXT:
2980 direction = 1;
2981 break;
2983 case REQ_SEARCH_BACK:
2984 case REQ_FIND_PREV:
2985 direction = -1;
2986 break;
2988 default:
2989 return;
2992 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2993 lineno += direction;
2995 /* Note, lineno is unsigned long so will wrap around in which case it
2996 * will become bigger than view->lines. */
2997 for (; lineno < view->lines; lineno += direction) {
2998 if (view->ops->grep(view, &view->line[lineno])) {
2999 select_view_line(view, lineno);
3000 report("Line %ld matches '%s'", lineno + 1, view->grep);
3001 return;
3005 report("No match found for '%s'", view->grep);
3008 static void
3009 search_view(struct view *view, enum request request)
3011 int regex_err;
3012 int regex_flags = opt_ignore_case ? REG_ICASE : 0;
3014 if (view->regex) {
3015 regfree(view->regex);
3016 *view->grep = 0;
3017 } else {
3018 view->regex = calloc(1, sizeof(*view->regex));
3019 if (!view->regex)
3020 return;
3023 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED | regex_flags);
3024 if (regex_err != 0) {
3025 char buf[SIZEOF_STR] = "unknown error";
3027 regerror(regex_err, view->regex, buf, sizeof(buf));
3028 report("Search failed: %s", buf);
3029 return;
3032 string_copy(view->grep, opt_search);
3034 find_next(view, request);
3038 * Incremental updating
3041 static inline bool
3042 check_position(struct position *pos)
3044 return pos->lineno || pos->col || pos->offset;
3047 static inline void
3048 clear_position(struct position *pos)
3050 memset(pos, 0, sizeof(*pos));
3053 static void
3054 reset_view(struct view *view)
3056 int i;
3058 if (view->ops->done)
3059 view->ops->done(view);
3061 for (i = 0; i < view->lines; i++)
3062 free(view->line[i].data);
3063 free(view->line);
3065 view->prev_pos = view->pos;
3066 clear_position(&view->pos);
3068 view->line = NULL;
3069 view->lines = 0;
3070 view->vid[0] = 0;
3071 view->custom_lines = 0;
3072 view->update_secs = 0;
3075 struct format_context {
3076 struct view *view;
3077 char buf[SIZEOF_STR];
3078 size_t bufpos;
3079 bool file_filter;
3082 static bool
3083 format_expand_arg(struct format_context *format, const char *name)
3085 static struct {
3086 const char *name;
3087 size_t namelen;
3088 const char *value;
3089 const char *value_if_empty;
3090 } vars[] = {
3091 #define FORMAT_VAR(name, value, value_if_empty) \
3092 { name, STRING_SIZE(name), value, value_if_empty }
3093 FORMAT_VAR("%(directory)", opt_path, "."),
3094 FORMAT_VAR("%(file)", opt_file, ""),
3095 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
3096 FORMAT_VAR("%(head)", ref_head, ""),
3097 FORMAT_VAR("%(commit)", ref_commit, ""),
3098 FORMAT_VAR("%(blob)", ref_blob, ""),
3099 FORMAT_VAR("%(branch)", ref_branch, ""),
3100 FORMAT_VAR("%(stash)", ref_stash, ""),
3102 int i;
3104 if (!prefixcmp(name, "%(prompt)")) {
3105 const char *value = read_prompt("Command argument: ");
3107 return string_format_from(format->buf, &format->bufpos, "%s", value);
3110 for (i = 0; i < ARRAY_SIZE(vars); i++) {
3111 const char *value;
3113 if (strncmp(name, vars[i].name, vars[i].namelen))
3114 continue;
3116 if (vars[i].value == opt_file && !format->file_filter)
3117 return TRUE;
3119 value = *vars[i].value ? vars[i].value : vars[i].value_if_empty;
3120 if (!*value)
3121 return TRUE;
3123 return string_format_from(format->buf, &format->bufpos, "%s", value);
3126 report("Unknown replacement: `%s`", name);
3127 return NULL;
3130 static bool
3131 format_append_arg(struct format_context *format, const char ***dst_argv, const char *arg)
3133 memset(format->buf, 0, sizeof(format->buf));
3134 format->bufpos = 0;
3136 while (arg) {
3137 char *next = strstr(arg, "%(");
3138 int len = next ? next - arg : strlen(arg);
3140 if (len && !string_format_from(format->buf, &format->bufpos, "%.*s", len, arg))
3141 return FALSE;
3143 if (next && !format_expand_arg(format, next))
3144 return FALSE;
3146 arg = next ? strchr(next, ')') + 1 : NULL;
3149 return argv_append(dst_argv, format->buf);
3152 static bool
3153 format_append_argv(struct format_context *format, const char ***dst_argv, const char *src_argv[])
3155 int argc;
3157 if (!src_argv)
3158 return TRUE;
3160 for (argc = 0; src_argv[argc]; argc++)
3161 if (!format_append_arg(format, dst_argv, src_argv[argc]))
3162 return FALSE;
3164 return src_argv[argc] == NULL;
3167 static bool
3168 format_argv(struct view *view, const char ***dst_argv, const char *src_argv[], bool first, bool file_filter)
3170 struct format_context format = { view, "", 0, file_filter };
3171 int argc;
3173 argv_free(*dst_argv);
3175 for (argc = 0; src_argv[argc]; argc++) {
3176 const char *arg = src_argv[argc];
3178 if (!strcmp(arg, "%(fileargs)")) {
3179 if (file_filter && !argv_append_array(dst_argv, opt_file_argv))
3180 break;
3182 } else if (!strcmp(arg, "%(diffargs)")) {
3183 if (!format_append_argv(&format, dst_argv, opt_diff_argv))
3184 break;
3186 } else if (!strcmp(arg, "%(blameargs)")) {
3187 if (!format_append_argv(&format, dst_argv, opt_blame_argv))
3188 break;
3190 } else if (!strcmp(arg, "%(revargs)") ||
3191 (first && !strcmp(arg, "%(commit)"))) {
3192 if (!argv_append_array(dst_argv, opt_rev_argv))
3193 break;
3195 } else if (!format_append_arg(&format, dst_argv, arg)) {
3196 break;
3200 return src_argv[argc] == NULL;
3203 static bool
3204 restore_view_position(struct view *view)
3206 /* A view without a previous view is the first view */
3207 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
3208 select_view_line(view, opt_lineno - 1);
3209 opt_lineno = 0;
3212 /* Ensure that the view position is in a valid state. */
3213 if (!check_position(&view->prev_pos) ||
3214 (view->pipe && view->lines <= view->prev_pos.lineno))
3215 return goto_view_line(view, view->pos.offset, view->pos.lineno);
3217 /* Changing the view position cancels the restoring. */
3218 /* FIXME: Changing back to the first line is not detected. */
3219 if (check_position(&view->pos)) {
3220 clear_position(&view->prev_pos);
3221 return FALSE;
3224 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
3225 view_is_displayed(view))
3226 werase(view->win);
3228 view->pos.col = view->prev_pos.col;
3229 clear_position(&view->prev_pos);
3231 return TRUE;
3234 static void
3235 end_update(struct view *view, bool force)
3237 if (!view->pipe)
3238 return;
3239 while (!view->ops->read(view, NULL))
3240 if (!force)
3241 return;
3242 if (force)
3243 io_kill(view->pipe);
3244 io_done(view->pipe);
3245 view->pipe = NULL;
3248 static void
3249 setup_update(struct view *view, const char *vid)
3251 reset_view(view);
3252 /* XXX: Do not use string_copy_rev(), it copies until first space. */
3253 string_ncopy(view->vid, vid, strlen(vid));
3254 view->pipe = &view->io;
3255 view->start_time = time(NULL);
3258 static bool
3259 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
3261 bool extra = !!(flags & (OPEN_EXTRA));
3262 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA | OPEN_PAGER_MODE));
3263 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED | OPEN_STDIN);
3264 bool forward_stdin = flags & OPEN_FORWARD_STDIN;
3265 enum io_type io_type = forward_stdin ? IO_RD_STDIN : IO_RD;
3267 if ((!reload && !strcmp(view->vid, view->id)) ||
3268 ((flags & OPEN_REFRESH) && view->unrefreshable))
3269 return TRUE;
3271 if (view->pipe) {
3272 if (extra)
3273 io_done(view->pipe);
3274 else
3275 end_update(view, TRUE);
3278 view->unrefreshable = open_in_pager_mode(flags);
3280 if (!refresh && argv) {
3281 bool file_filter = !view_has_flags(view, VIEW_FILE_FILTER) || opt_file_filter;
3283 view->dir = dir;
3284 if (!format_argv(view, &view->argv, argv, !view->prev, file_filter)) {
3285 report("Failed to format %s arguments", view->name);
3286 return FALSE;
3289 /* Put the current ref_* value to the view title ref
3290 * member. This is needed by the blob view. Most other
3291 * views sets it automatically after loading because the
3292 * first line is a commit line. */
3293 string_copy_rev(view->ref, view->id);
3296 if (view->argv && view->argv[0] &&
3297 !io_run(&view->io, io_type, view->dir, opt_env, view->argv)) {
3298 report("Failed to open %s view", view->name);
3299 return FALSE;
3302 if (open_from_stdin(flags)) {
3303 if (!io_open(&view->io, "%s", ""))
3304 die("Failed to open stdin");
3307 if (!extra)
3308 setup_update(view, view->id);
3310 return TRUE;
3313 static bool
3314 update_view(struct view *view)
3316 char *line;
3317 /* Clear the view and redraw everything since the tree sorting
3318 * might have rearranged things. */
3319 bool redraw = view->lines == 0;
3320 bool can_read = TRUE;
3321 struct encoding *encoding = view->encoding ? view->encoding : default_encoding;
3323 if (!view->pipe)
3324 return TRUE;
3326 if (!io_can_read(view->pipe, FALSE)) {
3327 if (view->lines == 0 && view_is_displayed(view)) {
3328 time_t secs = time(NULL) - view->start_time;
3330 if (secs > 1 && secs > view->update_secs) {
3331 if (view->update_secs == 0)
3332 redraw_view(view);
3333 update_view_title(view);
3334 view->update_secs = secs;
3337 return TRUE;
3340 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
3341 if (encoding) {
3342 line = encoding_convert(encoding, line);
3345 if (!view->ops->read(view, line)) {
3346 report("Allocation failure");
3347 end_update(view, TRUE);
3348 return FALSE;
3353 int digits = count_digits(view->lines);
3355 /* Keep the displayed view in sync with line number scaling. */
3356 if (digits != view->digits) {
3357 view->digits = digits;
3358 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3359 redraw = TRUE;
3363 if (io_error(view->pipe)) {
3364 report("Failed to read: %s", io_strerror(view->pipe));
3365 end_update(view, TRUE);
3367 } else if (io_eof(view->pipe)) {
3368 end_update(view, FALSE);
3371 if (restore_view_position(view))
3372 redraw = TRUE;
3374 if (!view_is_displayed(view))
3375 return TRUE;
3377 if (redraw || view->force_redraw)
3378 redraw_view_from(view, 0);
3379 else
3380 redraw_view_dirty(view);
3381 view->force_redraw = FALSE;
3383 /* Update the title _after_ the redraw so that if the redraw picks up a
3384 * commit reference in view->ref it'll be available here. */
3385 update_view_title(view);
3386 return TRUE;
3389 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3391 static struct line *
3392 add_line_at(struct view *view, unsigned long pos, const void *data, enum line_type type, size_t data_size, bool custom)
3394 struct line *line;
3395 unsigned long lineno = view->lines - view->custom_lines;
3397 if (!realloc_lines(&view->line, view->lines, 1))
3398 return NULL;
3400 if (data_size) {
3401 void *alloc_data = calloc(1, data_size);
3403 if (!alloc_data)
3404 return NULL;
3406 if (data)
3407 memcpy(alloc_data, data, data_size);
3408 data = alloc_data;
3411 if (pos < view->lines) {
3412 view->lines++;
3413 line = view->line + pos;
3414 if (!custom)
3415 lineno = line->lineno;
3417 memmove(line + 1, line, (view->lines - pos) * sizeof(*view->line));
3418 while (pos < view->lines) {
3419 view->line[pos].lineno++;
3420 view->line[pos++].dirty = 1;
3422 } else {
3423 line = &view->line[view->lines++];
3426 memset(line, 0, sizeof(*line));
3427 line->type = type;
3428 line->data = (void *) data;
3429 line->dirty = 1;
3431 if (custom)
3432 view->custom_lines++;
3433 else
3434 line->lineno = lineno;
3436 return line;
3439 static struct line *
3440 add_line(struct view *view, const void *data, enum line_type type, size_t data_size, bool custom)
3442 return add_line_at(view, view->lines, data, type, data_size, custom);
3445 static struct line *
3446 add_line_alloc_(struct view *view, void **ptr, enum line_type type, size_t data_size, bool custom)
3448 struct line *line = add_line(view, NULL, type, data_size, custom);
3450 if (line)
3451 *ptr = line->data;
3452 return line;
3455 #define add_line_alloc(view, data_ptr, type, extra_size, custom) \
3456 add_line_alloc_(view, (void **) data_ptr, type, sizeof(**data_ptr) + extra_size, custom)
3458 static struct line *
3459 add_line_nodata(struct view *view, enum line_type type)
3461 return add_line(view, NULL, type, 0, FALSE);
3464 static struct line *
3465 add_line_text(struct view *view, const char *text, enum line_type type)
3467 return add_line(view, text, type, strlen(text) + 1, FALSE);
3470 static struct line * PRINTF_LIKE(3, 4)
3471 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3473 char buf[SIZEOF_STR];
3474 int retval;
3476 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3477 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3481 * View opening
3484 static void
3485 split_view(struct view *prev, struct view *view)
3487 display[1] = view;
3488 current_view = opt_focus_child ? 1 : 0;
3489 view->parent = prev;
3490 resize_display();
3492 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3493 /* Take the title line into account. */
3494 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3496 /* Scroll the view that was split if the current line is
3497 * outside the new limited view. */
3498 do_scroll_view(prev, lines);
3501 if (view != prev && view_is_displayed(prev)) {
3502 /* "Blur" the previous view. */
3503 update_view_title(prev);
3507 static void
3508 maximize_view(struct view *view, bool redraw)
3510 memset(display, 0, sizeof(display));
3511 current_view = 0;
3512 display[current_view] = view;
3513 resize_display();
3514 if (redraw) {
3515 redraw_display(FALSE);
3516 report_clear();
3520 static void
3521 load_view(struct view *view, struct view *prev, enum open_flags flags)
3523 if (view->pipe)
3524 end_update(view, TRUE);
3525 if (view->ops->private_size) {
3526 if (!view->private)
3527 view->private = calloc(1, view->ops->private_size);
3528 else
3529 memset(view->private, 0, view->ops->private_size);
3532 /* When prev == view it means this is the first loaded view. */
3533 if (prev && view != prev) {
3534 view->prev = prev;
3537 if (!view->ops->open(view, flags))
3538 return;
3540 if (prev) {
3541 bool split = !!(flags & OPEN_SPLIT);
3543 if (split) {
3544 split_view(prev, view);
3545 } else {
3546 maximize_view(view, FALSE);
3550 restore_view_position(view);
3552 if (view->pipe && view->lines == 0) {
3553 /* Clear the old view and let the incremental updating refill
3554 * the screen. */
3555 werase(view->win);
3556 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3557 clear_position(&view->prev_pos);
3558 report_clear();
3559 } else if (view_is_displayed(view)) {
3560 redraw_view(view);
3561 report_clear();
3565 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3566 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3568 static void
3569 open_view(struct view *prev, enum request request, enum open_flags flags)
3571 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3572 struct view *view = VIEW(request);
3573 int nviews = displayed_views();
3575 assert(flags ^ OPEN_REFRESH);
3577 if (view == prev && nviews == 1 && !reload) {
3578 report("Already in %s view", view->name);
3579 return;
3582 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3583 report("The %s view is disabled in pager view", view->name);
3584 return;
3587 load_view(view, prev ? prev : view, flags);
3590 static void
3591 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3593 enum request request = view - views + REQ_OFFSET + 1;
3595 if (view->pipe)
3596 end_update(view, TRUE);
3597 view->dir = dir;
3599 if (!argv_copy(&view->argv, argv)) {
3600 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3601 } else {
3602 open_view(prev, request, flags | OPEN_PREPARED);
3606 static bool
3607 open_external_viewer(const char *argv[], const char *dir, bool confirm, const char *notice)
3609 bool ok;
3611 def_prog_mode(); /* save current tty modes */
3612 endwin(); /* restore original tty modes */
3613 ok = io_run_fg(argv, dir);
3614 if (confirm) {
3615 if (!ok && *notice)
3616 fprintf(stderr, "%s", notice);
3617 fprintf(stderr, "Press Enter to continue");
3618 getc(opt_tty);
3620 reset_prog_mode();
3621 redraw_display(TRUE);
3622 return ok;
3625 static void
3626 open_mergetool(const char *file)
3628 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3630 open_external_viewer(mergetool_argv, opt_cdup, TRUE, "");
3633 #define EDITOR_LINENO_MSG \
3634 "*** Your editor reported an error while opening the file.\n" \
3635 "*** This is probably because it doesn't support the line\n" \
3636 "*** number argument added automatically. The line number\n" \
3637 "*** has been disabled for now. You can permanently disable\n" \
3638 "*** it by adding the following line to ~/.tigrc\n" \
3639 "*** set editor-line-number = no\n"
3641 static void
3642 open_editor(const char *file, unsigned int lineno)
3644 const char *editor_argv[SIZEOF_ARG + 3] = { "vi", file, NULL };
3645 char editor_cmd[SIZEOF_STR];
3646 char lineno_cmd[SIZEOF_STR];
3647 const char *editor;
3648 int argc = 0;
3650 editor = getenv("GIT_EDITOR");
3651 if (!editor && *opt_editor)
3652 editor = opt_editor;
3653 if (!editor)
3654 editor = getenv("VISUAL");
3655 if (!editor)
3656 editor = getenv("EDITOR");
3657 if (!editor)
3658 editor = "vi";
3660 string_ncopy(editor_cmd, editor, strlen(editor));
3661 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3662 report("Failed to read editor command");
3663 return;
3666 if (lineno && opt_editor_lineno && string_format(lineno_cmd, "+%u", lineno))
3667 editor_argv[argc++] = lineno_cmd;
3668 editor_argv[argc] = file;
3669 if (!open_external_viewer(editor_argv, opt_cdup, TRUE, EDITOR_LINENO_MSG))
3670 opt_editor_lineno = FALSE;
3673 static enum request run_prompt_command(struct view *view, char *cmd);
3675 static enum request
3676 open_run_request(struct view *view, enum request request)
3678 struct run_request *req = get_run_request(request);
3679 const char **argv = NULL;
3680 bool confirmed = FALSE;
3682 request = REQ_NONE;
3684 if (!req) {
3685 report("Unknown run request");
3686 return request;
3689 if (format_argv(view, &argv, req->argv, FALSE, TRUE)) {
3690 if (req->internal) {
3691 char cmd[SIZEOF_STR];
3693 if (argv_to_string(argv, cmd, sizeof(cmd), " ")) {
3694 request = run_prompt_command(view, cmd);
3697 else {
3698 confirmed = !req->confirm;
3700 if (req->confirm) {
3701 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
3702 const char *and_exit = req->exit ? " and exit" : "";
3704 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
3705 string_format(prompt, "Run `%s`%s?", cmd, and_exit) &&
3706 prompt_yesno(prompt)) {
3707 confirmed = TRUE;
3711 if (confirmed && argv_remove_quotes(argv)) {
3712 if (req->silent)
3713 io_run_bg(argv);
3714 else
3715 open_external_viewer(argv, NULL, !req->exit, "");
3720 if (argv)
3721 argv_free(argv);
3722 free(argv);
3724 if (request == REQ_NONE) {
3725 if (req->confirm && !confirmed)
3726 request = REQ_NONE;
3728 else if (req->exit)
3729 request = REQ_QUIT;
3731 else if (!view->unrefreshable)
3732 request = REQ_REFRESH;
3734 return request;
3738 * User request switch noodle
3741 static int
3742 view_driver(struct view *view, enum request request)
3744 int i;
3746 if (request == REQ_NONE)
3747 return TRUE;
3749 if (request > REQ_NONE) {
3750 request = open_run_request(view, request);
3752 // exit quickly rather than going through view_request and back
3753 if (request == REQ_QUIT)
3754 return FALSE;
3757 request = view_request(view, request);
3758 if (request == REQ_NONE)
3759 return TRUE;
3761 switch (request) {
3762 case REQ_MOVE_UP:
3763 case REQ_MOVE_DOWN:
3764 case REQ_MOVE_PAGE_UP:
3765 case REQ_MOVE_PAGE_DOWN:
3766 case REQ_MOVE_FIRST_LINE:
3767 case REQ_MOVE_LAST_LINE:
3768 move_view(view, request);
3769 break;
3771 case REQ_SCROLL_FIRST_COL:
3772 case REQ_SCROLL_LEFT:
3773 case REQ_SCROLL_RIGHT:
3774 case REQ_SCROLL_LINE_DOWN:
3775 case REQ_SCROLL_LINE_UP:
3776 case REQ_SCROLL_PAGE_DOWN:
3777 case REQ_SCROLL_PAGE_UP:
3778 scroll_view(view, request);
3779 break;
3781 case REQ_VIEW_MAIN:
3782 case REQ_VIEW_DIFF:
3783 case REQ_VIEW_LOG:
3784 case REQ_VIEW_TREE:
3785 case REQ_VIEW_HELP:
3786 case REQ_VIEW_BRANCH:
3787 case REQ_VIEW_BLAME:
3788 case REQ_VIEW_BLOB:
3789 case REQ_VIEW_STATUS:
3790 case REQ_VIEW_STAGE:
3791 case REQ_VIEW_PAGER:
3792 case REQ_VIEW_STASH:
3793 open_view(view, request, OPEN_DEFAULT);
3794 break;
3796 case REQ_NEXT:
3797 case REQ_PREVIOUS:
3798 if (view->parent) {
3799 int line;
3801 view = view->parent;
3802 line = view->pos.lineno;
3803 view_request(view, request);
3804 move_view(view, request);
3805 if (view_is_displayed(view))
3806 update_view_title(view);
3807 if (line != view->pos.lineno)
3808 view_request(view, REQ_ENTER);
3809 } else {
3810 move_view(view, request);
3812 break;
3814 case REQ_VIEW_NEXT:
3816 int nviews = displayed_views();
3817 int next_view = (current_view + 1) % nviews;
3819 if (next_view == current_view) {
3820 report("Only one view is displayed");
3821 break;
3824 current_view = next_view;
3825 /* Blur out the title of the previous view. */
3826 update_view_title(view);
3827 report_clear();
3828 break;
3830 case REQ_REFRESH:
3831 report("Refreshing is not supported by the %s view", view->name);
3832 break;
3834 case REQ_PARENT:
3835 report("Moving to parent is not supported by the the %s view", view->name);
3836 break;
3838 case REQ_BACK:
3839 report("Going back is not supported for by %s view", view->name);
3840 break;
3842 case REQ_MAXIMIZE:
3843 if (displayed_views() == 2)
3844 maximize_view(view, TRUE);
3845 break;
3847 case REQ_OPTIONS:
3848 case REQ_TOGGLE_LINENO:
3849 case REQ_TOGGLE_DATE:
3850 case REQ_TOGGLE_AUTHOR:
3851 case REQ_TOGGLE_FILENAME:
3852 case REQ_TOGGLE_GRAPHIC:
3853 case REQ_TOGGLE_REV_GRAPH:
3854 case REQ_TOGGLE_REFS:
3855 case REQ_TOGGLE_CHANGES:
3856 case REQ_TOGGLE_IGNORE_SPACE:
3857 case REQ_TOGGLE_ID:
3858 case REQ_TOGGLE_FILES:
3859 case REQ_TOGGLE_TITLE_OVERFLOW:
3861 char action[SIZEOF_STR] = "";
3862 enum view_flag flags = toggle_option(view, request, action);
3864 foreach_displayed_view(view, i) {
3865 if (view_has_flags(view, flags) && !view->unrefreshable)
3866 reload_view(view);
3867 else
3868 redraw_view(view);
3871 if (*action)
3872 report("%s", action);
3874 break;
3876 case REQ_TOGGLE_SORT_FIELD:
3877 case REQ_TOGGLE_SORT_ORDER:
3878 report("Sorting is not yet supported for the %s view", view->name);
3879 break;
3881 case REQ_DIFF_CONTEXT_UP:
3882 case REQ_DIFF_CONTEXT_DOWN:
3883 report("Changing the diff context is not yet supported for the %s view", view->name);
3884 break;
3886 case REQ_SEARCH:
3887 case REQ_SEARCH_BACK:
3888 search_view(view, request);
3889 break;
3891 case REQ_FIND_NEXT:
3892 case REQ_FIND_PREV:
3893 find_next(view, request);
3894 break;
3896 case REQ_STOP_LOADING:
3897 foreach_view(view, i) {
3898 if (view->pipe)
3899 report("Stopped loading the %s view", view->name),
3900 end_update(view, TRUE);
3902 break;
3904 case REQ_SHOW_VERSION:
3905 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3906 return TRUE;
3908 case REQ_SCREEN_REDRAW:
3909 redraw_display(TRUE);
3910 break;
3912 case REQ_EDIT:
3913 report("Nothing to edit");
3914 break;
3916 case REQ_ENTER:
3917 report("Nothing to enter");
3918 break;
3920 case REQ_VIEW_CLOSE:
3921 /* XXX: Mark closed views by letting view->prev point to the
3922 * view itself. Parents to closed view should never be
3923 * followed. */
3924 if (view->prev && view->prev != view) {
3925 maximize_view(view->prev, TRUE);
3926 view->prev = view;
3927 break;
3929 /* Fall-through */
3930 case REQ_QUIT:
3931 return FALSE;
3933 default:
3934 report("Unknown key, press %s for help",
3935 get_view_key(view, REQ_VIEW_HELP));
3936 return TRUE;
3939 return TRUE;
3944 * View backend utilities
3947 enum sort_field {
3948 ORDERBY_NAME,
3949 ORDERBY_DATE,
3950 ORDERBY_AUTHOR,
3953 struct sort_state {
3954 const enum sort_field *fields;
3955 size_t size, current;
3956 bool reverse;
3959 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3960 #define get_sort_field(state) ((state).fields[(state).current])
3961 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3963 static void
3964 sort_view(struct view *view, enum request request, struct sort_state *state,
3965 int (*compare)(const void *, const void *))
3967 switch (request) {
3968 case REQ_TOGGLE_SORT_FIELD:
3969 state->current = (state->current + 1) % state->size;
3970 break;
3972 case REQ_TOGGLE_SORT_ORDER:
3973 state->reverse = !state->reverse;
3974 break;
3975 default:
3976 die("Not a sort request");
3979 qsort(view->line, view->lines, sizeof(*view->line), compare);
3980 redraw_view(view);
3983 static bool
3984 update_diff_context(enum request request)
3986 int diff_context = opt_diff_context;
3988 switch (request) {
3989 case REQ_DIFF_CONTEXT_UP:
3990 opt_diff_context += 1;
3991 update_diff_context_arg(opt_diff_context);
3992 break;
3994 case REQ_DIFF_CONTEXT_DOWN:
3995 if (opt_diff_context == 0) {
3996 report("Diff context cannot be less than zero");
3997 break;
3999 opt_diff_context -= 1;
4000 update_diff_context_arg(opt_diff_context);
4001 break;
4003 default:
4004 die("Not a diff context request");
4007 return diff_context != opt_diff_context;
4010 DEFINE_ALLOCATOR(realloc_paths, const char *, 256)
4012 /* Small cache to reduce memory consumption. It uses binary search to
4013 * lookup or find place to position new entries. No entries are ever
4014 * freed. */
4015 static const char *
4016 get_path(const char *path)
4018 static const char **paths;
4019 static size_t paths_size;
4020 int from = 0, to = paths_size - 1;
4021 char *entry;
4023 while (from <= to) {
4024 size_t pos = (to + from) / 2;
4025 int cmp = strcmp(path, paths[pos]);
4027 if (!cmp)
4028 return paths[pos];
4030 if (cmp < 0)
4031 to = pos - 1;
4032 else
4033 from = pos + 1;
4036 if (!realloc_paths(&paths, paths_size, 1))
4037 return NULL;
4038 entry = strdup(path);
4039 if (!entry)
4040 return NULL;
4042 memmove(paths + from + 1, paths + from, (paths_size - from) * sizeof(*paths));
4043 paths[from] = entry;
4044 paths_size++;
4046 return entry;
4049 DEFINE_ALLOCATOR(realloc_authors, struct ident *, 256)
4051 /* Small author cache to reduce memory consumption. It uses binary
4052 * search to lookup or find place to position new entries. No entries
4053 * are ever freed. */
4054 static struct ident *
4055 get_author(const char *name, const char *email)
4057 static struct ident **authors;
4058 static size_t authors_size;
4059 int from = 0, to = authors_size - 1;
4060 struct ident *ident;
4062 while (from <= to) {
4063 size_t pos = (to + from) / 2;
4064 int cmp = strcmp(name, authors[pos]->name);
4066 if (!cmp)
4067 return authors[pos];
4069 if (cmp < 0)
4070 to = pos - 1;
4071 else
4072 from = pos + 1;
4075 if (!realloc_authors(&authors, authors_size, 1))
4076 return NULL;
4077 ident = calloc(1, sizeof(*ident));
4078 if (!ident)
4079 return NULL;
4080 ident->name = strdup(name);
4081 ident->email = strdup(email);
4082 if (!ident->name || !ident->email) {
4083 free((void *) ident->name);
4084 free(ident);
4085 return NULL;
4088 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
4089 authors[from] = ident;
4090 authors_size++;
4092 return ident;
4095 static void
4096 parse_timesec(struct time *time, const char *sec)
4098 time->sec = (time_t) atol(sec);
4101 static void
4102 parse_timezone(struct time *time, const char *zone)
4104 long tz;
4106 tz = ('0' - zone[1]) * 60 * 60 * 10;
4107 tz += ('0' - zone[2]) * 60 * 60;
4108 tz += ('0' - zone[3]) * 60 * 10;
4109 tz += ('0' - zone[4]) * 60;
4111 if (zone[0] == '-')
4112 tz = -tz;
4114 time->tz = tz;
4115 time->sec -= tz;
4118 /* Parse author lines where the name may be empty:
4119 * author <email@address.tld> 1138474660 +0100
4121 static void
4122 parse_author_line(char *ident, const struct ident **author, struct time *time)
4124 char *nameend = strchr(ident, '<');
4125 char *emailend = strchr(ident, '>');
4126 const char *name, *email = "";
4128 if (nameend && emailend)
4129 *nameend = *emailend = 0;
4130 name = chomp_string(ident);
4131 if (nameend)
4132 email = chomp_string(nameend + 1);
4133 if (!*name)
4134 name = *email ? email : unknown_ident.name;
4135 if (!*email)
4136 email = *name ? name : unknown_ident.email;
4138 *author = get_author(name, email);
4140 /* Parse epoch and timezone */
4141 if (time && emailend && emailend[1] == ' ') {
4142 char *secs = emailend + 2;
4143 char *zone = strchr(secs, ' ');
4145 parse_timesec(time, secs);
4147 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
4148 parse_timezone(time, zone + 1);
4152 static struct line *
4153 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
4155 for (; view_has_line(view, line); line += direction)
4156 if (line->type == type)
4157 return line;
4159 return NULL;
4162 #define find_prev_line_by_type(view, line, type) \
4163 find_line_by_type(view, line, type, -1)
4165 #define find_next_line_by_type(view, line, type) \
4166 find_line_by_type(view, line, type, 1)
4169 * View history
4172 struct view_state {
4173 struct view_state *prev; /* Entry below this in the stack */
4174 struct position position; /* View position to restore */
4175 void *data; /* View specific state */
4178 struct view_history {
4179 size_t state_alloc;
4180 struct view_state *stack;
4181 struct position position;
4184 static bool
4185 view_history_is_empty(struct view_history *history)
4187 return !history->stack;
4190 static struct view_state *
4191 push_view_history_state(struct view_history *history, struct position *position, void *data)
4193 struct view_state *state = history->stack;
4195 if (state && data && history->state_alloc &&
4196 !memcmp(state->data, data, history->state_alloc))
4197 return NULL;
4199 state = calloc(1, sizeof(*state) + history->state_alloc);
4200 if (!state)
4201 return NULL;
4203 state->prev = history->stack;
4204 history->stack = state;
4205 clear_position(&history->position);
4206 state->position = *position;
4207 state->data = &state[1];
4208 if (data && history->state_alloc)
4209 memcpy(state->data, data, history->state_alloc);
4210 return state;
4213 static bool
4214 pop_view_history_state(struct view_history *history, struct position *position, void *data)
4216 struct view_state *state = history->stack;
4218 if (view_history_is_empty(history))
4219 return FALSE;
4221 history->position = state->position;
4222 history->stack = state->prev;
4224 if (data && history->state_alloc)
4225 memcpy(data, state->data, history->state_alloc);
4226 if (position)
4227 *position = state->position;
4229 free(state);
4230 return TRUE;
4233 static void
4234 reset_view_history(struct view_history *history)
4236 while (pop_view_history_state(history, NULL, NULL))
4241 * Blame
4244 struct blame_commit {
4245 char id[SIZEOF_REV]; /* SHA1 ID. */
4246 char title[128]; /* First line of the commit message. */
4247 const struct ident *author; /* Author of the commit. */
4248 struct time time; /* Date from the author ident. */
4249 const char *filename; /* Name of file. */
4250 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
4251 const char *parent_filename; /* Parent/previous name of file. */
4254 struct blame_header {
4255 char id[SIZEOF_REV]; /* SHA1 ID. */
4256 size_t orig_lineno;
4257 size_t lineno;
4258 size_t group;
4261 static bool
4262 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4264 const char *pos = *posref;
4266 *posref = NULL;
4267 pos = strchr(pos + 1, ' ');
4268 if (!pos || !isdigit(pos[1]))
4269 return FALSE;
4270 *number = atoi(pos + 1);
4271 if (*number < min || *number > max)
4272 return FALSE;
4274 *posref = pos;
4275 return TRUE;
4278 static bool
4279 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
4281 const char *pos = text + SIZEOF_REV - 2;
4283 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4284 return FALSE;
4286 string_ncopy(header->id, text, SIZEOF_REV);
4288 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
4289 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
4290 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
4291 return FALSE;
4293 return TRUE;
4296 static bool
4297 match_blame_header(const char *name, char **line)
4299 size_t namelen = strlen(name);
4300 bool matched = !strncmp(name, *line, namelen);
4302 if (matched)
4303 *line += namelen;
4305 return matched;
4308 static bool
4309 parse_blame_info(struct blame_commit *commit, char *line)
4311 if (match_blame_header("author ", &line)) {
4312 parse_author_line(line, &commit->author, NULL);
4314 } else if (match_blame_header("author-time ", &line)) {
4315 parse_timesec(&commit->time, line);
4317 } else if (match_blame_header("author-tz ", &line)) {
4318 parse_timezone(&commit->time, line);
4320 } else if (match_blame_header("summary ", &line)) {
4321 string_ncopy(commit->title, line, strlen(line));
4323 } else if (match_blame_header("previous ", &line)) {
4324 if (strlen(line) <= SIZEOF_REV)
4325 return FALSE;
4326 string_copy_rev(commit->parent_id, line);
4327 line += SIZEOF_REV;
4328 commit->parent_filename = get_path(line);
4329 if (!commit->parent_filename)
4330 return TRUE;
4332 } else if (match_blame_header("filename ", &line)) {
4333 commit->filename = get_path(line);
4334 return TRUE;
4337 return FALSE;
4341 * Pager backend
4344 static bool
4345 pager_draw(struct view *view, struct line *line, unsigned int lineno)
4347 if (draw_lineno(view, lineno))
4348 return TRUE;
4350 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4351 return TRUE;
4353 draw_text(view, line->type, line->data);
4354 return TRUE;
4357 static bool
4358 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
4360 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
4361 char ref[SIZEOF_STR];
4363 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
4364 return TRUE;
4366 /* This is the only fatal call, since it can "corrupt" the buffer. */
4367 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
4368 return FALSE;
4370 return TRUE;
4373 static void
4374 add_pager_refs(struct view *view, const char *commit_id)
4376 char buf[SIZEOF_STR];
4377 struct ref_list *list;
4378 size_t bufpos = 0, i;
4379 const char *sep = "Refs: ";
4380 bool is_tag = FALSE;
4382 list = get_ref_list(commit_id);
4383 if (!list) {
4384 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
4385 goto try_add_describe_ref;
4386 return;
4389 for (i = 0; i < list->size; i++) {
4390 struct ref *ref = list->refs[i];
4391 const char *fmt = ref->tag ? "%s[%s]" :
4392 ref->remote ? "%s<%s>" : "%s%s";
4394 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
4395 return;
4396 sep = ", ";
4397 if (ref->tag)
4398 is_tag = TRUE;
4401 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
4402 try_add_describe_ref:
4403 /* Add <tag>-g<commit_id> "fake" reference. */
4404 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
4405 return;
4408 if (bufpos == 0)
4409 return;
4411 add_line_text(view, buf, LINE_PP_REFS);
4414 static struct line *
4415 pager_wrap_line(struct view *view, const char *data, enum line_type type)
4417 size_t first_line = 0;
4418 bool has_first_line = FALSE;
4419 size_t datalen = strlen(data);
4420 size_t lineno = 0;
4422 while (datalen > 0 || !has_first_line) {
4423 bool wrapped = !!first_line;
4424 size_t linelen = string_expanded_length(data, datalen, opt_tab_size, view->width - !!wrapped);
4425 struct line *line;
4426 char *text;
4428 line = add_line(view, NULL, type, linelen + 1, wrapped);
4429 if (!line)
4430 break;
4431 if (!has_first_line) {
4432 first_line = view->lines - 1;
4433 has_first_line = TRUE;
4436 if (!wrapped)
4437 lineno = line->lineno;
4439 line->wrapped = wrapped;
4440 line->lineno = lineno;
4441 text = line->data;
4442 if (linelen)
4443 strncpy(text, data, linelen);
4444 text[linelen] = 0;
4446 datalen -= linelen;
4447 data += linelen;
4450 return has_first_line ? &view->line[first_line] : NULL;
4453 static bool
4454 pager_common_read(struct view *view, const char *data, enum line_type type)
4456 struct line *line;
4458 if (!data)
4459 return TRUE;
4461 if (opt_wrap_lines) {
4462 line = pager_wrap_line(view, data, type);
4463 } else {
4464 line = add_line_text(view, data, type);
4467 if (!line)
4468 return FALSE;
4470 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
4471 add_pager_refs(view, data + STRING_SIZE("commit "));
4473 return TRUE;
4476 static bool
4477 pager_read(struct view *view, char *data)
4479 if (!data)
4480 return TRUE;
4482 return pager_common_read(view, data, get_line_type(data));
4485 static enum request
4486 pager_request(struct view *view, enum request request, struct line *line)
4488 int split = 0;
4490 if (request != REQ_ENTER)
4491 return request;
4493 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
4494 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4495 split = 1;
4498 /* Always scroll the view even if it was split. That way
4499 * you can use Enter to scroll through the log view and
4500 * split open each commit diff. */
4501 scroll_view(view, REQ_SCROLL_LINE_DOWN);
4503 /* FIXME: A minor workaround. Scrolling the view will call report_clear()
4504 * but if we are scrolling a non-current view this won't properly
4505 * update the view title. */
4506 if (split)
4507 update_view_title(view);
4509 return REQ_NONE;
4512 static bool
4513 pager_grep(struct view *view, struct line *line)
4515 const char *text[] = { line->data, NULL };
4517 return grep_text(view, text);
4520 static void
4521 pager_select(struct view *view, struct line *line)
4523 if (line->type == LINE_COMMIT) {
4524 string_copy_rev_from_commit_line(ref_commit, line->data);
4525 if (!view_has_flags(view, VIEW_NO_REF))
4526 string_copy_rev(view->ref, ref_commit);
4530 struct log_state {
4531 /* Used for tracking when we need to recalculate the previous
4532 * commit, for example when the user scrolls up or uses the page
4533 * up/down in the log view. */
4534 int last_lineno;
4535 enum line_type last_type;
4538 static void
4539 log_select(struct view *view, struct line *line)
4541 struct log_state *state = view->private;
4542 int last_lineno = state->last_lineno;
4544 if (!last_lineno || abs(last_lineno - line->lineno) > 1
4545 || (state->last_type == LINE_COMMIT && last_lineno > line->lineno)) {
4546 const struct line *commit_line = find_prev_line_by_type(view, line, LINE_COMMIT);
4548 if (commit_line)
4549 string_copy_rev_from_commit_line(view->ref, commit_line->data);
4552 if (line->type == LINE_COMMIT && !view_has_flags(view, VIEW_NO_REF)) {
4553 string_copy_rev_from_commit_line(view->ref, (char *)line->data);
4555 string_copy_rev(ref_commit, view->ref);
4556 state->last_lineno = line->lineno;
4557 state->last_type = line->type;
4560 static bool
4561 pager_open(struct view *view, enum open_flags flags)
4563 if (!open_from_stdin(flags) && !view->lines) {
4564 report("No pager content, press %s to run command from prompt",
4565 get_view_key(view, REQ_PROMPT));
4566 return FALSE;
4569 return begin_update(view, NULL, NULL, flags);
4572 static struct view_ops pager_ops = {
4573 "line",
4574 { "pager" },
4575 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
4577 pager_open,
4578 pager_read,
4579 pager_draw,
4580 pager_request,
4581 pager_grep,
4582 pager_select,
4585 static bool
4586 log_open(struct view *view, enum open_flags flags)
4588 static const char *log_argv[] = {
4589 "git", "log", encoding_arg, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
4592 return begin_update(view, NULL, log_argv, flags);
4595 static enum request
4596 log_request(struct view *view, enum request request, struct line *line)
4598 switch (request) {
4599 case REQ_REFRESH:
4600 load_refs(TRUE);
4601 refresh_view(view);
4602 return REQ_NONE;
4604 case REQ_ENTER:
4605 if (!display[1] || strcmp(display[1]->vid, view->ref))
4606 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4607 return REQ_NONE;
4609 default:
4610 return request;
4614 static struct view_ops log_ops = {
4615 "line",
4616 { "log" },
4617 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF | VIEW_SEND_CHILD_ENTER | VIEW_LOG_LIKE,
4618 sizeof(struct log_state),
4619 log_open,
4620 pager_read,
4621 pager_draw,
4622 log_request,
4623 pager_grep,
4624 log_select,
4627 struct diff_state {
4628 bool after_commit_title;
4629 bool after_diff;
4630 bool reading_diff_stat;
4631 bool combined_diff;
4634 #define DIFF_LINE_COMMIT_TITLE 1
4636 static bool
4637 diff_open(struct view *view, enum open_flags flags)
4639 static const char *diff_argv[] = {
4640 "git", "show", encoding_arg, "--pretty=fuller", "--root",
4641 "--patch-with-stat",
4642 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
4643 "%(diffargs)", "--no-color", "%(commit)", "--", "%(fileargs)", NULL
4646 return begin_update(view, NULL, diff_argv, flags);
4649 static bool
4650 diff_common_read(struct view *view, const char *data, struct diff_state *state)
4652 enum line_type type = get_line_type(data);
4654 if (!view->lines && type != LINE_COMMIT)
4655 state->reading_diff_stat = TRUE;
4657 if (state->combined_diff && !state->after_diff && data[0] == ' ' && data[1] != ' ')
4658 state->reading_diff_stat = TRUE;
4660 if (state->reading_diff_stat) {
4661 size_t len = strlen(data);
4662 char *pipe = strchr(data, '|');
4663 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
4664 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
4665 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
4667 if (pipe && (has_histogram || has_bin_diff || has_rename)) {
4668 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
4669 } else {
4670 state->reading_diff_stat = FALSE;
4673 } else if (!strcmp(data, "---")) {
4674 state->reading_diff_stat = TRUE;
4677 if (!state->after_commit_title && !prefixcmp(data, " ")) {
4678 struct line *line = add_line_text(view, data, LINE_DEFAULT);
4680 if (line)
4681 line->user_flags |= DIFF_LINE_COMMIT_TITLE;
4682 state->after_commit_title = TRUE;
4683 return line != NULL;
4686 if (type == LINE_DIFF_HEADER) {
4687 const int len = line_info[LINE_DIFF_HEADER].linelen;
4689 state->after_diff = TRUE;
4690 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4691 !strncmp(data + len, "cc ", strlen("cc ")))
4692 state->combined_diff = TRUE;
4694 } else if (type == LINE_PP_MERGE) {
4695 state->combined_diff = TRUE;
4698 /* ADD2 and DEL2 are only valid in combined diff hunks */
4699 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4700 type = LINE_DEFAULT;
4702 return pager_common_read(view, data, type);
4705 static bool
4706 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
4708 struct line *marker = find_next_line_by_type(view, line, type);
4710 return marker &&
4711 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
4714 static enum request
4715 diff_common_enter(struct view *view, enum request request, struct line *line)
4717 if (line->type == LINE_DIFF_STAT) {
4718 int file_number = 0;
4720 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4721 file_number++;
4722 line--;
4725 for (line = view->line; view_has_line(view, line); line++) {
4726 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4727 if (!line)
4728 break;
4730 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4731 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4732 if (file_number == 1) {
4733 break;
4735 file_number--;
4739 if (!line) {
4740 report("Failed to find file diff");
4741 return REQ_NONE;
4744 select_view_line(view, line - view->line);
4745 report_clear();
4746 return REQ_NONE;
4748 } else {
4749 return pager_request(view, request, line);
4753 static bool
4754 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4756 char *sep = strchr(*text, c);
4758 if (sep != NULL) {
4759 *sep = 0;
4760 draw_text(view, *type, *text);
4761 *sep = c;
4762 *text = sep;
4763 *type = next_type;
4766 return sep != NULL;
4769 static bool
4770 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4772 char *text = line->data;
4773 enum line_type type = line->type;
4775 if (draw_lineno(view, lineno))
4776 return TRUE;
4778 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4779 return TRUE;
4781 if (type == LINE_DIFF_STAT) {
4782 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4783 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4784 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4785 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4786 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4787 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4788 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4790 } else {
4791 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4792 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4796 if (line->user_flags & DIFF_LINE_COMMIT_TITLE)
4797 draw_commit_title(view, text, 4);
4798 else
4799 draw_text(view, type, text);
4800 return TRUE;
4803 static bool
4804 diff_read(struct view *view, char *data)
4806 struct diff_state *state = view->private;
4808 if (!data) {
4809 /* Fall back to retry if no diff will be shown. */
4810 if (view->lines == 0 && opt_file_argv) {
4811 int pos = argv_size(view->argv)
4812 - argv_size(opt_file_argv) - 1;
4814 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4815 for (; view->argv[pos]; pos++) {
4816 free((void *) view->argv[pos]);
4817 view->argv[pos] = NULL;
4820 if (view->pipe)
4821 io_done(view->pipe);
4822 if (io_run(&view->io, IO_RD, view->dir, opt_env, view->argv))
4823 return FALSE;
4826 return TRUE;
4829 return diff_common_read(view, data, state);
4832 static bool
4833 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4834 struct blame_header *header, struct blame_commit *commit)
4836 char line_arg[SIZEOF_STR];
4837 const char *blame_argv[] = {
4838 "git", "blame", encoding_arg, "-p", line_arg, ref, "--", file, NULL
4840 struct io io;
4841 bool ok = FALSE;
4842 char *buf;
4844 if (!string_format(line_arg, "-L%ld,+1", lineno))
4845 return FALSE;
4847 if (!io_run(&io, IO_RD, opt_cdup, opt_env, blame_argv))
4848 return FALSE;
4850 while ((buf = io_get(&io, '\n', TRUE))) {
4851 if (header) {
4852 if (!parse_blame_header(header, buf, 9999999))
4853 break;
4854 header = NULL;
4856 } else if (parse_blame_info(commit, buf)) {
4857 ok = commit->filename != NULL;
4858 break;
4862 if (io_error(&io))
4863 ok = FALSE;
4865 io_done(&io);
4866 return ok;
4869 struct chunk_header_position {
4870 unsigned long position;
4871 unsigned long lines;
4874 struct chunk_header {
4875 struct chunk_header_position old;
4876 struct chunk_header_position new;
4879 static bool
4880 parse_ulong(const char **pos_ptr, unsigned long *value, const char *skip)
4882 const char *start = *pos_ptr;
4883 char *end;
4885 if (!isdigit(*start))
4886 return 0;
4888 *value = strtoul(start, &end, 10);
4889 if (end == start)
4890 return FALSE;
4892 start = end;
4893 while (skip && *start && strchr(skip, *start))
4894 start++;
4895 *pos_ptr = start;
4896 return TRUE;
4899 static bool
4900 parse_chunk_header(struct chunk_header *header, const char *line)
4902 if (prefixcmp(line, "@@ -"))
4903 return FALSE;
4905 line += STRING_SIZE("@@ -");
4907 return parse_ulong(&line, &header->old.position, ",") &&
4908 parse_ulong(&line, &header->old.lines, " +") &&
4909 parse_ulong(&line, &header->new.position, ",") &&
4910 parse_ulong(&line, &header->new.lines, NULL);
4913 static unsigned int
4914 diff_get_lineno(struct view *view, struct line *line)
4916 const struct line *header, *chunk;
4917 unsigned int lineno;
4918 struct chunk_header chunk_header;
4920 /* Verify that we are after a diff header and one of its chunks */
4921 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4922 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4923 if (!header || !chunk || chunk < header)
4924 return 0;
4927 * In a chunk header, the number after the '+' sign is the number of its
4928 * following line, in the new version of the file. We increment this
4929 * number for each non-deletion line, until the given line position.
4931 if (!parse_chunk_header(&chunk_header, chunk->data))
4932 return 0;
4934 lineno = chunk_header.old.position;
4935 chunk++;
4936 while (chunk++ < line)
4937 if (chunk->type != LINE_DIFF_DEL)
4938 lineno++;
4940 return lineno;
4943 static bool
4944 parse_chunk_lineno(unsigned long *lineno, const char *chunk, int marker)
4946 struct chunk_header chunk_header;
4948 if (!parse_chunk_header(&chunk_header, chunk))
4949 return 0;
4951 return marker == '-' ? chunk_header.old.position : chunk_header.new.position;
4954 static enum request
4955 diff_trace_origin(struct view *view, struct line *line)
4957 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4958 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4959 const char *chunk_data;
4960 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4961 unsigned long lineno = 0;
4962 const char *file = NULL;
4963 char ref[SIZEOF_REF];
4964 struct blame_header header;
4965 struct blame_commit commit;
4967 if (!diff || !chunk || chunk == line) {
4968 report("The line to trace must be inside a diff chunk");
4969 return REQ_NONE;
4972 for (; diff < line && !file; diff++) {
4973 const char *data = diff->data;
4975 if (!prefixcmp(data, "--- a/")) {
4976 file = data + STRING_SIZE("--- a/");
4977 break;
4981 if (diff == line || !file) {
4982 report("Failed to read the file name");
4983 return REQ_NONE;
4986 chunk_data = chunk->data;
4988 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4989 report("Failed to read the line number");
4990 return REQ_NONE;
4993 if (lineno == 0) {
4994 report("This is the origin of the line");
4995 return REQ_NONE;
4998 for (chunk += 1; chunk < line; chunk++) {
4999 if (chunk->type == LINE_DIFF_ADD) {
5000 lineno += chunk_marker == '+';
5001 } else if (chunk->type == LINE_DIFF_DEL) {
5002 lineno += chunk_marker == '-';
5003 } else {
5004 lineno++;
5008 if (chunk_marker == '+')
5009 string_copy(ref, view->vid);
5010 else
5011 string_format(ref, "%s^", view->vid);
5013 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
5014 report("Failed to read blame data");
5015 return REQ_NONE;
5018 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
5019 string_copy(opt_ref, header.id);
5020 opt_goto_line = header.orig_lineno - 1;
5022 return REQ_VIEW_BLAME;
5025 static const char *
5026 diff_get_pathname(struct view *view, struct line *line)
5028 const struct line *header;
5029 const char *dst = NULL;
5030 const char *prefixes[] = { " b/", "cc ", "combined " };
5031 int i;
5033 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
5034 if (!header)
5035 return NULL;
5037 for (i = 0; i < ARRAY_SIZE(prefixes) && !dst; i++)
5038 dst = strstr(header->data, prefixes[i]);
5040 return dst ? dst + strlen(prefixes[--i]) : NULL;
5043 static enum request
5044 diff_common_edit(struct view *view, enum request request, struct line *line)
5046 const char *file = diff_get_pathname(view, line);
5047 char path[SIZEOF_STR];
5048 bool has_path = file && string_format(path, "%s%s", opt_cdup, file);
5050 if (has_path && access(path, R_OK)) {
5051 report("Failed to open file: %s", file);
5052 return REQ_NONE;
5055 open_editor(file, diff_get_lineno(view, line));
5056 return REQ_NONE;
5059 static enum request
5060 diff_request(struct view *view, enum request request, struct line *line)
5062 switch (request) {
5063 case REQ_VIEW_BLAME:
5064 return diff_trace_origin(view, line);
5066 case REQ_DIFF_CONTEXT_UP:
5067 case REQ_DIFF_CONTEXT_DOWN:
5068 if (!update_diff_context(request))
5069 return REQ_NONE;
5070 reload_view(view);
5071 return REQ_NONE;
5074 case REQ_EDIT:
5075 return diff_common_edit(view, request, line);
5077 case REQ_ENTER:
5078 return diff_common_enter(view, request, line);
5080 case REQ_REFRESH:
5081 reload_view(view);
5082 return REQ_NONE;
5084 default:
5085 return pager_request(view, request, line);
5089 static void
5090 diff_select(struct view *view, struct line *line)
5092 if (line->type == LINE_DIFF_STAT) {
5093 string_format(view->ref, "Press '%s' to jump to file diff",
5094 get_view_key(view, REQ_ENTER));
5095 } else {
5096 const char *file = diff_get_pathname(view, line);
5098 if (file) {
5099 string_format(view->ref, "Changes to '%s'", file);
5100 string_format(opt_file, "%s", file);
5101 ref_blob[0] = 0;
5102 } else {
5103 string_ncopy(view->ref, view->id, strlen(view->id));
5104 pager_select(view, line);
5109 static struct view_ops diff_ops = {
5110 "line",
5111 { "diff" },
5112 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS | VIEW_FILE_FILTER,
5113 sizeof(struct diff_state),
5114 diff_open,
5115 diff_read,
5116 diff_common_draw,
5117 diff_request,
5118 pager_grep,
5119 diff_select,
5123 * Help backend
5126 static bool
5127 help_draw(struct view *view, struct line *line, unsigned int lineno)
5129 if (line->type == LINE_HELP_KEYMAP) {
5130 struct keymap *keymap = line->data;
5132 draw_formatted(view, line->type, "[%c] %s bindings",
5133 keymap->hidden ? '+' : '-', keymap->name);
5134 return TRUE;
5135 } else {
5136 return pager_draw(view, line, lineno);
5140 static bool
5141 help_open_keymap_title(struct view *view, struct keymap *keymap)
5143 add_line(view, keymap, LINE_HELP_KEYMAP, 0, FALSE);
5144 return keymap->hidden;
5147 static void
5148 help_open_keymap(struct view *view, struct keymap *keymap)
5150 const char *group = NULL;
5151 char buf[SIZEOF_STR];
5152 bool add_title = TRUE;
5153 int i;
5155 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
5156 const char *key = NULL;
5158 if (req_info[i].request == REQ_NONE)
5159 continue;
5161 if (!req_info[i].request) {
5162 group = req_info[i].help;
5163 continue;
5166 key = get_keys(keymap, req_info[i].request, TRUE);
5167 if (!key || !*key)
5168 continue;
5170 if (add_title && help_open_keymap_title(view, keymap))
5171 return;
5172 add_title = FALSE;
5174 if (group) {
5175 add_line_text(view, group, LINE_HELP_GROUP);
5176 group = NULL;
5179 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
5180 enum_name(req_info[i]), req_info[i].help);
5183 group = "External commands:";
5185 for (i = 0; i < run_requests; i++) {
5186 struct run_request *req = get_run_request(REQ_NONE + i + 1);
5187 const char *key;
5189 if (!req || req->keymap != keymap)
5190 continue;
5192 key = get_key_name(req->key);
5193 if (!*key)
5194 key = "(no key defined)";
5196 if (add_title && help_open_keymap_title(view, keymap))
5197 return;
5198 add_title = FALSE;
5200 if (group) {
5201 add_line_text(view, group, LINE_HELP_GROUP);
5202 group = NULL;
5205 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
5206 return;
5208 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
5212 static bool
5213 help_open(struct view *view, enum open_flags flags)
5215 struct keymap *keymap;
5217 reset_view(view);
5218 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
5219 add_line_text(view, "", LINE_DEFAULT);
5221 for (keymap = keymaps; keymap; keymap = keymap->next)
5222 help_open_keymap(view, keymap);
5224 return TRUE;
5227 static enum request
5228 help_request(struct view *view, enum request request, struct line *line)
5230 switch (request) {
5231 case REQ_ENTER:
5232 if (line->type == LINE_HELP_KEYMAP) {
5233 struct keymap *keymap = line->data;
5235 keymap->hidden = !keymap->hidden;
5236 refresh_view(view);
5239 return REQ_NONE;
5240 default:
5241 return pager_request(view, request, line);
5245 static void
5246 help_done(struct view *view)
5248 int i;
5250 for (i = 0; i < view->lines; i++)
5251 if (view->line[i].type == LINE_HELP_KEYMAP)
5252 view->line[i].data = NULL;
5255 static struct view_ops help_ops = {
5256 "line",
5257 { "help" },
5258 VIEW_NO_GIT_DIR,
5260 help_open,
5261 NULL,
5262 help_draw,
5263 help_request,
5264 pager_grep,
5265 pager_select,
5266 help_done,
5271 * Tree backend
5274 /* The top of the path stack. */
5275 static struct view_history tree_view_history = { sizeof(char *) };
5277 static void
5278 pop_tree_stack_entry(struct position *position)
5280 char *path_position = NULL;
5282 pop_view_history_state(&tree_view_history, position, &path_position);
5283 path_position[0] = 0;
5286 static void
5287 push_tree_stack_entry(const char *name, struct position *position)
5289 size_t pathlen = strlen(opt_path);
5290 char *path_position = opt_path + pathlen;
5291 struct view_state *state = push_view_history_state(&tree_view_history, position, &path_position);
5293 if (!state)
5294 return;
5296 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
5297 pop_tree_stack_entry(NULL);
5298 return;
5301 clear_position(position);
5304 /* Parse output from git-ls-tree(1):
5306 * 100644 blob 95925677ca47beb0b8cce7c0e0011bcc3f61470f 213045 tig.c
5309 #define SIZEOF_TREE_ATTR \
5310 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
5312 #define SIZEOF_TREE_MODE \
5313 STRING_SIZE("100644 ")
5315 #define TREE_ID_OFFSET \
5316 STRING_SIZE("100644 blob ")
5318 #define tree_path_is_parent(path) (!strcmp("..", (path)))
5320 struct tree_entry {
5321 char id[SIZEOF_REV];
5322 char commit[SIZEOF_REV];
5323 mode_t mode;
5324 struct time time; /* Date from the author ident. */
5325 const struct ident *author; /* Author of the commit. */
5326 unsigned long size;
5327 char name[1];
5330 struct tree_state {
5331 char commit[SIZEOF_REV];
5332 const struct ident *author;
5333 struct time author_time;
5334 int size_width;
5335 bool read_date;
5338 static const char *
5339 tree_path(const struct line *line)
5341 return ((struct tree_entry *) line->data)->name;
5344 static int
5345 tree_compare_entry(const struct line *line1, const struct line *line2)
5347 if (line1->type != line2->type)
5348 return line1->type == LINE_TREE_DIR ? -1 : 1;
5349 return strcmp(tree_path(line1), tree_path(line2));
5352 static const enum sort_field tree_sort_fields[] = {
5353 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5355 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
5357 static int
5358 tree_compare(const void *l1, const void *l2)
5360 const struct line *line1 = (const struct line *) l1;
5361 const struct line *line2 = (const struct line *) l2;
5362 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
5363 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
5365 if (line1->type == LINE_TREE_HEAD)
5366 return -1;
5367 if (line2->type == LINE_TREE_HEAD)
5368 return 1;
5370 switch (get_sort_field(tree_sort_state)) {
5371 case ORDERBY_DATE:
5372 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
5374 case ORDERBY_AUTHOR:
5375 return sort_order(tree_sort_state, ident_compare(entry1->author, entry2->author));
5377 case ORDERBY_NAME:
5378 default:
5379 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
5384 static struct line *
5385 tree_entry(struct view *view, enum line_type type, const char *path,
5386 const char *mode, const char *id, unsigned long size)
5388 bool custom = type == LINE_TREE_HEAD || tree_path_is_parent(path);
5389 struct tree_entry *entry;
5390 struct line *line = add_line_alloc(view, &entry, type, strlen(path), custom);
5392 if (!line)
5393 return NULL;
5395 strncpy(entry->name, path, strlen(path));
5396 if (mode)
5397 entry->mode = strtoul(mode, NULL, 8);
5398 if (id)
5399 string_copy_rev(entry->id, id);
5400 entry->size = size;
5402 return line;
5405 static bool
5406 tree_read_date(struct view *view, char *text, struct tree_state *state)
5408 if (!text && state->read_date) {
5409 state->read_date = FALSE;
5410 return TRUE;
5412 } else if (!text) {
5413 /* Find next entry to process */
5414 const char *log_file[] = {
5415 "git", "log", encoding_arg, "--no-color", "--pretty=raw",
5416 "--cc", "--raw", view->id, "--", "%(directory)", NULL
5419 if (!view->lines) {
5420 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0);
5421 tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0);
5422 report("Tree is empty");
5423 return TRUE;
5426 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
5427 report("Failed to load tree data");
5428 return TRUE;
5431 state->read_date = TRUE;
5432 return FALSE;
5434 } else if (*text == 'c' && get_line_type(text) == LINE_COMMIT) {
5435 string_copy_rev_from_commit_line(state->commit, text);
5437 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
5438 parse_author_line(text + STRING_SIZE("author "),
5439 &state->author, &state->author_time);
5441 } else if (*text == ':') {
5442 char *pos;
5443 size_t annotated = 1;
5444 size_t i;
5446 pos = strchr(text, '\t');
5447 if (!pos)
5448 return TRUE;
5449 text = pos + 1;
5450 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
5451 text += strlen(opt_path);
5452 pos = strchr(text, '/');
5453 if (pos)
5454 *pos = 0;
5456 for (i = 1; i < view->lines; i++) {
5457 struct line *line = &view->line[i];
5458 struct tree_entry *entry = line->data;
5460 annotated += !!entry->author;
5461 if (entry->author || strcmp(entry->name, text))
5462 continue;
5464 string_copy_rev(entry->commit, state->commit);
5465 entry->author = state->author;
5466 entry->time = state->author_time;
5467 line->dirty = 1;
5468 break;
5471 if (annotated == view->lines)
5472 io_kill(view->pipe);
5474 return TRUE;
5477 static inline size_t
5478 parse_size(const char *text, int *max_digits)
5480 size_t size = 0;
5481 int digits = 0;
5483 while (*text == ' ')
5484 text++;
5486 while (isdigit(*text)) {
5487 size = (size * 10) + (*text++ - '0');
5488 digits++;
5491 if (digits > *max_digits)
5492 *max_digits = digits;
5494 return size;
5497 static bool
5498 tree_read(struct view *view, char *text)
5500 struct tree_state *state = view->private;
5501 struct tree_entry *data;
5502 struct line *entry, *line;
5503 enum line_type type;
5504 size_t textlen = text ? strlen(text) : 0;
5505 const char *attr_offset = text + SIZEOF_TREE_ATTR;
5506 char *path;
5507 size_t size;
5509 if (state->read_date || !text)
5510 return tree_read_date(view, text, state);
5512 if (textlen <= SIZEOF_TREE_ATTR)
5513 return FALSE;
5514 if (view->lines == 0 &&
5515 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0))
5516 return FALSE;
5518 size = parse_size(attr_offset, &state->size_width);
5519 path = strchr(attr_offset, '\t');
5520 if (!path)
5521 return FALSE;
5522 path++;
5524 /* Strip the path part ... */
5525 if (*opt_path) {
5526 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
5527 size_t striplen = strlen(opt_path);
5529 if (pathlen > striplen)
5530 memmove(path, path + striplen,
5531 pathlen - striplen + 1);
5533 /* Insert "link" to parent directory. */
5534 if (view->lines == 1 &&
5535 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0))
5536 return FALSE;
5539 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
5540 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET, size);
5541 if (!entry)
5542 return FALSE;
5543 data = entry->data;
5545 /* Skip "Directory ..." and ".." line. */
5546 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
5547 if (tree_compare_entry(line, entry) <= 0)
5548 continue;
5550 memmove(line + 1, line, (entry - line) * sizeof(*entry));
5552 line->data = data;
5553 line->type = type;
5554 for (; line <= entry; line++)
5555 line->dirty = line->cleareol = 1;
5556 return TRUE;
5559 /* Move the current line to the first tree entry. */
5560 if (!check_position(&view->prev_pos) && !check_position(&view->pos))
5561 goto_view_line(view, 0, 1);
5563 return TRUE;
5566 static bool
5567 tree_draw(struct view *view, struct line *line, unsigned int lineno)
5569 struct tree_state *state = view->private;
5570 struct tree_entry *entry = line->data;
5572 if (line->type == LINE_TREE_HEAD) {
5573 if (draw_text(view, line->type, "Directory path /"))
5574 return TRUE;
5575 } else {
5576 if (draw_mode(view, entry->mode))
5577 return TRUE;
5579 if (draw_author(view, entry->author))
5580 return TRUE;
5582 if (draw_file_size(view, entry->size, state->size_width,
5583 line->type != LINE_TREE_FILE))
5584 return TRUE;
5586 if (draw_date(view, &entry->time))
5587 return TRUE;
5589 if (draw_id(view, entry->commit))
5590 return TRUE;
5593 draw_text(view, line->type, entry->name);
5594 return TRUE;
5597 static void
5598 open_blob_editor(const char *id, const char *name, unsigned int lineno)
5600 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
5601 char file[SIZEOF_STR];
5602 int fd;
5604 if (!name)
5605 name = "unknown";
5607 if (!string_format(file, "%s/tigblob.XXXXXX.%s", get_temp_dir(), name)) {
5608 report("Temporary file name is too long");
5609 return;
5612 fd = mkstemps(file, strlen(name) + 1);
5614 if (fd == -1)
5615 report("Failed to create temporary file");
5616 else if (!io_run_append(blob_argv, fd))
5617 report("Failed to save blob data to file");
5618 else
5619 open_editor(file, lineno);
5620 if (fd != -1)
5621 unlink(file);
5624 static enum request
5625 tree_request(struct view *view, enum request request, struct line *line)
5627 enum open_flags flags;
5628 struct tree_entry *entry = line->data;
5630 switch (request) {
5631 case REQ_VIEW_BLAME:
5632 if (line->type != LINE_TREE_FILE) {
5633 report("Blame only supported for files");
5634 return REQ_NONE;
5637 string_copy(opt_ref, view->vid);
5638 return request;
5640 case REQ_EDIT:
5641 if (line->type != LINE_TREE_FILE) {
5642 report("Edit only supported for files");
5643 } else if (!is_head_commit(view->vid)) {
5644 open_blob_editor(entry->id, entry->name, 0);
5645 } else {
5646 open_editor(opt_file, 0);
5648 return REQ_NONE;
5650 case REQ_TOGGLE_SORT_FIELD:
5651 case REQ_TOGGLE_SORT_ORDER:
5652 sort_view(view, request, &tree_sort_state, tree_compare);
5653 return REQ_NONE;
5655 case REQ_PARENT:
5656 case REQ_BACK:
5657 if (!*opt_path) {
5658 /* quit view if at top of tree */
5659 return REQ_VIEW_CLOSE;
5661 /* fake 'cd ..' */
5662 line = &view->line[1];
5663 break;
5665 case REQ_ENTER:
5666 break;
5668 default:
5669 return request;
5672 /* Cleanup the stack if the tree view is at a different tree. */
5673 if (!*opt_path)
5674 reset_view_history(&tree_view_history);
5676 switch (line->type) {
5677 case LINE_TREE_DIR:
5678 /* Depending on whether it is a subdirectory or parent link
5679 * mangle the path buffer. */
5680 if (line == &view->line[1] && *opt_path) {
5681 pop_tree_stack_entry(&view->pos);
5683 } else {
5684 const char *basename = tree_path(line);
5686 push_tree_stack_entry(basename, &view->pos);
5689 /* Trees and subtrees share the same ID, so they are not not
5690 * unique like blobs. */
5691 flags = OPEN_RELOAD;
5692 request = REQ_VIEW_TREE;
5693 break;
5695 case LINE_TREE_FILE:
5696 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5697 request = REQ_VIEW_BLOB;
5698 break;
5700 default:
5701 return REQ_NONE;
5704 open_view(view, request, flags);
5706 return REQ_NONE;
5709 static bool
5710 tree_grep(struct view *view, struct line *line)
5712 struct tree_entry *entry = line->data;
5713 const char *text[] = {
5714 entry->name,
5715 mkauthor(entry->author, opt_author_width, opt_author),
5716 mkdate(&entry->time, opt_date),
5717 NULL
5720 return grep_text(view, text);
5723 static void
5724 tree_select(struct view *view, struct line *line)
5726 struct tree_entry *entry = line->data;
5728 if (line->type == LINE_TREE_HEAD) {
5729 string_format(view->ref, "Files in /%s", opt_path);
5730 return;
5733 if (line->type == LINE_TREE_DIR && tree_path_is_parent(entry->name)) {
5734 string_copy(view->ref, "Open parent directory");
5735 ref_blob[0] = 0;
5736 return;
5739 if (line->type == LINE_TREE_FILE) {
5740 string_copy_rev(ref_blob, entry->id);
5741 string_format(opt_file, "%s%s", opt_path, tree_path(line));
5744 string_copy_rev(view->ref, entry->id);
5747 static bool
5748 tree_open(struct view *view, enum open_flags flags)
5750 static const char *tree_argv[] = {
5751 "git", "ls-tree", "-l", "%(commit)", "%(directory)", NULL
5754 if (string_rev_is_null(ref_commit)) {
5755 report("No tree exists for this commit");
5756 return FALSE;
5759 if (view->lines == 0 && opt_prefix[0]) {
5760 char *pos = opt_prefix;
5762 while (pos && *pos) {
5763 char *end = strchr(pos, '/');
5765 if (end)
5766 *end = 0;
5767 push_tree_stack_entry(pos, &view->pos);
5768 pos = end;
5769 if (end) {
5770 *end = '/';
5771 pos++;
5775 } else if (strcmp(view->vid, view->id)) {
5776 opt_path[0] = 0;
5779 return begin_update(view, opt_cdup, tree_argv, flags);
5782 static struct view_ops tree_ops = {
5783 "file",
5784 { "tree" },
5785 VIEW_SEND_CHILD_ENTER,
5786 sizeof(struct tree_state),
5787 tree_open,
5788 tree_read,
5789 tree_draw,
5790 tree_request,
5791 tree_grep,
5792 tree_select,
5795 static bool
5796 blob_open(struct view *view, enum open_flags flags)
5798 static const char *blob_argv[] = {
5799 "git", "cat-file", "blob", "%(blob)", NULL
5802 if (!ref_blob[0] && opt_file[0]) {
5803 const char *commit = ref_commit[0] ? ref_commit : "HEAD";
5804 char blob_spec[SIZEOF_STR];
5805 const char *rev_parse_argv[] = {
5806 "git", "rev-parse", blob_spec, NULL
5809 if (!string_format(blob_spec, "%s:%s", commit, opt_file) ||
5810 !io_run_buf(rev_parse_argv, ref_blob, sizeof(ref_blob))) {
5811 report("Failed to resolve blob from file name");
5812 return FALSE;
5816 if (!ref_blob[0]) {
5817 report("No file chosen, press %s to open tree view",
5818 get_view_key(view, REQ_VIEW_TREE));
5819 return FALSE;
5822 view->encoding = get_path_encoding(opt_file, default_encoding);
5824 return begin_update(view, NULL, blob_argv, flags);
5827 static bool
5828 blob_read(struct view *view, char *line)
5830 if (!line)
5831 return TRUE;
5832 return add_line_text(view, line, LINE_DEFAULT) != NULL;
5835 static enum request
5836 blob_request(struct view *view, enum request request, struct line *line)
5838 switch (request) {
5839 case REQ_EDIT:
5840 open_blob_editor(view->vid, NULL, (line - view->line) + 1);
5841 return REQ_NONE;
5842 default:
5843 return pager_request(view, request, line);
5847 static struct view_ops blob_ops = {
5848 "line",
5849 { "blob" },
5850 VIEW_NO_FLAGS,
5852 blob_open,
5853 blob_read,
5854 pager_draw,
5855 blob_request,
5856 pager_grep,
5857 pager_select,
5861 * Blame backend
5863 * Loading the blame view is a two phase job:
5865 * 1. File content is read either using opt_file from the
5866 * filesystem or using git-cat-file.
5867 * 2. Then blame information is incrementally added by
5868 * reading output from git-blame.
5871 struct blame_history_state {
5872 char id[SIZEOF_REV]; /* SHA1 ID. */
5873 const char *filename; /* Name of file. */
5876 static struct view_history blame_view_history = { sizeof(struct blame_history_state) };
5878 struct blame {
5879 struct blame_commit *commit;
5880 unsigned long lineno;
5881 char text[1];
5884 struct blame_state {
5885 struct blame_commit *commit;
5886 int blamed;
5887 bool done_reading;
5888 bool auto_filename_display;
5889 /* The history state for the current view is cached in the view
5890 * state so it always matches what was used to load the current blame
5891 * view. */
5892 struct blame_history_state history_state;
5895 static bool
5896 blame_detect_filename_display(struct view *view)
5898 bool show_filenames = FALSE;
5899 const char *filename = NULL;
5900 int i;
5902 if (opt_blame_argv) {
5903 for (i = 0; opt_blame_argv[i]; i++) {
5904 if (prefixcmp(opt_blame_argv[i], "-C"))
5905 continue;
5907 show_filenames = TRUE;
5911 for (i = 0; i < view->lines; i++) {
5912 struct blame *blame = view->line[i].data;
5914 if (blame->commit && blame->commit->id[0]) {
5915 if (!filename)
5916 filename = blame->commit->filename;
5917 else if (strcmp(filename, blame->commit->filename))
5918 show_filenames = TRUE;
5922 return show_filenames;
5925 static bool
5926 blame_open(struct view *view, enum open_flags flags)
5928 struct blame_state *state = view->private;
5929 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5930 char path[SIZEOF_STR];
5931 size_t i;
5933 if (!opt_file[0]) {
5934 report("No file chosen, press %s to open tree view",
5935 get_view_key(view, REQ_VIEW_TREE));
5936 return FALSE;
5939 if (!view->prev && *opt_prefix && !(flags & (OPEN_RELOAD | OPEN_REFRESH))) {
5940 string_copy(path, opt_file);
5941 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
5942 report("Failed to setup the blame view");
5943 return FALSE;
5947 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5948 const char *blame_cat_file_argv[] = {
5949 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5952 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5953 return FALSE;
5956 /* First pass: remove multiple references to the same commit. */
5957 for (i = 0; i < view->lines; i++) {
5958 struct blame *blame = view->line[i].data;
5960 if (blame->commit && blame->commit->id[0])
5961 blame->commit->id[0] = 0;
5962 else
5963 blame->commit = NULL;
5966 /* Second pass: free existing references. */
5967 for (i = 0; i < view->lines; i++) {
5968 struct blame *blame = view->line[i].data;
5970 if (blame->commit)
5971 free(blame->commit);
5974 if (!(flags & OPEN_RELOAD))
5975 reset_view_history(&blame_view_history);
5976 string_copy_rev(state->history_state.id, opt_ref);
5977 state->history_state.filename = get_path(opt_file);
5978 if (!state->history_state.filename)
5979 return FALSE;
5980 string_format(view->vid, "%s", opt_file);
5981 string_format(view->ref, "%s ...", opt_file);
5983 return TRUE;
5986 static struct blame_commit *
5987 get_blame_commit(struct view *view, const char *id)
5989 size_t i;
5991 for (i = 0; i < view->lines; i++) {
5992 struct blame *blame = view->line[i].data;
5994 if (!blame->commit)
5995 continue;
5997 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5998 return blame->commit;
6002 struct blame_commit *commit = calloc(1, sizeof(*commit));
6004 if (commit)
6005 string_ncopy(commit->id, id, SIZEOF_REV);
6006 return commit;
6010 static struct blame_commit *
6011 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
6013 struct blame_header header;
6014 struct blame_commit *commit;
6015 struct blame *blame;
6017 if (!parse_blame_header(&header, text, view->lines))
6018 return NULL;
6020 commit = get_blame_commit(view, text);
6021 if (!commit)
6022 return NULL;
6024 state->blamed += header.group;
6025 while (header.group--) {
6026 struct line *line = &view->line[header.lineno + header.group - 1];
6028 blame = line->data;
6029 blame->commit = commit;
6030 blame->lineno = header.orig_lineno + header.group - 1;
6031 line->dirty = 1;
6034 return commit;
6037 static bool
6038 blame_read_file(struct view *view, const char *text, struct blame_state *state)
6040 if (!text) {
6041 const char *blame_argv[] = {
6042 "git", "blame", encoding_arg, "%(blameargs)", "--incremental",
6043 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
6046 if (view->lines == 0 && !view->prev)
6047 die("No blame exist for %s", view->vid);
6049 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
6050 report("Failed to load blame data");
6051 return TRUE;
6054 if (opt_goto_line > 0) {
6055 select_view_line(view, opt_goto_line);
6056 opt_goto_line = 0;
6059 state->done_reading = TRUE;
6060 return FALSE;
6062 } else {
6063 size_t textlen = strlen(text);
6064 struct blame *blame;
6066 if (!add_line_alloc(view, &blame, LINE_ID, textlen, FALSE))
6067 return FALSE;
6069 blame->commit = NULL;
6070 strncpy(blame->text, text, textlen);
6071 blame->text[textlen] = 0;
6072 return TRUE;
6076 static bool
6077 blame_read(struct view *view, char *line)
6079 struct blame_state *state = view->private;
6081 if (!state->done_reading)
6082 return blame_read_file(view, line, state);
6084 if (!line) {
6085 state->auto_filename_display = blame_detect_filename_display(view);
6086 string_format(view->ref, "%s", view->vid);
6087 if (view_is_displayed(view)) {
6088 update_view_title(view);
6089 redraw_view_from(view, 0);
6091 return TRUE;
6094 if (!state->commit) {
6095 state->commit = read_blame_commit(view, line, state);
6096 string_format(view->ref, "%s %2zd%%", view->vid,
6097 view->lines ? state->blamed * 100 / view->lines : 0);
6099 } else if (parse_blame_info(state->commit, line)) {
6100 if (!state->commit->filename)
6101 return FALSE;
6102 state->commit = NULL;
6105 return TRUE;
6108 static bool
6109 blame_draw(struct view *view, struct line *line, unsigned int lineno)
6111 struct blame_state *state = view->private;
6112 struct blame *blame = line->data;
6113 struct time *time = NULL;
6114 const char *id = NULL, *filename = NULL;
6115 const struct ident *author = NULL;
6116 enum line_type id_type = LINE_ID;
6117 static const enum line_type blame_colors[] = {
6118 LINE_PALETTE_0,
6119 LINE_PALETTE_1,
6120 LINE_PALETTE_2,
6121 LINE_PALETTE_3,
6122 LINE_PALETTE_4,
6123 LINE_PALETTE_5,
6124 LINE_PALETTE_6,
6127 #define BLAME_COLOR(i) \
6128 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
6130 if (blame->commit && blame->commit->filename) {
6131 id = blame->commit->id;
6132 author = blame->commit->author;
6133 filename = blame->commit->filename;
6134 time = &blame->commit->time;
6135 id_type = BLAME_COLOR((long) blame->commit);
6138 if (draw_date(view, time))
6139 return TRUE;
6141 if (draw_author(view, author))
6142 return TRUE;
6144 if (draw_filename(view, filename, state->auto_filename_display))
6145 return TRUE;
6147 if (draw_id_custom(view, id_type, id, opt_id_cols))
6148 return TRUE;
6150 if (draw_lineno(view, lineno))
6151 return TRUE;
6153 draw_text(view, LINE_DEFAULT, blame->text);
6154 return TRUE;
6157 static bool
6158 check_blame_commit(struct blame *blame, bool check_null_id)
6160 if (!blame->commit)
6161 report("Commit data not loaded yet");
6162 else if (check_null_id && string_rev_is_null(blame->commit->id))
6163 report("No commit exist for the selected line");
6164 else
6165 return TRUE;
6166 return FALSE;
6169 static void
6170 setup_blame_parent_line(struct view *view, struct blame *blame)
6172 char from[SIZEOF_REF + SIZEOF_STR];
6173 char to[SIZEOF_REF + SIZEOF_STR];
6174 const char *diff_tree_argv[] = {
6175 "git", "diff", encoding_arg, "--no-textconv", "--no-extdiff",
6176 "--no-color", "-U0", from, to, "--", NULL
6178 struct io io;
6179 int parent_lineno = -1;
6180 int blamed_lineno = -1;
6181 char *line;
6183 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
6184 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
6185 !io_run(&io, IO_RD, NULL, opt_env, diff_tree_argv))
6186 return;
6188 while ((line = io_get(&io, '\n', TRUE))) {
6189 if (*line == '@') {
6190 char *pos = strchr(line, '+');
6192 parent_lineno = atoi(line + 4);
6193 if (pos)
6194 blamed_lineno = atoi(pos + 1);
6196 } else if (*line == '+' && parent_lineno != -1) {
6197 if (blame->lineno == blamed_lineno - 1 &&
6198 !strcmp(blame->text, line + 1)) {
6199 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
6200 break;
6202 blamed_lineno++;
6206 io_done(&io);
6209 static void
6210 blame_go_forward(struct view *view, struct blame *blame, bool parent)
6212 struct blame_state *state = view->private;
6213 struct blame_history_state *history_state = &state->history_state;
6214 struct blame_commit *commit = blame->commit;
6215 const char *id = parent ? commit->parent_id : commit->id;
6216 const char *filename = parent ? commit->parent_filename : commit->filename;
6218 if (!*id && parent) {
6219 report("The selected commit has no parents");
6220 return;
6223 if (!strcmp(history_state->id, id) && !strcmp(history_state->filename, filename)) {
6224 report("The selected commit is already displayed");
6225 return;
6228 if (!push_view_history_state(&blame_view_history, &view->pos, history_state)) {
6229 report("Failed to save current view state");
6230 return;
6233 string_ncopy(opt_ref, id, sizeof(commit->id));
6234 string_ncopy(opt_file, filename, strlen(filename));
6235 if (parent)
6236 setup_blame_parent_line(view, blame);
6237 opt_goto_line = blame->lineno;
6238 reload_view(view);
6241 static void
6242 blame_go_back(struct view *view)
6244 struct blame_history_state history_state;
6246 if (!pop_view_history_state(&blame_view_history, &view->pos, &history_state)) {
6247 report("Already at start of history");
6248 return;
6251 string_copy(opt_ref, history_state.id);
6252 string_ncopy(opt_file, history_state.filename, strlen(history_state.filename));
6253 opt_goto_line = view->pos.lineno;
6254 reload_view(view);
6257 static enum request
6258 blame_request(struct view *view, enum request request, struct line *line)
6260 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6261 struct blame *blame = line->data;
6263 switch (request) {
6264 case REQ_VIEW_BLAME:
6265 case REQ_PARENT:
6266 if (!check_blame_commit(blame, TRUE))
6267 break;
6268 blame_go_forward(view, blame, request == REQ_PARENT);
6269 break;
6271 case REQ_BACK:
6272 blame_go_back(view);
6273 break;
6275 case REQ_ENTER:
6276 if (!check_blame_commit(blame, FALSE))
6277 break;
6279 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
6280 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
6281 break;
6283 if (string_rev_is_null(blame->commit->id)) {
6284 struct view *diff = VIEW(REQ_VIEW_DIFF);
6285 const char *diff_parent_argv[] = {
6286 GIT_DIFF_BLAME(encoding_arg,
6287 opt_diff_context_arg,
6288 opt_ignore_space_arg, view->vid)
6290 const char *diff_no_parent_argv[] = {
6291 GIT_DIFF_BLAME_NO_PARENT(encoding_arg,
6292 opt_diff_context_arg,
6293 opt_ignore_space_arg, view->vid)
6295 const char **diff_index_argv = *blame->commit->parent_id
6296 ? diff_parent_argv : diff_no_parent_argv;
6298 open_argv(view, diff, diff_index_argv, NULL, flags);
6299 if (diff->pipe)
6300 string_copy_rev(diff->ref, NULL_ID);
6301 } else {
6302 open_view(view, REQ_VIEW_DIFF, flags);
6304 break;
6306 default:
6307 return request;
6310 return REQ_NONE;
6313 static bool
6314 blame_grep(struct view *view, struct line *line)
6316 struct blame *blame = line->data;
6317 struct blame_commit *commit = blame->commit;
6318 const char *text[] = {
6319 blame->text,
6320 commit ? commit->title : "",
6321 commit ? commit->id : "",
6322 commit ? mkauthor(commit->author, opt_author_width, opt_author) : "",
6323 commit ? mkdate(&commit->time, opt_date) : "",
6324 NULL
6327 return grep_text(view, text);
6330 static void
6331 blame_select(struct view *view, struct line *line)
6333 struct blame *blame = line->data;
6334 struct blame_commit *commit = blame->commit;
6336 if (!commit)
6337 return;
6339 if (string_rev_is_null(commit->id))
6340 string_ncopy(ref_commit, "HEAD", 4);
6341 else
6342 string_copy_rev(ref_commit, commit->id);
6345 static struct view_ops blame_ops = {
6346 "line",
6347 { "blame" },
6348 VIEW_ALWAYS_LINENO | VIEW_SEND_CHILD_ENTER,
6349 sizeof(struct blame_state),
6350 blame_open,
6351 blame_read,
6352 blame_draw,
6353 blame_request,
6354 blame_grep,
6355 blame_select,
6359 * Branch backend
6362 struct branch {
6363 const struct ident *author; /* Author of the last commit. */
6364 struct time time; /* Date of the last activity. */
6365 char title[128]; /* First line of the commit message. */
6366 const struct ref *ref; /* Name and commit ID information. */
6369 static const struct ref branch_all;
6370 #define BRANCH_ALL_NAME "All branches"
6371 #define branch_is_all(branch) ((branch)->ref == &branch_all)
6373 static const enum sort_field branch_sort_fields[] = {
6374 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
6376 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
6378 struct branch_state {
6379 char id[SIZEOF_REV];
6380 size_t max_ref_length;
6383 static int
6384 branch_compare(const void *l1, const void *l2)
6386 const struct branch *branch1 = ((const struct line *) l1)->data;
6387 const struct branch *branch2 = ((const struct line *) l2)->data;
6389 if (branch_is_all(branch1))
6390 return -1;
6391 else if (branch_is_all(branch2))
6392 return 1;
6394 switch (get_sort_field(branch_sort_state)) {
6395 case ORDERBY_DATE:
6396 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
6398 case ORDERBY_AUTHOR:
6399 return sort_order(branch_sort_state, ident_compare(branch1->author, branch2->author));
6401 case ORDERBY_NAME:
6402 default:
6403 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
6407 static bool
6408 branch_draw(struct view *view, struct line *line, unsigned int lineno)
6410 struct branch_state *state = view->private;
6411 struct branch *branch = line->data;
6412 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
6413 const char *branch_name = branch_is_all(branch) ? BRANCH_ALL_NAME : branch->ref->name;
6415 if (draw_lineno(view, lineno))
6416 return TRUE;
6418 if (draw_date(view, &branch->time))
6419 return TRUE;
6421 if (draw_author(view, branch->author))
6422 return TRUE;
6424 if (draw_field(view, type, branch_name, state->max_ref_length, ALIGN_LEFT, FALSE))
6425 return TRUE;
6427 if (draw_id(view, branch->ref->id))
6428 return TRUE;
6430 draw_text(view, LINE_DEFAULT, branch->title);
6431 return TRUE;
6434 static enum request
6435 branch_request(struct view *view, enum request request, struct line *line)
6437 struct branch *branch = line->data;
6439 switch (request) {
6440 case REQ_REFRESH:
6441 load_refs(TRUE);
6442 refresh_view(view);
6443 return REQ_NONE;
6445 case REQ_TOGGLE_SORT_FIELD:
6446 case REQ_TOGGLE_SORT_ORDER:
6447 sort_view(view, request, &branch_sort_state, branch_compare);
6448 return REQ_NONE;
6450 case REQ_ENTER:
6452 const struct ref *ref = branch->ref;
6453 const char *all_branches_argv[] = {
6454 GIT_MAIN_LOG(encoding_arg, "", branch_is_all(branch) ? "--all" : ref->name, "")
6456 struct view *main_view = VIEW(REQ_VIEW_MAIN);
6458 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
6459 return REQ_NONE;
6461 case REQ_JUMP_COMMIT:
6463 int lineno;
6465 for (lineno = 0; lineno < view->lines; lineno++) {
6466 struct branch *branch = view->line[lineno].data;
6468 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
6469 select_view_line(view, lineno);
6470 report_clear();
6471 return REQ_NONE;
6475 default:
6476 return request;
6480 static bool
6481 branch_read(struct view *view, char *line)
6483 struct branch_state *state = view->private;
6484 const char *title = NULL;
6485 const struct ident *author = NULL;
6486 struct time time = {};
6487 size_t i;
6489 if (!line)
6490 return TRUE;
6492 switch (get_line_type(line)) {
6493 case LINE_COMMIT:
6494 string_copy_rev_from_commit_line(state->id, line);
6495 return TRUE;
6497 case LINE_AUTHOR:
6498 parse_author_line(line + STRING_SIZE("author "), &author, &time);
6499 break;
6501 default:
6502 title = line + STRING_SIZE("title ");
6505 for (i = 0; i < view->lines; i++) {
6506 struct branch *branch = view->line[i].data;
6508 if (strcmp(branch->ref->id, state->id))
6509 continue;
6511 if (author) {
6512 branch->author = author;
6513 branch->time = time;
6516 if (title)
6517 string_expand(branch->title, sizeof(branch->title), title, 1);
6519 view->line[i].dirty = TRUE;
6522 return TRUE;
6525 static bool
6526 branch_open_visitor(void *data, const struct ref *ref)
6528 struct view *view = data;
6529 struct branch_state *state = view->private;
6530 struct branch *branch;
6531 bool is_all = ref == &branch_all;
6532 size_t ref_length;
6534 if (ref->tag || ref->ltag)
6535 return TRUE;
6537 if (!add_line_alloc(view, &branch, LINE_DEFAULT, 0, is_all))
6538 return FALSE;
6540 ref_length = is_all ? STRING_SIZE(BRANCH_ALL_NAME) : strlen(ref->name);
6541 if (ref_length > state->max_ref_length)
6542 state->max_ref_length = ref_length;
6544 branch->ref = ref;
6545 return TRUE;
6548 static bool
6549 branch_open(struct view *view, enum open_flags flags)
6551 const char *branch_log[] = {
6552 "git", "log", encoding_arg, "--no-color", "--date=raw",
6553 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
6554 "--all", "--simplify-by-decoration", NULL
6557 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
6558 report("Failed to load branch data");
6559 return FALSE;
6562 branch_open_visitor(view, &branch_all);
6563 foreach_ref(branch_open_visitor, view);
6565 return TRUE;
6568 static bool
6569 branch_grep(struct view *view, struct line *line)
6571 struct branch *branch = line->data;
6572 const char *text[] = {
6573 branch->ref->name,
6574 mkauthor(branch->author, opt_author_width, opt_author),
6575 NULL
6578 return grep_text(view, text);
6581 static void
6582 branch_select(struct view *view, struct line *line)
6584 struct branch *branch = line->data;
6586 if (branch_is_all(branch)) {
6587 string_copy(view->ref, BRANCH_ALL_NAME);
6588 return;
6590 string_copy_rev(view->ref, branch->ref->id);
6591 string_copy_rev(ref_commit, branch->ref->id);
6592 string_copy_rev(ref_head, branch->ref->id);
6593 string_copy_rev(ref_branch, branch->ref->name);
6596 static struct view_ops branch_ops = {
6597 "branch",
6598 { "branch" },
6599 VIEW_NO_FLAGS,
6600 sizeof(struct branch_state),
6601 branch_open,
6602 branch_read,
6603 branch_draw,
6604 branch_request,
6605 branch_grep,
6606 branch_select,
6610 * Status backend
6613 struct status {
6614 char status;
6615 struct {
6616 mode_t mode;
6617 char rev[SIZEOF_REV];
6618 char name[SIZEOF_STR];
6619 } old;
6620 struct {
6621 mode_t mode;
6622 char rev[SIZEOF_REV];
6623 char name[SIZEOF_STR];
6624 } new;
6627 static char status_onbranch[SIZEOF_STR];
6628 static struct status stage_status;
6629 static enum line_type stage_line_type;
6631 DEFINE_ALLOCATOR(realloc_ints, int, 32)
6633 /* This should work even for the "On branch" line. */
6634 static inline bool
6635 status_has_none(struct view *view, struct line *line)
6637 return view_has_line(view, line) && !line[1].data;
6640 /* Get fields from the diff line:
6641 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
6643 static inline bool
6644 status_get_diff(struct status *file, const char *buf, size_t bufsize)
6646 const char *old_mode = buf + 1;
6647 const char *new_mode = buf + 8;
6648 const char *old_rev = buf + 15;
6649 const char *new_rev = buf + 56;
6650 const char *status = buf + 97;
6652 if (bufsize < 98 ||
6653 old_mode[-1] != ':' ||
6654 new_mode[-1] != ' ' ||
6655 old_rev[-1] != ' ' ||
6656 new_rev[-1] != ' ' ||
6657 status[-1] != ' ')
6658 return FALSE;
6660 file->status = *status;
6662 string_copy_rev(file->old.rev, old_rev);
6663 string_copy_rev(file->new.rev, new_rev);
6665 file->old.mode = strtoul(old_mode, NULL, 8);
6666 file->new.mode = strtoul(new_mode, NULL, 8);
6668 file->old.name[0] = file->new.name[0] = 0;
6670 return TRUE;
6673 static bool
6674 status_run(struct view *view, const char *argv[], char status, enum line_type type)
6676 struct status *unmerged = NULL;
6677 char *buf;
6678 struct io io;
6680 if (!io_run(&io, IO_RD, opt_cdup, opt_env, argv))
6681 return FALSE;
6683 add_line_nodata(view, type);
6685 while ((buf = io_get(&io, 0, TRUE))) {
6686 struct status *file = unmerged;
6688 if (!file) {
6689 if (!add_line_alloc(view, &file, type, 0, FALSE))
6690 goto error_out;
6693 /* Parse diff info part. */
6694 if (status) {
6695 file->status = status;
6696 if (status == 'A')
6697 string_copy(file->old.rev, NULL_ID);
6699 } else if (!file->status || file == unmerged) {
6700 if (!status_get_diff(file, buf, strlen(buf)))
6701 goto error_out;
6703 buf = io_get(&io, 0, TRUE);
6704 if (!buf)
6705 break;
6707 /* Collapse all modified entries that follow an
6708 * associated unmerged entry. */
6709 if (unmerged == file) {
6710 unmerged->status = 'U';
6711 unmerged = NULL;
6712 } else if (file->status == 'U') {
6713 unmerged = file;
6717 /* Grab the old name for rename/copy. */
6718 if (!*file->old.name &&
6719 (file->status == 'R' || file->status == 'C')) {
6720 string_ncopy(file->old.name, buf, strlen(buf));
6722 buf = io_get(&io, 0, TRUE);
6723 if (!buf)
6724 break;
6727 /* git-ls-files just delivers a NUL separated list of
6728 * file names similar to the second half of the
6729 * git-diff-* output. */
6730 string_ncopy(file->new.name, buf, strlen(buf));
6731 if (!*file->old.name)
6732 string_copy(file->old.name, file->new.name);
6733 file = NULL;
6736 if (io_error(&io)) {
6737 error_out:
6738 io_done(&io);
6739 return FALSE;
6742 if (!view->line[view->lines - 1].data)
6743 add_line_nodata(view, LINE_STAT_NONE);
6745 io_done(&io);
6746 return TRUE;
6749 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
6750 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
6752 static const char *status_list_other_argv[] = {
6753 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
6756 static const char *status_list_no_head_argv[] = {
6757 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
6760 static const char *update_index_argv[] = {
6761 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
6764 /* Restore the previous line number to stay in the context or select a
6765 * line with something that can be updated. */
6766 static void
6767 status_restore(struct view *view)
6769 if (!check_position(&view->prev_pos))
6770 return;
6772 if (view->prev_pos.lineno >= view->lines)
6773 view->prev_pos.lineno = view->lines - 1;
6774 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
6775 view->prev_pos.lineno++;
6776 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
6777 view->prev_pos.lineno--;
6779 /* If the above fails, always skip the "On branch" line. */
6780 if (view->prev_pos.lineno < view->lines)
6781 view->pos.lineno = view->prev_pos.lineno;
6782 else
6783 view->pos.lineno = 1;
6785 if (view->prev_pos.offset > view->pos.lineno)
6786 view->pos.offset = view->pos.lineno;
6787 else if (view->prev_pos.offset < view->lines)
6788 view->pos.offset = view->prev_pos.offset;
6790 clear_position(&view->prev_pos);
6793 static void
6794 status_update_onbranch(void)
6796 static const char *paths[][2] = {
6797 { "rebase-apply/rebasing", "Rebasing" },
6798 { "rebase-apply/applying", "Applying mailbox" },
6799 { "rebase-apply/", "Rebasing mailbox" },
6800 { "rebase-merge/interactive", "Interactive rebase" },
6801 { "rebase-merge/", "Rebase merge" },
6802 { "MERGE_HEAD", "Merging" },
6803 { "BISECT_LOG", "Bisecting" },
6804 { "HEAD", "On branch" },
6806 char buf[SIZEOF_STR];
6807 struct stat stat;
6808 int i;
6810 if (is_initial_commit()) {
6811 string_copy(status_onbranch, "Initial commit");
6812 return;
6815 for (i = 0; i < ARRAY_SIZE(paths); i++) {
6816 char *head = opt_head;
6818 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
6819 lstat(buf, &stat) < 0)
6820 continue;
6822 if (!*opt_head) {
6823 struct io io;
6825 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
6826 io_read_buf(&io, buf, sizeof(buf))) {
6827 head = buf;
6828 if (!prefixcmp(head, "refs/heads/"))
6829 head += STRING_SIZE("refs/heads/");
6833 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
6834 string_copy(status_onbranch, opt_head);
6835 return;
6838 string_copy(status_onbranch, "Not currently on any branch");
6841 /* First parse staged info using git-diff-index(1), then parse unstaged
6842 * info using git-diff-files(1), and finally untracked files using
6843 * git-ls-files(1). */
6844 static bool
6845 status_open(struct view *view, enum open_flags flags)
6847 const char **staged_argv = is_initial_commit() ?
6848 status_list_no_head_argv : status_diff_index_argv;
6849 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
6851 if (opt_is_inside_work_tree == FALSE) {
6852 report("The status view requires a working tree");
6853 return FALSE;
6856 reset_view(view);
6858 add_line_nodata(view, LINE_STAT_HEAD);
6859 status_update_onbranch();
6861 io_run_bg(update_index_argv);
6863 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] =
6864 opt_untracked_dirs_content ? NULL : "--directory";
6866 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
6867 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
6868 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
6869 report("Failed to load status data");
6870 return FALSE;
6873 /* Restore the exact position or use the specialized restore
6874 * mode? */
6875 status_restore(view);
6876 return TRUE;
6879 static bool
6880 status_draw(struct view *view, struct line *line, unsigned int lineno)
6882 struct status *status = line->data;
6883 enum line_type type;
6884 const char *text;
6886 if (!status) {
6887 switch (line->type) {
6888 case LINE_STAT_STAGED:
6889 type = LINE_STAT_SECTION;
6890 text = "Changes to be committed:";
6891 break;
6893 case LINE_STAT_UNSTAGED:
6894 type = LINE_STAT_SECTION;
6895 text = "Changed but not updated:";
6896 break;
6898 case LINE_STAT_UNTRACKED:
6899 type = LINE_STAT_SECTION;
6900 text = "Untracked files:";
6901 break;
6903 case LINE_STAT_NONE:
6904 type = LINE_DEFAULT;
6905 text = " (no files)";
6906 break;
6908 case LINE_STAT_HEAD:
6909 type = LINE_STAT_HEAD;
6910 text = status_onbranch;
6911 break;
6913 default:
6914 return FALSE;
6916 } else {
6917 static char buf[] = { '?', ' ', ' ', ' ', 0 };
6919 buf[0] = status->status;
6920 if (draw_text(view, line->type, buf))
6921 return TRUE;
6922 type = LINE_DEFAULT;
6923 text = status->new.name;
6926 draw_text(view, type, text);
6927 return TRUE;
6930 static enum request
6931 status_enter(struct view *view, struct line *line)
6933 struct status *status = line->data;
6934 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6936 if (line->type == LINE_STAT_NONE ||
6937 (!status && line[1].type == LINE_STAT_NONE)) {
6938 report("No file to diff");
6939 return REQ_NONE;
6942 switch (line->type) {
6943 case LINE_STAT_STAGED:
6944 case LINE_STAT_UNSTAGED:
6945 break;
6947 case LINE_STAT_UNTRACKED:
6948 if (!status) {
6949 report("No file to show");
6950 return REQ_NONE;
6953 if (!suffixcmp(status->new.name, -1, "/")) {
6954 report("Cannot display a directory");
6955 return REQ_NONE;
6957 break;
6959 case LINE_STAT_HEAD:
6960 return REQ_NONE;
6962 default:
6963 die("line type %d not handled in switch", line->type);
6966 if (status) {
6967 stage_status = *status;
6968 } else {
6969 memset(&stage_status, 0, sizeof(stage_status));
6972 stage_line_type = line->type;
6974 open_view(view, REQ_VIEW_STAGE, flags);
6975 return REQ_NONE;
6978 static bool
6979 status_exists(struct view *view, struct status *status, enum line_type type)
6981 unsigned long lineno;
6983 for (lineno = 0; lineno < view->lines; lineno++) {
6984 struct line *line = &view->line[lineno];
6985 struct status *pos = line->data;
6987 if (line->type != type)
6988 continue;
6989 if (!pos && (!status || !status->status) && line[1].data) {
6990 select_view_line(view, lineno);
6991 return TRUE;
6993 if (pos && !strcmp(status->new.name, pos->new.name)) {
6994 select_view_line(view, lineno);
6995 return TRUE;
6999 return FALSE;
7003 static bool
7004 status_update_prepare(struct io *io, enum line_type type)
7006 const char *staged_argv[] = {
7007 "git", "update-index", "-z", "--index-info", NULL
7009 const char *others_argv[] = {
7010 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
7013 switch (type) {
7014 case LINE_STAT_STAGED:
7015 return io_run(io, IO_WR, opt_cdup, opt_env, staged_argv);
7017 case LINE_STAT_UNSTAGED:
7018 case LINE_STAT_UNTRACKED:
7019 return io_run(io, IO_WR, opt_cdup, opt_env, others_argv);
7021 default:
7022 die("line type %d not handled in switch", type);
7023 return FALSE;
7027 static bool
7028 status_update_write(struct io *io, struct status *status, enum line_type type)
7030 switch (type) {
7031 case LINE_STAT_STAGED:
7032 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
7033 status->old.rev, status->old.name, 0);
7035 case LINE_STAT_UNSTAGED:
7036 case LINE_STAT_UNTRACKED:
7037 return io_printf(io, "%s%c", status->new.name, 0);
7039 default:
7040 die("line type %d not handled in switch", type);
7041 return FALSE;
7045 static bool
7046 status_update_file(struct status *status, enum line_type type)
7048 struct io io;
7049 bool result;
7051 if (!status_update_prepare(&io, type))
7052 return FALSE;
7054 result = status_update_write(&io, status, type);
7055 return io_done(&io) && result;
7058 static bool
7059 status_update_files(struct view *view, struct line *line)
7061 char buf[sizeof(view->ref)];
7062 struct io io;
7063 bool result = TRUE;
7064 struct line *pos;
7065 int files = 0;
7066 int file, done;
7067 int cursor_y = -1, cursor_x = -1;
7069 if (!status_update_prepare(&io, line->type))
7070 return FALSE;
7072 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
7073 files++;
7075 string_copy(buf, view->ref);
7076 getsyx(cursor_y, cursor_x);
7077 for (file = 0, done = 5; result && file < files; line++, file++) {
7078 int almost_done = file * 100 / files;
7080 if (almost_done > done) {
7081 done = almost_done;
7082 string_format(view->ref, "updating file %u of %u (%d%% done)",
7083 file, files, done);
7084 update_view_title(view);
7085 setsyx(cursor_y, cursor_x);
7086 doupdate();
7088 result = status_update_write(&io, line->data, line->type);
7090 string_copy(view->ref, buf);
7092 return io_done(&io) && result;
7095 static bool
7096 status_update(struct view *view)
7098 struct line *line = &view->line[view->pos.lineno];
7100 assert(view->lines);
7102 if (!line->data) {
7103 if (status_has_none(view, line)) {
7104 report("Nothing to update");
7105 return FALSE;
7108 if (!status_update_files(view, line + 1)) {
7109 report("Failed to update file status");
7110 return FALSE;
7113 } else if (!status_update_file(line->data, line->type)) {
7114 report("Failed to update file status");
7115 return FALSE;
7118 return TRUE;
7121 static bool
7122 status_revert(struct status *status, enum line_type type, bool has_none)
7124 if (!status || type != LINE_STAT_UNSTAGED) {
7125 if (type == LINE_STAT_STAGED) {
7126 report("Cannot revert changes to staged files");
7127 } else if (type == LINE_STAT_UNTRACKED) {
7128 report("Cannot revert changes to untracked files");
7129 } else if (has_none) {
7130 report("Nothing to revert");
7131 } else {
7132 report("Cannot revert changes to multiple files");
7135 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
7136 char mode[10] = "100644";
7137 const char *reset_argv[] = {
7138 "git", "update-index", "--cacheinfo", mode,
7139 status->old.rev, status->old.name, NULL
7141 const char *checkout_argv[] = {
7142 "git", "checkout", "--", status->old.name, NULL
7145 if (status->status == 'U') {
7146 string_format(mode, "%5o", status->old.mode);
7148 if (status->old.mode == 0 && status->new.mode == 0) {
7149 reset_argv[2] = "--force-remove";
7150 reset_argv[3] = status->old.name;
7151 reset_argv[4] = NULL;
7154 if (!io_run_fg(reset_argv, opt_cdup))
7155 return FALSE;
7156 if (status->old.mode == 0 && status->new.mode == 0)
7157 return TRUE;
7160 return io_run_fg(checkout_argv, opt_cdup);
7163 return FALSE;
7166 static enum request
7167 status_request(struct view *view, enum request request, struct line *line)
7169 struct status *status = line->data;
7171 switch (request) {
7172 case REQ_STATUS_UPDATE:
7173 if (!status_update(view))
7174 return REQ_NONE;
7175 break;
7177 case REQ_STATUS_REVERT:
7178 if (!status_revert(status, line->type, status_has_none(view, line)))
7179 return REQ_NONE;
7180 break;
7182 case REQ_STATUS_MERGE:
7183 if (!status || status->status != 'U') {
7184 report("Merging only possible for files with unmerged status ('U').");
7185 return REQ_NONE;
7187 open_mergetool(status->new.name);
7188 break;
7190 case REQ_EDIT:
7191 if (!status)
7192 return request;
7193 if (status->status == 'D') {
7194 report("File has been deleted.");
7195 return REQ_NONE;
7198 open_editor(status->new.name, 0);
7199 break;
7201 case REQ_VIEW_BLAME:
7202 if (status)
7203 opt_ref[0] = 0;
7204 return request;
7206 case REQ_ENTER:
7207 /* After returning the status view has been split to
7208 * show the stage view. No further reloading is
7209 * necessary. */
7210 return status_enter(view, line);
7212 case REQ_REFRESH:
7213 /* Load the current branch information and then the view. */
7214 load_refs(TRUE);
7215 break;
7217 default:
7218 return request;
7221 refresh_view(view);
7223 return REQ_NONE;
7226 static bool
7227 status_stage_info_(char *buf, size_t bufsize,
7228 enum line_type type, struct status *status)
7230 const char *file = status ? status->new.name : "";
7231 const char *info;
7233 switch (type) {
7234 case LINE_STAT_STAGED:
7235 if (status && status->status)
7236 info = "Staged changes to %s";
7237 else
7238 info = "Staged changes";
7239 break;
7241 case LINE_STAT_UNSTAGED:
7242 if (status && status->status)
7243 info = "Unstaged changes to %s";
7244 else
7245 info = "Unstaged changes";
7246 break;
7248 case LINE_STAT_UNTRACKED:
7249 info = "Untracked file %s";
7250 break;
7252 case LINE_STAT_HEAD:
7253 default:
7254 info = "";
7257 return string_nformat(buf, bufsize, NULL, info, file);
7259 #define status_stage_info(buf, type, status) \
7260 status_stage_info_(buf, sizeof(buf), type, status)
7262 static void
7263 status_select(struct view *view, struct line *line)
7265 struct status *status = line->data;
7266 char file[SIZEOF_STR] = "all files";
7267 const char *text;
7268 const char *key;
7270 if (status && !string_format(file, "'%s'", status->new.name))
7271 return;
7273 if (!status && line[1].type == LINE_STAT_NONE)
7274 line++;
7276 switch (line->type) {
7277 case LINE_STAT_STAGED:
7278 text = "Press %s to unstage %s for commit";
7279 break;
7281 case LINE_STAT_UNSTAGED:
7282 text = "Press %s to stage %s for commit";
7283 break;
7285 case LINE_STAT_UNTRACKED:
7286 text = "Press %s to stage %s for addition";
7287 break;
7289 case LINE_STAT_HEAD:
7290 case LINE_STAT_NONE:
7291 text = "Nothing to update";
7292 break;
7294 default:
7295 die("line type %d not handled in switch", line->type);
7298 if (status && status->status == 'U') {
7299 text = "Press %s to resolve conflict in %s";
7300 key = get_view_key(view, REQ_STATUS_MERGE);
7302 } else {
7303 key = get_view_key(view, REQ_STATUS_UPDATE);
7306 string_format(view->ref, text, key, file);
7307 status_stage_info(ref_status, line->type, status);
7308 if (status)
7309 string_copy(opt_file, status->new.name);
7312 static bool
7313 status_grep(struct view *view, struct line *line)
7315 struct status *status = line->data;
7317 if (status) {
7318 const char buf[2] = { status->status, 0 };
7319 const char *text[] = { status->new.name, buf, NULL };
7321 return grep_text(view, text);
7324 return FALSE;
7327 static struct view_ops status_ops = {
7328 "file",
7329 { "status" },
7330 VIEW_CUSTOM_STATUS | VIEW_SEND_CHILD_ENTER | VIEW_STATUS_LIKE,
7332 status_open,
7333 NULL,
7334 status_draw,
7335 status_request,
7336 status_grep,
7337 status_select,
7341 struct stage_state {
7342 struct diff_state diff;
7343 size_t chunks;
7344 int *chunk;
7347 static bool
7348 stage_diff_write(struct io *io, struct line *line, struct line *end)
7350 while (line < end) {
7351 if (!io_write(io, line->data, strlen(line->data)) ||
7352 !io_write(io, "\n", 1))
7353 return FALSE;
7354 line++;
7355 if (line->type == LINE_DIFF_CHUNK ||
7356 line->type == LINE_DIFF_HEADER)
7357 break;
7360 return TRUE;
7363 static bool
7364 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
7366 const char *apply_argv[SIZEOF_ARG] = {
7367 "git", "apply", "--whitespace=nowarn", NULL
7369 struct line *diff_hdr;
7370 struct io io;
7371 int argc = 3;
7373 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
7374 if (!diff_hdr)
7375 return FALSE;
7377 if (!revert)
7378 apply_argv[argc++] = "--cached";
7379 if (line != NULL)
7380 apply_argv[argc++] = "--unidiff-zero";
7381 if (revert || stage_line_type == LINE_STAT_STAGED)
7382 apply_argv[argc++] = "-R";
7383 apply_argv[argc++] = "-";
7384 apply_argv[argc++] = NULL;
7385 if (!io_run(&io, IO_WR, opt_cdup, opt_env, apply_argv))
7386 return FALSE;
7388 if (line != NULL) {
7389 unsigned long lineno = 0;
7390 struct line *context = chunk + 1;
7391 const char *markers[] = {
7392 line->type == LINE_DIFF_DEL ? "" : ",0",
7393 line->type == LINE_DIFF_DEL ? ",0" : "",
7396 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
7398 while (context < line) {
7399 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
7400 break;
7401 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
7402 lineno++;
7404 context++;
7407 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7408 !io_printf(&io, "@@ -%lu%s +%lu%s @@\n",
7409 lineno, markers[0], lineno, markers[1]) ||
7410 !stage_diff_write(&io, line, line + 1)) {
7411 chunk = NULL;
7413 } else {
7414 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7415 !stage_diff_write(&io, chunk, view->line + view->lines))
7416 chunk = NULL;
7419 io_done(&io);
7421 return chunk ? TRUE : FALSE;
7424 static bool
7425 stage_update(struct view *view, struct line *line, bool single)
7427 struct line *chunk = NULL;
7429 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
7430 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7432 if (chunk) {
7433 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
7434 report("Failed to apply chunk");
7435 return FALSE;
7438 } else if (!stage_status.status) {
7439 view = view->parent;
7441 for (line = view->line; view_has_line(view, line); line++)
7442 if (line->type == stage_line_type)
7443 break;
7445 if (!status_update_files(view, line + 1)) {
7446 report("Failed to update files");
7447 return FALSE;
7450 } else if (!status_update_file(&stage_status, stage_line_type)) {
7451 report("Failed to update file");
7452 return FALSE;
7455 return TRUE;
7458 static bool
7459 stage_revert(struct view *view, struct line *line)
7461 struct line *chunk = NULL;
7463 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
7464 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7466 if (chunk) {
7467 if (!prompt_yesno("Are you sure you want to revert changes?"))
7468 return FALSE;
7470 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
7471 report("Failed to revert chunk");
7472 return FALSE;
7474 return TRUE;
7476 } else {
7477 return status_revert(stage_status.status ? &stage_status : NULL,
7478 stage_line_type, FALSE);
7483 static void
7484 stage_next(struct view *view, struct line *line)
7486 struct stage_state *state = view->private;
7487 int i;
7489 if (!state->chunks) {
7490 for (line = view->line; view_has_line(view, line); line++) {
7491 if (line->type != LINE_DIFF_CHUNK)
7492 continue;
7494 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
7495 report("Allocation failure");
7496 return;
7499 state->chunk[state->chunks++] = line - view->line;
7503 for (i = 0; i < state->chunks; i++) {
7504 if (state->chunk[i] > view->pos.lineno) {
7505 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
7506 report("Chunk %d of %zd", i + 1, state->chunks);
7507 return;
7511 report("No next chunk found");
7514 static struct line *
7515 stage_insert_chunk(struct view *view, struct chunk_header *header,
7516 struct line *from, struct line *to, struct line *last_unchanged_line)
7518 char buf[SIZEOF_STR];
7519 char *chunk_line;
7520 unsigned long from_lineno = last_unchanged_line - view->line;
7521 unsigned long to_lineno = to - view->line;
7522 unsigned long after_lineno = to_lineno;
7524 if (!string_format(buf, "@@ -%lu,%lu +%lu,%lu @@",
7525 header->old.position, header->old.lines,
7526 header->new.position, header->new.lines))
7527 return NULL;
7529 chunk_line = strdup(buf);
7530 if (!chunk_line)
7531 return NULL;
7533 free(from->data);
7534 from->data = chunk_line;
7536 if (!to)
7537 return from;
7539 if (!add_line_at(view, after_lineno++, buf, LINE_DIFF_CHUNK, strlen(buf) + 1, FALSE))
7540 return NULL;
7542 while (from_lineno < to_lineno) {
7543 struct line *line = &view->line[from_lineno++];
7545 if (!add_line_at(view, after_lineno++, line->data, line->type, strlen(line->data) + 1, FALSE))
7546 return FALSE;
7549 return view->line + after_lineno;
7552 static void
7553 stage_split_chunk(struct view *view, struct line *chunk_start)
7555 struct chunk_header header;
7556 struct line *last_changed_line = NULL, *last_unchanged_line = NULL, *pos;
7557 int chunks = 0;
7559 if (!chunk_start || !parse_chunk_header(&header, chunk_start->data)) {
7560 report("Failed to parse chunk header");
7561 return;
7564 header.old.lines = header.new.lines = 0;
7566 for (pos = chunk_start + 1; view_has_line(view, pos); pos++) {
7567 const char *chunk_line = pos->data;
7569 if (*chunk_line == '@' || *chunk_line == '\\')
7570 break;
7572 if (*chunk_line == ' ') {
7573 header.old.lines++;
7574 header.new.lines++;
7575 if (last_unchanged_line < last_changed_line)
7576 last_unchanged_line = pos;
7577 continue;
7580 if (last_changed_line && last_changed_line < last_unchanged_line) {
7581 unsigned long chunk_start_lineno = pos - view->line;
7582 unsigned long diff = pos - last_unchanged_line;
7584 pos = stage_insert_chunk(view, &header, chunk_start, pos, last_unchanged_line);
7586 header.old.position += header.old.lines - diff;
7587 header.new.position += header.new.lines - diff;
7588 header.old.lines = header.new.lines = diff;
7590 chunk_start = view->line + chunk_start_lineno;
7591 last_changed_line = last_unchanged_line = NULL;
7592 chunks++;
7595 if (*chunk_line == '-') {
7596 header.old.lines++;
7597 last_changed_line = pos;
7598 } else if (*chunk_line == '+') {
7599 header.new.lines++;
7600 last_changed_line = pos;
7604 if (chunks) {
7605 stage_insert_chunk(view, &header, chunk_start, NULL, NULL);
7606 redraw_view(view);
7607 report("Split the chunk in %d", chunks + 1);
7608 } else {
7609 report("The chunk cannot be split");
7613 static enum request
7614 stage_request(struct view *view, enum request request, struct line *line)
7616 switch (request) {
7617 case REQ_STATUS_UPDATE:
7618 if (!stage_update(view, line, FALSE))
7619 return REQ_NONE;
7620 break;
7622 case REQ_STATUS_REVERT:
7623 if (!stage_revert(view, line))
7624 return REQ_NONE;
7625 break;
7627 case REQ_STAGE_UPDATE_LINE:
7628 if (stage_line_type == LINE_STAT_UNTRACKED ||
7629 stage_status.status == 'A') {
7630 report("Staging single lines is not supported for new files");
7631 return REQ_NONE;
7633 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
7634 report("Please select a change to stage");
7635 return REQ_NONE;
7637 if (!stage_update(view, line, TRUE))
7638 return REQ_NONE;
7639 break;
7641 case REQ_STAGE_NEXT:
7642 if (stage_line_type == LINE_STAT_UNTRACKED) {
7643 report("File is untracked; press %s to add",
7644 get_view_key(view, REQ_STATUS_UPDATE));
7645 return REQ_NONE;
7647 stage_next(view, line);
7648 return REQ_NONE;
7650 case REQ_STAGE_SPLIT_CHUNK:
7651 if (stage_line_type == LINE_STAT_UNTRACKED ||
7652 !(line = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK))) {
7653 report("No chunks to split in sight");
7654 return REQ_NONE;
7656 stage_split_chunk(view, line);
7657 return REQ_NONE;
7659 case REQ_EDIT:
7660 if (!stage_status.new.name[0])
7661 return diff_common_edit(view, request, line);
7663 if (stage_status.status == 'D') {
7664 report("File has been deleted.");
7665 return REQ_NONE;
7668 if (stage_line_type == LINE_STAT_UNTRACKED) {
7669 open_editor(stage_status.new.name, (line - view->line) + 1);
7670 } else {
7671 open_editor(stage_status.new.name, diff_get_lineno(view, line));
7673 break;
7675 case REQ_REFRESH:
7676 /* Reload everything(including current branch information) ... */
7677 load_refs(TRUE);
7678 break;
7680 case REQ_VIEW_BLAME:
7681 if (stage_status.new.name[0]) {
7682 string_copy(opt_file, stage_status.new.name);
7683 opt_ref[0] = 0;
7685 return request;
7687 case REQ_ENTER:
7688 return diff_common_enter(view, request, line);
7690 case REQ_DIFF_CONTEXT_UP:
7691 case REQ_DIFF_CONTEXT_DOWN:
7692 if (!update_diff_context(request))
7693 return REQ_NONE;
7694 break;
7696 default:
7697 return request;
7700 refresh_view(view->parent);
7702 /* Check whether the staged entry still exists, and close the
7703 * stage view if it doesn't. */
7704 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
7705 status_restore(view->parent);
7706 return REQ_VIEW_CLOSE;
7709 refresh_view(view);
7711 return REQ_NONE;
7714 static bool
7715 stage_open(struct view *view, enum open_flags flags)
7717 static const char *no_head_diff_argv[] = {
7718 GIT_DIFF_STAGED_INITIAL(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7719 stage_status.new.name)
7721 static const char *index_show_argv[] = {
7722 GIT_DIFF_STAGED(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7723 stage_status.old.name, stage_status.new.name)
7725 static const char *files_show_argv[] = {
7726 GIT_DIFF_UNSTAGED(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7727 stage_status.old.name, stage_status.new.name)
7729 /* Diffs for unmerged entries are empty when passing the new
7730 * path, so leave out the new path. */
7731 static const char *files_unmerged_argv[] = {
7732 "git", "diff-files", encoding_arg, "--root", "--patch-with-stat",
7733 opt_diff_context_arg, opt_ignore_space_arg, "--",
7734 stage_status.old.name, NULL
7736 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
7737 const char **argv = NULL;
7739 if (!stage_line_type) {
7740 report("No stage content, press %s to open the status view and choose file",
7741 get_view_key(view, REQ_VIEW_STATUS));
7742 return FALSE;
7745 view->encoding = NULL;
7747 switch (stage_line_type) {
7748 case LINE_STAT_STAGED:
7749 if (is_initial_commit()) {
7750 argv = no_head_diff_argv;
7751 } else {
7752 argv = index_show_argv;
7754 break;
7756 case LINE_STAT_UNSTAGED:
7757 if (stage_status.status != 'U')
7758 argv = files_show_argv;
7759 else
7760 argv = files_unmerged_argv;
7761 break;
7763 case LINE_STAT_UNTRACKED:
7764 argv = file_argv;
7765 view->encoding = get_path_encoding(stage_status.old.name, default_encoding);
7766 break;
7768 case LINE_STAT_HEAD:
7769 default:
7770 die("line type %d not handled in switch", stage_line_type);
7773 if (!status_stage_info(view->ref, stage_line_type, &stage_status)
7774 || !argv_copy(&view->argv, argv)) {
7775 report("Failed to open staged view");
7776 return FALSE;
7779 view->vid[0] = 0;
7780 view->dir = opt_cdup;
7781 return begin_update(view, NULL, NULL, flags);
7784 static bool
7785 stage_read(struct view *view, char *data)
7787 struct stage_state *state = view->private;
7789 if (stage_line_type == LINE_STAT_UNTRACKED)
7790 return pager_common_read(view, data, LINE_DEFAULT);
7792 if (data && diff_common_read(view, data, &state->diff))
7793 return TRUE;
7795 return pager_read(view, data);
7798 static struct view_ops stage_ops = {
7799 "line",
7800 { "stage" },
7801 VIEW_DIFF_LIKE,
7802 sizeof(struct stage_state),
7803 stage_open,
7804 stage_read,
7805 diff_common_draw,
7806 stage_request,
7807 pager_grep,
7808 pager_select,
7813 * Revision graph
7816 static const enum line_type graph_colors[] = {
7817 LINE_PALETTE_0,
7818 LINE_PALETTE_1,
7819 LINE_PALETTE_2,
7820 LINE_PALETTE_3,
7821 LINE_PALETTE_4,
7822 LINE_PALETTE_5,
7823 LINE_PALETTE_6,
7826 static enum line_type get_graph_color(struct graph_symbol *symbol)
7828 if (symbol->commit)
7829 return LINE_GRAPH_COMMIT;
7830 assert(symbol->color < ARRAY_SIZE(graph_colors));
7831 return graph_colors[symbol->color];
7834 static bool
7835 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7837 const char *chars = graph_symbol_to_utf8(symbol);
7839 return draw_text(view, color, chars + !!first);
7842 static bool
7843 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7845 const char *chars = graph_symbol_to_ascii(symbol);
7847 return draw_text(view, color, chars + !!first);
7850 static bool
7851 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7853 const chtype *chars = graph_symbol_to_chtype(symbol);
7855 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
7858 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
7860 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
7862 static const draw_graph_fn fns[] = {
7863 draw_graph_ascii,
7864 draw_graph_chtype,
7865 draw_graph_utf8
7867 draw_graph_fn fn = fns[opt_line_graphics];
7868 int i;
7870 for (i = 0; i < canvas->size; i++) {
7871 struct graph_symbol *symbol = &canvas->symbols[i];
7872 enum line_type color = get_graph_color(symbol);
7874 if (fn(view, symbol, color, i == 0))
7875 return TRUE;
7878 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
7882 * Main view backend
7885 DEFINE_ALLOCATOR(realloc_reflogs, char *, 32)
7887 struct commit {
7888 char id[SIZEOF_REV]; /* SHA1 ID. */
7889 const struct ident *author; /* Author of the commit. */
7890 struct time time; /* Date from the author ident. */
7891 struct graph_canvas graph; /* Ancestry chain graphics. */
7892 char title[1]; /* First line of the commit message. */
7895 struct main_state {
7896 struct graph graph;
7897 struct commit current;
7898 char **reflog;
7899 size_t reflogs;
7900 int reflog_width;
7901 char reflogmsg[SIZEOF_STR / 2];
7902 bool in_header;
7903 bool added_changes_commits;
7904 bool with_graph;
7907 static void
7908 main_register_commit(struct view *view, struct commit *commit, const char *ids, bool is_boundary)
7910 struct main_state *state = view->private;
7912 string_copy_rev(commit->id, ids);
7913 if (state->with_graph)
7914 graph_add_commit(&state->graph, &commit->graph, commit->id, ids, is_boundary);
7917 static struct commit *
7918 main_add_commit(struct view *view, enum line_type type, struct commit *template,
7919 const char *title, bool custom)
7921 struct main_state *state = view->private;
7922 size_t titlelen = strlen(title);
7923 struct commit *commit;
7924 char buf[SIZEOF_STR / 2];
7926 /* FIXME: More graceful handling of titles; append "..." to
7927 * shortened titles, etc. */
7928 string_expand(buf, sizeof(buf), title, 1);
7929 title = buf;
7930 titlelen = strlen(title);
7932 if (!add_line_alloc(view, &commit, type, titlelen, custom))
7933 return NULL;
7935 *commit = *template;
7936 strncpy(commit->title, title, titlelen);
7937 state->graph.canvas = &commit->graph;
7938 memset(template, 0, sizeof(*template));
7939 state->reflogmsg[0] = 0;
7940 return commit;
7943 static inline void
7944 main_flush_commit(struct view *view, struct commit *commit)
7946 if (*commit->id)
7947 main_add_commit(view, LINE_MAIN_COMMIT, commit, "", FALSE);
7950 static bool
7951 main_has_changes(const char *argv[])
7953 struct io io;
7955 if (!io_run(&io, IO_BG, NULL, opt_env, argv, -1))
7956 return FALSE;
7957 io_done(&io);
7958 return io.status == 1;
7961 static void
7962 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
7964 char ids[SIZEOF_STR] = NULL_ID " ";
7965 struct main_state *state = view->private;
7966 struct commit commit = {};
7967 struct timeval now;
7968 struct timezone tz;
7970 if (!parent)
7971 return;
7973 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
7975 if (!gettimeofday(&now, &tz)) {
7976 commit.time.tz = tz.tz_minuteswest * 60;
7977 commit.time.sec = now.tv_sec - commit.time.tz;
7980 commit.author = &unknown_ident;
7981 main_register_commit(view, &commit, ids, FALSE);
7982 if (main_add_commit(view, type, &commit, title, TRUE) && state->with_graph)
7983 graph_render_parents(&state->graph);
7986 static void
7987 main_add_changes_commits(struct view *view, struct main_state *state, const char *parent)
7989 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
7990 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
7991 const char *staged_parent = NULL_ID;
7992 const char *unstaged_parent = parent;
7994 if (!is_head_commit(parent))
7995 return;
7997 state->added_changes_commits = TRUE;
7999 io_run_bg(update_index_argv);
8001 if (!main_has_changes(unstaged_argv)) {
8002 unstaged_parent = NULL;
8003 staged_parent = parent;
8006 if (!main_has_changes(staged_argv)) {
8007 staged_parent = NULL;
8010 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
8011 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
8014 static bool
8015 main_open(struct view *view, enum open_flags flags)
8017 static const char *main_argv[] = {
8018 GIT_MAIN_LOG(encoding_arg, "%(diffargs)", "%(revargs)", "%(fileargs)")
8020 struct main_state *state = view->private;
8022 state->with_graph = opt_rev_graph;
8024 if (flags & OPEN_PAGER_MODE) {
8025 state->added_changes_commits = TRUE;
8026 state->with_graph = FALSE;
8029 return begin_update(view, NULL, main_argv, flags);
8032 static void
8033 main_done(struct view *view)
8035 struct main_state *state = view->private;
8036 int i;
8038 for (i = 0; i < view->lines; i++) {
8039 struct commit *commit = view->line[i].data;
8041 free(commit->graph.symbols);
8044 for (i = 0; i < state->reflogs; i++)
8045 free(state->reflog[i]);
8046 free(state->reflog);
8049 #define MAIN_NO_COMMIT_REFS 1
8050 #define main_check_commit_refs(line) !((line)->user_flags & MAIN_NO_COMMIT_REFS)
8051 #define main_mark_no_commit_refs(line) ((line)->user_flags |= MAIN_NO_COMMIT_REFS)
8053 static inline struct ref_list *
8054 main_get_commit_refs(struct line *line, struct commit *commit)
8056 struct ref_list *refs = NULL;
8058 if (main_check_commit_refs(line) && !(refs = get_ref_list(commit->id)))
8059 main_mark_no_commit_refs(line);
8061 return refs;
8064 static bool
8065 main_draw(struct view *view, struct line *line, unsigned int lineno)
8067 struct main_state *state = view->private;
8068 struct commit *commit = line->data;
8069 struct ref_list *refs = NULL;
8071 if (!commit->author)
8072 return FALSE;
8074 if (draw_lineno(view, lineno))
8075 return TRUE;
8077 if (opt_show_id) {
8078 if (state->reflogs) {
8079 const char *id = state->reflog[line->lineno - 1];
8081 if (draw_id_custom(view, LINE_ID, id, state->reflog_width))
8082 return TRUE;
8083 } else if (draw_id(view, commit->id)) {
8084 return TRUE;
8088 if (draw_date(view, &commit->time))
8089 return TRUE;
8091 if (draw_author(view, commit->author))
8092 return TRUE;
8094 if (state->with_graph && draw_graph(view, &commit->graph))
8095 return TRUE;
8097 if ((refs = main_get_commit_refs(line, commit)) && draw_refs(view, refs))
8098 return TRUE;
8100 if (commit->title)
8101 draw_commit_title(view, commit->title, 0);
8102 return TRUE;
8105 static bool
8106 main_add_reflog(struct view *view, struct main_state *state, char *reflog)
8108 char *end = strchr(reflog, ' ');
8109 int id_width;
8111 if (!end)
8112 return FALSE;
8113 *end = 0;
8115 if (!realloc_reflogs(&state->reflog, state->reflogs, 1)
8116 || !(reflog = strdup(reflog)))
8117 return FALSE;
8119 state->reflog[state->reflogs++] = reflog;
8120 id_width = strlen(reflog);
8121 if (state->reflog_width < id_width) {
8122 state->reflog_width = id_width;
8123 if (opt_show_id)
8124 view->force_redraw = TRUE;
8127 return TRUE;
8130 /* Reads git log --pretty=raw output and parses it into the commit struct. */
8131 static bool
8132 main_read(struct view *view, char *line)
8134 struct main_state *state = view->private;
8135 struct graph *graph = &state->graph;
8136 enum line_type type;
8137 struct commit *commit = &state->current;
8139 if (!line) {
8140 main_flush_commit(view, commit);
8142 if (!view->lines && !view->prev)
8143 die("No revisions match the given arguments.");
8144 if (view->lines > 0) {
8145 struct commit *last = view->line[view->lines - 1].data;
8147 view->line[view->lines - 1].dirty = 1;
8148 if (!last->author) {
8149 view->lines--;
8150 free(last);
8154 if (state->with_graph)
8155 done_graph(graph);
8156 return TRUE;
8159 type = get_line_type(line);
8160 if (type == LINE_COMMIT) {
8161 bool is_boundary;
8163 state->in_header = TRUE;
8164 line += STRING_SIZE("commit ");
8165 is_boundary = *line == '-';
8166 if (is_boundary || !isalnum(*line))
8167 line++;
8169 if (!state->added_changes_commits && opt_show_changes && opt_is_inside_work_tree)
8170 main_add_changes_commits(view, state, line);
8171 else
8172 main_flush_commit(view, commit);
8174 main_register_commit(view, &state->current, line, is_boundary);
8175 return TRUE;
8178 if (!*commit->id)
8179 return TRUE;
8181 /* Empty line separates the commit header from the log itself. */
8182 if (*line == '\0')
8183 state->in_header = FALSE;
8185 switch (type) {
8186 case LINE_PP_REFLOG:
8187 if (!main_add_reflog(view, state, line + STRING_SIZE("Reflog: ")))
8188 return FALSE;
8189 break;
8191 case LINE_PP_REFLOGMSG:
8192 line += STRING_SIZE("Reflog message: ");
8193 string_ncopy(state->reflogmsg, line, strlen(line));
8194 break;
8196 case LINE_PARENT:
8197 if (state->with_graph && !graph->has_parents)
8198 graph_add_parent(graph, line + STRING_SIZE("parent "));
8199 break;
8201 case LINE_AUTHOR:
8202 parse_author_line(line + STRING_SIZE("author "),
8203 &commit->author, &commit->time);
8204 if (state->with_graph)
8205 graph_render_parents(graph);
8206 break;
8208 default:
8209 /* Fill in the commit title if it has not already been set. */
8210 if (*commit->title)
8211 break;
8213 /* Skip lines in the commit header. */
8214 if (state->in_header)
8215 break;
8217 /* Require titles to start with a non-space character at the
8218 * offset used by git log. */
8219 if (strncmp(line, " ", 4))
8220 break;
8221 line += 4;
8222 /* Well, if the title starts with a whitespace character,
8223 * try to be forgiving. Otherwise we end up with no title. */
8224 while (isspace(*line))
8225 line++;
8226 if (*line == '\0')
8227 break;
8228 if (*state->reflogmsg)
8229 line = state->reflogmsg;
8230 main_add_commit(view, LINE_MAIN_COMMIT, commit, line, FALSE);
8233 return TRUE;
8236 static enum request
8237 main_request(struct view *view, enum request request, struct line *line)
8239 enum open_flags flags = (view_is_displayed(view) && request != REQ_VIEW_DIFF)
8240 ? OPEN_SPLIT : OPEN_DEFAULT;
8242 switch (request) {
8243 case REQ_NEXT:
8244 case REQ_PREVIOUS:
8245 if (view_is_displayed(view) && display[0] != view)
8246 return request;
8247 /* Do not pass navigation requests to the branch view
8248 * when the main view is maximized. (GH #38) */
8249 return request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
8251 case REQ_VIEW_DIFF:
8252 case REQ_ENTER:
8253 if (view_is_displayed(view) && display[0] != view)
8254 maximize_view(view, TRUE);
8256 if (line->type == LINE_STAT_UNSTAGED
8257 || line->type == LINE_STAT_STAGED) {
8258 struct view *diff = VIEW(REQ_VIEW_DIFF);
8259 const char *diff_staged_argv[] = {
8260 GIT_DIFF_STAGED(encoding_arg,
8261 opt_diff_context_arg,
8262 opt_ignore_space_arg, NULL, NULL)
8264 const char *diff_unstaged_argv[] = {
8265 GIT_DIFF_UNSTAGED(encoding_arg,
8266 opt_diff_context_arg,
8267 opt_ignore_space_arg, NULL, NULL)
8269 const char **diff_argv = line->type == LINE_STAT_STAGED
8270 ? diff_staged_argv : diff_unstaged_argv;
8272 open_argv(view, diff, diff_argv, NULL, flags);
8273 break;
8276 open_view(view, REQ_VIEW_DIFF, flags);
8277 break;
8279 case REQ_REFRESH:
8280 load_refs(TRUE);
8281 refresh_view(view);
8282 break;
8284 case REQ_JUMP_COMMIT:
8286 int lineno;
8288 for (lineno = 0; lineno < view->lines; lineno++) {
8289 struct commit *commit = view->line[lineno].data;
8291 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
8292 select_view_line(view, lineno);
8293 report_clear();
8294 return REQ_NONE;
8298 report("Unable to find commit '%s'", opt_search);
8299 break;
8301 default:
8302 return request;
8305 return REQ_NONE;
8308 static bool
8309 grep_refs(struct line *line, struct commit *commit, regex_t *regex)
8311 struct ref_list *list;
8312 regmatch_t pmatch;
8313 size_t i;
8315 if (!opt_show_refs || !(list = main_get_commit_refs(line, commit)))
8316 return FALSE;
8318 for (i = 0; i < list->size; i++) {
8319 if (!regexec(regex, list->refs[i]->name, 1, &pmatch, 0))
8320 return TRUE;
8323 return FALSE;
8326 static bool
8327 main_grep(struct view *view, struct line *line)
8329 struct commit *commit = line->data;
8330 const char *text[] = {
8331 commit->id,
8332 commit->title,
8333 mkauthor(commit->author, opt_author_width, opt_author),
8334 mkdate(&commit->time, opt_date),
8335 NULL
8338 return grep_text(view, text) || grep_refs(line, commit, view->regex);
8341 static void
8342 main_select(struct view *view, struct line *line)
8344 struct commit *commit = line->data;
8346 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED)
8347 string_ncopy(view->ref, commit->title, strlen(commit->title));
8348 else
8349 string_copy_rev(view->ref, commit->id);
8350 string_copy_rev(ref_commit, commit->id);
8353 static struct view_ops main_ops = {
8354 "commit",
8355 { "main" },
8356 VIEW_SEND_CHILD_ENTER | VIEW_FILE_FILTER | VIEW_LOG_LIKE,
8357 sizeof(struct main_state),
8358 main_open,
8359 main_read,
8360 main_draw,
8361 main_request,
8362 main_grep,
8363 main_select,
8364 main_done,
8367 static bool
8368 stash_open(struct view *view, enum open_flags flags)
8370 static const char *stash_argv[] = { "git", "stash", "list",
8371 encoding_arg, "--no-color", "--pretty=raw", NULL };
8372 struct main_state *state = view->private;
8374 state->added_changes_commits = TRUE;
8375 state->with_graph = FALSE;
8376 return begin_update(view, NULL, stash_argv, flags | OPEN_RELOAD);
8379 static void
8380 stash_select(struct view *view, struct line *line)
8382 main_select(view, line);
8383 string_format(ref_stash, "stash@{%d}", line->lineno - 1);
8384 string_copy(view->ref, ref_stash);
8387 static struct view_ops stash_ops = {
8388 "stash",
8389 { "stash" },
8390 VIEW_SEND_CHILD_ENTER,
8391 sizeof(struct main_state),
8392 stash_open,
8393 main_read,
8394 main_draw,
8395 main_request,
8396 main_grep,
8397 stash_select,
8401 * Status management
8404 /* Whether or not the curses interface has been initialized. */
8405 static bool cursed = FALSE;
8407 /* Terminal hacks and workarounds. */
8408 static bool use_scroll_redrawwin;
8409 static bool use_scroll_status_wclear;
8411 /* The status window is used for polling keystrokes. */
8412 static WINDOW *status_win;
8414 /* Reading from the prompt? */
8415 static bool input_mode = FALSE;
8417 static bool status_empty = FALSE;
8419 /* Update status and title window. */
8420 static void
8421 report(const char *msg, ...)
8423 struct view *view = display[current_view];
8425 if (input_mode)
8426 return;
8428 if (!view) {
8429 char buf[SIZEOF_STR];
8430 int retval;
8432 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
8433 die("%s", buf);
8436 if (!status_empty || *msg) {
8437 va_list args;
8439 va_start(args, msg);
8441 wmove(status_win, 0, 0);
8442 if (view->has_scrolled && use_scroll_status_wclear)
8443 wclear(status_win);
8444 if (*msg) {
8445 vwprintw(status_win, msg, args);
8446 status_empty = FALSE;
8447 } else {
8448 status_empty = TRUE;
8450 wclrtoeol(status_win);
8451 wnoutrefresh(status_win);
8453 va_end(args);
8456 update_view_title(view);
8459 static void
8460 done_display(void)
8462 endwin();
8465 static void
8466 init_display(void)
8468 const char *term;
8469 int x, y;
8471 die_callback = done_display;
8473 /* Initialize the curses library */
8474 if (isatty(STDIN_FILENO)) {
8475 cursed = !!initscr();
8476 opt_tty = stdin;
8477 } else {
8478 /* Leave stdin and stdout alone when acting as a pager. */
8479 opt_tty = fopen("/dev/tty", "r+");
8480 if (!opt_tty)
8481 die("Failed to open /dev/tty");
8482 cursed = !!newterm(NULL, opt_tty, opt_tty);
8485 if (!cursed)
8486 die("Failed to initialize curses");
8488 nonl(); /* Disable conversion and detect newlines from input. */
8489 cbreak(); /* Take input chars one at a time, no wait for \n */
8490 noecho(); /* Don't echo input */
8491 leaveok(stdscr, FALSE);
8493 if (has_colors())
8494 init_colors();
8496 getmaxyx(stdscr, y, x);
8497 status_win = newwin(1, x, y - 1, 0);
8498 if (!status_win)
8499 die("Failed to create status window");
8501 /* Enable keyboard mapping */
8502 keypad(status_win, TRUE);
8503 wbkgdset(status_win, get_line_attr(LINE_STATUS));
8505 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
8506 set_tabsize(opt_tab_size);
8507 #else
8508 TABSIZE = opt_tab_size;
8509 #endif
8511 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
8512 if (term && !strcmp(term, "gnome-terminal")) {
8513 /* In the gnome-terminal-emulator, the message from
8514 * scrolling up one line when impossible followed by
8515 * scrolling down one line causes corruption of the
8516 * status line. This is fixed by calling wclear. */
8517 use_scroll_status_wclear = TRUE;
8518 use_scroll_redrawwin = FALSE;
8520 } else if (term && !strcmp(term, "xrvt-xpm")) {
8521 /* No problems with full optimizations in xrvt-(unicode)
8522 * and aterm. */
8523 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
8525 } else {
8526 /* When scrolling in (u)xterm the last line in the
8527 * scrolling direction will update slowly. */
8528 use_scroll_redrawwin = TRUE;
8529 use_scroll_status_wclear = FALSE;
8533 static int
8534 get_input(int prompt_position)
8536 struct view *view;
8537 int i, key, cursor_y, cursor_x;
8539 if (prompt_position)
8540 input_mode = TRUE;
8542 while (TRUE) {
8543 bool loading = FALSE;
8545 foreach_view (view, i) {
8546 update_view(view);
8547 if (view_is_displayed(view) && view->has_scrolled &&
8548 use_scroll_redrawwin)
8549 redrawwin(view->win);
8550 view->has_scrolled = FALSE;
8551 if (view->pipe)
8552 loading = TRUE;
8555 /* Update the cursor position. */
8556 if (prompt_position) {
8557 getbegyx(status_win, cursor_y, cursor_x);
8558 cursor_x = prompt_position;
8559 } else {
8560 view = display[current_view];
8561 getbegyx(view->win, cursor_y, cursor_x);
8562 cursor_x = view->width - 1;
8563 cursor_y += view->pos.lineno - view->pos.offset;
8565 setsyx(cursor_y, cursor_x);
8567 /* Refresh, accept single keystroke of input */
8568 doupdate();
8569 nodelay(status_win, loading);
8570 key = wgetch(status_win);
8572 /* wgetch() with nodelay() enabled returns ERR when
8573 * there's no input. */
8574 if (key == ERR) {
8576 } else if (key == KEY_RESIZE) {
8577 int height, width;
8579 getmaxyx(stdscr, height, width);
8581 wresize(status_win, 1, width);
8582 mvwin(status_win, height - 1, 0);
8583 wnoutrefresh(status_win);
8584 resize_display();
8585 redraw_display(TRUE);
8587 } else {
8588 input_mode = FALSE;
8589 if (key == erasechar())
8590 key = KEY_BACKSPACE;
8591 return key;
8596 static char *
8597 prompt_input(const char *prompt, input_handler handler, void *data)
8599 enum input_status status = INPUT_OK;
8600 static char buf[SIZEOF_STR];
8601 size_t pos = 0;
8603 buf[pos] = 0;
8605 while (status == INPUT_OK || status == INPUT_SKIP) {
8606 int key;
8608 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
8609 wclrtoeol(status_win);
8611 key = get_input(pos + 1);
8612 switch (key) {
8613 case KEY_RETURN:
8614 case KEY_ENTER:
8615 case '\n':
8616 status = pos ? INPUT_STOP : INPUT_CANCEL;
8617 break;
8619 case KEY_BACKSPACE:
8620 if (pos > 0)
8621 buf[--pos] = 0;
8622 else
8623 status = INPUT_CANCEL;
8624 break;
8626 case KEY_ESC:
8627 status = INPUT_CANCEL;
8628 break;
8630 default:
8631 if (pos >= sizeof(buf)) {
8632 report("Input string too long");
8633 return NULL;
8636 status = handler(data, buf, key);
8637 if (status == INPUT_OK)
8638 buf[pos++] = (char) key;
8642 /* Clear the status window */
8643 status_empty = FALSE;
8644 report_clear();
8646 if (status == INPUT_CANCEL)
8647 return NULL;
8649 buf[pos++] = 0;
8651 return buf;
8654 static enum input_status
8655 prompt_yesno_handler(void *data, char *buf, int c)
8657 if (c == 'y' || c == 'Y')
8658 return INPUT_STOP;
8659 if (c == 'n' || c == 'N')
8660 return INPUT_CANCEL;
8661 return INPUT_SKIP;
8664 static bool
8665 prompt_yesno(const char *prompt)
8667 char prompt2[SIZEOF_STR];
8669 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
8670 return FALSE;
8672 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
8675 static enum input_status
8676 read_prompt_handler(void *data, char *buf, int c)
8678 return isprint(c) ? INPUT_OK : INPUT_SKIP;
8681 static char *
8682 read_prompt(const char *prompt)
8684 return prompt_input(prompt, read_prompt_handler, NULL);
8687 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
8689 enum input_status status = INPUT_OK;
8690 int size = 0;
8692 while (items[size].text)
8693 size++;
8695 assert(size > 0);
8697 while (status == INPUT_OK) {
8698 const struct menu_item *item = &items[*selected];
8699 int key;
8700 int i;
8702 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
8703 prompt, *selected + 1, size);
8704 if (item->hotkey)
8705 wprintw(status_win, "[%c] ", (char) item->hotkey);
8706 wprintw(status_win, "%s", item->text);
8707 wclrtoeol(status_win);
8709 key = get_input(COLS - 1);
8710 switch (key) {
8711 case KEY_RETURN:
8712 case KEY_ENTER:
8713 case '\n':
8714 status = INPUT_STOP;
8715 break;
8717 case KEY_LEFT:
8718 case KEY_UP:
8719 *selected = *selected - 1;
8720 if (*selected < 0)
8721 *selected = size - 1;
8722 break;
8724 case KEY_RIGHT:
8725 case KEY_DOWN:
8726 *selected = (*selected + 1) % size;
8727 break;
8729 case KEY_ESC:
8730 status = INPUT_CANCEL;
8731 break;
8733 default:
8734 for (i = 0; items[i].text; i++)
8735 if (items[i].hotkey == key) {
8736 *selected = i;
8737 status = INPUT_STOP;
8738 break;
8743 /* Clear the status window */
8744 status_empty = FALSE;
8745 report_clear();
8747 return status != INPUT_CANCEL;
8751 * Repository properties
8755 static void
8756 set_remote_branch(const char *name, const char *value, size_t valuelen)
8758 if (!strcmp(name, ".remote")) {
8759 string_ncopy(opt_remote, value, valuelen);
8761 } else if (*opt_remote && !strcmp(name, ".merge")) {
8762 size_t from = strlen(opt_remote);
8764 if (!prefixcmp(value, "refs/heads/"))
8765 value += STRING_SIZE("refs/heads/");
8767 if (!string_format_from(opt_remote, &from, "/%s", value))
8768 opt_remote[0] = 0;
8772 static void
8773 set_repo_config_option(char *name, char *value, enum status_code (*cmd)(int, const char **))
8775 const char *argv[SIZEOF_ARG] = { name, "=" };
8776 int argc = 1 + (cmd == option_set_command);
8777 enum status_code error;
8779 if (!argv_from_string(argv, &argc, value))
8780 error = ERROR_TOO_MANY_OPTION_ARGUMENTS;
8781 else
8782 error = cmd(argc, argv);
8784 if (error != SUCCESS)
8785 warn("Option 'tig.%s': %s", name, get_status_message(error));
8788 static void
8789 set_work_tree(const char *value)
8791 char cwd[SIZEOF_STR];
8793 if (!getcwd(cwd, sizeof(cwd)))
8794 die("Failed to get cwd path: %s", strerror(errno));
8795 if (chdir(cwd) < 0)
8796 die("Failed to chdir(%s): %s", cwd, strerror(errno));
8797 if (chdir(opt_git_dir) < 0)
8798 die("Failed to chdir(%s): %s", opt_git_dir, strerror(errno));
8799 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
8800 die("Failed to get git path: %s", strerror(errno));
8801 if (chdir(value) < 0)
8802 die("Failed to chdir(%s): %s", value, strerror(errno));
8803 if (!getcwd(cwd, sizeof(cwd)))
8804 die("Failed to get cwd path: %s", strerror(errno));
8805 if (setenv("GIT_WORK_TREE", cwd, TRUE))
8806 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
8807 if (setenv("GIT_DIR", opt_git_dir, TRUE))
8808 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
8809 opt_is_inside_work_tree = TRUE;
8812 static void
8813 parse_git_color_option(enum line_type type, char *value)
8815 struct line_info *info = &line_info[type];
8816 const char *argv[SIZEOF_ARG];
8817 int argc = 0;
8818 bool first_color = TRUE;
8819 int i;
8821 if (!argv_from_string(argv, &argc, value))
8822 return;
8824 info->fg = COLOR_DEFAULT;
8825 info->bg = COLOR_DEFAULT;
8826 info->attr = 0;
8828 for (i = 0; i < argc; i++) {
8829 int attr = 0;
8831 if (set_attribute(&attr, argv[i])) {
8832 info->attr |= attr;
8834 } else if (set_color(&attr, argv[i])) {
8835 if (first_color)
8836 info->fg = attr;
8837 else
8838 info->bg = attr;
8839 first_color = FALSE;
8844 static void
8845 set_git_color_option(const char *name, char *value)
8847 static const struct enum_map color_option_map[] = {
8848 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
8849 ENUM_MAP("branch.local", LINE_MAIN_REF),
8850 ENUM_MAP("branch.plain", LINE_MAIN_REF),
8851 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
8853 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
8854 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
8855 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
8856 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
8857 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
8858 ENUM_MAP("diff.old", LINE_DIFF_DEL),
8859 ENUM_MAP("diff.new", LINE_DIFF_ADD),
8861 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
8863 ENUM_MAP("status.branch", LINE_STAT_HEAD),
8864 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
8865 ENUM_MAP("status.added", LINE_STAT_STAGED),
8866 ENUM_MAP("status.updated", LINE_STAT_STAGED),
8867 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
8868 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
8871 int type = LINE_NONE;
8873 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
8874 parse_git_color_option(type, value);
8878 static void
8879 set_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
8881 if (parse_encoding(encoding_ref, arg, priority) == SUCCESS)
8882 encoding_arg[0] = 0;
8885 static int
8886 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8888 if (!strcmp(name, "i18n.commitencoding"))
8889 set_encoding(&default_encoding, value, FALSE);
8891 else if (!strcmp(name, "gui.encoding"))
8892 set_encoding(&default_encoding, value, TRUE);
8894 else if (!strcmp(name, "core.editor"))
8895 string_ncopy(opt_editor, value, valuelen);
8897 else if (!strcmp(name, "core.worktree"))
8898 set_work_tree(value);
8900 else if (!strcmp(name, "core.abbrev"))
8901 parse_id(&opt_id_cols, value);
8903 else if (!prefixcmp(name, "tig.color."))
8904 set_repo_config_option(name + 10, value, option_color_command);
8906 else if (!prefixcmp(name, "tig.bind."))
8907 set_repo_config_option(name + 9, value, option_bind_command);
8909 else if (!prefixcmp(name, "tig."))
8910 set_repo_config_option(name + 4, value, option_set_command);
8912 else if (!prefixcmp(name, "color."))
8913 set_git_color_option(name + STRING_SIZE("color."), value);
8915 else if (*opt_head && !prefixcmp(name, "branch.") &&
8916 !strncmp(name + 7, opt_head, strlen(opt_head)))
8917 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
8919 return OK;
8922 static int
8923 load_git_config(void)
8925 const char *config_list_argv[] = { "git", "config", "--list", NULL };
8927 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
8930 #define REPO_INFO_GIT_DIR "--git-dir"
8931 #define REPO_INFO_WORK_TREE "--is-inside-work-tree"
8932 #define REPO_INFO_SHOW_CDUP "--show-cdup"
8933 #define REPO_INFO_SHOW_PREFIX "--show-prefix"
8934 #define REPO_INFO_SYMBOLIC_HEAD "--symbolic-full-name"
8935 #define REPO_INFO_RESOLVED_HEAD "HEAD"
8937 struct repo_info_state {
8938 const char **argv;
8939 char head_id[SIZEOF_REV];
8942 static int
8943 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8945 struct repo_info_state *state = data;
8946 const char *arg = *state->argv ? *state->argv++ : "";
8948 if (!strcmp(arg, REPO_INFO_GIT_DIR)) {
8949 string_ncopy(opt_git_dir, name, namelen);
8951 } else if (!strcmp(arg, REPO_INFO_WORK_TREE)) {
8952 /* This can be 3 different values depending on the
8953 * version of git being used. If git-rev-parse does not
8954 * understand --is-inside-work-tree it will simply echo
8955 * the option else either "true" or "false" is printed.
8956 * Default to true for the unknown case. */
8957 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
8959 } else if (!strcmp(arg, REPO_INFO_SHOW_CDUP)) {
8960 string_ncopy(opt_cdup, name, namelen);
8962 } else if (!strcmp(arg, REPO_INFO_SHOW_PREFIX)) {
8963 string_ncopy(opt_prefix, name, namelen);
8965 } else if (!strcmp(arg, REPO_INFO_RESOLVED_HEAD)) {
8966 string_ncopy(state->head_id, name, namelen);
8968 } else if (!strcmp(arg, REPO_INFO_SYMBOLIC_HEAD)) {
8969 if (!prefixcmp(name, "refs/heads/")) {
8970 char *offset = name + STRING_SIZE("refs/heads/");
8972 string_ncopy(opt_head, offset, strlen(offset) + 1);
8973 add_ref(state->head_id, name, opt_remote, opt_head);
8975 state->argv++;
8978 return OK;
8981 static int
8982 load_repo_info(void)
8984 const char *rev_parse_argv[] = {
8985 "git", "rev-parse", REPO_INFO_GIT_DIR, REPO_INFO_WORK_TREE,
8986 REPO_INFO_SHOW_CDUP, REPO_INFO_SHOW_PREFIX, \
8987 REPO_INFO_RESOLVED_HEAD, REPO_INFO_SYMBOLIC_HEAD, "HEAD",
8988 NULL
8990 struct repo_info_state state = { rev_parse_argv + 2 };
8992 return io_run_load(rev_parse_argv, "=", read_repo_info, &state);
8997 * Main
9000 static const char usage[] =
9001 "tig " TIG_VERSION " (" __DATE__ ")\n"
9002 "\n"
9003 "Usage: tig [options] [revs] [--] [paths]\n"
9004 " or: tig log [options] [revs] [--] [paths]\n"
9005 " or: tig show [options] [revs] [--] [paths]\n"
9006 " or: tig blame [options] [rev] [--] path\n"
9007 " or: tig stash\n"
9008 " or: tig status\n"
9009 " or: tig < [git command output]\n"
9010 "\n"
9011 "Options:\n"
9012 " +<number> Select line <number> in the first view\n"
9013 " -v, --version Show version and exit\n"
9014 " -h, --help Show help message and exit";
9016 static void TIG_NORETURN
9017 quit(int sig)
9019 if (sig)
9020 signal(sig, SIG_DFL);
9022 /* XXX: Restore tty modes and let the OS cleanup the rest! */
9023 if (cursed)
9024 endwin();
9025 exit(0);
9028 static int
9029 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
9031 const char ***filter_args = data;
9033 return argv_append(filter_args, name) ? OK : ERR;
9036 static void
9037 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
9039 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
9040 const char **all_argv = NULL;
9042 if (!argv_append_array(&all_argv, rev_parse_argv) ||
9043 !argv_append_array(&all_argv, argv) ||
9044 io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
9045 die("Failed to split arguments");
9046 argv_free(all_argv);
9047 free(all_argv);
9050 static bool
9051 is_rev_flag(const char *flag)
9053 static const char *rev_flags[] = { GIT_REV_FLAGS };
9054 int i;
9056 for (i = 0; i < ARRAY_SIZE(rev_flags); i++)
9057 if (!strcmp(flag, rev_flags[i]))
9058 return TRUE;
9060 return FALSE;
9063 static void
9064 filter_options(const char *argv[], bool blame)
9066 const char **flags = NULL;
9068 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
9069 filter_rev_parse(&flags, "--flags", "--no-revs", argv);
9071 if (flags) {
9072 int next, flags_pos;
9074 for (next = flags_pos = 0; flags && flags[next]; next++) {
9075 const char *flag = flags[next];
9077 if (is_rev_flag(flag))
9078 argv_append(&opt_rev_argv, flag);
9079 else
9080 flags[flags_pos++] = flag;
9083 flags[flags_pos] = NULL;
9085 if (blame)
9086 opt_blame_argv = flags;
9087 else
9088 opt_diff_argv = flags;
9091 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
9094 static enum request
9095 parse_options(int argc, const char *argv[], bool pager_mode)
9097 enum request request;
9098 const char *subcommand;
9099 bool seen_dashdash = FALSE;
9100 const char **filter_argv = NULL;
9101 int i;
9103 request = pager_mode ? REQ_VIEW_PAGER : REQ_VIEW_MAIN;
9105 if (argc <= 1)
9106 return request;
9108 subcommand = argv[1];
9109 if (!strcmp(subcommand, "status")) {
9110 request = REQ_VIEW_STATUS;
9112 } else if (!strcmp(subcommand, "blame")) {
9113 request = REQ_VIEW_BLAME;
9115 } else if (!strcmp(subcommand, "show")) {
9116 request = REQ_VIEW_DIFF;
9118 } else if (!strcmp(subcommand, "log")) {
9119 request = REQ_VIEW_LOG;
9121 } else if (!strcmp(subcommand, "stash")) {
9122 request = REQ_VIEW_STASH;
9124 } else {
9125 subcommand = NULL;
9128 for (i = 1 + !!subcommand; i < argc; i++) {
9129 const char *opt = argv[i];
9131 // stop parsing our options after -- and let rev-parse handle the rest
9132 if (!seen_dashdash) {
9133 if (!strcmp(opt, "--")) {
9134 seen_dashdash = TRUE;
9135 continue;
9137 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
9138 printf("tig version %s\n", TIG_VERSION);
9139 quit(0);
9141 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
9142 printf("%s\n", usage);
9143 quit(0);
9145 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
9146 opt_lineno = atoi(opt + 1);
9147 continue;
9152 if (!argv_append(&filter_argv, opt))
9153 die("command too long");
9156 if (filter_argv)
9157 filter_options(filter_argv, request == REQ_VIEW_BLAME);
9159 /* Finish validating and setting up blame options */
9160 if (request == REQ_VIEW_BLAME) {
9161 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
9162 die("invalid number of options to blame\n\n%s", usage);
9164 if (opt_rev_argv) {
9165 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
9168 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
9171 return request;
9174 static enum request
9175 open_pager_mode(enum request request)
9177 enum open_flags flags = OPEN_DEFAULT;
9179 if (request == REQ_VIEW_PAGER) {
9180 /* Detect if the user requested the main view. */
9181 if (argv_contains(opt_rev_argv, "--stdin")) {
9182 request = REQ_VIEW_MAIN;
9183 flags |= OPEN_FORWARD_STDIN;
9184 } else if (argv_contains(opt_diff_argv, "--pretty=raw")) {
9185 request = REQ_VIEW_MAIN;
9186 flags |= OPEN_STDIN;
9187 } else {
9188 flags |= OPEN_STDIN;
9191 } else if (request == REQ_VIEW_DIFF) {
9192 if (argv_contains(opt_rev_argv, "--stdin"))
9193 flags |= OPEN_FORWARD_STDIN;
9196 /* Open the requested view even if the pager mode is enabled so
9197 * the warning message below is displayed correctly. */
9198 open_view(NULL, request, flags);
9200 if (!open_in_pager_mode(flags)) {
9201 close(STDIN_FILENO);
9202 report("Ignoring stdin.");
9205 return REQ_NONE;
9208 static enum request
9209 run_prompt_command(struct view *view, char *cmd) {
9210 enum request request;
9212 if (cmd && string_isnumber(cmd)) {
9213 int lineno = view->pos.lineno + 1;
9215 if (parse_int(&lineno, cmd, 1, view->lines + 1) == SUCCESS) {
9216 select_view_line(view, lineno - 1);
9217 report_clear();
9218 } else {
9219 report("Unable to parse '%s' as a line number", cmd);
9221 } else if (cmd && iscommit(cmd)) {
9222 string_ncopy(opt_search, cmd, strlen(cmd));
9224 request = view_request(view, REQ_JUMP_COMMIT);
9225 if (request == REQ_JUMP_COMMIT) {
9226 report("Jumping to commits is not supported by the '%s' view", view->name);
9229 } else if (cmd && strlen(cmd) == 1) {
9230 request = get_keybinding(&view->ops->keymap, cmd[0]);
9231 return request;
9233 } else if (cmd && cmd[0] == '!') {
9234 struct view *next = VIEW(REQ_VIEW_PAGER);
9235 const char *argv[SIZEOF_ARG];
9236 int argc = 0;
9238 cmd++;
9239 /* When running random commands, initially show the
9240 * command in the title. However, it maybe later be
9241 * overwritten if a commit line is selected. */
9242 string_ncopy(next->ref, cmd, strlen(cmd));
9244 if (!argv_from_string(argv, &argc, cmd)) {
9245 report("Too many arguments");
9246 } else if (!format_argv(view, &next->argv, argv, FALSE, TRUE)) {
9247 report("Argument formatting failed");
9248 } else {
9249 next->dir = NULL;
9250 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
9253 } else if (cmd) {
9254 request = get_request(cmd);
9255 if (request != REQ_UNKNOWN)
9256 return request;
9258 char *args = strchr(cmd, ' ');
9259 if (args) {
9260 *args++ = 0;
9261 if (set_option(cmd, args) == SUCCESS) {
9262 request = !view->unrefreshable ? REQ_REFRESH : REQ_SCREEN_REDRAW;
9263 if (!strcmp(cmd, "color"))
9264 init_colors();
9267 return request;
9269 return REQ_NONE;
9273 main(int argc, const char *argv[])
9275 const char *codeset = ENCODING_UTF8;
9276 bool pager_mode = !isatty(STDIN_FILENO);
9277 enum request request = parse_options(argc, argv, pager_mode);
9278 struct view *view;
9279 int i;
9281 signal(SIGINT, quit);
9282 signal(SIGQUIT, quit);
9283 signal(SIGPIPE, SIG_IGN);
9285 if (setlocale(LC_ALL, "")) {
9286 codeset = nl_langinfo(CODESET);
9289 foreach_view(view, i) {
9290 add_keymap(&view->ops->keymap);
9293 if (load_repo_info() == ERR)
9294 die("Failed to load repo info.");
9296 if (load_options() == ERR)
9297 die("Failed to load user config.");
9299 if (load_git_config() == ERR)
9300 die("Failed to load repo config.");
9302 /* Require a git repository unless when running in pager mode. */
9303 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
9304 die("Not a git repository");
9306 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
9307 char translit[SIZEOF_STR];
9309 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
9310 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
9311 else
9312 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
9313 if (opt_iconv_out == ICONV_NONE)
9314 die("Failed to initialize character set conversion");
9317 if (load_refs(FALSE) == ERR)
9318 die("Failed to load refs.");
9320 init_display();
9322 if (pager_mode)
9323 request = open_pager_mode(request);
9325 while (view_driver(display[current_view], request)) {
9326 int key = get_input(0);
9328 if (key == KEY_ESC)
9329 key = get_input(0) + 0x80;
9331 view = display[current_view];
9332 request = get_keybinding(&view->ops->keymap, key);
9334 /* Some low-level request handling. This keeps access to
9335 * status_win restricted. */
9336 switch (request) {
9337 case REQ_NONE:
9338 report("Unknown key, press %s for help",
9339 get_view_key(view, REQ_VIEW_HELP));
9340 break;
9341 case REQ_PROMPT:
9343 char *cmd = read_prompt(":");
9344 request = run_prompt_command(view, cmd);
9345 break;
9347 case REQ_SEARCH:
9348 case REQ_SEARCH_BACK:
9350 const char *prompt = request == REQ_SEARCH ? "/" : "?";
9351 char *search = read_prompt(prompt);
9353 if (search)
9354 string_ncopy(opt_search, search, strlen(search));
9355 else if (*opt_search)
9356 request = request == REQ_SEARCH ?
9357 REQ_FIND_NEXT :
9358 REQ_FIND_PREV;
9359 else
9360 request = REQ_NONE;
9361 break;
9363 default:
9364 break;
9368 quit(0);
9370 return 0;
9373 /* vim: set ts=8 sw=8 noexpandtab: */