Set the commit reference when opening the blame view from the blob view
[tig.git] / tig.c
blobe88031b9261c4260e5ee0fc79bd90598f35127d7
1 /* Copyright (c) 2006-2013 Jonas Fonseca <fonseca@diku.dk>
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU General Public License as
5 * published by the Free Software Foundation; either version 2 of
6 * the License, or (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
14 #define WARN_MISSING_CURSES_CONFIGURATION
16 #include "tig.h"
17 #include "util.h"
18 #include "io.h"
19 #include "refs.h"
20 #include "graph.h"
21 #include "git.h"
23 static void report(const char *msg, ...) PRINTF_LIKE(1, 2);
24 #define report_clear() report("%s", "")
27 enum input_status {
28 INPUT_OK,
29 INPUT_SKIP,
30 INPUT_STOP,
31 INPUT_CANCEL
34 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
36 static char *prompt_input(const char *prompt, input_handler handler, void *data);
37 static bool prompt_yesno(const char *prompt);
38 static char *read_prompt(const char *prompt);
40 struct menu_item {
41 int hotkey;
42 const char *text;
43 void *data;
46 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
48 #define GRAPHIC_ENUM(_) \
49 _(GRAPHIC, ASCII), \
50 _(GRAPHIC, DEFAULT), \
51 _(GRAPHIC, UTF_8)
53 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
55 #define DATE_ENUM(_) \
56 _(DATE, NO), \
57 _(DATE, DEFAULT), \
58 _(DATE, LOCAL), \
59 _(DATE, RELATIVE), \
60 _(DATE, SHORT)
62 DEFINE_ENUM(date, DATE_ENUM);
64 struct time {
65 time_t sec;
66 int tz;
69 static inline int timecmp(const struct time *t1, const struct time *t2)
71 return t1->sec - t2->sec;
74 static const char *
75 mkdate(const struct time *time, enum date date)
77 static char buf[DATE_WIDTH + 1];
78 static const struct enum_map reldate[] = {
79 { "second", 1, 60 * 2 },
80 { "minute", 60, 60 * 60 * 2 },
81 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
82 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
83 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
84 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 365 },
85 { "year", 60 * 60 * 24 * 365, 0 },
87 struct tm tm;
89 if (!date || !time || !time->sec)
90 return "";
92 if (date == DATE_RELATIVE) {
93 struct timeval now;
94 time_t date = time->sec + time->tz;
95 time_t seconds;
96 int i;
98 gettimeofday(&now, NULL);
99 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
100 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
101 if (seconds >= reldate[i].value && reldate[i].value)
102 continue;
104 seconds /= reldate[i].namelen;
105 if (!string_format(buf, "%ld %s%s %s",
106 seconds, reldate[i].name,
107 seconds > 1 ? "s" : "",
108 now.tv_sec >= date ? "ago" : "ahead"))
109 break;
110 return buf;
114 if (date == DATE_LOCAL) {
115 time_t date = time->sec + time->tz;
116 localtime_r(&date, &tm);
118 else {
119 gmtime_r(&time->sec, &tm);
121 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
124 #define FILE_SIZE_ENUM(_) \
125 _(FILE_SIZE, NO), \
126 _(FILE_SIZE, DEFAULT), \
127 _(FILE_SIZE, UNITS)
129 DEFINE_ENUM(file_size, FILE_SIZE_ENUM);
131 static const char *
132 mkfilesize(unsigned long size, enum file_size format)
134 static char buf[64 + 1];
135 static const char relsize[] = {
136 'B', 'K', 'M', 'G', 'T', 'P'
139 if (!format)
140 return "";
142 if (format == FILE_SIZE_UNITS) {
143 const char *fmt = "%.0f%c";
144 double rsize = size;
145 int i;
147 for (i = 0; i < ARRAY_SIZE(relsize); i++) {
148 if (rsize > 1024.0 && i + 1 < ARRAY_SIZE(relsize)) {
149 rsize /= 1024;
150 continue;
153 size = rsize * 10;
154 if (size % 10 > 0)
155 fmt = "%.1f%c";
157 return string_format(buf, fmt, rsize, relsize[i])
158 ? buf : NULL;
162 return string_format(buf, "%ld", size) ? buf : NULL;
165 #define AUTHOR_ENUM(_) \
166 _(AUTHOR, NO), \
167 _(AUTHOR, FULL), \
168 _(AUTHOR, ABBREVIATED), \
169 _(AUTHOR, EMAIL), \
170 _(AUTHOR, EMAIL_USER)
172 DEFINE_ENUM(author, AUTHOR_ENUM);
174 struct ident {
175 const char *name;
176 const char *email;
179 static const struct ident unknown_ident = { "Unknown", "unknown@localhost" };
181 static inline int
182 ident_compare(const struct ident *i1, const struct ident *i2)
184 if (!i1 || !i2)
185 return (!!i1) - (!!i2);
186 if (!i1->name || !i2->name)
187 return (!!i1->name) - (!!i2->name);
188 return strcmp(i1->name, i2->name);
191 static const char *
192 get_author_initials(const char *author)
194 static char initials[AUTHOR_WIDTH * 6 + 1];
195 size_t pos = 0;
196 const char *end = strchr(author, '\0');
198 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
200 memset(initials, 0, sizeof(initials));
201 while (author < end) {
202 unsigned char bytes;
203 size_t i;
205 while (author < end && is_initial_sep(*author))
206 author++;
208 bytes = utf8_char_length(author, end);
209 if (bytes >= sizeof(initials) - 1 - pos)
210 break;
211 while (bytes--) {
212 initials[pos++] = *author++;
215 i = pos;
216 while (author < end && !is_initial_sep(*author)) {
217 bytes = utf8_char_length(author, end);
218 if (bytes >= sizeof(initials) - 1 - i) {
219 while (author < end && !is_initial_sep(*author))
220 author++;
221 break;
223 while (bytes--) {
224 initials[i++] = *author++;
228 initials[i++] = 0;
231 return initials;
234 static const char *
235 get_email_user(const char *email)
237 static char user[AUTHOR_WIDTH * 6 + 1];
238 const char *end = strchr(email, '@');
239 int length = end ? end - email : strlen(email);
241 string_format(user, "%.*s%c", length, email, 0);
242 return user;
245 #define author_trim(cols) (cols == 0 || cols > 10)
247 static const char *
248 mkauthor(const struct ident *ident, int cols, enum author author)
250 bool trim = author_trim(cols);
251 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
253 if (author == AUTHOR_NO || !ident)
254 return "";
255 if (author == AUTHOR_EMAIL && ident->email)
256 return ident->email;
257 if (author == AUTHOR_EMAIL_USER && ident->email)
258 return get_email_user(ident->email);
259 if (abbreviate && ident->name)
260 return get_author_initials(ident->name);
261 return ident->name;
264 static const char *
265 mkmode(mode_t mode)
267 if (S_ISDIR(mode))
268 return "drwxr-xr-x";
269 else if (S_ISLNK(mode))
270 return "lrwxrwxrwx";
271 else if (S_ISGITLINK(mode))
272 return "m---------";
273 else if (S_ISREG(mode) && mode & S_IXUSR)
274 return "-rwxr-xr-x";
275 else if (S_ISREG(mode))
276 return "-rw-r--r--";
277 else
278 return "----------";
281 #define FILENAME_ENUM(_) \
282 _(FILENAME, NO), \
283 _(FILENAME, ALWAYS), \
284 _(FILENAME, AUTO)
286 DEFINE_ENUM(filename, FILENAME_ENUM);
288 #define IGNORE_SPACE_ENUM(_) \
289 _(IGNORE_SPACE, NO), \
290 _(IGNORE_SPACE, ALL), \
291 _(IGNORE_SPACE, SOME), \
292 _(IGNORE_SPACE, AT_EOL)
294 DEFINE_ENUM(ignore_space, IGNORE_SPACE_ENUM);
296 #define COMMIT_ORDER_ENUM(_) \
297 _(COMMIT_ORDER, DEFAULT), \
298 _(COMMIT_ORDER, TOPO), \
299 _(COMMIT_ORDER, DATE), \
300 _(COMMIT_ORDER, REVERSE)
302 DEFINE_ENUM(commit_order, COMMIT_ORDER_ENUM);
304 #define VIEW_INFO(_) \
305 _(MAIN, main, ref_head), \
306 _(DIFF, diff, ref_commit), \
307 _(LOG, log, ref_head), \
308 _(TREE, tree, ref_commit), \
309 _(BLOB, blob, ref_blob), \
310 _(BLAME, blame, ref_commit), \
311 _(BRANCH, branch, ref_head), \
312 _(HELP, help, ""), \
313 _(PAGER, pager, ""), \
314 _(STATUS, status, "status"), \
315 _(STAGE, stage, ref_status), \
316 _(STASH, stash, ref_stash)
319 * User requests
322 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
324 #define REQ_INFO \
325 REQ_GROUP("View switching") \
326 VIEW_INFO(VIEW_REQ), \
328 REQ_GROUP("View manipulation") \
329 REQ_(ENTER, "Enter current line and scroll"), \
330 REQ_(BACK, "Go back to the previous view state"), \
331 REQ_(NEXT, "Move to next"), \
332 REQ_(PREVIOUS, "Move to previous"), \
333 REQ_(PARENT, "Move to parent"), \
334 REQ_(VIEW_NEXT, "Move focus to next view"), \
335 REQ_(REFRESH, "Reload and refresh"), \
336 REQ_(MAXIMIZE, "Maximize the current view"), \
337 REQ_(VIEW_CLOSE, "Close the current view"), \
338 REQ_(QUIT, "Close all views and quit"), \
340 REQ_GROUP("View specific requests") \
341 REQ_(STATUS_UPDATE, "Update file status"), \
342 REQ_(STATUS_REVERT, "Revert file changes"), \
343 REQ_(STATUS_MERGE, "Merge file using external tool"), \
344 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
345 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
346 REQ_(STAGE_SPLIT_CHUNK, "Split the current chunk"), \
347 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
348 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
350 REQ_GROUP("Cursor navigation") \
351 REQ_(MOVE_UP, "Move cursor one line up"), \
352 REQ_(MOVE_DOWN, "Move cursor one line down"), \
353 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
354 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
355 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
356 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
358 REQ_GROUP("Scrolling") \
359 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
360 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
361 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
362 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
363 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
364 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
365 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
367 REQ_GROUP("Searching") \
368 REQ_(SEARCH, "Search the view"), \
369 REQ_(SEARCH_BACK, "Search backwards in the view"), \
370 REQ_(FIND_NEXT, "Find next search match"), \
371 REQ_(FIND_PREV, "Find previous search match"), \
373 REQ_GROUP("Option manipulation") \
374 REQ_(OPTIONS, "Open option menu"), \
375 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
376 REQ_(TOGGLE_DATE, "Toggle date display"), \
377 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
378 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
379 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
380 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
381 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
382 REQ_(TOGGLE_CHANGES, "Toggle local changes display in the main view"), \
383 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
384 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
385 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
386 REQ_(TOGGLE_COMMIT_ORDER, "Toggle commit ordering"), \
387 REQ_(TOGGLE_ID, "Toggle commit ID display"), \
388 REQ_(TOGGLE_FILES, "Toggle file filtering"), \
389 REQ_(TOGGLE_TITLE_OVERFLOW, "Toggle highlighting of commit title overflow"), \
390 REQ_(TOGGLE_FILE_SIZE, "Toggle file size format"), \
391 REQ_(TOGGLE_UNTRACKED_DIRS, "Toggle display of files in untracked directories"), \
393 REQ_GROUP("Misc") \
394 REQ_(PROMPT, "Bring up the prompt"), \
395 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
396 REQ_(SHOW_VERSION, "Show version information"), \
397 REQ_(STOP_LOADING, "Stop all loading views"), \
398 REQ_(EDIT, "Open in editor"), \
399 REQ_(NONE, "Do nothing")
402 /* User action requests. */
403 enum request {
404 #define REQ_GROUP(help)
405 #define REQ_(req, help) REQ_##req
407 /* Offset all requests to avoid conflicts with ncurses getch values. */
408 REQ_UNKNOWN = KEY_MAX + 1,
409 REQ_OFFSET,
410 REQ_INFO,
412 /* Internal requests. */
413 REQ_JUMP_COMMIT,
415 #undef REQ_GROUP
416 #undef REQ_
419 struct request_info {
420 enum request request;
421 const char *name;
422 int namelen;
423 const char *help;
426 static const struct request_info req_info[] = {
427 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
428 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
429 REQ_INFO
430 #undef REQ_GROUP
431 #undef REQ_
434 static enum request
435 get_request(const char *name)
437 int namelen = strlen(name);
438 int i;
440 for (i = 0; i < ARRAY_SIZE(req_info); i++)
441 if (enum_equals(req_info[i], name, namelen))
442 return req_info[i].request;
444 return REQ_UNKNOWN;
449 * Options
452 /* Option and state variables. */
453 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
454 static enum date opt_date = DATE_DEFAULT;
455 static enum author opt_author = AUTHOR_FULL;
456 static enum filename opt_filename = FILENAME_AUTO;
457 static enum file_size opt_file_size = FILE_SIZE_DEFAULT;
458 static bool opt_rev_graph = TRUE;
459 static bool opt_line_number = FALSE;
460 static bool opt_show_refs = TRUE;
461 static bool opt_show_changes = TRUE;
462 static bool opt_untracked_dirs_content = TRUE;
463 static bool opt_read_git_colors = TRUE;
464 static bool opt_wrap_lines = FALSE;
465 static bool opt_ignore_case = FALSE;
466 static bool opt_focus_child = TRUE;
467 static int opt_diff_context = 3;
468 static char opt_diff_context_arg[9] = "";
469 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
470 static char opt_ignore_space_arg[22] = "";
471 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
472 static char opt_commit_order_arg[22] = "";
473 static bool opt_notes = TRUE;
474 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
475 static int opt_num_interval = 5;
476 static double opt_hscroll = 0.50;
477 static double opt_scale_split_view = 2.0 / 3.0;
478 static double opt_scale_vsplit_view = 0.5;
479 static bool opt_vsplit = FALSE;
480 static int opt_tab_size = 8;
481 static int opt_author_width = AUTHOR_WIDTH;
482 static int opt_filename_width = FILENAME_WIDTH;
483 static char opt_path[SIZEOF_STR] = "";
484 static char opt_file[SIZEOF_STR] = "";
485 static char opt_ref[SIZEOF_REF] = "";
486 static unsigned long opt_goto_line = 0;
487 static char opt_head[SIZEOF_REF] = "";
488 static char opt_remote[SIZEOF_REF] = "";
489 static iconv_t opt_iconv_out = ICONV_NONE;
490 static char opt_search[SIZEOF_STR] = "";
491 static char opt_cdup[SIZEOF_STR] = "";
492 static char opt_prefix[SIZEOF_STR] = "";
493 static char opt_git_dir[SIZEOF_STR] = "";
494 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
495 static char opt_editor[SIZEOF_STR] = "";
496 static bool opt_editor_lineno = TRUE;
497 static FILE *opt_tty = NULL;
498 static const char **opt_diff_argv = NULL;
499 static const char **opt_rev_argv = NULL;
500 static const char **opt_file_argv = NULL;
501 static const char **opt_blame_argv = NULL;
502 static int opt_lineno = 0;
503 static bool opt_show_id = FALSE;
504 static int opt_id_cols = ID_WIDTH;
505 static bool opt_file_filter = TRUE;
506 static bool opt_show_title_overflow = FALSE;
507 static int opt_title_overflow = 50;
508 static char opt_env_lines[64] = "";
509 static char opt_env_columns[64] = "";
510 static char *opt_env[] = { opt_env_lines, opt_env_columns, NULL };
512 #define is_initial_commit() (!get_ref_head())
513 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strncmp(rev, get_ref_head()->id, SIZEOF_REV - 1)))
515 static inline int
516 load_refs(bool force)
518 static bool loaded = FALSE;
520 if (force)
521 opt_head[0] = 0;
522 else if (loaded)
523 return OK;
525 loaded = TRUE;
526 return reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head));
529 static inline void
530 update_diff_context_arg(int diff_context)
532 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
533 string_ncopy(opt_diff_context_arg, "-U3", 3);
536 static inline void
537 update_ignore_space_arg()
539 if (opt_ignore_space == IGNORE_SPACE_ALL) {
540 string_copy(opt_ignore_space_arg, "--ignore-all-space");
541 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
542 string_copy(opt_ignore_space_arg, "--ignore-space-change");
543 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
544 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
545 } else {
546 string_copy(opt_ignore_space_arg, "");
550 static inline void
551 update_commit_order_arg()
553 if (opt_commit_order == COMMIT_ORDER_TOPO) {
554 string_copy(opt_commit_order_arg, "--topo-order");
555 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
556 string_copy(opt_commit_order_arg, "--date-order");
557 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
558 string_copy(opt_commit_order_arg, "--reverse");
559 } else {
560 string_copy(opt_commit_order_arg, "");
564 static inline void
565 update_notes_arg()
567 if (opt_notes) {
568 string_copy(opt_notes_arg, "--show-notes");
569 } else {
570 /* Notes are disabled by default when passing --pretty args. */
571 string_copy(opt_notes_arg, "");
576 * Line-oriented content detection.
579 #define LINE_INFO \
580 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
581 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
582 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
583 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
584 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
585 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
586 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
587 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
588 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
589 LINE(DIFF_DELETED_FILE_MODE, \
590 "deleted file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
591 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
592 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
593 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
594 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
595 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
596 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
597 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
598 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
599 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
600 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
601 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
602 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
603 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
604 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
605 LINE(PP_REFLOG, "Reflog: ", COLOR_RED, COLOR_DEFAULT, 0), \
606 LINE(PP_REFLOGMSG, "Reflog message: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
607 LINE(STASH, "stash@{", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
608 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
609 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
610 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
611 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
612 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
613 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
614 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
615 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
616 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
617 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
618 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
619 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
620 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
621 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
622 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
623 LINE(ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
624 LINE(OVERFLOW, "", COLOR_RED, COLOR_DEFAULT, 0), \
625 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
626 LINE(FILE_SIZE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
627 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
628 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
629 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
630 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
631 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
632 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
633 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
634 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
635 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
636 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
637 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
638 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
639 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
640 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
641 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
642 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
643 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
644 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
645 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
646 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
647 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
648 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
649 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
650 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
651 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
652 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
653 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
654 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
655 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
656 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
657 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
658 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
660 enum line_type {
661 #define LINE(type, line, fg, bg, attr) \
662 LINE_##type
663 LINE_INFO,
664 LINE_NONE
665 #undef LINE
668 struct line_info {
669 const char *name; /* Option name. */
670 int namelen; /* Size of option name. */
671 const char *line; /* The start of line to match. */
672 int linelen; /* Size of string to match. */
673 int fg, bg, attr; /* Color and text attributes for the lines. */
674 int color_pair;
677 static struct line_info line_info[] = {
678 #define LINE(type, line, fg, bg, attr) \
679 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
680 LINE_INFO
681 #undef LINE
684 static struct line_info **color_pair;
685 static size_t color_pairs;
687 static struct line_info *custom_color;
688 static size_t custom_colors;
690 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
691 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
693 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
694 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
696 /* Color IDs must be 1 or higher. [GH #15] */
697 #define COLOR_ID(line_type) ((line_type) + 1)
699 static enum line_type
700 get_line_type(const char *line)
702 int linelen = strlen(line);
703 enum line_type type;
705 for (type = 0; type < custom_colors; type++)
706 /* Case insensitive search matches Signed-off-by lines better. */
707 if (linelen >= custom_color[type].linelen &&
708 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
709 return TO_CUSTOM_COLOR_TYPE(type);
711 for (type = 0; type < ARRAY_SIZE(line_info); type++)
712 /* Case insensitive search matches Signed-off-by lines better. */
713 if (linelen >= line_info[type].linelen &&
714 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
715 return type;
717 return LINE_DEFAULT;
720 static enum line_type
721 get_line_type_from_ref(const struct ref *ref)
723 if (ref->head)
724 return LINE_MAIN_HEAD;
725 else if (ref->ltag)
726 return LINE_MAIN_LOCAL_TAG;
727 else if (ref->tag)
728 return LINE_MAIN_TAG;
729 else if (ref->tracked)
730 return LINE_MAIN_TRACKED;
731 else if (ref->remote)
732 return LINE_MAIN_REMOTE;
733 else if (ref->replace)
734 return LINE_MAIN_REPLACE;
736 return LINE_MAIN_REF;
739 static inline struct line_info *
740 get_line(enum line_type type)
742 if (type > LINE_NONE) {
743 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
744 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
745 } else {
746 assert(type < ARRAY_SIZE(line_info));
747 return &line_info[type];
751 static inline int
752 get_line_color(enum line_type type)
754 return COLOR_ID(get_line(type)->color_pair);
757 static inline int
758 get_line_attr(enum line_type type)
760 struct line_info *info = get_line(type);
762 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
765 static struct line_info *
766 get_line_info(const char *name)
768 size_t namelen = strlen(name);
769 enum line_type type;
771 for (type = 0; type < ARRAY_SIZE(line_info); type++)
772 if (enum_equals(line_info[type], name, namelen))
773 return &line_info[type];
775 return NULL;
778 static struct line_info *
779 add_custom_color(const char *quoted_line)
781 struct line_info *info;
782 char *line;
783 size_t linelen;
785 if (!realloc_custom_color(&custom_color, custom_colors, 1))
786 die("Failed to alloc custom line info");
788 linelen = strlen(quoted_line) - 1;
789 line = malloc(linelen);
790 if (!line)
791 return NULL;
793 strncpy(line, quoted_line + 1, linelen);
794 line[linelen - 1] = 0;
796 info = &custom_color[custom_colors++];
797 info->name = info->line = line;
798 info->namelen = info->linelen = strlen(line);
800 return info;
803 static void
804 init_line_info_color_pair(struct line_info *info, enum line_type type,
805 int default_bg, int default_fg)
807 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
808 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
809 int i;
811 for (i = 0; i < color_pairs; i++) {
812 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
813 info->color_pair = i;
814 return;
818 if (!realloc_color_pair(&color_pair, color_pairs, 1))
819 die("Failed to alloc color pair");
821 color_pair[color_pairs] = info;
822 info->color_pair = color_pairs++;
823 init_pair(COLOR_ID(info->color_pair), fg, bg);
826 static void
827 init_colors(void)
829 int default_bg = line_info[LINE_DEFAULT].bg;
830 int default_fg = line_info[LINE_DEFAULT].fg;
831 enum line_type type;
833 start_color();
835 if (assume_default_colors(default_fg, default_bg) == ERR) {
836 default_bg = COLOR_BLACK;
837 default_fg = COLOR_WHITE;
840 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
841 struct line_info *info = &line_info[type];
843 init_line_info_color_pair(info, type, default_bg, default_fg);
846 for (type = 0; type < custom_colors; type++) {
847 struct line_info *info = &custom_color[type];
849 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
850 default_bg, default_fg);
854 struct line {
855 enum line_type type;
856 unsigned int lineno:24;
858 /* State flags */
859 unsigned int selected:1;
860 unsigned int dirty:1;
861 unsigned int cleareol:1;
862 unsigned int wrapped:1;
864 unsigned int user_flags:6;
865 void *data; /* User data */
870 * Keys
873 struct keybinding {
874 int alias;
875 enum request request;
878 static struct keybinding default_keybindings[] = {
879 /* View switching */
880 { 'm', REQ_VIEW_MAIN },
881 { 'd', REQ_VIEW_DIFF },
882 { 'l', REQ_VIEW_LOG },
883 { 't', REQ_VIEW_TREE },
884 { 'f', REQ_VIEW_BLOB },
885 { 'B', REQ_VIEW_BLAME },
886 { 'H', REQ_VIEW_BRANCH },
887 { 'p', REQ_VIEW_PAGER },
888 { 'h', REQ_VIEW_HELP },
889 { 'S', REQ_VIEW_STATUS },
890 { 'c', REQ_VIEW_STAGE },
891 { 'y', REQ_VIEW_STASH },
893 /* View manipulation */
894 { 'q', REQ_VIEW_CLOSE },
895 { KEY_TAB, REQ_VIEW_NEXT },
896 { KEY_RETURN, REQ_ENTER },
897 { KEY_UP, REQ_PREVIOUS },
898 { KEY_CTL('P'), REQ_PREVIOUS },
899 { KEY_DOWN, REQ_NEXT },
900 { KEY_CTL('N'), REQ_NEXT },
901 { 'R', REQ_REFRESH },
902 { KEY_F(5), REQ_REFRESH },
903 { 'O', REQ_MAXIMIZE },
904 { ',', REQ_PARENT },
905 { '<', REQ_BACK },
907 /* View specific */
908 { 'u', REQ_STATUS_UPDATE },
909 { '!', REQ_STATUS_REVERT },
910 { 'M', REQ_STATUS_MERGE },
911 { '1', REQ_STAGE_UPDATE_LINE },
912 { '@', REQ_STAGE_NEXT },
913 { '\\', REQ_STAGE_SPLIT_CHUNK },
914 { '[', REQ_DIFF_CONTEXT_DOWN },
915 { ']', REQ_DIFF_CONTEXT_UP },
917 /* Cursor navigation */
918 { 'k', REQ_MOVE_UP },
919 { 'j', REQ_MOVE_DOWN },
920 { KEY_HOME, REQ_MOVE_FIRST_LINE },
921 { KEY_END, REQ_MOVE_LAST_LINE },
922 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
923 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
924 { ' ', REQ_MOVE_PAGE_DOWN },
925 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
926 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
927 { 'b', REQ_MOVE_PAGE_UP },
928 { '-', REQ_MOVE_PAGE_UP },
930 /* Scrolling */
931 { '|', REQ_SCROLL_FIRST_COL },
932 { KEY_LEFT, REQ_SCROLL_LEFT },
933 { KEY_RIGHT, REQ_SCROLL_RIGHT },
934 { KEY_IC, REQ_SCROLL_LINE_UP },
935 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
936 { KEY_DC, REQ_SCROLL_LINE_DOWN },
937 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
938 { 'w', REQ_SCROLL_PAGE_UP },
939 { 's', REQ_SCROLL_PAGE_DOWN },
941 /* Searching */
942 { '/', REQ_SEARCH },
943 { '?', REQ_SEARCH_BACK },
944 { 'n', REQ_FIND_NEXT },
945 { 'N', REQ_FIND_PREV },
947 /* Misc */
948 { 'Q', REQ_QUIT },
949 { 'z', REQ_STOP_LOADING },
950 { 'v', REQ_SHOW_VERSION },
951 { 'r', REQ_SCREEN_REDRAW },
952 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
953 { 'o', REQ_OPTIONS },
954 { '.', REQ_TOGGLE_LINENO },
955 { 'D', REQ_TOGGLE_DATE },
956 { 'A', REQ_TOGGLE_AUTHOR },
957 { 'g', REQ_TOGGLE_REV_GRAPH },
958 { '~', REQ_TOGGLE_GRAPHIC },
959 { '#', REQ_TOGGLE_FILENAME },
960 { 'F', REQ_TOGGLE_REFS },
961 { 'I', REQ_TOGGLE_SORT_ORDER },
962 { 'i', REQ_TOGGLE_SORT_FIELD },
963 { 'W', REQ_TOGGLE_IGNORE_SPACE },
964 { 'X', REQ_TOGGLE_ID },
965 { '%', REQ_TOGGLE_FILES },
966 { '$', REQ_TOGGLE_TITLE_OVERFLOW },
967 { ':', REQ_PROMPT },
968 { 'e', REQ_EDIT },
971 struct keymap {
972 const char *name;
973 struct keymap *next;
974 struct keybinding *data;
975 size_t size;
976 bool hidden;
979 static struct keymap generic_keymap = { "generic" };
980 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
982 static struct keymap *keymaps = &generic_keymap;
984 static void
985 add_keymap(struct keymap *keymap)
987 keymap->next = keymaps;
988 keymaps = keymap;
991 static struct keymap *
992 get_keymap(const char *name)
994 struct keymap *keymap = keymaps;
996 while (keymap) {
997 if (!strcasecmp(keymap->name, name))
998 return keymap;
999 keymap = keymap->next;
1002 return NULL;
1006 static void
1007 add_keybinding(struct keymap *table, enum request request, int key)
1009 size_t i;
1011 for (i = 0; i < table->size; i++) {
1012 if (table->data[i].alias == key) {
1013 table->data[i].request = request;
1014 return;
1018 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
1019 if (!table->data)
1020 die("Failed to allocate keybinding");
1021 table->data[table->size].alias = key;
1022 table->data[table->size++].request = request;
1024 if (request == REQ_NONE && is_generic_keymap(table)) {
1025 int i;
1027 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1028 if (default_keybindings[i].alias == key)
1029 default_keybindings[i].request = REQ_NONE;
1033 /* Looks for a key binding first in the given map, then in the generic map, and
1034 * lastly in the default keybindings. */
1035 static enum request
1036 get_keybinding(struct keymap *keymap, int key)
1038 size_t i;
1040 for (i = 0; i < keymap->size; i++)
1041 if (keymap->data[i].alias == key)
1042 return keymap->data[i].request;
1044 for (i = 0; i < generic_keymap.size; i++)
1045 if (generic_keymap.data[i].alias == key)
1046 return generic_keymap.data[i].request;
1048 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1049 if (default_keybindings[i].alias == key)
1050 return default_keybindings[i].request;
1052 return (enum request) key;
1056 struct key {
1057 const char *name;
1058 int value;
1061 static const struct key key_table[] = {
1062 { "Enter", KEY_RETURN },
1063 { "Space", ' ' },
1064 { "Backspace", KEY_BACKSPACE },
1065 { "Tab", KEY_TAB },
1066 { "Escape", KEY_ESC },
1067 { "Left", KEY_LEFT },
1068 { "Right", KEY_RIGHT },
1069 { "Up", KEY_UP },
1070 { "Down", KEY_DOWN },
1071 { "Insert", KEY_IC },
1072 { "Delete", KEY_DC },
1073 { "Hash", '#' },
1074 { "Home", KEY_HOME },
1075 { "End", KEY_END },
1076 { "PageUp", KEY_PPAGE },
1077 { "PageDown", KEY_NPAGE },
1078 { "F1", KEY_F(1) },
1079 { "F2", KEY_F(2) },
1080 { "F3", KEY_F(3) },
1081 { "F4", KEY_F(4) },
1082 { "F5", KEY_F(5) },
1083 { "F6", KEY_F(6) },
1084 { "F7", KEY_F(7) },
1085 { "F8", KEY_F(8) },
1086 { "F9", KEY_F(9) },
1087 { "F10", KEY_F(10) },
1088 { "F11", KEY_F(11) },
1089 { "F12", KEY_F(12) },
1092 static int
1093 get_key_value(const char *name)
1095 int i;
1097 for (i = 0; i < ARRAY_SIZE(key_table); i++)
1098 if (!strcasecmp(key_table[i].name, name))
1099 return key_table[i].value;
1101 if (strlen(name) == 3 && name[0] == '^' && name[1] == '[' && isprint(*name))
1102 return (int)name[2] + 0x80;
1103 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1104 return (int)name[1] & 0x1f;
1105 if (strlen(name) == 1 && isprint(*name))
1106 return (int) *name;
1107 return ERR;
1110 static const char *
1111 get_key_name(int key_value)
1113 static char key_char[] = "'X'\0";
1114 const char *seq = NULL;
1115 int key;
1117 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1118 if (key_table[key].value == key_value)
1119 seq = key_table[key].name;
1121 if (seq == NULL && key_value < 0x7f) {
1122 char *s = key_char + 1;
1124 if (key_value >= 0x20) {
1125 *s++ = key_value;
1126 } else {
1127 *s++ = '^';
1128 *s++ = 0x40 | (key_value & 0x1f);
1130 *s++ = '\'';
1131 *s++ = '\0';
1132 seq = key_char;
1135 return seq ? seq : "(no key)";
1138 static bool
1139 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1141 const char *sep = *pos > 0 ? ", " : "";
1142 const char *keyname = get_key_name(keybinding->alias);
1144 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1147 static bool
1148 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1149 struct keymap *keymap, bool all)
1151 int i;
1153 for (i = 0; i < keymap->size; i++) {
1154 if (keymap->data[i].request == request) {
1155 if (!append_key(buf, pos, &keymap->data[i]))
1156 return FALSE;
1157 if (!all)
1158 break;
1162 return TRUE;
1165 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1167 static const char *
1168 get_keys(struct keymap *keymap, enum request request, bool all)
1170 static char buf[BUFSIZ];
1171 size_t pos = 0;
1172 int i;
1174 buf[pos] = 0;
1176 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1177 return "Too many keybindings!";
1178 if (pos > 0 && !all)
1179 return buf;
1181 if (!is_generic_keymap(keymap)) {
1182 /* Only the generic keymap includes the default keybindings when
1183 * listing all keys. */
1184 if (all)
1185 return buf;
1187 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1188 return "Too many keybindings!";
1189 if (pos)
1190 return buf;
1193 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1194 if (default_keybindings[i].request == request) {
1195 if (!append_key(buf, &pos, &default_keybindings[i]))
1196 return "Too many keybindings!";
1197 if (!all)
1198 return buf;
1202 return buf;
1205 enum run_request_flag {
1206 RUN_REQUEST_DEFAULT = 0,
1207 RUN_REQUEST_FORCE = 1,
1208 RUN_REQUEST_SILENT = 2,
1209 RUN_REQUEST_CONFIRM = 4,
1210 RUN_REQUEST_EXIT = 8,
1211 RUN_REQUEST_INTERNAL = 16,
1214 struct run_request {
1215 struct keymap *keymap;
1216 int key;
1217 const char **argv;
1218 bool silent;
1219 bool confirm;
1220 bool exit;
1221 bool internal;
1224 static struct run_request *run_request;
1225 static size_t run_requests;
1227 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1229 static bool
1230 add_run_request(struct keymap *keymap, int key, const char **argv, enum run_request_flag flags)
1232 bool force = flags & RUN_REQUEST_FORCE;
1233 struct run_request *req;
1235 if (!force && get_keybinding(keymap, key) != key)
1236 return TRUE;
1238 if (!realloc_run_requests(&run_request, run_requests, 1))
1239 return FALSE;
1241 if (!argv_copy(&run_request[run_requests].argv, argv))
1242 return FALSE;
1244 req = &run_request[run_requests++];
1245 req->silent = flags & RUN_REQUEST_SILENT;
1246 req->confirm = flags & RUN_REQUEST_CONFIRM;
1247 req->exit = flags & RUN_REQUEST_EXIT;
1248 req->internal = flags & RUN_REQUEST_INTERNAL;
1249 req->keymap = keymap;
1250 req->key = key;
1252 add_keybinding(keymap, REQ_NONE + run_requests, key);
1253 return TRUE;
1256 static struct run_request *
1257 get_run_request(enum request request)
1259 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1260 return NULL;
1261 return &run_request[request - REQ_NONE - 1];
1264 static void
1265 add_builtin_run_requests(void)
1267 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1268 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1269 const char *commit[] = { "git", "commit", NULL };
1270 const char *gc[] = { "git", "gc", NULL };
1271 const char *stash_pop[] = { "git", "stash", "pop", "%(stash)", NULL };
1273 add_run_request(get_keymap("main"), 'C', cherry_pick, RUN_REQUEST_CONFIRM);
1274 add_run_request(get_keymap("status"), 'C', commit, RUN_REQUEST_DEFAULT);
1275 add_run_request(get_keymap("branch"), 'C', checkout, RUN_REQUEST_CONFIRM);
1276 add_run_request(get_keymap("generic"), 'G', gc, RUN_REQUEST_CONFIRM);
1277 add_run_request(get_keymap("stash"), 'P', stash_pop, RUN_REQUEST_CONFIRM);
1281 * User config file handling.
1284 static const struct enum_map color_map[] = {
1285 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1286 COLOR_MAP(DEFAULT),
1287 COLOR_MAP(BLACK),
1288 COLOR_MAP(BLUE),
1289 COLOR_MAP(CYAN),
1290 COLOR_MAP(GREEN),
1291 COLOR_MAP(MAGENTA),
1292 COLOR_MAP(RED),
1293 COLOR_MAP(WHITE),
1294 COLOR_MAP(YELLOW),
1297 static const struct enum_map attr_map[] = {
1298 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1299 ATTR_MAP(NORMAL),
1300 ATTR_MAP(BLINK),
1301 ATTR_MAP(BOLD),
1302 ATTR_MAP(DIM),
1303 ATTR_MAP(REVERSE),
1304 ATTR_MAP(STANDOUT),
1305 ATTR_MAP(UNDERLINE),
1308 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1310 static enum status_code
1311 parse_step(double *opt, const char *arg)
1313 *opt = atoi(arg);
1314 if (!strchr(arg, '%'))
1315 return SUCCESS;
1317 /* "Shift down" so 100% and 1 does not conflict. */
1318 *opt = (*opt - 1) / 100;
1319 if (*opt >= 1.0) {
1320 *opt = 0.99;
1321 return ERROR_INVALID_STEP_VALUE;
1323 if (*opt < 0.0) {
1324 *opt = 1;
1325 return ERROR_INVALID_STEP_VALUE;
1327 return SUCCESS;
1330 static enum status_code
1331 parse_int(int *opt, const char *arg, int min, int max)
1333 int value = atoi(arg);
1335 if (min <= value && value <= max) {
1336 *opt = value;
1337 return SUCCESS;
1340 return ERROR_INTEGER_VALUE_OUT_OF_BOUND;
1343 #define parse_id(opt, arg) \
1344 parse_int(opt, arg, 4, SIZEOF_REV - 1)
1346 static bool
1347 set_color(int *color, const char *name)
1349 if (map_enum(color, color_map, name))
1350 return TRUE;
1351 if (!prefixcmp(name, "color"))
1352 return parse_int(color, name + 5, 0, 255) == SUCCESS;
1353 /* Used when reading git colors. Git expects a plain int w/o prefix. */
1354 return parse_int(color, name, 0, 255) == SUCCESS;
1357 /* Wants: object fgcolor bgcolor [attribute] */
1358 static enum status_code
1359 option_color_command(int argc, const char *argv[])
1361 struct line_info *info;
1363 if (argc < 3)
1364 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1366 if (*argv[0] == '"' || *argv[0] == '\'') {
1367 info = add_custom_color(argv[0]);
1368 } else {
1369 info = get_line_info(argv[0]);
1371 if (!info) {
1372 static const struct enum_map obsolete[] = {
1373 ENUM_MAP("main-delim", LINE_DELIMITER),
1374 ENUM_MAP("main-date", LINE_DATE),
1375 ENUM_MAP("main-author", LINE_AUTHOR),
1376 ENUM_MAP("blame-id", LINE_ID),
1378 int index;
1380 if (!map_enum(&index, obsolete, argv[0]))
1381 return ERROR_UNKNOWN_COLOR_NAME;
1382 info = &line_info[index];
1385 if (!set_color(&info->fg, argv[1]) ||
1386 !set_color(&info->bg, argv[2]))
1387 return ERROR_UNKNOWN_COLOR;
1389 info->attr = 0;
1390 while (argc-- > 3) {
1391 int attr;
1393 if (!set_attribute(&attr, argv[argc]))
1394 return ERROR_UNKNOWN_ATTRIBUTE;
1395 info->attr |= attr;
1398 return SUCCESS;
1401 static enum status_code
1402 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1404 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1405 ? TRUE : FALSE;
1406 if (matched)
1407 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1408 return SUCCESS;
1411 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1413 static enum status_code
1414 parse_enum_do(unsigned int *opt, const char *arg,
1415 const struct enum_map *map, size_t map_size)
1417 bool is_true;
1419 assert(map_size > 1);
1421 if (map_enum_do(map, map_size, (int *) opt, arg))
1422 return SUCCESS;
1424 parse_bool(&is_true, arg);
1425 *opt = is_true ? map[1].value : map[0].value;
1426 return SUCCESS;
1429 #define parse_enum(opt, arg, map) \
1430 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1432 static enum status_code
1433 parse_string(char *opt, const char *arg, size_t optsize)
1435 int arglen = strlen(arg);
1437 switch (arg[0]) {
1438 case '\"':
1439 case '\'':
1440 if (arglen == 1 || arg[arglen - 1] != arg[0])
1441 return ERROR_UNMATCHED_QUOTATION;
1442 arg += 1; arglen -= 2;
1443 default:
1444 string_ncopy_do(opt, optsize, arg, arglen);
1445 return SUCCESS;
1449 static enum status_code
1450 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1452 char buf[SIZEOF_STR];
1453 enum status_code code = parse_string(buf, arg, sizeof(buf));
1455 if (code == SUCCESS) {
1456 struct encoding *encoding = *encoding_ref;
1458 if (encoding && !priority)
1459 return code;
1460 encoding = encoding_open(buf);
1461 if (encoding)
1462 *encoding_ref = encoding;
1465 return code;
1468 static enum status_code
1469 parse_args(const char ***args, const char *argv[])
1471 if (!argv_copy(args, argv))
1472 return ERROR_OUT_OF_MEMORY;
1473 return SUCCESS;
1476 /* Wants: name = value */
1477 static enum status_code
1478 option_set_command(int argc, const char *argv[])
1480 if (argc < 3)
1481 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1483 if (strcmp(argv[1], "="))
1484 return ERROR_NO_VALUE_ASSIGNED;
1486 if (!strcmp(argv[0], "blame-options"))
1487 return parse_args(&opt_blame_argv, argv + 2);
1489 if (!strcmp(argv[0], "diff-options"))
1490 return parse_args(&opt_diff_argv, argv + 2);
1492 if (argc != 3)
1493 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1495 if (!strcmp(argv[0], "show-author"))
1496 return parse_enum(&opt_author, argv[2], author_map);
1498 if (!strcmp(argv[0], "show-date"))
1499 return parse_enum(&opt_date, argv[2], date_map);
1501 if (!strcmp(argv[0], "show-rev-graph"))
1502 return parse_bool(&opt_rev_graph, argv[2]);
1504 if (!strcmp(argv[0], "show-refs"))
1505 return parse_bool(&opt_show_refs, argv[2]);
1507 if (!strcmp(argv[0], "show-changes"))
1508 return parse_bool(&opt_show_changes, argv[2]);
1510 if (!strcmp(argv[0], "show-notes")) {
1511 bool matched = FALSE;
1512 enum status_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1514 if (res == SUCCESS && matched) {
1515 update_notes_arg();
1516 return res;
1519 opt_notes = TRUE;
1520 strcpy(opt_notes_arg, "--show-notes=");
1521 res = parse_string(opt_notes_arg + 8, argv[2],
1522 sizeof(opt_notes_arg) - 8);
1523 if (res == SUCCESS && opt_notes_arg[8] == '\0')
1524 opt_notes_arg[7] = '\0';
1525 return res;
1528 if (!strcmp(argv[0], "show-line-numbers"))
1529 return parse_bool(&opt_line_number, argv[2]);
1531 if (!strcmp(argv[0], "line-graphics"))
1532 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1534 if (!strcmp(argv[0], "line-number-interval"))
1535 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1537 if (!strcmp(argv[0], "author-width"))
1538 return parse_int(&opt_author_width, argv[2], 0, 1024);
1540 if (!strcmp(argv[0], "filename-width"))
1541 return parse_int(&opt_filename_width, argv[2], 0, 1024);
1543 if (!strcmp(argv[0], "show-filename"))
1544 return parse_enum(&opt_filename, argv[2], filename_map);
1546 if (!strcmp(argv[0], "show-file-size"))
1547 return parse_enum(&opt_file_size, argv[2], file_size_map);
1549 if (!strcmp(argv[0], "horizontal-scroll"))
1550 return parse_step(&opt_hscroll, argv[2]);
1552 if (!strcmp(argv[0], "split-view-height"))
1553 return parse_step(&opt_scale_split_view, argv[2]);
1555 if (!strcmp(argv[0], "vertical-split"))
1556 return parse_bool(&opt_vsplit, argv[2]);
1558 if (!strcmp(argv[0], "tab-size"))
1559 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1561 if (!strcmp(argv[0], "diff-context")) {
1562 enum status_code code = parse_int(&opt_diff_context, argv[2], 0, 999999);
1564 if (code == SUCCESS)
1565 update_diff_context_arg(opt_diff_context);
1566 return code;
1569 if (!strcmp(argv[0], "ignore-space")) {
1570 enum status_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1572 if (code == SUCCESS)
1573 update_ignore_space_arg();
1574 return code;
1577 if (!strcmp(argv[0], "commit-order")) {
1578 enum status_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1580 if (code == SUCCESS)
1581 update_commit_order_arg();
1582 return code;
1585 if (!strcmp(argv[0], "status-untracked-dirs"))
1586 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1588 if (!strcmp(argv[0], "read-git-colors"))
1589 return parse_bool(&opt_read_git_colors, argv[2]);
1591 if (!strcmp(argv[0], "ignore-case"))
1592 return parse_bool(&opt_ignore_case, argv[2]);
1594 if (!strcmp(argv[0], "focus-child"))
1595 return parse_bool(&opt_focus_child, argv[2]);
1597 if (!strcmp(argv[0], "wrap-lines"))
1598 return parse_bool(&opt_wrap_lines, argv[2]);
1600 if (!strcmp(argv[0], "show-id"))
1601 return parse_bool(&opt_show_id, argv[2]);
1603 if (!strcmp(argv[0], "id-width"))
1604 return parse_id(&opt_id_cols, argv[2]);
1606 if (!strcmp(argv[0], "title-overflow")) {
1607 bool matched;
1608 enum status_code code;
1611 * "title-overflow" is considered a boolint.
1612 * We try to parse it as a boolean (and set the value to 50 if true),
1613 * otherwise we parse it as an integer and use the given value.
1615 code = parse_bool_matched(&opt_show_title_overflow, argv[2], &matched);
1616 if (code == SUCCESS && matched) {
1617 if (opt_show_title_overflow)
1618 opt_title_overflow = 50;
1619 } else {
1620 code = parse_int(&opt_title_overflow, argv[2], 2, 1024);
1621 if (code == SUCCESS)
1622 opt_show_title_overflow = TRUE;
1625 return code;
1628 if (!strcmp(argv[0], "editor-line-number"))
1629 return parse_bool(&opt_editor_lineno, argv[2]);
1631 return ERROR_UNKNOWN_VARIABLE_NAME;
1634 /* Wants: mode request key */
1635 static enum status_code
1636 option_bind_command(int argc, const char *argv[])
1638 enum request request;
1639 struct keymap *keymap;
1640 int key;
1642 if (argc < 3)
1643 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1645 if (!(keymap = get_keymap(argv[0])))
1646 return ERROR_UNKNOWN_KEY_MAP;
1648 key = get_key_value(argv[1]);
1649 if (key == ERR)
1650 return ERROR_UNKNOWN_KEY;
1652 request = get_request(argv[2]);
1653 if (request == REQ_UNKNOWN) {
1654 static const struct enum_map obsolete[] = {
1655 ENUM_MAP("cherry-pick", REQ_NONE),
1656 ENUM_MAP("screen-resize", REQ_NONE),
1657 ENUM_MAP("tree-parent", REQ_PARENT),
1659 int alias;
1661 if (map_enum(&alias, obsolete, argv[2])) {
1662 if (alias != REQ_NONE)
1663 add_keybinding(keymap, alias, key);
1664 return ERROR_OBSOLETE_REQUEST_NAME;
1668 if (request == REQ_UNKNOWN) {
1669 enum run_request_flag flags = RUN_REQUEST_FORCE;
1671 if (strchr("!?@<", *argv[2])) {
1672 while (*argv[2]) {
1673 if (*argv[2] == '@') {
1674 flags |= RUN_REQUEST_SILENT;
1675 } else if (*argv[2] == '?') {
1676 flags |= RUN_REQUEST_CONFIRM;
1677 } else if (*argv[2] == '<') {
1678 flags |= RUN_REQUEST_EXIT;
1679 } else if (*argv[2] != '!') {
1680 break;
1682 argv[2]++;
1685 } else if (*argv[2] == ':') {
1686 argv[2]++;
1687 flags |= RUN_REQUEST_INTERNAL;
1689 } else {
1690 return ERROR_UNKNOWN_REQUEST_NAME;
1693 return add_run_request(keymap, key, argv + 2, flags)
1694 ? SUCCESS : ERROR_OUT_OF_MEMORY;
1697 add_keybinding(keymap, request, key);
1699 return SUCCESS;
1703 static enum status_code load_option_file(const char *path);
1705 static enum status_code
1706 option_source_command(int argc, const char *argv[])
1708 if (argc < 1)
1709 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1711 return load_option_file(argv[0]);
1714 static enum status_code
1715 set_option(const char *opt, char *value)
1717 const char *argv[SIZEOF_ARG];
1718 int argc = 0;
1720 if (!argv_from_string(argv, &argc, value))
1721 return ERROR_TOO_MANY_OPTION_ARGUMENTS;
1723 if (!strcmp(opt, "color"))
1724 return option_color_command(argc, argv);
1726 if (!strcmp(opt, "set"))
1727 return option_set_command(argc, argv);
1729 if (!strcmp(opt, "bind"))
1730 return option_bind_command(argc, argv);
1732 if (!strcmp(opt, "source"))
1733 return option_source_command(argc, argv);
1735 return ERROR_UNKNOWN_OPTION_COMMAND;
1738 struct config_state {
1739 const char *path;
1740 int lineno;
1741 bool errors;
1744 static int
1745 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1747 struct config_state *config = data;
1748 enum status_code status = ERROR_NO_OPTION_VALUE;
1750 config->lineno++;
1752 /* Check for comment markers, since read_properties() will
1753 * only ensure opt and value are split at first " \t". */
1754 optlen = strcspn(opt, "#");
1755 if (optlen == 0)
1756 return OK;
1758 if (opt[optlen] == 0) {
1759 /* Look for comment endings in the value. */
1760 size_t len = strcspn(value, "#");
1762 if (len < valuelen) {
1763 valuelen = len;
1764 value[valuelen] = 0;
1767 status = set_option(opt, value);
1770 if (status != SUCCESS) {
1771 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1772 get_status_message(status), (int) optlen, opt);
1773 config->errors = TRUE;
1776 /* Always keep going if errors are encountered. */
1777 return OK;
1780 static enum status_code
1781 load_option_file(const char *path)
1783 struct config_state config = { path, 0, FALSE };
1784 struct io io;
1785 char buf[SIZEOF_STR];
1787 /* Do not read configuration from stdin if set to "" */
1788 if (!path || !strlen(path))
1789 return SUCCESS;
1791 if (!prefixcmp(path, "~/")) {
1792 const char *home = getenv("HOME");
1794 if (!home || !string_format(buf, "%s/%s", home, path + 2))
1795 return ERROR_HOME_UNRESOLVABLE;
1796 path = buf;
1799 /* It's OK that the file doesn't exist. */
1800 if (!io_open(&io, "%s", path))
1801 return ERROR_FILE_DOES_NOT_EXIST;
1803 if (io_load(&io, " \t", read_option, &config) == ERR ||
1804 config.errors == TRUE)
1805 warn("Errors while loading %s.", path);
1806 return SUCCESS;
1809 static int
1810 load_options(void)
1812 const char *tigrc_user = getenv("TIGRC_USER");
1813 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1814 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1815 const bool diff_opts_from_args = !!opt_diff_argv;
1817 if (!tigrc_system)
1818 tigrc_system = SYSCONFDIR "/tigrc";
1819 load_option_file(tigrc_system);
1821 if (!tigrc_user)
1822 tigrc_user = "~/.tigrc";
1823 load_option_file(tigrc_user);
1825 /* Add _after_ loading config files to avoid adding run requests
1826 * that conflict with keybindings. */
1827 add_builtin_run_requests();
1829 if (!diff_opts_from_args && tig_diff_opts && *tig_diff_opts) {
1830 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1831 char buf[SIZEOF_STR];
1832 int argc = 0;
1834 if (!string_format(buf, "%s", tig_diff_opts) ||
1835 !argv_from_string(diff_opts, &argc, buf))
1836 die("TIG_DIFF_OPTS contains too many arguments");
1837 else if (!argv_copy(&opt_diff_argv, diff_opts))
1838 die("Failed to format TIG_DIFF_OPTS arguments");
1841 return OK;
1846 * The viewer
1849 struct view;
1850 struct view_ops;
1852 /* The display array of active views and the index of the current view. */
1853 static struct view *display[2];
1854 static WINDOW *display_win[2];
1855 static WINDOW *display_title[2];
1856 static WINDOW *display_sep;
1858 static unsigned int current_view;
1860 #define foreach_displayed_view(view, i) \
1861 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1863 #define displayed_views() (display[1] != NULL ? 2 : 1)
1865 /* Current head and commit ID */
1866 static char ref_blob[SIZEOF_REF] = "";
1867 static char ref_commit[SIZEOF_REF] = "HEAD";
1868 static char ref_head[SIZEOF_REF] = "HEAD";
1869 static char ref_branch[SIZEOF_REF] = "";
1870 static char ref_status[SIZEOF_STR] = "";
1871 static char ref_stash[SIZEOF_REF] = "";
1873 enum view_flag {
1874 VIEW_NO_FLAGS = 0,
1875 VIEW_ALWAYS_LINENO = 1 << 0,
1876 VIEW_CUSTOM_STATUS = 1 << 1,
1877 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1878 VIEW_ADD_PAGER_REFS = 1 << 3,
1879 VIEW_OPEN_DIFF = 1 << 4,
1880 VIEW_NO_REF = 1 << 5,
1881 VIEW_NO_GIT_DIR = 1 << 6,
1882 VIEW_DIFF_LIKE = 1 << 7,
1883 VIEW_SEND_CHILD_ENTER = 1 << 9,
1884 VIEW_FILE_FILTER = 1 << 10,
1885 VIEW_LOG_LIKE = 1 << 11,
1886 VIEW_STATUS_LIKE = 1 << 12,
1889 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1891 struct position {
1892 unsigned long offset; /* Offset of the window top */
1893 unsigned long col; /* Offset from the window side. */
1894 unsigned long lineno; /* Current line number */
1897 struct view {
1898 const char *name; /* View name */
1899 const char *id; /* Points to either of ref_{head,commit,blob} */
1901 struct view_ops *ops; /* View operations */
1903 char ref[SIZEOF_REF]; /* Hovered commit reference */
1904 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1906 int height, width; /* The width and height of the main window */
1907 WINDOW *win; /* The main window */
1909 /* Navigation */
1910 struct position pos; /* Current position. */
1911 struct position prev_pos; /* Previous position. */
1913 /* Searching */
1914 char grep[SIZEOF_STR]; /* Search string */
1915 regex_t *regex; /* Pre-compiled regexp */
1917 /* If non-NULL, points to the view that opened this view. If this view
1918 * is closed tig will switch back to the parent view. */
1919 struct view *parent;
1920 struct view *prev;
1922 /* Buffering */
1923 size_t lines; /* Total number of lines */
1924 struct line *line; /* Line index */
1925 unsigned int digits; /* Number of digits in the lines member. */
1927 /* Number of lines with custom status, not to be counted in the
1928 * view title. */
1929 unsigned int custom_lines;
1931 /* Drawing */
1932 struct line *curline; /* Line currently being drawn. */
1933 enum line_type curtype; /* Attribute currently used for drawing. */
1934 unsigned long col; /* Column when drawing. */
1935 bool has_scrolled; /* View was scrolled. */
1936 bool force_redraw; /* Whether to force a redraw after reading. */
1938 /* Loading */
1939 const char **argv; /* Shell command arguments. */
1940 const char *dir; /* Directory from which to execute. */
1941 struct io io;
1942 struct io *pipe;
1943 time_t start_time;
1944 time_t update_secs;
1945 struct encoding *encoding;
1946 bool unrefreshable;
1948 /* Private data */
1949 void *private;
1952 enum open_flags {
1953 OPEN_DEFAULT = 0, /* Use default view switching. */
1954 OPEN_STDIN = 1, /* Open in pager mode. */
1955 OPEN_FORWARD_STDIN = 2, /* Forward stdin to I/O process. */
1956 OPEN_SPLIT = 4, /* Split current view. */
1957 OPEN_RELOAD = 8, /* Reload view even if it is the current. */
1958 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1959 OPEN_PREPARED = 32, /* Open already prepared command. */
1960 OPEN_EXTRA = 64, /* Open extra data from command. */
1962 OPEN_PAGER_MODE = OPEN_STDIN | OPEN_FORWARD_STDIN,
1965 #define open_in_pager_mode(flags) ((flags) & OPEN_PAGER_MODE)
1966 #define open_from_stdin(flags) ((flags) & OPEN_STDIN)
1968 struct view_ops {
1969 /* What type of content being displayed. Used in the title bar. */
1970 const char *type;
1971 /* What keymap does this view have */
1972 struct keymap keymap;
1973 /* Flags to control the view behavior. */
1974 enum view_flag flags;
1975 /* Size of private data. */
1976 size_t private_size;
1977 /* Open and reads in all view content. */
1978 bool (*open)(struct view *view, enum open_flags flags);
1979 /* Read one line; updates view->line. */
1980 bool (*read)(struct view *view, char *data);
1981 /* Draw one line; @lineno must be < view->height. */
1982 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1983 /* Depending on view handle a special requests. */
1984 enum request (*request)(struct view *view, enum request request, struct line *line);
1985 /* Search for regexp in a line. */
1986 bool (*grep)(struct view *view, struct line *line);
1987 /* Select line */
1988 void (*select)(struct view *view, struct line *line);
1989 /* Release resources when reloading the view */
1990 void (*done)(struct view *view);
1993 #define VIEW_OPS(id, name, ref) name##_ops
1994 static struct view_ops VIEW_INFO(VIEW_OPS);
1996 static struct view views[] = {
1997 #define VIEW_DATA(id, name, ref) \
1998 { #name, ref, &name##_ops }
1999 VIEW_INFO(VIEW_DATA)
2002 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
2004 #define foreach_view(view, i) \
2005 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2007 #define view_is_displayed(view) \
2008 (view == display[0] || view == display[1])
2010 #define view_has_line(view, line_) \
2011 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
2013 static bool
2014 forward_request_to_child(struct view *child, enum request request)
2016 return displayed_views() == 2 && view_is_displayed(child) &&
2017 !strcmp(child->vid, child->id);
2020 static enum request
2021 view_request(struct view *view, enum request request)
2023 if (!view || !view->lines)
2024 return request;
2026 if (request == REQ_ENTER && !opt_focus_child &&
2027 view_has_flags(view, VIEW_SEND_CHILD_ENTER)) {
2028 struct view *child = display[1];
2030 if (forward_request_to_child(child, request)) {
2031 view_request(child, request);
2032 return REQ_NONE;
2036 if (request == REQ_REFRESH && view->unrefreshable) {
2037 report("This view can not be refreshed");
2038 return REQ_NONE;
2041 return view->ops->request(view, request, &view->line[view->pos.lineno]);
2045 * View drawing.
2048 static inline void
2049 set_view_attr(struct view *view, enum line_type type)
2051 if (!view->curline->selected && view->curtype != type) {
2052 (void) wattrset(view->win, get_line_attr(type));
2053 wchgat(view->win, -1, 0, get_line_color(type), NULL);
2054 view->curtype = type;
2058 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
2060 static bool
2061 draw_chars(struct view *view, enum line_type type, const char *string,
2062 int max_len, bool use_tilde)
2064 int len = 0;
2065 int col = 0;
2066 int trimmed = FALSE;
2067 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2069 if (max_len <= 0)
2070 return VIEW_MAX_LEN(view) <= 0;
2072 if (opt_iconv_out != ICONV_NONE) {
2073 string = encoding_iconv(opt_iconv_out, string);
2074 if (!string)
2075 return VIEW_MAX_LEN(view) <= 0;
2078 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
2080 set_view_attr(view, type);
2081 if (len > 0) {
2082 waddnstr(view->win, string, len);
2084 if (trimmed && use_tilde) {
2085 set_view_attr(view, LINE_DELIMITER);
2086 waddch(view->win, '~');
2087 col++;
2091 view->col += col;
2092 return VIEW_MAX_LEN(view) <= 0;
2095 static bool
2096 draw_space(struct view *view, enum line_type type, int max, int spaces)
2098 static char space[] = " ";
2100 spaces = MIN(max, spaces);
2102 while (spaces > 0) {
2103 int len = MIN(spaces, sizeof(space) - 1);
2105 if (draw_chars(view, type, space, len, FALSE))
2106 return TRUE;
2107 spaces -= len;
2110 return VIEW_MAX_LEN(view) <= 0;
2113 static bool
2114 draw_text_expanded(struct view *view, enum line_type type, const char *string, int max_len, bool use_tilde)
2116 static char text[SIZEOF_STR];
2118 do {
2119 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
2121 if (draw_chars(view, type, text, max_len, use_tilde))
2122 return TRUE;
2123 string += pos;
2124 } while (*string);
2126 return VIEW_MAX_LEN(view) <= 0;
2129 static bool
2130 draw_text(struct view *view, enum line_type type, const char *string)
2132 return draw_text_expanded(view, type, string, VIEW_MAX_LEN(view), TRUE);
2135 static bool
2136 draw_text_overflow(struct view *view, const char *text, bool on, int overflow, enum line_type type)
2138 if (on) {
2139 int max = MIN(VIEW_MAX_LEN(view), overflow);
2140 int len = strlen(text);
2142 if (draw_text_expanded(view, type, text, max, max < overflow))
2143 return TRUE;
2145 text = len > overflow ? text + overflow : "";
2146 type = LINE_OVERFLOW;
2149 if (*text && draw_text(view, type, text))
2150 return TRUE;
2152 return VIEW_MAX_LEN(view) <= 0;
2155 #define draw_commit_title(view, text, offset) \
2156 draw_text_overflow(view, text, opt_show_title_overflow, opt_title_overflow + offset, LINE_DEFAULT)
2158 static bool PRINTF_LIKE(3, 4)
2159 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
2161 char text[SIZEOF_STR];
2162 int retval;
2164 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
2165 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
2168 static bool
2169 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
2171 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2172 int max = VIEW_MAX_LEN(view);
2173 int i;
2175 if (max < size)
2176 size = max;
2178 set_view_attr(view, type);
2179 /* Using waddch() instead of waddnstr() ensures that
2180 * they'll be rendered correctly for the cursor line. */
2181 for (i = skip; i < size; i++)
2182 waddch(view->win, graphic[i]);
2184 view->col += size;
2185 if (separator) {
2186 if (size < max && skip <= size)
2187 waddch(view->win, ' ');
2188 view->col++;
2191 return VIEW_MAX_LEN(view) <= 0;
2194 enum align {
2195 ALIGN_LEFT,
2196 ALIGN_RIGHT
2199 static bool
2200 draw_field(struct view *view, enum line_type type, const char *text, int width, enum align align, bool trim)
2202 int max = MIN(VIEW_MAX_LEN(view), width + 1);
2203 int col = view->col;
2205 if (!text)
2206 return draw_space(view, type, max, max);
2208 if (align == ALIGN_RIGHT) {
2209 int textlen = strlen(text);
2210 int leftpad = max - textlen - 1;
2212 if (leftpad > 0) {
2213 if (draw_space(view, type, leftpad, leftpad))
2214 return TRUE;
2215 max -= leftpad;
2216 col += leftpad;;
2220 return draw_chars(view, type, text, max - 1, trim)
2221 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2224 static bool
2225 draw_date(struct view *view, struct time *time)
2227 const char *date = mkdate(time, opt_date);
2228 int cols = opt_date == DATE_SHORT ? DATE_SHORT_WIDTH : DATE_WIDTH;
2230 if (opt_date == DATE_NO)
2231 return FALSE;
2233 return draw_field(view, LINE_DATE, date, cols, ALIGN_LEFT, FALSE);
2236 static bool
2237 draw_author(struct view *view, const struct ident *author)
2239 bool trim = author_trim(opt_author_width);
2240 const char *text = mkauthor(author, opt_author_width, opt_author);
2242 if (opt_author == AUTHOR_NO)
2243 return FALSE;
2245 return draw_field(view, LINE_AUTHOR, text, opt_author_width, ALIGN_LEFT, trim);
2248 static bool
2249 draw_id_custom(struct view *view, enum line_type type, const char *id, int width)
2251 return draw_field(view, type, id, width, ALIGN_LEFT, FALSE);
2254 static bool
2255 draw_id(struct view *view, const char *id)
2257 if (!opt_show_id)
2258 return FALSE;
2260 return draw_id_custom(view, LINE_ID, id, opt_id_cols);
2263 static bool
2264 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2266 bool trim = filename && strlen(filename) >= opt_filename_width;
2268 if (opt_filename == FILENAME_NO)
2269 return FALSE;
2271 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2272 return FALSE;
2274 return draw_field(view, LINE_FILENAME, filename, opt_filename_width, ALIGN_LEFT, trim);
2277 static bool
2278 draw_file_size(struct view *view, unsigned long size, int width, bool pad)
2280 const char *str = pad ? NULL : mkfilesize(size, opt_file_size);
2282 if (!width || opt_file_size == FILE_SIZE_NO)
2283 return FALSE;
2285 return draw_field(view, LINE_FILE_SIZE, str, width, ALIGN_RIGHT, FALSE);
2288 static bool
2289 draw_mode(struct view *view, mode_t mode)
2291 const char *str = mkmode(mode);
2293 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r--"), ALIGN_LEFT, FALSE);
2296 static bool
2297 draw_lineno(struct view *view, unsigned int lineno)
2299 char number[10];
2300 int digits3 = view->digits < 3 ? 3 : view->digits;
2301 int max = MIN(VIEW_MAX_LEN(view), digits3);
2302 char *text = NULL;
2303 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2305 if (!opt_line_number)
2306 return FALSE;
2308 lineno += view->pos.offset + 1;
2309 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2310 static char fmt[] = "%1ld";
2312 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2313 if (string_format(number, fmt, lineno))
2314 text = number;
2316 if (text)
2317 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2318 else
2319 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2320 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2323 static bool
2324 draw_refs(struct view *view, struct ref_list *refs)
2326 size_t i;
2328 if (!opt_show_refs || !refs)
2329 return FALSE;
2331 for (i = 0; i < refs->size; i++) {
2332 struct ref *ref = refs->refs[i];
2333 enum line_type type = get_line_type_from_ref(ref);
2335 if (draw_formatted(view, type, "[%s]", ref->name))
2336 return TRUE;
2338 if (draw_text(view, LINE_DEFAULT, " "))
2339 return TRUE;
2342 return FALSE;
2345 static bool
2346 draw_view_line(struct view *view, unsigned int lineno)
2348 struct line *line;
2349 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2351 assert(view_is_displayed(view));
2353 if (view->pos.offset + lineno >= view->lines)
2354 return FALSE;
2356 line = &view->line[view->pos.offset + lineno];
2358 wmove(view->win, lineno, 0);
2359 if (line->cleareol)
2360 wclrtoeol(view->win);
2361 view->col = 0;
2362 view->curline = line;
2363 view->curtype = LINE_NONE;
2364 line->selected = FALSE;
2365 line->dirty = line->cleareol = 0;
2367 if (selected) {
2368 set_view_attr(view, LINE_CURSOR);
2369 line->selected = TRUE;
2370 view->ops->select(view, line);
2373 return view->ops->draw(view, line, lineno);
2376 static void
2377 redraw_view_dirty(struct view *view)
2379 bool dirty = FALSE;
2380 int lineno;
2382 for (lineno = 0; lineno < view->height; lineno++) {
2383 if (view->pos.offset + lineno >= view->lines)
2384 break;
2385 if (!view->line[view->pos.offset + lineno].dirty)
2386 continue;
2387 dirty = TRUE;
2388 if (!draw_view_line(view, lineno))
2389 break;
2392 if (!dirty)
2393 return;
2394 wnoutrefresh(view->win);
2397 static void
2398 redraw_view_from(struct view *view, int lineno)
2400 assert(0 <= lineno && lineno < view->height);
2402 for (; lineno < view->height; lineno++) {
2403 if (!draw_view_line(view, lineno))
2404 break;
2407 wnoutrefresh(view->win);
2410 static void
2411 redraw_view(struct view *view)
2413 werase(view->win);
2414 redraw_view_from(view, 0);
2418 static void
2419 update_view_title(struct view *view)
2421 char buf[SIZEOF_STR];
2422 char state[SIZEOF_STR];
2423 size_t bufpos = 0, statelen = 0;
2424 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2425 struct line *line = &view->line[view->pos.lineno];
2427 assert(view_is_displayed(view));
2429 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view_has_line(view, line) &&
2430 line->lineno) {
2431 unsigned int view_lines = view->pos.offset + view->height;
2432 unsigned int lines = view->lines
2433 ? MIN(view_lines, view->lines) * 100 / view->lines
2434 : 0;
2436 string_format_from(state, &statelen, " - %s %d of %zd (%d%%)",
2437 view->ops->type,
2438 line->lineno,
2439 view->lines - view->custom_lines,
2440 lines);
2444 if (view->pipe) {
2445 time_t secs = time(NULL) - view->start_time;
2447 /* Three git seconds are a long time ... */
2448 if (secs > 2)
2449 string_format_from(state, &statelen, " loading %lds", secs);
2452 string_format_from(buf, &bufpos, "[%s]", view->name);
2453 if (*view->ref && bufpos < view->width) {
2454 size_t refsize = strlen(view->ref);
2455 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2457 if (minsize < view->width)
2458 refsize = view->width - minsize + 7;
2459 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2462 if (statelen && bufpos < view->width) {
2463 string_format_from(buf, &bufpos, "%s", state);
2466 if (view == display[current_view])
2467 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2468 else
2469 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2471 mvwaddnstr(window, 0, 0, buf, bufpos);
2472 wclrtoeol(window);
2473 wnoutrefresh(window);
2476 static int
2477 apply_step(double step, int value)
2479 if (step >= 1)
2480 return (int) step;
2481 value *= step + 0.01;
2482 return value ? value : 1;
2485 static void
2486 apply_horizontal_split(struct view *base, struct view *view)
2488 view->width = base->width;
2489 view->height = apply_step(opt_scale_split_view, base->height);
2490 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2491 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2492 base->height -= view->height;
2495 static void
2496 apply_vertical_split(struct view *base, struct view *view)
2498 view->height = base->height;
2499 view->width = apply_step(opt_scale_vsplit_view, base->width);
2500 view->width = MAX(view->width, MIN_VIEW_WIDTH);
2501 view->width = MIN(view->width, base->width - MIN_VIEW_WIDTH);
2502 base->width -= view->width;
2505 static void
2506 redraw_display_separator(bool clear)
2508 if (displayed_views() > 1 && opt_vsplit) {
2509 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2511 if (clear)
2512 wclear(display_sep);
2513 wbkgd(display_sep, separator + get_line_attr(LINE_TITLE_BLUR));
2514 wnoutrefresh(display_sep);
2518 static void
2519 resize_display(void)
2521 int x, y, i;
2522 struct view *base = display[0];
2523 struct view *view = display[1] ? display[1] : display[0];
2525 /* Setup window dimensions */
2527 getmaxyx(stdscr, base->height, base->width);
2528 string_format(opt_env_columns, "COLUMNS=%d", base->width);
2529 string_format(opt_env_lines, "LINES=%d", base->height);
2531 /* Make room for the status window. */
2532 base->height -= 1;
2534 if (view != base) {
2535 if (opt_vsplit) {
2536 apply_vertical_split(base, view);
2538 /* Make room for the separator bar. */
2539 view->width -= 1;
2540 } else {
2541 apply_horizontal_split(base, view);
2544 /* Make room for the title bar. */
2545 view->height -= 1;
2548 /* Make room for the title bar. */
2549 base->height -= 1;
2551 x = y = 0;
2553 foreach_displayed_view (view, i) {
2554 if (!display_win[i]) {
2555 display_win[i] = newwin(view->height, view->width, y, x);
2556 if (!display_win[i])
2557 die("Failed to create %s view", view->name);
2559 scrollok(display_win[i], FALSE);
2561 display_title[i] = newwin(1, view->width, y + view->height, x);
2562 if (!display_title[i])
2563 die("Failed to create title window");
2565 } else {
2566 wresize(display_win[i], view->height, view->width);
2567 mvwin(display_win[i], y, x);
2568 wresize(display_title[i], 1, view->width);
2569 mvwin(display_title[i], y + view->height, x);
2572 if (i > 0 && opt_vsplit) {
2573 if (!display_sep) {
2574 display_sep = newwin(view->height, 1, 0, x - 1);
2575 if (!display_sep)
2576 die("Failed to create separator window");
2578 } else {
2579 wresize(display_sep, view->height, 1);
2580 mvwin(display_sep, 0, x - 1);
2584 view->win = display_win[i];
2586 if (opt_vsplit)
2587 x += view->width + 1;
2588 else
2589 y += view->height + 1;
2592 redraw_display_separator(FALSE);
2595 static void
2596 redraw_display(bool clear)
2598 struct view *view;
2599 int i;
2601 foreach_displayed_view (view, i) {
2602 if (clear)
2603 wclear(view->win);
2604 redraw_view(view);
2605 update_view_title(view);
2608 redraw_display_separator(clear);
2612 * Option management
2615 #define TOGGLE_MENU_INFO(_) \
2616 _(LINENO, '.', "line numbers", &opt_line_number, NULL, 0, VIEW_NO_FLAGS), \
2617 _(DATE, 'D', "dates", &opt_date, date_map, ARRAY_SIZE(date_map), VIEW_NO_FLAGS), \
2618 _(AUTHOR, 'A', "author", &opt_author, author_map, ARRAY_SIZE(author_map), VIEW_NO_FLAGS), \
2619 _(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map, ARRAY_SIZE(graphic_map), VIEW_NO_FLAGS), \
2620 _(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL, 0, VIEW_LOG_LIKE), \
2621 _(FILENAME, '#', "file names", &opt_filename, filename_map, ARRAY_SIZE(filename_map), VIEW_NO_FLAGS), \
2622 _(FILE_SIZE, '*', "file sizes", &opt_file_size, file_size_map, ARRAY_SIZE(file_size_map), VIEW_NO_FLAGS), \
2623 _(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map, ARRAY_SIZE(ignore_space_map), VIEW_DIFF_LIKE), \
2624 _(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map, ARRAY_SIZE(commit_order_map), VIEW_LOG_LIKE), \
2625 _(REFS, 'F', "reference display", &opt_show_refs, NULL, 0, VIEW_NO_FLAGS), \
2626 _(CHANGES, 'C', "local change display", &opt_show_changes, NULL, 0, VIEW_NO_FLAGS), \
2627 _(ID, 'X', "commit ID display", &opt_show_id, NULL, 0, VIEW_NO_FLAGS), \
2628 _(FILES, '%', "file filtering", &opt_file_filter, NULL, 0, VIEW_DIFF_LIKE | VIEW_LOG_LIKE), \
2629 _(TITLE_OVERFLOW, '$', "commit title overflow display", &opt_show_title_overflow, NULL, 0, VIEW_NO_FLAGS), \
2630 _(UNTRACKED_DIRS, 'd', "untracked directory info", &opt_untracked_dirs_content, NULL, 0, VIEW_STATUS_LIKE), \
2632 static enum view_flag
2633 toggle_option(struct view *view, enum request request, char msg[SIZEOF_STR])
2635 const struct {
2636 enum request request;
2637 const struct enum_map *map;
2638 size_t map_size;
2639 enum view_flag reload_flags;
2640 } data[] = {
2641 #define DEFINE_TOGGLE_DATA(id, key, help, value, map, map_size, vflags) { REQ_TOGGLE_ ## id, map, map_size, vflags }
2642 TOGGLE_MENU_INFO(DEFINE_TOGGLE_DATA)
2644 const struct menu_item menu[] = {
2645 #define DEFINE_TOGGLE_MENU(id, key, help, value, map, map_size, vflags) { key, help, value }
2646 TOGGLE_MENU_INFO(DEFINE_TOGGLE_MENU)
2647 { 0 }
2649 int i = 0;
2651 if (request == REQ_OPTIONS) {
2652 if (!prompt_menu("Toggle option", menu, &i))
2653 return VIEW_NO_FLAGS;
2654 } else {
2655 while (i < ARRAY_SIZE(data) && data[i].request != request)
2656 i++;
2657 if (i >= ARRAY_SIZE(data))
2658 die("Invalid request (%d)", request);
2661 if (data[i].map != NULL) {
2662 unsigned int *opt = menu[i].data;
2664 *opt = (*opt + 1) % data[i].map_size;
2665 if (data[i].map == ignore_space_map) {
2666 update_ignore_space_arg();
2667 string_format_size(msg, SIZEOF_STR,
2668 "Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2670 } else if (data[i].map == commit_order_map) {
2671 update_commit_order_arg();
2672 string_format_size(msg, SIZEOF_STR,
2673 "Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2675 } else {
2676 string_format_size(msg, SIZEOF_STR,
2677 "Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2680 } else {
2681 bool *option = menu[i].data;
2683 *option = !*option;
2684 string_format_size(msg, SIZEOF_STR,
2685 "%sabling %s", *option ? "En" : "Dis", menu[i].text);
2688 return data[i].reload_flags;
2693 * Navigation
2696 static bool
2697 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2699 if (lineno >= view->lines)
2700 lineno = view->lines > 0 ? view->lines - 1 : 0;
2702 if (offset > lineno || offset + view->height <= lineno) {
2703 unsigned long half = view->height / 2;
2705 if (lineno > half)
2706 offset = lineno - half;
2707 else
2708 offset = 0;
2711 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2712 view->pos.offset = offset;
2713 view->pos.lineno = lineno;
2714 return TRUE;
2717 return FALSE;
2720 /* Scrolling backend */
2721 static void
2722 do_scroll_view(struct view *view, int lines)
2724 bool redraw_current_line = FALSE;
2726 /* The rendering expects the new offset. */
2727 view->pos.offset += lines;
2729 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2730 assert(lines);
2732 /* Move current line into the view. */
2733 if (view->pos.lineno < view->pos.offset) {
2734 view->pos.lineno = view->pos.offset;
2735 redraw_current_line = TRUE;
2736 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2737 view->pos.lineno = view->pos.offset + view->height - 1;
2738 redraw_current_line = TRUE;
2741 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2743 /* Redraw the whole screen if scrolling is pointless. */
2744 if (view->height < ABS(lines)) {
2745 redraw_view(view);
2747 } else {
2748 int line = lines > 0 ? view->height - lines : 0;
2749 int end = line + ABS(lines);
2751 scrollok(view->win, TRUE);
2752 wscrl(view->win, lines);
2753 scrollok(view->win, FALSE);
2755 while (line < end && draw_view_line(view, line))
2756 line++;
2758 if (redraw_current_line)
2759 draw_view_line(view, view->pos.lineno - view->pos.offset);
2760 wnoutrefresh(view->win);
2763 view->has_scrolled = TRUE;
2764 report_clear();
2767 /* Scroll frontend */
2768 static void
2769 scroll_view(struct view *view, enum request request)
2771 int lines = 1;
2773 assert(view_is_displayed(view));
2775 switch (request) {
2776 case REQ_SCROLL_FIRST_COL:
2777 view->pos.col = 0;
2778 redraw_view_from(view, 0);
2779 report_clear();
2780 return;
2781 case REQ_SCROLL_LEFT:
2782 if (view->pos.col == 0) {
2783 report("Cannot scroll beyond the first column");
2784 return;
2786 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2787 view->pos.col = 0;
2788 else
2789 view->pos.col -= apply_step(opt_hscroll, view->width);
2790 redraw_view_from(view, 0);
2791 report_clear();
2792 return;
2793 case REQ_SCROLL_RIGHT:
2794 view->pos.col += apply_step(opt_hscroll, view->width);
2795 redraw_view(view);
2796 report_clear();
2797 return;
2798 case REQ_SCROLL_PAGE_DOWN:
2799 lines = view->height;
2800 case REQ_SCROLL_LINE_DOWN:
2801 if (view->pos.offset + lines > view->lines)
2802 lines = view->lines - view->pos.offset;
2804 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2805 report("Cannot scroll beyond the last line");
2806 return;
2808 break;
2810 case REQ_SCROLL_PAGE_UP:
2811 lines = view->height;
2812 case REQ_SCROLL_LINE_UP:
2813 if (lines > view->pos.offset)
2814 lines = view->pos.offset;
2816 if (lines == 0) {
2817 report("Cannot scroll beyond the first line");
2818 return;
2821 lines = -lines;
2822 break;
2824 default:
2825 die("request %d not handled in switch", request);
2828 do_scroll_view(view, lines);
2831 /* Cursor moving */
2832 static void
2833 move_view(struct view *view, enum request request)
2835 int scroll_steps = 0;
2836 int steps;
2838 switch (request) {
2839 case REQ_MOVE_FIRST_LINE:
2840 steps = -view->pos.lineno;
2841 break;
2843 case REQ_MOVE_LAST_LINE:
2844 steps = view->lines - view->pos.lineno - 1;
2845 break;
2847 case REQ_MOVE_PAGE_UP:
2848 steps = view->height > view->pos.lineno
2849 ? -view->pos.lineno : -view->height;
2850 break;
2852 case REQ_MOVE_PAGE_DOWN:
2853 steps = view->pos.lineno + view->height >= view->lines
2854 ? view->lines - view->pos.lineno - 1 : view->height;
2855 break;
2857 case REQ_MOVE_UP:
2858 case REQ_PREVIOUS:
2859 steps = -1;
2860 break;
2862 case REQ_MOVE_DOWN:
2863 case REQ_NEXT:
2864 steps = 1;
2865 break;
2867 default:
2868 die("request %d not handled in switch", request);
2871 if (steps <= 0 && view->pos.lineno == 0) {
2872 report("Cannot move beyond the first line");
2873 return;
2875 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2876 report("Cannot move beyond the last line");
2877 return;
2880 /* Move the current line */
2881 view->pos.lineno += steps;
2882 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2884 /* Check whether the view needs to be scrolled */
2885 if (view->pos.lineno < view->pos.offset ||
2886 view->pos.lineno >= view->pos.offset + view->height) {
2887 scroll_steps = steps;
2888 if (steps < 0 && -steps > view->pos.offset) {
2889 scroll_steps = -view->pos.offset;
2891 } else if (steps > 0) {
2892 if (view->pos.lineno == view->lines - 1 &&
2893 view->lines > view->height) {
2894 scroll_steps = view->lines - view->pos.offset - 1;
2895 if (scroll_steps >= view->height)
2896 scroll_steps -= view->height - 1;
2901 if (!view_is_displayed(view)) {
2902 view->pos.offset += scroll_steps;
2903 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2904 view->ops->select(view, &view->line[view->pos.lineno]);
2905 return;
2908 /* Repaint the old "current" line if we be scrolling */
2909 if (ABS(steps) < view->height)
2910 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2912 if (scroll_steps) {
2913 do_scroll_view(view, scroll_steps);
2914 return;
2917 /* Draw the current line */
2918 draw_view_line(view, view->pos.lineno - view->pos.offset);
2920 wnoutrefresh(view->win);
2921 report_clear();
2926 * Searching
2929 static void search_view(struct view *view, enum request request);
2931 static bool
2932 grep_text(struct view *view, const char *text[])
2934 regmatch_t pmatch;
2935 size_t i;
2937 for (i = 0; text[i]; i++)
2938 if (*text[i] && !regexec(view->regex, text[i], 1, &pmatch, 0))
2939 return TRUE;
2940 return FALSE;
2943 static void
2944 select_view_line(struct view *view, unsigned long lineno)
2946 struct position old = view->pos;
2948 if (goto_view_line(view, view->pos.offset, lineno)) {
2949 if (view_is_displayed(view)) {
2950 if (old.offset != view->pos.offset) {
2951 redraw_view(view);
2952 } else {
2953 draw_view_line(view, old.lineno - view->pos.offset);
2954 draw_view_line(view, view->pos.lineno - view->pos.offset);
2955 wnoutrefresh(view->win);
2957 } else {
2958 view->ops->select(view, &view->line[view->pos.lineno]);
2963 static void
2964 find_next(struct view *view, enum request request)
2966 unsigned long lineno = view->pos.lineno;
2967 int direction;
2969 if (!*view->grep) {
2970 if (!*opt_search)
2971 report("No previous search");
2972 else
2973 search_view(view, request);
2974 return;
2977 switch (request) {
2978 case REQ_SEARCH:
2979 case REQ_FIND_NEXT:
2980 direction = 1;
2981 break;
2983 case REQ_SEARCH_BACK:
2984 case REQ_FIND_PREV:
2985 direction = -1;
2986 break;
2988 default:
2989 return;
2992 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2993 lineno += direction;
2995 /* Note, lineno is unsigned long so will wrap around in which case it
2996 * will become bigger than view->lines. */
2997 for (; lineno < view->lines; lineno += direction) {
2998 if (view->ops->grep(view, &view->line[lineno])) {
2999 select_view_line(view, lineno);
3000 report("Line %ld matches '%s'", lineno + 1, view->grep);
3001 return;
3005 report("No match found for '%s'", view->grep);
3008 static void
3009 search_view(struct view *view, enum request request)
3011 int regex_err;
3012 int regex_flags = opt_ignore_case ? REG_ICASE : 0;
3014 if (view->regex) {
3015 regfree(view->regex);
3016 *view->grep = 0;
3017 } else {
3018 view->regex = calloc(1, sizeof(*view->regex));
3019 if (!view->regex)
3020 return;
3023 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED | regex_flags);
3024 if (regex_err != 0) {
3025 char buf[SIZEOF_STR] = "unknown error";
3027 regerror(regex_err, view->regex, buf, sizeof(buf));
3028 report("Search failed: %s", buf);
3029 return;
3032 string_copy(view->grep, opt_search);
3034 find_next(view, request);
3038 * Incremental updating
3041 static inline bool
3042 check_position(struct position *pos)
3044 return pos->lineno || pos->col || pos->offset;
3047 static inline void
3048 clear_position(struct position *pos)
3050 memset(pos, 0, sizeof(*pos));
3053 static void
3054 reset_view(struct view *view)
3056 int i;
3058 if (view->ops->done)
3059 view->ops->done(view);
3061 for (i = 0; i < view->lines; i++)
3062 free(view->line[i].data);
3063 free(view->line);
3065 view->prev_pos = view->pos;
3066 clear_position(&view->pos);
3068 view->line = NULL;
3069 view->lines = 0;
3070 view->vid[0] = 0;
3071 view->custom_lines = 0;
3072 view->update_secs = 0;
3075 struct format_context {
3076 struct view *view;
3077 char buf[SIZEOF_STR];
3078 size_t bufpos;
3079 bool file_filter;
3082 static bool
3083 format_expand_arg(struct format_context *format, const char *name)
3085 static struct {
3086 const char *name;
3087 size_t namelen;
3088 const char *value;
3089 const char *value_if_empty;
3090 } vars[] = {
3091 #define FORMAT_VAR(name, value, value_if_empty) \
3092 { name, STRING_SIZE(name), value, value_if_empty }
3093 FORMAT_VAR("%(directory)", opt_path, "."),
3094 FORMAT_VAR("%(file)", opt_file, ""),
3095 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
3096 FORMAT_VAR("%(head)", ref_head, ""),
3097 FORMAT_VAR("%(commit)", ref_commit, ""),
3098 FORMAT_VAR("%(blob)", ref_blob, ""),
3099 FORMAT_VAR("%(branch)", ref_branch, ""),
3100 FORMAT_VAR("%(stash)", ref_stash, ""),
3102 int i;
3104 if (!prefixcmp(name, "%(prompt)")) {
3105 const char *value = read_prompt("Command argument: ");
3107 return string_format_from(format->buf, &format->bufpos, "%s", value);
3110 for (i = 0; i < ARRAY_SIZE(vars); i++) {
3111 const char *value;
3113 if (strncmp(name, vars[i].name, vars[i].namelen))
3114 continue;
3116 if (vars[i].value == opt_file && !format->file_filter)
3117 return TRUE;
3119 value = *vars[i].value ? vars[i].value : vars[i].value_if_empty;
3120 if (!*value)
3121 return TRUE;
3123 return string_format_from(format->buf, &format->bufpos, "%s", value);
3126 report("Unknown replacement: `%s`", name);
3127 return NULL;
3130 static bool
3131 format_append_arg(struct format_context *format, const char ***dst_argv, const char *arg)
3133 memset(format->buf, 0, sizeof(format->buf));
3134 format->bufpos = 0;
3136 while (arg) {
3137 char *next = strstr(arg, "%(");
3138 int len = next ? next - arg : strlen(arg);
3140 if (len && !string_format_from(format->buf, &format->bufpos, "%.*s", len, arg))
3141 return FALSE;
3143 if (next && !format_expand_arg(format, next))
3144 return FALSE;
3146 arg = next ? strchr(next, ')') + 1 : NULL;
3149 return argv_append(dst_argv, format->buf);
3152 static bool
3153 format_append_argv(struct format_context *format, const char ***dst_argv, const char *src_argv[])
3155 int argc;
3157 if (!src_argv)
3158 return TRUE;
3160 for (argc = 0; src_argv[argc]; argc++)
3161 if (!format_append_arg(format, dst_argv, src_argv[argc]))
3162 return FALSE;
3164 return src_argv[argc] == NULL;
3167 static bool
3168 format_argv(struct view *view, const char ***dst_argv, const char *src_argv[], bool first, bool file_filter)
3170 struct format_context format = { view, "", 0, file_filter };
3171 int argc;
3173 argv_free(*dst_argv);
3175 for (argc = 0; src_argv[argc]; argc++) {
3176 const char *arg = src_argv[argc];
3178 if (!strcmp(arg, "%(fileargs)")) {
3179 if (file_filter && !argv_append_array(dst_argv, opt_file_argv))
3180 break;
3182 } else if (!strcmp(arg, "%(diffargs)")) {
3183 if (!format_append_argv(&format, dst_argv, opt_diff_argv))
3184 break;
3186 } else if (!strcmp(arg, "%(blameargs)")) {
3187 if (!format_append_argv(&format, dst_argv, opt_blame_argv))
3188 break;
3190 } else if (!strcmp(arg, "%(revargs)") ||
3191 (first && !strcmp(arg, "%(commit)"))) {
3192 if (!argv_append_array(dst_argv, opt_rev_argv))
3193 break;
3195 } else if (!format_append_arg(&format, dst_argv, arg)) {
3196 break;
3200 return src_argv[argc] == NULL;
3203 static bool
3204 restore_view_position(struct view *view)
3206 /* A view without a previous view is the first view */
3207 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
3208 select_view_line(view, opt_lineno - 1);
3209 opt_lineno = 0;
3212 /* Ensure that the view position is in a valid state. */
3213 if (!check_position(&view->prev_pos) ||
3214 (view->pipe && view->lines <= view->prev_pos.lineno))
3215 return goto_view_line(view, view->pos.offset, view->pos.lineno);
3217 /* Changing the view position cancels the restoring. */
3218 /* FIXME: Changing back to the first line is not detected. */
3219 if (check_position(&view->pos)) {
3220 clear_position(&view->prev_pos);
3221 return FALSE;
3224 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
3225 view_is_displayed(view))
3226 werase(view->win);
3228 view->pos.col = view->prev_pos.col;
3229 clear_position(&view->prev_pos);
3231 return TRUE;
3234 static void
3235 end_update(struct view *view, bool force)
3237 if (!view->pipe)
3238 return;
3239 while (!view->ops->read(view, NULL))
3240 if (!force)
3241 return;
3242 if (force)
3243 io_kill(view->pipe);
3244 io_done(view->pipe);
3245 view->pipe = NULL;
3248 static void
3249 setup_update(struct view *view, const char *vid)
3251 reset_view(view);
3252 /* XXX: Do not use string_copy_rev(), it copies until first space. */
3253 string_ncopy(view->vid, vid, strlen(vid));
3254 view->pipe = &view->io;
3255 view->start_time = time(NULL);
3258 static bool
3259 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
3261 bool extra = !!(flags & (OPEN_EXTRA));
3262 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA | OPEN_PAGER_MODE));
3263 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED | OPEN_STDIN);
3264 bool forward_stdin = flags & OPEN_FORWARD_STDIN;
3265 enum io_type io_type = forward_stdin ? IO_RD_STDIN : IO_RD;
3267 if ((!reload && !strcmp(view->vid, view->id)) ||
3268 ((flags & OPEN_REFRESH) && view->unrefreshable))
3269 return TRUE;
3271 if (view->pipe) {
3272 if (extra)
3273 io_done(view->pipe);
3274 else
3275 end_update(view, TRUE);
3278 view->unrefreshable = open_in_pager_mode(flags);
3280 if (!refresh && argv) {
3281 bool file_filter = !view_has_flags(view, VIEW_FILE_FILTER) || opt_file_filter;
3283 view->dir = dir;
3284 if (!format_argv(view, &view->argv, argv, !view->prev, file_filter)) {
3285 report("Failed to format %s arguments", view->name);
3286 return FALSE;
3289 /* Put the current ref_* value to the view title ref
3290 * member. This is needed by the blob view. Most other
3291 * views sets it automatically after loading because the
3292 * first line is a commit line. */
3293 string_copy_rev(view->ref, view->id);
3296 if (view->argv && view->argv[0] &&
3297 !io_run(&view->io, io_type, view->dir, opt_env, view->argv)) {
3298 report("Failed to open %s view", view->name);
3299 return FALSE;
3302 if (open_from_stdin(flags)) {
3303 if (!io_open(&view->io, "%s", ""))
3304 die("Failed to open stdin");
3307 if (!extra)
3308 setup_update(view, view->id);
3310 return TRUE;
3313 static bool
3314 update_view(struct view *view)
3316 char *line;
3317 /* Clear the view and redraw everything since the tree sorting
3318 * might have rearranged things. */
3319 bool redraw = view->lines == 0;
3320 bool can_read = TRUE;
3321 struct encoding *encoding = view->encoding ? view->encoding : default_encoding;
3323 if (!view->pipe)
3324 return TRUE;
3326 if (!io_can_read(view->pipe, FALSE)) {
3327 if (view->lines == 0 && view_is_displayed(view)) {
3328 time_t secs = time(NULL) - view->start_time;
3330 if (secs > 1 && secs > view->update_secs) {
3331 if (view->update_secs == 0)
3332 redraw_view(view);
3333 update_view_title(view);
3334 view->update_secs = secs;
3337 return TRUE;
3340 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
3341 if (encoding) {
3342 line = encoding_convert(encoding, line);
3345 if (!view->ops->read(view, line)) {
3346 report("Allocation failure");
3347 end_update(view, TRUE);
3348 return FALSE;
3353 int digits = count_digits(view->lines);
3355 /* Keep the displayed view in sync with line number scaling. */
3356 if (digits != view->digits) {
3357 view->digits = digits;
3358 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3359 redraw = TRUE;
3363 if (io_error(view->pipe)) {
3364 report("Failed to read: %s", io_strerror(view->pipe));
3365 end_update(view, TRUE);
3367 } else if (io_eof(view->pipe)) {
3368 end_update(view, FALSE);
3371 if (restore_view_position(view))
3372 redraw = TRUE;
3374 if (!view_is_displayed(view))
3375 return TRUE;
3377 if (redraw || view->force_redraw)
3378 redraw_view_from(view, 0);
3379 else
3380 redraw_view_dirty(view);
3381 view->force_redraw = FALSE;
3383 /* Update the title _after_ the redraw so that if the redraw picks up a
3384 * commit reference in view->ref it'll be available here. */
3385 update_view_title(view);
3386 return TRUE;
3389 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3391 static struct line *
3392 add_line_at(struct view *view, unsigned long pos, const void *data, enum line_type type, size_t data_size, bool custom)
3394 struct line *line;
3395 unsigned long lineno;
3397 if (!realloc_lines(&view->line, view->lines, 1))
3398 return NULL;
3400 if (data_size) {
3401 void *alloc_data = calloc(1, data_size);
3403 if (!alloc_data)
3404 return NULL;
3406 if (data)
3407 memcpy(alloc_data, data, data_size);
3408 data = alloc_data;
3411 if (pos < view->lines) {
3412 view->lines++;
3413 line = view->line + pos;
3414 if (!custom)
3415 lineno = line->lineno;
3417 memmove(line + 1, line, (view->lines - pos) * sizeof(*view->line));
3418 while (pos < view->lines) {
3419 view->line[pos].lineno++;
3420 view->line[pos++].dirty = 1;
3422 } else {
3423 line = &view->line[view->lines++];
3424 lineno = view->lines - view->custom_lines;
3427 memset(line, 0, sizeof(*line));
3428 line->type = type;
3429 line->data = (void *) data;
3430 line->dirty = 1;
3432 if (custom)
3433 view->custom_lines++;
3434 else
3435 line->lineno = lineno;
3437 return line;
3440 static struct line *
3441 add_line(struct view *view, const void *data, enum line_type type, size_t data_size, bool custom)
3443 return add_line_at(view, view->lines, data, type, data_size, custom);
3446 static struct line *
3447 add_line_alloc_(struct view *view, void **ptr, enum line_type type, size_t data_size, bool custom)
3449 struct line *line = add_line(view, NULL, type, data_size, custom);
3451 if (line)
3452 *ptr = line->data;
3453 return line;
3456 #define add_line_alloc(view, data_ptr, type, extra_size, custom) \
3457 add_line_alloc_(view, (void **) data_ptr, type, sizeof(**data_ptr) + extra_size, custom)
3459 static struct line *
3460 add_line_nodata(struct view *view, enum line_type type)
3462 return add_line(view, NULL, type, 0, FALSE);
3465 static struct line *
3466 add_line_text(struct view *view, const char *text, enum line_type type)
3468 return add_line(view, text, type, strlen(text) + 1, FALSE);
3471 static struct line * PRINTF_LIKE(3, 4)
3472 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3474 char buf[SIZEOF_STR];
3475 int retval;
3477 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3478 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3482 * View opening
3485 static void
3486 split_view(struct view *prev, struct view *view)
3488 display[1] = view;
3489 current_view = opt_focus_child ? 1 : 0;
3490 view->parent = prev;
3491 resize_display();
3493 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3494 /* Take the title line into account. */
3495 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3497 /* Scroll the view that was split if the current line is
3498 * outside the new limited view. */
3499 do_scroll_view(prev, lines);
3502 if (view != prev && view_is_displayed(prev)) {
3503 /* "Blur" the previous view. */
3504 update_view_title(prev);
3508 static void
3509 maximize_view(struct view *view, bool redraw)
3511 memset(display, 0, sizeof(display));
3512 current_view = 0;
3513 display[current_view] = view;
3514 resize_display();
3515 if (redraw) {
3516 redraw_display(FALSE);
3517 report_clear();
3521 static void
3522 load_view(struct view *view, struct view *prev, enum open_flags flags)
3524 if (view->pipe)
3525 end_update(view, TRUE);
3526 if (view->ops->private_size) {
3527 if (!view->private)
3528 view->private = calloc(1, view->ops->private_size);
3529 else
3530 memset(view->private, 0, view->ops->private_size);
3533 /* When prev == view it means this is the first loaded view. */
3534 if (prev && view != prev) {
3535 view->prev = prev;
3538 if (!view->ops->open(view, flags))
3539 return;
3541 if (prev) {
3542 bool split = !!(flags & OPEN_SPLIT);
3544 if (split) {
3545 split_view(prev, view);
3546 } else {
3547 maximize_view(view, FALSE);
3551 restore_view_position(view);
3553 if (view->pipe && view->lines == 0) {
3554 /* Clear the old view and let the incremental updating refill
3555 * the screen. */
3556 werase(view->win);
3557 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3558 clear_position(&view->prev_pos);
3559 report_clear();
3560 } else if (view_is_displayed(view)) {
3561 redraw_view(view);
3562 report_clear();
3566 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3567 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3569 static void
3570 open_view(struct view *prev, enum request request, enum open_flags flags)
3572 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3573 struct view *view = VIEW(request);
3574 int nviews = displayed_views();
3576 assert(flags ^ OPEN_REFRESH);
3578 if (view == prev && nviews == 1 && !reload) {
3579 report("Already in %s view", view->name);
3580 return;
3583 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3584 report("The %s view is disabled in pager view", view->name);
3585 return;
3588 load_view(view, prev ? prev : view, flags);
3591 static void
3592 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3594 enum request request = view - views + REQ_OFFSET + 1;
3596 if (view->pipe)
3597 end_update(view, TRUE);
3598 view->dir = dir;
3600 if (!argv_copy(&view->argv, argv)) {
3601 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3602 } else {
3603 open_view(prev, request, flags | OPEN_PREPARED);
3607 static bool
3608 open_external_viewer(const char *argv[], const char *dir, bool confirm, const char *notice)
3610 bool ok;
3612 def_prog_mode(); /* save current tty modes */
3613 endwin(); /* restore original tty modes */
3614 ok = io_run_fg(argv, dir);
3615 if (confirm) {
3616 if (!ok && *notice)
3617 fprintf(stderr, "%s", notice);
3618 fprintf(stderr, "Press Enter to continue");
3619 getc(opt_tty);
3621 reset_prog_mode();
3622 redraw_display(TRUE);
3623 return ok;
3626 static void
3627 open_mergetool(const char *file)
3629 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3631 open_external_viewer(mergetool_argv, opt_cdup, TRUE, "");
3634 #define EDITOR_LINENO_MSG \
3635 "*** Your editor reported an error while opening the file.\n" \
3636 "*** This is probably because it doesn't support the line\n" \
3637 "*** number argument added automatically. The line number\n" \
3638 "*** has been disabled for now. You can permanently disable\n" \
3639 "*** it by adding the following line to ~/.tigrc\n" \
3640 "*** set editor-line-number = no\n"
3642 static void
3643 open_editor(const char *file, unsigned int lineno)
3645 const char *editor_argv[SIZEOF_ARG + 3] = { "vi", file, NULL };
3646 char editor_cmd[SIZEOF_STR];
3647 char lineno_cmd[SIZEOF_STR];
3648 const char *editor;
3649 int argc = 0;
3651 editor = getenv("GIT_EDITOR");
3652 if (!editor && *opt_editor)
3653 editor = opt_editor;
3654 if (!editor)
3655 editor = getenv("VISUAL");
3656 if (!editor)
3657 editor = getenv("EDITOR");
3658 if (!editor)
3659 editor = "vi";
3661 string_ncopy(editor_cmd, editor, strlen(editor));
3662 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3663 report("Failed to read editor command");
3664 return;
3667 if (lineno && opt_editor_lineno && string_format(lineno_cmd, "+%u", lineno))
3668 editor_argv[argc++] = lineno_cmd;
3669 editor_argv[argc] = file;
3670 if (!open_external_viewer(editor_argv, opt_cdup, TRUE, EDITOR_LINENO_MSG))
3671 opt_editor_lineno = FALSE;
3674 static enum request run_prompt_command(struct view *view, char *cmd);
3676 static enum request
3677 open_run_request(struct view *view, enum request request)
3679 struct run_request *req = get_run_request(request);
3680 const char **argv = NULL;
3681 bool confirmed = FALSE;
3683 request = REQ_NONE;
3685 if (!req) {
3686 report("Unknown run request");
3687 return request;
3690 if (format_argv(view, &argv, req->argv, FALSE, TRUE)) {
3691 if (req->internal) {
3692 char cmd[SIZEOF_STR];
3694 if (argv_to_string(argv, cmd, sizeof(cmd), " ")) {
3695 request = run_prompt_command(view, cmd);
3698 else {
3699 confirmed = !req->confirm;
3701 if (req->confirm) {
3702 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
3703 const char *and_exit = req->exit ? " and exit" : "";
3705 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
3706 string_format(prompt, "Run `%s`%s?", cmd, and_exit) &&
3707 prompt_yesno(prompt)) {
3708 confirmed = TRUE;
3712 if (confirmed && argv_remove_quotes(argv)) {
3713 if (req->silent)
3714 io_run_bg(argv);
3715 else
3716 open_external_viewer(argv, NULL, !req->exit, "");
3721 if (argv)
3722 argv_free(argv);
3723 free(argv);
3725 if (request == REQ_NONE) {
3726 if (req->confirm && !confirmed)
3727 request = REQ_NONE;
3729 else if (req->exit)
3730 request = REQ_QUIT;
3732 else if (!view->unrefreshable)
3733 request = REQ_REFRESH;
3735 return request;
3739 * User request switch noodle
3742 static int
3743 view_driver(struct view *view, enum request request)
3745 int i;
3747 if (request == REQ_NONE)
3748 return TRUE;
3750 if (request > REQ_NONE) {
3751 request = open_run_request(view, request);
3753 // exit quickly rather than going through view_request and back
3754 if (request == REQ_QUIT)
3755 return FALSE;
3758 request = view_request(view, request);
3759 if (request == REQ_NONE)
3760 return TRUE;
3762 switch (request) {
3763 case REQ_MOVE_UP:
3764 case REQ_MOVE_DOWN:
3765 case REQ_MOVE_PAGE_UP:
3766 case REQ_MOVE_PAGE_DOWN:
3767 case REQ_MOVE_FIRST_LINE:
3768 case REQ_MOVE_LAST_LINE:
3769 move_view(view, request);
3770 break;
3772 case REQ_SCROLL_FIRST_COL:
3773 case REQ_SCROLL_LEFT:
3774 case REQ_SCROLL_RIGHT:
3775 case REQ_SCROLL_LINE_DOWN:
3776 case REQ_SCROLL_LINE_UP:
3777 case REQ_SCROLL_PAGE_DOWN:
3778 case REQ_SCROLL_PAGE_UP:
3779 scroll_view(view, request);
3780 break;
3782 case REQ_VIEW_MAIN:
3783 case REQ_VIEW_DIFF:
3784 case REQ_VIEW_LOG:
3785 case REQ_VIEW_TREE:
3786 case REQ_VIEW_HELP:
3787 case REQ_VIEW_BRANCH:
3788 case REQ_VIEW_BLAME:
3789 case REQ_VIEW_BLOB:
3790 case REQ_VIEW_STATUS:
3791 case REQ_VIEW_STAGE:
3792 case REQ_VIEW_PAGER:
3793 case REQ_VIEW_STASH:
3794 open_view(view, request, OPEN_DEFAULT);
3795 break;
3797 case REQ_NEXT:
3798 case REQ_PREVIOUS:
3799 if (view->parent) {
3800 int line;
3802 view = view->parent;
3803 line = view->pos.lineno;
3804 view_request(view, request);
3805 move_view(view, request);
3806 if (view_is_displayed(view))
3807 update_view_title(view);
3808 if (line != view->pos.lineno)
3809 view_request(view, REQ_ENTER);
3810 } else {
3811 move_view(view, request);
3813 break;
3815 case REQ_VIEW_NEXT:
3817 int nviews = displayed_views();
3818 int next_view = (current_view + 1) % nviews;
3820 if (next_view == current_view) {
3821 report("Only one view is displayed");
3822 break;
3825 current_view = next_view;
3826 /* Blur out the title of the previous view. */
3827 update_view_title(view);
3828 report_clear();
3829 break;
3831 case REQ_REFRESH:
3832 report("Refreshing is not supported by the %s view", view->name);
3833 break;
3835 case REQ_PARENT:
3836 report("Moving to parent is not supported by the the %s view", view->name);
3837 break;
3839 case REQ_BACK:
3840 report("Going back is not supported for by %s view", view->name);
3841 break;
3843 case REQ_MAXIMIZE:
3844 if (displayed_views() == 2)
3845 maximize_view(view, TRUE);
3846 break;
3848 case REQ_OPTIONS:
3849 case REQ_TOGGLE_LINENO:
3850 case REQ_TOGGLE_DATE:
3851 case REQ_TOGGLE_AUTHOR:
3852 case REQ_TOGGLE_FILENAME:
3853 case REQ_TOGGLE_GRAPHIC:
3854 case REQ_TOGGLE_REV_GRAPH:
3855 case REQ_TOGGLE_REFS:
3856 case REQ_TOGGLE_CHANGES:
3857 case REQ_TOGGLE_IGNORE_SPACE:
3858 case REQ_TOGGLE_ID:
3859 case REQ_TOGGLE_FILES:
3860 case REQ_TOGGLE_TITLE_OVERFLOW:
3862 char action[SIZEOF_STR] = "";
3863 enum view_flag flags = toggle_option(view, request, action);
3865 foreach_displayed_view(view, i) {
3866 if (view_has_flags(view, flags) && !view->unrefreshable)
3867 reload_view(view);
3868 else
3869 redraw_view(view);
3872 if (*action)
3873 report("%s", action);
3875 break;
3877 case REQ_TOGGLE_SORT_FIELD:
3878 case REQ_TOGGLE_SORT_ORDER:
3879 report("Sorting is not yet supported for the %s view", view->name);
3880 break;
3882 case REQ_DIFF_CONTEXT_UP:
3883 case REQ_DIFF_CONTEXT_DOWN:
3884 report("Changing the diff context is not yet supported for the %s view", view->name);
3885 break;
3887 case REQ_SEARCH:
3888 case REQ_SEARCH_BACK:
3889 search_view(view, request);
3890 break;
3892 case REQ_FIND_NEXT:
3893 case REQ_FIND_PREV:
3894 find_next(view, request);
3895 break;
3897 case REQ_STOP_LOADING:
3898 foreach_view(view, i) {
3899 if (view->pipe)
3900 report("Stopped loading the %s view", view->name),
3901 end_update(view, TRUE);
3903 break;
3905 case REQ_SHOW_VERSION:
3906 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3907 return TRUE;
3909 case REQ_SCREEN_REDRAW:
3910 redraw_display(TRUE);
3911 break;
3913 case REQ_EDIT:
3914 report("Nothing to edit");
3915 break;
3917 case REQ_ENTER:
3918 report("Nothing to enter");
3919 break;
3921 case REQ_VIEW_CLOSE:
3922 /* XXX: Mark closed views by letting view->prev point to the
3923 * view itself. Parents to closed view should never be
3924 * followed. */
3925 if (view->prev && view->prev != view) {
3926 maximize_view(view->prev, TRUE);
3927 view->prev = view;
3928 break;
3930 /* Fall-through */
3931 case REQ_QUIT:
3932 return FALSE;
3934 default:
3935 report("Unknown key, press %s for help",
3936 get_view_key(view, REQ_VIEW_HELP));
3937 return TRUE;
3940 return TRUE;
3945 * View backend utilities
3948 enum sort_field {
3949 ORDERBY_NAME,
3950 ORDERBY_DATE,
3951 ORDERBY_AUTHOR,
3954 struct sort_state {
3955 const enum sort_field *fields;
3956 size_t size, current;
3957 bool reverse;
3960 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3961 #define get_sort_field(state) ((state).fields[(state).current])
3962 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3964 static void
3965 sort_view(struct view *view, enum request request, struct sort_state *state,
3966 int (*compare)(const void *, const void *))
3968 switch (request) {
3969 case REQ_TOGGLE_SORT_FIELD:
3970 state->current = (state->current + 1) % state->size;
3971 break;
3973 case REQ_TOGGLE_SORT_ORDER:
3974 state->reverse = !state->reverse;
3975 break;
3976 default:
3977 die("Not a sort request");
3980 qsort(view->line, view->lines, sizeof(*view->line), compare);
3981 redraw_view(view);
3984 static bool
3985 update_diff_context(enum request request)
3987 int diff_context = opt_diff_context;
3989 switch (request) {
3990 case REQ_DIFF_CONTEXT_UP:
3991 opt_diff_context += 1;
3992 update_diff_context_arg(opt_diff_context);
3993 break;
3995 case REQ_DIFF_CONTEXT_DOWN:
3996 if (opt_diff_context == 0) {
3997 report("Diff context cannot be less than zero");
3998 break;
4000 opt_diff_context -= 1;
4001 update_diff_context_arg(opt_diff_context);
4002 break;
4004 default:
4005 die("Not a diff context request");
4008 return diff_context != opt_diff_context;
4011 DEFINE_ALLOCATOR(realloc_paths, const char *, 256)
4013 /* Small cache to reduce memory consumption. It uses binary search to
4014 * lookup or find place to position new entries. No entries are ever
4015 * freed. */
4016 static const char *
4017 get_path(const char *path)
4019 static const char **paths;
4020 static size_t paths_size;
4021 int from = 0, to = paths_size - 1;
4022 char *entry;
4024 while (from <= to) {
4025 size_t pos = (to + from) / 2;
4026 int cmp = strcmp(path, paths[pos]);
4028 if (!cmp)
4029 return paths[pos];
4031 if (cmp < 0)
4032 to = pos - 1;
4033 else
4034 from = pos + 1;
4037 if (!realloc_paths(&paths, paths_size, 1))
4038 return NULL;
4039 entry = strdup(path);
4040 if (!entry)
4041 return NULL;
4043 memmove(paths + from + 1, paths + from, (paths_size - from) * sizeof(*paths));
4044 paths[from] = entry;
4045 paths_size++;
4047 return entry;
4050 DEFINE_ALLOCATOR(realloc_authors, struct ident *, 256)
4052 /* Small author cache to reduce memory consumption. It uses binary
4053 * search to lookup or find place to position new entries. No entries
4054 * are ever freed. */
4055 static struct ident *
4056 get_author(const char *name, const char *email)
4058 static struct ident **authors;
4059 static size_t authors_size;
4060 int from = 0, to = authors_size - 1;
4061 struct ident *ident;
4063 while (from <= to) {
4064 size_t pos = (to + from) / 2;
4065 int cmp = strcmp(name, authors[pos]->name);
4067 if (!cmp)
4068 return authors[pos];
4070 if (cmp < 0)
4071 to = pos - 1;
4072 else
4073 from = pos + 1;
4076 if (!realloc_authors(&authors, authors_size, 1))
4077 return NULL;
4078 ident = calloc(1, sizeof(*ident));
4079 if (!ident)
4080 return NULL;
4081 ident->name = strdup(name);
4082 ident->email = strdup(email);
4083 if (!ident->name || !ident->email) {
4084 free((void *) ident->name);
4085 free(ident);
4086 return NULL;
4089 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
4090 authors[from] = ident;
4091 authors_size++;
4093 return ident;
4096 static void
4097 parse_timesec(struct time *time, const char *sec)
4099 time->sec = (time_t) atol(sec);
4102 static void
4103 parse_timezone(struct time *time, const char *zone)
4105 long tz;
4107 tz = ('0' - zone[1]) * 60 * 60 * 10;
4108 tz += ('0' - zone[2]) * 60 * 60;
4109 tz += ('0' - zone[3]) * 60 * 10;
4110 tz += ('0' - zone[4]) * 60;
4112 if (zone[0] == '-')
4113 tz = -tz;
4115 time->tz = tz;
4116 time->sec -= tz;
4119 /* Parse author lines where the name may be empty:
4120 * author <email@address.tld> 1138474660 +0100
4122 static void
4123 parse_author_line(char *ident, const struct ident **author, struct time *time)
4125 char *nameend = strchr(ident, '<');
4126 char *emailend = strchr(ident, '>');
4127 const char *name, *email = "";
4129 if (nameend && emailend)
4130 *nameend = *emailend = 0;
4131 name = chomp_string(ident);
4132 if (nameend)
4133 email = chomp_string(nameend + 1);
4134 if (!*name)
4135 name = *email ? email : unknown_ident.name;
4136 if (!*email)
4137 email = *name ? name : unknown_ident.email;
4139 *author = get_author(name, email);
4141 /* Parse epoch and timezone */
4142 if (time && emailend && emailend[1] == ' ') {
4143 char *secs = emailend + 2;
4144 char *zone = strchr(secs, ' ');
4146 parse_timesec(time, secs);
4148 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
4149 parse_timezone(time, zone + 1);
4153 static struct line *
4154 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
4156 for (; view_has_line(view, line); line += direction)
4157 if (line->type == type)
4158 return line;
4160 return NULL;
4163 #define find_prev_line_by_type(view, line, type) \
4164 find_line_by_type(view, line, type, -1)
4166 #define find_next_line_by_type(view, line, type) \
4167 find_line_by_type(view, line, type, 1)
4170 * View history
4173 struct view_state {
4174 struct view_state *prev; /* Entry below this in the stack */
4175 struct position position; /* View position to restore */
4176 void *data; /* View specific state */
4179 struct view_history {
4180 size_t state_alloc;
4181 struct view_state *stack;
4182 struct position position;
4185 static bool
4186 view_history_is_empty(struct view_history *history)
4188 return !history->stack;
4191 static struct view_state *
4192 push_view_history_state(struct view_history *history, struct position *position, void *data)
4194 struct view_state *state = history->stack;
4196 if (state && data && history->state_alloc &&
4197 !memcmp(state->data, data, history->state_alloc))
4198 return NULL;
4200 state = calloc(1, sizeof(*state) + history->state_alloc);
4201 if (!state)
4202 return NULL;
4204 state->prev = history->stack;
4205 history->stack = state;
4206 clear_position(&history->position);
4207 state->position = *position;
4208 state->data = &state[1];
4209 if (data && history->state_alloc)
4210 memcpy(state->data, data, history->state_alloc);
4211 return state;
4214 static bool
4215 pop_view_history_state(struct view_history *history, struct position *position, void *data)
4217 struct view_state *state = history->stack;
4219 if (view_history_is_empty(history))
4220 return FALSE;
4222 history->position = state->position;
4223 history->stack = state->prev;
4225 if (data && history->state_alloc)
4226 memcpy(data, state->data, history->state_alloc);
4227 if (position)
4228 *position = state->position;
4230 free(state);
4231 return TRUE;
4234 static void
4235 reset_view_history(struct view_history *history)
4237 while (pop_view_history_state(history, NULL, NULL))
4242 * Blame
4245 struct blame_commit {
4246 char id[SIZEOF_REV]; /* SHA1 ID. */
4247 char title[128]; /* First line of the commit message. */
4248 const struct ident *author; /* Author of the commit. */
4249 struct time time; /* Date from the author ident. */
4250 const char *filename; /* Name of file. */
4251 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
4252 const char *parent_filename; /* Parent/previous name of file. */
4255 struct blame_header {
4256 char id[SIZEOF_REV]; /* SHA1 ID. */
4257 size_t orig_lineno;
4258 size_t lineno;
4259 size_t group;
4262 static bool
4263 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4265 const char *pos = *posref;
4267 *posref = NULL;
4268 pos = strchr(pos + 1, ' ');
4269 if (!pos || !isdigit(pos[1]))
4270 return FALSE;
4271 *number = atoi(pos + 1);
4272 if (*number < min || *number > max)
4273 return FALSE;
4275 *posref = pos;
4276 return TRUE;
4279 static bool
4280 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
4282 const char *pos = text + SIZEOF_REV - 2;
4284 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4285 return FALSE;
4287 string_ncopy(header->id, text, SIZEOF_REV);
4289 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
4290 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
4291 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
4292 return FALSE;
4294 return TRUE;
4297 static bool
4298 match_blame_header(const char *name, char **line)
4300 size_t namelen = strlen(name);
4301 bool matched = !strncmp(name, *line, namelen);
4303 if (matched)
4304 *line += namelen;
4306 return matched;
4309 static bool
4310 parse_blame_info(struct blame_commit *commit, char *line)
4312 if (match_blame_header("author ", &line)) {
4313 parse_author_line(line, &commit->author, NULL);
4315 } else if (match_blame_header("author-time ", &line)) {
4316 parse_timesec(&commit->time, line);
4318 } else if (match_blame_header("author-tz ", &line)) {
4319 parse_timezone(&commit->time, line);
4321 } else if (match_blame_header("summary ", &line)) {
4322 string_ncopy(commit->title, line, strlen(line));
4324 } else if (match_blame_header("previous ", &line)) {
4325 if (strlen(line) <= SIZEOF_REV)
4326 return FALSE;
4327 string_copy_rev(commit->parent_id, line);
4328 line += SIZEOF_REV;
4329 commit->parent_filename = get_path(line);
4330 if (!commit->parent_filename)
4331 return TRUE;
4333 } else if (match_blame_header("filename ", &line)) {
4334 commit->filename = get_path(line);
4335 return TRUE;
4338 return FALSE;
4342 * Pager backend
4345 static bool
4346 pager_draw(struct view *view, struct line *line, unsigned int lineno)
4348 if (draw_lineno(view, lineno))
4349 return TRUE;
4351 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4352 return TRUE;
4354 draw_text(view, line->type, line->data);
4355 return TRUE;
4358 static bool
4359 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
4361 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
4362 char ref[SIZEOF_STR];
4364 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
4365 return TRUE;
4367 /* This is the only fatal call, since it can "corrupt" the buffer. */
4368 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
4369 return FALSE;
4371 return TRUE;
4374 static void
4375 add_pager_refs(struct view *view, const char *commit_id)
4377 char buf[SIZEOF_STR];
4378 struct ref_list *list;
4379 size_t bufpos = 0, i;
4380 const char *sep = "Refs: ";
4381 bool is_tag = FALSE;
4383 list = get_ref_list(commit_id);
4384 if (!list) {
4385 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
4386 goto try_add_describe_ref;
4387 return;
4390 for (i = 0; i < list->size; i++) {
4391 struct ref *ref = list->refs[i];
4392 const char *fmt = ref->tag ? "%s[%s]" :
4393 ref->remote ? "%s<%s>" : "%s%s";
4395 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
4396 return;
4397 sep = ", ";
4398 if (ref->tag)
4399 is_tag = TRUE;
4402 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
4403 try_add_describe_ref:
4404 /* Add <tag>-g<commit_id> "fake" reference. */
4405 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
4406 return;
4409 if (bufpos == 0)
4410 return;
4412 add_line_text(view, buf, LINE_PP_REFS);
4415 static struct line *
4416 pager_wrap_line(struct view *view, const char *data, enum line_type type)
4418 size_t first_line = 0;
4419 bool has_first_line = FALSE;
4420 size_t datalen = strlen(data);
4421 size_t lineno = 0;
4423 while (datalen > 0 || !has_first_line) {
4424 bool wrapped = !!first_line;
4425 size_t linelen = string_expanded_length(data, datalen, opt_tab_size, view->width - !!wrapped);
4426 struct line *line;
4427 char *text;
4429 line = add_line(view, NULL, type, linelen + 1, wrapped);
4430 if (!line)
4431 break;
4432 if (!has_first_line) {
4433 first_line = view->lines - 1;
4434 has_first_line = TRUE;
4437 if (!wrapped)
4438 lineno = line->lineno;
4440 line->wrapped = wrapped;
4441 line->lineno = lineno;
4442 text = line->data;
4443 if (linelen)
4444 strncpy(text, data, linelen);
4445 text[linelen] = 0;
4447 datalen -= linelen;
4448 data += linelen;
4451 return has_first_line ? &view->line[first_line] : NULL;
4454 static bool
4455 pager_common_read(struct view *view, const char *data, enum line_type type)
4457 struct line *line;
4459 if (!data)
4460 return TRUE;
4462 if (opt_wrap_lines) {
4463 line = pager_wrap_line(view, data, type);
4464 } else {
4465 line = add_line_text(view, data, type);
4468 if (!line)
4469 return FALSE;
4471 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
4472 add_pager_refs(view, data + STRING_SIZE("commit "));
4474 return TRUE;
4477 static bool
4478 pager_read(struct view *view, char *data)
4480 if (!data)
4481 return TRUE;
4483 return pager_common_read(view, data, get_line_type(data));
4486 static enum request
4487 pager_request(struct view *view, enum request request, struct line *line)
4489 int split = 0;
4491 if (request != REQ_ENTER)
4492 return request;
4494 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
4495 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4496 split = 1;
4499 /* Always scroll the view even if it was split. That way
4500 * you can use Enter to scroll through the log view and
4501 * split open each commit diff. */
4502 scroll_view(view, REQ_SCROLL_LINE_DOWN);
4504 /* FIXME: A minor workaround. Scrolling the view will call report_clear()
4505 * but if we are scrolling a non-current view this won't properly
4506 * update the view title. */
4507 if (split)
4508 update_view_title(view);
4510 return REQ_NONE;
4513 static bool
4514 pager_grep(struct view *view, struct line *line)
4516 const char *text[] = { line->data, NULL };
4518 return grep_text(view, text);
4521 static void
4522 pager_select(struct view *view, struct line *line)
4524 if (line->type == LINE_COMMIT) {
4525 string_copy_rev_from_commit_line(ref_commit, line->data);
4526 if (!view_has_flags(view, VIEW_NO_REF))
4527 string_copy_rev(view->ref, ref_commit);
4531 struct log_state {
4532 /* Used for tracking when we need to recalculate the previous
4533 * commit, for example when the user scrolls up or uses the page
4534 * up/down in the log view. */
4535 int last_lineno;
4536 enum line_type last_type;
4539 static void
4540 log_select(struct view *view, struct line *line)
4542 struct log_state *state = view->private;
4543 int last_lineno = state->last_lineno;
4545 if (!last_lineno || abs(last_lineno - line->lineno) > 1
4546 || (state->last_type == LINE_COMMIT && last_lineno > line->lineno)) {
4547 const struct line *commit_line = find_prev_line_by_type(view, line, LINE_COMMIT);
4549 if (commit_line)
4550 string_copy_rev_from_commit_line(view->ref, commit_line->data);
4553 if (line->type == LINE_COMMIT && !view_has_flags(view, VIEW_NO_REF)) {
4554 string_copy_rev_from_commit_line(view->ref, (char *)line->data);
4556 string_copy_rev(ref_commit, view->ref);
4557 state->last_lineno = line->lineno;
4558 state->last_type = line->type;
4561 static bool
4562 pager_open(struct view *view, enum open_flags flags)
4564 if (!open_from_stdin(flags) && !view->lines) {
4565 report("No pager content, press %s to run command from prompt",
4566 get_view_key(view, REQ_PROMPT));
4567 return FALSE;
4570 return begin_update(view, NULL, NULL, flags);
4573 static struct view_ops pager_ops = {
4574 "line",
4575 { "pager" },
4576 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
4578 pager_open,
4579 pager_read,
4580 pager_draw,
4581 pager_request,
4582 pager_grep,
4583 pager_select,
4586 static bool
4587 log_open(struct view *view, enum open_flags flags)
4589 static const char *log_argv[] = {
4590 "git", "log", encoding_arg, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
4593 return begin_update(view, NULL, log_argv, flags);
4596 static enum request
4597 log_request(struct view *view, enum request request, struct line *line)
4599 switch (request) {
4600 case REQ_REFRESH:
4601 load_refs(TRUE);
4602 refresh_view(view);
4603 return REQ_NONE;
4605 case REQ_ENTER:
4606 if (!display[1] || strcmp(display[1]->vid, view->ref))
4607 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4608 return REQ_NONE;
4610 default:
4611 return request;
4615 static struct view_ops log_ops = {
4616 "line",
4617 { "log" },
4618 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF | VIEW_SEND_CHILD_ENTER | VIEW_LOG_LIKE,
4619 sizeof(struct log_state),
4620 log_open,
4621 pager_read,
4622 pager_draw,
4623 log_request,
4624 pager_grep,
4625 log_select,
4628 struct diff_state {
4629 bool after_commit_title;
4630 bool after_diff;
4631 bool reading_diff_stat;
4632 bool combined_diff;
4635 #define DIFF_LINE_COMMIT_TITLE 1
4637 static bool
4638 diff_open(struct view *view, enum open_flags flags)
4640 static const char *diff_argv[] = {
4641 "git", "show", encoding_arg, "--pretty=fuller", "--root",
4642 "--patch-with-stat",
4643 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
4644 "%(diffargs)", "--no-color", "%(commit)", "--", "%(fileargs)", NULL
4647 return begin_update(view, NULL, diff_argv, flags);
4650 static bool
4651 diff_common_read(struct view *view, const char *data, struct diff_state *state)
4653 enum line_type type = get_line_type(data);
4655 if (!view->lines && type != LINE_COMMIT)
4656 state->reading_diff_stat = TRUE;
4658 if (state->combined_diff && !state->after_diff && data[0] == ' ' && data[1] != ' ')
4659 state->reading_diff_stat = TRUE;
4661 if (state->reading_diff_stat) {
4662 size_t len = strlen(data);
4663 char *pipe = strchr(data, '|');
4664 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
4665 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
4666 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
4668 if (pipe && (has_histogram || has_bin_diff || has_rename)) {
4669 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
4670 } else {
4671 state->reading_diff_stat = FALSE;
4674 } else if (!strcmp(data, "---")) {
4675 state->reading_diff_stat = TRUE;
4678 if (!state->after_commit_title && !prefixcmp(data, " ")) {
4679 struct line *line = add_line_text(view, data, LINE_DEFAULT);
4681 if (line)
4682 line->user_flags |= DIFF_LINE_COMMIT_TITLE;
4683 state->after_commit_title = TRUE;
4684 return line != NULL;
4687 if (type == LINE_DIFF_HEADER) {
4688 const int len = line_info[LINE_DIFF_HEADER].linelen;
4690 state->after_diff = TRUE;
4691 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4692 !strncmp(data + len, "cc ", strlen("cc ")))
4693 state->combined_diff = TRUE;
4695 } else if (type == LINE_PP_MERGE) {
4696 state->combined_diff = TRUE;
4699 /* ADD2 and DEL2 are only valid in combined diff hunks */
4700 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4701 type = LINE_DEFAULT;
4703 return pager_common_read(view, data, type);
4706 static bool
4707 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
4709 struct line *marker = find_next_line_by_type(view, line, type);
4711 return marker &&
4712 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
4715 static enum request
4716 diff_common_enter(struct view *view, enum request request, struct line *line)
4718 if (line->type == LINE_DIFF_STAT) {
4719 int file_number = 0;
4721 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4722 file_number++;
4723 line--;
4726 for (line = view->line; view_has_line(view, line); line++) {
4727 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4728 if (!line)
4729 break;
4731 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4732 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4733 if (file_number == 1) {
4734 break;
4736 file_number--;
4740 if (!line) {
4741 report("Failed to find file diff");
4742 return REQ_NONE;
4745 select_view_line(view, line - view->line);
4746 report_clear();
4747 return REQ_NONE;
4749 } else {
4750 return pager_request(view, request, line);
4754 static bool
4755 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4757 char *sep = strchr(*text, c);
4759 if (sep != NULL) {
4760 *sep = 0;
4761 draw_text(view, *type, *text);
4762 *sep = c;
4763 *text = sep;
4764 *type = next_type;
4767 return sep != NULL;
4770 static bool
4771 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4773 char *text = line->data;
4774 enum line_type type = line->type;
4776 if (draw_lineno(view, lineno))
4777 return TRUE;
4779 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4780 return TRUE;
4782 if (type == LINE_DIFF_STAT) {
4783 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4784 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4785 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4786 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4787 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4788 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4789 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4791 } else {
4792 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4793 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4797 if (line->user_flags & DIFF_LINE_COMMIT_TITLE)
4798 draw_commit_title(view, text, 4);
4799 else
4800 draw_text(view, type, text);
4801 return TRUE;
4804 static bool
4805 diff_read(struct view *view, char *data)
4807 struct diff_state *state = view->private;
4809 if (!data) {
4810 /* Fall back to retry if no diff will be shown. */
4811 if (view->lines == 0 && opt_file_argv) {
4812 int pos = argv_size(view->argv)
4813 - argv_size(opt_file_argv) - 1;
4815 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4816 for (; view->argv[pos]; pos++) {
4817 free((void *) view->argv[pos]);
4818 view->argv[pos] = NULL;
4821 if (view->pipe)
4822 io_done(view->pipe);
4823 if (io_run(&view->io, IO_RD, view->dir, opt_env, view->argv))
4824 return FALSE;
4827 return TRUE;
4830 return diff_common_read(view, data, state);
4833 static bool
4834 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4835 struct blame_header *header, struct blame_commit *commit)
4837 char line_arg[SIZEOF_STR];
4838 const char *blame_argv[] = {
4839 "git", "blame", encoding_arg, "-p", line_arg, ref, "--", file, NULL
4841 struct io io;
4842 bool ok = FALSE;
4843 char *buf;
4845 if (!string_format(line_arg, "-L%ld,+1", lineno))
4846 return FALSE;
4848 if (!io_run(&io, IO_RD, opt_cdup, opt_env, blame_argv))
4849 return FALSE;
4851 while ((buf = io_get(&io, '\n', TRUE))) {
4852 if (header) {
4853 if (!parse_blame_header(header, buf, 9999999))
4854 break;
4855 header = NULL;
4857 } else if (parse_blame_info(commit, buf)) {
4858 ok = commit->filename != NULL;
4859 break;
4863 if (io_error(&io))
4864 ok = FALSE;
4866 io_done(&io);
4867 return ok;
4870 struct chunk_header_position {
4871 unsigned long position;
4872 unsigned long lines;
4875 struct chunk_header {
4876 struct chunk_header_position old;
4877 struct chunk_header_position new;
4880 static bool
4881 parse_ulong(const char **pos_ptr, unsigned long *value, const char *skip)
4883 const char *start = *pos_ptr;
4884 char *end;
4886 if (!isdigit(*start))
4887 return 0;
4889 *value = strtoul(start, &end, 10);
4890 if (end == start)
4891 return FALSE;
4893 start = end;
4894 while (skip && *start && strchr(skip, *start))
4895 start++;
4896 *pos_ptr = start;
4897 return TRUE;
4900 static bool
4901 parse_chunk_header(struct chunk_header *header, const char *line)
4903 memset(header, 0, sizeof(*header));
4905 if (prefixcmp(line, "@@ -"))
4906 return FALSE;
4908 line += STRING_SIZE("@@ -");
4910 return parse_ulong(&line, &header->old.position, ",") &&
4911 parse_ulong(&line, &header->old.lines, " +") &&
4912 parse_ulong(&line, &header->new.position, ",") &&
4913 parse_ulong(&line, &header->new.lines, NULL);
4916 static unsigned int
4917 diff_get_lineno(struct view *view, struct line *line)
4919 const struct line *header, *chunk;
4920 unsigned int lineno;
4921 struct chunk_header chunk_header;
4923 /* Verify that we are after a diff header and one of its chunks */
4924 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4925 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4926 if (!header || !chunk || chunk < header)
4927 return 0;
4930 * In a chunk header, the number after the '+' sign is the number of its
4931 * following line, in the new version of the file. We increment this
4932 * number for each non-deletion line, until the given line position.
4934 if (!parse_chunk_header(&chunk_header, chunk->data))
4935 return 0;
4937 lineno = chunk_header.new.position;
4938 chunk++;
4939 while (chunk++ < line)
4940 if (chunk->type != LINE_DIFF_DEL)
4941 lineno++;
4943 return lineno;
4946 static bool
4947 parse_chunk_lineno(unsigned long *lineno, const char *chunk, int marker)
4949 struct chunk_header chunk_header;
4951 *lineno = 0;
4953 if (!parse_chunk_header(&chunk_header, chunk))
4954 return FALSE;
4956 *lineno = marker == '-' ? chunk_header.old.position : chunk_header.new.position;
4957 return TRUE;
4960 static enum request
4961 diff_trace_origin(struct view *view, struct line *line)
4963 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4964 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4965 const char *chunk_data;
4966 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4967 unsigned long lineno = 0;
4968 const char *file = NULL;
4969 char ref[SIZEOF_REF];
4970 struct blame_header header;
4971 struct blame_commit commit;
4973 if (!diff || !chunk || chunk == line) {
4974 report("The line to trace must be inside a diff chunk");
4975 return REQ_NONE;
4978 for (; diff < line && !file; diff++) {
4979 const char *data = diff->data;
4981 if (!prefixcmp(data, "--- a/")) {
4982 file = data + STRING_SIZE("--- a/");
4983 break;
4987 if (diff == line || !file) {
4988 report("Failed to read the file name");
4989 return REQ_NONE;
4992 chunk_data = chunk->data;
4994 if (!parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4995 report("Failed to read the line number");
4996 return REQ_NONE;
4999 if (lineno == 0) {
5000 report("This is the origin of the line");
5001 return REQ_NONE;
5004 for (chunk += 1; chunk < line; chunk++) {
5005 if (chunk->type == LINE_DIFF_ADD) {
5006 lineno += chunk_marker == '+';
5007 } else if (chunk->type == LINE_DIFF_DEL) {
5008 lineno += chunk_marker == '-';
5009 } else {
5010 lineno++;
5014 if (chunk_marker == '+')
5015 string_copy(ref, view->vid);
5016 else
5017 string_format(ref, "%s^", view->vid);
5019 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
5020 report("Failed to read blame data");
5021 return REQ_NONE;
5024 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
5025 string_copy(opt_ref, header.id);
5026 opt_goto_line = header.orig_lineno - 1;
5028 return REQ_VIEW_BLAME;
5031 static const char *
5032 diff_get_pathname(struct view *view, struct line *line)
5034 const struct line *header;
5035 const char *dst = NULL;
5036 const char *prefixes[] = { " b/", "cc ", "combined " };
5037 int i;
5039 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
5040 if (!header)
5041 return NULL;
5043 for (i = 0; i < ARRAY_SIZE(prefixes) && !dst; i++)
5044 dst = strstr(header->data, prefixes[i]);
5046 return dst ? dst + strlen(prefixes[--i]) : NULL;
5049 static enum request
5050 diff_common_edit(struct view *view, enum request request, struct line *line)
5052 const char *file = diff_get_pathname(view, line);
5053 char path[SIZEOF_STR];
5054 bool has_path = file && string_format(path, "%s%s", opt_cdup, file);
5056 if (has_path && access(path, R_OK)) {
5057 report("Failed to open file: %s", file);
5058 return REQ_NONE;
5061 open_editor(file, diff_get_lineno(view, line));
5062 return REQ_NONE;
5065 static enum request
5066 diff_request(struct view *view, enum request request, struct line *line)
5068 switch (request) {
5069 case REQ_VIEW_BLAME:
5070 return diff_trace_origin(view, line);
5072 case REQ_DIFF_CONTEXT_UP:
5073 case REQ_DIFF_CONTEXT_DOWN:
5074 if (!update_diff_context(request))
5075 return REQ_NONE;
5076 reload_view(view);
5077 return REQ_NONE;
5080 case REQ_EDIT:
5081 return diff_common_edit(view, request, line);
5083 case REQ_ENTER:
5084 return diff_common_enter(view, request, line);
5086 case REQ_REFRESH:
5087 reload_view(view);
5088 return REQ_NONE;
5090 default:
5091 return pager_request(view, request, line);
5095 static void
5096 diff_select(struct view *view, struct line *line)
5098 if (line->type == LINE_DIFF_STAT) {
5099 string_format(view->ref, "Press '%s' to jump to file diff",
5100 get_view_key(view, REQ_ENTER));
5101 } else {
5102 const char *file = diff_get_pathname(view, line);
5104 if (file) {
5105 string_format(view->ref, "Changes to '%s'", file);
5106 string_format(opt_file, "%s", file);
5107 ref_blob[0] = 0;
5108 } else {
5109 string_ncopy(view->ref, view->id, strlen(view->id));
5110 pager_select(view, line);
5115 static struct view_ops diff_ops = {
5116 "line",
5117 { "diff" },
5118 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS | VIEW_FILE_FILTER,
5119 sizeof(struct diff_state),
5120 diff_open,
5121 diff_read,
5122 diff_common_draw,
5123 diff_request,
5124 pager_grep,
5125 diff_select,
5129 * Help backend
5132 static bool
5133 help_draw(struct view *view, struct line *line, unsigned int lineno)
5135 if (line->type == LINE_HELP_KEYMAP) {
5136 struct keymap *keymap = line->data;
5138 draw_formatted(view, line->type, "[%c] %s bindings",
5139 keymap->hidden ? '+' : '-', keymap->name);
5140 return TRUE;
5141 } else {
5142 return pager_draw(view, line, lineno);
5146 static bool
5147 help_open_keymap_title(struct view *view, struct keymap *keymap)
5149 add_line(view, keymap, LINE_HELP_KEYMAP, 0, FALSE);
5150 return keymap->hidden;
5153 static void
5154 help_open_keymap(struct view *view, struct keymap *keymap)
5156 const char *group = NULL;
5157 char buf[SIZEOF_STR];
5158 bool add_title = TRUE;
5159 int i;
5161 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
5162 const char *key = NULL;
5164 if (req_info[i].request == REQ_NONE)
5165 continue;
5167 if (!req_info[i].request) {
5168 group = req_info[i].help;
5169 continue;
5172 key = get_keys(keymap, req_info[i].request, TRUE);
5173 if (!key || !*key)
5174 continue;
5176 if (add_title && help_open_keymap_title(view, keymap))
5177 return;
5178 add_title = FALSE;
5180 if (group) {
5181 add_line_text(view, group, LINE_HELP_GROUP);
5182 group = NULL;
5185 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
5186 enum_name(req_info[i]), req_info[i].help);
5189 group = "External commands:";
5191 for (i = 0; i < run_requests; i++) {
5192 struct run_request *req = get_run_request(REQ_NONE + i + 1);
5193 const char *key;
5195 if (!req || req->keymap != keymap)
5196 continue;
5198 key = get_key_name(req->key);
5199 if (!*key)
5200 key = "(no key defined)";
5202 if (add_title && help_open_keymap_title(view, keymap))
5203 return;
5204 add_title = FALSE;
5206 if (group) {
5207 add_line_text(view, group, LINE_HELP_GROUP);
5208 group = NULL;
5211 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
5212 return;
5214 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
5218 static bool
5219 help_open(struct view *view, enum open_flags flags)
5221 struct keymap *keymap;
5223 reset_view(view);
5224 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
5225 add_line_text(view, "", LINE_DEFAULT);
5227 for (keymap = keymaps; keymap; keymap = keymap->next)
5228 help_open_keymap(view, keymap);
5230 return TRUE;
5233 static enum request
5234 help_request(struct view *view, enum request request, struct line *line)
5236 switch (request) {
5237 case REQ_ENTER:
5238 if (line->type == LINE_HELP_KEYMAP) {
5239 struct keymap *keymap = line->data;
5241 keymap->hidden = !keymap->hidden;
5242 refresh_view(view);
5245 return REQ_NONE;
5246 default:
5247 return pager_request(view, request, line);
5251 static void
5252 help_done(struct view *view)
5254 int i;
5256 for (i = 0; i < view->lines; i++)
5257 if (view->line[i].type == LINE_HELP_KEYMAP)
5258 view->line[i].data = NULL;
5261 static struct view_ops help_ops = {
5262 "line",
5263 { "help" },
5264 VIEW_NO_GIT_DIR,
5266 help_open,
5267 NULL,
5268 help_draw,
5269 help_request,
5270 pager_grep,
5271 pager_select,
5272 help_done,
5277 * Tree backend
5280 /* The top of the path stack. */
5281 static struct view_history tree_view_history = { sizeof(char *) };
5283 static void
5284 pop_tree_stack_entry(struct position *position)
5286 char *path_position = NULL;
5288 pop_view_history_state(&tree_view_history, position, &path_position);
5289 path_position[0] = 0;
5292 static void
5293 push_tree_stack_entry(const char *name, struct position *position)
5295 size_t pathlen = strlen(opt_path);
5296 char *path_position = opt_path + pathlen;
5297 struct view_state *state = push_view_history_state(&tree_view_history, position, &path_position);
5299 if (!state)
5300 return;
5302 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
5303 pop_tree_stack_entry(NULL);
5304 return;
5307 clear_position(position);
5310 /* Parse output from git-ls-tree(1):
5312 * 100644 blob 95925677ca47beb0b8cce7c0e0011bcc3f61470f 213045 tig.c
5315 #define SIZEOF_TREE_ATTR \
5316 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
5318 #define SIZEOF_TREE_MODE \
5319 STRING_SIZE("100644 ")
5321 #define TREE_ID_OFFSET \
5322 STRING_SIZE("100644 blob ")
5324 #define tree_path_is_parent(path) (!strcmp("..", (path)))
5326 struct tree_entry {
5327 char id[SIZEOF_REV];
5328 char commit[SIZEOF_REV];
5329 mode_t mode;
5330 struct time time; /* Date from the author ident. */
5331 const struct ident *author; /* Author of the commit. */
5332 unsigned long size;
5333 char name[1];
5336 struct tree_state {
5337 char commit[SIZEOF_REV];
5338 const struct ident *author;
5339 struct time author_time;
5340 int size_width;
5341 bool read_date;
5344 static const char *
5345 tree_path(const struct line *line)
5347 return ((struct tree_entry *) line->data)->name;
5350 static int
5351 tree_compare_entry(const struct line *line1, const struct line *line2)
5353 if (line1->type != line2->type)
5354 return line1->type == LINE_TREE_DIR ? -1 : 1;
5355 return strcmp(tree_path(line1), tree_path(line2));
5358 static const enum sort_field tree_sort_fields[] = {
5359 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5361 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
5363 static int
5364 tree_compare(const void *l1, const void *l2)
5366 const struct line *line1 = (const struct line *) l1;
5367 const struct line *line2 = (const struct line *) l2;
5368 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
5369 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
5371 if (line1->type == LINE_TREE_HEAD)
5372 return -1;
5373 if (line2->type == LINE_TREE_HEAD)
5374 return 1;
5376 switch (get_sort_field(tree_sort_state)) {
5377 case ORDERBY_DATE:
5378 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
5380 case ORDERBY_AUTHOR:
5381 return sort_order(tree_sort_state, ident_compare(entry1->author, entry2->author));
5383 case ORDERBY_NAME:
5384 default:
5385 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
5390 static struct line *
5391 tree_entry(struct view *view, enum line_type type, const char *path,
5392 const char *mode, const char *id, unsigned long size)
5394 bool custom = type == LINE_TREE_HEAD || tree_path_is_parent(path);
5395 struct tree_entry *entry;
5396 struct line *line = add_line_alloc(view, &entry, type, strlen(path), custom);
5398 if (!line)
5399 return NULL;
5401 strncpy(entry->name, path, strlen(path));
5402 if (mode)
5403 entry->mode = strtoul(mode, NULL, 8);
5404 if (id)
5405 string_copy_rev(entry->id, id);
5406 entry->size = size;
5408 return line;
5411 static bool
5412 tree_read_date(struct view *view, char *text, struct tree_state *state)
5414 if (!text && state->read_date) {
5415 state->read_date = FALSE;
5416 return TRUE;
5418 } else if (!text) {
5419 /* Find next entry to process */
5420 const char *log_file[] = {
5421 "git", "log", encoding_arg, "--no-color", "--pretty=raw",
5422 "--cc", "--raw", view->id, "--", "%(directory)", NULL
5425 if (!view->lines) {
5426 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0);
5427 tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0);
5428 report("Tree is empty");
5429 return TRUE;
5432 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
5433 report("Failed to load tree data");
5434 return TRUE;
5437 state->read_date = TRUE;
5438 return FALSE;
5440 } else if (*text == 'c' && get_line_type(text) == LINE_COMMIT) {
5441 string_copy_rev_from_commit_line(state->commit, text);
5443 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
5444 parse_author_line(text + STRING_SIZE("author "),
5445 &state->author, &state->author_time);
5447 } else if (*text == ':') {
5448 char *pos;
5449 size_t annotated = 1;
5450 size_t i;
5452 pos = strchr(text, '\t');
5453 if (!pos)
5454 return TRUE;
5455 text = pos + 1;
5456 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
5457 text += strlen(opt_path);
5458 pos = strchr(text, '/');
5459 if (pos)
5460 *pos = 0;
5462 for (i = 1; i < view->lines; i++) {
5463 struct line *line = &view->line[i];
5464 struct tree_entry *entry = line->data;
5466 annotated += !!entry->author;
5467 if (entry->author || strcmp(entry->name, text))
5468 continue;
5470 string_copy_rev(entry->commit, state->commit);
5471 entry->author = state->author;
5472 entry->time = state->author_time;
5473 line->dirty = 1;
5474 break;
5477 if (annotated == view->lines)
5478 io_kill(view->pipe);
5480 return TRUE;
5483 static inline size_t
5484 parse_size(const char *text, int *max_digits)
5486 size_t size = 0;
5487 int digits = 0;
5489 while (*text == ' ')
5490 text++;
5492 while (isdigit(*text)) {
5493 size = (size * 10) + (*text++ - '0');
5494 digits++;
5497 if (digits > *max_digits)
5498 *max_digits = digits;
5500 return size;
5503 static bool
5504 tree_read(struct view *view, char *text)
5506 struct tree_state *state = view->private;
5507 struct tree_entry *data;
5508 struct line *entry, *line;
5509 enum line_type type;
5510 size_t textlen = text ? strlen(text) : 0;
5511 const char *attr_offset = text + SIZEOF_TREE_ATTR;
5512 char *path;
5513 size_t size;
5515 if (state->read_date || !text)
5516 return tree_read_date(view, text, state);
5518 if (textlen <= SIZEOF_TREE_ATTR)
5519 return FALSE;
5520 if (view->lines == 0 &&
5521 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0))
5522 return FALSE;
5524 size = parse_size(attr_offset, &state->size_width);
5525 path = strchr(attr_offset, '\t');
5526 if (!path)
5527 return FALSE;
5528 path++;
5530 /* Strip the path part ... */
5531 if (*opt_path) {
5532 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
5533 size_t striplen = strlen(opt_path);
5535 if (pathlen > striplen)
5536 memmove(path, path + striplen,
5537 pathlen - striplen + 1);
5539 /* Insert "link" to parent directory. */
5540 if (view->lines == 1 &&
5541 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0))
5542 return FALSE;
5545 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
5546 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET, size);
5547 if (!entry)
5548 return FALSE;
5549 data = entry->data;
5551 /* Skip "Directory ..." and ".." line. */
5552 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
5553 if (tree_compare_entry(line, entry) <= 0)
5554 continue;
5556 memmove(line + 1, line, (entry - line) * sizeof(*entry));
5558 line->data = data;
5559 line->type = type;
5560 for (; line <= entry; line++)
5561 line->dirty = line->cleareol = 1;
5562 return TRUE;
5565 /* Move the current line to the first tree entry. */
5566 if (!check_position(&view->prev_pos) && !check_position(&view->pos))
5567 goto_view_line(view, 0, 1);
5569 return TRUE;
5572 static bool
5573 tree_draw(struct view *view, struct line *line, unsigned int lineno)
5575 struct tree_state *state = view->private;
5576 struct tree_entry *entry = line->data;
5578 if (line->type == LINE_TREE_HEAD) {
5579 if (draw_text(view, line->type, "Directory path /"))
5580 return TRUE;
5581 } else {
5582 if (draw_mode(view, entry->mode))
5583 return TRUE;
5585 if (draw_author(view, entry->author))
5586 return TRUE;
5588 if (draw_file_size(view, entry->size, state->size_width,
5589 line->type != LINE_TREE_FILE))
5590 return TRUE;
5592 if (draw_date(view, &entry->time))
5593 return TRUE;
5595 if (draw_id(view, entry->commit))
5596 return TRUE;
5599 draw_text(view, line->type, entry->name);
5600 return TRUE;
5603 static void
5604 open_blob_editor(const char *id, const char *name, unsigned int lineno)
5606 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
5607 char file[SIZEOF_STR];
5608 int fd;
5610 if (!name)
5611 name = "unknown";
5613 if (!string_format(file, "%s/tigblob.XXXXXX.%s", get_temp_dir(), name)) {
5614 report("Temporary file name is too long");
5615 return;
5618 fd = mkstemps(file, strlen(name) + 1);
5620 if (fd == -1)
5621 report("Failed to create temporary file");
5622 else if (!io_run_append(blob_argv, fd))
5623 report("Failed to save blob data to file");
5624 else
5625 open_editor(file, lineno);
5626 if (fd != -1)
5627 unlink(file);
5630 static enum request
5631 tree_request(struct view *view, enum request request, struct line *line)
5633 enum open_flags flags;
5634 struct tree_entry *entry = line->data;
5636 switch (request) {
5637 case REQ_VIEW_BLAME:
5638 if (line->type != LINE_TREE_FILE) {
5639 report("Blame only supported for files");
5640 return REQ_NONE;
5643 string_copy(opt_ref, view->vid);
5644 return request;
5646 case REQ_EDIT:
5647 if (line->type != LINE_TREE_FILE) {
5648 report("Edit only supported for files");
5649 } else if (!is_head_commit(view->vid)) {
5650 open_blob_editor(entry->id, entry->name, 0);
5651 } else {
5652 open_editor(opt_file, 0);
5654 return REQ_NONE;
5656 case REQ_TOGGLE_SORT_FIELD:
5657 case REQ_TOGGLE_SORT_ORDER:
5658 sort_view(view, request, &tree_sort_state, tree_compare);
5659 return REQ_NONE;
5661 case REQ_PARENT:
5662 case REQ_BACK:
5663 if (!*opt_path) {
5664 /* quit view if at top of tree */
5665 return REQ_VIEW_CLOSE;
5667 /* fake 'cd ..' */
5668 line = &view->line[1];
5669 break;
5671 case REQ_ENTER:
5672 break;
5674 default:
5675 return request;
5678 /* Cleanup the stack if the tree view is at a different tree. */
5679 if (!*opt_path)
5680 reset_view_history(&tree_view_history);
5682 switch (line->type) {
5683 case LINE_TREE_DIR:
5684 /* Depending on whether it is a subdirectory or parent link
5685 * mangle the path buffer. */
5686 if (line == &view->line[1] && *opt_path) {
5687 pop_tree_stack_entry(&view->pos);
5689 } else {
5690 const char *basename = tree_path(line);
5692 push_tree_stack_entry(basename, &view->pos);
5695 /* Trees and subtrees share the same ID, so they are not not
5696 * unique like blobs. */
5697 flags = OPEN_RELOAD;
5698 request = REQ_VIEW_TREE;
5699 break;
5701 case LINE_TREE_FILE:
5702 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5703 request = REQ_VIEW_BLOB;
5704 break;
5706 default:
5707 return REQ_NONE;
5710 open_view(view, request, flags);
5712 return REQ_NONE;
5715 static bool
5716 tree_grep(struct view *view, struct line *line)
5718 struct tree_entry *entry = line->data;
5719 const char *text[] = {
5720 entry->name,
5721 mkauthor(entry->author, opt_author_width, opt_author),
5722 mkdate(&entry->time, opt_date),
5723 NULL
5726 return grep_text(view, text);
5729 static void
5730 tree_select(struct view *view, struct line *line)
5732 struct tree_entry *entry = line->data;
5734 if (line->type == LINE_TREE_HEAD) {
5735 string_format(view->ref, "Files in /%s", opt_path);
5736 return;
5739 if (line->type == LINE_TREE_DIR && tree_path_is_parent(entry->name)) {
5740 string_copy(view->ref, "Open parent directory");
5741 ref_blob[0] = 0;
5742 return;
5745 if (line->type == LINE_TREE_FILE) {
5746 string_copy_rev(ref_blob, entry->id);
5747 string_format(opt_file, "%s%s", opt_path, tree_path(line));
5750 string_copy_rev(view->ref, entry->id);
5753 static bool
5754 tree_open(struct view *view, enum open_flags flags)
5756 static const char *tree_argv[] = {
5757 "git", "ls-tree", "-l", "%(commit)", "%(directory)", NULL
5760 if (string_rev_is_null(ref_commit)) {
5761 report("No tree exists for this commit");
5762 return FALSE;
5765 if (view->lines == 0 && opt_prefix[0]) {
5766 char *pos = opt_prefix;
5768 while (pos && *pos) {
5769 char *end = strchr(pos, '/');
5771 if (end)
5772 *end = 0;
5773 push_tree_stack_entry(pos, &view->pos);
5774 pos = end;
5775 if (end) {
5776 *end = '/';
5777 pos++;
5781 } else if (strcmp(view->vid, view->id)) {
5782 opt_path[0] = 0;
5785 return begin_update(view, opt_cdup, tree_argv, flags);
5788 static struct view_ops tree_ops = {
5789 "file",
5790 { "tree" },
5791 VIEW_SEND_CHILD_ENTER,
5792 sizeof(struct tree_state),
5793 tree_open,
5794 tree_read,
5795 tree_draw,
5796 tree_request,
5797 tree_grep,
5798 tree_select,
5801 static bool
5802 blob_open(struct view *view, enum open_flags flags)
5804 static const char *blob_argv[] = {
5805 "git", "cat-file", "blob", "%(blob)", NULL
5808 if (!ref_blob[0] && opt_file[0]) {
5809 const char *commit = ref_commit[0] ? ref_commit : "HEAD";
5810 char blob_spec[SIZEOF_STR];
5811 const char *rev_parse_argv[] = {
5812 "git", "rev-parse", blob_spec, NULL
5815 if (!string_format(blob_spec, "%s:%s", commit, opt_file) ||
5816 !io_run_buf(rev_parse_argv, ref_blob, sizeof(ref_blob))) {
5817 report("Failed to resolve blob from file name");
5818 return FALSE;
5822 if (!ref_blob[0]) {
5823 report("No file chosen, press %s to open tree view",
5824 get_view_key(view, REQ_VIEW_TREE));
5825 return FALSE;
5828 view->encoding = get_path_encoding(opt_file, default_encoding);
5830 return begin_update(view, NULL, blob_argv, flags);
5833 static bool
5834 blob_read(struct view *view, char *line)
5836 if (!line)
5837 return TRUE;
5838 return add_line_text(view, line, LINE_DEFAULT) != NULL;
5841 static enum request
5842 blob_request(struct view *view, enum request request, struct line *line)
5844 switch (request) {
5845 case REQ_VIEW_BLAME:
5846 if (view->parent)
5847 string_copy(opt_ref, view->parent->vid);
5848 return request;
5850 case REQ_EDIT:
5851 open_blob_editor(view->vid, NULL, (line - view->line) + 1);
5852 return REQ_NONE;
5853 default:
5854 return pager_request(view, request, line);
5858 static struct view_ops blob_ops = {
5859 "line",
5860 { "blob" },
5861 VIEW_NO_FLAGS,
5863 blob_open,
5864 blob_read,
5865 pager_draw,
5866 blob_request,
5867 pager_grep,
5868 pager_select,
5872 * Blame backend
5874 * Loading the blame view is a two phase job:
5876 * 1. File content is read either using opt_file from the
5877 * filesystem or using git-cat-file.
5878 * 2. Then blame information is incrementally added by
5879 * reading output from git-blame.
5882 struct blame_history_state {
5883 char id[SIZEOF_REV]; /* SHA1 ID. */
5884 const char *filename; /* Name of file. */
5887 static struct view_history blame_view_history = { sizeof(struct blame_history_state) };
5889 struct blame {
5890 struct blame_commit *commit;
5891 unsigned long lineno;
5892 char text[1];
5895 struct blame_state {
5896 struct blame_commit *commit;
5897 int blamed;
5898 bool done_reading;
5899 bool auto_filename_display;
5900 /* The history state for the current view is cached in the view
5901 * state so it always matches what was used to load the current blame
5902 * view. */
5903 struct blame_history_state history_state;
5906 static bool
5907 blame_detect_filename_display(struct view *view)
5909 bool show_filenames = FALSE;
5910 const char *filename = NULL;
5911 int i;
5913 if (opt_blame_argv) {
5914 for (i = 0; opt_blame_argv[i]; i++) {
5915 if (prefixcmp(opt_blame_argv[i], "-C"))
5916 continue;
5918 show_filenames = TRUE;
5922 for (i = 0; i < view->lines; i++) {
5923 struct blame *blame = view->line[i].data;
5925 if (blame->commit && blame->commit->id[0]) {
5926 if (!filename)
5927 filename = blame->commit->filename;
5928 else if (strcmp(filename, blame->commit->filename))
5929 show_filenames = TRUE;
5933 return show_filenames;
5936 static bool
5937 blame_open(struct view *view, enum open_flags flags)
5939 struct blame_state *state = view->private;
5940 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5941 char path[SIZEOF_STR];
5942 size_t i;
5944 if (!opt_file[0]) {
5945 report("No file chosen, press %s to open tree view",
5946 get_view_key(view, REQ_VIEW_TREE));
5947 return FALSE;
5950 if (!view->prev && *opt_prefix && !(flags & (OPEN_RELOAD | OPEN_REFRESH))) {
5951 string_copy(path, opt_file);
5952 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
5953 report("Failed to setup the blame view");
5954 return FALSE;
5958 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5959 const char *blame_cat_file_argv[] = {
5960 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5963 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5964 return FALSE;
5967 /* First pass: remove multiple references to the same commit. */
5968 for (i = 0; i < view->lines; i++) {
5969 struct blame *blame = view->line[i].data;
5971 if (blame->commit && blame->commit->id[0])
5972 blame->commit->id[0] = 0;
5973 else
5974 blame->commit = NULL;
5977 /* Second pass: free existing references. */
5978 for (i = 0; i < view->lines; i++) {
5979 struct blame *blame = view->line[i].data;
5981 if (blame->commit)
5982 free(blame->commit);
5985 if (!(flags & OPEN_RELOAD))
5986 reset_view_history(&blame_view_history);
5987 string_copy_rev(state->history_state.id, opt_ref);
5988 state->history_state.filename = get_path(opt_file);
5989 if (!state->history_state.filename)
5990 return FALSE;
5991 string_format(view->vid, "%s", opt_file);
5992 string_format(view->ref, "%s ...", opt_file);
5994 return TRUE;
5997 static struct blame_commit *
5998 get_blame_commit(struct view *view, const char *id)
6000 size_t i;
6002 for (i = 0; i < view->lines; i++) {
6003 struct blame *blame = view->line[i].data;
6005 if (!blame->commit)
6006 continue;
6008 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
6009 return blame->commit;
6013 struct blame_commit *commit = calloc(1, sizeof(*commit));
6015 if (commit)
6016 string_ncopy(commit->id, id, SIZEOF_REV);
6017 return commit;
6021 static struct blame_commit *
6022 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
6024 struct blame_header header;
6025 struct blame_commit *commit;
6026 struct blame *blame;
6028 if (!parse_blame_header(&header, text, view->lines))
6029 return NULL;
6031 commit = get_blame_commit(view, text);
6032 if (!commit)
6033 return NULL;
6035 state->blamed += header.group;
6036 while (header.group--) {
6037 struct line *line = &view->line[header.lineno + header.group - 1];
6039 blame = line->data;
6040 blame->commit = commit;
6041 blame->lineno = header.orig_lineno + header.group - 1;
6042 line->dirty = 1;
6045 return commit;
6048 static bool
6049 blame_read_file(struct view *view, const char *text, struct blame_state *state)
6051 if (!text) {
6052 const char *blame_argv[] = {
6053 "git", "blame", encoding_arg, "%(blameargs)", "--incremental",
6054 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
6057 if (view->lines == 0 && !view->prev)
6058 die("No blame exist for %s", view->vid);
6060 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
6061 report("Failed to load blame data");
6062 return TRUE;
6065 if (opt_goto_line > 0) {
6066 select_view_line(view, opt_goto_line);
6067 opt_goto_line = 0;
6070 state->done_reading = TRUE;
6071 return FALSE;
6073 } else {
6074 size_t textlen = strlen(text);
6075 struct blame *blame;
6077 if (!add_line_alloc(view, &blame, LINE_ID, textlen, FALSE))
6078 return FALSE;
6080 blame->commit = NULL;
6081 strncpy(blame->text, text, textlen);
6082 blame->text[textlen] = 0;
6083 return TRUE;
6087 static bool
6088 blame_read(struct view *view, char *line)
6090 struct blame_state *state = view->private;
6092 if (!state->done_reading)
6093 return blame_read_file(view, line, state);
6095 if (!line) {
6096 state->auto_filename_display = blame_detect_filename_display(view);
6097 string_format(view->ref, "%s", view->vid);
6098 if (view_is_displayed(view)) {
6099 update_view_title(view);
6100 redraw_view_from(view, 0);
6102 return TRUE;
6105 if (!state->commit) {
6106 state->commit = read_blame_commit(view, line, state);
6107 string_format(view->ref, "%s %2zd%%", view->vid,
6108 view->lines ? state->blamed * 100 / view->lines : 0);
6110 } else if (parse_blame_info(state->commit, line)) {
6111 if (!state->commit->filename)
6112 return FALSE;
6113 state->commit = NULL;
6116 return TRUE;
6119 static bool
6120 blame_draw(struct view *view, struct line *line, unsigned int lineno)
6122 struct blame_state *state = view->private;
6123 struct blame *blame = line->data;
6124 struct time *time = NULL;
6125 const char *id = NULL, *filename = NULL;
6126 const struct ident *author = NULL;
6127 enum line_type id_type = LINE_ID;
6128 static const enum line_type blame_colors[] = {
6129 LINE_PALETTE_0,
6130 LINE_PALETTE_1,
6131 LINE_PALETTE_2,
6132 LINE_PALETTE_3,
6133 LINE_PALETTE_4,
6134 LINE_PALETTE_5,
6135 LINE_PALETTE_6,
6138 #define BLAME_COLOR(i) \
6139 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
6141 if (blame->commit && blame->commit->filename) {
6142 id = blame->commit->id;
6143 author = blame->commit->author;
6144 filename = blame->commit->filename;
6145 time = &blame->commit->time;
6146 id_type = BLAME_COLOR((long) blame->commit);
6149 if (draw_date(view, time))
6150 return TRUE;
6152 if (draw_author(view, author))
6153 return TRUE;
6155 if (draw_filename(view, filename, state->auto_filename_display))
6156 return TRUE;
6158 if (draw_id_custom(view, id_type, id, opt_id_cols))
6159 return TRUE;
6161 if (draw_lineno(view, lineno))
6162 return TRUE;
6164 draw_text(view, LINE_DEFAULT, blame->text);
6165 return TRUE;
6168 static bool
6169 check_blame_commit(struct blame *blame, bool check_null_id)
6171 if (!blame->commit)
6172 report("Commit data not loaded yet");
6173 else if (check_null_id && string_rev_is_null(blame->commit->id))
6174 report("No commit exist for the selected line");
6175 else
6176 return TRUE;
6177 return FALSE;
6180 static void
6181 setup_blame_parent_line(struct view *view, struct blame *blame)
6183 char from[SIZEOF_REF + SIZEOF_STR];
6184 char to[SIZEOF_REF + SIZEOF_STR];
6185 const char *diff_tree_argv[] = {
6186 "git", "diff", encoding_arg, "--no-textconv", "--no-extdiff",
6187 "--no-color", "-U0", from, to, "--", NULL
6189 struct io io;
6190 int parent_lineno = -1;
6191 int blamed_lineno = -1;
6192 char *line;
6194 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
6195 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
6196 !io_run(&io, IO_RD, NULL, opt_env, diff_tree_argv))
6197 return;
6199 while ((line = io_get(&io, '\n', TRUE))) {
6200 if (*line == '@') {
6201 char *pos = strchr(line, '+');
6203 parent_lineno = atoi(line + 4);
6204 if (pos)
6205 blamed_lineno = atoi(pos + 1);
6207 } else if (*line == '+' && parent_lineno != -1) {
6208 if (blame->lineno == blamed_lineno - 1 &&
6209 !strcmp(blame->text, line + 1)) {
6210 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
6211 break;
6213 blamed_lineno++;
6217 io_done(&io);
6220 static void
6221 blame_go_forward(struct view *view, struct blame *blame, bool parent)
6223 struct blame_state *state = view->private;
6224 struct blame_history_state *history_state = &state->history_state;
6225 struct blame_commit *commit = blame->commit;
6226 const char *id = parent ? commit->parent_id : commit->id;
6227 const char *filename = parent ? commit->parent_filename : commit->filename;
6229 if (!*id && parent) {
6230 report("The selected commit has no parents");
6231 return;
6234 if (!strcmp(history_state->id, id) && !strcmp(history_state->filename, filename)) {
6235 report("The selected commit is already displayed");
6236 return;
6239 if (!push_view_history_state(&blame_view_history, &view->pos, history_state)) {
6240 report("Failed to save current view state");
6241 return;
6244 string_ncopy(opt_ref, id, sizeof(commit->id));
6245 string_ncopy(opt_file, filename, strlen(filename));
6246 if (parent)
6247 setup_blame_parent_line(view, blame);
6248 opt_goto_line = blame->lineno;
6249 reload_view(view);
6252 static void
6253 blame_go_back(struct view *view)
6255 struct blame_history_state history_state;
6257 if (!pop_view_history_state(&blame_view_history, &view->pos, &history_state)) {
6258 report("Already at start of history");
6259 return;
6262 string_copy(opt_ref, history_state.id);
6263 string_ncopy(opt_file, history_state.filename, strlen(history_state.filename));
6264 opt_goto_line = view->pos.lineno;
6265 reload_view(view);
6268 static enum request
6269 blame_request(struct view *view, enum request request, struct line *line)
6271 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6272 struct blame *blame = line->data;
6274 switch (request) {
6275 case REQ_VIEW_BLAME:
6276 case REQ_PARENT:
6277 if (!check_blame_commit(blame, TRUE))
6278 break;
6279 blame_go_forward(view, blame, request == REQ_PARENT);
6280 break;
6282 case REQ_BACK:
6283 blame_go_back(view);
6284 break;
6286 case REQ_ENTER:
6287 if (!check_blame_commit(blame, FALSE))
6288 break;
6290 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
6291 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
6292 break;
6294 if (string_rev_is_null(blame->commit->id)) {
6295 struct view *diff = VIEW(REQ_VIEW_DIFF);
6296 const char *diff_parent_argv[] = {
6297 GIT_DIFF_BLAME(encoding_arg,
6298 opt_diff_context_arg,
6299 opt_ignore_space_arg, view->vid)
6301 const char *diff_no_parent_argv[] = {
6302 GIT_DIFF_BLAME_NO_PARENT(encoding_arg,
6303 opt_diff_context_arg,
6304 opt_ignore_space_arg, view->vid)
6306 const char **diff_index_argv = *blame->commit->parent_id
6307 ? diff_parent_argv : diff_no_parent_argv;
6309 open_argv(view, diff, diff_index_argv, NULL, flags);
6310 if (diff->pipe)
6311 string_copy_rev(diff->ref, NULL_ID);
6312 } else {
6313 open_view(view, REQ_VIEW_DIFF, flags);
6315 break;
6317 default:
6318 return request;
6321 return REQ_NONE;
6324 static bool
6325 blame_grep(struct view *view, struct line *line)
6327 struct blame *blame = line->data;
6328 struct blame_commit *commit = blame->commit;
6329 const char *text[] = {
6330 blame->text,
6331 commit ? commit->title : "",
6332 commit ? commit->id : "",
6333 commit ? mkauthor(commit->author, opt_author_width, opt_author) : "",
6334 commit ? mkdate(&commit->time, opt_date) : "",
6335 NULL
6338 return grep_text(view, text);
6341 static void
6342 blame_select(struct view *view, struct line *line)
6344 struct blame *blame = line->data;
6345 struct blame_commit *commit = blame->commit;
6347 if (!commit)
6348 return;
6350 if (string_rev_is_null(commit->id))
6351 string_ncopy(ref_commit, "HEAD", 4);
6352 else
6353 string_copy_rev(ref_commit, commit->id);
6356 static struct view_ops blame_ops = {
6357 "line",
6358 { "blame" },
6359 VIEW_ALWAYS_LINENO | VIEW_SEND_CHILD_ENTER,
6360 sizeof(struct blame_state),
6361 blame_open,
6362 blame_read,
6363 blame_draw,
6364 blame_request,
6365 blame_grep,
6366 blame_select,
6370 * Branch backend
6373 struct branch {
6374 const struct ident *author; /* Author of the last commit. */
6375 struct time time; /* Date of the last activity. */
6376 char title[128]; /* First line of the commit message. */
6377 const struct ref *ref; /* Name and commit ID information. */
6380 static const struct ref branch_all;
6381 #define BRANCH_ALL_NAME "All branches"
6382 #define branch_is_all(branch) ((branch)->ref == &branch_all)
6384 static const enum sort_field branch_sort_fields[] = {
6385 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
6387 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
6389 struct branch_state {
6390 char id[SIZEOF_REV];
6391 size_t max_ref_length;
6394 static int
6395 branch_compare(const void *l1, const void *l2)
6397 const struct branch *branch1 = ((const struct line *) l1)->data;
6398 const struct branch *branch2 = ((const struct line *) l2)->data;
6400 if (branch_is_all(branch1))
6401 return -1;
6402 else if (branch_is_all(branch2))
6403 return 1;
6405 switch (get_sort_field(branch_sort_state)) {
6406 case ORDERBY_DATE:
6407 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
6409 case ORDERBY_AUTHOR:
6410 return sort_order(branch_sort_state, ident_compare(branch1->author, branch2->author));
6412 case ORDERBY_NAME:
6413 default:
6414 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
6418 static bool
6419 branch_draw(struct view *view, struct line *line, unsigned int lineno)
6421 struct branch_state *state = view->private;
6422 struct branch *branch = line->data;
6423 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
6424 const char *branch_name = branch_is_all(branch) ? BRANCH_ALL_NAME : branch->ref->name;
6426 if (draw_lineno(view, lineno))
6427 return TRUE;
6429 if (draw_date(view, &branch->time))
6430 return TRUE;
6432 if (draw_author(view, branch->author))
6433 return TRUE;
6435 if (draw_field(view, type, branch_name, state->max_ref_length, ALIGN_LEFT, FALSE))
6436 return TRUE;
6438 if (draw_id(view, branch->ref->id))
6439 return TRUE;
6441 draw_text(view, LINE_DEFAULT, branch->title);
6442 return TRUE;
6445 static enum request
6446 branch_request(struct view *view, enum request request, struct line *line)
6448 struct branch *branch = line->data;
6450 switch (request) {
6451 case REQ_REFRESH:
6452 load_refs(TRUE);
6453 refresh_view(view);
6454 return REQ_NONE;
6456 case REQ_TOGGLE_SORT_FIELD:
6457 case REQ_TOGGLE_SORT_ORDER:
6458 sort_view(view, request, &branch_sort_state, branch_compare);
6459 return REQ_NONE;
6461 case REQ_ENTER:
6463 const struct ref *ref = branch->ref;
6464 const char *all_branches_argv[] = {
6465 GIT_MAIN_LOG(encoding_arg, "", branch_is_all(branch) ? "--all" : ref->name, "")
6467 struct view *main_view = VIEW(REQ_VIEW_MAIN);
6469 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
6470 return REQ_NONE;
6472 case REQ_JUMP_COMMIT:
6474 int lineno;
6476 for (lineno = 0; lineno < view->lines; lineno++) {
6477 struct branch *branch = view->line[lineno].data;
6479 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
6480 select_view_line(view, lineno);
6481 report_clear();
6482 return REQ_NONE;
6486 default:
6487 return request;
6491 static bool
6492 branch_read(struct view *view, char *line)
6494 struct branch_state *state = view->private;
6495 const char *title = NULL;
6496 const struct ident *author = NULL;
6497 struct time time = {};
6498 size_t i;
6500 if (!line)
6501 return TRUE;
6503 switch (get_line_type(line)) {
6504 case LINE_COMMIT:
6505 string_copy_rev_from_commit_line(state->id, line);
6506 return TRUE;
6508 case LINE_AUTHOR:
6509 parse_author_line(line + STRING_SIZE("author "), &author, &time);
6510 break;
6512 default:
6513 title = line + STRING_SIZE("title ");
6516 for (i = 0; i < view->lines; i++) {
6517 struct branch *branch = view->line[i].data;
6519 if (strcmp(branch->ref->id, state->id))
6520 continue;
6522 if (author) {
6523 branch->author = author;
6524 branch->time = time;
6527 if (title)
6528 string_expand(branch->title, sizeof(branch->title), title, 1);
6530 view->line[i].dirty = TRUE;
6533 return TRUE;
6536 static bool
6537 branch_open_visitor(void *data, const struct ref *ref)
6539 struct view *view = data;
6540 struct branch_state *state = view->private;
6541 struct branch *branch;
6542 bool is_all = ref == &branch_all;
6543 size_t ref_length;
6545 if (ref->tag || ref->ltag)
6546 return TRUE;
6548 if (!add_line_alloc(view, &branch, LINE_DEFAULT, 0, is_all))
6549 return FALSE;
6551 ref_length = is_all ? STRING_SIZE(BRANCH_ALL_NAME) : strlen(ref->name);
6552 if (ref_length > state->max_ref_length)
6553 state->max_ref_length = ref_length;
6555 branch->ref = ref;
6556 return TRUE;
6559 static bool
6560 branch_open(struct view *view, enum open_flags flags)
6562 const char *branch_log[] = {
6563 "git", "log", encoding_arg, "--no-color", "--date=raw",
6564 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
6565 "--all", "--simplify-by-decoration", NULL
6568 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
6569 report("Failed to load branch data");
6570 return FALSE;
6573 branch_open_visitor(view, &branch_all);
6574 foreach_ref(branch_open_visitor, view);
6576 return TRUE;
6579 static bool
6580 branch_grep(struct view *view, struct line *line)
6582 struct branch *branch = line->data;
6583 const char *text[] = {
6584 branch->ref->name,
6585 mkauthor(branch->author, opt_author_width, opt_author),
6586 NULL
6589 return grep_text(view, text);
6592 static void
6593 branch_select(struct view *view, struct line *line)
6595 struct branch *branch = line->data;
6597 if (branch_is_all(branch)) {
6598 string_copy(view->ref, BRANCH_ALL_NAME);
6599 return;
6601 string_copy_rev(view->ref, branch->ref->id);
6602 string_copy_rev(ref_commit, branch->ref->id);
6603 string_copy_rev(ref_head, branch->ref->id);
6604 string_copy_rev(ref_branch, branch->ref->name);
6607 static struct view_ops branch_ops = {
6608 "branch",
6609 { "branch" },
6610 VIEW_NO_FLAGS,
6611 sizeof(struct branch_state),
6612 branch_open,
6613 branch_read,
6614 branch_draw,
6615 branch_request,
6616 branch_grep,
6617 branch_select,
6621 * Status backend
6624 struct status {
6625 char status;
6626 struct {
6627 mode_t mode;
6628 char rev[SIZEOF_REV];
6629 char name[SIZEOF_STR];
6630 } old;
6631 struct {
6632 mode_t mode;
6633 char rev[SIZEOF_REV];
6634 char name[SIZEOF_STR];
6635 } new;
6638 static char status_onbranch[SIZEOF_STR];
6639 static struct status stage_status;
6640 static enum line_type stage_line_type;
6642 DEFINE_ALLOCATOR(realloc_ints, int, 32)
6644 /* This should work even for the "On branch" line. */
6645 static inline bool
6646 status_has_none(struct view *view, struct line *line)
6648 return view_has_line(view, line) && !line[1].data;
6651 /* Get fields from the diff line:
6652 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
6654 static inline bool
6655 status_get_diff(struct status *file, const char *buf, size_t bufsize)
6657 const char *old_mode = buf + 1;
6658 const char *new_mode = buf + 8;
6659 const char *old_rev = buf + 15;
6660 const char *new_rev = buf + 56;
6661 const char *status = buf + 97;
6663 if (bufsize < 98 ||
6664 old_mode[-1] != ':' ||
6665 new_mode[-1] != ' ' ||
6666 old_rev[-1] != ' ' ||
6667 new_rev[-1] != ' ' ||
6668 status[-1] != ' ')
6669 return FALSE;
6671 file->status = *status;
6673 string_copy_rev(file->old.rev, old_rev);
6674 string_copy_rev(file->new.rev, new_rev);
6676 file->old.mode = strtoul(old_mode, NULL, 8);
6677 file->new.mode = strtoul(new_mode, NULL, 8);
6679 file->old.name[0] = file->new.name[0] = 0;
6681 return TRUE;
6684 static bool
6685 status_run(struct view *view, const char *argv[], char status, enum line_type type)
6687 struct status *unmerged = NULL;
6688 char *buf;
6689 struct io io;
6691 if (!io_run(&io, IO_RD, opt_cdup, opt_env, argv))
6692 return FALSE;
6694 add_line_nodata(view, type);
6696 while ((buf = io_get(&io, 0, TRUE))) {
6697 struct status *file = unmerged;
6699 if (!file) {
6700 if (!add_line_alloc(view, &file, type, 0, FALSE))
6701 goto error_out;
6704 /* Parse diff info part. */
6705 if (status) {
6706 file->status = status;
6707 if (status == 'A')
6708 string_copy(file->old.rev, NULL_ID);
6710 } else if (!file->status || file == unmerged) {
6711 if (!status_get_diff(file, buf, strlen(buf)))
6712 goto error_out;
6714 buf = io_get(&io, 0, TRUE);
6715 if (!buf)
6716 break;
6718 /* Collapse all modified entries that follow an
6719 * associated unmerged entry. */
6720 if (unmerged == file) {
6721 unmerged->status = 'U';
6722 unmerged = NULL;
6723 } else if (file->status == 'U') {
6724 unmerged = file;
6728 /* Grab the old name for rename/copy. */
6729 if (!*file->old.name &&
6730 (file->status == 'R' || file->status == 'C')) {
6731 string_ncopy(file->old.name, buf, strlen(buf));
6733 buf = io_get(&io, 0, TRUE);
6734 if (!buf)
6735 break;
6738 /* git-ls-files just delivers a NUL separated list of
6739 * file names similar to the second half of the
6740 * git-diff-* output. */
6741 string_ncopy(file->new.name, buf, strlen(buf));
6742 if (!*file->old.name)
6743 string_copy(file->old.name, file->new.name);
6744 file = NULL;
6747 if (io_error(&io)) {
6748 error_out:
6749 io_done(&io);
6750 return FALSE;
6753 if (!view->line[view->lines - 1].data)
6754 add_line_nodata(view, LINE_STAT_NONE);
6756 io_done(&io);
6757 return TRUE;
6760 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
6761 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
6763 static const char *status_list_other_argv[] = {
6764 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
6767 static const char *status_list_no_head_argv[] = {
6768 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
6771 static const char *update_index_argv[] = {
6772 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
6775 /* Restore the previous line number to stay in the context or select a
6776 * line with something that can be updated. */
6777 static void
6778 status_restore(struct view *view)
6780 if (!check_position(&view->prev_pos))
6781 return;
6783 if (view->prev_pos.lineno >= view->lines)
6784 view->prev_pos.lineno = view->lines - 1;
6785 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
6786 view->prev_pos.lineno++;
6787 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
6788 view->prev_pos.lineno--;
6790 /* If the above fails, always skip the "On branch" line. */
6791 if (view->prev_pos.lineno < view->lines)
6792 view->pos.lineno = view->prev_pos.lineno;
6793 else
6794 view->pos.lineno = 1;
6796 if (view->prev_pos.offset > view->pos.lineno)
6797 view->pos.offset = view->pos.lineno;
6798 else if (view->prev_pos.offset < view->lines)
6799 view->pos.offset = view->prev_pos.offset;
6801 clear_position(&view->prev_pos);
6804 static void
6805 status_update_onbranch(void)
6807 static const char *paths[][2] = {
6808 { "rebase-apply/rebasing", "Rebasing" },
6809 { "rebase-apply/applying", "Applying mailbox" },
6810 { "rebase-apply/", "Rebasing mailbox" },
6811 { "rebase-merge/interactive", "Interactive rebase" },
6812 { "rebase-merge/", "Rebase merge" },
6813 { "MERGE_HEAD", "Merging" },
6814 { "BISECT_LOG", "Bisecting" },
6815 { "HEAD", "On branch" },
6817 char buf[SIZEOF_STR];
6818 struct stat stat;
6819 int i;
6821 if (is_initial_commit()) {
6822 string_copy(status_onbranch, "Initial commit");
6823 return;
6826 for (i = 0; i < ARRAY_SIZE(paths); i++) {
6827 char *head = opt_head;
6829 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
6830 lstat(buf, &stat) < 0)
6831 continue;
6833 if (!*opt_head) {
6834 struct io io;
6836 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
6837 io_read_buf(&io, buf, sizeof(buf))) {
6838 head = buf;
6839 if (!prefixcmp(head, "refs/heads/"))
6840 head += STRING_SIZE("refs/heads/");
6844 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
6845 string_copy(status_onbranch, opt_head);
6846 return;
6849 string_copy(status_onbranch, "Not currently on any branch");
6852 /* First parse staged info using git-diff-index(1), then parse unstaged
6853 * info using git-diff-files(1), and finally untracked files using
6854 * git-ls-files(1). */
6855 static bool
6856 status_open(struct view *view, enum open_flags flags)
6858 const char **staged_argv = is_initial_commit() ?
6859 status_list_no_head_argv : status_diff_index_argv;
6860 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
6862 if (opt_is_inside_work_tree == FALSE) {
6863 report("The status view requires a working tree");
6864 return FALSE;
6867 reset_view(view);
6869 add_line_nodata(view, LINE_STAT_HEAD);
6870 status_update_onbranch();
6872 io_run_bg(update_index_argv);
6874 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] =
6875 opt_untracked_dirs_content ? NULL : "--directory";
6877 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
6878 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
6879 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
6880 report("Failed to load status data");
6881 return FALSE;
6884 /* Restore the exact position or use the specialized restore
6885 * mode? */
6886 status_restore(view);
6887 return TRUE;
6890 static bool
6891 status_draw(struct view *view, struct line *line, unsigned int lineno)
6893 struct status *status = line->data;
6894 enum line_type type;
6895 const char *text;
6897 if (!status) {
6898 switch (line->type) {
6899 case LINE_STAT_STAGED:
6900 type = LINE_STAT_SECTION;
6901 text = "Changes to be committed:";
6902 break;
6904 case LINE_STAT_UNSTAGED:
6905 type = LINE_STAT_SECTION;
6906 text = "Changed but not updated:";
6907 break;
6909 case LINE_STAT_UNTRACKED:
6910 type = LINE_STAT_SECTION;
6911 text = "Untracked files:";
6912 break;
6914 case LINE_STAT_NONE:
6915 type = LINE_DEFAULT;
6916 text = " (no files)";
6917 break;
6919 case LINE_STAT_HEAD:
6920 type = LINE_STAT_HEAD;
6921 text = status_onbranch;
6922 break;
6924 default:
6925 return FALSE;
6927 } else {
6928 static char buf[] = { '?', ' ', ' ', ' ', 0 };
6930 buf[0] = status->status;
6931 if (draw_text(view, line->type, buf))
6932 return TRUE;
6933 type = LINE_DEFAULT;
6934 text = status->new.name;
6937 draw_text(view, type, text);
6938 return TRUE;
6941 static enum request
6942 status_enter(struct view *view, struct line *line)
6944 struct status *status = line->data;
6945 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6947 if (line->type == LINE_STAT_NONE ||
6948 (!status && line[1].type == LINE_STAT_NONE)) {
6949 report("No file to diff");
6950 return REQ_NONE;
6953 switch (line->type) {
6954 case LINE_STAT_STAGED:
6955 case LINE_STAT_UNSTAGED:
6956 break;
6958 case LINE_STAT_UNTRACKED:
6959 if (!status) {
6960 report("No file to show");
6961 return REQ_NONE;
6964 if (!suffixcmp(status->new.name, -1, "/")) {
6965 report("Cannot display a directory");
6966 return REQ_NONE;
6968 break;
6970 case LINE_STAT_HEAD:
6971 return REQ_NONE;
6973 default:
6974 die("line type %d not handled in switch", line->type);
6977 if (status) {
6978 stage_status = *status;
6979 } else {
6980 memset(&stage_status, 0, sizeof(stage_status));
6983 stage_line_type = line->type;
6985 open_view(view, REQ_VIEW_STAGE, flags);
6986 return REQ_NONE;
6989 static bool
6990 status_exists(struct view *view, struct status *status, enum line_type type)
6992 unsigned long lineno;
6994 for (lineno = 0; lineno < view->lines; lineno++) {
6995 struct line *line = &view->line[lineno];
6996 struct status *pos = line->data;
6998 if (line->type != type)
6999 continue;
7000 if (!pos && (!status || !status->status) && line[1].data) {
7001 select_view_line(view, lineno);
7002 return TRUE;
7004 if (pos && !strcmp(status->new.name, pos->new.name)) {
7005 select_view_line(view, lineno);
7006 return TRUE;
7010 return FALSE;
7014 static bool
7015 status_update_prepare(struct io *io, enum line_type type)
7017 const char *staged_argv[] = {
7018 "git", "update-index", "-z", "--index-info", NULL
7020 const char *others_argv[] = {
7021 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
7024 switch (type) {
7025 case LINE_STAT_STAGED:
7026 return io_run(io, IO_WR, opt_cdup, opt_env, staged_argv);
7028 case LINE_STAT_UNSTAGED:
7029 case LINE_STAT_UNTRACKED:
7030 return io_run(io, IO_WR, opt_cdup, opt_env, others_argv);
7032 default:
7033 die("line type %d not handled in switch", type);
7034 return FALSE;
7038 static bool
7039 status_update_write(struct io *io, struct status *status, enum line_type type)
7041 switch (type) {
7042 case LINE_STAT_STAGED:
7043 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
7044 status->old.rev, status->old.name, 0);
7046 case LINE_STAT_UNSTAGED:
7047 case LINE_STAT_UNTRACKED:
7048 return io_printf(io, "%s%c", status->new.name, 0);
7050 default:
7051 die("line type %d not handled in switch", type);
7052 return FALSE;
7056 static bool
7057 status_update_file(struct status *status, enum line_type type)
7059 struct io io;
7060 bool result;
7062 if (!status_update_prepare(&io, type))
7063 return FALSE;
7065 result = status_update_write(&io, status, type);
7066 return io_done(&io) && result;
7069 static bool
7070 status_update_files(struct view *view, struct line *line)
7072 char buf[sizeof(view->ref)];
7073 struct io io;
7074 bool result = TRUE;
7075 struct line *pos;
7076 int files = 0;
7077 int file, done;
7078 int cursor_y = -1, cursor_x = -1;
7080 if (!status_update_prepare(&io, line->type))
7081 return FALSE;
7083 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
7084 files++;
7086 string_copy(buf, view->ref);
7087 getsyx(cursor_y, cursor_x);
7088 for (file = 0, done = 5; result && file < files; line++, file++) {
7089 int almost_done = file * 100 / files;
7091 if (almost_done > done) {
7092 done = almost_done;
7093 string_format(view->ref, "updating file %u of %u (%d%% done)",
7094 file, files, done);
7095 update_view_title(view);
7096 setsyx(cursor_y, cursor_x);
7097 doupdate();
7099 result = status_update_write(&io, line->data, line->type);
7101 string_copy(view->ref, buf);
7103 return io_done(&io) && result;
7106 static bool
7107 status_update(struct view *view)
7109 struct line *line = &view->line[view->pos.lineno];
7111 assert(view->lines);
7113 if (!line->data) {
7114 if (status_has_none(view, line)) {
7115 report("Nothing to update");
7116 return FALSE;
7119 if (!status_update_files(view, line + 1)) {
7120 report("Failed to update file status");
7121 return FALSE;
7124 } else if (!status_update_file(line->data, line->type)) {
7125 report("Failed to update file status");
7126 return FALSE;
7129 return TRUE;
7132 static bool
7133 status_revert(struct status *status, enum line_type type, bool has_none)
7135 if (!status || type != LINE_STAT_UNSTAGED) {
7136 if (type == LINE_STAT_STAGED) {
7137 report("Cannot revert changes to staged files");
7138 } else if (type == LINE_STAT_UNTRACKED) {
7139 report("Cannot revert changes to untracked files");
7140 } else if (has_none) {
7141 report("Nothing to revert");
7142 } else {
7143 report("Cannot revert changes to multiple files");
7146 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
7147 char mode[10] = "100644";
7148 const char *reset_argv[] = {
7149 "git", "update-index", "--cacheinfo", mode,
7150 status->old.rev, status->old.name, NULL
7152 const char *checkout_argv[] = {
7153 "git", "checkout", "--", status->old.name, NULL
7156 if (status->status == 'U') {
7157 string_format(mode, "%5o", status->old.mode);
7159 if (status->old.mode == 0 && status->new.mode == 0) {
7160 reset_argv[2] = "--force-remove";
7161 reset_argv[3] = status->old.name;
7162 reset_argv[4] = NULL;
7165 if (!io_run_fg(reset_argv, opt_cdup))
7166 return FALSE;
7167 if (status->old.mode == 0 && status->new.mode == 0)
7168 return TRUE;
7171 return io_run_fg(checkout_argv, opt_cdup);
7174 return FALSE;
7177 static enum request
7178 status_request(struct view *view, enum request request, struct line *line)
7180 struct status *status = line->data;
7182 switch (request) {
7183 case REQ_STATUS_UPDATE:
7184 if (!status_update(view))
7185 return REQ_NONE;
7186 break;
7188 case REQ_STATUS_REVERT:
7189 if (!status_revert(status, line->type, status_has_none(view, line)))
7190 return REQ_NONE;
7191 break;
7193 case REQ_STATUS_MERGE:
7194 if (!status || status->status != 'U') {
7195 report("Merging only possible for files with unmerged status ('U').");
7196 return REQ_NONE;
7198 open_mergetool(status->new.name);
7199 break;
7201 case REQ_EDIT:
7202 if (!status)
7203 return request;
7204 if (status->status == 'D') {
7205 report("File has been deleted.");
7206 return REQ_NONE;
7209 open_editor(status->new.name, 0);
7210 break;
7212 case REQ_VIEW_BLAME:
7213 if (status)
7214 opt_ref[0] = 0;
7215 return request;
7217 case REQ_ENTER:
7218 /* After returning the status view has been split to
7219 * show the stage view. No further reloading is
7220 * necessary. */
7221 return status_enter(view, line);
7223 case REQ_REFRESH:
7224 /* Load the current branch information and then the view. */
7225 load_refs(TRUE);
7226 break;
7228 default:
7229 return request;
7232 refresh_view(view);
7234 return REQ_NONE;
7237 static bool
7238 status_stage_info_(char *buf, size_t bufsize,
7239 enum line_type type, struct status *status)
7241 const char *file = status ? status->new.name : "";
7242 const char *info;
7244 switch (type) {
7245 case LINE_STAT_STAGED:
7246 if (status && status->status)
7247 info = "Staged changes to %s";
7248 else
7249 info = "Staged changes";
7250 break;
7252 case LINE_STAT_UNSTAGED:
7253 if (status && status->status)
7254 info = "Unstaged changes to %s";
7255 else
7256 info = "Unstaged changes";
7257 break;
7259 case LINE_STAT_UNTRACKED:
7260 info = "Untracked file %s";
7261 break;
7263 case LINE_STAT_HEAD:
7264 default:
7265 info = "";
7268 return string_nformat(buf, bufsize, NULL, info, file);
7270 #define status_stage_info(buf, type, status) \
7271 status_stage_info_(buf, sizeof(buf), type, status)
7273 static void
7274 status_select(struct view *view, struct line *line)
7276 struct status *status = line->data;
7277 char file[SIZEOF_STR] = "all files";
7278 const char *text;
7279 const char *key;
7281 if (status && !string_format(file, "'%s'", status->new.name))
7282 return;
7284 if (!status && line[1].type == LINE_STAT_NONE)
7285 line++;
7287 switch (line->type) {
7288 case LINE_STAT_STAGED:
7289 text = "Press %s to unstage %s for commit";
7290 break;
7292 case LINE_STAT_UNSTAGED:
7293 text = "Press %s to stage %s for commit";
7294 break;
7296 case LINE_STAT_UNTRACKED:
7297 text = "Press %s to stage %s for addition";
7298 break;
7300 case LINE_STAT_HEAD:
7301 case LINE_STAT_NONE:
7302 text = "Nothing to update";
7303 break;
7305 default:
7306 die("line type %d not handled in switch", line->type);
7309 if (status && status->status == 'U') {
7310 text = "Press %s to resolve conflict in %s";
7311 key = get_view_key(view, REQ_STATUS_MERGE);
7313 } else {
7314 key = get_view_key(view, REQ_STATUS_UPDATE);
7317 string_format(view->ref, text, key, file);
7318 status_stage_info(ref_status, line->type, status);
7319 if (status)
7320 string_copy(opt_file, status->new.name);
7323 static bool
7324 status_grep(struct view *view, struct line *line)
7326 struct status *status = line->data;
7328 if (status) {
7329 const char buf[2] = { status->status, 0 };
7330 const char *text[] = { status->new.name, buf, NULL };
7332 return grep_text(view, text);
7335 return FALSE;
7338 static struct view_ops status_ops = {
7339 "file",
7340 { "status" },
7341 VIEW_CUSTOM_STATUS | VIEW_SEND_CHILD_ENTER | VIEW_STATUS_LIKE,
7343 status_open,
7344 NULL,
7345 status_draw,
7346 status_request,
7347 status_grep,
7348 status_select,
7352 struct stage_state {
7353 struct diff_state diff;
7354 size_t chunks;
7355 int *chunk;
7358 static bool
7359 stage_diff_write(struct io *io, struct line *line, struct line *end)
7361 while (line < end) {
7362 if (!io_write(io, line->data, strlen(line->data)) ||
7363 !io_write(io, "\n", 1))
7364 return FALSE;
7365 line++;
7366 if (line->type == LINE_DIFF_CHUNK ||
7367 line->type == LINE_DIFF_HEADER)
7368 break;
7371 return TRUE;
7374 static bool
7375 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
7377 const char *apply_argv[SIZEOF_ARG] = {
7378 "git", "apply", "--whitespace=nowarn", NULL
7380 struct line *diff_hdr;
7381 struct io io;
7382 int argc = 3;
7384 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
7385 if (!diff_hdr)
7386 return FALSE;
7388 if (!revert)
7389 apply_argv[argc++] = "--cached";
7390 if (line != NULL)
7391 apply_argv[argc++] = "--unidiff-zero";
7392 if (revert || stage_line_type == LINE_STAT_STAGED)
7393 apply_argv[argc++] = "-R";
7394 apply_argv[argc++] = "-";
7395 apply_argv[argc++] = NULL;
7396 if (!io_run(&io, IO_WR, opt_cdup, opt_env, apply_argv))
7397 return FALSE;
7399 if (line != NULL) {
7400 unsigned long lineno = 0;
7401 struct line *context = chunk + 1;
7402 const char *markers[] = {
7403 line->type == LINE_DIFF_DEL ? "" : ",0",
7404 line->type == LINE_DIFF_DEL ? ",0" : "",
7407 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
7409 while (context < line) {
7410 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
7411 break;
7412 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
7413 lineno++;
7415 context++;
7418 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7419 !io_printf(&io, "@@ -%lu%s +%lu%s @@\n",
7420 lineno, markers[0], lineno, markers[1]) ||
7421 !stage_diff_write(&io, line, line + 1)) {
7422 chunk = NULL;
7424 } else {
7425 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7426 !stage_diff_write(&io, chunk, view->line + view->lines))
7427 chunk = NULL;
7430 io_done(&io);
7432 return chunk ? TRUE : FALSE;
7435 static bool
7436 stage_update(struct view *view, struct line *line, bool single)
7438 struct line *chunk = NULL;
7440 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
7441 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7443 if (chunk) {
7444 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
7445 report("Failed to apply chunk");
7446 return FALSE;
7449 } else if (!stage_status.status) {
7450 view = view->parent;
7452 for (line = view->line; view_has_line(view, line); line++)
7453 if (line->type == stage_line_type)
7454 break;
7456 if (!status_update_files(view, line + 1)) {
7457 report("Failed to update files");
7458 return FALSE;
7461 } else if (!status_update_file(&stage_status, stage_line_type)) {
7462 report("Failed to update file");
7463 return FALSE;
7466 return TRUE;
7469 static bool
7470 stage_revert(struct view *view, struct line *line)
7472 struct line *chunk = NULL;
7474 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
7475 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7477 if (chunk) {
7478 if (!prompt_yesno("Are you sure you want to revert changes?"))
7479 return FALSE;
7481 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
7482 report("Failed to revert chunk");
7483 return FALSE;
7485 return TRUE;
7487 } else {
7488 return status_revert(stage_status.status ? &stage_status : NULL,
7489 stage_line_type, FALSE);
7494 static void
7495 stage_next(struct view *view, struct line *line)
7497 struct stage_state *state = view->private;
7498 int i;
7500 if (!state->chunks) {
7501 for (line = view->line; view_has_line(view, line); line++) {
7502 if (line->type != LINE_DIFF_CHUNK)
7503 continue;
7505 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
7506 report("Allocation failure");
7507 return;
7510 state->chunk[state->chunks++] = line - view->line;
7514 for (i = 0; i < state->chunks; i++) {
7515 if (state->chunk[i] > view->pos.lineno) {
7516 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
7517 report("Chunk %d of %zd", i + 1, state->chunks);
7518 return;
7522 report("No next chunk found");
7525 static struct line *
7526 stage_insert_chunk(struct view *view, struct chunk_header *header,
7527 struct line *from, struct line *to, struct line *last_unchanged_line)
7529 char buf[SIZEOF_STR];
7530 char *chunk_line;
7531 unsigned long from_lineno = last_unchanged_line - view->line;
7532 unsigned long to_lineno = to - view->line;
7533 unsigned long after_lineno = to_lineno;
7535 if (!string_format(buf, "@@ -%lu,%lu +%lu,%lu @@",
7536 header->old.position, header->old.lines,
7537 header->new.position, header->new.lines))
7538 return NULL;
7540 chunk_line = strdup(buf);
7541 if (!chunk_line)
7542 return NULL;
7544 free(from->data);
7545 from->data = chunk_line;
7547 if (!to)
7548 return from;
7550 if (!add_line_at(view, after_lineno++, buf, LINE_DIFF_CHUNK, strlen(buf) + 1, FALSE))
7551 return NULL;
7553 while (from_lineno < to_lineno) {
7554 struct line *line = &view->line[from_lineno++];
7556 if (!add_line_at(view, after_lineno++, line->data, line->type, strlen(line->data) + 1, FALSE))
7557 return FALSE;
7560 return view->line + after_lineno;
7563 static void
7564 stage_split_chunk(struct view *view, struct line *chunk_start)
7566 struct chunk_header header;
7567 struct line *last_changed_line = NULL, *last_unchanged_line = NULL, *pos;
7568 int chunks = 0;
7570 if (!chunk_start || !parse_chunk_header(&header, chunk_start->data)) {
7571 report("Failed to parse chunk header");
7572 return;
7575 header.old.lines = header.new.lines = 0;
7577 for (pos = chunk_start + 1; view_has_line(view, pos); pos++) {
7578 const char *chunk_line = pos->data;
7580 if (*chunk_line == '@' || *chunk_line == '\\')
7581 break;
7583 if (*chunk_line == ' ') {
7584 header.old.lines++;
7585 header.new.lines++;
7586 if (last_unchanged_line < last_changed_line)
7587 last_unchanged_line = pos;
7588 continue;
7591 if (last_changed_line && last_changed_line < last_unchanged_line) {
7592 unsigned long chunk_start_lineno = pos - view->line;
7593 unsigned long diff = pos - last_unchanged_line;
7595 pos = stage_insert_chunk(view, &header, chunk_start, pos, last_unchanged_line);
7597 header.old.position += header.old.lines - diff;
7598 header.new.position += header.new.lines - diff;
7599 header.old.lines = header.new.lines = diff;
7601 chunk_start = view->line + chunk_start_lineno;
7602 last_changed_line = last_unchanged_line = NULL;
7603 chunks++;
7606 if (*chunk_line == '-') {
7607 header.old.lines++;
7608 last_changed_line = pos;
7609 } else if (*chunk_line == '+') {
7610 header.new.lines++;
7611 last_changed_line = pos;
7615 if (chunks) {
7616 stage_insert_chunk(view, &header, chunk_start, NULL, NULL);
7617 redraw_view(view);
7618 report("Split the chunk in %d", chunks + 1);
7619 } else {
7620 report("The chunk cannot be split");
7624 static enum request
7625 stage_request(struct view *view, enum request request, struct line *line)
7627 switch (request) {
7628 case REQ_STATUS_UPDATE:
7629 if (!stage_update(view, line, FALSE))
7630 return REQ_NONE;
7631 break;
7633 case REQ_STATUS_REVERT:
7634 if (!stage_revert(view, line))
7635 return REQ_NONE;
7636 break;
7638 case REQ_STAGE_UPDATE_LINE:
7639 if (stage_line_type == LINE_STAT_UNTRACKED ||
7640 stage_status.status == 'A') {
7641 report("Staging single lines is not supported for new files");
7642 return REQ_NONE;
7644 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
7645 report("Please select a change to stage");
7646 return REQ_NONE;
7648 if (!stage_update(view, line, TRUE))
7649 return REQ_NONE;
7650 break;
7652 case REQ_STAGE_NEXT:
7653 if (stage_line_type == LINE_STAT_UNTRACKED) {
7654 report("File is untracked; press %s to add",
7655 get_view_key(view, REQ_STATUS_UPDATE));
7656 return REQ_NONE;
7658 stage_next(view, line);
7659 return REQ_NONE;
7661 case REQ_STAGE_SPLIT_CHUNK:
7662 if (stage_line_type == LINE_STAT_UNTRACKED ||
7663 !(line = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK))) {
7664 report("No chunks to split in sight");
7665 return REQ_NONE;
7667 stage_split_chunk(view, line);
7668 return REQ_NONE;
7670 case REQ_EDIT:
7671 if (!stage_status.new.name[0])
7672 return diff_common_edit(view, request, line);
7674 if (stage_status.status == 'D') {
7675 report("File has been deleted.");
7676 return REQ_NONE;
7679 if (stage_line_type == LINE_STAT_UNTRACKED) {
7680 open_editor(stage_status.new.name, (line - view->line) + 1);
7681 } else {
7682 open_editor(stage_status.new.name, diff_get_lineno(view, line));
7684 break;
7686 case REQ_REFRESH:
7687 /* Reload everything(including current branch information) ... */
7688 load_refs(TRUE);
7689 break;
7691 case REQ_VIEW_BLAME:
7692 if (stage_status.new.name[0]) {
7693 string_copy(opt_file, stage_status.new.name);
7694 opt_ref[0] = 0;
7696 return request;
7698 case REQ_ENTER:
7699 return diff_common_enter(view, request, line);
7701 case REQ_DIFF_CONTEXT_UP:
7702 case REQ_DIFF_CONTEXT_DOWN:
7703 if (!update_diff_context(request))
7704 return REQ_NONE;
7705 break;
7707 default:
7708 return request;
7711 refresh_view(view->parent);
7713 /* Check whether the staged entry still exists, and close the
7714 * stage view if it doesn't. */
7715 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
7716 status_restore(view->parent);
7717 return REQ_VIEW_CLOSE;
7720 refresh_view(view);
7722 return REQ_NONE;
7725 static bool
7726 stage_open(struct view *view, enum open_flags flags)
7728 static const char *no_head_diff_argv[] = {
7729 GIT_DIFF_STAGED_INITIAL(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7730 stage_status.new.name)
7732 static const char *index_show_argv[] = {
7733 GIT_DIFF_STAGED(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7734 stage_status.old.name, stage_status.new.name)
7736 static const char *files_show_argv[] = {
7737 GIT_DIFF_UNSTAGED(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7738 stage_status.old.name, stage_status.new.name)
7740 /* Diffs for unmerged entries are empty when passing the new
7741 * path, so leave out the new path. */
7742 static const char *files_unmerged_argv[] = {
7743 "git", "diff-files", encoding_arg, "--root", "--patch-with-stat",
7744 opt_diff_context_arg, opt_ignore_space_arg, "--",
7745 stage_status.old.name, NULL
7747 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
7748 const char **argv = NULL;
7750 if (!stage_line_type) {
7751 report("No stage content, press %s to open the status view and choose file",
7752 get_view_key(view, REQ_VIEW_STATUS));
7753 return FALSE;
7756 view->encoding = NULL;
7758 switch (stage_line_type) {
7759 case LINE_STAT_STAGED:
7760 if (is_initial_commit()) {
7761 argv = no_head_diff_argv;
7762 } else {
7763 argv = index_show_argv;
7765 break;
7767 case LINE_STAT_UNSTAGED:
7768 if (stage_status.status != 'U')
7769 argv = files_show_argv;
7770 else
7771 argv = files_unmerged_argv;
7772 break;
7774 case LINE_STAT_UNTRACKED:
7775 argv = file_argv;
7776 view->encoding = get_path_encoding(stage_status.old.name, default_encoding);
7777 break;
7779 case LINE_STAT_HEAD:
7780 default:
7781 die("line type %d not handled in switch", stage_line_type);
7784 if (!status_stage_info(view->ref, stage_line_type, &stage_status)
7785 || !argv_copy(&view->argv, argv)) {
7786 report("Failed to open staged view");
7787 return FALSE;
7790 view->vid[0] = 0;
7791 view->dir = opt_cdup;
7792 return begin_update(view, NULL, NULL, flags);
7795 static bool
7796 stage_read(struct view *view, char *data)
7798 struct stage_state *state = view->private;
7800 if (stage_line_type == LINE_STAT_UNTRACKED)
7801 return pager_common_read(view, data, LINE_DEFAULT);
7803 if (data && diff_common_read(view, data, &state->diff))
7804 return TRUE;
7806 return pager_read(view, data);
7809 static struct view_ops stage_ops = {
7810 "line",
7811 { "stage" },
7812 VIEW_DIFF_LIKE,
7813 sizeof(struct stage_state),
7814 stage_open,
7815 stage_read,
7816 diff_common_draw,
7817 stage_request,
7818 pager_grep,
7819 pager_select,
7824 * Revision graph
7827 static const enum line_type graph_colors[] = {
7828 LINE_PALETTE_0,
7829 LINE_PALETTE_1,
7830 LINE_PALETTE_2,
7831 LINE_PALETTE_3,
7832 LINE_PALETTE_4,
7833 LINE_PALETTE_5,
7834 LINE_PALETTE_6,
7837 static enum line_type get_graph_color(struct graph_symbol *symbol)
7839 if (symbol->commit)
7840 return LINE_GRAPH_COMMIT;
7841 assert(symbol->color < ARRAY_SIZE(graph_colors));
7842 return graph_colors[symbol->color];
7845 static bool
7846 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7848 const char *chars = graph_symbol_to_utf8(symbol);
7850 return draw_text(view, color, chars + !!first);
7853 static bool
7854 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7856 const char *chars = graph_symbol_to_ascii(symbol);
7858 return draw_text(view, color, chars + !!first);
7861 static bool
7862 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7864 const chtype *chars = graph_symbol_to_chtype(symbol);
7866 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
7869 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
7871 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
7873 static const draw_graph_fn fns[] = {
7874 draw_graph_ascii,
7875 draw_graph_chtype,
7876 draw_graph_utf8
7878 draw_graph_fn fn = fns[opt_line_graphics];
7879 int i;
7881 for (i = 0; i < canvas->size; i++) {
7882 struct graph_symbol *symbol = &canvas->symbols[i];
7883 enum line_type color = get_graph_color(symbol);
7885 if (fn(view, symbol, color, i == 0))
7886 return TRUE;
7889 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
7893 * Main view backend
7896 DEFINE_ALLOCATOR(realloc_reflogs, char *, 32)
7898 struct commit {
7899 char id[SIZEOF_REV]; /* SHA1 ID. */
7900 const struct ident *author; /* Author of the commit. */
7901 struct time time; /* Date from the author ident. */
7902 struct graph_canvas graph; /* Ancestry chain graphics. */
7903 char title[1]; /* First line of the commit message. */
7906 struct main_state {
7907 struct graph graph;
7908 struct commit current;
7909 char **reflog;
7910 size_t reflogs;
7911 int reflog_width;
7912 char reflogmsg[SIZEOF_STR / 2];
7913 bool in_header;
7914 bool added_changes_commits;
7915 bool with_graph;
7918 static void
7919 main_register_commit(struct view *view, struct commit *commit, const char *ids, bool is_boundary)
7921 struct main_state *state = view->private;
7923 string_copy_rev(commit->id, ids);
7924 if (state->with_graph)
7925 graph_add_commit(&state->graph, &commit->graph, commit->id, ids, is_boundary);
7928 static struct commit *
7929 main_add_commit(struct view *view, enum line_type type, struct commit *template,
7930 const char *title, bool custom)
7932 struct main_state *state = view->private;
7933 size_t titlelen = strlen(title);
7934 struct commit *commit;
7935 char buf[SIZEOF_STR / 2];
7937 /* FIXME: More graceful handling of titles; append "..." to
7938 * shortened titles, etc. */
7939 string_expand(buf, sizeof(buf), title, 1);
7940 title = buf;
7941 titlelen = strlen(title);
7943 if (!add_line_alloc(view, &commit, type, titlelen, custom))
7944 return NULL;
7946 *commit = *template;
7947 strncpy(commit->title, title, titlelen);
7948 state->graph.canvas = &commit->graph;
7949 memset(template, 0, sizeof(*template));
7950 state->reflogmsg[0] = 0;
7951 return commit;
7954 static inline void
7955 main_flush_commit(struct view *view, struct commit *commit)
7957 if (*commit->id)
7958 main_add_commit(view, LINE_MAIN_COMMIT, commit, "", FALSE);
7961 static bool
7962 main_has_changes(const char *argv[])
7964 struct io io;
7966 if (!io_run(&io, IO_BG, NULL, opt_env, argv, -1))
7967 return FALSE;
7968 io_done(&io);
7969 return io.status == 1;
7972 static void
7973 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
7975 char ids[SIZEOF_STR] = NULL_ID " ";
7976 struct main_state *state = view->private;
7977 struct commit commit = {};
7978 struct timeval now;
7979 struct timezone tz;
7981 if (!parent)
7982 return;
7984 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
7986 if (!gettimeofday(&now, &tz)) {
7987 commit.time.tz = tz.tz_minuteswest * 60;
7988 commit.time.sec = now.tv_sec - commit.time.tz;
7991 commit.author = &unknown_ident;
7992 main_register_commit(view, &commit, ids, FALSE);
7993 if (main_add_commit(view, type, &commit, title, TRUE) && state->with_graph)
7994 graph_render_parents(&state->graph);
7997 static void
7998 main_add_changes_commits(struct view *view, struct main_state *state, const char *parent)
8000 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
8001 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
8002 const char *staged_parent = NULL_ID;
8003 const char *unstaged_parent = parent;
8005 if (!is_head_commit(parent))
8006 return;
8008 state->added_changes_commits = TRUE;
8010 io_run_bg(update_index_argv);
8012 if (!main_has_changes(unstaged_argv)) {
8013 unstaged_parent = NULL;
8014 staged_parent = parent;
8017 if (!main_has_changes(staged_argv)) {
8018 staged_parent = NULL;
8021 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
8022 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
8025 static bool
8026 main_open(struct view *view, enum open_flags flags)
8028 static const char *main_argv[] = {
8029 GIT_MAIN_LOG(encoding_arg, "%(diffargs)", "%(revargs)", "%(fileargs)")
8031 struct main_state *state = view->private;
8033 state->with_graph = opt_rev_graph;
8035 if (flags & OPEN_PAGER_MODE) {
8036 state->added_changes_commits = TRUE;
8037 state->with_graph = FALSE;
8040 return begin_update(view, NULL, main_argv, flags);
8043 static void
8044 main_done(struct view *view)
8046 struct main_state *state = view->private;
8047 int i;
8049 for (i = 0; i < view->lines; i++) {
8050 struct commit *commit = view->line[i].data;
8052 free(commit->graph.symbols);
8055 for (i = 0; i < state->reflogs; i++)
8056 free(state->reflog[i]);
8057 free(state->reflog);
8060 #define MAIN_NO_COMMIT_REFS 1
8061 #define main_check_commit_refs(line) !((line)->user_flags & MAIN_NO_COMMIT_REFS)
8062 #define main_mark_no_commit_refs(line) ((line)->user_flags |= MAIN_NO_COMMIT_REFS)
8064 static inline struct ref_list *
8065 main_get_commit_refs(struct line *line, struct commit *commit)
8067 struct ref_list *refs = NULL;
8069 if (main_check_commit_refs(line) && !(refs = get_ref_list(commit->id)))
8070 main_mark_no_commit_refs(line);
8072 return refs;
8075 static bool
8076 main_draw(struct view *view, struct line *line, unsigned int lineno)
8078 struct main_state *state = view->private;
8079 struct commit *commit = line->data;
8080 struct ref_list *refs = NULL;
8082 if (!commit->author)
8083 return FALSE;
8085 if (draw_lineno(view, lineno))
8086 return TRUE;
8088 if (opt_show_id) {
8089 if (state->reflogs) {
8090 const char *id = state->reflog[line->lineno - 1];
8092 if (draw_id_custom(view, LINE_ID, id, state->reflog_width))
8093 return TRUE;
8094 } else if (draw_id(view, commit->id)) {
8095 return TRUE;
8099 if (draw_date(view, &commit->time))
8100 return TRUE;
8102 if (draw_author(view, commit->author))
8103 return TRUE;
8105 if (state->with_graph && draw_graph(view, &commit->graph))
8106 return TRUE;
8108 if ((refs = main_get_commit_refs(line, commit)) && draw_refs(view, refs))
8109 return TRUE;
8111 if (commit->title)
8112 draw_commit_title(view, commit->title, 0);
8113 return TRUE;
8116 static bool
8117 main_add_reflog(struct view *view, struct main_state *state, char *reflog)
8119 char *end = strchr(reflog, ' ');
8120 int id_width;
8122 if (!end)
8123 return FALSE;
8124 *end = 0;
8126 if (!realloc_reflogs(&state->reflog, state->reflogs, 1)
8127 || !(reflog = strdup(reflog)))
8128 return FALSE;
8130 state->reflog[state->reflogs++] = reflog;
8131 id_width = strlen(reflog);
8132 if (state->reflog_width < id_width) {
8133 state->reflog_width = id_width;
8134 if (opt_show_id)
8135 view->force_redraw = TRUE;
8138 return TRUE;
8141 /* Reads git log --pretty=raw output and parses it into the commit struct. */
8142 static bool
8143 main_read(struct view *view, char *line)
8145 struct main_state *state = view->private;
8146 struct graph *graph = &state->graph;
8147 enum line_type type;
8148 struct commit *commit = &state->current;
8150 if (!line) {
8151 main_flush_commit(view, commit);
8153 if (!view->lines && !view->prev)
8154 die("No revisions match the given arguments.");
8155 if (view->lines > 0) {
8156 struct commit *last = view->line[view->lines - 1].data;
8158 view->line[view->lines - 1].dirty = 1;
8159 if (!last->author) {
8160 view->lines--;
8161 free(last);
8165 if (state->with_graph)
8166 done_graph(graph);
8167 return TRUE;
8170 type = get_line_type(line);
8171 if (type == LINE_COMMIT) {
8172 bool is_boundary;
8174 state->in_header = TRUE;
8175 line += STRING_SIZE("commit ");
8176 is_boundary = *line == '-';
8177 if (is_boundary || !isalnum(*line))
8178 line++;
8180 if (!state->added_changes_commits && opt_show_changes && opt_is_inside_work_tree)
8181 main_add_changes_commits(view, state, line);
8182 else
8183 main_flush_commit(view, commit);
8185 main_register_commit(view, &state->current, line, is_boundary);
8186 return TRUE;
8189 if (!*commit->id)
8190 return TRUE;
8192 /* Empty line separates the commit header from the log itself. */
8193 if (*line == '\0')
8194 state->in_header = FALSE;
8196 switch (type) {
8197 case LINE_PP_REFLOG:
8198 if (!main_add_reflog(view, state, line + STRING_SIZE("Reflog: ")))
8199 return FALSE;
8200 break;
8202 case LINE_PP_REFLOGMSG:
8203 line += STRING_SIZE("Reflog message: ");
8204 string_ncopy(state->reflogmsg, line, strlen(line));
8205 break;
8207 case LINE_PARENT:
8208 if (state->with_graph && !graph->has_parents)
8209 graph_add_parent(graph, line + STRING_SIZE("parent "));
8210 break;
8212 case LINE_AUTHOR:
8213 parse_author_line(line + STRING_SIZE("author "),
8214 &commit->author, &commit->time);
8215 if (state->with_graph)
8216 graph_render_parents(graph);
8217 break;
8219 default:
8220 /* Fill in the commit title if it has not already been set. */
8221 if (*commit->title)
8222 break;
8224 /* Skip lines in the commit header. */
8225 if (state->in_header)
8226 break;
8228 /* Require titles to start with a non-space character at the
8229 * offset used by git log. */
8230 if (strncmp(line, " ", 4))
8231 break;
8232 line += 4;
8233 /* Well, if the title starts with a whitespace character,
8234 * try to be forgiving. Otherwise we end up with no title. */
8235 while (isspace(*line))
8236 line++;
8237 if (*line == '\0')
8238 break;
8239 if (*state->reflogmsg)
8240 line = state->reflogmsg;
8241 main_add_commit(view, LINE_MAIN_COMMIT, commit, line, FALSE);
8244 return TRUE;
8247 static enum request
8248 main_request(struct view *view, enum request request, struct line *line)
8250 enum open_flags flags = (view_is_displayed(view) && request != REQ_VIEW_DIFF)
8251 ? OPEN_SPLIT : OPEN_DEFAULT;
8253 switch (request) {
8254 case REQ_NEXT:
8255 case REQ_PREVIOUS:
8256 if (view_is_displayed(view) && display[0] != view)
8257 return request;
8258 /* Do not pass navigation requests to the branch view
8259 * when the main view is maximized. (GH #38) */
8260 return request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
8262 case REQ_VIEW_DIFF:
8263 case REQ_ENTER:
8264 if (view_is_displayed(view) && display[0] != view)
8265 maximize_view(view, TRUE);
8267 if (line->type == LINE_STAT_UNSTAGED
8268 || line->type == LINE_STAT_STAGED) {
8269 struct view *diff = VIEW(REQ_VIEW_DIFF);
8270 const char *diff_staged_argv[] = {
8271 GIT_DIFF_STAGED(encoding_arg,
8272 opt_diff_context_arg,
8273 opt_ignore_space_arg, NULL, NULL)
8275 const char *diff_unstaged_argv[] = {
8276 GIT_DIFF_UNSTAGED(encoding_arg,
8277 opt_diff_context_arg,
8278 opt_ignore_space_arg, NULL, NULL)
8280 const char **diff_argv = line->type == LINE_STAT_STAGED
8281 ? diff_staged_argv : diff_unstaged_argv;
8283 open_argv(view, diff, diff_argv, NULL, flags);
8284 break;
8287 open_view(view, REQ_VIEW_DIFF, flags);
8288 break;
8290 case REQ_REFRESH:
8291 load_refs(TRUE);
8292 refresh_view(view);
8293 break;
8295 case REQ_JUMP_COMMIT:
8297 int lineno;
8299 for (lineno = 0; lineno < view->lines; lineno++) {
8300 struct commit *commit = view->line[lineno].data;
8302 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
8303 select_view_line(view, lineno);
8304 report_clear();
8305 return REQ_NONE;
8309 report("Unable to find commit '%s'", opt_search);
8310 break;
8312 default:
8313 return request;
8316 return REQ_NONE;
8319 static bool
8320 grep_refs(struct line *line, struct commit *commit, regex_t *regex)
8322 struct ref_list *list;
8323 regmatch_t pmatch;
8324 size_t i;
8326 if (!opt_show_refs || !(list = main_get_commit_refs(line, commit)))
8327 return FALSE;
8329 for (i = 0; i < list->size; i++) {
8330 if (!regexec(regex, list->refs[i]->name, 1, &pmatch, 0))
8331 return TRUE;
8334 return FALSE;
8337 static bool
8338 main_grep(struct view *view, struct line *line)
8340 struct commit *commit = line->data;
8341 const char *text[] = {
8342 commit->id,
8343 commit->title,
8344 mkauthor(commit->author, opt_author_width, opt_author),
8345 mkdate(&commit->time, opt_date),
8346 NULL
8349 return grep_text(view, text) || grep_refs(line, commit, view->regex);
8352 static void
8353 main_select(struct view *view, struct line *line)
8355 struct commit *commit = line->data;
8357 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED)
8358 string_ncopy(view->ref, commit->title, strlen(commit->title));
8359 else
8360 string_copy_rev(view->ref, commit->id);
8361 string_copy_rev(ref_commit, commit->id);
8364 static struct view_ops main_ops = {
8365 "commit",
8366 { "main" },
8367 VIEW_SEND_CHILD_ENTER | VIEW_FILE_FILTER | VIEW_LOG_LIKE,
8368 sizeof(struct main_state),
8369 main_open,
8370 main_read,
8371 main_draw,
8372 main_request,
8373 main_grep,
8374 main_select,
8375 main_done,
8378 static bool
8379 stash_open(struct view *view, enum open_flags flags)
8381 static const char *stash_argv[] = { "git", "stash", "list",
8382 encoding_arg, "--no-color", "--pretty=raw", NULL };
8383 struct main_state *state = view->private;
8385 state->added_changes_commits = TRUE;
8386 state->with_graph = FALSE;
8387 return begin_update(view, NULL, stash_argv, flags | OPEN_RELOAD);
8390 static void
8391 stash_select(struct view *view, struct line *line)
8393 main_select(view, line);
8394 string_format(ref_stash, "stash@{%d}", line->lineno - 1);
8395 string_copy(view->ref, ref_stash);
8398 static struct view_ops stash_ops = {
8399 "stash",
8400 { "stash" },
8401 VIEW_SEND_CHILD_ENTER,
8402 sizeof(struct main_state),
8403 stash_open,
8404 main_read,
8405 main_draw,
8406 main_request,
8407 main_grep,
8408 stash_select,
8412 * Status management
8415 /* Whether or not the curses interface has been initialized. */
8416 static bool cursed = FALSE;
8418 /* Terminal hacks and workarounds. */
8419 static bool use_scroll_redrawwin;
8420 static bool use_scroll_status_wclear;
8422 /* The status window is used for polling keystrokes. */
8423 static WINDOW *status_win;
8425 /* Reading from the prompt? */
8426 static bool input_mode = FALSE;
8428 static bool status_empty = FALSE;
8430 /* Update status and title window. */
8431 static void
8432 report(const char *msg, ...)
8434 struct view *view = display[current_view];
8436 if (input_mode)
8437 return;
8439 if (!view) {
8440 char buf[SIZEOF_STR];
8441 int retval;
8443 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
8444 die("%s", buf);
8447 if (!status_empty || *msg) {
8448 va_list args;
8450 va_start(args, msg);
8452 wmove(status_win, 0, 0);
8453 if (view->has_scrolled && use_scroll_status_wclear)
8454 wclear(status_win);
8455 if (*msg) {
8456 vwprintw(status_win, msg, args);
8457 status_empty = FALSE;
8458 } else {
8459 status_empty = TRUE;
8461 wclrtoeol(status_win);
8462 wnoutrefresh(status_win);
8464 va_end(args);
8467 update_view_title(view);
8470 static void
8471 done_display(void)
8473 endwin();
8476 static void
8477 init_display(void)
8479 const char *term;
8480 int x, y;
8482 die_callback = done_display;
8484 /* Initialize the curses library */
8485 if (isatty(STDIN_FILENO)) {
8486 cursed = !!initscr();
8487 opt_tty = stdin;
8488 } else {
8489 /* Leave stdin and stdout alone when acting as a pager. */
8490 opt_tty = fopen("/dev/tty", "r+");
8491 if (!opt_tty)
8492 die("Failed to open /dev/tty");
8493 cursed = !!newterm(NULL, opt_tty, opt_tty);
8496 if (!cursed)
8497 die("Failed to initialize curses");
8499 nonl(); /* Disable conversion and detect newlines from input. */
8500 cbreak(); /* Take input chars one at a time, no wait for \n */
8501 noecho(); /* Don't echo input */
8502 leaveok(stdscr, FALSE);
8504 if (has_colors())
8505 init_colors();
8507 getmaxyx(stdscr, y, x);
8508 status_win = newwin(1, x, y - 1, 0);
8509 if (!status_win)
8510 die("Failed to create status window");
8512 /* Enable keyboard mapping */
8513 keypad(status_win, TRUE);
8514 wbkgdset(status_win, get_line_attr(LINE_STATUS));
8516 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
8517 set_tabsize(opt_tab_size);
8518 #else
8519 TABSIZE = opt_tab_size;
8520 #endif
8522 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
8523 if (term && !strcmp(term, "gnome-terminal")) {
8524 /* In the gnome-terminal-emulator, the message from
8525 * scrolling up one line when impossible followed by
8526 * scrolling down one line causes corruption of the
8527 * status line. This is fixed by calling wclear. */
8528 use_scroll_status_wclear = TRUE;
8529 use_scroll_redrawwin = FALSE;
8531 } else if (term && !strcmp(term, "xrvt-xpm")) {
8532 /* No problems with full optimizations in xrvt-(unicode)
8533 * and aterm. */
8534 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
8536 } else {
8537 /* When scrolling in (u)xterm the last line in the
8538 * scrolling direction will update slowly. */
8539 use_scroll_redrawwin = TRUE;
8540 use_scroll_status_wclear = FALSE;
8544 static int
8545 get_input(int prompt_position)
8547 struct view *view;
8548 int i, key, cursor_y, cursor_x;
8550 if (prompt_position)
8551 input_mode = TRUE;
8553 while (TRUE) {
8554 bool loading = FALSE;
8556 foreach_view (view, i) {
8557 update_view(view);
8558 if (view_is_displayed(view) && view->has_scrolled &&
8559 use_scroll_redrawwin)
8560 redrawwin(view->win);
8561 view->has_scrolled = FALSE;
8562 if (view->pipe)
8563 loading = TRUE;
8566 /* Update the cursor position. */
8567 if (prompt_position) {
8568 getbegyx(status_win, cursor_y, cursor_x);
8569 cursor_x = prompt_position;
8570 } else {
8571 view = display[current_view];
8572 getbegyx(view->win, cursor_y, cursor_x);
8573 cursor_x = view->width - 1;
8574 cursor_y += view->pos.lineno - view->pos.offset;
8576 setsyx(cursor_y, cursor_x);
8578 /* Refresh, accept single keystroke of input */
8579 doupdate();
8580 nodelay(status_win, loading);
8581 key = wgetch(status_win);
8583 /* wgetch() with nodelay() enabled returns ERR when
8584 * there's no input. */
8585 if (key == ERR) {
8587 } else if (key == KEY_RESIZE) {
8588 int height, width;
8590 getmaxyx(stdscr, height, width);
8592 wresize(status_win, 1, width);
8593 mvwin(status_win, height - 1, 0);
8594 wnoutrefresh(status_win);
8595 resize_display();
8596 redraw_display(TRUE);
8598 } else {
8599 input_mode = FALSE;
8600 if (key == erasechar())
8601 key = KEY_BACKSPACE;
8602 return key;
8607 static char *
8608 prompt_input(const char *prompt, input_handler handler, void *data)
8610 enum input_status status = INPUT_OK;
8611 static char buf[SIZEOF_STR];
8612 size_t pos = 0;
8614 buf[pos] = 0;
8616 while (status == INPUT_OK || status == INPUT_SKIP) {
8617 int key;
8619 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
8620 wclrtoeol(status_win);
8622 key = get_input(pos + 1);
8623 switch (key) {
8624 case KEY_RETURN:
8625 case KEY_ENTER:
8626 case '\n':
8627 status = pos ? INPUT_STOP : INPUT_CANCEL;
8628 break;
8630 case KEY_BACKSPACE:
8631 if (pos > 0)
8632 buf[--pos] = 0;
8633 else
8634 status = INPUT_CANCEL;
8635 break;
8637 case KEY_ESC:
8638 status = INPUT_CANCEL;
8639 break;
8641 default:
8642 if (pos >= sizeof(buf)) {
8643 report("Input string too long");
8644 return NULL;
8647 status = handler(data, buf, key);
8648 if (status == INPUT_OK)
8649 buf[pos++] = (char) key;
8653 /* Clear the status window */
8654 status_empty = FALSE;
8655 report_clear();
8657 if (status == INPUT_CANCEL)
8658 return NULL;
8660 buf[pos++] = 0;
8662 return buf;
8665 static enum input_status
8666 prompt_yesno_handler(void *data, char *buf, int c)
8668 if (c == 'y' || c == 'Y')
8669 return INPUT_STOP;
8670 if (c == 'n' || c == 'N')
8671 return INPUT_CANCEL;
8672 return INPUT_SKIP;
8675 static bool
8676 prompt_yesno(const char *prompt)
8678 char prompt2[SIZEOF_STR];
8680 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
8681 return FALSE;
8683 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
8686 static enum input_status
8687 read_prompt_handler(void *data, char *buf, int c)
8689 return isprint(c) ? INPUT_OK : INPUT_SKIP;
8692 static char *
8693 read_prompt(const char *prompt)
8695 return prompt_input(prompt, read_prompt_handler, NULL);
8698 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
8700 enum input_status status = INPUT_OK;
8701 int size = 0;
8703 while (items[size].text)
8704 size++;
8706 assert(size > 0);
8708 while (status == INPUT_OK) {
8709 const struct menu_item *item = &items[*selected];
8710 int key;
8711 int i;
8713 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
8714 prompt, *selected + 1, size);
8715 if (item->hotkey)
8716 wprintw(status_win, "[%c] ", (char) item->hotkey);
8717 wprintw(status_win, "%s", item->text);
8718 wclrtoeol(status_win);
8720 key = get_input(COLS - 1);
8721 switch (key) {
8722 case KEY_RETURN:
8723 case KEY_ENTER:
8724 case '\n':
8725 status = INPUT_STOP;
8726 break;
8728 case KEY_LEFT:
8729 case KEY_UP:
8730 *selected = *selected - 1;
8731 if (*selected < 0)
8732 *selected = size - 1;
8733 break;
8735 case KEY_RIGHT:
8736 case KEY_DOWN:
8737 *selected = (*selected + 1) % size;
8738 break;
8740 case KEY_ESC:
8741 status = INPUT_CANCEL;
8742 break;
8744 default:
8745 for (i = 0; items[i].text; i++)
8746 if (items[i].hotkey == key) {
8747 *selected = i;
8748 status = INPUT_STOP;
8749 break;
8754 /* Clear the status window */
8755 status_empty = FALSE;
8756 report_clear();
8758 return status != INPUT_CANCEL;
8762 * Repository properties
8766 static void
8767 set_remote_branch(const char *name, const char *value, size_t valuelen)
8769 if (!strcmp(name, ".remote")) {
8770 string_ncopy(opt_remote, value, valuelen);
8772 } else if (*opt_remote && !strcmp(name, ".merge")) {
8773 size_t from = strlen(opt_remote);
8775 if (!prefixcmp(value, "refs/heads/"))
8776 value += STRING_SIZE("refs/heads/");
8778 if (!string_format_from(opt_remote, &from, "/%s", value))
8779 opt_remote[0] = 0;
8783 static void
8784 set_repo_config_option(char *name, char *value, enum status_code (*cmd)(int, const char **))
8786 const char *argv[SIZEOF_ARG] = { name, "=" };
8787 int argc = 1 + (cmd == option_set_command);
8788 enum status_code error;
8790 if (!argv_from_string(argv, &argc, value))
8791 error = ERROR_TOO_MANY_OPTION_ARGUMENTS;
8792 else
8793 error = cmd(argc, argv);
8795 if (error != SUCCESS)
8796 warn("Option 'tig.%s': %s", name, get_status_message(error));
8799 static void
8800 set_work_tree(const char *value)
8802 char cwd[SIZEOF_STR];
8804 if (!getcwd(cwd, sizeof(cwd)))
8805 die("Failed to get cwd path: %s", strerror(errno));
8806 if (chdir(cwd) < 0)
8807 die("Failed to chdir(%s): %s", cwd, strerror(errno));
8808 if (chdir(opt_git_dir) < 0)
8809 die("Failed to chdir(%s): %s", opt_git_dir, strerror(errno));
8810 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
8811 die("Failed to get git path: %s", strerror(errno));
8812 if (chdir(value) < 0)
8813 die("Failed to chdir(%s): %s", value, strerror(errno));
8814 if (!getcwd(cwd, sizeof(cwd)))
8815 die("Failed to get cwd path: %s", strerror(errno));
8816 if (setenv("GIT_WORK_TREE", cwd, TRUE))
8817 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
8818 if (setenv("GIT_DIR", opt_git_dir, TRUE))
8819 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
8820 opt_is_inside_work_tree = TRUE;
8823 static void
8824 parse_git_color_option(enum line_type type, char *value)
8826 struct line_info *info = &line_info[type];
8827 const char *argv[SIZEOF_ARG];
8828 int argc = 0;
8829 bool first_color = TRUE;
8830 int i;
8832 if (!argv_from_string(argv, &argc, value))
8833 return;
8835 info->fg = COLOR_DEFAULT;
8836 info->bg = COLOR_DEFAULT;
8837 info->attr = 0;
8839 for (i = 0; i < argc; i++) {
8840 int attr = 0;
8842 if (set_attribute(&attr, argv[i])) {
8843 info->attr |= attr;
8845 } else if (set_color(&attr, argv[i])) {
8846 if (first_color)
8847 info->fg = attr;
8848 else
8849 info->bg = attr;
8850 first_color = FALSE;
8855 static void
8856 set_git_color_option(const char *name, char *value)
8858 static const struct enum_map color_option_map[] = {
8859 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
8860 ENUM_MAP("branch.local", LINE_MAIN_REF),
8861 ENUM_MAP("branch.plain", LINE_MAIN_REF),
8862 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
8864 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
8865 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
8866 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
8867 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
8868 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
8869 ENUM_MAP("diff.old", LINE_DIFF_DEL),
8870 ENUM_MAP("diff.new", LINE_DIFF_ADD),
8872 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
8874 ENUM_MAP("status.branch", LINE_STAT_HEAD),
8875 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
8876 ENUM_MAP("status.added", LINE_STAT_STAGED),
8877 ENUM_MAP("status.updated", LINE_STAT_STAGED),
8878 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
8879 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
8882 int type = LINE_NONE;
8884 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
8885 parse_git_color_option(type, value);
8889 static void
8890 set_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
8892 if (parse_encoding(encoding_ref, arg, priority) == SUCCESS)
8893 encoding_arg[0] = 0;
8896 static int
8897 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8899 if (!strcmp(name, "i18n.commitencoding"))
8900 set_encoding(&default_encoding, value, FALSE);
8902 else if (!strcmp(name, "gui.encoding"))
8903 set_encoding(&default_encoding, value, TRUE);
8905 else if (!strcmp(name, "core.editor"))
8906 string_ncopy(opt_editor, value, valuelen);
8908 else if (!strcmp(name, "core.worktree"))
8909 set_work_tree(value);
8911 else if (!strcmp(name, "core.abbrev"))
8912 parse_id(&opt_id_cols, value);
8914 else if (!prefixcmp(name, "tig.color."))
8915 set_repo_config_option(name + 10, value, option_color_command);
8917 else if (!prefixcmp(name, "tig.bind."))
8918 set_repo_config_option(name + 9, value, option_bind_command);
8920 else if (!prefixcmp(name, "tig."))
8921 set_repo_config_option(name + 4, value, option_set_command);
8923 else if (!prefixcmp(name, "color."))
8924 set_git_color_option(name + STRING_SIZE("color."), value);
8926 else if (*opt_head && !prefixcmp(name, "branch.") &&
8927 !strncmp(name + 7, opt_head, strlen(opt_head)))
8928 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
8930 return OK;
8933 static int
8934 load_git_config(void)
8936 const char *config_list_argv[] = { "git", "config", "--list", NULL };
8938 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
8941 #define REPO_INFO_GIT_DIR "--git-dir"
8942 #define REPO_INFO_WORK_TREE "--is-inside-work-tree"
8943 #define REPO_INFO_SHOW_CDUP "--show-cdup"
8944 #define REPO_INFO_SHOW_PREFIX "--show-prefix"
8945 #define REPO_INFO_SYMBOLIC_HEAD "--symbolic-full-name"
8946 #define REPO_INFO_RESOLVED_HEAD "HEAD"
8948 struct repo_info_state {
8949 const char **argv;
8950 char head_id[SIZEOF_REV];
8953 static int
8954 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8956 struct repo_info_state *state = data;
8957 const char *arg = *state->argv ? *state->argv++ : "";
8959 if (!strcmp(arg, REPO_INFO_GIT_DIR)) {
8960 string_ncopy(opt_git_dir, name, namelen);
8962 } else if (!strcmp(arg, REPO_INFO_WORK_TREE)) {
8963 /* This can be 3 different values depending on the
8964 * version of git being used. If git-rev-parse does not
8965 * understand --is-inside-work-tree it will simply echo
8966 * the option else either "true" or "false" is printed.
8967 * Default to true for the unknown case. */
8968 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
8970 } else if (!strcmp(arg, REPO_INFO_SHOW_CDUP)) {
8971 string_ncopy(opt_cdup, name, namelen);
8973 } else if (!strcmp(arg, REPO_INFO_SHOW_PREFIX)) {
8974 string_ncopy(opt_prefix, name, namelen);
8976 } else if (!strcmp(arg, REPO_INFO_RESOLVED_HEAD)) {
8977 string_ncopy(state->head_id, name, namelen);
8979 } else if (!strcmp(arg, REPO_INFO_SYMBOLIC_HEAD)) {
8980 if (!prefixcmp(name, "refs/heads/")) {
8981 char *offset = name + STRING_SIZE("refs/heads/");
8983 string_ncopy(opt_head, offset, strlen(offset) + 1);
8984 add_ref(state->head_id, name, opt_remote, opt_head);
8986 state->argv++;
8989 return OK;
8992 static int
8993 load_repo_info(void)
8995 const char *rev_parse_argv[] = {
8996 "git", "rev-parse", REPO_INFO_GIT_DIR, REPO_INFO_WORK_TREE,
8997 REPO_INFO_SHOW_CDUP, REPO_INFO_SHOW_PREFIX, \
8998 REPO_INFO_RESOLVED_HEAD, REPO_INFO_SYMBOLIC_HEAD, "HEAD",
8999 NULL
9001 struct repo_info_state state = { rev_parse_argv + 2 };
9003 return io_run_load(rev_parse_argv, "=", read_repo_info, &state);
9008 * Main
9011 static const char usage[] =
9012 "tig " TIG_VERSION " (" __DATE__ ")\n"
9013 "\n"
9014 "Usage: tig [options] [revs] [--] [paths]\n"
9015 " or: tig log [options] [revs] [--] [paths]\n"
9016 " or: tig show [options] [revs] [--] [paths]\n"
9017 " or: tig blame [options] [rev] [--] path\n"
9018 " or: tig stash\n"
9019 " or: tig status\n"
9020 " or: tig < [git command output]\n"
9021 "\n"
9022 "Options:\n"
9023 " +<number> Select line <number> in the first view\n"
9024 " -v, --version Show version and exit\n"
9025 " -h, --help Show help message and exit";
9027 static void TIG_NORETURN
9028 quit(int sig)
9030 if (sig)
9031 signal(sig, SIG_DFL);
9033 /* XXX: Restore tty modes and let the OS cleanup the rest! */
9034 if (cursed)
9035 endwin();
9036 exit(0);
9039 static int
9040 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
9042 const char ***filter_args = data;
9044 return argv_append(filter_args, name) ? OK : ERR;
9047 static void
9048 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
9050 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
9051 const char **all_argv = NULL;
9053 if (!argv_append_array(&all_argv, rev_parse_argv) ||
9054 !argv_append_array(&all_argv, argv) ||
9055 io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
9056 die("Failed to split arguments");
9057 argv_free(all_argv);
9058 free(all_argv);
9061 static bool
9062 is_rev_flag(const char *flag)
9064 static const char *rev_flags[] = { GIT_REV_FLAGS };
9065 int i;
9067 for (i = 0; i < ARRAY_SIZE(rev_flags); i++)
9068 if (!strcmp(flag, rev_flags[i]))
9069 return TRUE;
9071 return FALSE;
9074 static void
9075 filter_options(const char *argv[], bool blame)
9077 const char **flags = NULL;
9079 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
9080 filter_rev_parse(&flags, "--flags", "--no-revs", argv);
9082 if (flags) {
9083 int next, flags_pos;
9085 for (next = flags_pos = 0; flags && flags[next]; next++) {
9086 const char *flag = flags[next];
9088 if (is_rev_flag(flag))
9089 argv_append(&opt_rev_argv, flag);
9090 else
9091 flags[flags_pos++] = flag;
9094 flags[flags_pos] = NULL;
9096 if (blame)
9097 opt_blame_argv = flags;
9098 else
9099 opt_diff_argv = flags;
9102 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
9105 static enum request
9106 parse_options(int argc, const char *argv[], bool pager_mode)
9108 enum request request;
9109 const char *subcommand;
9110 bool seen_dashdash = FALSE;
9111 const char **filter_argv = NULL;
9112 int i;
9114 request = pager_mode ? REQ_VIEW_PAGER : REQ_VIEW_MAIN;
9116 if (argc <= 1)
9117 return request;
9119 subcommand = argv[1];
9120 if (!strcmp(subcommand, "status")) {
9121 request = REQ_VIEW_STATUS;
9123 } else if (!strcmp(subcommand, "blame")) {
9124 request = REQ_VIEW_BLAME;
9126 } else if (!strcmp(subcommand, "show")) {
9127 request = REQ_VIEW_DIFF;
9129 } else if (!strcmp(subcommand, "log")) {
9130 request = REQ_VIEW_LOG;
9132 } else if (!strcmp(subcommand, "stash")) {
9133 request = REQ_VIEW_STASH;
9135 } else {
9136 subcommand = NULL;
9139 for (i = 1 + !!subcommand; i < argc; i++) {
9140 const char *opt = argv[i];
9142 // stop parsing our options after -- and let rev-parse handle the rest
9143 if (!seen_dashdash) {
9144 if (!strcmp(opt, "--")) {
9145 seen_dashdash = TRUE;
9146 continue;
9148 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
9149 printf("tig version %s\n", TIG_VERSION);
9150 quit(0);
9152 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
9153 printf("%s\n", usage);
9154 quit(0);
9156 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
9157 opt_lineno = atoi(opt + 1);
9158 continue;
9163 if (!argv_append(&filter_argv, opt))
9164 die("command too long");
9167 if (filter_argv)
9168 filter_options(filter_argv, request == REQ_VIEW_BLAME);
9170 /* Finish validating and setting up blame options */
9171 if (request == REQ_VIEW_BLAME) {
9172 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
9173 die("invalid number of options to blame\n\n%s", usage);
9175 if (opt_rev_argv) {
9176 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
9179 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
9182 return request;
9185 static enum request
9186 open_pager_mode(enum request request)
9188 enum open_flags flags = OPEN_DEFAULT;
9190 if (request == REQ_VIEW_PAGER) {
9191 /* Detect if the user requested the main view. */
9192 if (argv_contains(opt_rev_argv, "--stdin")) {
9193 request = REQ_VIEW_MAIN;
9194 flags |= OPEN_FORWARD_STDIN;
9195 } else if (argv_contains(opt_diff_argv, "--pretty=raw")) {
9196 request = REQ_VIEW_MAIN;
9197 flags |= OPEN_STDIN;
9198 } else {
9199 flags |= OPEN_STDIN;
9202 } else if (request == REQ_VIEW_DIFF) {
9203 if (argv_contains(opt_rev_argv, "--stdin"))
9204 flags |= OPEN_FORWARD_STDIN;
9207 /* Open the requested view even if the pager mode is enabled so
9208 * the warning message below is displayed correctly. */
9209 open_view(NULL, request, flags);
9211 if (!open_in_pager_mode(flags)) {
9212 close(STDIN_FILENO);
9213 report("Ignoring stdin.");
9216 return REQ_NONE;
9219 static enum request
9220 run_prompt_command(struct view *view, char *cmd) {
9221 enum request request;
9223 if (cmd && string_isnumber(cmd)) {
9224 int lineno = view->pos.lineno + 1;
9226 if (parse_int(&lineno, cmd, 1, view->lines + 1) == SUCCESS) {
9227 select_view_line(view, lineno - 1);
9228 report_clear();
9229 } else {
9230 report("Unable to parse '%s' as a line number", cmd);
9232 } else if (cmd && iscommit(cmd)) {
9233 string_ncopy(opt_search, cmd, strlen(cmd));
9235 request = view_request(view, REQ_JUMP_COMMIT);
9236 if (request == REQ_JUMP_COMMIT) {
9237 report("Jumping to commits is not supported by the '%s' view", view->name);
9240 } else if (cmd && strlen(cmd) == 1) {
9241 request = get_keybinding(&view->ops->keymap, cmd[0]);
9242 return request;
9244 } else if (cmd && cmd[0] == '!') {
9245 struct view *next = VIEW(REQ_VIEW_PAGER);
9246 const char *argv[SIZEOF_ARG];
9247 int argc = 0;
9249 cmd++;
9250 /* When running random commands, initially show the
9251 * command in the title. However, it maybe later be
9252 * overwritten if a commit line is selected. */
9253 string_ncopy(next->ref, cmd, strlen(cmd));
9255 if (!argv_from_string(argv, &argc, cmd)) {
9256 report("Too many arguments");
9257 } else if (!format_argv(view, &next->argv, argv, FALSE, TRUE)) {
9258 report("Argument formatting failed");
9259 } else {
9260 next->dir = NULL;
9261 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
9264 } else if (cmd) {
9265 request = get_request(cmd);
9266 if (request != REQ_UNKNOWN)
9267 return request;
9269 char *args = strchr(cmd, ' ');
9270 if (args) {
9271 *args++ = 0;
9272 if (set_option(cmd, args) == SUCCESS) {
9273 request = !view->unrefreshable ? REQ_REFRESH : REQ_SCREEN_REDRAW;
9274 if (!strcmp(cmd, "color"))
9275 init_colors();
9278 return request;
9280 return REQ_NONE;
9284 main(int argc, const char *argv[])
9286 const char *codeset = ENCODING_UTF8;
9287 bool pager_mode = !isatty(STDIN_FILENO);
9288 enum request request = parse_options(argc, argv, pager_mode);
9289 struct view *view;
9290 int i;
9292 signal(SIGINT, quit);
9293 signal(SIGQUIT, quit);
9294 signal(SIGPIPE, SIG_IGN);
9296 if (setlocale(LC_ALL, "")) {
9297 codeset = nl_langinfo(CODESET);
9300 foreach_view(view, i) {
9301 add_keymap(&view->ops->keymap);
9304 if (load_repo_info() == ERR)
9305 die("Failed to load repo info.");
9307 if (load_options() == ERR)
9308 die("Failed to load user config.");
9310 if (load_git_config() == ERR)
9311 die("Failed to load repo config.");
9313 /* Require a git repository unless when running in pager mode. */
9314 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
9315 die("Not a git repository");
9317 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
9318 char translit[SIZEOF_STR];
9320 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
9321 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
9322 else
9323 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
9324 if (opt_iconv_out == ICONV_NONE)
9325 die("Failed to initialize character set conversion");
9328 if (load_refs(FALSE) == ERR)
9329 die("Failed to load refs.");
9331 init_display();
9333 if (pager_mode)
9334 request = open_pager_mode(request);
9336 while (view_driver(display[current_view], request)) {
9337 int key = get_input(0);
9339 if (key == KEY_ESC)
9340 key = get_input(0) + 0x80;
9342 view = display[current_view];
9343 request = get_keybinding(&view->ops->keymap, key);
9345 /* Some low-level request handling. This keeps access to
9346 * status_win restricted. */
9347 switch (request) {
9348 case REQ_NONE:
9349 report("Unknown key, press %s for help",
9350 get_view_key(view, REQ_VIEW_HELP));
9351 break;
9352 case REQ_PROMPT:
9354 char *cmd = read_prompt(":");
9355 request = run_prompt_command(view, cmd);
9356 break;
9358 case REQ_SEARCH:
9359 case REQ_SEARCH_BACK:
9361 const char *prompt = request == REQ_SEARCH ? "/" : "?";
9362 char *search = read_prompt(prompt);
9364 if (search)
9365 string_ncopy(opt_search, search, strlen(search));
9366 else if (*opt_search)
9367 request = request == REQ_SEARCH ?
9368 REQ_FIND_NEXT :
9369 REQ_FIND_PREV;
9370 else
9371 request = REQ_NONE;
9372 break;
9374 default:
9375 break;
9379 quit(0);
9381 return 0;
9384 /* vim: set ts=8 sw=8 noexpandtab: */