Introduce a path cache and use it for the blame view
[tig.git] / tig.c
blobd794af166991494c813fac095a5a07f63f78487a
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_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
347 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
349 REQ_GROUP("Cursor navigation") \
350 REQ_(MOVE_UP, "Move cursor one line up"), \
351 REQ_(MOVE_DOWN, "Move cursor one line down"), \
352 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
353 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
354 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
355 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
357 REQ_GROUP("Scrolling") \
358 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
359 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
360 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
361 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
362 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
363 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
364 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
366 REQ_GROUP("Searching") \
367 REQ_(SEARCH, "Search the view"), \
368 REQ_(SEARCH_BACK, "Search backwards in the view"), \
369 REQ_(FIND_NEXT, "Find next search match"), \
370 REQ_(FIND_PREV, "Find previous search match"), \
372 REQ_GROUP("Option manipulation") \
373 REQ_(OPTIONS, "Open option menu"), \
374 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
375 REQ_(TOGGLE_DATE, "Toggle date display"), \
376 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
377 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
378 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
379 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
380 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
381 REQ_(TOGGLE_CHANGES, "Toggle local changes display in the main view"), \
382 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
383 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
384 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
385 REQ_(TOGGLE_COMMIT_ORDER, "Toggle commit ordering"), \
386 REQ_(TOGGLE_ID, "Toggle commit ID display"), \
387 REQ_(TOGGLE_FILES, "Toggle file filtering"), \
388 REQ_(TOGGLE_TITLE_OVERFLOW, "Toggle highlighting of commit title overflow"), \
389 REQ_(TOGGLE_FILE_SIZE, "Toggle file size format"), \
390 REQ_(TOGGLE_UNTRACKED_DIRS, "Toggle display of files in untracked directories"), \
392 REQ_GROUP("Misc") \
393 REQ_(PROMPT, "Bring up the prompt"), \
394 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
395 REQ_(SHOW_VERSION, "Show version information"), \
396 REQ_(STOP_LOADING, "Stop all loading views"), \
397 REQ_(EDIT, "Open in editor"), \
398 REQ_(NONE, "Do nothing")
401 /* User action requests. */
402 enum request {
403 #define REQ_GROUP(help)
404 #define REQ_(req, help) REQ_##req
406 /* Offset all requests to avoid conflicts with ncurses getch values. */
407 REQ_UNKNOWN = KEY_MAX + 1,
408 REQ_OFFSET,
409 REQ_INFO,
411 /* Internal requests. */
412 REQ_JUMP_COMMIT,
414 #undef REQ_GROUP
415 #undef REQ_
418 struct request_info {
419 enum request request;
420 const char *name;
421 int namelen;
422 const char *help;
425 static const struct request_info req_info[] = {
426 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
427 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
428 REQ_INFO
429 #undef REQ_GROUP
430 #undef REQ_
433 static enum request
434 get_request(const char *name)
436 int namelen = strlen(name);
437 int i;
439 for (i = 0; i < ARRAY_SIZE(req_info); i++)
440 if (enum_equals(req_info[i], name, namelen))
441 return req_info[i].request;
443 return REQ_UNKNOWN;
448 * Options
451 /* Option and state variables. */
452 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
453 static enum date opt_date = DATE_DEFAULT;
454 static enum author opt_author = AUTHOR_FULL;
455 static enum filename opt_filename = FILENAME_AUTO;
456 static enum file_size opt_file_size = FILE_SIZE_DEFAULT;
457 static bool opt_rev_graph = TRUE;
458 static bool opt_line_number = FALSE;
459 static bool opt_show_refs = TRUE;
460 static bool opt_show_changes = TRUE;
461 static bool opt_untracked_dirs_content = TRUE;
462 static bool opt_read_git_colors = TRUE;
463 static bool opt_wrap_lines = FALSE;
464 static bool opt_ignore_case = FALSE;
465 static bool opt_focus_child = TRUE;
466 static int opt_diff_context = 3;
467 static char opt_diff_context_arg[9] = "";
468 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
469 static char opt_ignore_space_arg[22] = "";
470 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
471 static char opt_commit_order_arg[22] = "";
472 static bool opt_notes = TRUE;
473 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
474 static int opt_num_interval = 5;
475 static double opt_hscroll = 0.50;
476 static double opt_scale_split_view = 2.0 / 3.0;
477 static double opt_scale_vsplit_view = 0.5;
478 static bool opt_vsplit = FALSE;
479 static int opt_tab_size = 8;
480 static int opt_author_width = AUTHOR_WIDTH;
481 static int opt_filename_width = FILENAME_WIDTH;
482 static char opt_path[SIZEOF_STR] = "";
483 static char opt_file[SIZEOF_STR] = "";
484 static char opt_ref[SIZEOF_REF] = "";
485 static unsigned long opt_goto_line = 0;
486 static char opt_head[SIZEOF_REF] = "";
487 static char opt_remote[SIZEOF_REF] = "";
488 static iconv_t opt_iconv_out = ICONV_NONE;
489 static char opt_search[SIZEOF_STR] = "";
490 static char opt_cdup[SIZEOF_STR] = "";
491 static char opt_prefix[SIZEOF_STR] = "";
492 static char opt_git_dir[SIZEOF_STR] = "";
493 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
494 static char opt_editor[SIZEOF_STR] = "";
495 static bool opt_editor_lineno = TRUE;
496 static FILE *opt_tty = NULL;
497 static const char **opt_diff_argv = NULL;
498 static const char **opt_rev_argv = NULL;
499 static const char **opt_file_argv = NULL;
500 static const char **opt_blame_argv = NULL;
501 static int opt_lineno = 0;
502 static bool opt_show_id = FALSE;
503 static int opt_id_cols = ID_WIDTH;
504 static bool opt_file_filter = TRUE;
505 static bool opt_show_title_overflow = FALSE;
506 static int opt_title_overflow = 50;
507 static char opt_env_lines[64] = "";
508 static char opt_env_columns[64] = "";
509 static char *opt_env[] = { opt_env_lines, opt_env_columns, NULL };
511 #define is_initial_commit() (!get_ref_head())
512 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strncmp(rev, get_ref_head()->id, SIZEOF_REV - 1)))
514 static inline int
515 load_refs(bool force)
517 static bool loaded = FALSE;
519 if (force)
520 opt_head[0] = 0;
521 else if (loaded)
522 return OK;
524 loaded = TRUE;
525 return reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head));
528 static inline void
529 update_diff_context_arg(int diff_context)
531 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
532 string_ncopy(opt_diff_context_arg, "-U3", 3);
535 static inline void
536 update_ignore_space_arg()
538 if (opt_ignore_space == IGNORE_SPACE_ALL) {
539 string_copy(opt_ignore_space_arg, "--ignore-all-space");
540 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
541 string_copy(opt_ignore_space_arg, "--ignore-space-change");
542 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
543 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
544 } else {
545 string_copy(opt_ignore_space_arg, "");
549 static inline void
550 update_commit_order_arg()
552 if (opt_commit_order == COMMIT_ORDER_TOPO) {
553 string_copy(opt_commit_order_arg, "--topo-order");
554 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
555 string_copy(opt_commit_order_arg, "--date-order");
556 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
557 string_copy(opt_commit_order_arg, "--reverse");
558 } else {
559 string_copy(opt_commit_order_arg, "");
563 static inline void
564 update_notes_arg()
566 if (opt_notes) {
567 string_copy(opt_notes_arg, "--show-notes");
568 } else {
569 /* Notes are disabled by default when passing --pretty args. */
570 string_copy(opt_notes_arg, "");
575 * Line-oriented content detection.
578 #define LINE_INFO \
579 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
580 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
581 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
582 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
583 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
584 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
585 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
586 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
587 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
588 LINE(DIFF_DELETED_FILE_MODE, \
589 "deleted file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
590 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
591 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
592 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
593 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
594 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
595 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
596 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
597 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
598 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
599 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
600 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
601 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
602 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
603 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
604 LINE(PP_REFLOG, "Reflog: ", COLOR_RED, COLOR_DEFAULT, 0), \
605 LINE(PP_REFLOGMSG, "Reflog message: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
606 LINE(STASH, "stash@{", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
607 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
608 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
609 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
610 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
611 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
612 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
613 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
614 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
615 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
616 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
617 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
618 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
619 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
620 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
621 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
622 LINE(ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
623 LINE(OVERFLOW, "", COLOR_RED, COLOR_DEFAULT, 0), \
624 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
625 LINE(FILE_SIZE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
626 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
627 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
628 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
629 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
630 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
631 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
632 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
633 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
634 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
635 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
636 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
637 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
638 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
639 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
640 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
641 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
642 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
643 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
644 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
645 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
646 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
647 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
648 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
649 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
650 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
651 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
652 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
653 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
654 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
655 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
656 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
657 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
659 enum line_type {
660 #define LINE(type, line, fg, bg, attr) \
661 LINE_##type
662 LINE_INFO,
663 LINE_NONE
664 #undef LINE
667 struct line_info {
668 const char *name; /* Option name. */
669 int namelen; /* Size of option name. */
670 const char *line; /* The start of line to match. */
671 int linelen; /* Size of string to match. */
672 int fg, bg, attr; /* Color and text attributes for the lines. */
673 int color_pair;
676 static struct line_info line_info[] = {
677 #define LINE(type, line, fg, bg, attr) \
678 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
679 LINE_INFO
680 #undef LINE
683 static struct line_info **color_pair;
684 static size_t color_pairs;
686 static struct line_info *custom_color;
687 static size_t custom_colors;
689 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
690 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
692 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
693 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
695 /* Color IDs must be 1 or higher. [GH #15] */
696 #define COLOR_ID(line_type) ((line_type) + 1)
698 static enum line_type
699 get_line_type(const char *line)
701 int linelen = strlen(line);
702 enum line_type type;
704 for (type = 0; type < custom_colors; type++)
705 /* Case insensitive search matches Signed-off-by lines better. */
706 if (linelen >= custom_color[type].linelen &&
707 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
708 return TO_CUSTOM_COLOR_TYPE(type);
710 for (type = 0; type < ARRAY_SIZE(line_info); type++)
711 /* Case insensitive search matches Signed-off-by lines better. */
712 if (linelen >= line_info[type].linelen &&
713 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
714 return type;
716 return LINE_DEFAULT;
719 static enum line_type
720 get_line_type_from_ref(const struct ref *ref)
722 if (ref->head)
723 return LINE_MAIN_HEAD;
724 else if (ref->ltag)
725 return LINE_MAIN_LOCAL_TAG;
726 else if (ref->tag)
727 return LINE_MAIN_TAG;
728 else if (ref->tracked)
729 return LINE_MAIN_TRACKED;
730 else if (ref->remote)
731 return LINE_MAIN_REMOTE;
732 else if (ref->replace)
733 return LINE_MAIN_REPLACE;
735 return LINE_MAIN_REF;
738 static inline struct line_info *
739 get_line(enum line_type type)
741 if (type > LINE_NONE) {
742 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
743 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
744 } else {
745 assert(type < ARRAY_SIZE(line_info));
746 return &line_info[type];
750 static inline int
751 get_line_color(enum line_type type)
753 return COLOR_ID(get_line(type)->color_pair);
756 static inline int
757 get_line_attr(enum line_type type)
759 struct line_info *info = get_line(type);
761 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
764 static struct line_info *
765 get_line_info(const char *name)
767 size_t namelen = strlen(name);
768 enum line_type type;
770 for (type = 0; type < ARRAY_SIZE(line_info); type++)
771 if (enum_equals(line_info[type], name, namelen))
772 return &line_info[type];
774 return NULL;
777 static struct line_info *
778 add_custom_color(const char *quoted_line)
780 struct line_info *info;
781 char *line;
782 size_t linelen;
784 if (!realloc_custom_color(&custom_color, custom_colors, 1))
785 die("Failed to alloc custom line info");
787 linelen = strlen(quoted_line) - 1;
788 line = malloc(linelen);
789 if (!line)
790 return NULL;
792 strncpy(line, quoted_line + 1, linelen);
793 line[linelen - 1] = 0;
795 info = &custom_color[custom_colors++];
796 info->name = info->line = line;
797 info->namelen = info->linelen = strlen(line);
799 return info;
802 static void
803 init_line_info_color_pair(struct line_info *info, enum line_type type,
804 int default_bg, int default_fg)
806 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
807 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
808 int i;
810 for (i = 0; i < color_pairs; i++) {
811 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
812 info->color_pair = i;
813 return;
817 if (!realloc_color_pair(&color_pair, color_pairs, 1))
818 die("Failed to alloc color pair");
820 color_pair[color_pairs] = info;
821 info->color_pair = color_pairs++;
822 init_pair(COLOR_ID(info->color_pair), fg, bg);
825 static void
826 init_colors(void)
828 int default_bg = line_info[LINE_DEFAULT].bg;
829 int default_fg = line_info[LINE_DEFAULT].fg;
830 enum line_type type;
832 start_color();
834 if (assume_default_colors(default_fg, default_bg) == ERR) {
835 default_bg = COLOR_BLACK;
836 default_fg = COLOR_WHITE;
839 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
840 struct line_info *info = &line_info[type];
842 init_line_info_color_pair(info, type, default_bg, default_fg);
845 for (type = 0; type < custom_colors; type++) {
846 struct line_info *info = &custom_color[type];
848 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
849 default_bg, default_fg);
853 struct line {
854 enum line_type type;
855 unsigned int lineno:24;
857 /* State flags */
858 unsigned int selected:1;
859 unsigned int dirty:1;
860 unsigned int cleareol:1;
861 unsigned int wrapped:1;
863 unsigned int user_flags:6;
864 void *data; /* User data */
869 * Keys
872 struct keybinding {
873 int alias;
874 enum request request;
877 static struct keybinding default_keybindings[] = {
878 /* View switching */
879 { 'm', REQ_VIEW_MAIN },
880 { 'd', REQ_VIEW_DIFF },
881 { 'l', REQ_VIEW_LOG },
882 { 't', REQ_VIEW_TREE },
883 { 'f', REQ_VIEW_BLOB },
884 { 'B', REQ_VIEW_BLAME },
885 { 'H', REQ_VIEW_BRANCH },
886 { 'p', REQ_VIEW_PAGER },
887 { 'h', REQ_VIEW_HELP },
888 { 'S', REQ_VIEW_STATUS },
889 { 'c', REQ_VIEW_STAGE },
890 { 'y', REQ_VIEW_STASH },
892 /* View manipulation */
893 { 'q', REQ_VIEW_CLOSE },
894 { KEY_TAB, REQ_VIEW_NEXT },
895 { KEY_RETURN, REQ_ENTER },
896 { KEY_UP, REQ_PREVIOUS },
897 { KEY_CTL('P'), REQ_PREVIOUS },
898 { KEY_DOWN, REQ_NEXT },
899 { KEY_CTL('N'), REQ_NEXT },
900 { 'R', REQ_REFRESH },
901 { KEY_F(5), REQ_REFRESH },
902 { 'O', REQ_MAXIMIZE },
903 { ',', REQ_PARENT },
904 { '<', REQ_BACK },
906 /* View specific */
907 { 'u', REQ_STATUS_UPDATE },
908 { '!', REQ_STATUS_REVERT },
909 { 'M', REQ_STATUS_MERGE },
910 { '1', REQ_STAGE_UPDATE_LINE },
911 { '@', REQ_STAGE_NEXT },
912 { '[', REQ_DIFF_CONTEXT_DOWN },
913 { ']', REQ_DIFF_CONTEXT_UP },
915 /* Cursor navigation */
916 { 'k', REQ_MOVE_UP },
917 { 'j', REQ_MOVE_DOWN },
918 { KEY_HOME, REQ_MOVE_FIRST_LINE },
919 { KEY_END, REQ_MOVE_LAST_LINE },
920 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
921 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
922 { ' ', REQ_MOVE_PAGE_DOWN },
923 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
924 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
925 { 'b', REQ_MOVE_PAGE_UP },
926 { '-', REQ_MOVE_PAGE_UP },
928 /* Scrolling */
929 { '|', REQ_SCROLL_FIRST_COL },
930 { KEY_LEFT, REQ_SCROLL_LEFT },
931 { KEY_RIGHT, REQ_SCROLL_RIGHT },
932 { KEY_IC, REQ_SCROLL_LINE_UP },
933 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
934 { KEY_DC, REQ_SCROLL_LINE_DOWN },
935 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
936 { 'w', REQ_SCROLL_PAGE_UP },
937 { 's', REQ_SCROLL_PAGE_DOWN },
939 /* Searching */
940 { '/', REQ_SEARCH },
941 { '?', REQ_SEARCH_BACK },
942 { 'n', REQ_FIND_NEXT },
943 { 'N', REQ_FIND_PREV },
945 /* Misc */
946 { 'Q', REQ_QUIT },
947 { 'z', REQ_STOP_LOADING },
948 { 'v', REQ_SHOW_VERSION },
949 { 'r', REQ_SCREEN_REDRAW },
950 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
951 { 'o', REQ_OPTIONS },
952 { '.', REQ_TOGGLE_LINENO },
953 { 'D', REQ_TOGGLE_DATE },
954 { 'A', REQ_TOGGLE_AUTHOR },
955 { 'g', REQ_TOGGLE_REV_GRAPH },
956 { '~', REQ_TOGGLE_GRAPHIC },
957 { '#', REQ_TOGGLE_FILENAME },
958 { 'F', REQ_TOGGLE_REFS },
959 { 'I', REQ_TOGGLE_SORT_ORDER },
960 { 'i', REQ_TOGGLE_SORT_FIELD },
961 { 'W', REQ_TOGGLE_IGNORE_SPACE },
962 { 'X', REQ_TOGGLE_ID },
963 { '%', REQ_TOGGLE_FILES },
964 { '$', REQ_TOGGLE_TITLE_OVERFLOW },
965 { ':', REQ_PROMPT },
966 { 'e', REQ_EDIT },
969 struct keymap {
970 const char *name;
971 struct keymap *next;
972 struct keybinding *data;
973 size_t size;
974 bool hidden;
977 static struct keymap generic_keymap = { "generic" };
978 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
980 static struct keymap *keymaps = &generic_keymap;
982 static void
983 add_keymap(struct keymap *keymap)
985 keymap->next = keymaps;
986 keymaps = keymap;
989 static struct keymap *
990 get_keymap(const char *name)
992 struct keymap *keymap = keymaps;
994 while (keymap) {
995 if (!strcasecmp(keymap->name, name))
996 return keymap;
997 keymap = keymap->next;
1000 return NULL;
1004 static void
1005 add_keybinding(struct keymap *table, enum request request, int key)
1007 size_t i;
1009 for (i = 0; i < table->size; i++) {
1010 if (table->data[i].alias == key) {
1011 table->data[i].request = request;
1012 return;
1016 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
1017 if (!table->data)
1018 die("Failed to allocate keybinding");
1019 table->data[table->size].alias = key;
1020 table->data[table->size++].request = request;
1022 if (request == REQ_NONE && is_generic_keymap(table)) {
1023 int i;
1025 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1026 if (default_keybindings[i].alias == key)
1027 default_keybindings[i].request = REQ_NONE;
1031 /* Looks for a key binding first in the given map, then in the generic map, and
1032 * lastly in the default keybindings. */
1033 static enum request
1034 get_keybinding(struct keymap *keymap, int key)
1036 size_t i;
1038 for (i = 0; i < keymap->size; i++)
1039 if (keymap->data[i].alias == key)
1040 return keymap->data[i].request;
1042 for (i = 0; i < generic_keymap.size; i++)
1043 if (generic_keymap.data[i].alias == key)
1044 return generic_keymap.data[i].request;
1046 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1047 if (default_keybindings[i].alias == key)
1048 return default_keybindings[i].request;
1050 return (enum request) key;
1054 struct key {
1055 const char *name;
1056 int value;
1059 static const struct key key_table[] = {
1060 { "Enter", KEY_RETURN },
1061 { "Space", ' ' },
1062 { "Backspace", KEY_BACKSPACE },
1063 { "Tab", KEY_TAB },
1064 { "Escape", KEY_ESC },
1065 { "Left", KEY_LEFT },
1066 { "Right", KEY_RIGHT },
1067 { "Up", KEY_UP },
1068 { "Down", KEY_DOWN },
1069 { "Insert", KEY_IC },
1070 { "Delete", KEY_DC },
1071 { "Hash", '#' },
1072 { "Home", KEY_HOME },
1073 { "End", KEY_END },
1074 { "PageUp", KEY_PPAGE },
1075 { "PageDown", KEY_NPAGE },
1076 { "F1", KEY_F(1) },
1077 { "F2", KEY_F(2) },
1078 { "F3", KEY_F(3) },
1079 { "F4", KEY_F(4) },
1080 { "F5", KEY_F(5) },
1081 { "F6", KEY_F(6) },
1082 { "F7", KEY_F(7) },
1083 { "F8", KEY_F(8) },
1084 { "F9", KEY_F(9) },
1085 { "F10", KEY_F(10) },
1086 { "F11", KEY_F(11) },
1087 { "F12", KEY_F(12) },
1090 static int
1091 get_key_value(const char *name)
1093 int i;
1095 for (i = 0; i < ARRAY_SIZE(key_table); i++)
1096 if (!strcasecmp(key_table[i].name, name))
1097 return key_table[i].value;
1099 if (strlen(name) == 3 && name[0] == '^' && name[1] == '[' && isprint(*name))
1100 return (int)name[2] + 0x80;
1101 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1102 return (int)name[1] & 0x1f;
1103 if (strlen(name) == 1 && isprint(*name))
1104 return (int) *name;
1105 return ERR;
1108 static const char *
1109 get_key_name(int key_value)
1111 static char key_char[] = "'X'\0";
1112 const char *seq = NULL;
1113 int key;
1115 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1116 if (key_table[key].value == key_value)
1117 seq = key_table[key].name;
1119 if (seq == NULL && key_value < 0x7f) {
1120 char *s = key_char + 1;
1122 if (key_value >= 0x20) {
1123 *s++ = key_value;
1124 } else {
1125 *s++ = '^';
1126 *s++ = 0x40 | (key_value & 0x1f);
1128 *s++ = '\'';
1129 *s++ = '\0';
1130 seq = key_char;
1133 return seq ? seq : "(no key)";
1136 static bool
1137 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1139 const char *sep = *pos > 0 ? ", " : "";
1140 const char *keyname = get_key_name(keybinding->alias);
1142 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1145 static bool
1146 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1147 struct keymap *keymap, bool all)
1149 int i;
1151 for (i = 0; i < keymap->size; i++) {
1152 if (keymap->data[i].request == request) {
1153 if (!append_key(buf, pos, &keymap->data[i]))
1154 return FALSE;
1155 if (!all)
1156 break;
1160 return TRUE;
1163 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1165 static const char *
1166 get_keys(struct keymap *keymap, enum request request, bool all)
1168 static char buf[BUFSIZ];
1169 size_t pos = 0;
1170 int i;
1172 buf[pos] = 0;
1174 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1175 return "Too many keybindings!";
1176 if (pos > 0 && !all)
1177 return buf;
1179 if (!is_generic_keymap(keymap)) {
1180 /* Only the generic keymap includes the default keybindings when
1181 * listing all keys. */
1182 if (all)
1183 return buf;
1185 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1186 return "Too many keybindings!";
1187 if (pos)
1188 return buf;
1191 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1192 if (default_keybindings[i].request == request) {
1193 if (!append_key(buf, &pos, &default_keybindings[i]))
1194 return "Too many keybindings!";
1195 if (!all)
1196 return buf;
1200 return buf;
1203 enum run_request_flag {
1204 RUN_REQUEST_DEFAULT = 0,
1205 RUN_REQUEST_FORCE = 1,
1206 RUN_REQUEST_SILENT = 2,
1207 RUN_REQUEST_CONFIRM = 4,
1208 RUN_REQUEST_EXIT = 8,
1209 RUN_REQUEST_INTERNAL = 16,
1212 struct run_request {
1213 struct keymap *keymap;
1214 int key;
1215 const char **argv;
1216 bool silent;
1217 bool confirm;
1218 bool exit;
1219 bool internal;
1222 static struct run_request *run_request;
1223 static size_t run_requests;
1225 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1227 static bool
1228 add_run_request(struct keymap *keymap, int key, const char **argv, enum run_request_flag flags)
1230 bool force = flags & RUN_REQUEST_FORCE;
1231 struct run_request *req;
1233 if (!force && get_keybinding(keymap, key) != key)
1234 return TRUE;
1236 if (!realloc_run_requests(&run_request, run_requests, 1))
1237 return FALSE;
1239 if (!argv_copy(&run_request[run_requests].argv, argv))
1240 return FALSE;
1242 req = &run_request[run_requests++];
1243 req->silent = flags & RUN_REQUEST_SILENT;
1244 req->confirm = flags & RUN_REQUEST_CONFIRM;
1245 req->exit = flags & RUN_REQUEST_EXIT;
1246 req->internal = flags & RUN_REQUEST_INTERNAL;
1247 req->keymap = keymap;
1248 req->key = key;
1250 add_keybinding(keymap, REQ_NONE + run_requests, key);
1251 return TRUE;
1254 static struct run_request *
1255 get_run_request(enum request request)
1257 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1258 return NULL;
1259 return &run_request[request - REQ_NONE - 1];
1262 static void
1263 add_builtin_run_requests(void)
1265 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1266 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1267 const char *commit[] = { "git", "commit", NULL };
1268 const char *gc[] = { "git", "gc", NULL };
1269 const char *stash_pop[] = { "git", "stash", "pop", "%(stash)", NULL };
1271 add_run_request(get_keymap("main"), 'C', cherry_pick, RUN_REQUEST_CONFIRM);
1272 add_run_request(get_keymap("status"), 'C', commit, RUN_REQUEST_DEFAULT);
1273 add_run_request(get_keymap("branch"), 'C', checkout, RUN_REQUEST_CONFIRM);
1274 add_run_request(get_keymap("generic"), 'G', gc, RUN_REQUEST_CONFIRM);
1275 add_run_request(get_keymap("stash"), 'P', stash_pop, RUN_REQUEST_CONFIRM);
1279 * User config file handling.
1282 static const struct enum_map color_map[] = {
1283 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1284 COLOR_MAP(DEFAULT),
1285 COLOR_MAP(BLACK),
1286 COLOR_MAP(BLUE),
1287 COLOR_MAP(CYAN),
1288 COLOR_MAP(GREEN),
1289 COLOR_MAP(MAGENTA),
1290 COLOR_MAP(RED),
1291 COLOR_MAP(WHITE),
1292 COLOR_MAP(YELLOW),
1295 static const struct enum_map attr_map[] = {
1296 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1297 ATTR_MAP(NORMAL),
1298 ATTR_MAP(BLINK),
1299 ATTR_MAP(BOLD),
1300 ATTR_MAP(DIM),
1301 ATTR_MAP(REVERSE),
1302 ATTR_MAP(STANDOUT),
1303 ATTR_MAP(UNDERLINE),
1306 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1308 static enum status_code
1309 parse_step(double *opt, const char *arg)
1311 *opt = atoi(arg);
1312 if (!strchr(arg, '%'))
1313 return SUCCESS;
1315 /* "Shift down" so 100% and 1 does not conflict. */
1316 *opt = (*opt - 1) / 100;
1317 if (*opt >= 1.0) {
1318 *opt = 0.99;
1319 return ERROR_INVALID_STEP_VALUE;
1321 if (*opt < 0.0) {
1322 *opt = 1;
1323 return ERROR_INVALID_STEP_VALUE;
1325 return SUCCESS;
1328 static enum status_code
1329 parse_int(int *opt, const char *arg, int min, int max)
1331 int value = atoi(arg);
1333 if (min <= value && value <= max) {
1334 *opt = value;
1335 return SUCCESS;
1338 return ERROR_INTEGER_VALUE_OUT_OF_BOUND;
1341 #define parse_id(opt, arg) \
1342 parse_int(opt, arg, 4, SIZEOF_REV - 1)
1344 static bool
1345 set_color(int *color, const char *name)
1347 if (map_enum(color, color_map, name))
1348 return TRUE;
1349 if (!prefixcmp(name, "color"))
1350 return parse_int(color, name + 5, 0, 255) == SUCCESS;
1351 /* Used when reading git colors. Git expects a plain int w/o prefix. */
1352 return parse_int(color, name, 0, 255) == SUCCESS;
1355 /* Wants: object fgcolor bgcolor [attribute] */
1356 static enum status_code
1357 option_color_command(int argc, const char *argv[])
1359 struct line_info *info;
1361 if (argc < 3)
1362 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1364 if (*argv[0] == '"' || *argv[0] == '\'') {
1365 info = add_custom_color(argv[0]);
1366 } else {
1367 info = get_line_info(argv[0]);
1369 if (!info) {
1370 static const struct enum_map obsolete[] = {
1371 ENUM_MAP("main-delim", LINE_DELIMITER),
1372 ENUM_MAP("main-date", LINE_DATE),
1373 ENUM_MAP("main-author", LINE_AUTHOR),
1374 ENUM_MAP("blame-id", LINE_ID),
1376 int index;
1378 if (!map_enum(&index, obsolete, argv[0]))
1379 return ERROR_UNKNOWN_COLOR_NAME;
1380 info = &line_info[index];
1383 if (!set_color(&info->fg, argv[1]) ||
1384 !set_color(&info->bg, argv[2]))
1385 return ERROR_UNKNOWN_COLOR;
1387 info->attr = 0;
1388 while (argc-- > 3) {
1389 int attr;
1391 if (!set_attribute(&attr, argv[argc]))
1392 return ERROR_UNKNOWN_ATTRIBUTE;
1393 info->attr |= attr;
1396 return SUCCESS;
1399 static enum status_code
1400 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1402 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1403 ? TRUE : FALSE;
1404 if (matched)
1405 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1406 return SUCCESS;
1409 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1411 static enum status_code
1412 parse_enum_do(unsigned int *opt, const char *arg,
1413 const struct enum_map *map, size_t map_size)
1415 bool is_true;
1417 assert(map_size > 1);
1419 if (map_enum_do(map, map_size, (int *) opt, arg))
1420 return SUCCESS;
1422 parse_bool(&is_true, arg);
1423 *opt = is_true ? map[1].value : map[0].value;
1424 return SUCCESS;
1427 #define parse_enum(opt, arg, map) \
1428 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1430 static enum status_code
1431 parse_string(char *opt, const char *arg, size_t optsize)
1433 int arglen = strlen(arg);
1435 switch (arg[0]) {
1436 case '\"':
1437 case '\'':
1438 if (arglen == 1 || arg[arglen - 1] != arg[0])
1439 return ERROR_UNMATCHED_QUOTATION;
1440 arg += 1; arglen -= 2;
1441 default:
1442 string_ncopy_do(opt, optsize, arg, arglen);
1443 return SUCCESS;
1447 static enum status_code
1448 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1450 char buf[SIZEOF_STR];
1451 enum status_code code = parse_string(buf, arg, sizeof(buf));
1453 if (code == SUCCESS) {
1454 struct encoding *encoding = *encoding_ref;
1456 if (encoding && !priority)
1457 return code;
1458 encoding = encoding_open(buf);
1459 if (encoding)
1460 *encoding_ref = encoding;
1463 return code;
1466 static enum status_code
1467 parse_args(const char ***args, const char *argv[])
1469 if (!argv_copy(args, argv))
1470 return ERROR_OUT_OF_MEMORY;
1471 return SUCCESS;
1474 /* Wants: name = value */
1475 static enum status_code
1476 option_set_command(int argc, const char *argv[])
1478 if (argc < 3)
1479 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1481 if (strcmp(argv[1], "="))
1482 return ERROR_NO_VALUE_ASSIGNED;
1484 if (!strcmp(argv[0], "blame-options"))
1485 return parse_args(&opt_blame_argv, argv + 2);
1487 if (!strcmp(argv[0], "diff-options"))
1488 return parse_args(&opt_diff_argv, argv + 2);
1490 if (argc != 3)
1491 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1493 if (!strcmp(argv[0], "show-author"))
1494 return parse_enum(&opt_author, argv[2], author_map);
1496 if (!strcmp(argv[0], "show-date"))
1497 return parse_enum(&opt_date, argv[2], date_map);
1499 if (!strcmp(argv[0], "show-rev-graph"))
1500 return parse_bool(&opt_rev_graph, argv[2]);
1502 if (!strcmp(argv[0], "show-refs"))
1503 return parse_bool(&opt_show_refs, argv[2]);
1505 if (!strcmp(argv[0], "show-changes"))
1506 return parse_bool(&opt_show_changes, argv[2]);
1508 if (!strcmp(argv[0], "show-notes")) {
1509 bool matched = FALSE;
1510 enum status_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1512 if (res == SUCCESS && matched) {
1513 update_notes_arg();
1514 return res;
1517 opt_notes = TRUE;
1518 strcpy(opt_notes_arg, "--show-notes=");
1519 res = parse_string(opt_notes_arg + 8, argv[2],
1520 sizeof(opt_notes_arg) - 8);
1521 if (res == SUCCESS && opt_notes_arg[8] == '\0')
1522 opt_notes_arg[7] = '\0';
1523 return res;
1526 if (!strcmp(argv[0], "show-line-numbers"))
1527 return parse_bool(&opt_line_number, argv[2]);
1529 if (!strcmp(argv[0], "line-graphics"))
1530 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1532 if (!strcmp(argv[0], "line-number-interval"))
1533 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1535 if (!strcmp(argv[0], "author-width"))
1536 return parse_int(&opt_author_width, argv[2], 0, 1024);
1538 if (!strcmp(argv[0], "filename-width"))
1539 return parse_int(&opt_filename_width, argv[2], 0, 1024);
1541 if (!strcmp(argv[0], "show-filename"))
1542 return parse_enum(&opt_filename, argv[2], filename_map);
1544 if (!strcmp(argv[0], "show-file-size"))
1545 return parse_enum(&opt_file_size, argv[2], file_size_map);
1547 if (!strcmp(argv[0], "horizontal-scroll"))
1548 return parse_step(&opt_hscroll, argv[2]);
1550 if (!strcmp(argv[0], "split-view-height"))
1551 return parse_step(&opt_scale_split_view, argv[2]);
1553 if (!strcmp(argv[0], "vertical-split"))
1554 return parse_bool(&opt_vsplit, argv[2]);
1556 if (!strcmp(argv[0], "tab-size"))
1557 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1559 if (!strcmp(argv[0], "diff-context")) {
1560 enum status_code code = parse_int(&opt_diff_context, argv[2], 0, 999999);
1562 if (code == SUCCESS)
1563 update_diff_context_arg(opt_diff_context);
1564 return code;
1567 if (!strcmp(argv[0], "ignore-space")) {
1568 enum status_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1570 if (code == SUCCESS)
1571 update_ignore_space_arg();
1572 return code;
1575 if (!strcmp(argv[0], "commit-order")) {
1576 enum status_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1578 if (code == SUCCESS)
1579 update_commit_order_arg();
1580 return code;
1583 if (!strcmp(argv[0], "status-untracked-dirs"))
1584 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1586 if (!strcmp(argv[0], "read-git-colors"))
1587 return parse_bool(&opt_read_git_colors, argv[2]);
1589 if (!strcmp(argv[0], "ignore-case"))
1590 return parse_bool(&opt_ignore_case, argv[2]);
1592 if (!strcmp(argv[0], "focus-child"))
1593 return parse_bool(&opt_focus_child, argv[2]);
1595 if (!strcmp(argv[0], "wrap-lines"))
1596 return parse_bool(&opt_wrap_lines, argv[2]);
1598 if (!strcmp(argv[0], "show-id"))
1599 return parse_bool(&opt_show_id, argv[2]);
1601 if (!strcmp(argv[0], "id-width"))
1602 return parse_id(&opt_id_cols, argv[2]);
1604 if (!strcmp(argv[0], "title-overflow")) {
1605 bool matched;
1606 enum status_code code;
1609 * "title-overflow" is considered a boolint.
1610 * We try to parse it as a boolean (and set the value to 50 if true),
1611 * otherwise we parse it as an integer and use the given value.
1613 code = parse_bool_matched(&opt_show_title_overflow, argv[2], &matched);
1614 if (code == SUCCESS && matched) {
1615 if (opt_show_title_overflow)
1616 opt_title_overflow = 50;
1617 } else {
1618 code = parse_int(&opt_title_overflow, argv[2], 2, 1024);
1619 if (code == SUCCESS)
1620 opt_show_title_overflow = TRUE;
1623 return code;
1626 if (!strcmp(argv[0], "editor-line-number"))
1627 return parse_bool(&opt_editor_lineno, argv[2]);
1629 return ERROR_UNKNOWN_VARIABLE_NAME;
1632 /* Wants: mode request key */
1633 static enum status_code
1634 option_bind_command(int argc, const char *argv[])
1636 enum request request;
1637 struct keymap *keymap;
1638 int key;
1640 if (argc < 3)
1641 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1643 if (!(keymap = get_keymap(argv[0])))
1644 return ERROR_UNKNOWN_KEY_MAP;
1646 key = get_key_value(argv[1]);
1647 if (key == ERR)
1648 return ERROR_UNKNOWN_KEY;
1650 request = get_request(argv[2]);
1651 if (request == REQ_UNKNOWN) {
1652 static const struct enum_map obsolete[] = {
1653 ENUM_MAP("cherry-pick", REQ_NONE),
1654 ENUM_MAP("screen-resize", REQ_NONE),
1655 ENUM_MAP("tree-parent", REQ_PARENT),
1657 int alias;
1659 if (map_enum(&alias, obsolete, argv[2])) {
1660 if (alias != REQ_NONE)
1661 add_keybinding(keymap, alias, key);
1662 return ERROR_OBSOLETE_REQUEST_NAME;
1666 if (request == REQ_UNKNOWN) {
1667 enum run_request_flag flags = RUN_REQUEST_FORCE;
1669 if (strchr("!?@<", *argv[2])) {
1670 while (*argv[2]) {
1671 if (*argv[2] == '@') {
1672 flags |= RUN_REQUEST_SILENT;
1673 } else if (*argv[2] == '?') {
1674 flags |= RUN_REQUEST_CONFIRM;
1675 } else if (*argv[2] == '<') {
1676 flags |= RUN_REQUEST_EXIT;
1677 } else if (*argv[2] != '!') {
1678 break;
1680 argv[2]++;
1683 } else if (*argv[2] == ':') {
1684 argv[2]++;
1685 flags |= RUN_REQUEST_INTERNAL;
1687 } else {
1688 return ERROR_UNKNOWN_REQUEST_NAME;
1691 return add_run_request(keymap, key, argv + 2, flags)
1692 ? SUCCESS : ERROR_OUT_OF_MEMORY;
1695 add_keybinding(keymap, request, key);
1697 return SUCCESS;
1701 static enum status_code load_option_file(const char *path);
1703 static enum status_code
1704 option_source_command(int argc, const char *argv[])
1706 if (argc < 1)
1707 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1709 return load_option_file(argv[0]);
1712 static enum status_code
1713 set_option(const char *opt, char *value)
1715 const char *argv[SIZEOF_ARG];
1716 int argc = 0;
1718 if (!argv_from_string(argv, &argc, value))
1719 return ERROR_TOO_MANY_OPTION_ARGUMENTS;
1721 if (!strcmp(opt, "color"))
1722 return option_color_command(argc, argv);
1724 if (!strcmp(opt, "set"))
1725 return option_set_command(argc, argv);
1727 if (!strcmp(opt, "bind"))
1728 return option_bind_command(argc, argv);
1730 if (!strcmp(opt, "source"))
1731 return option_source_command(argc, argv);
1733 return ERROR_UNKNOWN_OPTION_COMMAND;
1736 struct config_state {
1737 const char *path;
1738 int lineno;
1739 bool errors;
1742 static int
1743 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1745 struct config_state *config = data;
1746 enum status_code status = ERROR_NO_OPTION_VALUE;
1748 config->lineno++;
1750 /* Check for comment markers, since read_properties() will
1751 * only ensure opt and value are split at first " \t". */
1752 optlen = strcspn(opt, "#");
1753 if (optlen == 0)
1754 return OK;
1756 if (opt[optlen] == 0) {
1757 /* Look for comment endings in the value. */
1758 size_t len = strcspn(value, "#");
1760 if (len < valuelen) {
1761 valuelen = len;
1762 value[valuelen] = 0;
1765 status = set_option(opt, value);
1768 if (status != SUCCESS) {
1769 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1770 get_status_message(status), (int) optlen, opt);
1771 config->errors = TRUE;
1774 /* Always keep going if errors are encountered. */
1775 return OK;
1778 static enum status_code
1779 load_option_file(const char *path)
1781 struct config_state config = { path, 0, FALSE };
1782 struct io io;
1783 char buf[SIZEOF_STR];
1785 /* Do not read configuration from stdin if set to "" */
1786 if (!path || !strlen(path))
1787 return SUCCESS;
1789 if (!prefixcmp(path, "~/")) {
1790 const char *home = getenv("HOME");
1792 if (!home || !string_format(buf, "%s/%s", home, path + 2))
1793 return ERROR_HOME_UNRESOLVABLE;
1794 path = buf;
1797 /* It's OK that the file doesn't exist. */
1798 if (!io_open(&io, "%s", path))
1799 return ERROR_FILE_DOES_NOT_EXIST;
1801 if (io_load(&io, " \t", read_option, &config) == ERR ||
1802 config.errors == TRUE)
1803 warn("Errors while loading %s.", path);
1804 return SUCCESS;
1807 static int
1808 load_options(void)
1810 const char *tigrc_user = getenv("TIGRC_USER");
1811 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1812 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1813 const bool diff_opts_from_args = !!opt_diff_argv;
1815 if (!tigrc_system)
1816 tigrc_system = SYSCONFDIR "/tigrc";
1817 load_option_file(tigrc_system);
1819 if (!tigrc_user)
1820 tigrc_user = "~/.tigrc";
1821 load_option_file(tigrc_user);
1823 /* Add _after_ loading config files to avoid adding run requests
1824 * that conflict with keybindings. */
1825 add_builtin_run_requests();
1827 if (!diff_opts_from_args && tig_diff_opts && *tig_diff_opts) {
1828 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1829 char buf[SIZEOF_STR];
1830 int argc = 0;
1832 if (!string_format(buf, "%s", tig_diff_opts) ||
1833 !argv_from_string(diff_opts, &argc, buf))
1834 die("TIG_DIFF_OPTS contains too many arguments");
1835 else if (!argv_copy(&opt_diff_argv, diff_opts))
1836 die("Failed to format TIG_DIFF_OPTS arguments");
1839 return OK;
1844 * The viewer
1847 struct view;
1848 struct view_ops;
1850 /* The display array of active views and the index of the current view. */
1851 static struct view *display[2];
1852 static WINDOW *display_win[2];
1853 static WINDOW *display_title[2];
1854 static WINDOW *display_sep;
1856 static unsigned int current_view;
1858 #define foreach_displayed_view(view, i) \
1859 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1861 #define displayed_views() (display[1] != NULL ? 2 : 1)
1863 /* Current head and commit ID */
1864 static char ref_blob[SIZEOF_REF] = "";
1865 static char ref_commit[SIZEOF_REF] = "HEAD";
1866 static char ref_head[SIZEOF_REF] = "HEAD";
1867 static char ref_branch[SIZEOF_REF] = "";
1868 static char ref_status[SIZEOF_STR] = "";
1869 static char ref_stash[SIZEOF_REF] = "";
1871 enum view_flag {
1872 VIEW_NO_FLAGS = 0,
1873 VIEW_ALWAYS_LINENO = 1 << 0,
1874 VIEW_CUSTOM_STATUS = 1 << 1,
1875 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1876 VIEW_ADD_PAGER_REFS = 1 << 3,
1877 VIEW_OPEN_DIFF = 1 << 4,
1878 VIEW_NO_REF = 1 << 5,
1879 VIEW_NO_GIT_DIR = 1 << 6,
1880 VIEW_DIFF_LIKE = 1 << 7,
1881 VIEW_SEND_CHILD_ENTER = 1 << 9,
1882 VIEW_FILE_FILTER = 1 << 10,
1883 VIEW_LOG_LIKE = 1 << 11,
1884 VIEW_STATUS_LIKE = 1 << 12,
1887 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1889 struct position {
1890 unsigned long offset; /* Offset of the window top */
1891 unsigned long col; /* Offset from the window side. */
1892 unsigned long lineno; /* Current line number */
1895 struct view {
1896 const char *name; /* View name */
1897 const char *id; /* Points to either of ref_{head,commit,blob} */
1899 struct view_ops *ops; /* View operations */
1901 char ref[SIZEOF_REF]; /* Hovered commit reference */
1902 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1904 int height, width; /* The width and height of the main window */
1905 WINDOW *win; /* The main window */
1907 /* Navigation */
1908 struct position pos; /* Current position. */
1909 struct position prev_pos; /* Previous position. */
1911 /* Searching */
1912 char grep[SIZEOF_STR]; /* Search string */
1913 regex_t *regex; /* Pre-compiled regexp */
1915 /* If non-NULL, points to the view that opened this view. If this view
1916 * is closed tig will switch back to the parent view. */
1917 struct view *parent;
1918 struct view *prev;
1920 /* Buffering */
1921 size_t lines; /* Total number of lines */
1922 struct line *line; /* Line index */
1923 unsigned int digits; /* Number of digits in the lines member. */
1925 /* Number of lines with custom status, not to be counted in the
1926 * view title. */
1927 unsigned int custom_lines;
1929 /* Drawing */
1930 struct line *curline; /* Line currently being drawn. */
1931 enum line_type curtype; /* Attribute currently used for drawing. */
1932 unsigned long col; /* Column when drawing. */
1933 bool has_scrolled; /* View was scrolled. */
1934 bool force_redraw; /* Whether to force a redraw after reading. */
1936 /* Loading */
1937 const char **argv; /* Shell command arguments. */
1938 const char *dir; /* Directory from which to execute. */
1939 struct io io;
1940 struct io *pipe;
1941 time_t start_time;
1942 time_t update_secs;
1943 struct encoding *encoding;
1944 bool unrefreshable;
1946 /* Private data */
1947 void *private;
1950 enum open_flags {
1951 OPEN_DEFAULT = 0, /* Use default view switching. */
1952 OPEN_STDIN = 1, /* Open in pager mode. */
1953 OPEN_FORWARD_STDIN = 2, /* Forward stdin to I/O process. */
1954 OPEN_SPLIT = 4, /* Split current view. */
1955 OPEN_RELOAD = 8, /* Reload view even if it is the current. */
1956 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1957 OPEN_PREPARED = 32, /* Open already prepared command. */
1958 OPEN_EXTRA = 64, /* Open extra data from command. */
1960 OPEN_PAGER_MODE = OPEN_STDIN | OPEN_FORWARD_STDIN,
1963 #define open_in_pager_mode(flags) ((flags) & OPEN_PAGER_MODE)
1964 #define open_from_stdin(flags) ((flags) & OPEN_STDIN)
1966 struct view_ops {
1967 /* What type of content being displayed. Used in the title bar. */
1968 const char *type;
1969 /* What keymap does this view have */
1970 struct keymap keymap;
1971 /* Flags to control the view behavior. */
1972 enum view_flag flags;
1973 /* Size of private data. */
1974 size_t private_size;
1975 /* Open and reads in all view content. */
1976 bool (*open)(struct view *view, enum open_flags flags);
1977 /* Read one line; updates view->line. */
1978 bool (*read)(struct view *view, char *data);
1979 /* Draw one line; @lineno must be < view->height. */
1980 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1981 /* Depending on view handle a special requests. */
1982 enum request (*request)(struct view *view, enum request request, struct line *line);
1983 /* Search for regexp in a line. */
1984 bool (*grep)(struct view *view, struct line *line);
1985 /* Select line */
1986 void (*select)(struct view *view, struct line *line);
1987 /* Release resources when reloading the view */
1988 void (*done)(struct view *view);
1991 #define VIEW_OPS(id, name, ref) name##_ops
1992 static struct view_ops VIEW_INFO(VIEW_OPS);
1994 static struct view views[] = {
1995 #define VIEW_DATA(id, name, ref) \
1996 { #name, ref, &name##_ops }
1997 VIEW_INFO(VIEW_DATA)
2000 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
2002 #define foreach_view(view, i) \
2003 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2005 #define view_is_displayed(view) \
2006 (view == display[0] || view == display[1])
2008 #define view_has_line(view, line_) \
2009 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
2011 static bool
2012 forward_request_to_child(struct view *child, enum request request)
2014 return displayed_views() == 2 && view_is_displayed(child) &&
2015 !strcmp(child->vid, child->id);
2018 static enum request
2019 view_request(struct view *view, enum request request)
2021 if (!view || !view->lines)
2022 return request;
2024 if (request == REQ_ENTER && !opt_focus_child &&
2025 view_has_flags(view, VIEW_SEND_CHILD_ENTER)) {
2026 struct view *child = display[1];
2028 if (forward_request_to_child(child, request)) {
2029 view_request(child, request);
2030 return REQ_NONE;
2034 if (request == REQ_REFRESH && view->unrefreshable) {
2035 report("This view can not be refreshed");
2036 return REQ_NONE;
2039 return view->ops->request(view, request, &view->line[view->pos.lineno]);
2043 * View drawing.
2046 static inline void
2047 set_view_attr(struct view *view, enum line_type type)
2049 if (!view->curline->selected && view->curtype != type) {
2050 (void) wattrset(view->win, get_line_attr(type));
2051 wchgat(view->win, -1, 0, get_line_color(type), NULL);
2052 view->curtype = type;
2056 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
2058 static bool
2059 draw_chars(struct view *view, enum line_type type, const char *string,
2060 int max_len, bool use_tilde)
2062 int len = 0;
2063 int col = 0;
2064 int trimmed = FALSE;
2065 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2067 if (max_len <= 0)
2068 return VIEW_MAX_LEN(view) <= 0;
2070 if (opt_iconv_out != ICONV_NONE) {
2071 string = encoding_iconv(opt_iconv_out, string);
2072 if (!string)
2073 return VIEW_MAX_LEN(view) <= 0;
2076 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
2078 set_view_attr(view, type);
2079 if (len > 0) {
2080 waddnstr(view->win, string, len);
2082 if (trimmed && use_tilde) {
2083 set_view_attr(view, LINE_DELIMITER);
2084 waddch(view->win, '~');
2085 col++;
2089 view->col += col;
2090 return VIEW_MAX_LEN(view) <= 0;
2093 static bool
2094 draw_space(struct view *view, enum line_type type, int max, int spaces)
2096 static char space[] = " ";
2098 spaces = MIN(max, spaces);
2100 while (spaces > 0) {
2101 int len = MIN(spaces, sizeof(space) - 1);
2103 if (draw_chars(view, type, space, len, FALSE))
2104 return TRUE;
2105 spaces -= len;
2108 return VIEW_MAX_LEN(view) <= 0;
2111 static bool
2112 draw_text_expanded(struct view *view, enum line_type type, const char *string, int max_len, bool use_tilde)
2114 static char text[SIZEOF_STR];
2116 do {
2117 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
2119 if (draw_chars(view, type, text, max_len, use_tilde))
2120 return TRUE;
2121 string += pos;
2122 } while (*string);
2124 return VIEW_MAX_LEN(view) <= 0;
2127 static bool
2128 draw_text(struct view *view, enum line_type type, const char *string)
2130 return draw_text_expanded(view, type, string, VIEW_MAX_LEN(view), TRUE);
2133 static bool
2134 draw_text_overflow(struct view *view, const char *text, bool on, int overflow, enum line_type type)
2136 if (on) {
2137 int max = MIN(VIEW_MAX_LEN(view), overflow);
2138 int len = strlen(text);
2140 if (draw_text_expanded(view, type, text, max, max < overflow))
2141 return TRUE;
2143 text = len > overflow ? text + overflow : "";
2144 type = LINE_OVERFLOW;
2147 if (*text && draw_text(view, type, text))
2148 return TRUE;
2150 return VIEW_MAX_LEN(view) <= 0;
2153 #define draw_commit_title(view, text, offset) \
2154 draw_text_overflow(view, text, opt_show_title_overflow, opt_title_overflow + offset, LINE_DEFAULT)
2156 static bool PRINTF_LIKE(3, 4)
2157 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
2159 char text[SIZEOF_STR];
2160 int retval;
2162 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
2163 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
2166 static bool
2167 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
2169 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2170 int max = VIEW_MAX_LEN(view);
2171 int i;
2173 if (max < size)
2174 size = max;
2176 set_view_attr(view, type);
2177 /* Using waddch() instead of waddnstr() ensures that
2178 * they'll be rendered correctly for the cursor line. */
2179 for (i = skip; i < size; i++)
2180 waddch(view->win, graphic[i]);
2182 view->col += size;
2183 if (separator) {
2184 if (size < max && skip <= size)
2185 waddch(view->win, ' ');
2186 view->col++;
2189 return VIEW_MAX_LEN(view) <= 0;
2192 enum align {
2193 ALIGN_LEFT,
2194 ALIGN_RIGHT
2197 static bool
2198 draw_field(struct view *view, enum line_type type, const char *text, int width, enum align align, bool trim)
2200 int max = MIN(VIEW_MAX_LEN(view), width + 1);
2201 int col = view->col;
2203 if (!text)
2204 return draw_space(view, type, max, max);
2206 if (align == ALIGN_RIGHT) {
2207 int textlen = strlen(text);
2208 int leftpad = max - textlen - 1;
2210 if (leftpad > 0) {
2211 if (draw_space(view, type, leftpad, leftpad))
2212 return TRUE;
2213 max -= leftpad;
2214 col += leftpad;;
2218 return draw_chars(view, type, text, max - 1, trim)
2219 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2222 static bool
2223 draw_date(struct view *view, struct time *time)
2225 const char *date = mkdate(time, opt_date);
2226 int cols = opt_date == DATE_SHORT ? DATE_SHORT_WIDTH : DATE_WIDTH;
2228 if (opt_date == DATE_NO)
2229 return FALSE;
2231 return draw_field(view, LINE_DATE, date, cols, ALIGN_LEFT, FALSE);
2234 static bool
2235 draw_author(struct view *view, const struct ident *author)
2237 bool trim = author_trim(opt_author_width);
2238 const char *text = mkauthor(author, opt_author_width, opt_author);
2240 if (opt_author == AUTHOR_NO)
2241 return FALSE;
2243 return draw_field(view, LINE_AUTHOR, text, opt_author_width, ALIGN_LEFT, trim);
2246 static bool
2247 draw_id_custom(struct view *view, enum line_type type, const char *id, int width)
2249 return draw_field(view, type, id, width, ALIGN_LEFT, FALSE);
2252 static bool
2253 draw_id(struct view *view, const char *id)
2255 if (!opt_show_id)
2256 return FALSE;
2258 return draw_id_custom(view, LINE_ID, id, opt_id_cols);
2261 static bool
2262 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2264 bool trim = filename && strlen(filename) >= opt_filename_width;
2266 if (opt_filename == FILENAME_NO)
2267 return FALSE;
2269 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2270 return FALSE;
2272 return draw_field(view, LINE_FILENAME, filename, opt_filename_width, ALIGN_LEFT, trim);
2275 static bool
2276 draw_file_size(struct view *view, unsigned long size, int width, bool pad)
2278 const char *str = pad ? NULL : mkfilesize(size, opt_file_size);
2280 if (!width || opt_file_size == FILE_SIZE_NO)
2281 return FALSE;
2283 return draw_field(view, LINE_FILE_SIZE, str, width, ALIGN_RIGHT, FALSE);
2286 static bool
2287 draw_mode(struct view *view, mode_t mode)
2289 const char *str = mkmode(mode);
2291 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r--"), ALIGN_LEFT, FALSE);
2294 static bool
2295 draw_lineno(struct view *view, unsigned int lineno)
2297 char number[10];
2298 int digits3 = view->digits < 3 ? 3 : view->digits;
2299 int max = MIN(VIEW_MAX_LEN(view), digits3);
2300 char *text = NULL;
2301 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2303 if (!opt_line_number)
2304 return FALSE;
2306 lineno += view->pos.offset + 1;
2307 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2308 static char fmt[] = "%1ld";
2310 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2311 if (string_format(number, fmt, lineno))
2312 text = number;
2314 if (text)
2315 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2316 else
2317 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2318 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2321 static bool
2322 draw_refs(struct view *view, struct ref_list *refs)
2324 size_t i;
2326 if (!opt_show_refs || !refs)
2327 return FALSE;
2329 for (i = 0; i < refs->size; i++) {
2330 struct ref *ref = refs->refs[i];
2331 enum line_type type = get_line_type_from_ref(ref);
2333 if (draw_formatted(view, type, "[%s]", ref->name))
2334 return TRUE;
2336 if (draw_text(view, LINE_DEFAULT, " "))
2337 return TRUE;
2340 return FALSE;
2343 static bool
2344 draw_view_line(struct view *view, unsigned int lineno)
2346 struct line *line;
2347 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2349 assert(view_is_displayed(view));
2351 if (view->pos.offset + lineno >= view->lines)
2352 return FALSE;
2354 line = &view->line[view->pos.offset + lineno];
2356 wmove(view->win, lineno, 0);
2357 if (line->cleareol)
2358 wclrtoeol(view->win);
2359 view->col = 0;
2360 view->curline = line;
2361 view->curtype = LINE_NONE;
2362 line->selected = FALSE;
2363 line->dirty = line->cleareol = 0;
2365 if (selected) {
2366 set_view_attr(view, LINE_CURSOR);
2367 line->selected = TRUE;
2368 view->ops->select(view, line);
2371 return view->ops->draw(view, line, lineno);
2374 static void
2375 redraw_view_dirty(struct view *view)
2377 bool dirty = FALSE;
2378 int lineno;
2380 for (lineno = 0; lineno < view->height; lineno++) {
2381 if (view->pos.offset + lineno >= view->lines)
2382 break;
2383 if (!view->line[view->pos.offset + lineno].dirty)
2384 continue;
2385 dirty = TRUE;
2386 if (!draw_view_line(view, lineno))
2387 break;
2390 if (!dirty)
2391 return;
2392 wnoutrefresh(view->win);
2395 static void
2396 redraw_view_from(struct view *view, int lineno)
2398 assert(0 <= lineno && lineno < view->height);
2400 for (; lineno < view->height; lineno++) {
2401 if (!draw_view_line(view, lineno))
2402 break;
2405 wnoutrefresh(view->win);
2408 static void
2409 redraw_view(struct view *view)
2411 werase(view->win);
2412 redraw_view_from(view, 0);
2416 static void
2417 update_view_title(struct view *view)
2419 char buf[SIZEOF_STR];
2420 char state[SIZEOF_STR];
2421 size_t bufpos = 0, statelen = 0;
2422 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2423 struct line *line = &view->line[view->pos.lineno];
2425 assert(view_is_displayed(view));
2427 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view_has_line(view, line) &&
2428 line->lineno) {
2429 unsigned int view_lines = view->pos.offset + view->height;
2430 unsigned int lines = view->lines
2431 ? MIN(view_lines, view->lines) * 100 / view->lines
2432 : 0;
2434 string_format_from(state, &statelen, " - %s %d of %zd (%d%%)",
2435 view->ops->type,
2436 line->lineno,
2437 view->lines - view->custom_lines,
2438 lines);
2442 if (view->pipe) {
2443 time_t secs = time(NULL) - view->start_time;
2445 /* Three git seconds are a long time ... */
2446 if (secs > 2)
2447 string_format_from(state, &statelen, " loading %lds", secs);
2450 string_format_from(buf, &bufpos, "[%s]", view->name);
2451 if (*view->ref && bufpos < view->width) {
2452 size_t refsize = strlen(view->ref);
2453 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2455 if (minsize < view->width)
2456 refsize = view->width - minsize + 7;
2457 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2460 if (statelen && bufpos < view->width) {
2461 string_format_from(buf, &bufpos, "%s", state);
2464 if (view == display[current_view])
2465 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2466 else
2467 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2469 mvwaddnstr(window, 0, 0, buf, bufpos);
2470 wclrtoeol(window);
2471 wnoutrefresh(window);
2474 static int
2475 apply_step(double step, int value)
2477 if (step >= 1)
2478 return (int) step;
2479 value *= step + 0.01;
2480 return value ? value : 1;
2483 static void
2484 apply_horizontal_split(struct view *base, struct view *view)
2486 view->width = base->width;
2487 view->height = apply_step(opt_scale_split_view, base->height);
2488 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2489 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2490 base->height -= view->height;
2493 static void
2494 apply_vertical_split(struct view *base, struct view *view)
2496 view->height = base->height;
2497 view->width = apply_step(opt_scale_vsplit_view, base->width);
2498 view->width = MAX(view->width, MIN_VIEW_WIDTH);
2499 view->width = MIN(view->width, base->width - MIN_VIEW_WIDTH);
2500 base->width -= view->width;
2503 static void
2504 redraw_display_separator(bool clear)
2506 if (displayed_views() > 1 && opt_vsplit) {
2507 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2509 if (clear)
2510 wclear(display_sep);
2511 wbkgd(display_sep, separator + get_line_attr(LINE_TITLE_BLUR));
2512 wnoutrefresh(display_sep);
2516 static void
2517 resize_display(void)
2519 int x, y, i;
2520 struct view *base = display[0];
2521 struct view *view = display[1] ? display[1] : display[0];
2523 /* Setup window dimensions */
2525 getmaxyx(stdscr, base->height, base->width);
2526 string_format(opt_env_columns, "COLUMNS=%d", base->width);
2527 string_format(opt_env_lines, "LINES=%d", base->height);
2529 /* Make room for the status window. */
2530 base->height -= 1;
2532 if (view != base) {
2533 if (opt_vsplit) {
2534 apply_vertical_split(base, view);
2536 /* Make room for the separator bar. */
2537 view->width -= 1;
2538 } else {
2539 apply_horizontal_split(base, view);
2542 /* Make room for the title bar. */
2543 view->height -= 1;
2546 /* Make room for the title bar. */
2547 base->height -= 1;
2549 x = y = 0;
2551 foreach_displayed_view (view, i) {
2552 if (!display_win[i]) {
2553 display_win[i] = newwin(view->height, view->width, y, x);
2554 if (!display_win[i])
2555 die("Failed to create %s view", view->name);
2557 scrollok(display_win[i], FALSE);
2559 display_title[i] = newwin(1, view->width, y + view->height, x);
2560 if (!display_title[i])
2561 die("Failed to create title window");
2563 } else {
2564 wresize(display_win[i], view->height, view->width);
2565 mvwin(display_win[i], y, x);
2566 wresize(display_title[i], 1, view->width);
2567 mvwin(display_title[i], y + view->height, x);
2570 if (i > 0 && opt_vsplit) {
2571 if (!display_sep) {
2572 display_sep = newwin(view->height, 1, 0, x - 1);
2573 if (!display_sep)
2574 die("Failed to create separator window");
2576 } else {
2577 wresize(display_sep, view->height, 1);
2578 mvwin(display_sep, 0, x - 1);
2582 view->win = display_win[i];
2584 if (opt_vsplit)
2585 x += view->width + 1;
2586 else
2587 y += view->height + 1;
2590 redraw_display_separator(FALSE);
2593 static void
2594 redraw_display(bool clear)
2596 struct view *view;
2597 int i;
2599 foreach_displayed_view (view, i) {
2600 if (clear)
2601 wclear(view->win);
2602 redraw_view(view);
2603 update_view_title(view);
2606 redraw_display_separator(clear);
2610 * Option management
2613 #define TOGGLE_MENU_INFO(_) \
2614 _(LINENO, '.', "line numbers", &opt_line_number, NULL, 0, VIEW_NO_FLAGS), \
2615 _(DATE, 'D', "dates", &opt_date, date_map, ARRAY_SIZE(date_map), VIEW_NO_FLAGS), \
2616 _(AUTHOR, 'A', "author", &opt_author, author_map, ARRAY_SIZE(author_map), VIEW_NO_FLAGS), \
2617 _(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map, ARRAY_SIZE(graphic_map), VIEW_NO_FLAGS), \
2618 _(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL, 0, VIEW_LOG_LIKE), \
2619 _(FILENAME, '#', "file names", &opt_filename, filename_map, ARRAY_SIZE(filename_map), VIEW_NO_FLAGS), \
2620 _(FILE_SIZE, '*', "file sizes", &opt_file_size, file_size_map, ARRAY_SIZE(file_size_map), VIEW_NO_FLAGS), \
2621 _(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map, ARRAY_SIZE(ignore_space_map), VIEW_DIFF_LIKE), \
2622 _(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map, ARRAY_SIZE(commit_order_map), VIEW_LOG_LIKE), \
2623 _(REFS, 'F', "reference display", &opt_show_refs, NULL, 0, VIEW_NO_FLAGS), \
2624 _(CHANGES, 'C', "local change display", &opt_show_changes, NULL, 0, VIEW_NO_FLAGS), \
2625 _(ID, 'X', "commit ID display", &opt_show_id, NULL, 0, VIEW_NO_FLAGS), \
2626 _(FILES, '%', "file filtering", &opt_file_filter, NULL, 0, VIEW_DIFF_LIKE | VIEW_LOG_LIKE), \
2627 _(TITLE_OVERFLOW, '$', "commit title overflow display", &opt_show_title_overflow, NULL, 0, VIEW_NO_FLAGS), \
2628 _(UNTRACKED_DIRS, 'd', "untracked directory info", &opt_untracked_dirs_content, NULL, 0, VIEW_STATUS_LIKE), \
2630 static enum view_flag
2631 toggle_option(struct view *view, enum request request, char msg[SIZEOF_STR])
2633 const struct {
2634 enum request request;
2635 const struct enum_map *map;
2636 size_t map_size;
2637 enum view_flag reload_flags;
2638 } data[] = {
2639 #define DEFINE_TOGGLE_DATA(id, key, help, value, map, map_size, vflags) { REQ_TOGGLE_ ## id, map, map_size, vflags }
2640 TOGGLE_MENU_INFO(DEFINE_TOGGLE_DATA)
2642 const struct menu_item menu[] = {
2643 #define DEFINE_TOGGLE_MENU(id, key, help, value, map, map_size, vflags) { key, help, value }
2644 TOGGLE_MENU_INFO(DEFINE_TOGGLE_MENU)
2645 { 0 }
2647 int i = 0;
2649 if (request == REQ_OPTIONS) {
2650 if (!prompt_menu("Toggle option", menu, &i))
2651 return VIEW_NO_FLAGS;
2652 } else {
2653 while (i < ARRAY_SIZE(data) && data[i].request != request)
2654 i++;
2655 if (i >= ARRAY_SIZE(data))
2656 die("Invalid request (%d)", request);
2659 if (data[i].map != NULL) {
2660 unsigned int *opt = menu[i].data;
2662 *opt = (*opt + 1) % data[i].map_size;
2663 if (data[i].map == ignore_space_map) {
2664 update_ignore_space_arg();
2665 string_format_size(msg, SIZEOF_STR,
2666 "Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2668 } else if (data[i].map == commit_order_map) {
2669 update_commit_order_arg();
2670 string_format_size(msg, SIZEOF_STR,
2671 "Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2673 } else {
2674 string_format_size(msg, SIZEOF_STR,
2675 "Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2678 } else {
2679 bool *option = menu[i].data;
2681 *option = !*option;
2682 string_format_size(msg, SIZEOF_STR,
2683 "%sabling %s", *option ? "En" : "Dis", menu[i].text);
2686 return data[i].reload_flags;
2691 * Navigation
2694 static bool
2695 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2697 if (lineno >= view->lines)
2698 lineno = view->lines > 0 ? view->lines - 1 : 0;
2700 if (offset > lineno || offset + view->height <= lineno) {
2701 unsigned long half = view->height / 2;
2703 if (lineno > half)
2704 offset = lineno - half;
2705 else
2706 offset = 0;
2709 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2710 view->pos.offset = offset;
2711 view->pos.lineno = lineno;
2712 return TRUE;
2715 return FALSE;
2718 /* Scrolling backend */
2719 static void
2720 do_scroll_view(struct view *view, int lines)
2722 bool redraw_current_line = FALSE;
2724 /* The rendering expects the new offset. */
2725 view->pos.offset += lines;
2727 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2728 assert(lines);
2730 /* Move current line into the view. */
2731 if (view->pos.lineno < view->pos.offset) {
2732 view->pos.lineno = view->pos.offset;
2733 redraw_current_line = TRUE;
2734 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2735 view->pos.lineno = view->pos.offset + view->height - 1;
2736 redraw_current_line = TRUE;
2739 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2741 /* Redraw the whole screen if scrolling is pointless. */
2742 if (view->height < ABS(lines)) {
2743 redraw_view(view);
2745 } else {
2746 int line = lines > 0 ? view->height - lines : 0;
2747 int end = line + ABS(lines);
2749 scrollok(view->win, TRUE);
2750 wscrl(view->win, lines);
2751 scrollok(view->win, FALSE);
2753 while (line < end && draw_view_line(view, line))
2754 line++;
2756 if (redraw_current_line)
2757 draw_view_line(view, view->pos.lineno - view->pos.offset);
2758 wnoutrefresh(view->win);
2761 view->has_scrolled = TRUE;
2762 report_clear();
2765 /* Scroll frontend */
2766 static void
2767 scroll_view(struct view *view, enum request request)
2769 int lines = 1;
2771 assert(view_is_displayed(view));
2773 switch (request) {
2774 case REQ_SCROLL_FIRST_COL:
2775 view->pos.col = 0;
2776 redraw_view_from(view, 0);
2777 report_clear();
2778 return;
2779 case REQ_SCROLL_LEFT:
2780 if (view->pos.col == 0) {
2781 report("Cannot scroll beyond the first column");
2782 return;
2784 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2785 view->pos.col = 0;
2786 else
2787 view->pos.col -= apply_step(opt_hscroll, view->width);
2788 redraw_view_from(view, 0);
2789 report_clear();
2790 return;
2791 case REQ_SCROLL_RIGHT:
2792 view->pos.col += apply_step(opt_hscroll, view->width);
2793 redraw_view(view);
2794 report_clear();
2795 return;
2796 case REQ_SCROLL_PAGE_DOWN:
2797 lines = view->height;
2798 case REQ_SCROLL_LINE_DOWN:
2799 if (view->pos.offset + lines > view->lines)
2800 lines = view->lines - view->pos.offset;
2802 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2803 report("Cannot scroll beyond the last line");
2804 return;
2806 break;
2808 case REQ_SCROLL_PAGE_UP:
2809 lines = view->height;
2810 case REQ_SCROLL_LINE_UP:
2811 if (lines > view->pos.offset)
2812 lines = view->pos.offset;
2814 if (lines == 0) {
2815 report("Cannot scroll beyond the first line");
2816 return;
2819 lines = -lines;
2820 break;
2822 default:
2823 die("request %d not handled in switch", request);
2826 do_scroll_view(view, lines);
2829 /* Cursor moving */
2830 static void
2831 move_view(struct view *view, enum request request)
2833 int scroll_steps = 0;
2834 int steps;
2836 switch (request) {
2837 case REQ_MOVE_FIRST_LINE:
2838 steps = -view->pos.lineno;
2839 break;
2841 case REQ_MOVE_LAST_LINE:
2842 steps = view->lines - view->pos.lineno - 1;
2843 break;
2845 case REQ_MOVE_PAGE_UP:
2846 steps = view->height > view->pos.lineno
2847 ? -view->pos.lineno : -view->height;
2848 break;
2850 case REQ_MOVE_PAGE_DOWN:
2851 steps = view->pos.lineno + view->height >= view->lines
2852 ? view->lines - view->pos.lineno - 1 : view->height;
2853 break;
2855 case REQ_MOVE_UP:
2856 case REQ_PREVIOUS:
2857 steps = -1;
2858 break;
2860 case REQ_MOVE_DOWN:
2861 case REQ_NEXT:
2862 steps = 1;
2863 break;
2865 default:
2866 die("request %d not handled in switch", request);
2869 if (steps <= 0 && view->pos.lineno == 0) {
2870 report("Cannot move beyond the first line");
2871 return;
2873 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2874 report("Cannot move beyond the last line");
2875 return;
2878 /* Move the current line */
2879 view->pos.lineno += steps;
2880 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2882 /* Check whether the view needs to be scrolled */
2883 if (view->pos.lineno < view->pos.offset ||
2884 view->pos.lineno >= view->pos.offset + view->height) {
2885 scroll_steps = steps;
2886 if (steps < 0 && -steps > view->pos.offset) {
2887 scroll_steps = -view->pos.offset;
2889 } else if (steps > 0) {
2890 if (view->pos.lineno == view->lines - 1 &&
2891 view->lines > view->height) {
2892 scroll_steps = view->lines - view->pos.offset - 1;
2893 if (scroll_steps >= view->height)
2894 scroll_steps -= view->height - 1;
2899 if (!view_is_displayed(view)) {
2900 view->pos.offset += scroll_steps;
2901 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2902 view->ops->select(view, &view->line[view->pos.lineno]);
2903 return;
2906 /* Repaint the old "current" line if we be scrolling */
2907 if (ABS(steps) < view->height)
2908 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2910 if (scroll_steps) {
2911 do_scroll_view(view, scroll_steps);
2912 return;
2915 /* Draw the current line */
2916 draw_view_line(view, view->pos.lineno - view->pos.offset);
2918 wnoutrefresh(view->win);
2919 report_clear();
2924 * Searching
2927 static void search_view(struct view *view, enum request request);
2929 static bool
2930 grep_text(struct view *view, const char *text[])
2932 regmatch_t pmatch;
2933 size_t i;
2935 for (i = 0; text[i]; i++)
2936 if (*text[i] && !regexec(view->regex, text[i], 1, &pmatch, 0))
2937 return TRUE;
2938 return FALSE;
2941 static void
2942 select_view_line(struct view *view, unsigned long lineno)
2944 struct position old = view->pos;
2946 if (goto_view_line(view, view->pos.offset, lineno)) {
2947 if (view_is_displayed(view)) {
2948 if (old.offset != view->pos.offset) {
2949 redraw_view(view);
2950 } else {
2951 draw_view_line(view, old.lineno - view->pos.offset);
2952 draw_view_line(view, view->pos.lineno - view->pos.offset);
2953 wnoutrefresh(view->win);
2955 } else {
2956 view->ops->select(view, &view->line[view->pos.lineno]);
2961 static void
2962 find_next(struct view *view, enum request request)
2964 unsigned long lineno = view->pos.lineno;
2965 int direction;
2967 if (!*view->grep) {
2968 if (!*opt_search)
2969 report("No previous search");
2970 else
2971 search_view(view, request);
2972 return;
2975 switch (request) {
2976 case REQ_SEARCH:
2977 case REQ_FIND_NEXT:
2978 direction = 1;
2979 break;
2981 case REQ_SEARCH_BACK:
2982 case REQ_FIND_PREV:
2983 direction = -1;
2984 break;
2986 default:
2987 return;
2990 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2991 lineno += direction;
2993 /* Note, lineno is unsigned long so will wrap around in which case it
2994 * will become bigger than view->lines. */
2995 for (; lineno < view->lines; lineno += direction) {
2996 if (view->ops->grep(view, &view->line[lineno])) {
2997 select_view_line(view, lineno);
2998 report("Line %ld matches '%s'", lineno + 1, view->grep);
2999 return;
3003 report("No match found for '%s'", view->grep);
3006 static void
3007 search_view(struct view *view, enum request request)
3009 int regex_err;
3010 int regex_flags = opt_ignore_case ? REG_ICASE : 0;
3012 if (view->regex) {
3013 regfree(view->regex);
3014 *view->grep = 0;
3015 } else {
3016 view->regex = calloc(1, sizeof(*view->regex));
3017 if (!view->regex)
3018 return;
3021 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED | regex_flags);
3022 if (regex_err != 0) {
3023 char buf[SIZEOF_STR] = "unknown error";
3025 regerror(regex_err, view->regex, buf, sizeof(buf));
3026 report("Search failed: %s", buf);
3027 return;
3030 string_copy(view->grep, opt_search);
3032 find_next(view, request);
3036 * Incremental updating
3039 static inline bool
3040 check_position(struct position *pos)
3042 return pos->lineno || pos->col || pos->offset;
3045 static inline void
3046 clear_position(struct position *pos)
3048 memset(pos, 0, sizeof(*pos));
3051 static void
3052 reset_view(struct view *view)
3054 int i;
3056 if (view->ops->done)
3057 view->ops->done(view);
3059 for (i = 0; i < view->lines; i++)
3060 free(view->line[i].data);
3061 free(view->line);
3063 view->prev_pos = view->pos;
3064 clear_position(&view->pos);
3066 view->line = NULL;
3067 view->lines = 0;
3068 view->vid[0] = 0;
3069 view->custom_lines = 0;
3070 view->update_secs = 0;
3073 struct format_context {
3074 struct view *view;
3075 char buf[SIZEOF_STR];
3076 size_t bufpos;
3077 bool file_filter;
3080 static bool
3081 format_expand_arg(struct format_context *format, const char *name)
3083 static struct {
3084 const char *name;
3085 size_t namelen;
3086 const char *value;
3087 const char *value_if_empty;
3088 } vars[] = {
3089 #define FORMAT_VAR(name, value, value_if_empty) \
3090 { name, STRING_SIZE(name), value, value_if_empty }
3091 FORMAT_VAR("%(directory)", opt_path, "."),
3092 FORMAT_VAR("%(file)", opt_file, ""),
3093 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
3094 FORMAT_VAR("%(head)", ref_head, ""),
3095 FORMAT_VAR("%(commit)", ref_commit, ""),
3096 FORMAT_VAR("%(blob)", ref_blob, ""),
3097 FORMAT_VAR("%(branch)", ref_branch, ""),
3098 FORMAT_VAR("%(stash)", ref_stash, ""),
3100 int i;
3102 if (!prefixcmp(name, "%(prompt)")) {
3103 const char *value = read_prompt("Command argument: ");
3105 return string_format_from(format->buf, &format->bufpos, "%s", value);
3108 for (i = 0; i < ARRAY_SIZE(vars); i++) {
3109 const char *value;
3111 if (strncmp(name, vars[i].name, vars[i].namelen))
3112 continue;
3114 if (vars[i].value == opt_file && !format->file_filter)
3115 return TRUE;
3117 value = *vars[i].value ? vars[i].value : vars[i].value_if_empty;
3118 if (!*value)
3119 return TRUE;
3121 return string_format_from(format->buf, &format->bufpos, "%s", value);
3124 report("Unknown replacement: `%s`", name);
3125 return NULL;
3128 static bool
3129 format_append_arg(struct format_context *format, const char ***dst_argv, const char *arg)
3131 memset(format->buf, 0, sizeof(format->buf));
3132 format->bufpos = 0;
3134 while (arg) {
3135 char *next = strstr(arg, "%(");
3136 int len = next ? next - arg : strlen(arg);
3138 if (len && !string_format_from(format->buf, &format->bufpos, "%.*s", len, arg))
3139 return FALSE;
3141 if (next && !format_expand_arg(format, next))
3142 return FALSE;
3144 arg = next ? strchr(next, ')') + 1 : NULL;
3147 return argv_append(dst_argv, format->buf);
3150 static bool
3151 format_append_argv(struct format_context *format, const char ***dst_argv, const char *src_argv[])
3153 int argc;
3155 if (!src_argv)
3156 return TRUE;
3158 for (argc = 0; src_argv[argc]; argc++)
3159 if (!format_append_arg(format, dst_argv, src_argv[argc]))
3160 return FALSE;
3162 return src_argv[argc] == NULL;
3165 static bool
3166 format_argv(struct view *view, const char ***dst_argv, const char *src_argv[], bool first, bool file_filter)
3168 struct format_context format = { view, "", 0, file_filter };
3169 int argc;
3171 argv_free(*dst_argv);
3173 for (argc = 0; src_argv[argc]; argc++) {
3174 const char *arg = src_argv[argc];
3176 if (!strcmp(arg, "%(fileargs)")) {
3177 if (file_filter && !argv_append_array(dst_argv, opt_file_argv))
3178 break;
3180 } else if (!strcmp(arg, "%(diffargs)")) {
3181 if (!format_append_argv(&format, dst_argv, opt_diff_argv))
3182 break;
3184 } else if (!strcmp(arg, "%(blameargs)")) {
3185 if (!format_append_argv(&format, dst_argv, opt_blame_argv))
3186 break;
3188 } else if (!strcmp(arg, "%(revargs)") ||
3189 (first && !strcmp(arg, "%(commit)"))) {
3190 if (!argv_append_array(dst_argv, opt_rev_argv))
3191 break;
3193 } else if (!format_append_arg(&format, dst_argv, arg)) {
3194 break;
3198 return src_argv[argc] == NULL;
3201 static bool
3202 restore_view_position(struct view *view)
3204 /* A view without a previous view is the first view */
3205 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
3206 select_view_line(view, opt_lineno - 1);
3207 opt_lineno = 0;
3210 /* Ensure that the view position is in a valid state. */
3211 if (!check_position(&view->prev_pos) ||
3212 (view->pipe && view->lines <= view->prev_pos.lineno))
3213 return goto_view_line(view, view->pos.offset, view->pos.lineno);
3215 /* Changing the view position cancels the restoring. */
3216 /* FIXME: Changing back to the first line is not detected. */
3217 if (check_position(&view->pos)) {
3218 clear_position(&view->prev_pos);
3219 return FALSE;
3222 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
3223 view_is_displayed(view))
3224 werase(view->win);
3226 view->pos.col = view->prev_pos.col;
3227 clear_position(&view->prev_pos);
3229 return TRUE;
3232 static void
3233 end_update(struct view *view, bool force)
3235 if (!view->pipe)
3236 return;
3237 while (!view->ops->read(view, NULL))
3238 if (!force)
3239 return;
3240 if (force)
3241 io_kill(view->pipe);
3242 io_done(view->pipe);
3243 view->pipe = NULL;
3246 static void
3247 setup_update(struct view *view, const char *vid)
3249 reset_view(view);
3250 /* XXX: Do not use string_copy_rev(), it copies until first space. */
3251 string_ncopy(view->vid, vid, strlen(vid));
3252 view->pipe = &view->io;
3253 view->start_time = time(NULL);
3256 static bool
3257 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
3259 bool extra = !!(flags & (OPEN_EXTRA));
3260 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA | OPEN_PAGER_MODE));
3261 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED | OPEN_STDIN);
3262 bool forward_stdin = flags & OPEN_FORWARD_STDIN;
3263 enum io_type io_type = forward_stdin ? IO_RD_STDIN : IO_RD;
3265 if ((!reload && !strcmp(view->vid, view->id)) ||
3266 ((flags & OPEN_REFRESH) && view->unrefreshable))
3267 return TRUE;
3269 if (view->pipe) {
3270 if (extra)
3271 io_done(view->pipe);
3272 else
3273 end_update(view, TRUE);
3276 view->unrefreshable = open_in_pager_mode(flags);
3278 if (!refresh && argv) {
3279 bool file_filter = !view_has_flags(view, VIEW_FILE_FILTER) || opt_file_filter;
3281 view->dir = dir;
3282 if (!format_argv(view, &view->argv, argv, !view->prev, file_filter)) {
3283 report("Failed to format %s arguments", view->name);
3284 return FALSE;
3287 /* Put the current ref_* value to the view title ref
3288 * member. This is needed by the blob view. Most other
3289 * views sets it automatically after loading because the
3290 * first line is a commit line. */
3291 string_copy_rev(view->ref, view->id);
3294 if (view->argv && view->argv[0] &&
3295 !io_run(&view->io, io_type, view->dir, opt_env, view->argv)) {
3296 report("Failed to open %s view", view->name);
3297 return FALSE;
3300 if (open_from_stdin(flags)) {
3301 if (!io_open(&view->io, "%s", ""))
3302 die("Failed to open stdin");
3305 if (!extra)
3306 setup_update(view, view->id);
3308 return TRUE;
3311 static bool
3312 update_view(struct view *view)
3314 char *line;
3315 /* Clear the view and redraw everything since the tree sorting
3316 * might have rearranged things. */
3317 bool redraw = view->lines == 0;
3318 bool can_read = TRUE;
3319 struct encoding *encoding = view->encoding ? view->encoding : default_encoding;
3321 if (!view->pipe)
3322 return TRUE;
3324 if (!io_can_read(view->pipe, FALSE)) {
3325 if (view->lines == 0 && view_is_displayed(view)) {
3326 time_t secs = time(NULL) - view->start_time;
3328 if (secs > 1 && secs > view->update_secs) {
3329 if (view->update_secs == 0)
3330 redraw_view(view);
3331 update_view_title(view);
3332 view->update_secs = secs;
3335 return TRUE;
3338 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
3339 if (encoding) {
3340 line = encoding_convert(encoding, line);
3343 if (!view->ops->read(view, line)) {
3344 report("Allocation failure");
3345 end_update(view, TRUE);
3346 return FALSE;
3351 int digits = count_digits(view->lines);
3353 /* Keep the displayed view in sync with line number scaling. */
3354 if (digits != view->digits) {
3355 view->digits = digits;
3356 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3357 redraw = TRUE;
3361 if (io_error(view->pipe)) {
3362 report("Failed to read: %s", io_strerror(view->pipe));
3363 end_update(view, TRUE);
3365 } else if (io_eof(view->pipe)) {
3366 end_update(view, FALSE);
3369 if (restore_view_position(view))
3370 redraw = TRUE;
3372 if (!view_is_displayed(view))
3373 return TRUE;
3375 if (redraw || view->force_redraw)
3376 redraw_view_from(view, 0);
3377 else
3378 redraw_view_dirty(view);
3379 view->force_redraw = FALSE;
3381 /* Update the title _after_ the redraw so that if the redraw picks up a
3382 * commit reference in view->ref it'll be available here. */
3383 update_view_title(view);
3384 return TRUE;
3387 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3389 static struct line *
3390 add_line(struct view *view, const void *data, enum line_type type, size_t data_size, bool custom)
3392 struct line *line;
3394 if (!realloc_lines(&view->line, view->lines, 1))
3395 return NULL;
3397 if (data_size) {
3398 void *alloc_data = calloc(1, data_size);
3400 if (!alloc_data)
3401 return NULL;
3403 if (data)
3404 memcpy(alloc_data, data, data_size);
3405 data = alloc_data;
3408 line = &view->line[view->lines++];
3409 memset(line, 0, sizeof(*line));
3410 line->type = type;
3411 line->data = (void *) data;
3412 line->dirty = 1;
3414 if (custom)
3415 view->custom_lines++;
3416 else
3417 line->lineno = view->lines - view->custom_lines;
3419 return line;
3422 static struct line *
3423 add_line_alloc_(struct view *view, void **ptr, enum line_type type, size_t data_size, bool custom)
3425 struct line *line = add_line(view, NULL, type, data_size, custom);
3427 if (line)
3428 *ptr = line->data;
3429 return line;
3432 #define add_line_alloc(view, data_ptr, type, extra_size, custom) \
3433 add_line_alloc_(view, (void **) data_ptr, type, sizeof(**data_ptr) + extra_size, custom)
3435 static struct line *
3436 add_line_nodata(struct view *view, enum line_type type)
3438 return add_line(view, NULL, type, 0, FALSE);
3441 static struct line *
3442 add_line_text(struct view *view, const char *text, enum line_type type)
3444 return add_line(view, text, type, strlen(text) + 1, FALSE);
3447 static struct line * PRINTF_LIKE(3, 4)
3448 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3450 char buf[SIZEOF_STR];
3451 int retval;
3453 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3454 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3458 * View opening
3461 static void
3462 split_view(struct view *prev, struct view *view)
3464 display[1] = view;
3465 current_view = opt_focus_child ? 1 : 0;
3466 view->parent = prev;
3467 resize_display();
3469 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3470 /* Take the title line into account. */
3471 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3473 /* Scroll the view that was split if the current line is
3474 * outside the new limited view. */
3475 do_scroll_view(prev, lines);
3478 if (view != prev && view_is_displayed(prev)) {
3479 /* "Blur" the previous view. */
3480 update_view_title(prev);
3484 static void
3485 maximize_view(struct view *view, bool redraw)
3487 memset(display, 0, sizeof(display));
3488 current_view = 0;
3489 display[current_view] = view;
3490 resize_display();
3491 if (redraw) {
3492 redraw_display(FALSE);
3493 report_clear();
3497 static void
3498 load_view(struct view *view, struct view *prev, enum open_flags flags)
3500 if (view->pipe)
3501 end_update(view, TRUE);
3502 if (view->ops->private_size) {
3503 if (!view->private)
3504 view->private = calloc(1, view->ops->private_size);
3505 else
3506 memset(view->private, 0, view->ops->private_size);
3509 /* When prev == view it means this is the first loaded view. */
3510 if (prev && view != prev) {
3511 view->prev = prev;
3514 if (!view->ops->open(view, flags))
3515 return;
3517 if (prev) {
3518 bool split = !!(flags & OPEN_SPLIT);
3520 if (split) {
3521 split_view(prev, view);
3522 } else {
3523 maximize_view(view, FALSE);
3527 restore_view_position(view);
3529 if (view->pipe && view->lines == 0) {
3530 /* Clear the old view and let the incremental updating refill
3531 * the screen. */
3532 werase(view->win);
3533 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3534 clear_position(&view->prev_pos);
3535 report_clear();
3536 } else if (view_is_displayed(view)) {
3537 redraw_view(view);
3538 report_clear();
3542 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3543 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3545 static void
3546 open_view(struct view *prev, enum request request, enum open_flags flags)
3548 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3549 struct view *view = VIEW(request);
3550 int nviews = displayed_views();
3552 assert(flags ^ OPEN_REFRESH);
3554 if (view == prev && nviews == 1 && !reload) {
3555 report("Already in %s view", view->name);
3556 return;
3559 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3560 report("The %s view is disabled in pager view", view->name);
3561 return;
3564 load_view(view, prev ? prev : view, flags);
3567 static void
3568 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3570 enum request request = view - views + REQ_OFFSET + 1;
3572 if (view->pipe)
3573 end_update(view, TRUE);
3574 view->dir = dir;
3576 if (!argv_copy(&view->argv, argv)) {
3577 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3578 } else {
3579 open_view(prev, request, flags | OPEN_PREPARED);
3583 static bool
3584 open_external_viewer(const char *argv[], const char *dir, bool confirm, const char *notice)
3586 bool ok;
3588 def_prog_mode(); /* save current tty modes */
3589 endwin(); /* restore original tty modes */
3590 ok = io_run_fg(argv, dir);
3591 if (confirm) {
3592 if (!ok && *notice)
3593 fprintf(stderr, "%s", notice);
3594 fprintf(stderr, "Press Enter to continue");
3595 getc(opt_tty);
3597 reset_prog_mode();
3598 redraw_display(TRUE);
3599 return ok;
3602 static void
3603 open_mergetool(const char *file)
3605 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3607 open_external_viewer(mergetool_argv, opt_cdup, TRUE, "");
3610 #define EDITOR_LINENO_MSG \
3611 "*** Your editor reported an error while opening the file.\n" \
3612 "*** This is probably because it doesn't support the line\n" \
3613 "*** number argument added automatically. The line number\n" \
3614 "*** has been disabled for now. You can permanently disable\n" \
3615 "*** it by adding the following line to ~/.tigrc\n" \
3616 "*** set editor-line-number = no\n"
3618 static void
3619 open_editor(const char *file, unsigned int lineno)
3621 const char *editor_argv[SIZEOF_ARG + 3] = { "vi", file, NULL };
3622 char editor_cmd[SIZEOF_STR];
3623 char lineno_cmd[SIZEOF_STR];
3624 const char *editor;
3625 int argc = 0;
3627 editor = getenv("GIT_EDITOR");
3628 if (!editor && *opt_editor)
3629 editor = opt_editor;
3630 if (!editor)
3631 editor = getenv("VISUAL");
3632 if (!editor)
3633 editor = getenv("EDITOR");
3634 if (!editor)
3635 editor = "vi";
3637 string_ncopy(editor_cmd, editor, strlen(editor));
3638 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3639 report("Failed to read editor command");
3640 return;
3643 if (lineno && opt_editor_lineno && string_format(lineno_cmd, "+%u", lineno))
3644 editor_argv[argc++] = lineno_cmd;
3645 editor_argv[argc] = file;
3646 if (!open_external_viewer(editor_argv, opt_cdup, TRUE, EDITOR_LINENO_MSG))
3647 opt_editor_lineno = FALSE;
3650 static enum request run_prompt_command(struct view *view, char *cmd);
3652 static enum request
3653 open_run_request(struct view *view, enum request request)
3655 struct run_request *req = get_run_request(request);
3656 const char **argv = NULL;
3657 bool confirmed = FALSE;
3659 request = REQ_NONE;
3661 if (!req) {
3662 report("Unknown run request");
3663 return request;
3666 if (format_argv(view, &argv, req->argv, FALSE, TRUE)) {
3667 if (req->internal) {
3668 char cmd[SIZEOF_STR];
3670 if (argv_to_string(argv, cmd, sizeof(cmd), " ")) {
3671 request = run_prompt_command(view, cmd);
3674 else {
3675 confirmed = !req->confirm;
3677 if (req->confirm) {
3678 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
3679 const char *and_exit = req->exit ? " and exit" : "";
3681 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
3682 string_format(prompt, "Run `%s`%s?", cmd, and_exit) &&
3683 prompt_yesno(prompt)) {
3684 confirmed = TRUE;
3688 if (confirmed && argv_remove_quotes(argv)) {
3689 if (req->silent)
3690 io_run_bg(argv);
3691 else
3692 open_external_viewer(argv, NULL, !req->exit, "");
3697 if (argv)
3698 argv_free(argv);
3699 free(argv);
3701 if (request == REQ_NONE) {
3702 if (req->confirm && !confirmed)
3703 request = REQ_NONE;
3705 else if (req->exit)
3706 request = REQ_QUIT;
3708 else if (!view->unrefreshable)
3709 request = REQ_REFRESH;
3711 return request;
3715 * User request switch noodle
3718 static int
3719 view_driver(struct view *view, enum request request)
3721 int i;
3723 if (request == REQ_NONE)
3724 return TRUE;
3726 if (request > REQ_NONE) {
3727 request = open_run_request(view, request);
3729 // exit quickly rather than going through view_request and back
3730 if (request == REQ_QUIT)
3731 return FALSE;
3734 request = view_request(view, request);
3735 if (request == REQ_NONE)
3736 return TRUE;
3738 switch (request) {
3739 case REQ_MOVE_UP:
3740 case REQ_MOVE_DOWN:
3741 case REQ_MOVE_PAGE_UP:
3742 case REQ_MOVE_PAGE_DOWN:
3743 case REQ_MOVE_FIRST_LINE:
3744 case REQ_MOVE_LAST_LINE:
3745 move_view(view, request);
3746 break;
3748 case REQ_SCROLL_FIRST_COL:
3749 case REQ_SCROLL_LEFT:
3750 case REQ_SCROLL_RIGHT:
3751 case REQ_SCROLL_LINE_DOWN:
3752 case REQ_SCROLL_LINE_UP:
3753 case REQ_SCROLL_PAGE_DOWN:
3754 case REQ_SCROLL_PAGE_UP:
3755 scroll_view(view, request);
3756 break;
3758 case REQ_VIEW_MAIN:
3759 case REQ_VIEW_DIFF:
3760 case REQ_VIEW_LOG:
3761 case REQ_VIEW_TREE:
3762 case REQ_VIEW_HELP:
3763 case REQ_VIEW_BRANCH:
3764 case REQ_VIEW_BLAME:
3765 case REQ_VIEW_BLOB:
3766 case REQ_VIEW_STATUS:
3767 case REQ_VIEW_STAGE:
3768 case REQ_VIEW_PAGER:
3769 case REQ_VIEW_STASH:
3770 open_view(view, request, OPEN_DEFAULT);
3771 break;
3773 case REQ_NEXT:
3774 case REQ_PREVIOUS:
3775 if (view->parent) {
3776 int line;
3778 view = view->parent;
3779 line = view->pos.lineno;
3780 view_request(view, request);
3781 move_view(view, request);
3782 if (view_is_displayed(view))
3783 update_view_title(view);
3784 if (line != view->pos.lineno)
3785 view_request(view, REQ_ENTER);
3786 } else {
3787 move_view(view, request);
3789 break;
3791 case REQ_VIEW_NEXT:
3793 int nviews = displayed_views();
3794 int next_view = (current_view + 1) % nviews;
3796 if (next_view == current_view) {
3797 report("Only one view is displayed");
3798 break;
3801 current_view = next_view;
3802 /* Blur out the title of the previous view. */
3803 update_view_title(view);
3804 report_clear();
3805 break;
3807 case REQ_REFRESH:
3808 report("Refreshing is not supported by the %s view", view->name);
3809 break;
3811 case REQ_PARENT:
3812 report("Moving to parent is not supported by the the %s view", view->name);
3813 break;
3815 case REQ_BACK:
3816 report("Going back is not supported for by %s view", view->name);
3817 break;
3819 case REQ_MAXIMIZE:
3820 if (displayed_views() == 2)
3821 maximize_view(view, TRUE);
3822 break;
3824 case REQ_OPTIONS:
3825 case REQ_TOGGLE_LINENO:
3826 case REQ_TOGGLE_DATE:
3827 case REQ_TOGGLE_AUTHOR:
3828 case REQ_TOGGLE_FILENAME:
3829 case REQ_TOGGLE_GRAPHIC:
3830 case REQ_TOGGLE_REV_GRAPH:
3831 case REQ_TOGGLE_REFS:
3832 case REQ_TOGGLE_CHANGES:
3833 case REQ_TOGGLE_IGNORE_SPACE:
3834 case REQ_TOGGLE_ID:
3835 case REQ_TOGGLE_FILES:
3836 case REQ_TOGGLE_TITLE_OVERFLOW:
3838 char action[SIZEOF_STR] = "";
3839 enum view_flag flags = toggle_option(view, request, action);
3841 foreach_displayed_view(view, i) {
3842 if (view_has_flags(view, flags) && !view->unrefreshable)
3843 reload_view(view);
3844 else
3845 redraw_view(view);
3848 if (*action)
3849 report("%s", action);
3851 break;
3853 case REQ_TOGGLE_SORT_FIELD:
3854 case REQ_TOGGLE_SORT_ORDER:
3855 report("Sorting is not yet supported for the %s view", view->name);
3856 break;
3858 case REQ_DIFF_CONTEXT_UP:
3859 case REQ_DIFF_CONTEXT_DOWN:
3860 report("Changing the diff context is not yet supported for the %s view", view->name);
3861 break;
3863 case REQ_SEARCH:
3864 case REQ_SEARCH_BACK:
3865 search_view(view, request);
3866 break;
3868 case REQ_FIND_NEXT:
3869 case REQ_FIND_PREV:
3870 find_next(view, request);
3871 break;
3873 case REQ_STOP_LOADING:
3874 foreach_view(view, i) {
3875 if (view->pipe)
3876 report("Stopped loading the %s view", view->name),
3877 end_update(view, TRUE);
3879 break;
3881 case REQ_SHOW_VERSION:
3882 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3883 return TRUE;
3885 case REQ_SCREEN_REDRAW:
3886 redraw_display(TRUE);
3887 break;
3889 case REQ_EDIT:
3890 report("Nothing to edit");
3891 break;
3893 case REQ_ENTER:
3894 report("Nothing to enter");
3895 break;
3897 case REQ_VIEW_CLOSE:
3898 /* XXX: Mark closed views by letting view->prev point to the
3899 * view itself. Parents to closed view should never be
3900 * followed. */
3901 if (view->prev && view->prev != view) {
3902 maximize_view(view->prev, TRUE);
3903 view->prev = view;
3904 break;
3906 /* Fall-through */
3907 case REQ_QUIT:
3908 return FALSE;
3910 default:
3911 report("Unknown key, press %s for help",
3912 get_view_key(view, REQ_VIEW_HELP));
3913 return TRUE;
3916 return TRUE;
3921 * View backend utilities
3924 enum sort_field {
3925 ORDERBY_NAME,
3926 ORDERBY_DATE,
3927 ORDERBY_AUTHOR,
3930 struct sort_state {
3931 const enum sort_field *fields;
3932 size_t size, current;
3933 bool reverse;
3936 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3937 #define get_sort_field(state) ((state).fields[(state).current])
3938 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3940 static void
3941 sort_view(struct view *view, enum request request, struct sort_state *state,
3942 int (*compare)(const void *, const void *))
3944 switch (request) {
3945 case REQ_TOGGLE_SORT_FIELD:
3946 state->current = (state->current + 1) % state->size;
3947 break;
3949 case REQ_TOGGLE_SORT_ORDER:
3950 state->reverse = !state->reverse;
3951 break;
3952 default:
3953 die("Not a sort request");
3956 qsort(view->line, view->lines, sizeof(*view->line), compare);
3957 redraw_view(view);
3960 static bool
3961 update_diff_context(enum request request)
3963 int diff_context = opt_diff_context;
3965 switch (request) {
3966 case REQ_DIFF_CONTEXT_UP:
3967 opt_diff_context += 1;
3968 update_diff_context_arg(opt_diff_context);
3969 break;
3971 case REQ_DIFF_CONTEXT_DOWN:
3972 if (opt_diff_context == 0) {
3973 report("Diff context cannot be less than zero");
3974 break;
3976 opt_diff_context -= 1;
3977 update_diff_context_arg(opt_diff_context);
3978 break;
3980 default:
3981 die("Not a diff context request");
3984 return diff_context != opt_diff_context;
3987 DEFINE_ALLOCATOR(realloc_paths, const char *, 256)
3989 /* Small cache to reduce memory consumption. It uses binary search to
3990 * lookup or find place to position new entries. No entries are ever
3991 * freed. */
3992 static const char *
3993 get_path(const char *path)
3995 static const char **paths;
3996 static size_t paths_size;
3997 int from = 0, to = paths_size - 1;
3998 char *entry;
4000 while (from <= to) {
4001 size_t pos = (to + from) / 2;
4002 int cmp = strcmp(path, paths[pos]);
4004 if (!cmp)
4005 return paths[pos];
4007 if (cmp < 0)
4008 to = pos - 1;
4009 else
4010 from = pos + 1;
4013 if (!realloc_paths(&paths, paths_size, 1))
4014 return NULL;
4015 entry = strdup(path);
4016 if (!entry)
4017 return NULL;
4019 memmove(paths + from + 1, paths + from, (paths_size - from) * sizeof(*paths));
4020 paths[from] = entry;
4021 paths_size++;
4023 return entry;
4026 DEFINE_ALLOCATOR(realloc_authors, struct ident *, 256)
4028 /* Small author cache to reduce memory consumption. It uses binary
4029 * search to lookup or find place to position new entries. No entries
4030 * are ever freed. */
4031 static struct ident *
4032 get_author(const char *name, const char *email)
4034 static struct ident **authors;
4035 static size_t authors_size;
4036 int from = 0, to = authors_size - 1;
4037 struct ident *ident;
4039 while (from <= to) {
4040 size_t pos = (to + from) / 2;
4041 int cmp = strcmp(name, authors[pos]->name);
4043 if (!cmp)
4044 return authors[pos];
4046 if (cmp < 0)
4047 to = pos - 1;
4048 else
4049 from = pos + 1;
4052 if (!realloc_authors(&authors, authors_size, 1))
4053 return NULL;
4054 ident = calloc(1, sizeof(*ident));
4055 if (!ident)
4056 return NULL;
4057 ident->name = strdup(name);
4058 ident->email = strdup(email);
4059 if (!ident->name || !ident->email) {
4060 free((void *) ident->name);
4061 free(ident);
4062 return NULL;
4065 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
4066 authors[from] = ident;
4067 authors_size++;
4069 return ident;
4072 static void
4073 parse_timesec(struct time *time, const char *sec)
4075 time->sec = (time_t) atol(sec);
4078 static void
4079 parse_timezone(struct time *time, const char *zone)
4081 long tz;
4083 tz = ('0' - zone[1]) * 60 * 60 * 10;
4084 tz += ('0' - zone[2]) * 60 * 60;
4085 tz += ('0' - zone[3]) * 60 * 10;
4086 tz += ('0' - zone[4]) * 60;
4088 if (zone[0] == '-')
4089 tz = -tz;
4091 time->tz = tz;
4092 time->sec -= tz;
4095 /* Parse author lines where the name may be empty:
4096 * author <email@address.tld> 1138474660 +0100
4098 static void
4099 parse_author_line(char *ident, const struct ident **author, struct time *time)
4101 char *nameend = strchr(ident, '<');
4102 char *emailend = strchr(ident, '>');
4103 const char *name, *email = "";
4105 if (nameend && emailend)
4106 *nameend = *emailend = 0;
4107 name = chomp_string(ident);
4108 if (nameend)
4109 email = chomp_string(nameend + 1);
4110 if (!*name)
4111 name = *email ? email : unknown_ident.name;
4112 if (!*email)
4113 email = *name ? name : unknown_ident.email;
4115 *author = get_author(name, email);
4117 /* Parse epoch and timezone */
4118 if (time && emailend && emailend[1] == ' ') {
4119 char *secs = emailend + 2;
4120 char *zone = strchr(secs, ' ');
4122 parse_timesec(time, secs);
4124 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
4125 parse_timezone(time, zone + 1);
4129 static struct line *
4130 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
4132 for (; view_has_line(view, line); line += direction)
4133 if (line->type == type)
4134 return line;
4136 return NULL;
4139 #define find_prev_line_by_type(view, line, type) \
4140 find_line_by_type(view, line, type, -1)
4142 #define find_next_line_by_type(view, line, type) \
4143 find_line_by_type(view, line, type, 1)
4146 * View history
4149 struct view_state {
4150 struct view_state *prev; /* Entry below this in the stack */
4151 struct position position; /* View position to restore */
4152 void *data; /* View specific state */
4155 struct view_history {
4156 size_t state_alloc;
4157 struct view_state *stack;
4158 struct position position;
4161 static bool
4162 view_history_is_empty(struct view_history *history)
4164 return !history->stack;
4167 static struct view_state *
4168 push_view_history_state(struct view_history *history, struct position *position, void *data)
4170 struct view_state *state = history->stack;
4172 if (state && data && history->state_alloc &&
4173 !memcmp(state->data, data, history->state_alloc))
4174 return NULL;
4176 state = calloc(1, sizeof(*state) + history->state_alloc);
4177 if (!state)
4178 return NULL;
4180 state->prev = history->stack;
4181 history->stack = state;
4182 clear_position(&history->position);
4183 state->position = *position;
4184 state->data = &state[1];
4185 if (data && history->state_alloc)
4186 memcpy(state->data, data, history->state_alloc);
4187 return state;
4190 static bool
4191 pop_view_history_state(struct view_history *history, struct position *position, void *data)
4193 struct view_state *state = history->stack;
4195 if (view_history_is_empty(history))
4196 return FALSE;
4198 history->position = state->position;
4199 history->stack = state->prev;
4201 if (data && history->state_alloc)
4202 memcpy(data, state->data, history->state_alloc);
4203 if (position)
4204 *position = state->position;
4206 free(state);
4207 return TRUE;
4210 static void
4211 reset_view_history(struct view_history *history)
4213 while (pop_view_history_state(history, NULL, NULL))
4218 * Blame
4221 struct blame_commit {
4222 char id[SIZEOF_REV]; /* SHA1 ID. */
4223 char title[128]; /* First line of the commit message. */
4224 const struct ident *author; /* Author of the commit. */
4225 struct time time; /* Date from the author ident. */
4226 const char *filename; /* Name of file. */
4227 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
4228 const char *parent_filename; /* Parent/previous name of file. */
4231 struct blame_header {
4232 char id[SIZEOF_REV]; /* SHA1 ID. */
4233 size_t orig_lineno;
4234 size_t lineno;
4235 size_t group;
4238 static bool
4239 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4241 const char *pos = *posref;
4243 *posref = NULL;
4244 pos = strchr(pos + 1, ' ');
4245 if (!pos || !isdigit(pos[1]))
4246 return FALSE;
4247 *number = atoi(pos + 1);
4248 if (*number < min || *number > max)
4249 return FALSE;
4251 *posref = pos;
4252 return TRUE;
4255 static bool
4256 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
4258 const char *pos = text + SIZEOF_REV - 2;
4260 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4261 return FALSE;
4263 string_ncopy(header->id, text, SIZEOF_REV);
4265 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
4266 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
4267 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
4268 return FALSE;
4270 return TRUE;
4273 static bool
4274 match_blame_header(const char *name, char **line)
4276 size_t namelen = strlen(name);
4277 bool matched = !strncmp(name, *line, namelen);
4279 if (matched)
4280 *line += namelen;
4282 return matched;
4285 static bool
4286 parse_blame_info(struct blame_commit *commit, char *line)
4288 if (match_blame_header("author ", &line)) {
4289 parse_author_line(line, &commit->author, NULL);
4291 } else if (match_blame_header("author-time ", &line)) {
4292 parse_timesec(&commit->time, line);
4294 } else if (match_blame_header("author-tz ", &line)) {
4295 parse_timezone(&commit->time, line);
4297 } else if (match_blame_header("summary ", &line)) {
4298 string_ncopy(commit->title, line, strlen(line));
4300 } else if (match_blame_header("previous ", &line)) {
4301 if (strlen(line) <= SIZEOF_REV)
4302 return FALSE;
4303 string_copy_rev(commit->parent_id, line);
4304 line += SIZEOF_REV;
4305 commit->parent_filename = get_path(line);
4306 if (!commit->parent_filename)
4307 return TRUE;
4309 } else if (match_blame_header("filename ", &line)) {
4310 commit->filename = get_path(line);
4311 return TRUE;
4314 return FALSE;
4318 * Pager backend
4321 static bool
4322 pager_draw(struct view *view, struct line *line, unsigned int lineno)
4324 if (draw_lineno(view, lineno))
4325 return TRUE;
4327 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4328 return TRUE;
4330 draw_text(view, line->type, line->data);
4331 return TRUE;
4334 static bool
4335 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
4337 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
4338 char ref[SIZEOF_STR];
4340 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
4341 return TRUE;
4343 /* This is the only fatal call, since it can "corrupt" the buffer. */
4344 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
4345 return FALSE;
4347 return TRUE;
4350 static void
4351 add_pager_refs(struct view *view, const char *commit_id)
4353 char buf[SIZEOF_STR];
4354 struct ref_list *list;
4355 size_t bufpos = 0, i;
4356 const char *sep = "Refs: ";
4357 bool is_tag = FALSE;
4359 list = get_ref_list(commit_id);
4360 if (!list) {
4361 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
4362 goto try_add_describe_ref;
4363 return;
4366 for (i = 0; i < list->size; i++) {
4367 struct ref *ref = list->refs[i];
4368 const char *fmt = ref->tag ? "%s[%s]" :
4369 ref->remote ? "%s<%s>" : "%s%s";
4371 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
4372 return;
4373 sep = ", ";
4374 if (ref->tag)
4375 is_tag = TRUE;
4378 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
4379 try_add_describe_ref:
4380 /* Add <tag>-g<commit_id> "fake" reference. */
4381 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
4382 return;
4385 if (bufpos == 0)
4386 return;
4388 add_line_text(view, buf, LINE_PP_REFS);
4391 static struct line *
4392 pager_wrap_line(struct view *view, const char *data, enum line_type type)
4394 size_t first_line = 0;
4395 bool has_first_line = FALSE;
4396 size_t datalen = strlen(data);
4397 size_t lineno = 0;
4399 while (datalen > 0 || !has_first_line) {
4400 bool wrapped = !!first_line;
4401 size_t linelen = string_expanded_length(data, datalen, opt_tab_size, view->width - !!wrapped);
4402 struct line *line;
4403 char *text;
4405 line = add_line(view, NULL, type, linelen + 1, wrapped);
4406 if (!line)
4407 break;
4408 if (!has_first_line) {
4409 first_line = view->lines - 1;
4410 has_first_line = TRUE;
4413 if (!wrapped)
4414 lineno = line->lineno;
4416 line->wrapped = wrapped;
4417 line->lineno = lineno;
4418 text = line->data;
4419 if (linelen)
4420 strncpy(text, data, linelen);
4421 text[linelen] = 0;
4423 datalen -= linelen;
4424 data += linelen;
4427 return has_first_line ? &view->line[first_line] : NULL;
4430 static bool
4431 pager_common_read(struct view *view, const char *data, enum line_type type)
4433 struct line *line;
4435 if (!data)
4436 return TRUE;
4438 if (opt_wrap_lines) {
4439 line = pager_wrap_line(view, data, type);
4440 } else {
4441 line = add_line_text(view, data, type);
4444 if (!line)
4445 return FALSE;
4447 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
4448 add_pager_refs(view, data + STRING_SIZE("commit "));
4450 return TRUE;
4453 static bool
4454 pager_read(struct view *view, char *data)
4456 if (!data)
4457 return TRUE;
4459 return pager_common_read(view, data, get_line_type(data));
4462 static enum request
4463 pager_request(struct view *view, enum request request, struct line *line)
4465 int split = 0;
4467 if (request != REQ_ENTER)
4468 return request;
4470 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
4471 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4472 split = 1;
4475 /* Always scroll the view even if it was split. That way
4476 * you can use Enter to scroll through the log view and
4477 * split open each commit diff. */
4478 scroll_view(view, REQ_SCROLL_LINE_DOWN);
4480 /* FIXME: A minor workaround. Scrolling the view will call report_clear()
4481 * but if we are scrolling a non-current view this won't properly
4482 * update the view title. */
4483 if (split)
4484 update_view_title(view);
4486 return REQ_NONE;
4489 static bool
4490 pager_grep(struct view *view, struct line *line)
4492 const char *text[] = { line->data, NULL };
4494 return grep_text(view, text);
4497 static void
4498 pager_select(struct view *view, struct line *line)
4500 if (line->type == LINE_COMMIT) {
4501 string_copy_rev_from_commit_line(ref_commit, line->data);
4502 if (!view_has_flags(view, VIEW_NO_REF))
4503 string_copy_rev(view->ref, ref_commit);
4507 struct log_state {
4508 /* Used for tracking when we need to recalculate the previous
4509 * commit, for example when the user scrolls up or uses the page
4510 * up/down in the log view. */
4511 int last_lineno;
4512 enum line_type last_type;
4515 static void
4516 log_select(struct view *view, struct line *line)
4518 struct log_state *state = view->private;
4519 int last_lineno = state->last_lineno;
4521 if (!last_lineno || abs(last_lineno - line->lineno) > 1
4522 || (state->last_type == LINE_COMMIT && last_lineno > line->lineno)) {
4523 const struct line *commit_line = find_prev_line_by_type(view, line, LINE_COMMIT);
4525 if (commit_line)
4526 string_copy_rev_from_commit_line(view->ref, commit_line->data);
4529 if (line->type == LINE_COMMIT && !view_has_flags(view, VIEW_NO_REF)) {
4530 string_copy_rev_from_commit_line(view->ref, (char *)line->data);
4532 string_copy_rev(ref_commit, view->ref);
4533 state->last_lineno = line->lineno;
4534 state->last_type = line->type;
4537 static bool
4538 pager_open(struct view *view, enum open_flags flags)
4540 if (!open_from_stdin(flags) && !view->lines) {
4541 report("No pager content, press %s to run command from prompt",
4542 get_view_key(view, REQ_PROMPT));
4543 return FALSE;
4546 return begin_update(view, NULL, NULL, flags);
4549 static struct view_ops pager_ops = {
4550 "line",
4551 { "pager" },
4552 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
4554 pager_open,
4555 pager_read,
4556 pager_draw,
4557 pager_request,
4558 pager_grep,
4559 pager_select,
4562 static bool
4563 log_open(struct view *view, enum open_flags flags)
4565 static const char *log_argv[] = {
4566 "git", "log", encoding_arg, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
4569 return begin_update(view, NULL, log_argv, flags);
4572 static enum request
4573 log_request(struct view *view, enum request request, struct line *line)
4575 switch (request) {
4576 case REQ_REFRESH:
4577 load_refs(TRUE);
4578 refresh_view(view);
4579 return REQ_NONE;
4581 case REQ_ENTER:
4582 if (!display[1] || strcmp(display[1]->vid, view->ref))
4583 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4584 return REQ_NONE;
4586 default:
4587 return request;
4591 static struct view_ops log_ops = {
4592 "line",
4593 { "log" },
4594 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF | VIEW_SEND_CHILD_ENTER | VIEW_LOG_LIKE,
4595 sizeof(struct log_state),
4596 log_open,
4597 pager_read,
4598 pager_draw,
4599 log_request,
4600 pager_grep,
4601 log_select,
4604 struct diff_state {
4605 bool after_commit_title;
4606 bool after_diff;
4607 bool reading_diff_stat;
4608 bool combined_diff;
4611 #define DIFF_LINE_COMMIT_TITLE 1
4613 static bool
4614 diff_open(struct view *view, enum open_flags flags)
4616 static const char *diff_argv[] = {
4617 "git", "show", encoding_arg, "--pretty=fuller", "--root",
4618 "--patch-with-stat",
4619 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
4620 "%(diffargs)", "--no-color", "%(commit)", "--", "%(fileargs)", NULL
4623 return begin_update(view, NULL, diff_argv, flags);
4626 static bool
4627 diff_common_read(struct view *view, const char *data, struct diff_state *state)
4629 enum line_type type = get_line_type(data);
4631 if (!view->lines && type != LINE_COMMIT)
4632 state->reading_diff_stat = TRUE;
4634 if (state->combined_diff && !state->after_diff && data[0] == ' ' && data[1] != ' ')
4635 state->reading_diff_stat = TRUE;
4637 if (state->reading_diff_stat) {
4638 size_t len = strlen(data);
4639 char *pipe = strchr(data, '|');
4640 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
4641 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
4642 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
4644 if (pipe && (has_histogram || has_bin_diff || has_rename)) {
4645 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
4646 } else {
4647 state->reading_diff_stat = FALSE;
4650 } else if (!strcmp(data, "---")) {
4651 state->reading_diff_stat = TRUE;
4654 if (!state->after_commit_title && !prefixcmp(data, " ")) {
4655 struct line *line = add_line_text(view, data, LINE_DEFAULT);
4657 if (line)
4658 line->user_flags |= DIFF_LINE_COMMIT_TITLE;
4659 state->after_commit_title = TRUE;
4660 return line != NULL;
4663 if (type == LINE_DIFF_HEADER) {
4664 const int len = line_info[LINE_DIFF_HEADER].linelen;
4666 state->after_diff = TRUE;
4667 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4668 !strncmp(data + len, "cc ", strlen("cc ")))
4669 state->combined_diff = TRUE;
4671 } else if (type == LINE_PP_MERGE) {
4672 state->combined_diff = TRUE;
4675 /* ADD2 and DEL2 are only valid in combined diff hunks */
4676 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4677 type = LINE_DEFAULT;
4679 return pager_common_read(view, data, type);
4682 static bool
4683 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
4685 struct line *marker = find_next_line_by_type(view, line, type);
4687 return marker &&
4688 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
4691 static enum request
4692 diff_common_enter(struct view *view, enum request request, struct line *line)
4694 if (line->type == LINE_DIFF_STAT) {
4695 int file_number = 0;
4697 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4698 file_number++;
4699 line--;
4702 for (line = view->line; view_has_line(view, line); line++) {
4703 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4704 if (!line)
4705 break;
4707 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4708 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4709 if (file_number == 1) {
4710 break;
4712 file_number--;
4716 if (!line) {
4717 report("Failed to find file diff");
4718 return REQ_NONE;
4721 select_view_line(view, line - view->line);
4722 report_clear();
4723 return REQ_NONE;
4725 } else {
4726 return pager_request(view, request, line);
4730 static bool
4731 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4733 char *sep = strchr(*text, c);
4735 if (sep != NULL) {
4736 *sep = 0;
4737 draw_text(view, *type, *text);
4738 *sep = c;
4739 *text = sep;
4740 *type = next_type;
4743 return sep != NULL;
4746 static bool
4747 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4749 char *text = line->data;
4750 enum line_type type = line->type;
4752 if (draw_lineno(view, lineno))
4753 return TRUE;
4755 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4756 return TRUE;
4758 if (type == LINE_DIFF_STAT) {
4759 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4760 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4761 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4762 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4763 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4764 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4765 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4767 } else {
4768 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4769 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4773 if (line->user_flags & DIFF_LINE_COMMIT_TITLE)
4774 draw_commit_title(view, text, 4);
4775 else
4776 draw_text(view, type, text);
4777 return TRUE;
4780 static bool
4781 diff_read(struct view *view, char *data)
4783 struct diff_state *state = view->private;
4785 if (!data) {
4786 /* Fall back to retry if no diff will be shown. */
4787 if (view->lines == 0 && opt_file_argv) {
4788 int pos = argv_size(view->argv)
4789 - argv_size(opt_file_argv) - 1;
4791 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4792 for (; view->argv[pos]; pos++) {
4793 free((void *) view->argv[pos]);
4794 view->argv[pos] = NULL;
4797 if (view->pipe)
4798 io_done(view->pipe);
4799 if (io_run(&view->io, IO_RD, view->dir, opt_env, view->argv))
4800 return FALSE;
4803 return TRUE;
4806 return diff_common_read(view, data, state);
4809 static bool
4810 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4811 struct blame_header *header, struct blame_commit *commit)
4813 char line_arg[SIZEOF_STR];
4814 const char *blame_argv[] = {
4815 "git", "blame", encoding_arg, "-p", line_arg, ref, "--", file, NULL
4817 struct io io;
4818 bool ok = FALSE;
4819 char *buf;
4821 if (!string_format(line_arg, "-L%ld,+1", lineno))
4822 return FALSE;
4824 if (!io_run(&io, IO_RD, opt_cdup, opt_env, blame_argv))
4825 return FALSE;
4827 while ((buf = io_get(&io, '\n', TRUE))) {
4828 if (header) {
4829 if (!parse_blame_header(header, buf, 9999999))
4830 break;
4831 header = NULL;
4833 } else if (parse_blame_info(commit, buf)) {
4834 ok = commit->filename != NULL;
4835 break;
4839 if (io_error(&io))
4840 ok = FALSE;
4842 io_done(&io);
4843 return ok;
4846 static unsigned int
4847 diff_get_lineno(struct view *view, struct line *line)
4849 const struct line *header, *chunk;
4850 const char *data;
4851 unsigned int lineno;
4853 /* Verify that we are after a diff header and one of its chunks */
4854 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4855 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4856 if (!header || !chunk || chunk < header)
4857 return 0;
4860 * In a chunk header, the number after the '+' sign is the number of its
4861 * following line, in the new version of the file. We increment this
4862 * number for each non-deletion line, until the given line position.
4864 data = strchr(chunk->data, '+');
4865 if (!data)
4866 return 0;
4868 lineno = atoi(data);
4869 chunk++;
4870 while (chunk++ < line)
4871 if (chunk->type != LINE_DIFF_DEL)
4872 lineno++;
4874 return lineno;
4877 static bool
4878 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4880 return prefixcmp(chunk, "@@ -") ||
4881 !(chunk = strchr(chunk, marker)) ||
4882 parse_int(lineno, chunk + 1, 0, 9999999) != SUCCESS;
4885 static enum request
4886 diff_trace_origin(struct view *view, struct line *line)
4888 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4889 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4890 const char *chunk_data;
4891 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4892 int lineno = 0;
4893 const char *file = NULL;
4894 char ref[SIZEOF_REF];
4895 struct blame_header header;
4896 struct blame_commit commit;
4898 if (!diff || !chunk || chunk == line) {
4899 report("The line to trace must be inside a diff chunk");
4900 return REQ_NONE;
4903 for (; diff < line && !file; diff++) {
4904 const char *data = diff->data;
4906 if (!prefixcmp(data, "--- a/")) {
4907 file = data + STRING_SIZE("--- a/");
4908 break;
4912 if (diff == line || !file) {
4913 report("Failed to read the file name");
4914 return REQ_NONE;
4917 chunk_data = chunk->data;
4919 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4920 report("Failed to read the line number");
4921 return REQ_NONE;
4924 if (lineno == 0) {
4925 report("This is the origin of the line");
4926 return REQ_NONE;
4929 for (chunk += 1; chunk < line; chunk++) {
4930 if (chunk->type == LINE_DIFF_ADD) {
4931 lineno += chunk_marker == '+';
4932 } else if (chunk->type == LINE_DIFF_DEL) {
4933 lineno += chunk_marker == '-';
4934 } else {
4935 lineno++;
4939 if (chunk_marker == '+')
4940 string_copy(ref, view->vid);
4941 else
4942 string_format(ref, "%s^", view->vid);
4944 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4945 report("Failed to read blame data");
4946 return REQ_NONE;
4949 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4950 string_copy(opt_ref, header.id);
4951 opt_goto_line = header.orig_lineno - 1;
4953 return REQ_VIEW_BLAME;
4956 static const char *
4957 diff_get_pathname(struct view *view, struct line *line)
4959 const struct line *header;
4960 const char *dst = NULL;
4961 const char *prefixes[] = { " b/", "cc ", "combined " };
4962 int i;
4964 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4965 if (!header)
4966 return NULL;
4968 for (i = 0; i < ARRAY_SIZE(prefixes) && !dst; i++)
4969 dst = strstr(header->data, prefixes[i]);
4971 return dst ? dst + strlen(prefixes[--i]) : NULL;
4974 static enum request
4975 diff_common_edit(struct view *view, enum request request, struct line *line)
4977 const char *file = diff_get_pathname(view, line);
4978 char path[SIZEOF_STR];
4979 bool has_path = file && string_format(path, "%s%s", opt_cdup, file);
4981 if (has_path && access(path, R_OK)) {
4982 report("Failed to open file: %s", file);
4983 return REQ_NONE;
4986 open_editor(file, diff_get_lineno(view, line));
4987 return REQ_NONE;
4990 static enum request
4991 diff_request(struct view *view, enum request request, struct line *line)
4993 switch (request) {
4994 case REQ_VIEW_BLAME:
4995 return diff_trace_origin(view, line);
4997 case REQ_DIFF_CONTEXT_UP:
4998 case REQ_DIFF_CONTEXT_DOWN:
4999 if (!update_diff_context(request))
5000 return REQ_NONE;
5001 reload_view(view);
5002 return REQ_NONE;
5005 case REQ_EDIT:
5006 return diff_common_edit(view, request, line);
5008 case REQ_ENTER:
5009 return diff_common_enter(view, request, line);
5011 case REQ_REFRESH:
5012 reload_view(view);
5013 return REQ_NONE;
5015 default:
5016 return pager_request(view, request, line);
5020 static void
5021 diff_select(struct view *view, struct line *line)
5023 if (line->type == LINE_DIFF_STAT) {
5024 string_format(view->ref, "Press '%s' to jump to file diff",
5025 get_view_key(view, REQ_ENTER));
5026 } else {
5027 const char *file = diff_get_pathname(view, line);
5029 if (file) {
5030 string_format(view->ref, "Changes to '%s'", file);
5031 string_format(opt_file, "%s", file);
5032 ref_blob[0] = 0;
5033 } else {
5034 string_ncopy(view->ref, view->id, strlen(view->id));
5035 pager_select(view, line);
5040 static struct view_ops diff_ops = {
5041 "line",
5042 { "diff" },
5043 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS | VIEW_FILE_FILTER,
5044 sizeof(struct diff_state),
5045 diff_open,
5046 diff_read,
5047 diff_common_draw,
5048 diff_request,
5049 pager_grep,
5050 diff_select,
5054 * Help backend
5057 static bool
5058 help_draw(struct view *view, struct line *line, unsigned int lineno)
5060 if (line->type == LINE_HELP_KEYMAP) {
5061 struct keymap *keymap = line->data;
5063 draw_formatted(view, line->type, "[%c] %s bindings",
5064 keymap->hidden ? '+' : '-', keymap->name);
5065 return TRUE;
5066 } else {
5067 return pager_draw(view, line, lineno);
5071 static bool
5072 help_open_keymap_title(struct view *view, struct keymap *keymap)
5074 add_line(view, keymap, LINE_HELP_KEYMAP, 0, FALSE);
5075 return keymap->hidden;
5078 static void
5079 help_open_keymap(struct view *view, struct keymap *keymap)
5081 const char *group = NULL;
5082 char buf[SIZEOF_STR];
5083 bool add_title = TRUE;
5084 int i;
5086 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
5087 const char *key = NULL;
5089 if (req_info[i].request == REQ_NONE)
5090 continue;
5092 if (!req_info[i].request) {
5093 group = req_info[i].help;
5094 continue;
5097 key = get_keys(keymap, req_info[i].request, TRUE);
5098 if (!key || !*key)
5099 continue;
5101 if (add_title && help_open_keymap_title(view, keymap))
5102 return;
5103 add_title = FALSE;
5105 if (group) {
5106 add_line_text(view, group, LINE_HELP_GROUP);
5107 group = NULL;
5110 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
5111 enum_name(req_info[i]), req_info[i].help);
5114 group = "External commands:";
5116 for (i = 0; i < run_requests; i++) {
5117 struct run_request *req = get_run_request(REQ_NONE + i + 1);
5118 const char *key;
5120 if (!req || req->keymap != keymap)
5121 continue;
5123 key = get_key_name(req->key);
5124 if (!*key)
5125 key = "(no key defined)";
5127 if (add_title && help_open_keymap_title(view, keymap))
5128 return;
5129 add_title = FALSE;
5131 if (group) {
5132 add_line_text(view, group, LINE_HELP_GROUP);
5133 group = NULL;
5136 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
5137 return;
5139 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
5143 static bool
5144 help_open(struct view *view, enum open_flags flags)
5146 struct keymap *keymap;
5148 reset_view(view);
5149 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
5150 add_line_text(view, "", LINE_DEFAULT);
5152 for (keymap = keymaps; keymap; keymap = keymap->next)
5153 help_open_keymap(view, keymap);
5155 return TRUE;
5158 static enum request
5159 help_request(struct view *view, enum request request, struct line *line)
5161 switch (request) {
5162 case REQ_ENTER:
5163 if (line->type == LINE_HELP_KEYMAP) {
5164 struct keymap *keymap = line->data;
5166 keymap->hidden = !keymap->hidden;
5167 refresh_view(view);
5170 return REQ_NONE;
5171 default:
5172 return pager_request(view, request, line);
5176 static void
5177 help_done(struct view *view)
5179 int i;
5181 for (i = 0; i < view->lines; i++)
5182 if (view->line[i].type == LINE_HELP_KEYMAP)
5183 view->line[i].data = NULL;
5186 static struct view_ops help_ops = {
5187 "line",
5188 { "help" },
5189 VIEW_NO_GIT_DIR,
5191 help_open,
5192 NULL,
5193 help_draw,
5194 help_request,
5195 pager_grep,
5196 pager_select,
5197 help_done,
5202 * Tree backend
5205 /* The top of the path stack. */
5206 static struct view_history tree_view_history = { sizeof(char *) };
5208 static void
5209 pop_tree_stack_entry(struct position *position)
5211 char *path_position = NULL;
5213 pop_view_history_state(&tree_view_history, position, &path_position);
5214 path_position[0] = 0;
5217 static void
5218 push_tree_stack_entry(const char *name, struct position *position)
5220 size_t pathlen = strlen(opt_path);
5221 char *path_position = opt_path + pathlen;
5222 struct view_state *state = push_view_history_state(&tree_view_history, position, &path_position);
5224 if (!state)
5225 return;
5227 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
5228 pop_tree_stack_entry(NULL);
5229 return;
5232 clear_position(position);
5235 /* Parse output from git-ls-tree(1):
5237 * 100644 blob 95925677ca47beb0b8cce7c0e0011bcc3f61470f 213045 tig.c
5240 #define SIZEOF_TREE_ATTR \
5241 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
5243 #define SIZEOF_TREE_MODE \
5244 STRING_SIZE("100644 ")
5246 #define TREE_ID_OFFSET \
5247 STRING_SIZE("100644 blob ")
5249 #define tree_path_is_parent(path) (!strcmp("..", (path)))
5251 struct tree_entry {
5252 char id[SIZEOF_REV];
5253 char commit[SIZEOF_REV];
5254 mode_t mode;
5255 struct time time; /* Date from the author ident. */
5256 const struct ident *author; /* Author of the commit. */
5257 unsigned long size;
5258 char name[1];
5261 struct tree_state {
5262 char commit[SIZEOF_REV];
5263 const struct ident *author;
5264 struct time author_time;
5265 int size_width;
5266 bool read_date;
5269 static const char *
5270 tree_path(const struct line *line)
5272 return ((struct tree_entry *) line->data)->name;
5275 static int
5276 tree_compare_entry(const struct line *line1, const struct line *line2)
5278 if (line1->type != line2->type)
5279 return line1->type == LINE_TREE_DIR ? -1 : 1;
5280 return strcmp(tree_path(line1), tree_path(line2));
5283 static const enum sort_field tree_sort_fields[] = {
5284 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5286 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
5288 static int
5289 tree_compare(const void *l1, const void *l2)
5291 const struct line *line1 = (const struct line *) l1;
5292 const struct line *line2 = (const struct line *) l2;
5293 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
5294 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
5296 if (line1->type == LINE_TREE_HEAD)
5297 return -1;
5298 if (line2->type == LINE_TREE_HEAD)
5299 return 1;
5301 switch (get_sort_field(tree_sort_state)) {
5302 case ORDERBY_DATE:
5303 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
5305 case ORDERBY_AUTHOR:
5306 return sort_order(tree_sort_state, ident_compare(entry1->author, entry2->author));
5308 case ORDERBY_NAME:
5309 default:
5310 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
5315 static struct line *
5316 tree_entry(struct view *view, enum line_type type, const char *path,
5317 const char *mode, const char *id, unsigned long size)
5319 bool custom = type == LINE_TREE_HEAD || tree_path_is_parent(path);
5320 struct tree_entry *entry;
5321 struct line *line = add_line_alloc(view, &entry, type, strlen(path), custom);
5323 if (!line)
5324 return NULL;
5326 strncpy(entry->name, path, strlen(path));
5327 if (mode)
5328 entry->mode = strtoul(mode, NULL, 8);
5329 if (id)
5330 string_copy_rev(entry->id, id);
5331 entry->size = size;
5333 return line;
5336 static bool
5337 tree_read_date(struct view *view, char *text, struct tree_state *state)
5339 if (!text && state->read_date) {
5340 state->read_date = FALSE;
5341 return TRUE;
5343 } else if (!text) {
5344 /* Find next entry to process */
5345 const char *log_file[] = {
5346 "git", "log", encoding_arg, "--no-color", "--pretty=raw",
5347 "--cc", "--raw", view->id, "--", "%(directory)", NULL
5350 if (!view->lines) {
5351 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0);
5352 tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0);
5353 report("Tree is empty");
5354 return TRUE;
5357 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
5358 report("Failed to load tree data");
5359 return TRUE;
5362 state->read_date = TRUE;
5363 return FALSE;
5365 } else if (*text == 'c' && get_line_type(text) == LINE_COMMIT) {
5366 string_copy_rev_from_commit_line(state->commit, text);
5368 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
5369 parse_author_line(text + STRING_SIZE("author "),
5370 &state->author, &state->author_time);
5372 } else if (*text == ':') {
5373 char *pos;
5374 size_t annotated = 1;
5375 size_t i;
5377 pos = strchr(text, '\t');
5378 if (!pos)
5379 return TRUE;
5380 text = pos + 1;
5381 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
5382 text += strlen(opt_path);
5383 pos = strchr(text, '/');
5384 if (pos)
5385 *pos = 0;
5387 for (i = 1; i < view->lines; i++) {
5388 struct line *line = &view->line[i];
5389 struct tree_entry *entry = line->data;
5391 annotated += !!entry->author;
5392 if (entry->author || strcmp(entry->name, text))
5393 continue;
5395 string_copy_rev(entry->commit, state->commit);
5396 entry->author = state->author;
5397 entry->time = state->author_time;
5398 line->dirty = 1;
5399 break;
5402 if (annotated == view->lines)
5403 io_kill(view->pipe);
5405 return TRUE;
5408 static inline size_t
5409 parse_size(const char *text, int *max_digits)
5411 size_t size = 0;
5412 int digits = 0;
5414 while (*text == ' ')
5415 text++;
5417 while (isdigit(*text)) {
5418 size = (size * 10) + (*text++ - '0');
5419 digits++;
5422 if (digits > *max_digits)
5423 *max_digits = digits;
5425 return size;
5428 static bool
5429 tree_read(struct view *view, char *text)
5431 struct tree_state *state = view->private;
5432 struct tree_entry *data;
5433 struct line *entry, *line;
5434 enum line_type type;
5435 size_t textlen = text ? strlen(text) : 0;
5436 const char *attr_offset = text + SIZEOF_TREE_ATTR;
5437 char *path;
5438 size_t size;
5440 if (state->read_date || !text)
5441 return tree_read_date(view, text, state);
5443 if (textlen <= SIZEOF_TREE_ATTR)
5444 return FALSE;
5445 if (view->lines == 0 &&
5446 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0))
5447 return FALSE;
5449 size = parse_size(attr_offset, &state->size_width);
5450 path = strchr(attr_offset, '\t');
5451 if (!path)
5452 return FALSE;
5453 path++;
5455 /* Strip the path part ... */
5456 if (*opt_path) {
5457 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
5458 size_t striplen = strlen(opt_path);
5460 if (pathlen > striplen)
5461 memmove(path, path + striplen,
5462 pathlen - striplen + 1);
5464 /* Insert "link" to parent directory. */
5465 if (view->lines == 1 &&
5466 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0))
5467 return FALSE;
5470 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
5471 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET, size);
5472 if (!entry)
5473 return FALSE;
5474 data = entry->data;
5476 /* Skip "Directory ..." and ".." line. */
5477 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
5478 if (tree_compare_entry(line, entry) <= 0)
5479 continue;
5481 memmove(line + 1, line, (entry - line) * sizeof(*entry));
5483 line->data = data;
5484 line->type = type;
5485 for (; line <= entry; line++)
5486 line->dirty = line->cleareol = 1;
5487 return TRUE;
5490 /* Move the current line to the first tree entry. */
5491 if (!check_position(&view->prev_pos) && !check_position(&view->pos))
5492 goto_view_line(view, 0, 1);
5494 return TRUE;
5497 static bool
5498 tree_draw(struct view *view, struct line *line, unsigned int lineno)
5500 struct tree_state *state = view->private;
5501 struct tree_entry *entry = line->data;
5503 if (line->type == LINE_TREE_HEAD) {
5504 if (draw_text(view, line->type, "Directory path /"))
5505 return TRUE;
5506 } else {
5507 if (draw_mode(view, entry->mode))
5508 return TRUE;
5510 if (draw_author(view, entry->author))
5511 return TRUE;
5513 if (draw_file_size(view, entry->size, state->size_width,
5514 line->type != LINE_TREE_FILE))
5515 return TRUE;
5517 if (draw_date(view, &entry->time))
5518 return TRUE;
5520 if (draw_id(view, entry->commit))
5521 return TRUE;
5524 draw_text(view, line->type, entry->name);
5525 return TRUE;
5528 static void
5529 open_blob_editor(const char *id, const char *name, unsigned int lineno)
5531 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
5532 char file[SIZEOF_STR];
5533 int fd;
5535 if (!name)
5536 name = "unknown";
5538 if (!string_format(file, "%s/tigblob.XXXXXX.%s", get_temp_dir(), name)) {
5539 report("Temporary file name is too long");
5540 return;
5543 fd = mkstemps(file, strlen(name) + 1);
5545 if (fd == -1)
5546 report("Failed to create temporary file");
5547 else if (!io_run_append(blob_argv, fd))
5548 report("Failed to save blob data to file");
5549 else
5550 open_editor(file, lineno);
5551 if (fd != -1)
5552 unlink(file);
5555 static enum request
5556 tree_request(struct view *view, enum request request, struct line *line)
5558 enum open_flags flags;
5559 struct tree_entry *entry = line->data;
5561 switch (request) {
5562 case REQ_VIEW_BLAME:
5563 if (line->type != LINE_TREE_FILE) {
5564 report("Blame only supported for files");
5565 return REQ_NONE;
5568 string_copy(opt_ref, view->vid);
5569 return request;
5571 case REQ_EDIT:
5572 if (line->type != LINE_TREE_FILE) {
5573 report("Edit only supported for files");
5574 } else if (!is_head_commit(view->vid)) {
5575 open_blob_editor(entry->id, entry->name, 0);
5576 } else {
5577 open_editor(opt_file, 0);
5579 return REQ_NONE;
5581 case REQ_TOGGLE_SORT_FIELD:
5582 case REQ_TOGGLE_SORT_ORDER:
5583 sort_view(view, request, &tree_sort_state, tree_compare);
5584 return REQ_NONE;
5586 case REQ_PARENT:
5587 case REQ_BACK:
5588 if (!*opt_path) {
5589 /* quit view if at top of tree */
5590 return REQ_VIEW_CLOSE;
5592 /* fake 'cd ..' */
5593 line = &view->line[1];
5594 break;
5596 case REQ_ENTER:
5597 break;
5599 default:
5600 return request;
5603 /* Cleanup the stack if the tree view is at a different tree. */
5604 if (!*opt_path)
5605 reset_view_history(&tree_view_history);
5607 switch (line->type) {
5608 case LINE_TREE_DIR:
5609 /* Depending on whether it is a subdirectory or parent link
5610 * mangle the path buffer. */
5611 if (line == &view->line[1] && *opt_path) {
5612 pop_tree_stack_entry(&view->pos);
5614 } else {
5615 const char *basename = tree_path(line);
5617 push_tree_stack_entry(basename, &view->pos);
5620 /* Trees and subtrees share the same ID, so they are not not
5621 * unique like blobs. */
5622 flags = OPEN_RELOAD;
5623 request = REQ_VIEW_TREE;
5624 break;
5626 case LINE_TREE_FILE:
5627 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5628 request = REQ_VIEW_BLOB;
5629 break;
5631 default:
5632 return REQ_NONE;
5635 open_view(view, request, flags);
5637 return REQ_NONE;
5640 static bool
5641 tree_grep(struct view *view, struct line *line)
5643 struct tree_entry *entry = line->data;
5644 const char *text[] = {
5645 entry->name,
5646 mkauthor(entry->author, opt_author_width, opt_author),
5647 mkdate(&entry->time, opt_date),
5648 NULL
5651 return grep_text(view, text);
5654 static void
5655 tree_select(struct view *view, struct line *line)
5657 struct tree_entry *entry = line->data;
5659 if (line->type == LINE_TREE_HEAD) {
5660 string_format(view->ref, "Files in /%s", opt_path);
5661 return;
5664 if (line->type == LINE_TREE_DIR && tree_path_is_parent(entry->name)) {
5665 string_copy(view->ref, "Open parent directory");
5666 ref_blob[0] = 0;
5667 return;
5670 if (line->type == LINE_TREE_FILE) {
5671 string_copy_rev(ref_blob, entry->id);
5672 string_format(opt_file, "%s%s", opt_path, tree_path(line));
5675 string_copy_rev(view->ref, entry->id);
5678 static bool
5679 tree_open(struct view *view, enum open_flags flags)
5681 static const char *tree_argv[] = {
5682 "git", "ls-tree", "-l", "%(commit)", "%(directory)", NULL
5685 if (string_rev_is_null(ref_commit)) {
5686 report("No tree exists for this commit");
5687 return FALSE;
5690 if (view->lines == 0 && opt_prefix[0]) {
5691 char *pos = opt_prefix;
5693 while (pos && *pos) {
5694 char *end = strchr(pos, '/');
5696 if (end)
5697 *end = 0;
5698 push_tree_stack_entry(pos, &view->pos);
5699 pos = end;
5700 if (end) {
5701 *end = '/';
5702 pos++;
5706 } else if (strcmp(view->vid, view->id)) {
5707 opt_path[0] = 0;
5710 return begin_update(view, opt_cdup, tree_argv, flags);
5713 static struct view_ops tree_ops = {
5714 "file",
5715 { "tree" },
5716 VIEW_SEND_CHILD_ENTER,
5717 sizeof(struct tree_state),
5718 tree_open,
5719 tree_read,
5720 tree_draw,
5721 tree_request,
5722 tree_grep,
5723 tree_select,
5726 static bool
5727 blob_open(struct view *view, enum open_flags flags)
5729 static const char *blob_argv[] = {
5730 "git", "cat-file", "blob", "%(blob)", NULL
5733 if (!ref_blob[0] && opt_file[0]) {
5734 const char *commit = ref_commit[0] ? ref_commit : "HEAD";
5735 char blob_spec[SIZEOF_STR];
5736 const char *rev_parse_argv[] = {
5737 "git", "rev-parse", blob_spec, NULL
5740 if (!string_format(blob_spec, "%s:%s", commit, opt_file) ||
5741 !io_run_buf(rev_parse_argv, ref_blob, sizeof(ref_blob))) {
5742 report("Failed to resolve blob from file name");
5743 return FALSE;
5747 if (!ref_blob[0]) {
5748 report("No file chosen, press %s to open tree view",
5749 get_view_key(view, REQ_VIEW_TREE));
5750 return FALSE;
5753 view->encoding = get_path_encoding(opt_file, default_encoding);
5755 return begin_update(view, NULL, blob_argv, flags);
5758 static bool
5759 blob_read(struct view *view, char *line)
5761 if (!line)
5762 return TRUE;
5763 return add_line_text(view, line, LINE_DEFAULT) != NULL;
5766 static enum request
5767 blob_request(struct view *view, enum request request, struct line *line)
5769 switch (request) {
5770 case REQ_EDIT:
5771 open_blob_editor(view->vid, NULL, (line - view->line) + 1);
5772 return REQ_NONE;
5773 default:
5774 return pager_request(view, request, line);
5778 static struct view_ops blob_ops = {
5779 "line",
5780 { "blob" },
5781 VIEW_NO_FLAGS,
5783 blob_open,
5784 blob_read,
5785 pager_draw,
5786 blob_request,
5787 pager_grep,
5788 pager_select,
5792 * Blame backend
5794 * Loading the blame view is a two phase job:
5796 * 1. File content is read either using opt_file from the
5797 * filesystem or using git-cat-file.
5798 * 2. Then blame information is incrementally added by
5799 * reading output from git-blame.
5802 struct blame_history_state {
5803 char id[SIZEOF_REV]; /* SHA1 ID. */
5804 const char *filename; /* Name of file. */
5807 static struct view_history blame_view_history = { sizeof(struct blame_history_state) };
5809 struct blame {
5810 struct blame_commit *commit;
5811 unsigned long lineno;
5812 char text[1];
5815 struct blame_state {
5816 struct blame_commit *commit;
5817 int blamed;
5818 bool done_reading;
5819 bool auto_filename_display;
5820 /* The history state for the current view is cached in the view
5821 * state so it always matches what was used to load the current blame
5822 * view. */
5823 struct blame_history_state history_state;
5826 static bool
5827 blame_detect_filename_display(struct view *view)
5829 bool show_filenames = FALSE;
5830 const char *filename = NULL;
5831 int i;
5833 if (opt_blame_argv) {
5834 for (i = 0; opt_blame_argv[i]; i++) {
5835 if (prefixcmp(opt_blame_argv[i], "-C"))
5836 continue;
5838 show_filenames = TRUE;
5842 for (i = 0; i < view->lines; i++) {
5843 struct blame *blame = view->line[i].data;
5845 if (blame->commit && blame->commit->id[0]) {
5846 if (!filename)
5847 filename = blame->commit->filename;
5848 else if (strcmp(filename, blame->commit->filename))
5849 show_filenames = TRUE;
5853 return show_filenames;
5856 static bool
5857 blame_open(struct view *view, enum open_flags flags)
5859 struct blame_state *state = view->private;
5860 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5861 char path[SIZEOF_STR];
5862 size_t i;
5864 if (!opt_file[0]) {
5865 report("No file chosen, press %s to open tree view",
5866 get_view_key(view, REQ_VIEW_TREE));
5867 return FALSE;
5870 if (!view->prev && *opt_prefix && !(flags & (OPEN_RELOAD | OPEN_REFRESH))) {
5871 string_copy(path, opt_file);
5872 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
5873 report("Failed to setup the blame view");
5874 return FALSE;
5878 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5879 const char *blame_cat_file_argv[] = {
5880 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5883 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5884 return FALSE;
5887 /* First pass: remove multiple references to the same commit. */
5888 for (i = 0; i < view->lines; i++) {
5889 struct blame *blame = view->line[i].data;
5891 if (blame->commit && blame->commit->id[0])
5892 blame->commit->id[0] = 0;
5893 else
5894 blame->commit = NULL;
5897 /* Second pass: free existing references. */
5898 for (i = 0; i < view->lines; i++) {
5899 struct blame *blame = view->line[i].data;
5901 if (blame->commit)
5902 free(blame->commit);
5905 if (!(flags & OPEN_RELOAD))
5906 reset_view_history(&blame_view_history);
5907 string_copy_rev(state->history_state.id, opt_ref);
5908 state->history_state.filename = get_path(opt_file);
5909 if (!state->history_state.filename)
5910 return FALSE;
5911 string_format(view->vid, "%s", opt_file);
5912 string_format(view->ref, "%s ...", opt_file);
5914 return TRUE;
5917 static struct blame_commit *
5918 get_blame_commit(struct view *view, const char *id)
5920 size_t i;
5922 for (i = 0; i < view->lines; i++) {
5923 struct blame *blame = view->line[i].data;
5925 if (!blame->commit)
5926 continue;
5928 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5929 return blame->commit;
5933 struct blame_commit *commit = calloc(1, sizeof(*commit));
5935 if (commit)
5936 string_ncopy(commit->id, id, SIZEOF_REV);
5937 return commit;
5941 static struct blame_commit *
5942 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5944 struct blame_header header;
5945 struct blame_commit *commit;
5946 struct blame *blame;
5948 if (!parse_blame_header(&header, text, view->lines))
5949 return NULL;
5951 commit = get_blame_commit(view, text);
5952 if (!commit)
5953 return NULL;
5955 state->blamed += header.group;
5956 while (header.group--) {
5957 struct line *line = &view->line[header.lineno + header.group - 1];
5959 blame = line->data;
5960 blame->commit = commit;
5961 blame->lineno = header.orig_lineno + header.group - 1;
5962 line->dirty = 1;
5965 return commit;
5968 static bool
5969 blame_read_file(struct view *view, const char *text, struct blame_state *state)
5971 if (!text) {
5972 const char *blame_argv[] = {
5973 "git", "blame", encoding_arg, "%(blameargs)", "--incremental",
5974 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
5977 if (view->lines == 0 && !view->prev)
5978 die("No blame exist for %s", view->vid);
5980 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
5981 report("Failed to load blame data");
5982 return TRUE;
5985 if (opt_goto_line > 0) {
5986 select_view_line(view, opt_goto_line);
5987 opt_goto_line = 0;
5990 state->done_reading = TRUE;
5991 return FALSE;
5993 } else {
5994 size_t textlen = strlen(text);
5995 struct blame *blame;
5997 if (!add_line_alloc(view, &blame, LINE_ID, textlen, FALSE))
5998 return FALSE;
6000 blame->commit = NULL;
6001 strncpy(blame->text, text, textlen);
6002 blame->text[textlen] = 0;
6003 return TRUE;
6007 static bool
6008 blame_read(struct view *view, char *line)
6010 struct blame_state *state = view->private;
6012 if (!state->done_reading)
6013 return blame_read_file(view, line, state);
6015 if (!line) {
6016 state->auto_filename_display = blame_detect_filename_display(view);
6017 string_format(view->ref, "%s", view->vid);
6018 if (view_is_displayed(view)) {
6019 update_view_title(view);
6020 redraw_view_from(view, 0);
6022 return TRUE;
6025 if (!state->commit) {
6026 state->commit = read_blame_commit(view, line, state);
6027 string_format(view->ref, "%s %2zd%%", view->vid,
6028 view->lines ? state->blamed * 100 / view->lines : 0);
6030 } else if (parse_blame_info(state->commit, line)) {
6031 if (!state->commit->filename)
6032 return FALSE;
6033 state->commit = NULL;
6036 return TRUE;
6039 static bool
6040 blame_draw(struct view *view, struct line *line, unsigned int lineno)
6042 struct blame_state *state = view->private;
6043 struct blame *blame = line->data;
6044 struct time *time = NULL;
6045 const char *id = NULL, *filename = NULL;
6046 const struct ident *author = NULL;
6047 enum line_type id_type = LINE_ID;
6048 static const enum line_type blame_colors[] = {
6049 LINE_PALETTE_0,
6050 LINE_PALETTE_1,
6051 LINE_PALETTE_2,
6052 LINE_PALETTE_3,
6053 LINE_PALETTE_4,
6054 LINE_PALETTE_5,
6055 LINE_PALETTE_6,
6058 #define BLAME_COLOR(i) \
6059 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
6061 if (blame->commit && *blame->commit->filename) {
6062 id = blame->commit->id;
6063 author = blame->commit->author;
6064 filename = blame->commit->filename;
6065 time = &blame->commit->time;
6066 id_type = BLAME_COLOR((long) blame->commit);
6069 if (draw_date(view, time))
6070 return TRUE;
6072 if (draw_author(view, author))
6073 return TRUE;
6075 if (draw_filename(view, filename, state->auto_filename_display))
6076 return TRUE;
6078 if (draw_id_custom(view, id_type, id, opt_id_cols))
6079 return TRUE;
6081 if (draw_lineno(view, lineno))
6082 return TRUE;
6084 draw_text(view, LINE_DEFAULT, blame->text);
6085 return TRUE;
6088 static bool
6089 check_blame_commit(struct blame *blame, bool check_null_id)
6091 if (!blame->commit)
6092 report("Commit data not loaded yet");
6093 else if (check_null_id && string_rev_is_null(blame->commit->id))
6094 report("No commit exist for the selected line");
6095 else
6096 return TRUE;
6097 return FALSE;
6100 static void
6101 setup_blame_parent_line(struct view *view, struct blame *blame)
6103 char from[SIZEOF_REF + SIZEOF_STR];
6104 char to[SIZEOF_REF + SIZEOF_STR];
6105 const char *diff_tree_argv[] = {
6106 "git", "diff", encoding_arg, "--no-textconv", "--no-extdiff",
6107 "--no-color", "-U0", from, to, "--", NULL
6109 struct io io;
6110 int parent_lineno = -1;
6111 int blamed_lineno = -1;
6112 char *line;
6114 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
6115 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
6116 !io_run(&io, IO_RD, NULL, opt_env, diff_tree_argv))
6117 return;
6119 while ((line = io_get(&io, '\n', TRUE))) {
6120 if (*line == '@') {
6121 char *pos = strchr(line, '+');
6123 parent_lineno = atoi(line + 4);
6124 if (pos)
6125 blamed_lineno = atoi(pos + 1);
6127 } else if (*line == '+' && parent_lineno != -1) {
6128 if (blame->lineno == blamed_lineno - 1 &&
6129 !strcmp(blame->text, line + 1)) {
6130 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
6131 break;
6133 blamed_lineno++;
6137 io_done(&io);
6140 static void
6141 blame_go_forward(struct view *view, struct blame *blame, bool parent)
6143 struct blame_state *state = view->private;
6144 struct blame_history_state *history_state = &state->history_state;
6145 struct blame_commit *commit = blame->commit;
6146 const char *id = parent ? commit->parent_id : commit->id;
6147 const char *filename = parent ? commit->parent_filename : commit->filename;
6149 if (!*id && parent) {
6150 report("The selected commit has no parents");
6151 return;
6154 if (!strcmp(history_state->id, id) && !strcmp(history_state->filename, filename)) {
6155 report("The selected commit is already displayed");
6156 return;
6159 if (!push_view_history_state(&blame_view_history, &view->pos, history_state)) {
6160 report("Failed to save current view state");
6161 return;
6164 string_ncopy(opt_ref, id, sizeof(commit->id));
6165 string_ncopy(opt_file, filename, strlen(filename));
6166 if (parent)
6167 setup_blame_parent_line(view, blame);
6168 opt_goto_line = blame->lineno;
6169 reload_view(view);
6172 static void
6173 blame_go_back(struct view *view)
6175 struct blame_history_state history_state;
6177 if (!pop_view_history_state(&blame_view_history, &view->pos, &history_state)) {
6178 report("Already at start of history");
6179 return;
6182 string_copy(opt_ref, history_state.id);
6183 string_ncopy(opt_file, history_state.filename, strlen(history_state.filename));
6184 opt_goto_line = view->pos.lineno;
6185 reload_view(view);
6188 static enum request
6189 blame_request(struct view *view, enum request request, struct line *line)
6191 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6192 struct blame *blame = line->data;
6194 switch (request) {
6195 case REQ_VIEW_BLAME:
6196 case REQ_PARENT:
6197 if (!check_blame_commit(blame, TRUE))
6198 break;
6199 blame_go_forward(view, blame, request == REQ_PARENT);
6200 break;
6202 case REQ_BACK:
6203 blame_go_back(view);
6204 break;
6206 case REQ_ENTER:
6207 if (!check_blame_commit(blame, FALSE))
6208 break;
6210 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
6211 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
6212 break;
6214 if (string_rev_is_null(blame->commit->id)) {
6215 struct view *diff = VIEW(REQ_VIEW_DIFF);
6216 const char *diff_parent_argv[] = {
6217 GIT_DIFF_BLAME(encoding_arg,
6218 opt_diff_context_arg,
6219 opt_ignore_space_arg, view->vid)
6221 const char *diff_no_parent_argv[] = {
6222 GIT_DIFF_BLAME_NO_PARENT(encoding_arg,
6223 opt_diff_context_arg,
6224 opt_ignore_space_arg, view->vid)
6226 const char **diff_index_argv = *blame->commit->parent_id
6227 ? diff_parent_argv : diff_no_parent_argv;
6229 open_argv(view, diff, diff_index_argv, NULL, flags);
6230 if (diff->pipe)
6231 string_copy_rev(diff->ref, NULL_ID);
6232 } else {
6233 open_view(view, REQ_VIEW_DIFF, flags);
6235 break;
6237 default:
6238 return request;
6241 return REQ_NONE;
6244 static bool
6245 blame_grep(struct view *view, struct line *line)
6247 struct blame *blame = line->data;
6248 struct blame_commit *commit = blame->commit;
6249 const char *text[] = {
6250 blame->text,
6251 commit ? commit->title : "",
6252 commit ? commit->id : "",
6253 commit ? mkauthor(commit->author, opt_author_width, opt_author) : "",
6254 commit ? mkdate(&commit->time, opt_date) : "",
6255 NULL
6258 return grep_text(view, text);
6261 static void
6262 blame_select(struct view *view, struct line *line)
6264 struct blame *blame = line->data;
6265 struct blame_commit *commit = blame->commit;
6267 if (!commit)
6268 return;
6270 if (string_rev_is_null(commit->id))
6271 string_ncopy(ref_commit, "HEAD", 4);
6272 else
6273 string_copy_rev(ref_commit, commit->id);
6276 static struct view_ops blame_ops = {
6277 "line",
6278 { "blame" },
6279 VIEW_ALWAYS_LINENO | VIEW_SEND_CHILD_ENTER,
6280 sizeof(struct blame_state),
6281 blame_open,
6282 blame_read,
6283 blame_draw,
6284 blame_request,
6285 blame_grep,
6286 blame_select,
6290 * Branch backend
6293 struct branch {
6294 const struct ident *author; /* Author of the last commit. */
6295 struct time time; /* Date of the last activity. */
6296 char title[128]; /* First line of the commit message. */
6297 const struct ref *ref; /* Name and commit ID information. */
6300 static const struct ref branch_all;
6301 #define BRANCH_ALL_NAME "All branches"
6302 #define branch_is_all(branch) ((branch)->ref == &branch_all)
6304 static const enum sort_field branch_sort_fields[] = {
6305 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
6307 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
6309 struct branch_state {
6310 char id[SIZEOF_REV];
6311 size_t max_ref_length;
6314 static int
6315 branch_compare(const void *l1, const void *l2)
6317 const struct branch *branch1 = ((const struct line *) l1)->data;
6318 const struct branch *branch2 = ((const struct line *) l2)->data;
6320 if (branch_is_all(branch1))
6321 return -1;
6322 else if (branch_is_all(branch2))
6323 return 1;
6325 switch (get_sort_field(branch_sort_state)) {
6326 case ORDERBY_DATE:
6327 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
6329 case ORDERBY_AUTHOR:
6330 return sort_order(branch_sort_state, ident_compare(branch1->author, branch2->author));
6332 case ORDERBY_NAME:
6333 default:
6334 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
6338 static bool
6339 branch_draw(struct view *view, struct line *line, unsigned int lineno)
6341 struct branch_state *state = view->private;
6342 struct branch *branch = line->data;
6343 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
6344 const char *branch_name = branch_is_all(branch) ? BRANCH_ALL_NAME : branch->ref->name;
6346 if (draw_lineno(view, lineno))
6347 return TRUE;
6349 if (draw_date(view, &branch->time))
6350 return TRUE;
6352 if (draw_author(view, branch->author))
6353 return TRUE;
6355 if (draw_field(view, type, branch_name, state->max_ref_length, ALIGN_LEFT, FALSE))
6356 return TRUE;
6358 if (draw_id(view, branch->ref->id))
6359 return TRUE;
6361 draw_text(view, LINE_DEFAULT, branch->title);
6362 return TRUE;
6365 static enum request
6366 branch_request(struct view *view, enum request request, struct line *line)
6368 struct branch *branch = line->data;
6370 switch (request) {
6371 case REQ_REFRESH:
6372 load_refs(TRUE);
6373 refresh_view(view);
6374 return REQ_NONE;
6376 case REQ_TOGGLE_SORT_FIELD:
6377 case REQ_TOGGLE_SORT_ORDER:
6378 sort_view(view, request, &branch_sort_state, branch_compare);
6379 return REQ_NONE;
6381 case REQ_ENTER:
6383 const struct ref *ref = branch->ref;
6384 const char *all_branches_argv[] = {
6385 GIT_MAIN_LOG(encoding_arg, "", branch_is_all(branch) ? "--all" : ref->name, "")
6387 struct view *main_view = VIEW(REQ_VIEW_MAIN);
6389 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
6390 return REQ_NONE;
6392 case REQ_JUMP_COMMIT:
6394 int lineno;
6396 for (lineno = 0; lineno < view->lines; lineno++) {
6397 struct branch *branch = view->line[lineno].data;
6399 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
6400 select_view_line(view, lineno);
6401 report_clear();
6402 return REQ_NONE;
6406 default:
6407 return request;
6411 static bool
6412 branch_read(struct view *view, char *line)
6414 struct branch_state *state = view->private;
6415 const char *title = NULL;
6416 const struct ident *author = NULL;
6417 struct time time = {};
6418 size_t i;
6420 if (!line)
6421 return TRUE;
6423 switch (get_line_type(line)) {
6424 case LINE_COMMIT:
6425 string_copy_rev_from_commit_line(state->id, line);
6426 return TRUE;
6428 case LINE_AUTHOR:
6429 parse_author_line(line + STRING_SIZE("author "), &author, &time);
6430 break;
6432 default:
6433 title = line + STRING_SIZE("title ");
6436 for (i = 0; i < view->lines; i++) {
6437 struct branch *branch = view->line[i].data;
6439 if (strcmp(branch->ref->id, state->id))
6440 continue;
6442 if (author) {
6443 branch->author = author;
6444 branch->time = time;
6447 if (title)
6448 string_expand(branch->title, sizeof(branch->title), title, 1);
6450 view->line[i].dirty = TRUE;
6453 return TRUE;
6456 static bool
6457 branch_open_visitor(void *data, const struct ref *ref)
6459 struct view *view = data;
6460 struct branch_state *state = view->private;
6461 struct branch *branch;
6462 bool is_all = ref == &branch_all;
6463 size_t ref_length;
6465 if (ref->tag || ref->ltag)
6466 return TRUE;
6468 if (!add_line_alloc(view, &branch, LINE_DEFAULT, 0, is_all))
6469 return FALSE;
6471 ref_length = is_all ? STRING_SIZE(BRANCH_ALL_NAME) : strlen(ref->name);
6472 if (ref_length > state->max_ref_length)
6473 state->max_ref_length = ref_length;
6475 branch->ref = ref;
6476 return TRUE;
6479 static bool
6480 branch_open(struct view *view, enum open_flags flags)
6482 const char *branch_log[] = {
6483 "git", "log", encoding_arg, "--no-color", "--date=raw",
6484 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
6485 "--all", "--simplify-by-decoration", NULL
6488 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
6489 report("Failed to load branch data");
6490 return FALSE;
6493 branch_open_visitor(view, &branch_all);
6494 foreach_ref(branch_open_visitor, view);
6496 return TRUE;
6499 static bool
6500 branch_grep(struct view *view, struct line *line)
6502 struct branch *branch = line->data;
6503 const char *text[] = {
6504 branch->ref->name,
6505 mkauthor(branch->author, opt_author_width, opt_author),
6506 NULL
6509 return grep_text(view, text);
6512 static void
6513 branch_select(struct view *view, struct line *line)
6515 struct branch *branch = line->data;
6517 if (branch_is_all(branch)) {
6518 string_copy(view->ref, BRANCH_ALL_NAME);
6519 return;
6521 string_copy_rev(view->ref, branch->ref->id);
6522 string_copy_rev(ref_commit, branch->ref->id);
6523 string_copy_rev(ref_head, branch->ref->id);
6524 string_copy_rev(ref_branch, branch->ref->name);
6527 static struct view_ops branch_ops = {
6528 "branch",
6529 { "branch" },
6530 VIEW_NO_FLAGS,
6531 sizeof(struct branch_state),
6532 branch_open,
6533 branch_read,
6534 branch_draw,
6535 branch_request,
6536 branch_grep,
6537 branch_select,
6541 * Status backend
6544 struct status {
6545 char status;
6546 struct {
6547 mode_t mode;
6548 char rev[SIZEOF_REV];
6549 char name[SIZEOF_STR];
6550 } old;
6551 struct {
6552 mode_t mode;
6553 char rev[SIZEOF_REV];
6554 char name[SIZEOF_STR];
6555 } new;
6558 static char status_onbranch[SIZEOF_STR];
6559 static struct status stage_status;
6560 static enum line_type stage_line_type;
6562 DEFINE_ALLOCATOR(realloc_ints, int, 32)
6564 /* This should work even for the "On branch" line. */
6565 static inline bool
6566 status_has_none(struct view *view, struct line *line)
6568 return view_has_line(view, line) && !line[1].data;
6571 /* Get fields from the diff line:
6572 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
6574 static inline bool
6575 status_get_diff(struct status *file, const char *buf, size_t bufsize)
6577 const char *old_mode = buf + 1;
6578 const char *new_mode = buf + 8;
6579 const char *old_rev = buf + 15;
6580 const char *new_rev = buf + 56;
6581 const char *status = buf + 97;
6583 if (bufsize < 98 ||
6584 old_mode[-1] != ':' ||
6585 new_mode[-1] != ' ' ||
6586 old_rev[-1] != ' ' ||
6587 new_rev[-1] != ' ' ||
6588 status[-1] != ' ')
6589 return FALSE;
6591 file->status = *status;
6593 string_copy_rev(file->old.rev, old_rev);
6594 string_copy_rev(file->new.rev, new_rev);
6596 file->old.mode = strtoul(old_mode, NULL, 8);
6597 file->new.mode = strtoul(new_mode, NULL, 8);
6599 file->old.name[0] = file->new.name[0] = 0;
6601 return TRUE;
6604 static bool
6605 status_run(struct view *view, const char *argv[], char status, enum line_type type)
6607 struct status *unmerged = NULL;
6608 char *buf;
6609 struct io io;
6611 if (!io_run(&io, IO_RD, opt_cdup, opt_env, argv))
6612 return FALSE;
6614 add_line_nodata(view, type);
6616 while ((buf = io_get(&io, 0, TRUE))) {
6617 struct status *file = unmerged;
6619 if (!file) {
6620 if (!add_line_alloc(view, &file, type, 0, FALSE))
6621 goto error_out;
6624 /* Parse diff info part. */
6625 if (status) {
6626 file->status = status;
6627 if (status == 'A')
6628 string_copy(file->old.rev, NULL_ID);
6630 } else if (!file->status || file == unmerged) {
6631 if (!status_get_diff(file, buf, strlen(buf)))
6632 goto error_out;
6634 buf = io_get(&io, 0, TRUE);
6635 if (!buf)
6636 break;
6638 /* Collapse all modified entries that follow an
6639 * associated unmerged entry. */
6640 if (unmerged == file) {
6641 unmerged->status = 'U';
6642 unmerged = NULL;
6643 } else if (file->status == 'U') {
6644 unmerged = file;
6648 /* Grab the old name for rename/copy. */
6649 if (!*file->old.name &&
6650 (file->status == 'R' || file->status == 'C')) {
6651 string_ncopy(file->old.name, buf, strlen(buf));
6653 buf = io_get(&io, 0, TRUE);
6654 if (!buf)
6655 break;
6658 /* git-ls-files just delivers a NUL separated list of
6659 * file names similar to the second half of the
6660 * git-diff-* output. */
6661 string_ncopy(file->new.name, buf, strlen(buf));
6662 if (!*file->old.name)
6663 string_copy(file->old.name, file->new.name);
6664 file = NULL;
6667 if (io_error(&io)) {
6668 error_out:
6669 io_done(&io);
6670 return FALSE;
6673 if (!view->line[view->lines - 1].data)
6674 add_line_nodata(view, LINE_STAT_NONE);
6676 io_done(&io);
6677 return TRUE;
6680 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
6681 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
6683 static const char *status_list_other_argv[] = {
6684 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
6687 static const char *status_list_no_head_argv[] = {
6688 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
6691 static const char *update_index_argv[] = {
6692 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
6695 /* Restore the previous line number to stay in the context or select a
6696 * line with something that can be updated. */
6697 static void
6698 status_restore(struct view *view)
6700 if (!check_position(&view->prev_pos))
6701 return;
6703 if (view->prev_pos.lineno >= view->lines)
6704 view->prev_pos.lineno = view->lines - 1;
6705 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
6706 view->prev_pos.lineno++;
6707 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
6708 view->prev_pos.lineno--;
6710 /* If the above fails, always skip the "On branch" line. */
6711 if (view->prev_pos.lineno < view->lines)
6712 view->pos.lineno = view->prev_pos.lineno;
6713 else
6714 view->pos.lineno = 1;
6716 if (view->prev_pos.offset > view->pos.lineno)
6717 view->pos.offset = view->pos.lineno;
6718 else if (view->prev_pos.offset < view->lines)
6719 view->pos.offset = view->prev_pos.offset;
6721 clear_position(&view->prev_pos);
6724 static void
6725 status_update_onbranch(void)
6727 static const char *paths[][2] = {
6728 { "rebase-apply/rebasing", "Rebasing" },
6729 { "rebase-apply/applying", "Applying mailbox" },
6730 { "rebase-apply/", "Rebasing mailbox" },
6731 { "rebase-merge/interactive", "Interactive rebase" },
6732 { "rebase-merge/", "Rebase merge" },
6733 { "MERGE_HEAD", "Merging" },
6734 { "BISECT_LOG", "Bisecting" },
6735 { "HEAD", "On branch" },
6737 char buf[SIZEOF_STR];
6738 struct stat stat;
6739 int i;
6741 if (is_initial_commit()) {
6742 string_copy(status_onbranch, "Initial commit");
6743 return;
6746 for (i = 0; i < ARRAY_SIZE(paths); i++) {
6747 char *head = opt_head;
6749 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
6750 lstat(buf, &stat) < 0)
6751 continue;
6753 if (!*opt_head) {
6754 struct io io;
6756 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
6757 io_read_buf(&io, buf, sizeof(buf))) {
6758 head = buf;
6759 if (!prefixcmp(head, "refs/heads/"))
6760 head += STRING_SIZE("refs/heads/");
6764 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
6765 string_copy(status_onbranch, opt_head);
6766 return;
6769 string_copy(status_onbranch, "Not currently on any branch");
6772 /* First parse staged info using git-diff-index(1), then parse unstaged
6773 * info using git-diff-files(1), and finally untracked files using
6774 * git-ls-files(1). */
6775 static bool
6776 status_open(struct view *view, enum open_flags flags)
6778 const char **staged_argv = is_initial_commit() ?
6779 status_list_no_head_argv : status_diff_index_argv;
6780 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
6782 if (opt_is_inside_work_tree == FALSE) {
6783 report("The status view requires a working tree");
6784 return FALSE;
6787 reset_view(view);
6789 add_line_nodata(view, LINE_STAT_HEAD);
6790 status_update_onbranch();
6792 io_run_bg(update_index_argv);
6794 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] =
6795 opt_untracked_dirs_content ? NULL : "--directory";
6797 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
6798 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
6799 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
6800 report("Failed to load status data");
6801 return FALSE;
6804 /* Restore the exact position or use the specialized restore
6805 * mode? */
6806 status_restore(view);
6807 return TRUE;
6810 static bool
6811 status_draw(struct view *view, struct line *line, unsigned int lineno)
6813 struct status *status = line->data;
6814 enum line_type type;
6815 const char *text;
6817 if (!status) {
6818 switch (line->type) {
6819 case LINE_STAT_STAGED:
6820 type = LINE_STAT_SECTION;
6821 text = "Changes to be committed:";
6822 break;
6824 case LINE_STAT_UNSTAGED:
6825 type = LINE_STAT_SECTION;
6826 text = "Changed but not updated:";
6827 break;
6829 case LINE_STAT_UNTRACKED:
6830 type = LINE_STAT_SECTION;
6831 text = "Untracked files:";
6832 break;
6834 case LINE_STAT_NONE:
6835 type = LINE_DEFAULT;
6836 text = " (no files)";
6837 break;
6839 case LINE_STAT_HEAD:
6840 type = LINE_STAT_HEAD;
6841 text = status_onbranch;
6842 break;
6844 default:
6845 return FALSE;
6847 } else {
6848 static char buf[] = { '?', ' ', ' ', ' ', 0 };
6850 buf[0] = status->status;
6851 if (draw_text(view, line->type, buf))
6852 return TRUE;
6853 type = LINE_DEFAULT;
6854 text = status->new.name;
6857 draw_text(view, type, text);
6858 return TRUE;
6861 static enum request
6862 status_enter(struct view *view, struct line *line)
6864 struct status *status = line->data;
6865 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6867 if (line->type == LINE_STAT_NONE ||
6868 (!status && line[1].type == LINE_STAT_NONE)) {
6869 report("No file to diff");
6870 return REQ_NONE;
6873 switch (line->type) {
6874 case LINE_STAT_STAGED:
6875 case LINE_STAT_UNSTAGED:
6876 break;
6878 case LINE_STAT_UNTRACKED:
6879 if (!status) {
6880 report("No file to show");
6881 return REQ_NONE;
6884 if (!suffixcmp(status->new.name, -1, "/")) {
6885 report("Cannot display a directory");
6886 return REQ_NONE;
6888 break;
6890 case LINE_STAT_HEAD:
6891 return REQ_NONE;
6893 default:
6894 die("line type %d not handled in switch", line->type);
6897 if (status) {
6898 stage_status = *status;
6899 } else {
6900 memset(&stage_status, 0, sizeof(stage_status));
6903 stage_line_type = line->type;
6905 open_view(view, REQ_VIEW_STAGE, flags);
6906 return REQ_NONE;
6909 static bool
6910 status_exists(struct view *view, struct status *status, enum line_type type)
6912 unsigned long lineno;
6914 for (lineno = 0; lineno < view->lines; lineno++) {
6915 struct line *line = &view->line[lineno];
6916 struct status *pos = line->data;
6918 if (line->type != type)
6919 continue;
6920 if (!pos && (!status || !status->status) && line[1].data) {
6921 select_view_line(view, lineno);
6922 return TRUE;
6924 if (pos && !strcmp(status->new.name, pos->new.name)) {
6925 select_view_line(view, lineno);
6926 return TRUE;
6930 return FALSE;
6934 static bool
6935 status_update_prepare(struct io *io, enum line_type type)
6937 const char *staged_argv[] = {
6938 "git", "update-index", "-z", "--index-info", NULL
6940 const char *others_argv[] = {
6941 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
6944 switch (type) {
6945 case LINE_STAT_STAGED:
6946 return io_run(io, IO_WR, opt_cdup, opt_env, staged_argv);
6948 case LINE_STAT_UNSTAGED:
6949 case LINE_STAT_UNTRACKED:
6950 return io_run(io, IO_WR, opt_cdup, opt_env, others_argv);
6952 default:
6953 die("line type %d not handled in switch", type);
6954 return FALSE;
6958 static bool
6959 status_update_write(struct io *io, struct status *status, enum line_type type)
6961 switch (type) {
6962 case LINE_STAT_STAGED:
6963 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
6964 status->old.rev, status->old.name, 0);
6966 case LINE_STAT_UNSTAGED:
6967 case LINE_STAT_UNTRACKED:
6968 return io_printf(io, "%s%c", status->new.name, 0);
6970 default:
6971 die("line type %d not handled in switch", type);
6972 return FALSE;
6976 static bool
6977 status_update_file(struct status *status, enum line_type type)
6979 struct io io;
6980 bool result;
6982 if (!status_update_prepare(&io, type))
6983 return FALSE;
6985 result = status_update_write(&io, status, type);
6986 return io_done(&io) && result;
6989 static bool
6990 status_update_files(struct view *view, struct line *line)
6992 char buf[sizeof(view->ref)];
6993 struct io io;
6994 bool result = TRUE;
6995 struct line *pos;
6996 int files = 0;
6997 int file, done;
6998 int cursor_y = -1, cursor_x = -1;
7000 if (!status_update_prepare(&io, line->type))
7001 return FALSE;
7003 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
7004 files++;
7006 string_copy(buf, view->ref);
7007 getsyx(cursor_y, cursor_x);
7008 for (file = 0, done = 5; result && file < files; line++, file++) {
7009 int almost_done = file * 100 / files;
7011 if (almost_done > done) {
7012 done = almost_done;
7013 string_format(view->ref, "updating file %u of %u (%d%% done)",
7014 file, files, done);
7015 update_view_title(view);
7016 setsyx(cursor_y, cursor_x);
7017 doupdate();
7019 result = status_update_write(&io, line->data, line->type);
7021 string_copy(view->ref, buf);
7023 return io_done(&io) && result;
7026 static bool
7027 status_update(struct view *view)
7029 struct line *line = &view->line[view->pos.lineno];
7031 assert(view->lines);
7033 if (!line->data) {
7034 if (status_has_none(view, line)) {
7035 report("Nothing to update");
7036 return FALSE;
7039 if (!status_update_files(view, line + 1)) {
7040 report("Failed to update file status");
7041 return FALSE;
7044 } else if (!status_update_file(line->data, line->type)) {
7045 report("Failed to update file status");
7046 return FALSE;
7049 return TRUE;
7052 static bool
7053 status_revert(struct status *status, enum line_type type, bool has_none)
7055 if (!status || type != LINE_STAT_UNSTAGED) {
7056 if (type == LINE_STAT_STAGED) {
7057 report("Cannot revert changes to staged files");
7058 } else if (type == LINE_STAT_UNTRACKED) {
7059 report("Cannot revert changes to untracked files");
7060 } else if (has_none) {
7061 report("Nothing to revert");
7062 } else {
7063 report("Cannot revert changes to multiple files");
7066 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
7067 char mode[10] = "100644";
7068 const char *reset_argv[] = {
7069 "git", "update-index", "--cacheinfo", mode,
7070 status->old.rev, status->old.name, NULL
7072 const char *checkout_argv[] = {
7073 "git", "checkout", "--", status->old.name, NULL
7076 if (status->status == 'U') {
7077 string_format(mode, "%5o", status->old.mode);
7079 if (status->old.mode == 0 && status->new.mode == 0) {
7080 reset_argv[2] = "--force-remove";
7081 reset_argv[3] = status->old.name;
7082 reset_argv[4] = NULL;
7085 if (!io_run_fg(reset_argv, opt_cdup))
7086 return FALSE;
7087 if (status->old.mode == 0 && status->new.mode == 0)
7088 return TRUE;
7091 return io_run_fg(checkout_argv, opt_cdup);
7094 return FALSE;
7097 static enum request
7098 status_request(struct view *view, enum request request, struct line *line)
7100 struct status *status = line->data;
7102 switch (request) {
7103 case REQ_STATUS_UPDATE:
7104 if (!status_update(view))
7105 return REQ_NONE;
7106 break;
7108 case REQ_STATUS_REVERT:
7109 if (!status_revert(status, line->type, status_has_none(view, line)))
7110 return REQ_NONE;
7111 break;
7113 case REQ_STATUS_MERGE:
7114 if (!status || status->status != 'U') {
7115 report("Merging only possible for files with unmerged status ('U').");
7116 return REQ_NONE;
7118 open_mergetool(status->new.name);
7119 break;
7121 case REQ_EDIT:
7122 if (!status)
7123 return request;
7124 if (status->status == 'D') {
7125 report("File has been deleted.");
7126 return REQ_NONE;
7129 open_editor(status->new.name, 0);
7130 break;
7132 case REQ_VIEW_BLAME:
7133 if (status)
7134 opt_ref[0] = 0;
7135 return request;
7137 case REQ_ENTER:
7138 /* After returning the status view has been split to
7139 * show the stage view. No further reloading is
7140 * necessary. */
7141 return status_enter(view, line);
7143 case REQ_REFRESH:
7144 /* Load the current branch information and then the view. */
7145 load_refs(TRUE);
7146 break;
7148 default:
7149 return request;
7152 refresh_view(view);
7154 return REQ_NONE;
7157 static bool
7158 status_stage_info_(char *buf, size_t bufsize,
7159 enum line_type type, struct status *status)
7161 const char *file = status ? status->new.name : "";
7162 const char *info;
7164 switch (type) {
7165 case LINE_STAT_STAGED:
7166 if (status && status->status)
7167 info = "Staged changes to %s";
7168 else
7169 info = "Staged changes";
7170 break;
7172 case LINE_STAT_UNSTAGED:
7173 if (status && status->status)
7174 info = "Unstaged changes to %s";
7175 else
7176 info = "Unstaged changes";
7177 break;
7179 case LINE_STAT_UNTRACKED:
7180 info = "Untracked file %s";
7181 break;
7183 case LINE_STAT_HEAD:
7184 default:
7185 info = "";
7188 return string_nformat(buf, bufsize, NULL, info, file);
7190 #define status_stage_info(buf, type, status) \
7191 status_stage_info_(buf, sizeof(buf), type, status)
7193 static void
7194 status_select(struct view *view, struct line *line)
7196 struct status *status = line->data;
7197 char file[SIZEOF_STR] = "all files";
7198 const char *text;
7199 const char *key;
7201 if (status && !string_format(file, "'%s'", status->new.name))
7202 return;
7204 if (!status && line[1].type == LINE_STAT_NONE)
7205 line++;
7207 switch (line->type) {
7208 case LINE_STAT_STAGED:
7209 text = "Press %s to unstage %s for commit";
7210 break;
7212 case LINE_STAT_UNSTAGED:
7213 text = "Press %s to stage %s for commit";
7214 break;
7216 case LINE_STAT_UNTRACKED:
7217 text = "Press %s to stage %s for addition";
7218 break;
7220 case LINE_STAT_HEAD:
7221 case LINE_STAT_NONE:
7222 text = "Nothing to update";
7223 break;
7225 default:
7226 die("line type %d not handled in switch", line->type);
7229 if (status && status->status == 'U') {
7230 text = "Press %s to resolve conflict in %s";
7231 key = get_view_key(view, REQ_STATUS_MERGE);
7233 } else {
7234 key = get_view_key(view, REQ_STATUS_UPDATE);
7237 string_format(view->ref, text, key, file);
7238 status_stage_info(ref_status, line->type, status);
7239 if (status)
7240 string_copy(opt_file, status->new.name);
7243 static bool
7244 status_grep(struct view *view, struct line *line)
7246 struct status *status = line->data;
7248 if (status) {
7249 const char buf[2] = { status->status, 0 };
7250 const char *text[] = { status->new.name, buf, NULL };
7252 return grep_text(view, text);
7255 return FALSE;
7258 static struct view_ops status_ops = {
7259 "file",
7260 { "status" },
7261 VIEW_CUSTOM_STATUS | VIEW_SEND_CHILD_ENTER | VIEW_STATUS_LIKE,
7263 status_open,
7264 NULL,
7265 status_draw,
7266 status_request,
7267 status_grep,
7268 status_select,
7272 struct stage_state {
7273 struct diff_state diff;
7274 size_t chunks;
7275 int *chunk;
7278 static bool
7279 stage_diff_write(struct io *io, struct line *line, struct line *end)
7281 while (line < end) {
7282 if (!io_write(io, line->data, strlen(line->data)) ||
7283 !io_write(io, "\n", 1))
7284 return FALSE;
7285 line++;
7286 if (line->type == LINE_DIFF_CHUNK ||
7287 line->type == LINE_DIFF_HEADER)
7288 break;
7291 return TRUE;
7294 static bool
7295 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
7297 const char *apply_argv[SIZEOF_ARG] = {
7298 "git", "apply", "--whitespace=nowarn", NULL
7300 struct line *diff_hdr;
7301 struct io io;
7302 int argc = 3;
7304 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
7305 if (!diff_hdr)
7306 return FALSE;
7308 if (!revert)
7309 apply_argv[argc++] = "--cached";
7310 if (line != NULL)
7311 apply_argv[argc++] = "--unidiff-zero";
7312 if (revert || stage_line_type == LINE_STAT_STAGED)
7313 apply_argv[argc++] = "-R";
7314 apply_argv[argc++] = "-";
7315 apply_argv[argc++] = NULL;
7316 if (!io_run(&io, IO_WR, opt_cdup, opt_env, apply_argv))
7317 return FALSE;
7319 if (line != NULL) {
7320 int lineno = 0;
7321 struct line *context = chunk + 1;
7322 const char *markers[] = {
7323 line->type == LINE_DIFF_DEL ? "" : ",0",
7324 line->type == LINE_DIFF_DEL ? ",0" : "",
7327 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
7329 while (context < line) {
7330 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
7331 break;
7332 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
7333 lineno++;
7335 context++;
7338 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7339 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
7340 lineno, markers[0], lineno, markers[1]) ||
7341 !stage_diff_write(&io, line, line + 1)) {
7342 chunk = NULL;
7344 } else {
7345 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7346 !stage_diff_write(&io, chunk, view->line + view->lines))
7347 chunk = NULL;
7350 io_done(&io);
7352 return chunk ? TRUE : FALSE;
7355 static bool
7356 stage_update(struct view *view, struct line *line, bool single)
7358 struct line *chunk = NULL;
7360 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
7361 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7363 if (chunk) {
7364 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
7365 report("Failed to apply chunk");
7366 return FALSE;
7369 } else if (!stage_status.status) {
7370 view = view->parent;
7372 for (line = view->line; view_has_line(view, line); line++)
7373 if (line->type == stage_line_type)
7374 break;
7376 if (!status_update_files(view, line + 1)) {
7377 report("Failed to update files");
7378 return FALSE;
7381 } else if (!status_update_file(&stage_status, stage_line_type)) {
7382 report("Failed to update file");
7383 return FALSE;
7386 return TRUE;
7389 static bool
7390 stage_revert(struct view *view, struct line *line)
7392 struct line *chunk = NULL;
7394 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
7395 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7397 if (chunk) {
7398 if (!prompt_yesno("Are you sure you want to revert changes?"))
7399 return FALSE;
7401 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
7402 report("Failed to revert chunk");
7403 return FALSE;
7405 return TRUE;
7407 } else {
7408 return status_revert(stage_status.status ? &stage_status : NULL,
7409 stage_line_type, FALSE);
7414 static void
7415 stage_next(struct view *view, struct line *line)
7417 struct stage_state *state = view->private;
7418 int i;
7420 if (!state->chunks) {
7421 for (line = view->line; view_has_line(view, line); line++) {
7422 if (line->type != LINE_DIFF_CHUNK)
7423 continue;
7425 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
7426 report("Allocation failure");
7427 return;
7430 state->chunk[state->chunks++] = line - view->line;
7434 for (i = 0; i < state->chunks; i++) {
7435 if (state->chunk[i] > view->pos.lineno) {
7436 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
7437 report("Chunk %d of %zd", i + 1, state->chunks);
7438 return;
7442 report("No next chunk found");
7445 static enum request
7446 stage_request(struct view *view, enum request request, struct line *line)
7448 switch (request) {
7449 case REQ_STATUS_UPDATE:
7450 if (!stage_update(view, line, FALSE))
7451 return REQ_NONE;
7452 break;
7454 case REQ_STATUS_REVERT:
7455 if (!stage_revert(view, line))
7456 return REQ_NONE;
7457 break;
7459 case REQ_STAGE_UPDATE_LINE:
7460 if (stage_line_type == LINE_STAT_UNTRACKED ||
7461 stage_status.status == 'A') {
7462 report("Staging single lines is not supported for new files");
7463 return REQ_NONE;
7465 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
7466 report("Please select a change to stage");
7467 return REQ_NONE;
7469 if (!stage_update(view, line, TRUE))
7470 return REQ_NONE;
7471 break;
7473 case REQ_STAGE_NEXT:
7474 if (stage_line_type == LINE_STAT_UNTRACKED) {
7475 report("File is untracked; press %s to add",
7476 get_view_key(view, REQ_STATUS_UPDATE));
7477 return REQ_NONE;
7479 stage_next(view, line);
7480 return REQ_NONE;
7482 case REQ_EDIT:
7483 if (!stage_status.new.name[0])
7484 return diff_common_edit(view, request, line);
7486 if (stage_status.status == 'D') {
7487 report("File has been deleted.");
7488 return REQ_NONE;
7491 if (stage_line_type == LINE_STAT_UNTRACKED) {
7492 open_editor(stage_status.new.name, (line - view->line) + 1);
7493 } else {
7494 open_editor(stage_status.new.name, diff_get_lineno(view, line));
7496 break;
7498 case REQ_REFRESH:
7499 /* Reload everything(including current branch information) ... */
7500 load_refs(TRUE);
7501 break;
7503 case REQ_VIEW_BLAME:
7504 if (stage_status.new.name[0]) {
7505 string_copy(opt_file, stage_status.new.name);
7506 opt_ref[0] = 0;
7508 return request;
7510 case REQ_ENTER:
7511 return diff_common_enter(view, request, line);
7513 case REQ_DIFF_CONTEXT_UP:
7514 case REQ_DIFF_CONTEXT_DOWN:
7515 if (!update_diff_context(request))
7516 return REQ_NONE;
7517 break;
7519 default:
7520 return request;
7523 refresh_view(view->parent);
7525 /* Check whether the staged entry still exists, and close the
7526 * stage view if it doesn't. */
7527 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
7528 status_restore(view->parent);
7529 return REQ_VIEW_CLOSE;
7532 refresh_view(view);
7534 return REQ_NONE;
7537 static bool
7538 stage_open(struct view *view, enum open_flags flags)
7540 static const char *no_head_diff_argv[] = {
7541 GIT_DIFF_STAGED_INITIAL(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7542 stage_status.new.name)
7544 static const char *index_show_argv[] = {
7545 GIT_DIFF_STAGED(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7546 stage_status.old.name, stage_status.new.name)
7548 static const char *files_show_argv[] = {
7549 GIT_DIFF_UNSTAGED(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7550 stage_status.old.name, stage_status.new.name)
7552 /* Diffs for unmerged entries are empty when passing the new
7553 * path, so leave out the new path. */
7554 static const char *files_unmerged_argv[] = {
7555 "git", "diff-files", encoding_arg, "--root", "--patch-with-stat",
7556 opt_diff_context_arg, opt_ignore_space_arg, "--",
7557 stage_status.old.name, NULL
7559 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
7560 const char **argv = NULL;
7562 if (!stage_line_type) {
7563 report("No stage content, press %s to open the status view and choose file",
7564 get_view_key(view, REQ_VIEW_STATUS));
7565 return FALSE;
7568 view->encoding = NULL;
7570 switch (stage_line_type) {
7571 case LINE_STAT_STAGED:
7572 if (is_initial_commit()) {
7573 argv = no_head_diff_argv;
7574 } else {
7575 argv = index_show_argv;
7577 break;
7579 case LINE_STAT_UNSTAGED:
7580 if (stage_status.status != 'U')
7581 argv = files_show_argv;
7582 else
7583 argv = files_unmerged_argv;
7584 break;
7586 case LINE_STAT_UNTRACKED:
7587 argv = file_argv;
7588 view->encoding = get_path_encoding(stage_status.old.name, default_encoding);
7589 break;
7591 case LINE_STAT_HEAD:
7592 default:
7593 die("line type %d not handled in switch", stage_line_type);
7596 if (!status_stage_info(view->ref, stage_line_type, &stage_status)
7597 || !argv_copy(&view->argv, argv)) {
7598 report("Failed to open staged view");
7599 return FALSE;
7602 view->vid[0] = 0;
7603 view->dir = opt_cdup;
7604 return begin_update(view, NULL, NULL, flags);
7607 static bool
7608 stage_read(struct view *view, char *data)
7610 struct stage_state *state = view->private;
7612 if (stage_line_type == LINE_STAT_UNTRACKED)
7613 return pager_common_read(view, data, LINE_DEFAULT);
7615 if (data && diff_common_read(view, data, &state->diff))
7616 return TRUE;
7618 return pager_read(view, data);
7621 static struct view_ops stage_ops = {
7622 "line",
7623 { "stage" },
7624 VIEW_DIFF_LIKE,
7625 sizeof(struct stage_state),
7626 stage_open,
7627 stage_read,
7628 diff_common_draw,
7629 stage_request,
7630 pager_grep,
7631 pager_select,
7636 * Revision graph
7639 static const enum line_type graph_colors[] = {
7640 LINE_PALETTE_0,
7641 LINE_PALETTE_1,
7642 LINE_PALETTE_2,
7643 LINE_PALETTE_3,
7644 LINE_PALETTE_4,
7645 LINE_PALETTE_5,
7646 LINE_PALETTE_6,
7649 static enum line_type get_graph_color(struct graph_symbol *symbol)
7651 if (symbol->commit)
7652 return LINE_GRAPH_COMMIT;
7653 assert(symbol->color < ARRAY_SIZE(graph_colors));
7654 return graph_colors[symbol->color];
7657 static bool
7658 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7660 const char *chars = graph_symbol_to_utf8(symbol);
7662 return draw_text(view, color, chars + !!first);
7665 static bool
7666 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7668 const char *chars = graph_symbol_to_ascii(symbol);
7670 return draw_text(view, color, chars + !!first);
7673 static bool
7674 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7676 const chtype *chars = graph_symbol_to_chtype(symbol);
7678 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
7681 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
7683 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
7685 static const draw_graph_fn fns[] = {
7686 draw_graph_ascii,
7687 draw_graph_chtype,
7688 draw_graph_utf8
7690 draw_graph_fn fn = fns[opt_line_graphics];
7691 int i;
7693 for (i = 0; i < canvas->size; i++) {
7694 struct graph_symbol *symbol = &canvas->symbols[i];
7695 enum line_type color = get_graph_color(symbol);
7697 if (fn(view, symbol, color, i == 0))
7698 return TRUE;
7701 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
7705 * Main view backend
7708 DEFINE_ALLOCATOR(realloc_reflogs, char *, 32)
7710 struct commit {
7711 char id[SIZEOF_REV]; /* SHA1 ID. */
7712 const struct ident *author; /* Author of the commit. */
7713 struct time time; /* Date from the author ident. */
7714 struct graph_canvas graph; /* Ancestry chain graphics. */
7715 char title[1]; /* First line of the commit message. */
7718 struct main_state {
7719 struct graph graph;
7720 struct commit current;
7721 char **reflog;
7722 size_t reflogs;
7723 int reflog_width;
7724 char reflogmsg[SIZEOF_STR / 2];
7725 bool in_header;
7726 bool added_changes_commits;
7727 bool with_graph;
7730 static void
7731 main_register_commit(struct view *view, struct commit *commit, const char *ids, bool is_boundary)
7733 struct main_state *state = view->private;
7735 string_copy_rev(commit->id, ids);
7736 if (state->with_graph)
7737 graph_add_commit(&state->graph, &commit->graph, commit->id, ids, is_boundary);
7740 static struct commit *
7741 main_add_commit(struct view *view, enum line_type type, struct commit *template,
7742 const char *title, bool custom)
7744 struct main_state *state = view->private;
7745 size_t titlelen = strlen(title);
7746 struct commit *commit;
7747 char buf[SIZEOF_STR / 2];
7749 /* FIXME: More graceful handling of titles; append "..." to
7750 * shortened titles, etc. */
7751 string_expand(buf, sizeof(buf), title, 1);
7752 title = buf;
7753 titlelen = strlen(title);
7755 if (!add_line_alloc(view, &commit, type, titlelen, custom))
7756 return NULL;
7758 *commit = *template;
7759 strncpy(commit->title, title, titlelen);
7760 state->graph.canvas = &commit->graph;
7761 memset(template, 0, sizeof(*template));
7762 state->reflogmsg[0] = 0;
7763 return commit;
7766 static inline void
7767 main_flush_commit(struct view *view, struct commit *commit)
7769 if (*commit->id)
7770 main_add_commit(view, LINE_MAIN_COMMIT, commit, "", FALSE);
7773 static bool
7774 main_has_changes(const char *argv[])
7776 struct io io;
7778 if (!io_run(&io, IO_BG, NULL, opt_env, argv, -1))
7779 return FALSE;
7780 io_done(&io);
7781 return io.status == 1;
7784 static void
7785 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
7787 char ids[SIZEOF_STR] = NULL_ID " ";
7788 struct main_state *state = view->private;
7789 struct commit commit = {};
7790 struct timeval now;
7791 struct timezone tz;
7793 if (!parent)
7794 return;
7796 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
7798 if (!gettimeofday(&now, &tz)) {
7799 commit.time.tz = tz.tz_minuteswest * 60;
7800 commit.time.sec = now.tv_sec - commit.time.tz;
7803 commit.author = &unknown_ident;
7804 main_register_commit(view, &commit, ids, FALSE);
7805 if (main_add_commit(view, type, &commit, title, TRUE) && state->with_graph)
7806 graph_render_parents(&state->graph);
7809 static void
7810 main_add_changes_commits(struct view *view, struct main_state *state, const char *parent)
7812 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
7813 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
7814 const char *staged_parent = NULL_ID;
7815 const char *unstaged_parent = parent;
7817 if (!is_head_commit(parent))
7818 return;
7820 state->added_changes_commits = TRUE;
7822 io_run_bg(update_index_argv);
7824 if (!main_has_changes(unstaged_argv)) {
7825 unstaged_parent = NULL;
7826 staged_parent = parent;
7829 if (!main_has_changes(staged_argv)) {
7830 staged_parent = NULL;
7833 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
7834 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
7837 static bool
7838 main_open(struct view *view, enum open_flags flags)
7840 static const char *main_argv[] = {
7841 GIT_MAIN_LOG(encoding_arg, "%(diffargs)", "%(revargs)", "%(fileargs)")
7843 struct main_state *state = view->private;
7845 state->with_graph = opt_rev_graph;
7847 if (flags & OPEN_PAGER_MODE) {
7848 state->added_changes_commits = TRUE;
7849 state->with_graph = FALSE;
7852 return begin_update(view, NULL, main_argv, flags);
7855 static void
7856 main_done(struct view *view)
7858 struct main_state *state = view->private;
7859 int i;
7861 for (i = 0; i < view->lines; i++) {
7862 struct commit *commit = view->line[i].data;
7864 free(commit->graph.symbols);
7867 for (i = 0; i < state->reflogs; i++)
7868 free(state->reflog[i]);
7869 free(state->reflog);
7872 #define MAIN_NO_COMMIT_REFS 1
7873 #define main_check_commit_refs(line) !((line)->user_flags & MAIN_NO_COMMIT_REFS)
7874 #define main_mark_no_commit_refs(line) ((line)->user_flags |= MAIN_NO_COMMIT_REFS)
7876 static inline struct ref_list *
7877 main_get_commit_refs(struct line *line, struct commit *commit)
7879 struct ref_list *refs = NULL;
7881 if (main_check_commit_refs(line) && !(refs = get_ref_list(commit->id)))
7882 main_mark_no_commit_refs(line);
7884 return refs;
7887 static bool
7888 main_draw(struct view *view, struct line *line, unsigned int lineno)
7890 struct main_state *state = view->private;
7891 struct commit *commit = line->data;
7892 struct ref_list *refs = NULL;
7894 if (!commit->author)
7895 return FALSE;
7897 if (draw_lineno(view, lineno))
7898 return TRUE;
7900 if (opt_show_id) {
7901 if (state->reflogs) {
7902 const char *id = state->reflog[line->lineno - 1];
7904 if (draw_id_custom(view, LINE_ID, id, state->reflog_width))
7905 return TRUE;
7906 } else if (draw_id(view, commit->id)) {
7907 return TRUE;
7911 if (draw_date(view, &commit->time))
7912 return TRUE;
7914 if (draw_author(view, commit->author))
7915 return TRUE;
7917 if (state->with_graph && draw_graph(view, &commit->graph))
7918 return TRUE;
7920 if ((refs = main_get_commit_refs(line, commit)) && draw_refs(view, refs))
7921 return TRUE;
7923 if (commit->title)
7924 draw_commit_title(view, commit->title, 0);
7925 return TRUE;
7928 static bool
7929 main_add_reflog(struct view *view, struct main_state *state, char *reflog)
7931 char *end = strchr(reflog, ' ');
7932 int id_width;
7934 if (!end)
7935 return FALSE;
7936 *end = 0;
7938 if (!realloc_reflogs(&state->reflog, state->reflogs, 1)
7939 || !(reflog = strdup(reflog)))
7940 return FALSE;
7942 state->reflog[state->reflogs++] = reflog;
7943 id_width = strlen(reflog);
7944 if (state->reflog_width < id_width) {
7945 state->reflog_width = id_width;
7946 if (opt_show_id)
7947 view->force_redraw = TRUE;
7950 return TRUE;
7953 /* Reads git log --pretty=raw output and parses it into the commit struct. */
7954 static bool
7955 main_read(struct view *view, char *line)
7957 struct main_state *state = view->private;
7958 struct graph *graph = &state->graph;
7959 enum line_type type;
7960 struct commit *commit = &state->current;
7962 if (!line) {
7963 main_flush_commit(view, commit);
7965 if (!view->lines && !view->prev)
7966 die("No revisions match the given arguments.");
7967 if (view->lines > 0) {
7968 struct commit *last = view->line[view->lines - 1].data;
7970 view->line[view->lines - 1].dirty = 1;
7971 if (!last->author) {
7972 view->lines--;
7973 free(last);
7977 if (state->with_graph)
7978 done_graph(graph);
7979 return TRUE;
7982 type = get_line_type(line);
7983 if (type == LINE_COMMIT) {
7984 bool is_boundary;
7986 state->in_header = TRUE;
7987 line += STRING_SIZE("commit ");
7988 is_boundary = *line == '-';
7989 if (is_boundary || !isalnum(*line))
7990 line++;
7992 if (!state->added_changes_commits && opt_show_changes && opt_is_inside_work_tree)
7993 main_add_changes_commits(view, state, line);
7994 else
7995 main_flush_commit(view, commit);
7997 main_register_commit(view, &state->current, line, is_boundary);
7998 return TRUE;
8001 if (!*commit->id)
8002 return TRUE;
8004 /* Empty line separates the commit header from the log itself. */
8005 if (*line == '\0')
8006 state->in_header = FALSE;
8008 switch (type) {
8009 case LINE_PP_REFLOG:
8010 if (!main_add_reflog(view, state, line + STRING_SIZE("Reflog: ")))
8011 return FALSE;
8012 break;
8014 case LINE_PP_REFLOGMSG:
8015 line += STRING_SIZE("Reflog message: ");
8016 string_ncopy(state->reflogmsg, line, strlen(line));
8017 break;
8019 case LINE_PARENT:
8020 if (state->with_graph && !graph->has_parents)
8021 graph_add_parent(graph, line + STRING_SIZE("parent "));
8022 break;
8024 case LINE_AUTHOR:
8025 parse_author_line(line + STRING_SIZE("author "),
8026 &commit->author, &commit->time);
8027 if (state->with_graph)
8028 graph_render_parents(graph);
8029 break;
8031 default:
8032 /* Fill in the commit title if it has not already been set. */
8033 if (*commit->title)
8034 break;
8036 /* Skip lines in the commit header. */
8037 if (state->in_header)
8038 break;
8040 /* Require titles to start with a non-space character at the
8041 * offset used by git log. */
8042 if (strncmp(line, " ", 4))
8043 break;
8044 line += 4;
8045 /* Well, if the title starts with a whitespace character,
8046 * try to be forgiving. Otherwise we end up with no title. */
8047 while (isspace(*line))
8048 line++;
8049 if (*line == '\0')
8050 break;
8051 if (*state->reflogmsg)
8052 line = state->reflogmsg;
8053 main_add_commit(view, LINE_MAIN_COMMIT, commit, line, FALSE);
8056 return TRUE;
8059 static enum request
8060 main_request(struct view *view, enum request request, struct line *line)
8062 enum open_flags flags = (view_is_displayed(view) && request != REQ_VIEW_DIFF)
8063 ? OPEN_SPLIT : OPEN_DEFAULT;
8065 switch (request) {
8066 case REQ_NEXT:
8067 case REQ_PREVIOUS:
8068 if (view_is_displayed(view) && display[0] != view)
8069 return request;
8070 /* Do not pass navigation requests to the branch view
8071 * when the main view is maximized. (GH #38) */
8072 return request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
8074 case REQ_VIEW_DIFF:
8075 case REQ_ENTER:
8076 if (view_is_displayed(view) && display[0] != view)
8077 maximize_view(view, TRUE);
8079 if (line->type == LINE_STAT_UNSTAGED
8080 || line->type == LINE_STAT_STAGED) {
8081 struct view *diff = VIEW(REQ_VIEW_DIFF);
8082 const char *diff_staged_argv[] = {
8083 GIT_DIFF_STAGED(encoding_arg,
8084 opt_diff_context_arg,
8085 opt_ignore_space_arg, NULL, NULL)
8087 const char *diff_unstaged_argv[] = {
8088 GIT_DIFF_UNSTAGED(encoding_arg,
8089 opt_diff_context_arg,
8090 opt_ignore_space_arg, NULL, NULL)
8092 const char **diff_argv = line->type == LINE_STAT_STAGED
8093 ? diff_staged_argv : diff_unstaged_argv;
8095 open_argv(view, diff, diff_argv, NULL, flags);
8096 break;
8099 open_view(view, REQ_VIEW_DIFF, flags);
8100 break;
8102 case REQ_REFRESH:
8103 load_refs(TRUE);
8104 refresh_view(view);
8105 break;
8107 case REQ_JUMP_COMMIT:
8109 int lineno;
8111 for (lineno = 0; lineno < view->lines; lineno++) {
8112 struct commit *commit = view->line[lineno].data;
8114 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
8115 select_view_line(view, lineno);
8116 report_clear();
8117 return REQ_NONE;
8121 report("Unable to find commit '%s'", opt_search);
8122 break;
8124 default:
8125 return request;
8128 return REQ_NONE;
8131 static bool
8132 grep_refs(struct line *line, struct commit *commit, regex_t *regex)
8134 struct ref_list *list;
8135 regmatch_t pmatch;
8136 size_t i;
8138 if (!opt_show_refs || !(list = main_get_commit_refs(line, commit)))
8139 return FALSE;
8141 for (i = 0; i < list->size; i++) {
8142 if (!regexec(regex, list->refs[i]->name, 1, &pmatch, 0))
8143 return TRUE;
8146 return FALSE;
8149 static bool
8150 main_grep(struct view *view, struct line *line)
8152 struct commit *commit = line->data;
8153 const char *text[] = {
8154 commit->id,
8155 commit->title,
8156 mkauthor(commit->author, opt_author_width, opt_author),
8157 mkdate(&commit->time, opt_date),
8158 NULL
8161 return grep_text(view, text) || grep_refs(line, commit, view->regex);
8164 static void
8165 main_select(struct view *view, struct line *line)
8167 struct commit *commit = line->data;
8169 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED)
8170 string_ncopy(view->ref, commit->title, strlen(commit->title));
8171 else
8172 string_copy_rev(view->ref, commit->id);
8173 string_copy_rev(ref_commit, commit->id);
8176 static struct view_ops main_ops = {
8177 "commit",
8178 { "main" },
8179 VIEW_SEND_CHILD_ENTER | VIEW_FILE_FILTER | VIEW_LOG_LIKE,
8180 sizeof(struct main_state),
8181 main_open,
8182 main_read,
8183 main_draw,
8184 main_request,
8185 main_grep,
8186 main_select,
8187 main_done,
8190 static bool
8191 stash_open(struct view *view, enum open_flags flags)
8193 static const char *stash_argv[] = { "git", "stash", "list",
8194 encoding_arg, "--no-color", "--pretty=raw", NULL };
8195 struct main_state *state = view->private;
8197 state->added_changes_commits = TRUE;
8198 state->with_graph = FALSE;
8199 return begin_update(view, NULL, stash_argv, flags | OPEN_RELOAD);
8202 static void
8203 stash_select(struct view *view, struct line *line)
8205 main_select(view, line);
8206 string_format(ref_stash, "stash@{%d}", line->lineno - 1);
8207 string_copy(view->ref, ref_stash);
8210 static struct view_ops stash_ops = {
8211 "stash",
8212 { "stash" },
8213 VIEW_SEND_CHILD_ENTER,
8214 sizeof(struct main_state),
8215 stash_open,
8216 main_read,
8217 main_draw,
8218 main_request,
8219 main_grep,
8220 stash_select,
8224 * Status management
8227 /* Whether or not the curses interface has been initialized. */
8228 static bool cursed = FALSE;
8230 /* Terminal hacks and workarounds. */
8231 static bool use_scroll_redrawwin;
8232 static bool use_scroll_status_wclear;
8234 /* The status window is used for polling keystrokes. */
8235 static WINDOW *status_win;
8237 /* Reading from the prompt? */
8238 static bool input_mode = FALSE;
8240 static bool status_empty = FALSE;
8242 /* Update status and title window. */
8243 static void
8244 report(const char *msg, ...)
8246 struct view *view = display[current_view];
8248 if (input_mode)
8249 return;
8251 if (!view) {
8252 char buf[SIZEOF_STR];
8253 int retval;
8255 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
8256 die("%s", buf);
8259 if (!status_empty || *msg) {
8260 va_list args;
8262 va_start(args, msg);
8264 wmove(status_win, 0, 0);
8265 if (view->has_scrolled && use_scroll_status_wclear)
8266 wclear(status_win);
8267 if (*msg) {
8268 vwprintw(status_win, msg, args);
8269 status_empty = FALSE;
8270 } else {
8271 status_empty = TRUE;
8273 wclrtoeol(status_win);
8274 wnoutrefresh(status_win);
8276 va_end(args);
8279 update_view_title(view);
8282 static void
8283 done_display(void)
8285 endwin();
8288 static void
8289 init_display(void)
8291 const char *term;
8292 int x, y;
8294 die_callback = done_display;
8296 /* Initialize the curses library */
8297 if (isatty(STDIN_FILENO)) {
8298 cursed = !!initscr();
8299 opt_tty = stdin;
8300 } else {
8301 /* Leave stdin and stdout alone when acting as a pager. */
8302 opt_tty = fopen("/dev/tty", "r+");
8303 if (!opt_tty)
8304 die("Failed to open /dev/tty");
8305 cursed = !!newterm(NULL, opt_tty, opt_tty);
8308 if (!cursed)
8309 die("Failed to initialize curses");
8311 nonl(); /* Disable conversion and detect newlines from input. */
8312 cbreak(); /* Take input chars one at a time, no wait for \n */
8313 noecho(); /* Don't echo input */
8314 leaveok(stdscr, FALSE);
8316 if (has_colors())
8317 init_colors();
8319 getmaxyx(stdscr, y, x);
8320 status_win = newwin(1, x, y - 1, 0);
8321 if (!status_win)
8322 die("Failed to create status window");
8324 /* Enable keyboard mapping */
8325 keypad(status_win, TRUE);
8326 wbkgdset(status_win, get_line_attr(LINE_STATUS));
8328 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
8329 set_tabsize(opt_tab_size);
8330 #else
8331 TABSIZE = opt_tab_size;
8332 #endif
8334 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
8335 if (term && !strcmp(term, "gnome-terminal")) {
8336 /* In the gnome-terminal-emulator, the message from
8337 * scrolling up one line when impossible followed by
8338 * scrolling down one line causes corruption of the
8339 * status line. This is fixed by calling wclear. */
8340 use_scroll_status_wclear = TRUE;
8341 use_scroll_redrawwin = FALSE;
8343 } else if (term && !strcmp(term, "xrvt-xpm")) {
8344 /* No problems with full optimizations in xrvt-(unicode)
8345 * and aterm. */
8346 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
8348 } else {
8349 /* When scrolling in (u)xterm the last line in the
8350 * scrolling direction will update slowly. */
8351 use_scroll_redrawwin = TRUE;
8352 use_scroll_status_wclear = FALSE;
8356 static int
8357 get_input(int prompt_position)
8359 struct view *view;
8360 int i, key, cursor_y, cursor_x;
8362 if (prompt_position)
8363 input_mode = TRUE;
8365 while (TRUE) {
8366 bool loading = FALSE;
8368 foreach_view (view, i) {
8369 update_view(view);
8370 if (view_is_displayed(view) && view->has_scrolled &&
8371 use_scroll_redrawwin)
8372 redrawwin(view->win);
8373 view->has_scrolled = FALSE;
8374 if (view->pipe)
8375 loading = TRUE;
8378 /* Update the cursor position. */
8379 if (prompt_position) {
8380 getbegyx(status_win, cursor_y, cursor_x);
8381 cursor_x = prompt_position;
8382 } else {
8383 view = display[current_view];
8384 getbegyx(view->win, cursor_y, cursor_x);
8385 cursor_x = view->width - 1;
8386 cursor_y += view->pos.lineno - view->pos.offset;
8388 setsyx(cursor_y, cursor_x);
8390 /* Refresh, accept single keystroke of input */
8391 doupdate();
8392 nodelay(status_win, loading);
8393 key = wgetch(status_win);
8395 /* wgetch() with nodelay() enabled returns ERR when
8396 * there's no input. */
8397 if (key == ERR) {
8399 } else if (key == KEY_RESIZE) {
8400 int height, width;
8402 getmaxyx(stdscr, height, width);
8404 wresize(status_win, 1, width);
8405 mvwin(status_win, height - 1, 0);
8406 wnoutrefresh(status_win);
8407 resize_display();
8408 redraw_display(TRUE);
8410 } else {
8411 input_mode = FALSE;
8412 if (key == erasechar())
8413 key = KEY_BACKSPACE;
8414 return key;
8419 static char *
8420 prompt_input(const char *prompt, input_handler handler, void *data)
8422 enum input_status status = INPUT_OK;
8423 static char buf[SIZEOF_STR];
8424 size_t pos = 0;
8426 buf[pos] = 0;
8428 while (status == INPUT_OK || status == INPUT_SKIP) {
8429 int key;
8431 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
8432 wclrtoeol(status_win);
8434 key = get_input(pos + 1);
8435 switch (key) {
8436 case KEY_RETURN:
8437 case KEY_ENTER:
8438 case '\n':
8439 status = pos ? INPUT_STOP : INPUT_CANCEL;
8440 break;
8442 case KEY_BACKSPACE:
8443 if (pos > 0)
8444 buf[--pos] = 0;
8445 else
8446 status = INPUT_CANCEL;
8447 break;
8449 case KEY_ESC:
8450 status = INPUT_CANCEL;
8451 break;
8453 default:
8454 if (pos >= sizeof(buf)) {
8455 report("Input string too long");
8456 return NULL;
8459 status = handler(data, buf, key);
8460 if (status == INPUT_OK)
8461 buf[pos++] = (char) key;
8465 /* Clear the status window */
8466 status_empty = FALSE;
8467 report_clear();
8469 if (status == INPUT_CANCEL)
8470 return NULL;
8472 buf[pos++] = 0;
8474 return buf;
8477 static enum input_status
8478 prompt_yesno_handler(void *data, char *buf, int c)
8480 if (c == 'y' || c == 'Y')
8481 return INPUT_STOP;
8482 if (c == 'n' || c == 'N')
8483 return INPUT_CANCEL;
8484 return INPUT_SKIP;
8487 static bool
8488 prompt_yesno(const char *prompt)
8490 char prompt2[SIZEOF_STR];
8492 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
8493 return FALSE;
8495 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
8498 static enum input_status
8499 read_prompt_handler(void *data, char *buf, int c)
8501 return isprint(c) ? INPUT_OK : INPUT_SKIP;
8504 static char *
8505 read_prompt(const char *prompt)
8507 return prompt_input(prompt, read_prompt_handler, NULL);
8510 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
8512 enum input_status status = INPUT_OK;
8513 int size = 0;
8515 while (items[size].text)
8516 size++;
8518 assert(size > 0);
8520 while (status == INPUT_OK) {
8521 const struct menu_item *item = &items[*selected];
8522 int key;
8523 int i;
8525 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
8526 prompt, *selected + 1, size);
8527 if (item->hotkey)
8528 wprintw(status_win, "[%c] ", (char) item->hotkey);
8529 wprintw(status_win, "%s", item->text);
8530 wclrtoeol(status_win);
8532 key = get_input(COLS - 1);
8533 switch (key) {
8534 case KEY_RETURN:
8535 case KEY_ENTER:
8536 case '\n':
8537 status = INPUT_STOP;
8538 break;
8540 case KEY_LEFT:
8541 case KEY_UP:
8542 *selected = *selected - 1;
8543 if (*selected < 0)
8544 *selected = size - 1;
8545 break;
8547 case KEY_RIGHT:
8548 case KEY_DOWN:
8549 *selected = (*selected + 1) % size;
8550 break;
8552 case KEY_ESC:
8553 status = INPUT_CANCEL;
8554 break;
8556 default:
8557 for (i = 0; items[i].text; i++)
8558 if (items[i].hotkey == key) {
8559 *selected = i;
8560 status = INPUT_STOP;
8561 break;
8566 /* Clear the status window */
8567 status_empty = FALSE;
8568 report_clear();
8570 return status != INPUT_CANCEL;
8574 * Repository properties
8578 static void
8579 set_remote_branch(const char *name, const char *value, size_t valuelen)
8581 if (!strcmp(name, ".remote")) {
8582 string_ncopy(opt_remote, value, valuelen);
8584 } else if (*opt_remote && !strcmp(name, ".merge")) {
8585 size_t from = strlen(opt_remote);
8587 if (!prefixcmp(value, "refs/heads/"))
8588 value += STRING_SIZE("refs/heads/");
8590 if (!string_format_from(opt_remote, &from, "/%s", value))
8591 opt_remote[0] = 0;
8595 static void
8596 set_repo_config_option(char *name, char *value, enum status_code (*cmd)(int, const char **))
8598 const char *argv[SIZEOF_ARG] = { name, "=" };
8599 int argc = 1 + (cmd == option_set_command);
8600 enum status_code error;
8602 if (!argv_from_string(argv, &argc, value))
8603 error = ERROR_TOO_MANY_OPTION_ARGUMENTS;
8604 else
8605 error = cmd(argc, argv);
8607 if (error != SUCCESS)
8608 warn("Option 'tig.%s': %s", name, get_status_message(error));
8611 static void
8612 set_work_tree(const char *value)
8614 char cwd[SIZEOF_STR];
8616 if (!getcwd(cwd, sizeof(cwd)))
8617 die("Failed to get cwd path: %s", strerror(errno));
8618 if (chdir(cwd) < 0)
8619 die("Failed to chdir(%s): %s", cwd, strerror(errno));
8620 if (chdir(opt_git_dir) < 0)
8621 die("Failed to chdir(%s): %s", opt_git_dir, strerror(errno));
8622 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
8623 die("Failed to get git path: %s", strerror(errno));
8624 if (chdir(value) < 0)
8625 die("Failed to chdir(%s): %s", value, strerror(errno));
8626 if (!getcwd(cwd, sizeof(cwd)))
8627 die("Failed to get cwd path: %s", strerror(errno));
8628 if (setenv("GIT_WORK_TREE", cwd, TRUE))
8629 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
8630 if (setenv("GIT_DIR", opt_git_dir, TRUE))
8631 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
8632 opt_is_inside_work_tree = TRUE;
8635 static void
8636 parse_git_color_option(enum line_type type, char *value)
8638 struct line_info *info = &line_info[type];
8639 const char *argv[SIZEOF_ARG];
8640 int argc = 0;
8641 bool first_color = TRUE;
8642 int i;
8644 if (!argv_from_string(argv, &argc, value))
8645 return;
8647 info->fg = COLOR_DEFAULT;
8648 info->bg = COLOR_DEFAULT;
8649 info->attr = 0;
8651 for (i = 0; i < argc; i++) {
8652 int attr = 0;
8654 if (set_attribute(&attr, argv[i])) {
8655 info->attr |= attr;
8657 } else if (set_color(&attr, argv[i])) {
8658 if (first_color)
8659 info->fg = attr;
8660 else
8661 info->bg = attr;
8662 first_color = FALSE;
8667 static void
8668 set_git_color_option(const char *name, char *value)
8670 static const struct enum_map color_option_map[] = {
8671 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
8672 ENUM_MAP("branch.local", LINE_MAIN_REF),
8673 ENUM_MAP("branch.plain", LINE_MAIN_REF),
8674 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
8676 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
8677 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
8678 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
8679 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
8680 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
8681 ENUM_MAP("diff.old", LINE_DIFF_DEL),
8682 ENUM_MAP("diff.new", LINE_DIFF_ADD),
8684 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
8686 ENUM_MAP("status.branch", LINE_STAT_HEAD),
8687 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
8688 ENUM_MAP("status.added", LINE_STAT_STAGED),
8689 ENUM_MAP("status.updated", LINE_STAT_STAGED),
8690 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
8691 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
8694 int type = LINE_NONE;
8696 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
8697 parse_git_color_option(type, value);
8701 static void
8702 set_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
8704 if (parse_encoding(encoding_ref, arg, priority) == SUCCESS)
8705 encoding_arg[0] = 0;
8708 static int
8709 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8711 if (!strcmp(name, "i18n.commitencoding"))
8712 set_encoding(&default_encoding, value, FALSE);
8714 else if (!strcmp(name, "gui.encoding"))
8715 set_encoding(&default_encoding, value, TRUE);
8717 else if (!strcmp(name, "core.editor"))
8718 string_ncopy(opt_editor, value, valuelen);
8720 else if (!strcmp(name, "core.worktree"))
8721 set_work_tree(value);
8723 else if (!strcmp(name, "core.abbrev"))
8724 parse_id(&opt_id_cols, value);
8726 else if (!prefixcmp(name, "tig.color."))
8727 set_repo_config_option(name + 10, value, option_color_command);
8729 else if (!prefixcmp(name, "tig.bind."))
8730 set_repo_config_option(name + 9, value, option_bind_command);
8732 else if (!prefixcmp(name, "tig."))
8733 set_repo_config_option(name + 4, value, option_set_command);
8735 else if (!prefixcmp(name, "color."))
8736 set_git_color_option(name + STRING_SIZE("color."), value);
8738 else if (*opt_head && !prefixcmp(name, "branch.") &&
8739 !strncmp(name + 7, opt_head, strlen(opt_head)))
8740 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
8742 return OK;
8745 static int
8746 load_git_config(void)
8748 const char *config_list_argv[] = { "git", "config", "--list", NULL };
8750 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
8753 #define REPO_INFO_GIT_DIR "--git-dir"
8754 #define REPO_INFO_WORK_TREE "--is-inside-work-tree"
8755 #define REPO_INFO_SHOW_CDUP "--show-cdup"
8756 #define REPO_INFO_SHOW_PREFIX "--show-prefix"
8757 #define REPO_INFO_SYMBOLIC_HEAD "--symbolic-full-name"
8758 #define REPO_INFO_RESOLVED_HEAD "HEAD"
8760 struct repo_info_state {
8761 const char **argv;
8762 char head_id[SIZEOF_REV];
8765 static int
8766 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8768 struct repo_info_state *state = data;
8769 const char *arg = *state->argv ? *state->argv++ : "";
8771 if (!strcmp(arg, REPO_INFO_GIT_DIR)) {
8772 string_ncopy(opt_git_dir, name, namelen);
8774 } else if (!strcmp(arg, REPO_INFO_WORK_TREE)) {
8775 /* This can be 3 different values depending on the
8776 * version of git being used. If git-rev-parse does not
8777 * understand --is-inside-work-tree it will simply echo
8778 * the option else either "true" or "false" is printed.
8779 * Default to true for the unknown case. */
8780 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
8782 } else if (!strcmp(arg, REPO_INFO_SHOW_CDUP)) {
8783 string_ncopy(opt_cdup, name, namelen);
8785 } else if (!strcmp(arg, REPO_INFO_SHOW_PREFIX)) {
8786 string_ncopy(opt_prefix, name, namelen);
8788 } else if (!strcmp(arg, REPO_INFO_RESOLVED_HEAD)) {
8789 string_ncopy(state->head_id, name, namelen);
8791 } else if (!strcmp(arg, REPO_INFO_SYMBOLIC_HEAD)) {
8792 if (!prefixcmp(name, "refs/heads/")) {
8793 char *offset = name + STRING_SIZE("refs/heads/");
8795 string_ncopy(opt_head, offset, strlen(offset) + 1);
8796 add_ref(state->head_id, name, opt_remote, opt_head);
8798 state->argv++;
8801 return OK;
8804 static int
8805 load_repo_info(void)
8807 const char *rev_parse_argv[] = {
8808 "git", "rev-parse", REPO_INFO_GIT_DIR, REPO_INFO_WORK_TREE,
8809 REPO_INFO_SHOW_CDUP, REPO_INFO_SHOW_PREFIX, \
8810 REPO_INFO_RESOLVED_HEAD, REPO_INFO_SYMBOLIC_HEAD, "HEAD",
8811 NULL
8813 struct repo_info_state state = { rev_parse_argv + 2 };
8815 return io_run_load(rev_parse_argv, "=", read_repo_info, &state);
8820 * Main
8823 static const char usage[] =
8824 "tig " TIG_VERSION " (" __DATE__ ")\n"
8825 "\n"
8826 "Usage: tig [options] [revs] [--] [paths]\n"
8827 " or: tig log [options] [revs] [--] [paths]\n"
8828 " or: tig show [options] [revs] [--] [paths]\n"
8829 " or: tig blame [options] [rev] [--] path\n"
8830 " or: tig stash\n"
8831 " or: tig status\n"
8832 " or: tig < [git command output]\n"
8833 "\n"
8834 "Options:\n"
8835 " +<number> Select line <number> in the first view\n"
8836 " -v, --version Show version and exit\n"
8837 " -h, --help Show help message and exit";
8839 static void TIG_NORETURN
8840 quit(int sig)
8842 if (sig)
8843 signal(sig, SIG_DFL);
8845 /* XXX: Restore tty modes and let the OS cleanup the rest! */
8846 if (cursed)
8847 endwin();
8848 exit(0);
8851 static int
8852 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8854 const char ***filter_args = data;
8856 return argv_append(filter_args, name) ? OK : ERR;
8859 static void
8860 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
8862 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
8863 const char **all_argv = NULL;
8865 if (!argv_append_array(&all_argv, rev_parse_argv) ||
8866 !argv_append_array(&all_argv, argv) ||
8867 io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
8868 die("Failed to split arguments");
8869 argv_free(all_argv);
8870 free(all_argv);
8873 static bool
8874 is_rev_flag(const char *flag)
8876 static const char *rev_flags[] = { GIT_REV_FLAGS };
8877 int i;
8879 for (i = 0; i < ARRAY_SIZE(rev_flags); i++)
8880 if (!strcmp(flag, rev_flags[i]))
8881 return TRUE;
8883 return FALSE;
8886 static void
8887 filter_options(const char *argv[], bool blame)
8889 const char **flags = NULL;
8891 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
8892 filter_rev_parse(&flags, "--flags", "--no-revs", argv);
8894 if (flags) {
8895 int next, flags_pos;
8897 for (next = flags_pos = 0; flags && flags[next]; next++) {
8898 const char *flag = flags[next];
8900 if (is_rev_flag(flag))
8901 argv_append(&opt_rev_argv, flag);
8902 else
8903 flags[flags_pos++] = flag;
8906 flags[flags_pos] = NULL;
8908 if (blame)
8909 opt_blame_argv = flags;
8910 else
8911 opt_diff_argv = flags;
8914 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
8917 static enum request
8918 parse_options(int argc, const char *argv[], bool pager_mode)
8920 enum request request;
8921 const char *subcommand;
8922 bool seen_dashdash = FALSE;
8923 const char **filter_argv = NULL;
8924 int i;
8926 request = pager_mode ? REQ_VIEW_PAGER : REQ_VIEW_MAIN;
8928 if (argc <= 1)
8929 return request;
8931 subcommand = argv[1];
8932 if (!strcmp(subcommand, "status")) {
8933 request = REQ_VIEW_STATUS;
8935 } else if (!strcmp(subcommand, "blame")) {
8936 request = REQ_VIEW_BLAME;
8938 } else if (!strcmp(subcommand, "show")) {
8939 request = REQ_VIEW_DIFF;
8941 } else if (!strcmp(subcommand, "log")) {
8942 request = REQ_VIEW_LOG;
8944 } else if (!strcmp(subcommand, "stash")) {
8945 request = REQ_VIEW_STASH;
8947 } else {
8948 subcommand = NULL;
8951 for (i = 1 + !!subcommand; i < argc; i++) {
8952 const char *opt = argv[i];
8954 // stop parsing our options after -- and let rev-parse handle the rest
8955 if (!seen_dashdash) {
8956 if (!strcmp(opt, "--")) {
8957 seen_dashdash = TRUE;
8958 continue;
8960 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
8961 printf("tig version %s\n", TIG_VERSION);
8962 quit(0);
8964 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
8965 printf("%s\n", usage);
8966 quit(0);
8968 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
8969 opt_lineno = atoi(opt + 1);
8970 continue;
8975 if (!argv_append(&filter_argv, opt))
8976 die("command too long");
8979 if (filter_argv)
8980 filter_options(filter_argv, request == REQ_VIEW_BLAME);
8982 /* Finish validating and setting up blame options */
8983 if (request == REQ_VIEW_BLAME) {
8984 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
8985 die("invalid number of options to blame\n\n%s", usage);
8987 if (opt_rev_argv) {
8988 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
8991 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
8994 return request;
8997 static enum request
8998 open_pager_mode(enum request request)
9000 enum open_flags flags = OPEN_DEFAULT;
9002 if (request == REQ_VIEW_PAGER) {
9003 /* Detect if the user requested the main view. */
9004 if (argv_contains(opt_rev_argv, "--stdin")) {
9005 request = REQ_VIEW_MAIN;
9006 flags |= OPEN_FORWARD_STDIN;
9007 } else if (argv_contains(opt_diff_argv, "--pretty=raw")) {
9008 request = REQ_VIEW_MAIN;
9009 flags |= OPEN_STDIN;
9010 } else {
9011 flags |= OPEN_STDIN;
9014 } else if (request == REQ_VIEW_DIFF) {
9015 if (argv_contains(opt_rev_argv, "--stdin"))
9016 flags |= OPEN_FORWARD_STDIN;
9019 /* Open the requested view even if the pager mode is enabled so
9020 * the warning message below is displayed correctly. */
9021 open_view(NULL, request, flags);
9023 if (!open_in_pager_mode(flags)) {
9024 close(STDIN_FILENO);
9025 report("Ignoring stdin.");
9028 return REQ_NONE;
9031 static enum request
9032 run_prompt_command(struct view *view, char *cmd) {
9033 enum request request;
9035 if (cmd && string_isnumber(cmd)) {
9036 int lineno = view->pos.lineno + 1;
9038 if (parse_int(&lineno, cmd, 1, view->lines + 1) == SUCCESS) {
9039 select_view_line(view, lineno - 1);
9040 report_clear();
9041 } else {
9042 report("Unable to parse '%s' as a line number", cmd);
9044 } else if (cmd && iscommit(cmd)) {
9045 string_ncopy(opt_search, cmd, strlen(cmd));
9047 request = view_request(view, REQ_JUMP_COMMIT);
9048 if (request == REQ_JUMP_COMMIT) {
9049 report("Jumping to commits is not supported by the '%s' view", view->name);
9052 } else if (cmd && strlen(cmd) == 1) {
9053 request = get_keybinding(&view->ops->keymap, cmd[0]);
9054 return request;
9056 } else if (cmd && cmd[0] == '!') {
9057 struct view *next = VIEW(REQ_VIEW_PAGER);
9058 const char *argv[SIZEOF_ARG];
9059 int argc = 0;
9061 cmd++;
9062 /* When running random commands, initially show the
9063 * command in the title. However, it maybe later be
9064 * overwritten if a commit line is selected. */
9065 string_ncopy(next->ref, cmd, strlen(cmd));
9067 if (!argv_from_string(argv, &argc, cmd)) {
9068 report("Too many arguments");
9069 } else if (!format_argv(view, &next->argv, argv, FALSE, TRUE)) {
9070 report("Argument formatting failed");
9071 } else {
9072 next->dir = NULL;
9073 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
9076 } else if (cmd) {
9077 request = get_request(cmd);
9078 if (request != REQ_UNKNOWN)
9079 return request;
9081 char *args = strchr(cmd, ' ');
9082 if (args) {
9083 *args++ = 0;
9084 if (set_option(cmd, args) == SUCCESS) {
9085 request = !view->unrefreshable ? REQ_REFRESH : REQ_SCREEN_REDRAW;
9086 if (!strcmp(cmd, "color"))
9087 init_colors();
9090 return request;
9092 return REQ_NONE;
9096 main(int argc, const char *argv[])
9098 const char *codeset = ENCODING_UTF8;
9099 bool pager_mode = !isatty(STDIN_FILENO);
9100 enum request request = parse_options(argc, argv, pager_mode);
9101 struct view *view;
9102 int i;
9104 signal(SIGINT, quit);
9105 signal(SIGQUIT, quit);
9106 signal(SIGPIPE, SIG_IGN);
9108 if (setlocale(LC_ALL, "")) {
9109 codeset = nl_langinfo(CODESET);
9112 foreach_view(view, i) {
9113 add_keymap(&view->ops->keymap);
9116 if (load_repo_info() == ERR)
9117 die("Failed to load repo info.");
9119 if (load_options() == ERR)
9120 die("Failed to load user config.");
9122 if (load_git_config() == ERR)
9123 die("Failed to load repo config.");
9125 /* Require a git repository unless when running in pager mode. */
9126 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
9127 die("Not a git repository");
9129 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
9130 char translit[SIZEOF_STR];
9132 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
9133 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
9134 else
9135 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
9136 if (opt_iconv_out == ICONV_NONE)
9137 die("Failed to initialize character set conversion");
9140 if (load_refs(FALSE) == ERR)
9141 die("Failed to load refs.");
9143 init_display();
9145 if (pager_mode)
9146 request = open_pager_mode(request);
9148 while (view_driver(display[current_view], request)) {
9149 int key = get_input(0);
9151 if (key == KEY_ESC)
9152 key = get_input(0) + 0x80;
9154 view = display[current_view];
9155 request = get_keybinding(&view->ops->keymap, key);
9157 /* Some low-level request handling. This keeps access to
9158 * status_win restricted. */
9159 switch (request) {
9160 case REQ_NONE:
9161 report("Unknown key, press %s for help",
9162 get_view_key(view, REQ_VIEW_HELP));
9163 break;
9164 case REQ_PROMPT:
9166 char *cmd = read_prompt(":");
9167 request = run_prompt_command(view, cmd);
9168 break;
9170 case REQ_SEARCH:
9171 case REQ_SEARCH_BACK:
9173 const char *prompt = request == REQ_SEARCH ? "/" : "?";
9174 char *search = read_prompt(prompt);
9176 if (search)
9177 string_ncopy(opt_search, search, strlen(search));
9178 else if (*opt_search)
9179 request = request == REQ_SEARCH ?
9180 REQ_FIND_NEXT :
9181 REQ_FIND_PREV;
9182 else
9183 request = REQ_NONE;
9184 break;
9186 default:
9187 break;
9191 quit(0);
9193 return 0;
9196 /* vim: set ts=8 sw=8 noexpandtab: */