Add common utility for parsing chunk headers
[tig.git] / tig.c
blob0b001c99273c57fdeb5c256268bb55cab9c36f02
1 /* Copyright (c) 2006-2013 Jonas Fonseca <fonseca@diku.dk>
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU General Public License as
5 * published by the Free Software Foundation; either version 2 of
6 * the License, or (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
14 #define WARN_MISSING_CURSES_CONFIGURATION
16 #include "tig.h"
17 #include "util.h"
18 #include "io.h"
19 #include "refs.h"
20 #include "graph.h"
21 #include "git.h"
23 static void report(const char *msg, ...) PRINTF_LIKE(1, 2);
24 #define report_clear() report("%s", "")
27 enum input_status {
28 INPUT_OK,
29 INPUT_SKIP,
30 INPUT_STOP,
31 INPUT_CANCEL
34 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
36 static char *prompt_input(const char *prompt, input_handler handler, void *data);
37 static bool prompt_yesno(const char *prompt);
38 static char *read_prompt(const char *prompt);
40 struct menu_item {
41 int hotkey;
42 const char *text;
43 void *data;
46 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
48 #define GRAPHIC_ENUM(_) \
49 _(GRAPHIC, ASCII), \
50 _(GRAPHIC, DEFAULT), \
51 _(GRAPHIC, UTF_8)
53 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
55 #define DATE_ENUM(_) \
56 _(DATE, NO), \
57 _(DATE, DEFAULT), \
58 _(DATE, LOCAL), \
59 _(DATE, RELATIVE), \
60 _(DATE, SHORT)
62 DEFINE_ENUM(date, DATE_ENUM);
64 struct time {
65 time_t sec;
66 int tz;
69 static inline int timecmp(const struct time *t1, const struct time *t2)
71 return t1->sec - t2->sec;
74 static const char *
75 mkdate(const struct time *time, enum date date)
77 static char buf[DATE_WIDTH + 1];
78 static const struct enum_map reldate[] = {
79 { "second", 1, 60 * 2 },
80 { "minute", 60, 60 * 60 * 2 },
81 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
82 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
83 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
84 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 365 },
85 { "year", 60 * 60 * 24 * 365, 0 },
87 struct tm tm;
89 if (!date || !time || !time->sec)
90 return "";
92 if (date == DATE_RELATIVE) {
93 struct timeval now;
94 time_t date = time->sec + time->tz;
95 time_t seconds;
96 int i;
98 gettimeofday(&now, NULL);
99 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
100 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
101 if (seconds >= reldate[i].value && reldate[i].value)
102 continue;
104 seconds /= reldate[i].namelen;
105 if (!string_format(buf, "%ld %s%s %s",
106 seconds, reldate[i].name,
107 seconds > 1 ? "s" : "",
108 now.tv_sec >= date ? "ago" : "ahead"))
109 break;
110 return buf;
114 if (date == DATE_LOCAL) {
115 time_t date = time->sec + time->tz;
116 localtime_r(&date, &tm);
118 else {
119 gmtime_r(&time->sec, &tm);
121 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
124 #define FILE_SIZE_ENUM(_) \
125 _(FILE_SIZE, NO), \
126 _(FILE_SIZE, DEFAULT), \
127 _(FILE_SIZE, UNITS)
129 DEFINE_ENUM(file_size, FILE_SIZE_ENUM);
131 static const char *
132 mkfilesize(unsigned long size, enum file_size format)
134 static char buf[64 + 1];
135 static const char relsize[] = {
136 'B', 'K', 'M', 'G', 'T', 'P'
139 if (!format)
140 return "";
142 if (format == FILE_SIZE_UNITS) {
143 const char *fmt = "%.0f%c";
144 double rsize = size;
145 int i;
147 for (i = 0; i < ARRAY_SIZE(relsize); i++) {
148 if (rsize > 1024.0 && i + 1 < ARRAY_SIZE(relsize)) {
149 rsize /= 1024;
150 continue;
153 size = rsize * 10;
154 if (size % 10 > 0)
155 fmt = "%.1f%c";
157 return string_format(buf, fmt, rsize, relsize[i])
158 ? buf : NULL;
162 return string_format(buf, "%ld", size) ? buf : NULL;
165 #define AUTHOR_ENUM(_) \
166 _(AUTHOR, NO), \
167 _(AUTHOR, FULL), \
168 _(AUTHOR, ABBREVIATED), \
169 _(AUTHOR, EMAIL), \
170 _(AUTHOR, EMAIL_USER)
172 DEFINE_ENUM(author, AUTHOR_ENUM);
174 struct ident {
175 const char *name;
176 const char *email;
179 static const struct ident unknown_ident = { "Unknown", "unknown@localhost" };
181 static inline int
182 ident_compare(const struct ident *i1, const struct ident *i2)
184 if (!i1 || !i2)
185 return (!!i1) - (!!i2);
186 if (!i1->name || !i2->name)
187 return (!!i1->name) - (!!i2->name);
188 return strcmp(i1->name, i2->name);
191 static const char *
192 get_author_initials(const char *author)
194 static char initials[AUTHOR_WIDTH * 6 + 1];
195 size_t pos = 0;
196 const char *end = strchr(author, '\0');
198 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
200 memset(initials, 0, sizeof(initials));
201 while (author < end) {
202 unsigned char bytes;
203 size_t i;
205 while (author < end && is_initial_sep(*author))
206 author++;
208 bytes = utf8_char_length(author, end);
209 if (bytes >= sizeof(initials) - 1 - pos)
210 break;
211 while (bytes--) {
212 initials[pos++] = *author++;
215 i = pos;
216 while (author < end && !is_initial_sep(*author)) {
217 bytes = utf8_char_length(author, end);
218 if (bytes >= sizeof(initials) - 1 - i) {
219 while (author < end && !is_initial_sep(*author))
220 author++;
221 break;
223 while (bytes--) {
224 initials[i++] = *author++;
228 initials[i++] = 0;
231 return initials;
234 static const char *
235 get_email_user(const char *email)
237 static char user[AUTHOR_WIDTH * 6 + 1];
238 const char *end = strchr(email, '@');
239 int length = end ? end - email : strlen(email);
241 string_format(user, "%.*s%c", length, email, 0);
242 return user;
245 #define author_trim(cols) (cols == 0 || cols > 10)
247 static const char *
248 mkauthor(const struct ident *ident, int cols, enum author author)
250 bool trim = author_trim(cols);
251 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
253 if (author == AUTHOR_NO || !ident)
254 return "";
255 if (author == AUTHOR_EMAIL && ident->email)
256 return ident->email;
257 if (author == AUTHOR_EMAIL_USER && ident->email)
258 return get_email_user(ident->email);
259 if (abbreviate && ident->name)
260 return get_author_initials(ident->name);
261 return ident->name;
264 static const char *
265 mkmode(mode_t mode)
267 if (S_ISDIR(mode))
268 return "drwxr-xr-x";
269 else if (S_ISLNK(mode))
270 return "lrwxrwxrwx";
271 else if (S_ISGITLINK(mode))
272 return "m---------";
273 else if (S_ISREG(mode) && mode & S_IXUSR)
274 return "-rwxr-xr-x";
275 else if (S_ISREG(mode))
276 return "-rw-r--r--";
277 else
278 return "----------";
281 #define FILENAME_ENUM(_) \
282 _(FILENAME, NO), \
283 _(FILENAME, ALWAYS), \
284 _(FILENAME, AUTO)
286 DEFINE_ENUM(filename, FILENAME_ENUM);
288 #define IGNORE_SPACE_ENUM(_) \
289 _(IGNORE_SPACE, NO), \
290 _(IGNORE_SPACE, ALL), \
291 _(IGNORE_SPACE, SOME), \
292 _(IGNORE_SPACE, AT_EOL)
294 DEFINE_ENUM(ignore_space, IGNORE_SPACE_ENUM);
296 #define COMMIT_ORDER_ENUM(_) \
297 _(COMMIT_ORDER, DEFAULT), \
298 _(COMMIT_ORDER, TOPO), \
299 _(COMMIT_ORDER, DATE), \
300 _(COMMIT_ORDER, REVERSE)
302 DEFINE_ENUM(commit_order, COMMIT_ORDER_ENUM);
304 #define VIEW_INFO(_) \
305 _(MAIN, main, ref_head), \
306 _(DIFF, diff, ref_commit), \
307 _(LOG, log, ref_head), \
308 _(TREE, tree, ref_commit), \
309 _(BLOB, blob, ref_blob), \
310 _(BLAME, blame, ref_commit), \
311 _(BRANCH, branch, ref_head), \
312 _(HELP, help, ""), \
313 _(PAGER, pager, ""), \
314 _(STATUS, status, "status"), \
315 _(STAGE, stage, ref_status), \
316 _(STASH, stash, ref_stash)
319 * User requests
322 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
324 #define REQ_INFO \
325 REQ_GROUP("View switching") \
326 VIEW_INFO(VIEW_REQ), \
328 REQ_GROUP("View manipulation") \
329 REQ_(ENTER, "Enter current line and scroll"), \
330 REQ_(BACK, "Go back to the previous view state"), \
331 REQ_(NEXT, "Move to next"), \
332 REQ_(PREVIOUS, "Move to previous"), \
333 REQ_(PARENT, "Move to parent"), \
334 REQ_(VIEW_NEXT, "Move focus to next view"), \
335 REQ_(REFRESH, "Reload and refresh"), \
336 REQ_(MAXIMIZE, "Maximize the current view"), \
337 REQ_(VIEW_CLOSE, "Close the current view"), \
338 REQ_(QUIT, "Close all views and quit"), \
340 REQ_GROUP("View specific requests") \
341 REQ_(STATUS_UPDATE, "Update file status"), \
342 REQ_(STATUS_REVERT, "Revert file changes"), \
343 REQ_(STATUS_MERGE, "Merge file using external tool"), \
344 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
345 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
346 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
347 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
349 REQ_GROUP("Cursor navigation") \
350 REQ_(MOVE_UP, "Move cursor one line up"), \
351 REQ_(MOVE_DOWN, "Move cursor one line down"), \
352 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
353 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
354 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
355 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
357 REQ_GROUP("Scrolling") \
358 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
359 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
360 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
361 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
362 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
363 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
364 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
366 REQ_GROUP("Searching") \
367 REQ_(SEARCH, "Search the view"), \
368 REQ_(SEARCH_BACK, "Search backwards in the view"), \
369 REQ_(FIND_NEXT, "Find next search match"), \
370 REQ_(FIND_PREV, "Find previous search match"), \
372 REQ_GROUP("Option manipulation") \
373 REQ_(OPTIONS, "Open option menu"), \
374 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
375 REQ_(TOGGLE_DATE, "Toggle date display"), \
376 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
377 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
378 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
379 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
380 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
381 REQ_(TOGGLE_CHANGES, "Toggle local changes display in the main view"), \
382 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
383 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
384 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
385 REQ_(TOGGLE_COMMIT_ORDER, "Toggle commit ordering"), \
386 REQ_(TOGGLE_ID, "Toggle commit ID display"), \
387 REQ_(TOGGLE_FILES, "Toggle file filtering"), \
388 REQ_(TOGGLE_TITLE_OVERFLOW, "Toggle highlighting of commit title overflow"), \
389 REQ_(TOGGLE_FILE_SIZE, "Toggle file size format"), \
390 REQ_(TOGGLE_UNTRACKED_DIRS, "Toggle display of files in untracked directories"), \
392 REQ_GROUP("Misc") \
393 REQ_(PROMPT, "Bring up the prompt"), \
394 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
395 REQ_(SHOW_VERSION, "Show version information"), \
396 REQ_(STOP_LOADING, "Stop all loading views"), \
397 REQ_(EDIT, "Open in editor"), \
398 REQ_(NONE, "Do nothing")
401 /* User action requests. */
402 enum request {
403 #define REQ_GROUP(help)
404 #define REQ_(req, help) REQ_##req
406 /* Offset all requests to avoid conflicts with ncurses getch values. */
407 REQ_UNKNOWN = KEY_MAX + 1,
408 REQ_OFFSET,
409 REQ_INFO,
411 /* Internal requests. */
412 REQ_JUMP_COMMIT,
414 #undef REQ_GROUP
415 #undef REQ_
418 struct request_info {
419 enum request request;
420 const char *name;
421 int namelen;
422 const char *help;
425 static const struct request_info req_info[] = {
426 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
427 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
428 REQ_INFO
429 #undef REQ_GROUP
430 #undef REQ_
433 static enum request
434 get_request(const char *name)
436 int namelen = strlen(name);
437 int i;
439 for (i = 0; i < ARRAY_SIZE(req_info); i++)
440 if (enum_equals(req_info[i], name, namelen))
441 return req_info[i].request;
443 return REQ_UNKNOWN;
448 * Options
451 /* Option and state variables. */
452 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
453 static enum date opt_date = DATE_DEFAULT;
454 static enum author opt_author = AUTHOR_FULL;
455 static enum filename opt_filename = FILENAME_AUTO;
456 static enum file_size opt_file_size = FILE_SIZE_DEFAULT;
457 static bool opt_rev_graph = TRUE;
458 static bool opt_line_number = FALSE;
459 static bool opt_show_refs = TRUE;
460 static bool opt_show_changes = TRUE;
461 static bool opt_untracked_dirs_content = TRUE;
462 static bool opt_read_git_colors = TRUE;
463 static bool opt_wrap_lines = FALSE;
464 static bool opt_ignore_case = FALSE;
465 static bool opt_focus_child = TRUE;
466 static int opt_diff_context = 3;
467 static char opt_diff_context_arg[9] = "";
468 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
469 static char opt_ignore_space_arg[22] = "";
470 static enum commit_order opt_commit_order = COMMIT_ORDER_DEFAULT;
471 static char opt_commit_order_arg[22] = "";
472 static bool opt_notes = TRUE;
473 static char opt_notes_arg[SIZEOF_STR] = "--show-notes";
474 static int opt_num_interval = 5;
475 static double opt_hscroll = 0.50;
476 static double opt_scale_split_view = 2.0 / 3.0;
477 static double opt_scale_vsplit_view = 0.5;
478 static bool opt_vsplit = FALSE;
479 static int opt_tab_size = 8;
480 static int opt_author_width = AUTHOR_WIDTH;
481 static int opt_filename_width = FILENAME_WIDTH;
482 static char opt_path[SIZEOF_STR] = "";
483 static char opt_file[SIZEOF_STR] = "";
484 static char opt_ref[SIZEOF_REF] = "";
485 static unsigned long opt_goto_line = 0;
486 static char opt_head[SIZEOF_REF] = "";
487 static char opt_remote[SIZEOF_REF] = "";
488 static iconv_t opt_iconv_out = ICONV_NONE;
489 static char opt_search[SIZEOF_STR] = "";
490 static char opt_cdup[SIZEOF_STR] = "";
491 static char opt_prefix[SIZEOF_STR] = "";
492 static char opt_git_dir[SIZEOF_STR] = "";
493 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
494 static char opt_editor[SIZEOF_STR] = "";
495 static bool opt_editor_lineno = TRUE;
496 static FILE *opt_tty = NULL;
497 static const char **opt_diff_argv = NULL;
498 static const char **opt_rev_argv = NULL;
499 static const char **opt_file_argv = NULL;
500 static const char **opt_blame_argv = NULL;
501 static int opt_lineno = 0;
502 static bool opt_show_id = FALSE;
503 static int opt_id_cols = ID_WIDTH;
504 static bool opt_file_filter = TRUE;
505 static bool opt_show_title_overflow = FALSE;
506 static int opt_title_overflow = 50;
507 static char opt_env_lines[64] = "";
508 static char opt_env_columns[64] = "";
509 static char *opt_env[] = { opt_env_lines, opt_env_columns, NULL };
511 #define is_initial_commit() (!get_ref_head())
512 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strncmp(rev, get_ref_head()->id, SIZEOF_REV - 1)))
514 static inline int
515 load_refs(bool force)
517 static bool loaded = FALSE;
519 if (force)
520 opt_head[0] = 0;
521 else if (loaded)
522 return OK;
524 loaded = TRUE;
525 return reload_refs(opt_git_dir, opt_remote, opt_head, sizeof(opt_head));
528 static inline void
529 update_diff_context_arg(int diff_context)
531 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
532 string_ncopy(opt_diff_context_arg, "-U3", 3);
535 static inline void
536 update_ignore_space_arg()
538 if (opt_ignore_space == IGNORE_SPACE_ALL) {
539 string_copy(opt_ignore_space_arg, "--ignore-all-space");
540 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
541 string_copy(opt_ignore_space_arg, "--ignore-space-change");
542 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
543 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
544 } else {
545 string_copy(opt_ignore_space_arg, "");
549 static inline void
550 update_commit_order_arg()
552 if (opt_commit_order == COMMIT_ORDER_TOPO) {
553 string_copy(opt_commit_order_arg, "--topo-order");
554 } else if (opt_commit_order == COMMIT_ORDER_DATE) {
555 string_copy(opt_commit_order_arg, "--date-order");
556 } else if (opt_commit_order == COMMIT_ORDER_REVERSE) {
557 string_copy(opt_commit_order_arg, "--reverse");
558 } else {
559 string_copy(opt_commit_order_arg, "");
563 static inline void
564 update_notes_arg()
566 if (opt_notes) {
567 string_copy(opt_notes_arg, "--show-notes");
568 } else {
569 /* Notes are disabled by default when passing --pretty args. */
570 string_copy(opt_notes_arg, "");
575 * Line-oriented content detection.
578 #define LINE_INFO \
579 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
580 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
581 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
582 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
583 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
584 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
585 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
586 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
587 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
588 LINE(DIFF_DELETED_FILE_MODE, \
589 "deleted file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
590 LINE(DIFF_COPY_FROM, "copy from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
591 LINE(DIFF_COPY_TO, "copy to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
592 LINE(DIFF_RENAME_FROM, "rename from ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
593 LINE(DIFF_RENAME_TO, "rename to ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
594 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
595 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
596 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
597 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
598 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
599 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
600 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
601 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
602 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
603 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
604 LINE(PP_REFLOG, "Reflog: ", COLOR_RED, COLOR_DEFAULT, 0), \
605 LINE(PP_REFLOGMSG, "Reflog message: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
606 LINE(STASH, "stash@{", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
607 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
608 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
609 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
610 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
611 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
612 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
613 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
614 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
615 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
616 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
617 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
618 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
619 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
620 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
621 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
622 LINE(ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
623 LINE(OVERFLOW, "", COLOR_RED, COLOR_DEFAULT, 0), \
624 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
625 LINE(FILE_SIZE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
626 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
627 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
628 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
629 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
630 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
631 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
632 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
633 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
634 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
635 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
636 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
637 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
638 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
639 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
640 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
641 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
642 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
643 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
644 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
645 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
646 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
647 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
648 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
649 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
650 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
651 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
652 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
653 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
654 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
655 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
656 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
657 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
659 enum line_type {
660 #define LINE(type, line, fg, bg, attr) \
661 LINE_##type
662 LINE_INFO,
663 LINE_NONE
664 #undef LINE
667 struct line_info {
668 const char *name; /* Option name. */
669 int namelen; /* Size of option name. */
670 const char *line; /* The start of line to match. */
671 int linelen; /* Size of string to match. */
672 int fg, bg, attr; /* Color and text attributes for the lines. */
673 int color_pair;
676 static struct line_info line_info[] = {
677 #define LINE(type, line, fg, bg, attr) \
678 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
679 LINE_INFO
680 #undef LINE
683 static struct line_info **color_pair;
684 static size_t color_pairs;
686 static struct line_info *custom_color;
687 static size_t custom_colors;
689 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
690 DEFINE_ALLOCATOR(realloc_color_pair, struct line_info *, 8)
692 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
693 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
695 /* Color IDs must be 1 or higher. [GH #15] */
696 #define COLOR_ID(line_type) ((line_type) + 1)
698 static enum line_type
699 get_line_type(const char *line)
701 int linelen = strlen(line);
702 enum line_type type;
704 for (type = 0; type < custom_colors; type++)
705 /* Case insensitive search matches Signed-off-by lines better. */
706 if (linelen >= custom_color[type].linelen &&
707 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
708 return TO_CUSTOM_COLOR_TYPE(type);
710 for (type = 0; type < ARRAY_SIZE(line_info); type++)
711 /* Case insensitive search matches Signed-off-by lines better. */
712 if (linelen >= line_info[type].linelen &&
713 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
714 return type;
716 return LINE_DEFAULT;
719 static enum line_type
720 get_line_type_from_ref(const struct ref *ref)
722 if (ref->head)
723 return LINE_MAIN_HEAD;
724 else if (ref->ltag)
725 return LINE_MAIN_LOCAL_TAG;
726 else if (ref->tag)
727 return LINE_MAIN_TAG;
728 else if (ref->tracked)
729 return LINE_MAIN_TRACKED;
730 else if (ref->remote)
731 return LINE_MAIN_REMOTE;
732 else if (ref->replace)
733 return LINE_MAIN_REPLACE;
735 return LINE_MAIN_REF;
738 static inline struct line_info *
739 get_line(enum line_type type)
741 if (type > LINE_NONE) {
742 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
743 return &custom_color[TO_CUSTOM_COLOR_OFFSET(type)];
744 } else {
745 assert(type < ARRAY_SIZE(line_info));
746 return &line_info[type];
750 static inline int
751 get_line_color(enum line_type type)
753 return COLOR_ID(get_line(type)->color_pair);
756 static inline int
757 get_line_attr(enum line_type type)
759 struct line_info *info = get_line(type);
761 return COLOR_PAIR(COLOR_ID(info->color_pair)) | info->attr;
764 static struct line_info *
765 get_line_info(const char *name)
767 size_t namelen = strlen(name);
768 enum line_type type;
770 for (type = 0; type < ARRAY_SIZE(line_info); type++)
771 if (enum_equals(line_info[type], name, namelen))
772 return &line_info[type];
774 return NULL;
777 static struct line_info *
778 add_custom_color(const char *quoted_line)
780 struct line_info *info;
781 char *line;
782 size_t linelen;
784 if (!realloc_custom_color(&custom_color, custom_colors, 1))
785 die("Failed to alloc custom line info");
787 linelen = strlen(quoted_line) - 1;
788 line = malloc(linelen);
789 if (!line)
790 return NULL;
792 strncpy(line, quoted_line + 1, linelen);
793 line[linelen - 1] = 0;
795 info = &custom_color[custom_colors++];
796 info->name = info->line = line;
797 info->namelen = info->linelen = strlen(line);
799 return info;
802 static void
803 init_line_info_color_pair(struct line_info *info, enum line_type type,
804 int default_bg, int default_fg)
806 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
807 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
808 int i;
810 for (i = 0; i < color_pairs; i++) {
811 if (color_pair[i]->fg == info->fg && color_pair[i]->bg == info->bg) {
812 info->color_pair = i;
813 return;
817 if (!realloc_color_pair(&color_pair, color_pairs, 1))
818 die("Failed to alloc color pair");
820 color_pair[color_pairs] = info;
821 info->color_pair = color_pairs++;
822 init_pair(COLOR_ID(info->color_pair), fg, bg);
825 static void
826 init_colors(void)
828 int default_bg = line_info[LINE_DEFAULT].bg;
829 int default_fg = line_info[LINE_DEFAULT].fg;
830 enum line_type type;
832 start_color();
834 if (assume_default_colors(default_fg, default_bg) == ERR) {
835 default_bg = COLOR_BLACK;
836 default_fg = COLOR_WHITE;
839 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
840 struct line_info *info = &line_info[type];
842 init_line_info_color_pair(info, type, default_bg, default_fg);
845 for (type = 0; type < custom_colors; type++) {
846 struct line_info *info = &custom_color[type];
848 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
849 default_bg, default_fg);
853 struct line {
854 enum line_type type;
855 unsigned int lineno:24;
857 /* State flags */
858 unsigned int selected:1;
859 unsigned int dirty:1;
860 unsigned int cleareol:1;
861 unsigned int wrapped:1;
863 unsigned int user_flags:6;
864 void *data; /* User data */
869 * Keys
872 struct keybinding {
873 int alias;
874 enum request request;
877 static struct keybinding default_keybindings[] = {
878 /* View switching */
879 { 'm', REQ_VIEW_MAIN },
880 { 'd', REQ_VIEW_DIFF },
881 { 'l', REQ_VIEW_LOG },
882 { 't', REQ_VIEW_TREE },
883 { 'f', REQ_VIEW_BLOB },
884 { 'B', REQ_VIEW_BLAME },
885 { 'H', REQ_VIEW_BRANCH },
886 { 'p', REQ_VIEW_PAGER },
887 { 'h', REQ_VIEW_HELP },
888 { 'S', REQ_VIEW_STATUS },
889 { 'c', REQ_VIEW_STAGE },
890 { 'y', REQ_VIEW_STASH },
892 /* View manipulation */
893 { 'q', REQ_VIEW_CLOSE },
894 { KEY_TAB, REQ_VIEW_NEXT },
895 { KEY_RETURN, REQ_ENTER },
896 { KEY_UP, REQ_PREVIOUS },
897 { KEY_CTL('P'), REQ_PREVIOUS },
898 { KEY_DOWN, REQ_NEXT },
899 { KEY_CTL('N'), REQ_NEXT },
900 { 'R', REQ_REFRESH },
901 { KEY_F(5), REQ_REFRESH },
902 { 'O', REQ_MAXIMIZE },
903 { ',', REQ_PARENT },
904 { '<', REQ_BACK },
906 /* View specific */
907 { 'u', REQ_STATUS_UPDATE },
908 { '!', REQ_STATUS_REVERT },
909 { 'M', REQ_STATUS_MERGE },
910 { '1', REQ_STAGE_UPDATE_LINE },
911 { '@', REQ_STAGE_NEXT },
912 { '[', REQ_DIFF_CONTEXT_DOWN },
913 { ']', REQ_DIFF_CONTEXT_UP },
915 /* Cursor navigation */
916 { 'k', REQ_MOVE_UP },
917 { 'j', REQ_MOVE_DOWN },
918 { KEY_HOME, REQ_MOVE_FIRST_LINE },
919 { KEY_END, REQ_MOVE_LAST_LINE },
920 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
921 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
922 { ' ', REQ_MOVE_PAGE_DOWN },
923 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
924 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
925 { 'b', REQ_MOVE_PAGE_UP },
926 { '-', REQ_MOVE_PAGE_UP },
928 /* Scrolling */
929 { '|', REQ_SCROLL_FIRST_COL },
930 { KEY_LEFT, REQ_SCROLL_LEFT },
931 { KEY_RIGHT, REQ_SCROLL_RIGHT },
932 { KEY_IC, REQ_SCROLL_LINE_UP },
933 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
934 { KEY_DC, REQ_SCROLL_LINE_DOWN },
935 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
936 { 'w', REQ_SCROLL_PAGE_UP },
937 { 's', REQ_SCROLL_PAGE_DOWN },
939 /* Searching */
940 { '/', REQ_SEARCH },
941 { '?', REQ_SEARCH_BACK },
942 { 'n', REQ_FIND_NEXT },
943 { 'N', REQ_FIND_PREV },
945 /* Misc */
946 { 'Q', REQ_QUIT },
947 { 'z', REQ_STOP_LOADING },
948 { 'v', REQ_SHOW_VERSION },
949 { 'r', REQ_SCREEN_REDRAW },
950 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
951 { 'o', REQ_OPTIONS },
952 { '.', REQ_TOGGLE_LINENO },
953 { 'D', REQ_TOGGLE_DATE },
954 { 'A', REQ_TOGGLE_AUTHOR },
955 { 'g', REQ_TOGGLE_REV_GRAPH },
956 { '~', REQ_TOGGLE_GRAPHIC },
957 { '#', REQ_TOGGLE_FILENAME },
958 { 'F', REQ_TOGGLE_REFS },
959 { 'I', REQ_TOGGLE_SORT_ORDER },
960 { 'i', REQ_TOGGLE_SORT_FIELD },
961 { 'W', REQ_TOGGLE_IGNORE_SPACE },
962 { 'X', REQ_TOGGLE_ID },
963 { '%', REQ_TOGGLE_FILES },
964 { '$', REQ_TOGGLE_TITLE_OVERFLOW },
965 { ':', REQ_PROMPT },
966 { 'e', REQ_EDIT },
969 struct keymap {
970 const char *name;
971 struct keymap *next;
972 struct keybinding *data;
973 size_t size;
974 bool hidden;
977 static struct keymap generic_keymap = { "generic" };
978 #define is_generic_keymap(keymap) ((keymap) == &generic_keymap)
980 static struct keymap *keymaps = &generic_keymap;
982 static void
983 add_keymap(struct keymap *keymap)
985 keymap->next = keymaps;
986 keymaps = keymap;
989 static struct keymap *
990 get_keymap(const char *name)
992 struct keymap *keymap = keymaps;
994 while (keymap) {
995 if (!strcasecmp(keymap->name, name))
996 return keymap;
997 keymap = keymap->next;
1000 return NULL;
1004 static void
1005 add_keybinding(struct keymap *table, enum request request, int key)
1007 size_t i;
1009 for (i = 0; i < table->size; i++) {
1010 if (table->data[i].alias == key) {
1011 table->data[i].request = request;
1012 return;
1016 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
1017 if (!table->data)
1018 die("Failed to allocate keybinding");
1019 table->data[table->size].alias = key;
1020 table->data[table->size++].request = request;
1022 if (request == REQ_NONE && is_generic_keymap(table)) {
1023 int i;
1025 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1026 if (default_keybindings[i].alias == key)
1027 default_keybindings[i].request = REQ_NONE;
1031 /* Looks for a key binding first in the given map, then in the generic map, and
1032 * lastly in the default keybindings. */
1033 static enum request
1034 get_keybinding(struct keymap *keymap, int key)
1036 size_t i;
1038 for (i = 0; i < keymap->size; i++)
1039 if (keymap->data[i].alias == key)
1040 return keymap->data[i].request;
1042 for (i = 0; i < generic_keymap.size; i++)
1043 if (generic_keymap.data[i].alias == key)
1044 return generic_keymap.data[i].request;
1046 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
1047 if (default_keybindings[i].alias == key)
1048 return default_keybindings[i].request;
1050 return (enum request) key;
1054 struct key {
1055 const char *name;
1056 int value;
1059 static const struct key key_table[] = {
1060 { "Enter", KEY_RETURN },
1061 { "Space", ' ' },
1062 { "Backspace", KEY_BACKSPACE },
1063 { "Tab", KEY_TAB },
1064 { "Escape", KEY_ESC },
1065 { "Left", KEY_LEFT },
1066 { "Right", KEY_RIGHT },
1067 { "Up", KEY_UP },
1068 { "Down", KEY_DOWN },
1069 { "Insert", KEY_IC },
1070 { "Delete", KEY_DC },
1071 { "Hash", '#' },
1072 { "Home", KEY_HOME },
1073 { "End", KEY_END },
1074 { "PageUp", KEY_PPAGE },
1075 { "PageDown", KEY_NPAGE },
1076 { "F1", KEY_F(1) },
1077 { "F2", KEY_F(2) },
1078 { "F3", KEY_F(3) },
1079 { "F4", KEY_F(4) },
1080 { "F5", KEY_F(5) },
1081 { "F6", KEY_F(6) },
1082 { "F7", KEY_F(7) },
1083 { "F8", KEY_F(8) },
1084 { "F9", KEY_F(9) },
1085 { "F10", KEY_F(10) },
1086 { "F11", KEY_F(11) },
1087 { "F12", KEY_F(12) },
1090 static int
1091 get_key_value(const char *name)
1093 int i;
1095 for (i = 0; i < ARRAY_SIZE(key_table); i++)
1096 if (!strcasecmp(key_table[i].name, name))
1097 return key_table[i].value;
1099 if (strlen(name) == 3 && name[0] == '^' && name[1] == '[' && isprint(*name))
1100 return (int)name[2] + 0x80;
1101 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
1102 return (int)name[1] & 0x1f;
1103 if (strlen(name) == 1 && isprint(*name))
1104 return (int) *name;
1105 return ERR;
1108 static const char *
1109 get_key_name(int key_value)
1111 static char key_char[] = "'X'\0";
1112 const char *seq = NULL;
1113 int key;
1115 for (key = 0; key < ARRAY_SIZE(key_table); key++)
1116 if (key_table[key].value == key_value)
1117 seq = key_table[key].name;
1119 if (seq == NULL && key_value < 0x7f) {
1120 char *s = key_char + 1;
1122 if (key_value >= 0x20) {
1123 *s++ = key_value;
1124 } else {
1125 *s++ = '^';
1126 *s++ = 0x40 | (key_value & 0x1f);
1128 *s++ = '\'';
1129 *s++ = '\0';
1130 seq = key_char;
1133 return seq ? seq : "(no key)";
1136 static bool
1137 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
1139 const char *sep = *pos > 0 ? ", " : "";
1140 const char *keyname = get_key_name(keybinding->alias);
1142 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
1145 static bool
1146 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
1147 struct keymap *keymap, bool all)
1149 int i;
1151 for (i = 0; i < keymap->size; i++) {
1152 if (keymap->data[i].request == request) {
1153 if (!append_key(buf, pos, &keymap->data[i]))
1154 return FALSE;
1155 if (!all)
1156 break;
1160 return TRUE;
1163 #define get_view_key(view, request) get_keys(&(view)->ops->keymap, request, FALSE)
1165 static const char *
1166 get_keys(struct keymap *keymap, enum request request, bool all)
1168 static char buf[BUFSIZ];
1169 size_t pos = 0;
1170 int i;
1172 buf[pos] = 0;
1174 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1175 return "Too many keybindings!";
1176 if (pos > 0 && !all)
1177 return buf;
1179 if (!is_generic_keymap(keymap)) {
1180 /* Only the generic keymap includes the default keybindings when
1181 * listing all keys. */
1182 if (all)
1183 return buf;
1185 if (!append_keymap_request_keys(buf, &pos, request, &generic_keymap, all))
1186 return "Too many keybindings!";
1187 if (pos)
1188 return buf;
1191 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1192 if (default_keybindings[i].request == request) {
1193 if (!append_key(buf, &pos, &default_keybindings[i]))
1194 return "Too many keybindings!";
1195 if (!all)
1196 return buf;
1200 return buf;
1203 enum run_request_flag {
1204 RUN_REQUEST_DEFAULT = 0,
1205 RUN_REQUEST_FORCE = 1,
1206 RUN_REQUEST_SILENT = 2,
1207 RUN_REQUEST_CONFIRM = 4,
1208 RUN_REQUEST_EXIT = 8,
1209 RUN_REQUEST_INTERNAL = 16,
1212 struct run_request {
1213 struct keymap *keymap;
1214 int key;
1215 const char **argv;
1216 bool silent;
1217 bool confirm;
1218 bool exit;
1219 bool internal;
1222 static struct run_request *run_request;
1223 static size_t run_requests;
1225 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1227 static bool
1228 add_run_request(struct keymap *keymap, int key, const char **argv, enum run_request_flag flags)
1230 bool force = flags & RUN_REQUEST_FORCE;
1231 struct run_request *req;
1233 if (!force && get_keybinding(keymap, key) != key)
1234 return TRUE;
1236 if (!realloc_run_requests(&run_request, run_requests, 1))
1237 return FALSE;
1239 if (!argv_copy(&run_request[run_requests].argv, argv))
1240 return FALSE;
1242 req = &run_request[run_requests++];
1243 req->silent = flags & RUN_REQUEST_SILENT;
1244 req->confirm = flags & RUN_REQUEST_CONFIRM;
1245 req->exit = flags & RUN_REQUEST_EXIT;
1246 req->internal = flags & RUN_REQUEST_INTERNAL;
1247 req->keymap = keymap;
1248 req->key = key;
1250 add_keybinding(keymap, REQ_NONE + run_requests, key);
1251 return TRUE;
1254 static struct run_request *
1255 get_run_request(enum request request)
1257 if (request <= REQ_NONE || request > REQ_NONE + run_requests)
1258 return NULL;
1259 return &run_request[request - REQ_NONE - 1];
1262 static void
1263 add_builtin_run_requests(void)
1265 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1266 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1267 const char *commit[] = { "git", "commit", NULL };
1268 const char *gc[] = { "git", "gc", NULL };
1269 const char *stash_pop[] = { "git", "stash", "pop", "%(stash)", NULL };
1271 add_run_request(get_keymap("main"), 'C', cherry_pick, RUN_REQUEST_CONFIRM);
1272 add_run_request(get_keymap("status"), 'C', commit, RUN_REQUEST_DEFAULT);
1273 add_run_request(get_keymap("branch"), 'C', checkout, RUN_REQUEST_CONFIRM);
1274 add_run_request(get_keymap("generic"), 'G', gc, RUN_REQUEST_CONFIRM);
1275 add_run_request(get_keymap("stash"), 'P', stash_pop, RUN_REQUEST_CONFIRM);
1279 * User config file handling.
1282 static const struct enum_map color_map[] = {
1283 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1284 COLOR_MAP(DEFAULT),
1285 COLOR_MAP(BLACK),
1286 COLOR_MAP(BLUE),
1287 COLOR_MAP(CYAN),
1288 COLOR_MAP(GREEN),
1289 COLOR_MAP(MAGENTA),
1290 COLOR_MAP(RED),
1291 COLOR_MAP(WHITE),
1292 COLOR_MAP(YELLOW),
1295 static const struct enum_map attr_map[] = {
1296 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1297 ATTR_MAP(NORMAL),
1298 ATTR_MAP(BLINK),
1299 ATTR_MAP(BOLD),
1300 ATTR_MAP(DIM),
1301 ATTR_MAP(REVERSE),
1302 ATTR_MAP(STANDOUT),
1303 ATTR_MAP(UNDERLINE),
1306 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1308 static enum status_code
1309 parse_step(double *opt, const char *arg)
1311 *opt = atoi(arg);
1312 if (!strchr(arg, '%'))
1313 return SUCCESS;
1315 /* "Shift down" so 100% and 1 does not conflict. */
1316 *opt = (*opt - 1) / 100;
1317 if (*opt >= 1.0) {
1318 *opt = 0.99;
1319 return ERROR_INVALID_STEP_VALUE;
1321 if (*opt < 0.0) {
1322 *opt = 1;
1323 return ERROR_INVALID_STEP_VALUE;
1325 return SUCCESS;
1328 static enum status_code
1329 parse_int(int *opt, const char *arg, int min, int max)
1331 int value = atoi(arg);
1333 if (min <= value && value <= max) {
1334 *opt = value;
1335 return SUCCESS;
1338 return ERROR_INTEGER_VALUE_OUT_OF_BOUND;
1341 #define parse_id(opt, arg) \
1342 parse_int(opt, arg, 4, SIZEOF_REV - 1)
1344 static bool
1345 set_color(int *color, const char *name)
1347 if (map_enum(color, color_map, name))
1348 return TRUE;
1349 if (!prefixcmp(name, "color"))
1350 return parse_int(color, name + 5, 0, 255) == SUCCESS;
1351 /* Used when reading git colors. Git expects a plain int w/o prefix. */
1352 return parse_int(color, name, 0, 255) == SUCCESS;
1355 /* Wants: object fgcolor bgcolor [attribute] */
1356 static enum status_code
1357 option_color_command(int argc, const char *argv[])
1359 struct line_info *info;
1361 if (argc < 3)
1362 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1364 if (*argv[0] == '"' || *argv[0] == '\'') {
1365 info = add_custom_color(argv[0]);
1366 } else {
1367 info = get_line_info(argv[0]);
1369 if (!info) {
1370 static const struct enum_map obsolete[] = {
1371 ENUM_MAP("main-delim", LINE_DELIMITER),
1372 ENUM_MAP("main-date", LINE_DATE),
1373 ENUM_MAP("main-author", LINE_AUTHOR),
1374 ENUM_MAP("blame-id", LINE_ID),
1376 int index;
1378 if (!map_enum(&index, obsolete, argv[0]))
1379 return ERROR_UNKNOWN_COLOR_NAME;
1380 info = &line_info[index];
1383 if (!set_color(&info->fg, argv[1]) ||
1384 !set_color(&info->bg, argv[2]))
1385 return ERROR_UNKNOWN_COLOR;
1387 info->attr = 0;
1388 while (argc-- > 3) {
1389 int attr;
1391 if (!set_attribute(&attr, argv[argc]))
1392 return ERROR_UNKNOWN_ATTRIBUTE;
1393 info->attr |= attr;
1396 return SUCCESS;
1399 static enum status_code
1400 parse_bool_matched(bool *opt, const char *arg, bool *matched)
1402 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1403 ? TRUE : FALSE;
1404 if (matched)
1405 *matched = *opt || (!strcmp(arg, "0") || !strcmp(arg, "false") || !strcmp(arg, "no"));
1406 return SUCCESS;
1409 #define parse_bool(opt, arg) parse_bool_matched(opt, arg, NULL)
1411 static enum status_code
1412 parse_enum_do(unsigned int *opt, const char *arg,
1413 const struct enum_map *map, size_t map_size)
1415 bool is_true;
1417 assert(map_size > 1);
1419 if (map_enum_do(map, map_size, (int *) opt, arg))
1420 return SUCCESS;
1422 parse_bool(&is_true, arg);
1423 *opt = is_true ? map[1].value : map[0].value;
1424 return SUCCESS;
1427 #define parse_enum(opt, arg, map) \
1428 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1430 static enum status_code
1431 parse_string(char *opt, const char *arg, size_t optsize)
1433 int arglen = strlen(arg);
1435 switch (arg[0]) {
1436 case '\"':
1437 case '\'':
1438 if (arglen == 1 || arg[arglen - 1] != arg[0])
1439 return ERROR_UNMATCHED_QUOTATION;
1440 arg += 1; arglen -= 2;
1441 default:
1442 string_ncopy_do(opt, optsize, arg, arglen);
1443 return SUCCESS;
1447 static enum status_code
1448 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1450 char buf[SIZEOF_STR];
1451 enum status_code code = parse_string(buf, arg, sizeof(buf));
1453 if (code == SUCCESS) {
1454 struct encoding *encoding = *encoding_ref;
1456 if (encoding && !priority)
1457 return code;
1458 encoding = encoding_open(buf);
1459 if (encoding)
1460 *encoding_ref = encoding;
1463 return code;
1466 static enum status_code
1467 parse_args(const char ***args, const char *argv[])
1469 if (!argv_copy(args, argv))
1470 return ERROR_OUT_OF_MEMORY;
1471 return SUCCESS;
1474 /* Wants: name = value */
1475 static enum status_code
1476 option_set_command(int argc, const char *argv[])
1478 if (argc < 3)
1479 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1481 if (strcmp(argv[1], "="))
1482 return ERROR_NO_VALUE_ASSIGNED;
1484 if (!strcmp(argv[0], "blame-options"))
1485 return parse_args(&opt_blame_argv, argv + 2);
1487 if (!strcmp(argv[0], "diff-options"))
1488 return parse_args(&opt_diff_argv, argv + 2);
1490 if (argc != 3)
1491 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1493 if (!strcmp(argv[0], "show-author"))
1494 return parse_enum(&opt_author, argv[2], author_map);
1496 if (!strcmp(argv[0], "show-date"))
1497 return parse_enum(&opt_date, argv[2], date_map);
1499 if (!strcmp(argv[0], "show-rev-graph"))
1500 return parse_bool(&opt_rev_graph, argv[2]);
1502 if (!strcmp(argv[0], "show-refs"))
1503 return parse_bool(&opt_show_refs, argv[2]);
1505 if (!strcmp(argv[0], "show-changes"))
1506 return parse_bool(&opt_show_changes, argv[2]);
1508 if (!strcmp(argv[0], "show-notes")) {
1509 bool matched = FALSE;
1510 enum status_code res = parse_bool_matched(&opt_notes, argv[2], &matched);
1512 if (res == SUCCESS && matched) {
1513 update_notes_arg();
1514 return res;
1517 opt_notes = TRUE;
1518 strcpy(opt_notes_arg, "--show-notes=");
1519 res = parse_string(opt_notes_arg + 8, argv[2],
1520 sizeof(opt_notes_arg) - 8);
1521 if (res == SUCCESS && opt_notes_arg[8] == '\0')
1522 opt_notes_arg[7] = '\0';
1523 return res;
1526 if (!strcmp(argv[0], "show-line-numbers"))
1527 return parse_bool(&opt_line_number, argv[2]);
1529 if (!strcmp(argv[0], "line-graphics"))
1530 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1532 if (!strcmp(argv[0], "line-number-interval"))
1533 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1535 if (!strcmp(argv[0], "author-width"))
1536 return parse_int(&opt_author_width, argv[2], 0, 1024);
1538 if (!strcmp(argv[0], "filename-width"))
1539 return parse_int(&opt_filename_width, argv[2], 0, 1024);
1541 if (!strcmp(argv[0], "show-filename"))
1542 return parse_enum(&opt_filename, argv[2], filename_map);
1544 if (!strcmp(argv[0], "show-file-size"))
1545 return parse_enum(&opt_file_size, argv[2], file_size_map);
1547 if (!strcmp(argv[0], "horizontal-scroll"))
1548 return parse_step(&opt_hscroll, argv[2]);
1550 if (!strcmp(argv[0], "split-view-height"))
1551 return parse_step(&opt_scale_split_view, argv[2]);
1553 if (!strcmp(argv[0], "vertical-split"))
1554 return parse_bool(&opt_vsplit, argv[2]);
1556 if (!strcmp(argv[0], "tab-size"))
1557 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1559 if (!strcmp(argv[0], "diff-context")) {
1560 enum status_code code = parse_int(&opt_diff_context, argv[2], 0, 999999);
1562 if (code == SUCCESS)
1563 update_diff_context_arg(opt_diff_context);
1564 return code;
1567 if (!strcmp(argv[0], "ignore-space")) {
1568 enum status_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1570 if (code == SUCCESS)
1571 update_ignore_space_arg();
1572 return code;
1575 if (!strcmp(argv[0], "commit-order")) {
1576 enum status_code code = parse_enum(&opt_commit_order, argv[2], commit_order_map);
1578 if (code == SUCCESS)
1579 update_commit_order_arg();
1580 return code;
1583 if (!strcmp(argv[0], "status-untracked-dirs"))
1584 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1586 if (!strcmp(argv[0], "read-git-colors"))
1587 return parse_bool(&opt_read_git_colors, argv[2]);
1589 if (!strcmp(argv[0], "ignore-case"))
1590 return parse_bool(&opt_ignore_case, argv[2]);
1592 if (!strcmp(argv[0], "focus-child"))
1593 return parse_bool(&opt_focus_child, argv[2]);
1595 if (!strcmp(argv[0], "wrap-lines"))
1596 return parse_bool(&opt_wrap_lines, argv[2]);
1598 if (!strcmp(argv[0], "show-id"))
1599 return parse_bool(&opt_show_id, argv[2]);
1601 if (!strcmp(argv[0], "id-width"))
1602 return parse_id(&opt_id_cols, argv[2]);
1604 if (!strcmp(argv[0], "title-overflow")) {
1605 bool matched;
1606 enum status_code code;
1609 * "title-overflow" is considered a boolint.
1610 * We try to parse it as a boolean (and set the value to 50 if true),
1611 * otherwise we parse it as an integer and use the given value.
1613 code = parse_bool_matched(&opt_show_title_overflow, argv[2], &matched);
1614 if (code == SUCCESS && matched) {
1615 if (opt_show_title_overflow)
1616 opt_title_overflow = 50;
1617 } else {
1618 code = parse_int(&opt_title_overflow, argv[2], 2, 1024);
1619 if (code == SUCCESS)
1620 opt_show_title_overflow = TRUE;
1623 return code;
1626 if (!strcmp(argv[0], "editor-line-number"))
1627 return parse_bool(&opt_editor_lineno, argv[2]);
1629 return ERROR_UNKNOWN_VARIABLE_NAME;
1632 /* Wants: mode request key */
1633 static enum status_code
1634 option_bind_command(int argc, const char *argv[])
1636 enum request request;
1637 struct keymap *keymap;
1638 int key;
1640 if (argc < 3)
1641 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1643 if (!(keymap = get_keymap(argv[0])))
1644 return ERROR_UNKNOWN_KEY_MAP;
1646 key = get_key_value(argv[1]);
1647 if (key == ERR)
1648 return ERROR_UNKNOWN_KEY;
1650 request = get_request(argv[2]);
1651 if (request == REQ_UNKNOWN) {
1652 static const struct enum_map obsolete[] = {
1653 ENUM_MAP("cherry-pick", REQ_NONE),
1654 ENUM_MAP("screen-resize", REQ_NONE),
1655 ENUM_MAP("tree-parent", REQ_PARENT),
1657 int alias;
1659 if (map_enum(&alias, obsolete, argv[2])) {
1660 if (alias != REQ_NONE)
1661 add_keybinding(keymap, alias, key);
1662 return ERROR_OBSOLETE_REQUEST_NAME;
1666 if (request == REQ_UNKNOWN) {
1667 enum run_request_flag flags = RUN_REQUEST_FORCE;
1669 if (strchr("!?@<", *argv[2])) {
1670 while (*argv[2]) {
1671 if (*argv[2] == '@') {
1672 flags |= RUN_REQUEST_SILENT;
1673 } else if (*argv[2] == '?') {
1674 flags |= RUN_REQUEST_CONFIRM;
1675 } else if (*argv[2] == '<') {
1676 flags |= RUN_REQUEST_EXIT;
1677 } else if (*argv[2] != '!') {
1678 break;
1680 argv[2]++;
1683 } else if (*argv[2] == ':') {
1684 argv[2]++;
1685 flags |= RUN_REQUEST_INTERNAL;
1687 } else {
1688 return ERROR_UNKNOWN_REQUEST_NAME;
1691 return add_run_request(keymap, key, argv + 2, flags)
1692 ? SUCCESS : ERROR_OUT_OF_MEMORY;
1695 add_keybinding(keymap, request, key);
1697 return SUCCESS;
1701 static enum status_code load_option_file(const char *path);
1703 static enum status_code
1704 option_source_command(int argc, const char *argv[])
1706 if (argc < 1)
1707 return ERROR_WRONG_NUMBER_OF_ARGUMENTS;
1709 return load_option_file(argv[0]);
1712 static enum status_code
1713 set_option(const char *opt, char *value)
1715 const char *argv[SIZEOF_ARG];
1716 int argc = 0;
1718 if (!argv_from_string(argv, &argc, value))
1719 return ERROR_TOO_MANY_OPTION_ARGUMENTS;
1721 if (!strcmp(opt, "color"))
1722 return option_color_command(argc, argv);
1724 if (!strcmp(opt, "set"))
1725 return option_set_command(argc, argv);
1727 if (!strcmp(opt, "bind"))
1728 return option_bind_command(argc, argv);
1730 if (!strcmp(opt, "source"))
1731 return option_source_command(argc, argv);
1733 return ERROR_UNKNOWN_OPTION_COMMAND;
1736 struct config_state {
1737 const char *path;
1738 int lineno;
1739 bool errors;
1742 static int
1743 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1745 struct config_state *config = data;
1746 enum status_code status = ERROR_NO_OPTION_VALUE;
1748 config->lineno++;
1750 /* Check for comment markers, since read_properties() will
1751 * only ensure opt and value are split at first " \t". */
1752 optlen = strcspn(opt, "#");
1753 if (optlen == 0)
1754 return OK;
1756 if (opt[optlen] == 0) {
1757 /* Look for comment endings in the value. */
1758 size_t len = strcspn(value, "#");
1760 if (len < valuelen) {
1761 valuelen = len;
1762 value[valuelen] = 0;
1765 status = set_option(opt, value);
1768 if (status != SUCCESS) {
1769 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1770 get_status_message(status), (int) optlen, opt);
1771 config->errors = TRUE;
1774 /* Always keep going if errors are encountered. */
1775 return OK;
1778 static enum status_code
1779 load_option_file(const char *path)
1781 struct config_state config = { path, 0, FALSE };
1782 struct io io;
1783 char buf[SIZEOF_STR];
1785 /* Do not read configuration from stdin if set to "" */
1786 if (!path || !strlen(path))
1787 return SUCCESS;
1789 if (!prefixcmp(path, "~/")) {
1790 const char *home = getenv("HOME");
1792 if (!home || !string_format(buf, "%s/%s", home, path + 2))
1793 return ERROR_HOME_UNRESOLVABLE;
1794 path = buf;
1797 /* It's OK that the file doesn't exist. */
1798 if (!io_open(&io, "%s", path))
1799 return ERROR_FILE_DOES_NOT_EXIST;
1801 if (io_load(&io, " \t", read_option, &config) == ERR ||
1802 config.errors == TRUE)
1803 warn("Errors while loading %s.", path);
1804 return SUCCESS;
1807 static int
1808 load_options(void)
1810 const char *tigrc_user = getenv("TIGRC_USER");
1811 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1812 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1813 const bool diff_opts_from_args = !!opt_diff_argv;
1815 if (!tigrc_system)
1816 tigrc_system = SYSCONFDIR "/tigrc";
1817 load_option_file(tigrc_system);
1819 if (!tigrc_user)
1820 tigrc_user = "~/.tigrc";
1821 load_option_file(tigrc_user);
1823 /* Add _after_ loading config files to avoid adding run requests
1824 * that conflict with keybindings. */
1825 add_builtin_run_requests();
1827 if (!diff_opts_from_args && tig_diff_opts && *tig_diff_opts) {
1828 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1829 char buf[SIZEOF_STR];
1830 int argc = 0;
1832 if (!string_format(buf, "%s", tig_diff_opts) ||
1833 !argv_from_string(diff_opts, &argc, buf))
1834 die("TIG_DIFF_OPTS contains too many arguments");
1835 else if (!argv_copy(&opt_diff_argv, diff_opts))
1836 die("Failed to format TIG_DIFF_OPTS arguments");
1839 return OK;
1844 * The viewer
1847 struct view;
1848 struct view_ops;
1850 /* The display array of active views and the index of the current view. */
1851 static struct view *display[2];
1852 static WINDOW *display_win[2];
1853 static WINDOW *display_title[2];
1854 static WINDOW *display_sep;
1856 static unsigned int current_view;
1858 #define foreach_displayed_view(view, i) \
1859 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1861 #define displayed_views() (display[1] != NULL ? 2 : 1)
1863 /* Current head and commit ID */
1864 static char ref_blob[SIZEOF_REF] = "";
1865 static char ref_commit[SIZEOF_REF] = "HEAD";
1866 static char ref_head[SIZEOF_REF] = "HEAD";
1867 static char ref_branch[SIZEOF_REF] = "";
1868 static char ref_status[SIZEOF_STR] = "";
1869 static char ref_stash[SIZEOF_REF] = "";
1871 enum view_flag {
1872 VIEW_NO_FLAGS = 0,
1873 VIEW_ALWAYS_LINENO = 1 << 0,
1874 VIEW_CUSTOM_STATUS = 1 << 1,
1875 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1876 VIEW_ADD_PAGER_REFS = 1 << 3,
1877 VIEW_OPEN_DIFF = 1 << 4,
1878 VIEW_NO_REF = 1 << 5,
1879 VIEW_NO_GIT_DIR = 1 << 6,
1880 VIEW_DIFF_LIKE = 1 << 7,
1881 VIEW_SEND_CHILD_ENTER = 1 << 9,
1882 VIEW_FILE_FILTER = 1 << 10,
1883 VIEW_LOG_LIKE = 1 << 11,
1884 VIEW_STATUS_LIKE = 1 << 12,
1887 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1889 struct position {
1890 unsigned long offset; /* Offset of the window top */
1891 unsigned long col; /* Offset from the window side. */
1892 unsigned long lineno; /* Current line number */
1895 struct view {
1896 const char *name; /* View name */
1897 const char *id; /* Points to either of ref_{head,commit,blob} */
1899 struct view_ops *ops; /* View operations */
1901 char ref[SIZEOF_REF]; /* Hovered commit reference */
1902 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1904 int height, width; /* The width and height of the main window */
1905 WINDOW *win; /* The main window */
1907 /* Navigation */
1908 struct position pos; /* Current position. */
1909 struct position prev_pos; /* Previous position. */
1911 /* Searching */
1912 char grep[SIZEOF_STR]; /* Search string */
1913 regex_t *regex; /* Pre-compiled regexp */
1915 /* If non-NULL, points to the view that opened this view. If this view
1916 * is closed tig will switch back to the parent view. */
1917 struct view *parent;
1918 struct view *prev;
1920 /* Buffering */
1921 size_t lines; /* Total number of lines */
1922 struct line *line; /* Line index */
1923 unsigned int digits; /* Number of digits in the lines member. */
1925 /* Number of lines with custom status, not to be counted in the
1926 * view title. */
1927 unsigned int custom_lines;
1929 /* Drawing */
1930 struct line *curline; /* Line currently being drawn. */
1931 enum line_type curtype; /* Attribute currently used for drawing. */
1932 unsigned long col; /* Column when drawing. */
1933 bool has_scrolled; /* View was scrolled. */
1934 bool force_redraw; /* Whether to force a redraw after reading. */
1936 /* Loading */
1937 const char **argv; /* Shell command arguments. */
1938 const char *dir; /* Directory from which to execute. */
1939 struct io io;
1940 struct io *pipe;
1941 time_t start_time;
1942 time_t update_secs;
1943 struct encoding *encoding;
1944 bool unrefreshable;
1946 /* Private data */
1947 void *private;
1950 enum open_flags {
1951 OPEN_DEFAULT = 0, /* Use default view switching. */
1952 OPEN_STDIN = 1, /* Open in pager mode. */
1953 OPEN_FORWARD_STDIN = 2, /* Forward stdin to I/O process. */
1954 OPEN_SPLIT = 4, /* Split current view. */
1955 OPEN_RELOAD = 8, /* Reload view even if it is the current. */
1956 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1957 OPEN_PREPARED = 32, /* Open already prepared command. */
1958 OPEN_EXTRA = 64, /* Open extra data from command. */
1960 OPEN_PAGER_MODE = OPEN_STDIN | OPEN_FORWARD_STDIN,
1963 #define open_in_pager_mode(flags) ((flags) & OPEN_PAGER_MODE)
1964 #define open_from_stdin(flags) ((flags) & OPEN_STDIN)
1966 struct view_ops {
1967 /* What type of content being displayed. Used in the title bar. */
1968 const char *type;
1969 /* What keymap does this view have */
1970 struct keymap keymap;
1971 /* Flags to control the view behavior. */
1972 enum view_flag flags;
1973 /* Size of private data. */
1974 size_t private_size;
1975 /* Open and reads in all view content. */
1976 bool (*open)(struct view *view, enum open_flags flags);
1977 /* Read one line; updates view->line. */
1978 bool (*read)(struct view *view, char *data);
1979 /* Draw one line; @lineno must be < view->height. */
1980 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1981 /* Depending on view handle a special requests. */
1982 enum request (*request)(struct view *view, enum request request, struct line *line);
1983 /* Search for regexp in a line. */
1984 bool (*grep)(struct view *view, struct line *line);
1985 /* Select line */
1986 void (*select)(struct view *view, struct line *line);
1987 /* Release resources when reloading the view */
1988 void (*done)(struct view *view);
1991 #define VIEW_OPS(id, name, ref) name##_ops
1992 static struct view_ops VIEW_INFO(VIEW_OPS);
1994 static struct view views[] = {
1995 #define VIEW_DATA(id, name, ref) \
1996 { #name, ref, &name##_ops }
1997 VIEW_INFO(VIEW_DATA)
2000 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
2002 #define foreach_view(view, i) \
2003 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2005 #define view_is_displayed(view) \
2006 (view == display[0] || view == display[1])
2008 #define view_has_line(view, line_) \
2009 ((view)->line <= (line_) && (line_) < (view)->line + (view)->lines)
2011 static bool
2012 forward_request_to_child(struct view *child, enum request request)
2014 return displayed_views() == 2 && view_is_displayed(child) &&
2015 !strcmp(child->vid, child->id);
2018 static enum request
2019 view_request(struct view *view, enum request request)
2021 if (!view || !view->lines)
2022 return request;
2024 if (request == REQ_ENTER && !opt_focus_child &&
2025 view_has_flags(view, VIEW_SEND_CHILD_ENTER)) {
2026 struct view *child = display[1];
2028 if (forward_request_to_child(child, request)) {
2029 view_request(child, request);
2030 return REQ_NONE;
2034 if (request == REQ_REFRESH && view->unrefreshable) {
2035 report("This view can not be refreshed");
2036 return REQ_NONE;
2039 return view->ops->request(view, request, &view->line[view->pos.lineno]);
2043 * View drawing.
2046 static inline void
2047 set_view_attr(struct view *view, enum line_type type)
2049 if (!view->curline->selected && view->curtype != type) {
2050 (void) wattrset(view->win, get_line_attr(type));
2051 wchgat(view->win, -1, 0, get_line_color(type), NULL);
2052 view->curtype = type;
2056 #define VIEW_MAX_LEN(view) ((view)->width + (view)->pos.col - (view)->col)
2058 static bool
2059 draw_chars(struct view *view, enum line_type type, const char *string,
2060 int max_len, bool use_tilde)
2062 int len = 0;
2063 int col = 0;
2064 int trimmed = FALSE;
2065 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2067 if (max_len <= 0)
2068 return VIEW_MAX_LEN(view) <= 0;
2070 if (opt_iconv_out != ICONV_NONE) {
2071 string = encoding_iconv(opt_iconv_out, string);
2072 if (!string)
2073 return VIEW_MAX_LEN(view) <= 0;
2076 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
2078 set_view_attr(view, type);
2079 if (len > 0) {
2080 waddnstr(view->win, string, len);
2082 if (trimmed && use_tilde) {
2083 set_view_attr(view, LINE_DELIMITER);
2084 waddch(view->win, '~');
2085 col++;
2089 view->col += col;
2090 return VIEW_MAX_LEN(view) <= 0;
2093 static bool
2094 draw_space(struct view *view, enum line_type type, int max, int spaces)
2096 static char space[] = " ";
2098 spaces = MIN(max, spaces);
2100 while (spaces > 0) {
2101 int len = MIN(spaces, sizeof(space) - 1);
2103 if (draw_chars(view, type, space, len, FALSE))
2104 return TRUE;
2105 spaces -= len;
2108 return VIEW_MAX_LEN(view) <= 0;
2111 static bool
2112 draw_text_expanded(struct view *view, enum line_type type, const char *string, int max_len, bool use_tilde)
2114 static char text[SIZEOF_STR];
2116 do {
2117 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
2119 if (draw_chars(view, type, text, max_len, use_tilde))
2120 return TRUE;
2121 string += pos;
2122 } while (*string);
2124 return VIEW_MAX_LEN(view) <= 0;
2127 static bool
2128 draw_text(struct view *view, enum line_type type, const char *string)
2130 return draw_text_expanded(view, type, string, VIEW_MAX_LEN(view), TRUE);
2133 static bool
2134 draw_text_overflow(struct view *view, const char *text, bool on, int overflow, enum line_type type)
2136 if (on) {
2137 int max = MIN(VIEW_MAX_LEN(view), overflow);
2138 int len = strlen(text);
2140 if (draw_text_expanded(view, type, text, max, max < overflow))
2141 return TRUE;
2143 text = len > overflow ? text + overflow : "";
2144 type = LINE_OVERFLOW;
2147 if (*text && draw_text(view, type, text))
2148 return TRUE;
2150 return VIEW_MAX_LEN(view) <= 0;
2153 #define draw_commit_title(view, text, offset) \
2154 draw_text_overflow(view, text, opt_show_title_overflow, opt_title_overflow + offset, LINE_DEFAULT)
2156 static bool PRINTF_LIKE(3, 4)
2157 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
2159 char text[SIZEOF_STR];
2160 int retval;
2162 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
2163 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
2166 static bool
2167 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
2169 size_t skip = view->pos.col > view->col ? view->pos.col - view->col : 0;
2170 int max = VIEW_MAX_LEN(view);
2171 int i;
2173 if (max < size)
2174 size = max;
2176 set_view_attr(view, type);
2177 /* Using waddch() instead of waddnstr() ensures that
2178 * they'll be rendered correctly for the cursor line. */
2179 for (i = skip; i < size; i++)
2180 waddch(view->win, graphic[i]);
2182 view->col += size;
2183 if (separator) {
2184 if (size < max && skip <= size)
2185 waddch(view->win, ' ');
2186 view->col++;
2189 return VIEW_MAX_LEN(view) <= 0;
2192 enum align {
2193 ALIGN_LEFT,
2194 ALIGN_RIGHT
2197 static bool
2198 draw_field(struct view *view, enum line_type type, const char *text, int width, enum align align, bool trim)
2200 int max = MIN(VIEW_MAX_LEN(view), width + 1);
2201 int col = view->col;
2203 if (!text)
2204 return draw_space(view, type, max, max);
2206 if (align == ALIGN_RIGHT) {
2207 int textlen = strlen(text);
2208 int leftpad = max - textlen - 1;
2210 if (leftpad > 0) {
2211 if (draw_space(view, type, leftpad, leftpad))
2212 return TRUE;
2213 max -= leftpad;
2214 col += leftpad;;
2218 return draw_chars(view, type, text, max - 1, trim)
2219 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
2222 static bool
2223 draw_date(struct view *view, struct time *time)
2225 const char *date = mkdate(time, opt_date);
2226 int cols = opt_date == DATE_SHORT ? DATE_SHORT_WIDTH : DATE_WIDTH;
2228 if (opt_date == DATE_NO)
2229 return FALSE;
2231 return draw_field(view, LINE_DATE, date, cols, ALIGN_LEFT, FALSE);
2234 static bool
2235 draw_author(struct view *view, const struct ident *author)
2237 bool trim = author_trim(opt_author_width);
2238 const char *text = mkauthor(author, opt_author_width, opt_author);
2240 if (opt_author == AUTHOR_NO)
2241 return FALSE;
2243 return draw_field(view, LINE_AUTHOR, text, opt_author_width, ALIGN_LEFT, trim);
2246 static bool
2247 draw_id_custom(struct view *view, enum line_type type, const char *id, int width)
2249 return draw_field(view, type, id, width, ALIGN_LEFT, FALSE);
2252 static bool
2253 draw_id(struct view *view, const char *id)
2255 if (!opt_show_id)
2256 return FALSE;
2258 return draw_id_custom(view, LINE_ID, id, opt_id_cols);
2261 static bool
2262 draw_filename(struct view *view, const char *filename, bool auto_enabled)
2264 bool trim = filename && strlen(filename) >= opt_filename_width;
2266 if (opt_filename == FILENAME_NO)
2267 return FALSE;
2269 if (opt_filename == FILENAME_AUTO && !auto_enabled)
2270 return FALSE;
2272 return draw_field(view, LINE_FILENAME, filename, opt_filename_width, ALIGN_LEFT, trim);
2275 static bool
2276 draw_file_size(struct view *view, unsigned long size, int width, bool pad)
2278 const char *str = pad ? NULL : mkfilesize(size, opt_file_size);
2280 if (!width || opt_file_size == FILE_SIZE_NO)
2281 return FALSE;
2283 return draw_field(view, LINE_FILE_SIZE, str, width, ALIGN_RIGHT, FALSE);
2286 static bool
2287 draw_mode(struct view *view, mode_t mode)
2289 const char *str = mkmode(mode);
2291 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r--"), ALIGN_LEFT, FALSE);
2294 static bool
2295 draw_lineno(struct view *view, unsigned int lineno)
2297 char number[10];
2298 int digits3 = view->digits < 3 ? 3 : view->digits;
2299 int max = MIN(VIEW_MAX_LEN(view), digits3);
2300 char *text = NULL;
2301 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2303 if (!opt_line_number)
2304 return FALSE;
2306 lineno += view->pos.offset + 1;
2307 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
2308 static char fmt[] = "%1ld";
2310 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
2311 if (string_format(number, fmt, lineno))
2312 text = number;
2314 if (text)
2315 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
2316 else
2317 draw_space(view, LINE_LINE_NUMBER, max, digits3);
2318 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
2321 static bool
2322 draw_refs(struct view *view, struct ref_list *refs)
2324 size_t i;
2326 if (!opt_show_refs || !refs)
2327 return FALSE;
2329 for (i = 0; i < refs->size; i++) {
2330 struct ref *ref = refs->refs[i];
2331 enum line_type type = get_line_type_from_ref(ref);
2333 if (draw_formatted(view, type, "[%s]", ref->name))
2334 return TRUE;
2336 if (draw_text(view, LINE_DEFAULT, " "))
2337 return TRUE;
2340 return FALSE;
2343 static bool
2344 draw_view_line(struct view *view, unsigned int lineno)
2346 struct line *line;
2347 bool selected = (view->pos.offset + lineno == view->pos.lineno);
2349 assert(view_is_displayed(view));
2351 if (view->pos.offset + lineno >= view->lines)
2352 return FALSE;
2354 line = &view->line[view->pos.offset + lineno];
2356 wmove(view->win, lineno, 0);
2357 if (line->cleareol)
2358 wclrtoeol(view->win);
2359 view->col = 0;
2360 view->curline = line;
2361 view->curtype = LINE_NONE;
2362 line->selected = FALSE;
2363 line->dirty = line->cleareol = 0;
2365 if (selected) {
2366 set_view_attr(view, LINE_CURSOR);
2367 line->selected = TRUE;
2368 view->ops->select(view, line);
2371 return view->ops->draw(view, line, lineno);
2374 static void
2375 redraw_view_dirty(struct view *view)
2377 bool dirty = FALSE;
2378 int lineno;
2380 for (lineno = 0; lineno < view->height; lineno++) {
2381 if (view->pos.offset + lineno >= view->lines)
2382 break;
2383 if (!view->line[view->pos.offset + lineno].dirty)
2384 continue;
2385 dirty = TRUE;
2386 if (!draw_view_line(view, lineno))
2387 break;
2390 if (!dirty)
2391 return;
2392 wnoutrefresh(view->win);
2395 static void
2396 redraw_view_from(struct view *view, int lineno)
2398 assert(0 <= lineno && lineno < view->height);
2400 for (; lineno < view->height; lineno++) {
2401 if (!draw_view_line(view, lineno))
2402 break;
2405 wnoutrefresh(view->win);
2408 static void
2409 redraw_view(struct view *view)
2411 werase(view->win);
2412 redraw_view_from(view, 0);
2416 static void
2417 update_view_title(struct view *view)
2419 char buf[SIZEOF_STR];
2420 char state[SIZEOF_STR];
2421 size_t bufpos = 0, statelen = 0;
2422 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2423 struct line *line = &view->line[view->pos.lineno];
2425 assert(view_is_displayed(view));
2427 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view_has_line(view, line) &&
2428 line->lineno) {
2429 unsigned int view_lines = view->pos.offset + view->height;
2430 unsigned int lines = view->lines
2431 ? MIN(view_lines, view->lines) * 100 / view->lines
2432 : 0;
2434 string_format_from(state, &statelen, " - %s %d of %zd (%d%%)",
2435 view->ops->type,
2436 line->lineno,
2437 view->lines - view->custom_lines,
2438 lines);
2442 if (view->pipe) {
2443 time_t secs = time(NULL) - view->start_time;
2445 /* Three git seconds are a long time ... */
2446 if (secs > 2)
2447 string_format_from(state, &statelen, " loading %lds", secs);
2450 string_format_from(buf, &bufpos, "[%s]", view->name);
2451 if (*view->ref && bufpos < view->width) {
2452 size_t refsize = strlen(view->ref);
2453 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2455 if (minsize < view->width)
2456 refsize = view->width - minsize + 7;
2457 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2460 if (statelen && bufpos < view->width) {
2461 string_format_from(buf, &bufpos, "%s", state);
2464 if (view == display[current_view])
2465 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2466 else
2467 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2469 mvwaddnstr(window, 0, 0, buf, bufpos);
2470 wclrtoeol(window);
2471 wnoutrefresh(window);
2474 static int
2475 apply_step(double step, int value)
2477 if (step >= 1)
2478 return (int) step;
2479 value *= step + 0.01;
2480 return value ? value : 1;
2483 static void
2484 apply_horizontal_split(struct view *base, struct view *view)
2486 view->width = base->width;
2487 view->height = apply_step(opt_scale_split_view, base->height);
2488 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2489 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2490 base->height -= view->height;
2493 static void
2494 apply_vertical_split(struct view *base, struct view *view)
2496 view->height = base->height;
2497 view->width = apply_step(opt_scale_vsplit_view, base->width);
2498 view->width = MAX(view->width, MIN_VIEW_WIDTH);
2499 view->width = MIN(view->width, base->width - MIN_VIEW_WIDTH);
2500 base->width -= view->width;
2503 static void
2504 redraw_display_separator(bool clear)
2506 if (displayed_views() > 1 && opt_vsplit) {
2507 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
2509 if (clear)
2510 wclear(display_sep);
2511 wbkgd(display_sep, separator + get_line_attr(LINE_TITLE_BLUR));
2512 wnoutrefresh(display_sep);
2516 static void
2517 resize_display(void)
2519 int x, y, i;
2520 struct view *base = display[0];
2521 struct view *view = display[1] ? display[1] : display[0];
2523 /* Setup window dimensions */
2525 getmaxyx(stdscr, base->height, base->width);
2526 string_format(opt_env_columns, "COLUMNS=%d", base->width);
2527 string_format(opt_env_lines, "LINES=%d", base->height);
2529 /* Make room for the status window. */
2530 base->height -= 1;
2532 if (view != base) {
2533 if (opt_vsplit) {
2534 apply_vertical_split(base, view);
2536 /* Make room for the separator bar. */
2537 view->width -= 1;
2538 } else {
2539 apply_horizontal_split(base, view);
2542 /* Make room for the title bar. */
2543 view->height -= 1;
2546 /* Make room for the title bar. */
2547 base->height -= 1;
2549 x = y = 0;
2551 foreach_displayed_view (view, i) {
2552 if (!display_win[i]) {
2553 display_win[i] = newwin(view->height, view->width, y, x);
2554 if (!display_win[i])
2555 die("Failed to create %s view", view->name);
2557 scrollok(display_win[i], FALSE);
2559 display_title[i] = newwin(1, view->width, y + view->height, x);
2560 if (!display_title[i])
2561 die("Failed to create title window");
2563 } else {
2564 wresize(display_win[i], view->height, view->width);
2565 mvwin(display_win[i], y, x);
2566 wresize(display_title[i], 1, view->width);
2567 mvwin(display_title[i], y + view->height, x);
2570 if (i > 0 && opt_vsplit) {
2571 if (!display_sep) {
2572 display_sep = newwin(view->height, 1, 0, x - 1);
2573 if (!display_sep)
2574 die("Failed to create separator window");
2576 } else {
2577 wresize(display_sep, view->height, 1);
2578 mvwin(display_sep, 0, x - 1);
2582 view->win = display_win[i];
2584 if (opt_vsplit)
2585 x += view->width + 1;
2586 else
2587 y += view->height + 1;
2590 redraw_display_separator(FALSE);
2593 static void
2594 redraw_display(bool clear)
2596 struct view *view;
2597 int i;
2599 foreach_displayed_view (view, i) {
2600 if (clear)
2601 wclear(view->win);
2602 redraw_view(view);
2603 update_view_title(view);
2606 redraw_display_separator(clear);
2610 * Option management
2613 #define TOGGLE_MENU_INFO(_) \
2614 _(LINENO, '.', "line numbers", &opt_line_number, NULL, 0, VIEW_NO_FLAGS), \
2615 _(DATE, 'D', "dates", &opt_date, date_map, ARRAY_SIZE(date_map), VIEW_NO_FLAGS), \
2616 _(AUTHOR, 'A', "author", &opt_author, author_map, ARRAY_SIZE(author_map), VIEW_NO_FLAGS), \
2617 _(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map, ARRAY_SIZE(graphic_map), VIEW_NO_FLAGS), \
2618 _(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL, 0, VIEW_LOG_LIKE), \
2619 _(FILENAME, '#', "file names", &opt_filename, filename_map, ARRAY_SIZE(filename_map), VIEW_NO_FLAGS), \
2620 _(FILE_SIZE, '*', "file sizes", &opt_file_size, file_size_map, ARRAY_SIZE(file_size_map), VIEW_NO_FLAGS), \
2621 _(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map, ARRAY_SIZE(ignore_space_map), VIEW_DIFF_LIKE), \
2622 _(COMMIT_ORDER, 'l', "commit order", &opt_commit_order, commit_order_map, ARRAY_SIZE(commit_order_map), VIEW_LOG_LIKE), \
2623 _(REFS, 'F', "reference display", &opt_show_refs, NULL, 0, VIEW_NO_FLAGS), \
2624 _(CHANGES, 'C', "local change display", &opt_show_changes, NULL, 0, VIEW_NO_FLAGS), \
2625 _(ID, 'X', "commit ID display", &opt_show_id, NULL, 0, VIEW_NO_FLAGS), \
2626 _(FILES, '%', "file filtering", &opt_file_filter, NULL, 0, VIEW_DIFF_LIKE | VIEW_LOG_LIKE), \
2627 _(TITLE_OVERFLOW, '$', "commit title overflow display", &opt_show_title_overflow, NULL, 0, VIEW_NO_FLAGS), \
2628 _(UNTRACKED_DIRS, 'd', "untracked directory info", &opt_untracked_dirs_content, NULL, 0, VIEW_STATUS_LIKE), \
2630 static enum view_flag
2631 toggle_option(struct view *view, enum request request, char msg[SIZEOF_STR])
2633 const struct {
2634 enum request request;
2635 const struct enum_map *map;
2636 size_t map_size;
2637 enum view_flag reload_flags;
2638 } data[] = {
2639 #define DEFINE_TOGGLE_DATA(id, key, help, value, map, map_size, vflags) { REQ_TOGGLE_ ## id, map, map_size, vflags }
2640 TOGGLE_MENU_INFO(DEFINE_TOGGLE_DATA)
2642 const struct menu_item menu[] = {
2643 #define DEFINE_TOGGLE_MENU(id, key, help, value, map, map_size, vflags) { key, help, value }
2644 TOGGLE_MENU_INFO(DEFINE_TOGGLE_MENU)
2645 { 0 }
2647 int i = 0;
2649 if (request == REQ_OPTIONS) {
2650 if (!prompt_menu("Toggle option", menu, &i))
2651 return VIEW_NO_FLAGS;
2652 } else {
2653 while (i < ARRAY_SIZE(data) && data[i].request != request)
2654 i++;
2655 if (i >= ARRAY_SIZE(data))
2656 die("Invalid request (%d)", request);
2659 if (data[i].map != NULL) {
2660 unsigned int *opt = menu[i].data;
2662 *opt = (*opt + 1) % data[i].map_size;
2663 if (data[i].map == ignore_space_map) {
2664 update_ignore_space_arg();
2665 string_format_size(msg, SIZEOF_STR,
2666 "Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2668 } else if (data[i].map == commit_order_map) {
2669 update_commit_order_arg();
2670 string_format_size(msg, SIZEOF_STR,
2671 "Using %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2673 } else {
2674 string_format_size(msg, SIZEOF_STR,
2675 "Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2678 } else {
2679 bool *option = menu[i].data;
2681 *option = !*option;
2682 string_format_size(msg, SIZEOF_STR,
2683 "%sabling %s", *option ? "En" : "Dis", menu[i].text);
2686 return data[i].reload_flags;
2691 * Navigation
2694 static bool
2695 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2697 if (lineno >= view->lines)
2698 lineno = view->lines > 0 ? view->lines - 1 : 0;
2700 if (offset > lineno || offset + view->height <= lineno) {
2701 unsigned long half = view->height / 2;
2703 if (lineno > half)
2704 offset = lineno - half;
2705 else
2706 offset = 0;
2709 if (offset != view->pos.offset || lineno != view->pos.lineno) {
2710 view->pos.offset = offset;
2711 view->pos.lineno = lineno;
2712 return TRUE;
2715 return FALSE;
2718 /* Scrolling backend */
2719 static void
2720 do_scroll_view(struct view *view, int lines)
2722 bool redraw_current_line = FALSE;
2724 /* The rendering expects the new offset. */
2725 view->pos.offset += lines;
2727 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2728 assert(lines);
2730 /* Move current line into the view. */
2731 if (view->pos.lineno < view->pos.offset) {
2732 view->pos.lineno = view->pos.offset;
2733 redraw_current_line = TRUE;
2734 } else if (view->pos.lineno >= view->pos.offset + view->height) {
2735 view->pos.lineno = view->pos.offset + view->height - 1;
2736 redraw_current_line = TRUE;
2739 assert(view->pos.offset <= view->pos.lineno && view->pos.lineno < view->lines);
2741 /* Redraw the whole screen if scrolling is pointless. */
2742 if (view->height < ABS(lines)) {
2743 redraw_view(view);
2745 } else {
2746 int line = lines > 0 ? view->height - lines : 0;
2747 int end = line + ABS(lines);
2749 scrollok(view->win, TRUE);
2750 wscrl(view->win, lines);
2751 scrollok(view->win, FALSE);
2753 while (line < end && draw_view_line(view, line))
2754 line++;
2756 if (redraw_current_line)
2757 draw_view_line(view, view->pos.lineno - view->pos.offset);
2758 wnoutrefresh(view->win);
2761 view->has_scrolled = TRUE;
2762 report_clear();
2765 /* Scroll frontend */
2766 static void
2767 scroll_view(struct view *view, enum request request)
2769 int lines = 1;
2771 assert(view_is_displayed(view));
2773 switch (request) {
2774 case REQ_SCROLL_FIRST_COL:
2775 view->pos.col = 0;
2776 redraw_view_from(view, 0);
2777 report_clear();
2778 return;
2779 case REQ_SCROLL_LEFT:
2780 if (view->pos.col == 0) {
2781 report("Cannot scroll beyond the first column");
2782 return;
2784 if (view->pos.col <= apply_step(opt_hscroll, view->width))
2785 view->pos.col = 0;
2786 else
2787 view->pos.col -= apply_step(opt_hscroll, view->width);
2788 redraw_view_from(view, 0);
2789 report_clear();
2790 return;
2791 case REQ_SCROLL_RIGHT:
2792 view->pos.col += apply_step(opt_hscroll, view->width);
2793 redraw_view(view);
2794 report_clear();
2795 return;
2796 case REQ_SCROLL_PAGE_DOWN:
2797 lines = view->height;
2798 case REQ_SCROLL_LINE_DOWN:
2799 if (view->pos.offset + lines > view->lines)
2800 lines = view->lines - view->pos.offset;
2802 if (lines == 0 || view->pos.offset + view->height >= view->lines) {
2803 report("Cannot scroll beyond the last line");
2804 return;
2806 break;
2808 case REQ_SCROLL_PAGE_UP:
2809 lines = view->height;
2810 case REQ_SCROLL_LINE_UP:
2811 if (lines > view->pos.offset)
2812 lines = view->pos.offset;
2814 if (lines == 0) {
2815 report("Cannot scroll beyond the first line");
2816 return;
2819 lines = -lines;
2820 break;
2822 default:
2823 die("request %d not handled in switch", request);
2826 do_scroll_view(view, lines);
2829 /* Cursor moving */
2830 static void
2831 move_view(struct view *view, enum request request)
2833 int scroll_steps = 0;
2834 int steps;
2836 switch (request) {
2837 case REQ_MOVE_FIRST_LINE:
2838 steps = -view->pos.lineno;
2839 break;
2841 case REQ_MOVE_LAST_LINE:
2842 steps = view->lines - view->pos.lineno - 1;
2843 break;
2845 case REQ_MOVE_PAGE_UP:
2846 steps = view->height > view->pos.lineno
2847 ? -view->pos.lineno : -view->height;
2848 break;
2850 case REQ_MOVE_PAGE_DOWN:
2851 steps = view->pos.lineno + view->height >= view->lines
2852 ? view->lines - view->pos.lineno - 1 : view->height;
2853 break;
2855 case REQ_MOVE_UP:
2856 case REQ_PREVIOUS:
2857 steps = -1;
2858 break;
2860 case REQ_MOVE_DOWN:
2861 case REQ_NEXT:
2862 steps = 1;
2863 break;
2865 default:
2866 die("request %d not handled in switch", request);
2869 if (steps <= 0 && view->pos.lineno == 0) {
2870 report("Cannot move beyond the first line");
2871 return;
2873 } else if (steps >= 0 && view->pos.lineno + 1 >= view->lines) {
2874 report("Cannot move beyond the last line");
2875 return;
2878 /* Move the current line */
2879 view->pos.lineno += steps;
2880 assert(0 <= view->pos.lineno && view->pos.lineno < view->lines);
2882 /* Check whether the view needs to be scrolled */
2883 if (view->pos.lineno < view->pos.offset ||
2884 view->pos.lineno >= view->pos.offset + view->height) {
2885 scroll_steps = steps;
2886 if (steps < 0 && -steps > view->pos.offset) {
2887 scroll_steps = -view->pos.offset;
2889 } else if (steps > 0) {
2890 if (view->pos.lineno == view->lines - 1 &&
2891 view->lines > view->height) {
2892 scroll_steps = view->lines - view->pos.offset - 1;
2893 if (scroll_steps >= view->height)
2894 scroll_steps -= view->height - 1;
2899 if (!view_is_displayed(view)) {
2900 view->pos.offset += scroll_steps;
2901 assert(0 <= view->pos.offset && view->pos.offset < view->lines);
2902 view->ops->select(view, &view->line[view->pos.lineno]);
2903 return;
2906 /* Repaint the old "current" line if we be scrolling */
2907 if (ABS(steps) < view->height)
2908 draw_view_line(view, view->pos.lineno - steps - view->pos.offset);
2910 if (scroll_steps) {
2911 do_scroll_view(view, scroll_steps);
2912 return;
2915 /* Draw the current line */
2916 draw_view_line(view, view->pos.lineno - view->pos.offset);
2918 wnoutrefresh(view->win);
2919 report_clear();
2924 * Searching
2927 static void search_view(struct view *view, enum request request);
2929 static bool
2930 grep_text(struct view *view, const char *text[])
2932 regmatch_t pmatch;
2933 size_t i;
2935 for (i = 0; text[i]; i++)
2936 if (*text[i] && !regexec(view->regex, text[i], 1, &pmatch, 0))
2937 return TRUE;
2938 return FALSE;
2941 static void
2942 select_view_line(struct view *view, unsigned long lineno)
2944 struct position old = view->pos;
2946 if (goto_view_line(view, view->pos.offset, lineno)) {
2947 if (view_is_displayed(view)) {
2948 if (old.offset != view->pos.offset) {
2949 redraw_view(view);
2950 } else {
2951 draw_view_line(view, old.lineno - view->pos.offset);
2952 draw_view_line(view, view->pos.lineno - view->pos.offset);
2953 wnoutrefresh(view->win);
2955 } else {
2956 view->ops->select(view, &view->line[view->pos.lineno]);
2961 static void
2962 find_next(struct view *view, enum request request)
2964 unsigned long lineno = view->pos.lineno;
2965 int direction;
2967 if (!*view->grep) {
2968 if (!*opt_search)
2969 report("No previous search");
2970 else
2971 search_view(view, request);
2972 return;
2975 switch (request) {
2976 case REQ_SEARCH:
2977 case REQ_FIND_NEXT:
2978 direction = 1;
2979 break;
2981 case REQ_SEARCH_BACK:
2982 case REQ_FIND_PREV:
2983 direction = -1;
2984 break;
2986 default:
2987 return;
2990 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2991 lineno += direction;
2993 /* Note, lineno is unsigned long so will wrap around in which case it
2994 * will become bigger than view->lines. */
2995 for (; lineno < view->lines; lineno += direction) {
2996 if (view->ops->grep(view, &view->line[lineno])) {
2997 select_view_line(view, lineno);
2998 report("Line %ld matches '%s'", lineno + 1, view->grep);
2999 return;
3003 report("No match found for '%s'", view->grep);
3006 static void
3007 search_view(struct view *view, enum request request)
3009 int regex_err;
3010 int regex_flags = opt_ignore_case ? REG_ICASE : 0;
3012 if (view->regex) {
3013 regfree(view->regex);
3014 *view->grep = 0;
3015 } else {
3016 view->regex = calloc(1, sizeof(*view->regex));
3017 if (!view->regex)
3018 return;
3021 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED | regex_flags);
3022 if (regex_err != 0) {
3023 char buf[SIZEOF_STR] = "unknown error";
3025 regerror(regex_err, view->regex, buf, sizeof(buf));
3026 report("Search failed: %s", buf);
3027 return;
3030 string_copy(view->grep, opt_search);
3032 find_next(view, request);
3036 * Incremental updating
3039 static inline bool
3040 check_position(struct position *pos)
3042 return pos->lineno || pos->col || pos->offset;
3045 static inline void
3046 clear_position(struct position *pos)
3048 memset(pos, 0, sizeof(*pos));
3051 static void
3052 reset_view(struct view *view)
3054 int i;
3056 if (view->ops->done)
3057 view->ops->done(view);
3059 for (i = 0; i < view->lines; i++)
3060 free(view->line[i].data);
3061 free(view->line);
3063 view->prev_pos = view->pos;
3064 clear_position(&view->pos);
3066 view->line = NULL;
3067 view->lines = 0;
3068 view->vid[0] = 0;
3069 view->custom_lines = 0;
3070 view->update_secs = 0;
3073 struct format_context {
3074 struct view *view;
3075 char buf[SIZEOF_STR];
3076 size_t bufpos;
3077 bool file_filter;
3080 static bool
3081 format_expand_arg(struct format_context *format, const char *name)
3083 static struct {
3084 const char *name;
3085 size_t namelen;
3086 const char *value;
3087 const char *value_if_empty;
3088 } vars[] = {
3089 #define FORMAT_VAR(name, value, value_if_empty) \
3090 { name, STRING_SIZE(name), value, value_if_empty }
3091 FORMAT_VAR("%(directory)", opt_path, "."),
3092 FORMAT_VAR("%(file)", opt_file, ""),
3093 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
3094 FORMAT_VAR("%(head)", ref_head, ""),
3095 FORMAT_VAR("%(commit)", ref_commit, ""),
3096 FORMAT_VAR("%(blob)", ref_blob, ""),
3097 FORMAT_VAR("%(branch)", ref_branch, ""),
3098 FORMAT_VAR("%(stash)", ref_stash, ""),
3100 int i;
3102 if (!prefixcmp(name, "%(prompt)")) {
3103 const char *value = read_prompt("Command argument: ");
3105 return string_format_from(format->buf, &format->bufpos, "%s", value);
3108 for (i = 0; i < ARRAY_SIZE(vars); i++) {
3109 const char *value;
3111 if (strncmp(name, vars[i].name, vars[i].namelen))
3112 continue;
3114 if (vars[i].value == opt_file && !format->file_filter)
3115 return TRUE;
3117 value = *vars[i].value ? vars[i].value : vars[i].value_if_empty;
3118 if (!*value)
3119 return TRUE;
3121 return string_format_from(format->buf, &format->bufpos, "%s", value);
3124 report("Unknown replacement: `%s`", name);
3125 return NULL;
3128 static bool
3129 format_append_arg(struct format_context *format, const char ***dst_argv, const char *arg)
3131 memset(format->buf, 0, sizeof(format->buf));
3132 format->bufpos = 0;
3134 while (arg) {
3135 char *next = strstr(arg, "%(");
3136 int len = next ? next - arg : strlen(arg);
3138 if (len && !string_format_from(format->buf, &format->bufpos, "%.*s", len, arg))
3139 return FALSE;
3141 if (next && !format_expand_arg(format, next))
3142 return FALSE;
3144 arg = next ? strchr(next, ')') + 1 : NULL;
3147 return argv_append(dst_argv, format->buf);
3150 static bool
3151 format_append_argv(struct format_context *format, const char ***dst_argv, const char *src_argv[])
3153 int argc;
3155 if (!src_argv)
3156 return TRUE;
3158 for (argc = 0; src_argv[argc]; argc++)
3159 if (!format_append_arg(format, dst_argv, src_argv[argc]))
3160 return FALSE;
3162 return src_argv[argc] == NULL;
3165 static bool
3166 format_argv(struct view *view, const char ***dst_argv, const char *src_argv[], bool first, bool file_filter)
3168 struct format_context format = { view, "", 0, file_filter };
3169 int argc;
3171 argv_free(*dst_argv);
3173 for (argc = 0; src_argv[argc]; argc++) {
3174 const char *arg = src_argv[argc];
3176 if (!strcmp(arg, "%(fileargs)")) {
3177 if (file_filter && !argv_append_array(dst_argv, opt_file_argv))
3178 break;
3180 } else if (!strcmp(arg, "%(diffargs)")) {
3181 if (!format_append_argv(&format, dst_argv, opt_diff_argv))
3182 break;
3184 } else if (!strcmp(arg, "%(blameargs)")) {
3185 if (!format_append_argv(&format, dst_argv, opt_blame_argv))
3186 break;
3188 } else if (!strcmp(arg, "%(revargs)") ||
3189 (first && !strcmp(arg, "%(commit)"))) {
3190 if (!argv_append_array(dst_argv, opt_rev_argv))
3191 break;
3193 } else if (!format_append_arg(&format, dst_argv, arg)) {
3194 break;
3198 return src_argv[argc] == NULL;
3201 static bool
3202 restore_view_position(struct view *view)
3204 /* A view without a previous view is the first view */
3205 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
3206 select_view_line(view, opt_lineno - 1);
3207 opt_lineno = 0;
3210 /* Ensure that the view position is in a valid state. */
3211 if (!check_position(&view->prev_pos) ||
3212 (view->pipe && view->lines <= view->prev_pos.lineno))
3213 return goto_view_line(view, view->pos.offset, view->pos.lineno);
3215 /* Changing the view position cancels the restoring. */
3216 /* FIXME: Changing back to the first line is not detected. */
3217 if (check_position(&view->pos)) {
3218 clear_position(&view->prev_pos);
3219 return FALSE;
3222 if (goto_view_line(view, view->prev_pos.offset, view->prev_pos.lineno) &&
3223 view_is_displayed(view))
3224 werase(view->win);
3226 view->pos.col = view->prev_pos.col;
3227 clear_position(&view->prev_pos);
3229 return TRUE;
3232 static void
3233 end_update(struct view *view, bool force)
3235 if (!view->pipe)
3236 return;
3237 while (!view->ops->read(view, NULL))
3238 if (!force)
3239 return;
3240 if (force)
3241 io_kill(view->pipe);
3242 io_done(view->pipe);
3243 view->pipe = NULL;
3246 static void
3247 setup_update(struct view *view, const char *vid)
3249 reset_view(view);
3250 /* XXX: Do not use string_copy_rev(), it copies until first space. */
3251 string_ncopy(view->vid, vid, strlen(vid));
3252 view->pipe = &view->io;
3253 view->start_time = time(NULL);
3256 static bool
3257 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
3259 bool extra = !!(flags & (OPEN_EXTRA));
3260 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA | OPEN_PAGER_MODE));
3261 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED | OPEN_STDIN);
3262 bool forward_stdin = flags & OPEN_FORWARD_STDIN;
3263 enum io_type io_type = forward_stdin ? IO_RD_STDIN : IO_RD;
3265 if ((!reload && !strcmp(view->vid, view->id)) ||
3266 ((flags & OPEN_REFRESH) && view->unrefreshable))
3267 return TRUE;
3269 if (view->pipe) {
3270 if (extra)
3271 io_done(view->pipe);
3272 else
3273 end_update(view, TRUE);
3276 view->unrefreshable = open_in_pager_mode(flags);
3278 if (!refresh && argv) {
3279 bool file_filter = !view_has_flags(view, VIEW_FILE_FILTER) || opt_file_filter;
3281 view->dir = dir;
3282 if (!format_argv(view, &view->argv, argv, !view->prev, file_filter)) {
3283 report("Failed to format %s arguments", view->name);
3284 return FALSE;
3287 /* Put the current ref_* value to the view title ref
3288 * member. This is needed by the blob view. Most other
3289 * views sets it automatically after loading because the
3290 * first line is a commit line. */
3291 string_copy_rev(view->ref, view->id);
3294 if (view->argv && view->argv[0] &&
3295 !io_run(&view->io, io_type, view->dir, opt_env, view->argv)) {
3296 report("Failed to open %s view", view->name);
3297 return FALSE;
3300 if (open_from_stdin(flags)) {
3301 if (!io_open(&view->io, "%s", ""))
3302 die("Failed to open stdin");
3305 if (!extra)
3306 setup_update(view, view->id);
3308 return TRUE;
3311 static bool
3312 update_view(struct view *view)
3314 char *line;
3315 /* Clear the view and redraw everything since the tree sorting
3316 * might have rearranged things. */
3317 bool redraw = view->lines == 0;
3318 bool can_read = TRUE;
3319 struct encoding *encoding = view->encoding ? view->encoding : default_encoding;
3321 if (!view->pipe)
3322 return TRUE;
3324 if (!io_can_read(view->pipe, FALSE)) {
3325 if (view->lines == 0 && view_is_displayed(view)) {
3326 time_t secs = time(NULL) - view->start_time;
3328 if (secs > 1 && secs > view->update_secs) {
3329 if (view->update_secs == 0)
3330 redraw_view(view);
3331 update_view_title(view);
3332 view->update_secs = secs;
3335 return TRUE;
3338 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
3339 if (encoding) {
3340 line = encoding_convert(encoding, line);
3343 if (!view->ops->read(view, line)) {
3344 report("Allocation failure");
3345 end_update(view, TRUE);
3346 return FALSE;
3351 int digits = count_digits(view->lines);
3353 /* Keep the displayed view in sync with line number scaling. */
3354 if (digits != view->digits) {
3355 view->digits = digits;
3356 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
3357 redraw = TRUE;
3361 if (io_error(view->pipe)) {
3362 report("Failed to read: %s", io_strerror(view->pipe));
3363 end_update(view, TRUE);
3365 } else if (io_eof(view->pipe)) {
3366 end_update(view, FALSE);
3369 if (restore_view_position(view))
3370 redraw = TRUE;
3372 if (!view_is_displayed(view))
3373 return TRUE;
3375 if (redraw || view->force_redraw)
3376 redraw_view_from(view, 0);
3377 else
3378 redraw_view_dirty(view);
3379 view->force_redraw = FALSE;
3381 /* Update the title _after_ the redraw so that if the redraw picks up a
3382 * commit reference in view->ref it'll be available here. */
3383 update_view_title(view);
3384 return TRUE;
3387 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
3389 static struct line *
3390 add_line(struct view *view, const void *data, enum line_type type, size_t data_size, bool custom)
3392 struct line *line;
3394 if (!realloc_lines(&view->line, view->lines, 1))
3395 return NULL;
3397 if (data_size) {
3398 void *alloc_data = calloc(1, data_size);
3400 if (!alloc_data)
3401 return NULL;
3403 if (data)
3404 memcpy(alloc_data, data, data_size);
3405 data = alloc_data;
3408 line = &view->line[view->lines++];
3409 memset(line, 0, sizeof(*line));
3410 line->type = type;
3411 line->data = (void *) data;
3412 line->dirty = 1;
3414 if (custom)
3415 view->custom_lines++;
3416 else
3417 line->lineno = view->lines - view->custom_lines;
3419 return line;
3422 static struct line *
3423 add_line_alloc_(struct view *view, void **ptr, enum line_type type, size_t data_size, bool custom)
3425 struct line *line = add_line(view, NULL, type, data_size, custom);
3427 if (line)
3428 *ptr = line->data;
3429 return line;
3432 #define add_line_alloc(view, data_ptr, type, extra_size, custom) \
3433 add_line_alloc_(view, (void **) data_ptr, type, sizeof(**data_ptr) + extra_size, custom)
3435 static struct line *
3436 add_line_nodata(struct view *view, enum line_type type)
3438 return add_line(view, NULL, type, 0, FALSE);
3441 static struct line *
3442 add_line_text(struct view *view, const char *text, enum line_type type)
3444 return add_line(view, text, type, strlen(text) + 1, FALSE);
3447 static struct line * PRINTF_LIKE(3, 4)
3448 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
3450 char buf[SIZEOF_STR];
3451 int retval;
3453 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
3454 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
3458 * View opening
3461 static void
3462 split_view(struct view *prev, struct view *view)
3464 display[1] = view;
3465 current_view = opt_focus_child ? 1 : 0;
3466 view->parent = prev;
3467 resize_display();
3469 if (prev->pos.lineno - prev->pos.offset >= prev->height) {
3470 /* Take the title line into account. */
3471 int lines = prev->pos.lineno - prev->pos.offset - prev->height + 1;
3473 /* Scroll the view that was split if the current line is
3474 * outside the new limited view. */
3475 do_scroll_view(prev, lines);
3478 if (view != prev && view_is_displayed(prev)) {
3479 /* "Blur" the previous view. */
3480 update_view_title(prev);
3484 static void
3485 maximize_view(struct view *view, bool redraw)
3487 memset(display, 0, sizeof(display));
3488 current_view = 0;
3489 display[current_view] = view;
3490 resize_display();
3491 if (redraw) {
3492 redraw_display(FALSE);
3493 report_clear();
3497 static void
3498 load_view(struct view *view, struct view *prev, enum open_flags flags)
3500 if (view->pipe)
3501 end_update(view, TRUE);
3502 if (view->ops->private_size) {
3503 if (!view->private)
3504 view->private = calloc(1, view->ops->private_size);
3505 else
3506 memset(view->private, 0, view->ops->private_size);
3509 /* When prev == view it means this is the first loaded view. */
3510 if (prev && view != prev) {
3511 view->prev = prev;
3514 if (!view->ops->open(view, flags))
3515 return;
3517 if (prev) {
3518 bool split = !!(flags & OPEN_SPLIT);
3520 if (split) {
3521 split_view(prev, view);
3522 } else {
3523 maximize_view(view, FALSE);
3527 restore_view_position(view);
3529 if (view->pipe && view->lines == 0) {
3530 /* Clear the old view and let the incremental updating refill
3531 * the screen. */
3532 werase(view->win);
3533 if (!(flags & (OPEN_RELOAD | OPEN_REFRESH)))
3534 clear_position(&view->prev_pos);
3535 report_clear();
3536 } else if (view_is_displayed(view)) {
3537 redraw_view(view);
3538 report_clear();
3542 #define refresh_view(view) load_view(view, NULL, OPEN_REFRESH)
3543 #define reload_view(view) load_view(view, NULL, OPEN_RELOAD)
3545 static void
3546 open_view(struct view *prev, enum request request, enum open_flags flags)
3548 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3549 struct view *view = VIEW(request);
3550 int nviews = displayed_views();
3552 assert(flags ^ OPEN_REFRESH);
3554 if (view == prev && nviews == 1 && !reload) {
3555 report("Already in %s view", view->name);
3556 return;
3559 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3560 report("The %s view is disabled in pager view", view->name);
3561 return;
3564 load_view(view, prev ? prev : view, flags);
3567 static void
3568 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3570 enum request request = view - views + REQ_OFFSET + 1;
3572 if (view->pipe)
3573 end_update(view, TRUE);
3574 view->dir = dir;
3576 if (!argv_copy(&view->argv, argv)) {
3577 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3578 } else {
3579 open_view(prev, request, flags | OPEN_PREPARED);
3583 static bool
3584 open_external_viewer(const char *argv[], const char *dir, bool confirm, const char *notice)
3586 bool ok;
3588 def_prog_mode(); /* save current tty modes */
3589 endwin(); /* restore original tty modes */
3590 ok = io_run_fg(argv, dir);
3591 if (confirm) {
3592 if (!ok && *notice)
3593 fprintf(stderr, "%s", notice);
3594 fprintf(stderr, "Press Enter to continue");
3595 getc(opt_tty);
3597 reset_prog_mode();
3598 redraw_display(TRUE);
3599 return ok;
3602 static void
3603 open_mergetool(const char *file)
3605 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3607 open_external_viewer(mergetool_argv, opt_cdup, TRUE, "");
3610 #define EDITOR_LINENO_MSG \
3611 "*** Your editor reported an error while opening the file.\n" \
3612 "*** This is probably because it doesn't support the line\n" \
3613 "*** number argument added automatically. The line number\n" \
3614 "*** has been disabled for now. You can permanently disable\n" \
3615 "*** it by adding the following line to ~/.tigrc\n" \
3616 "*** set editor-line-number = no\n"
3618 static void
3619 open_editor(const char *file, unsigned int lineno)
3621 const char *editor_argv[SIZEOF_ARG + 3] = { "vi", file, NULL };
3622 char editor_cmd[SIZEOF_STR];
3623 char lineno_cmd[SIZEOF_STR];
3624 const char *editor;
3625 int argc = 0;
3627 editor = getenv("GIT_EDITOR");
3628 if (!editor && *opt_editor)
3629 editor = opt_editor;
3630 if (!editor)
3631 editor = getenv("VISUAL");
3632 if (!editor)
3633 editor = getenv("EDITOR");
3634 if (!editor)
3635 editor = "vi";
3637 string_ncopy(editor_cmd, editor, strlen(editor));
3638 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3639 report("Failed to read editor command");
3640 return;
3643 if (lineno && opt_editor_lineno && string_format(lineno_cmd, "+%u", lineno))
3644 editor_argv[argc++] = lineno_cmd;
3645 editor_argv[argc] = file;
3646 if (!open_external_viewer(editor_argv, opt_cdup, TRUE, EDITOR_LINENO_MSG))
3647 opt_editor_lineno = FALSE;
3650 static enum request run_prompt_command(struct view *view, char *cmd);
3652 static enum request
3653 open_run_request(struct view *view, enum request request)
3655 struct run_request *req = get_run_request(request);
3656 const char **argv = NULL;
3657 bool confirmed = FALSE;
3659 request = REQ_NONE;
3661 if (!req) {
3662 report("Unknown run request");
3663 return request;
3666 if (format_argv(view, &argv, req->argv, FALSE, TRUE)) {
3667 if (req->internal) {
3668 char cmd[SIZEOF_STR];
3670 if (argv_to_string(argv, cmd, sizeof(cmd), " ")) {
3671 request = run_prompt_command(view, cmd);
3674 else {
3675 confirmed = !req->confirm;
3677 if (req->confirm) {
3678 char cmd[SIZEOF_STR], prompt[SIZEOF_STR];
3679 const char *and_exit = req->exit ? " and exit" : "";
3681 if (argv_to_string(argv, cmd, sizeof(cmd), " ") &&
3682 string_format(prompt, "Run `%s`%s?", cmd, and_exit) &&
3683 prompt_yesno(prompt)) {
3684 confirmed = TRUE;
3688 if (confirmed && argv_remove_quotes(argv)) {
3689 if (req->silent)
3690 io_run_bg(argv);
3691 else
3692 open_external_viewer(argv, NULL, !req->exit, "");
3697 if (argv)
3698 argv_free(argv);
3699 free(argv);
3701 if (request == REQ_NONE) {
3702 if (req->confirm && !confirmed)
3703 request = REQ_NONE;
3705 else if (req->exit)
3706 request = REQ_QUIT;
3708 else if (!view->unrefreshable)
3709 request = REQ_REFRESH;
3711 return request;
3715 * User request switch noodle
3718 static int
3719 view_driver(struct view *view, enum request request)
3721 int i;
3723 if (request == REQ_NONE)
3724 return TRUE;
3726 if (request > REQ_NONE) {
3727 request = open_run_request(view, request);
3729 // exit quickly rather than going through view_request and back
3730 if (request == REQ_QUIT)
3731 return FALSE;
3734 request = view_request(view, request);
3735 if (request == REQ_NONE)
3736 return TRUE;
3738 switch (request) {
3739 case REQ_MOVE_UP:
3740 case REQ_MOVE_DOWN:
3741 case REQ_MOVE_PAGE_UP:
3742 case REQ_MOVE_PAGE_DOWN:
3743 case REQ_MOVE_FIRST_LINE:
3744 case REQ_MOVE_LAST_LINE:
3745 move_view(view, request);
3746 break;
3748 case REQ_SCROLL_FIRST_COL:
3749 case REQ_SCROLL_LEFT:
3750 case REQ_SCROLL_RIGHT:
3751 case REQ_SCROLL_LINE_DOWN:
3752 case REQ_SCROLL_LINE_UP:
3753 case REQ_SCROLL_PAGE_DOWN:
3754 case REQ_SCROLL_PAGE_UP:
3755 scroll_view(view, request);
3756 break;
3758 case REQ_VIEW_MAIN:
3759 case REQ_VIEW_DIFF:
3760 case REQ_VIEW_LOG:
3761 case REQ_VIEW_TREE:
3762 case REQ_VIEW_HELP:
3763 case REQ_VIEW_BRANCH:
3764 case REQ_VIEW_BLAME:
3765 case REQ_VIEW_BLOB:
3766 case REQ_VIEW_STATUS:
3767 case REQ_VIEW_STAGE:
3768 case REQ_VIEW_PAGER:
3769 case REQ_VIEW_STASH:
3770 open_view(view, request, OPEN_DEFAULT);
3771 break;
3773 case REQ_NEXT:
3774 case REQ_PREVIOUS:
3775 if (view->parent) {
3776 int line;
3778 view = view->parent;
3779 line = view->pos.lineno;
3780 view_request(view, request);
3781 move_view(view, request);
3782 if (view_is_displayed(view))
3783 update_view_title(view);
3784 if (line != view->pos.lineno)
3785 view_request(view, REQ_ENTER);
3786 } else {
3787 move_view(view, request);
3789 break;
3791 case REQ_VIEW_NEXT:
3793 int nviews = displayed_views();
3794 int next_view = (current_view + 1) % nviews;
3796 if (next_view == current_view) {
3797 report("Only one view is displayed");
3798 break;
3801 current_view = next_view;
3802 /* Blur out the title of the previous view. */
3803 update_view_title(view);
3804 report_clear();
3805 break;
3807 case REQ_REFRESH:
3808 report("Refreshing is not supported by the %s view", view->name);
3809 break;
3811 case REQ_PARENT:
3812 report("Moving to parent is not supported by the the %s view", view->name);
3813 break;
3815 case REQ_BACK:
3816 report("Going back is not supported for by %s view", view->name);
3817 break;
3819 case REQ_MAXIMIZE:
3820 if (displayed_views() == 2)
3821 maximize_view(view, TRUE);
3822 break;
3824 case REQ_OPTIONS:
3825 case REQ_TOGGLE_LINENO:
3826 case REQ_TOGGLE_DATE:
3827 case REQ_TOGGLE_AUTHOR:
3828 case REQ_TOGGLE_FILENAME:
3829 case REQ_TOGGLE_GRAPHIC:
3830 case REQ_TOGGLE_REV_GRAPH:
3831 case REQ_TOGGLE_REFS:
3832 case REQ_TOGGLE_CHANGES:
3833 case REQ_TOGGLE_IGNORE_SPACE:
3834 case REQ_TOGGLE_ID:
3835 case REQ_TOGGLE_FILES:
3836 case REQ_TOGGLE_TITLE_OVERFLOW:
3838 char action[SIZEOF_STR] = "";
3839 enum view_flag flags = toggle_option(view, request, action);
3841 foreach_displayed_view(view, i) {
3842 if (view_has_flags(view, flags) && !view->unrefreshable)
3843 reload_view(view);
3844 else
3845 redraw_view(view);
3848 if (*action)
3849 report("%s", action);
3851 break;
3853 case REQ_TOGGLE_SORT_FIELD:
3854 case REQ_TOGGLE_SORT_ORDER:
3855 report("Sorting is not yet supported for the %s view", view->name);
3856 break;
3858 case REQ_DIFF_CONTEXT_UP:
3859 case REQ_DIFF_CONTEXT_DOWN:
3860 report("Changing the diff context is not yet supported for the %s view", view->name);
3861 break;
3863 case REQ_SEARCH:
3864 case REQ_SEARCH_BACK:
3865 search_view(view, request);
3866 break;
3868 case REQ_FIND_NEXT:
3869 case REQ_FIND_PREV:
3870 find_next(view, request);
3871 break;
3873 case REQ_STOP_LOADING:
3874 foreach_view(view, i) {
3875 if (view->pipe)
3876 report("Stopped loading the %s view", view->name),
3877 end_update(view, TRUE);
3879 break;
3881 case REQ_SHOW_VERSION:
3882 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3883 return TRUE;
3885 case REQ_SCREEN_REDRAW:
3886 redraw_display(TRUE);
3887 break;
3889 case REQ_EDIT:
3890 report("Nothing to edit");
3891 break;
3893 case REQ_ENTER:
3894 report("Nothing to enter");
3895 break;
3897 case REQ_VIEW_CLOSE:
3898 /* XXX: Mark closed views by letting view->prev point to the
3899 * view itself. Parents to closed view should never be
3900 * followed. */
3901 if (view->prev && view->prev != view) {
3902 maximize_view(view->prev, TRUE);
3903 view->prev = view;
3904 break;
3906 /* Fall-through */
3907 case REQ_QUIT:
3908 return FALSE;
3910 default:
3911 report("Unknown key, press %s for help",
3912 get_view_key(view, REQ_VIEW_HELP));
3913 return TRUE;
3916 return TRUE;
3921 * View backend utilities
3924 enum sort_field {
3925 ORDERBY_NAME,
3926 ORDERBY_DATE,
3927 ORDERBY_AUTHOR,
3930 struct sort_state {
3931 const enum sort_field *fields;
3932 size_t size, current;
3933 bool reverse;
3936 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3937 #define get_sort_field(state) ((state).fields[(state).current])
3938 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3940 static void
3941 sort_view(struct view *view, enum request request, struct sort_state *state,
3942 int (*compare)(const void *, const void *))
3944 switch (request) {
3945 case REQ_TOGGLE_SORT_FIELD:
3946 state->current = (state->current + 1) % state->size;
3947 break;
3949 case REQ_TOGGLE_SORT_ORDER:
3950 state->reverse = !state->reverse;
3951 break;
3952 default:
3953 die("Not a sort request");
3956 qsort(view->line, view->lines, sizeof(*view->line), compare);
3957 redraw_view(view);
3960 static bool
3961 update_diff_context(enum request request)
3963 int diff_context = opt_diff_context;
3965 switch (request) {
3966 case REQ_DIFF_CONTEXT_UP:
3967 opt_diff_context += 1;
3968 update_diff_context_arg(opt_diff_context);
3969 break;
3971 case REQ_DIFF_CONTEXT_DOWN:
3972 if (opt_diff_context == 0) {
3973 report("Diff context cannot be less than zero");
3974 break;
3976 opt_diff_context -= 1;
3977 update_diff_context_arg(opt_diff_context);
3978 break;
3980 default:
3981 die("Not a diff context request");
3984 return diff_context != opt_diff_context;
3987 DEFINE_ALLOCATOR(realloc_paths, const char *, 256)
3989 /* Small cache to reduce memory consumption. It uses binary search to
3990 * lookup or find place to position new entries. No entries are ever
3991 * freed. */
3992 static const char *
3993 get_path(const char *path)
3995 static const char **paths;
3996 static size_t paths_size;
3997 int from = 0, to = paths_size - 1;
3998 char *entry;
4000 while (from <= to) {
4001 size_t pos = (to + from) / 2;
4002 int cmp = strcmp(path, paths[pos]);
4004 if (!cmp)
4005 return paths[pos];
4007 if (cmp < 0)
4008 to = pos - 1;
4009 else
4010 from = pos + 1;
4013 if (!realloc_paths(&paths, paths_size, 1))
4014 return NULL;
4015 entry = strdup(path);
4016 if (!entry)
4017 return NULL;
4019 memmove(paths + from + 1, paths + from, (paths_size - from) * sizeof(*paths));
4020 paths[from] = entry;
4021 paths_size++;
4023 return entry;
4026 DEFINE_ALLOCATOR(realloc_authors, struct ident *, 256)
4028 /* Small author cache to reduce memory consumption. It uses binary
4029 * search to lookup or find place to position new entries. No entries
4030 * are ever freed. */
4031 static struct ident *
4032 get_author(const char *name, const char *email)
4034 static struct ident **authors;
4035 static size_t authors_size;
4036 int from = 0, to = authors_size - 1;
4037 struct ident *ident;
4039 while (from <= to) {
4040 size_t pos = (to + from) / 2;
4041 int cmp = strcmp(name, authors[pos]->name);
4043 if (!cmp)
4044 return authors[pos];
4046 if (cmp < 0)
4047 to = pos - 1;
4048 else
4049 from = pos + 1;
4052 if (!realloc_authors(&authors, authors_size, 1))
4053 return NULL;
4054 ident = calloc(1, sizeof(*ident));
4055 if (!ident)
4056 return NULL;
4057 ident->name = strdup(name);
4058 ident->email = strdup(email);
4059 if (!ident->name || !ident->email) {
4060 free((void *) ident->name);
4061 free(ident);
4062 return NULL;
4065 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
4066 authors[from] = ident;
4067 authors_size++;
4069 return ident;
4072 static void
4073 parse_timesec(struct time *time, const char *sec)
4075 time->sec = (time_t) atol(sec);
4078 static void
4079 parse_timezone(struct time *time, const char *zone)
4081 long tz;
4083 tz = ('0' - zone[1]) * 60 * 60 * 10;
4084 tz += ('0' - zone[2]) * 60 * 60;
4085 tz += ('0' - zone[3]) * 60 * 10;
4086 tz += ('0' - zone[4]) * 60;
4088 if (zone[0] == '-')
4089 tz = -tz;
4091 time->tz = tz;
4092 time->sec -= tz;
4095 /* Parse author lines where the name may be empty:
4096 * author <email@address.tld> 1138474660 +0100
4098 static void
4099 parse_author_line(char *ident, const struct ident **author, struct time *time)
4101 char *nameend = strchr(ident, '<');
4102 char *emailend = strchr(ident, '>');
4103 const char *name, *email = "";
4105 if (nameend && emailend)
4106 *nameend = *emailend = 0;
4107 name = chomp_string(ident);
4108 if (nameend)
4109 email = chomp_string(nameend + 1);
4110 if (!*name)
4111 name = *email ? email : unknown_ident.name;
4112 if (!*email)
4113 email = *name ? name : unknown_ident.email;
4115 *author = get_author(name, email);
4117 /* Parse epoch and timezone */
4118 if (time && emailend && emailend[1] == ' ') {
4119 char *secs = emailend + 2;
4120 char *zone = strchr(secs, ' ');
4122 parse_timesec(time, secs);
4124 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
4125 parse_timezone(time, zone + 1);
4129 static struct line *
4130 find_line_by_type(struct view *view, struct line *line, enum line_type type, int direction)
4132 for (; view_has_line(view, line); line += direction)
4133 if (line->type == type)
4134 return line;
4136 return NULL;
4139 #define find_prev_line_by_type(view, line, type) \
4140 find_line_by_type(view, line, type, -1)
4142 #define find_next_line_by_type(view, line, type) \
4143 find_line_by_type(view, line, type, 1)
4146 * View history
4149 struct view_state {
4150 struct view_state *prev; /* Entry below this in the stack */
4151 struct position position; /* View position to restore */
4152 void *data; /* View specific state */
4155 struct view_history {
4156 size_t state_alloc;
4157 struct view_state *stack;
4158 struct position position;
4161 static bool
4162 view_history_is_empty(struct view_history *history)
4164 return !history->stack;
4167 static struct view_state *
4168 push_view_history_state(struct view_history *history, struct position *position, void *data)
4170 struct view_state *state = history->stack;
4172 if (state && data && history->state_alloc &&
4173 !memcmp(state->data, data, history->state_alloc))
4174 return NULL;
4176 state = calloc(1, sizeof(*state) + history->state_alloc);
4177 if (!state)
4178 return NULL;
4180 state->prev = history->stack;
4181 history->stack = state;
4182 clear_position(&history->position);
4183 state->position = *position;
4184 state->data = &state[1];
4185 if (data && history->state_alloc)
4186 memcpy(state->data, data, history->state_alloc);
4187 return state;
4190 static bool
4191 pop_view_history_state(struct view_history *history, struct position *position, void *data)
4193 struct view_state *state = history->stack;
4195 if (view_history_is_empty(history))
4196 return FALSE;
4198 history->position = state->position;
4199 history->stack = state->prev;
4201 if (data && history->state_alloc)
4202 memcpy(data, state->data, history->state_alloc);
4203 if (position)
4204 *position = state->position;
4206 free(state);
4207 return TRUE;
4210 static void
4211 reset_view_history(struct view_history *history)
4213 while (pop_view_history_state(history, NULL, NULL))
4218 * Blame
4221 struct blame_commit {
4222 char id[SIZEOF_REV]; /* SHA1 ID. */
4223 char title[128]; /* First line of the commit message. */
4224 const struct ident *author; /* Author of the commit. */
4225 struct time time; /* Date from the author ident. */
4226 const char *filename; /* Name of file. */
4227 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
4228 const char *parent_filename; /* Parent/previous name of file. */
4231 struct blame_header {
4232 char id[SIZEOF_REV]; /* SHA1 ID. */
4233 size_t orig_lineno;
4234 size_t lineno;
4235 size_t group;
4238 static bool
4239 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4241 const char *pos = *posref;
4243 *posref = NULL;
4244 pos = strchr(pos + 1, ' ');
4245 if (!pos || !isdigit(pos[1]))
4246 return FALSE;
4247 *number = atoi(pos + 1);
4248 if (*number < min || *number > max)
4249 return FALSE;
4251 *posref = pos;
4252 return TRUE;
4255 static bool
4256 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
4258 const char *pos = text + SIZEOF_REV - 2;
4260 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4261 return FALSE;
4263 string_ncopy(header->id, text, SIZEOF_REV);
4265 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
4266 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
4267 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
4268 return FALSE;
4270 return TRUE;
4273 static bool
4274 match_blame_header(const char *name, char **line)
4276 size_t namelen = strlen(name);
4277 bool matched = !strncmp(name, *line, namelen);
4279 if (matched)
4280 *line += namelen;
4282 return matched;
4285 static bool
4286 parse_blame_info(struct blame_commit *commit, char *line)
4288 if (match_blame_header("author ", &line)) {
4289 parse_author_line(line, &commit->author, NULL);
4291 } else if (match_blame_header("author-time ", &line)) {
4292 parse_timesec(&commit->time, line);
4294 } else if (match_blame_header("author-tz ", &line)) {
4295 parse_timezone(&commit->time, line);
4297 } else if (match_blame_header("summary ", &line)) {
4298 string_ncopy(commit->title, line, strlen(line));
4300 } else if (match_blame_header("previous ", &line)) {
4301 if (strlen(line) <= SIZEOF_REV)
4302 return FALSE;
4303 string_copy_rev(commit->parent_id, line);
4304 line += SIZEOF_REV;
4305 commit->parent_filename = get_path(line);
4306 if (!commit->parent_filename)
4307 return TRUE;
4309 } else if (match_blame_header("filename ", &line)) {
4310 commit->filename = get_path(line);
4311 return TRUE;
4314 return FALSE;
4318 * Pager backend
4321 static bool
4322 pager_draw(struct view *view, struct line *line, unsigned int lineno)
4324 if (draw_lineno(view, lineno))
4325 return TRUE;
4327 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4328 return TRUE;
4330 draw_text(view, line->type, line->data);
4331 return TRUE;
4334 static bool
4335 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
4337 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
4338 char ref[SIZEOF_STR];
4340 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
4341 return TRUE;
4343 /* This is the only fatal call, since it can "corrupt" the buffer. */
4344 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
4345 return FALSE;
4347 return TRUE;
4350 static void
4351 add_pager_refs(struct view *view, const char *commit_id)
4353 char buf[SIZEOF_STR];
4354 struct ref_list *list;
4355 size_t bufpos = 0, i;
4356 const char *sep = "Refs: ";
4357 bool is_tag = FALSE;
4359 list = get_ref_list(commit_id);
4360 if (!list) {
4361 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
4362 goto try_add_describe_ref;
4363 return;
4366 for (i = 0; i < list->size; i++) {
4367 struct ref *ref = list->refs[i];
4368 const char *fmt = ref->tag ? "%s[%s]" :
4369 ref->remote ? "%s<%s>" : "%s%s";
4371 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
4372 return;
4373 sep = ", ";
4374 if (ref->tag)
4375 is_tag = TRUE;
4378 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
4379 try_add_describe_ref:
4380 /* Add <tag>-g<commit_id> "fake" reference. */
4381 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
4382 return;
4385 if (bufpos == 0)
4386 return;
4388 add_line_text(view, buf, LINE_PP_REFS);
4391 static struct line *
4392 pager_wrap_line(struct view *view, const char *data, enum line_type type)
4394 size_t first_line = 0;
4395 bool has_first_line = FALSE;
4396 size_t datalen = strlen(data);
4397 size_t lineno = 0;
4399 while (datalen > 0 || !has_first_line) {
4400 bool wrapped = !!first_line;
4401 size_t linelen = string_expanded_length(data, datalen, opt_tab_size, view->width - !!wrapped);
4402 struct line *line;
4403 char *text;
4405 line = add_line(view, NULL, type, linelen + 1, wrapped);
4406 if (!line)
4407 break;
4408 if (!has_first_line) {
4409 first_line = view->lines - 1;
4410 has_first_line = TRUE;
4413 if (!wrapped)
4414 lineno = line->lineno;
4416 line->wrapped = wrapped;
4417 line->lineno = lineno;
4418 text = line->data;
4419 if (linelen)
4420 strncpy(text, data, linelen);
4421 text[linelen] = 0;
4423 datalen -= linelen;
4424 data += linelen;
4427 return has_first_line ? &view->line[first_line] : NULL;
4430 static bool
4431 pager_common_read(struct view *view, const char *data, enum line_type type)
4433 struct line *line;
4435 if (!data)
4436 return TRUE;
4438 if (opt_wrap_lines) {
4439 line = pager_wrap_line(view, data, type);
4440 } else {
4441 line = add_line_text(view, data, type);
4444 if (!line)
4445 return FALSE;
4447 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
4448 add_pager_refs(view, data + STRING_SIZE("commit "));
4450 return TRUE;
4453 static bool
4454 pager_read(struct view *view, char *data)
4456 if (!data)
4457 return TRUE;
4459 return pager_common_read(view, data, get_line_type(data));
4462 static enum request
4463 pager_request(struct view *view, enum request request, struct line *line)
4465 int split = 0;
4467 if (request != REQ_ENTER)
4468 return request;
4470 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
4471 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4472 split = 1;
4475 /* Always scroll the view even if it was split. That way
4476 * you can use Enter to scroll through the log view and
4477 * split open each commit diff. */
4478 scroll_view(view, REQ_SCROLL_LINE_DOWN);
4480 /* FIXME: A minor workaround. Scrolling the view will call report_clear()
4481 * but if we are scrolling a non-current view this won't properly
4482 * update the view title. */
4483 if (split)
4484 update_view_title(view);
4486 return REQ_NONE;
4489 static bool
4490 pager_grep(struct view *view, struct line *line)
4492 const char *text[] = { line->data, NULL };
4494 return grep_text(view, text);
4497 static void
4498 pager_select(struct view *view, struct line *line)
4500 if (line->type == LINE_COMMIT) {
4501 string_copy_rev_from_commit_line(ref_commit, line->data);
4502 if (!view_has_flags(view, VIEW_NO_REF))
4503 string_copy_rev(view->ref, ref_commit);
4507 struct log_state {
4508 /* Used for tracking when we need to recalculate the previous
4509 * commit, for example when the user scrolls up or uses the page
4510 * up/down in the log view. */
4511 int last_lineno;
4512 enum line_type last_type;
4515 static void
4516 log_select(struct view *view, struct line *line)
4518 struct log_state *state = view->private;
4519 int last_lineno = state->last_lineno;
4521 if (!last_lineno || abs(last_lineno - line->lineno) > 1
4522 || (state->last_type == LINE_COMMIT && last_lineno > line->lineno)) {
4523 const struct line *commit_line = find_prev_line_by_type(view, line, LINE_COMMIT);
4525 if (commit_line)
4526 string_copy_rev_from_commit_line(view->ref, commit_line->data);
4529 if (line->type == LINE_COMMIT && !view_has_flags(view, VIEW_NO_REF)) {
4530 string_copy_rev_from_commit_line(view->ref, (char *)line->data);
4532 string_copy_rev(ref_commit, view->ref);
4533 state->last_lineno = line->lineno;
4534 state->last_type = line->type;
4537 static bool
4538 pager_open(struct view *view, enum open_flags flags)
4540 if (!open_from_stdin(flags) && !view->lines) {
4541 report("No pager content, press %s to run command from prompt",
4542 get_view_key(view, REQ_PROMPT));
4543 return FALSE;
4546 return begin_update(view, NULL, NULL, flags);
4549 static struct view_ops pager_ops = {
4550 "line",
4551 { "pager" },
4552 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
4554 pager_open,
4555 pager_read,
4556 pager_draw,
4557 pager_request,
4558 pager_grep,
4559 pager_select,
4562 static bool
4563 log_open(struct view *view, enum open_flags flags)
4565 static const char *log_argv[] = {
4566 "git", "log", encoding_arg, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
4569 return begin_update(view, NULL, log_argv, flags);
4572 static enum request
4573 log_request(struct view *view, enum request request, struct line *line)
4575 switch (request) {
4576 case REQ_REFRESH:
4577 load_refs(TRUE);
4578 refresh_view(view);
4579 return REQ_NONE;
4581 case REQ_ENTER:
4582 if (!display[1] || strcmp(display[1]->vid, view->ref))
4583 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
4584 return REQ_NONE;
4586 default:
4587 return request;
4591 static struct view_ops log_ops = {
4592 "line",
4593 { "log" },
4594 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF | VIEW_SEND_CHILD_ENTER | VIEW_LOG_LIKE,
4595 sizeof(struct log_state),
4596 log_open,
4597 pager_read,
4598 pager_draw,
4599 log_request,
4600 pager_grep,
4601 log_select,
4604 struct diff_state {
4605 bool after_commit_title;
4606 bool after_diff;
4607 bool reading_diff_stat;
4608 bool combined_diff;
4611 #define DIFF_LINE_COMMIT_TITLE 1
4613 static bool
4614 diff_open(struct view *view, enum open_flags flags)
4616 static const char *diff_argv[] = {
4617 "git", "show", encoding_arg, "--pretty=fuller", "--root",
4618 "--patch-with-stat",
4619 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
4620 "%(diffargs)", "--no-color", "%(commit)", "--", "%(fileargs)", NULL
4623 return begin_update(view, NULL, diff_argv, flags);
4626 static bool
4627 diff_common_read(struct view *view, const char *data, struct diff_state *state)
4629 enum line_type type = get_line_type(data);
4631 if (!view->lines && type != LINE_COMMIT)
4632 state->reading_diff_stat = TRUE;
4634 if (state->combined_diff && !state->after_diff && data[0] == ' ' && data[1] != ' ')
4635 state->reading_diff_stat = TRUE;
4637 if (state->reading_diff_stat) {
4638 size_t len = strlen(data);
4639 char *pipe = strchr(data, '|');
4640 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
4641 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
4642 bool has_rename = data[len - 1] == '0' && (strstr(data, "=>") || !strncmp(data, " ...", 4));
4644 if (pipe && (has_histogram || has_bin_diff || has_rename)) {
4645 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
4646 } else {
4647 state->reading_diff_stat = FALSE;
4650 } else if (!strcmp(data, "---")) {
4651 state->reading_diff_stat = TRUE;
4654 if (!state->after_commit_title && !prefixcmp(data, " ")) {
4655 struct line *line = add_line_text(view, data, LINE_DEFAULT);
4657 if (line)
4658 line->user_flags |= DIFF_LINE_COMMIT_TITLE;
4659 state->after_commit_title = TRUE;
4660 return line != NULL;
4663 if (type == LINE_DIFF_HEADER) {
4664 const int len = line_info[LINE_DIFF_HEADER].linelen;
4666 state->after_diff = TRUE;
4667 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
4668 !strncmp(data + len, "cc ", strlen("cc ")))
4669 state->combined_diff = TRUE;
4671 } else if (type == LINE_PP_MERGE) {
4672 state->combined_diff = TRUE;
4675 /* ADD2 and DEL2 are only valid in combined diff hunks */
4676 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
4677 type = LINE_DEFAULT;
4679 return pager_common_read(view, data, type);
4682 static bool
4683 diff_find_stat_entry(struct view *view, struct line *line, enum line_type type)
4685 struct line *marker = find_next_line_by_type(view, line, type);
4687 return marker &&
4688 line == find_prev_line_by_type(view, marker, LINE_DIFF_HEADER);
4691 static enum request
4692 diff_common_enter(struct view *view, enum request request, struct line *line)
4694 if (line->type == LINE_DIFF_STAT) {
4695 int file_number = 0;
4697 while (view_has_line(view, line) && line->type == LINE_DIFF_STAT) {
4698 file_number++;
4699 line--;
4702 for (line = view->line; view_has_line(view, line); line++) {
4703 line = find_next_line_by_type(view, line, LINE_DIFF_HEADER);
4704 if (!line)
4705 break;
4707 if (diff_find_stat_entry(view, line, LINE_DIFF_INDEX)
4708 || diff_find_stat_entry(view, line, LINE_DIFF_SIMILARITY)) {
4709 if (file_number == 1) {
4710 break;
4712 file_number--;
4716 if (!line) {
4717 report("Failed to find file diff");
4718 return REQ_NONE;
4721 select_view_line(view, line - view->line);
4722 report_clear();
4723 return REQ_NONE;
4725 } else {
4726 return pager_request(view, request, line);
4730 static bool
4731 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
4733 char *sep = strchr(*text, c);
4735 if (sep != NULL) {
4736 *sep = 0;
4737 draw_text(view, *type, *text);
4738 *sep = c;
4739 *text = sep;
4740 *type = next_type;
4743 return sep != NULL;
4746 static bool
4747 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
4749 char *text = line->data;
4750 enum line_type type = line->type;
4752 if (draw_lineno(view, lineno))
4753 return TRUE;
4755 if (line->wrapped && draw_text(view, LINE_DELIMITER, "+"))
4756 return TRUE;
4758 if (type == LINE_DIFF_STAT) {
4759 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
4760 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
4761 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
4762 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
4763 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
4764 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
4765 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
4767 } else {
4768 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
4769 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
4773 if (line->user_flags & DIFF_LINE_COMMIT_TITLE)
4774 draw_commit_title(view, text, 4);
4775 else
4776 draw_text(view, type, text);
4777 return TRUE;
4780 static bool
4781 diff_read(struct view *view, char *data)
4783 struct diff_state *state = view->private;
4785 if (!data) {
4786 /* Fall back to retry if no diff will be shown. */
4787 if (view->lines == 0 && opt_file_argv) {
4788 int pos = argv_size(view->argv)
4789 - argv_size(opt_file_argv) - 1;
4791 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
4792 for (; view->argv[pos]; pos++) {
4793 free((void *) view->argv[pos]);
4794 view->argv[pos] = NULL;
4797 if (view->pipe)
4798 io_done(view->pipe);
4799 if (io_run(&view->io, IO_RD, view->dir, opt_env, view->argv))
4800 return FALSE;
4803 return TRUE;
4806 return diff_common_read(view, data, state);
4809 static bool
4810 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
4811 struct blame_header *header, struct blame_commit *commit)
4813 char line_arg[SIZEOF_STR];
4814 const char *blame_argv[] = {
4815 "git", "blame", encoding_arg, "-p", line_arg, ref, "--", file, NULL
4817 struct io io;
4818 bool ok = FALSE;
4819 char *buf;
4821 if (!string_format(line_arg, "-L%ld,+1", lineno))
4822 return FALSE;
4824 if (!io_run(&io, IO_RD, opt_cdup, opt_env, blame_argv))
4825 return FALSE;
4827 while ((buf = io_get(&io, '\n', TRUE))) {
4828 if (header) {
4829 if (!parse_blame_header(header, buf, 9999999))
4830 break;
4831 header = NULL;
4833 } else if (parse_blame_info(commit, buf)) {
4834 ok = commit->filename != NULL;
4835 break;
4839 if (io_error(&io))
4840 ok = FALSE;
4842 io_done(&io);
4843 return ok;
4846 struct chunk_header_position {
4847 unsigned long position;
4848 unsigned long lines;
4851 struct chunk_header {
4852 struct chunk_header_position old;
4853 struct chunk_header_position new;
4856 static bool
4857 parse_ulong(const char **pos_ptr, unsigned long *value, const char *skip)
4859 const char *start = *pos_ptr;
4860 char *end;
4862 if (!isdigit(*start))
4863 return 0;
4865 *value = strtoul(start, &end, 10);
4866 if (end == start)
4867 return FALSE;
4869 start = end;
4870 while (skip && *start && strchr(skip, *start))
4871 start++;
4872 *pos_ptr = start;
4873 return TRUE;
4876 static bool
4877 parse_chunk_header(struct chunk_header *header, const char *line)
4879 if (prefixcmp(line, "@@ -"))
4880 return FALSE;
4882 line += STRING_SIZE("@@ -");
4884 return parse_ulong(&line, &header->old.position, ",") &&
4885 parse_ulong(&line, &header->old.lines, " +") &&
4886 parse_ulong(&line, &header->new.position, ",") &&
4887 parse_ulong(&line, &header->new.lines, NULL);
4890 static unsigned int
4891 diff_get_lineno(struct view *view, struct line *line)
4893 const struct line *header, *chunk;
4894 unsigned int lineno;
4895 struct chunk_header chunk_header;
4897 /* Verify that we are after a diff header and one of its chunks */
4898 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4899 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4900 if (!header || !chunk || chunk < header)
4901 return 0;
4904 * In a chunk header, the number after the '+' sign is the number of its
4905 * following line, in the new version of the file. We increment this
4906 * number for each non-deletion line, until the given line position.
4908 if (!parse_chunk_header(&chunk_header, chunk->data))
4909 return 0;
4911 lineno = chunk_header.old.position;
4912 chunk++;
4913 while (chunk++ < line)
4914 if (chunk->type != LINE_DIFF_DEL)
4915 lineno++;
4917 return lineno;
4920 static bool
4921 parse_chunk_lineno(unsigned long *lineno, const char *chunk, int marker)
4923 struct chunk_header chunk_header;
4925 if (!parse_chunk_header(&chunk_header, chunk))
4926 return 0;
4928 return marker == '-' ? chunk_header.old.position : chunk_header.new.position;
4931 static enum request
4932 diff_trace_origin(struct view *view, struct line *line)
4934 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4935 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4936 const char *chunk_data;
4937 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4938 unsigned long lineno = 0;
4939 const char *file = NULL;
4940 char ref[SIZEOF_REF];
4941 struct blame_header header;
4942 struct blame_commit commit;
4944 if (!diff || !chunk || chunk == line) {
4945 report("The line to trace must be inside a diff chunk");
4946 return REQ_NONE;
4949 for (; diff < line && !file; diff++) {
4950 const char *data = diff->data;
4952 if (!prefixcmp(data, "--- a/")) {
4953 file = data + STRING_SIZE("--- a/");
4954 break;
4958 if (diff == line || !file) {
4959 report("Failed to read the file name");
4960 return REQ_NONE;
4963 chunk_data = chunk->data;
4965 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4966 report("Failed to read the line number");
4967 return REQ_NONE;
4970 if (lineno == 0) {
4971 report("This is the origin of the line");
4972 return REQ_NONE;
4975 for (chunk += 1; chunk < line; chunk++) {
4976 if (chunk->type == LINE_DIFF_ADD) {
4977 lineno += chunk_marker == '+';
4978 } else if (chunk->type == LINE_DIFF_DEL) {
4979 lineno += chunk_marker == '-';
4980 } else {
4981 lineno++;
4985 if (chunk_marker == '+')
4986 string_copy(ref, view->vid);
4987 else
4988 string_format(ref, "%s^", view->vid);
4990 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4991 report("Failed to read blame data");
4992 return REQ_NONE;
4995 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4996 string_copy(opt_ref, header.id);
4997 opt_goto_line = header.orig_lineno - 1;
4999 return REQ_VIEW_BLAME;
5002 static const char *
5003 diff_get_pathname(struct view *view, struct line *line)
5005 const struct line *header;
5006 const char *dst = NULL;
5007 const char *prefixes[] = { " b/", "cc ", "combined " };
5008 int i;
5010 header = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
5011 if (!header)
5012 return NULL;
5014 for (i = 0; i < ARRAY_SIZE(prefixes) && !dst; i++)
5015 dst = strstr(header->data, prefixes[i]);
5017 return dst ? dst + strlen(prefixes[--i]) : NULL;
5020 static enum request
5021 diff_common_edit(struct view *view, enum request request, struct line *line)
5023 const char *file = diff_get_pathname(view, line);
5024 char path[SIZEOF_STR];
5025 bool has_path = file && string_format(path, "%s%s", opt_cdup, file);
5027 if (has_path && access(path, R_OK)) {
5028 report("Failed to open file: %s", file);
5029 return REQ_NONE;
5032 open_editor(file, diff_get_lineno(view, line));
5033 return REQ_NONE;
5036 static enum request
5037 diff_request(struct view *view, enum request request, struct line *line)
5039 switch (request) {
5040 case REQ_VIEW_BLAME:
5041 return diff_trace_origin(view, line);
5043 case REQ_DIFF_CONTEXT_UP:
5044 case REQ_DIFF_CONTEXT_DOWN:
5045 if (!update_diff_context(request))
5046 return REQ_NONE;
5047 reload_view(view);
5048 return REQ_NONE;
5051 case REQ_EDIT:
5052 return diff_common_edit(view, request, line);
5054 case REQ_ENTER:
5055 return diff_common_enter(view, request, line);
5057 case REQ_REFRESH:
5058 reload_view(view);
5059 return REQ_NONE;
5061 default:
5062 return pager_request(view, request, line);
5066 static void
5067 diff_select(struct view *view, struct line *line)
5069 if (line->type == LINE_DIFF_STAT) {
5070 string_format(view->ref, "Press '%s' to jump to file diff",
5071 get_view_key(view, REQ_ENTER));
5072 } else {
5073 const char *file = diff_get_pathname(view, line);
5075 if (file) {
5076 string_format(view->ref, "Changes to '%s'", file);
5077 string_format(opt_file, "%s", file);
5078 ref_blob[0] = 0;
5079 } else {
5080 string_ncopy(view->ref, view->id, strlen(view->id));
5081 pager_select(view, line);
5086 static struct view_ops diff_ops = {
5087 "line",
5088 { "diff" },
5089 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS | VIEW_FILE_FILTER,
5090 sizeof(struct diff_state),
5091 diff_open,
5092 diff_read,
5093 diff_common_draw,
5094 diff_request,
5095 pager_grep,
5096 diff_select,
5100 * Help backend
5103 static bool
5104 help_draw(struct view *view, struct line *line, unsigned int lineno)
5106 if (line->type == LINE_HELP_KEYMAP) {
5107 struct keymap *keymap = line->data;
5109 draw_formatted(view, line->type, "[%c] %s bindings",
5110 keymap->hidden ? '+' : '-', keymap->name);
5111 return TRUE;
5112 } else {
5113 return pager_draw(view, line, lineno);
5117 static bool
5118 help_open_keymap_title(struct view *view, struct keymap *keymap)
5120 add_line(view, keymap, LINE_HELP_KEYMAP, 0, FALSE);
5121 return keymap->hidden;
5124 static void
5125 help_open_keymap(struct view *view, struct keymap *keymap)
5127 const char *group = NULL;
5128 char buf[SIZEOF_STR];
5129 bool add_title = TRUE;
5130 int i;
5132 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
5133 const char *key = NULL;
5135 if (req_info[i].request == REQ_NONE)
5136 continue;
5138 if (!req_info[i].request) {
5139 group = req_info[i].help;
5140 continue;
5143 key = get_keys(keymap, req_info[i].request, TRUE);
5144 if (!key || !*key)
5145 continue;
5147 if (add_title && help_open_keymap_title(view, keymap))
5148 return;
5149 add_title = FALSE;
5151 if (group) {
5152 add_line_text(view, group, LINE_HELP_GROUP);
5153 group = NULL;
5156 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
5157 enum_name(req_info[i]), req_info[i].help);
5160 group = "External commands:";
5162 for (i = 0; i < run_requests; i++) {
5163 struct run_request *req = get_run_request(REQ_NONE + i + 1);
5164 const char *key;
5166 if (!req || req->keymap != keymap)
5167 continue;
5169 key = get_key_name(req->key);
5170 if (!*key)
5171 key = "(no key defined)";
5173 if (add_title && help_open_keymap_title(view, keymap))
5174 return;
5175 add_title = FALSE;
5177 if (group) {
5178 add_line_text(view, group, LINE_HELP_GROUP);
5179 group = NULL;
5182 if (!argv_to_string(req->argv, buf, sizeof(buf), " "))
5183 return;
5185 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
5189 static bool
5190 help_open(struct view *view, enum open_flags flags)
5192 struct keymap *keymap;
5194 reset_view(view);
5195 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
5196 add_line_text(view, "", LINE_DEFAULT);
5198 for (keymap = keymaps; keymap; keymap = keymap->next)
5199 help_open_keymap(view, keymap);
5201 return TRUE;
5204 static enum request
5205 help_request(struct view *view, enum request request, struct line *line)
5207 switch (request) {
5208 case REQ_ENTER:
5209 if (line->type == LINE_HELP_KEYMAP) {
5210 struct keymap *keymap = line->data;
5212 keymap->hidden = !keymap->hidden;
5213 refresh_view(view);
5216 return REQ_NONE;
5217 default:
5218 return pager_request(view, request, line);
5222 static void
5223 help_done(struct view *view)
5225 int i;
5227 for (i = 0; i < view->lines; i++)
5228 if (view->line[i].type == LINE_HELP_KEYMAP)
5229 view->line[i].data = NULL;
5232 static struct view_ops help_ops = {
5233 "line",
5234 { "help" },
5235 VIEW_NO_GIT_DIR,
5237 help_open,
5238 NULL,
5239 help_draw,
5240 help_request,
5241 pager_grep,
5242 pager_select,
5243 help_done,
5248 * Tree backend
5251 /* The top of the path stack. */
5252 static struct view_history tree_view_history = { sizeof(char *) };
5254 static void
5255 pop_tree_stack_entry(struct position *position)
5257 char *path_position = NULL;
5259 pop_view_history_state(&tree_view_history, position, &path_position);
5260 path_position[0] = 0;
5263 static void
5264 push_tree_stack_entry(const char *name, struct position *position)
5266 size_t pathlen = strlen(opt_path);
5267 char *path_position = opt_path + pathlen;
5268 struct view_state *state = push_view_history_state(&tree_view_history, position, &path_position);
5270 if (!state)
5271 return;
5273 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
5274 pop_tree_stack_entry(NULL);
5275 return;
5278 clear_position(position);
5281 /* Parse output from git-ls-tree(1):
5283 * 100644 blob 95925677ca47beb0b8cce7c0e0011bcc3f61470f 213045 tig.c
5286 #define SIZEOF_TREE_ATTR \
5287 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
5289 #define SIZEOF_TREE_MODE \
5290 STRING_SIZE("100644 ")
5292 #define TREE_ID_OFFSET \
5293 STRING_SIZE("100644 blob ")
5295 #define tree_path_is_parent(path) (!strcmp("..", (path)))
5297 struct tree_entry {
5298 char id[SIZEOF_REV];
5299 char commit[SIZEOF_REV];
5300 mode_t mode;
5301 struct time time; /* Date from the author ident. */
5302 const struct ident *author; /* Author of the commit. */
5303 unsigned long size;
5304 char name[1];
5307 struct tree_state {
5308 char commit[SIZEOF_REV];
5309 const struct ident *author;
5310 struct time author_time;
5311 int size_width;
5312 bool read_date;
5315 static const char *
5316 tree_path(const struct line *line)
5318 return ((struct tree_entry *) line->data)->name;
5321 static int
5322 tree_compare_entry(const struct line *line1, const struct line *line2)
5324 if (line1->type != line2->type)
5325 return line1->type == LINE_TREE_DIR ? -1 : 1;
5326 return strcmp(tree_path(line1), tree_path(line2));
5329 static const enum sort_field tree_sort_fields[] = {
5330 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5332 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
5334 static int
5335 tree_compare(const void *l1, const void *l2)
5337 const struct line *line1 = (const struct line *) l1;
5338 const struct line *line2 = (const struct line *) l2;
5339 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
5340 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
5342 if (line1->type == LINE_TREE_HEAD)
5343 return -1;
5344 if (line2->type == LINE_TREE_HEAD)
5345 return 1;
5347 switch (get_sort_field(tree_sort_state)) {
5348 case ORDERBY_DATE:
5349 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
5351 case ORDERBY_AUTHOR:
5352 return sort_order(tree_sort_state, ident_compare(entry1->author, entry2->author));
5354 case ORDERBY_NAME:
5355 default:
5356 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
5361 static struct line *
5362 tree_entry(struct view *view, enum line_type type, const char *path,
5363 const char *mode, const char *id, unsigned long size)
5365 bool custom = type == LINE_TREE_HEAD || tree_path_is_parent(path);
5366 struct tree_entry *entry;
5367 struct line *line = add_line_alloc(view, &entry, type, strlen(path), custom);
5369 if (!line)
5370 return NULL;
5372 strncpy(entry->name, path, strlen(path));
5373 if (mode)
5374 entry->mode = strtoul(mode, NULL, 8);
5375 if (id)
5376 string_copy_rev(entry->id, id);
5377 entry->size = size;
5379 return line;
5382 static bool
5383 tree_read_date(struct view *view, char *text, struct tree_state *state)
5385 if (!text && state->read_date) {
5386 state->read_date = FALSE;
5387 return TRUE;
5389 } else if (!text) {
5390 /* Find next entry to process */
5391 const char *log_file[] = {
5392 "git", "log", encoding_arg, "--no-color", "--pretty=raw",
5393 "--cc", "--raw", view->id, "--", "%(directory)", NULL
5396 if (!view->lines) {
5397 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0);
5398 tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0);
5399 report("Tree is empty");
5400 return TRUE;
5403 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
5404 report("Failed to load tree data");
5405 return TRUE;
5408 state->read_date = TRUE;
5409 return FALSE;
5411 } else if (*text == 'c' && get_line_type(text) == LINE_COMMIT) {
5412 string_copy_rev_from_commit_line(state->commit, text);
5414 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
5415 parse_author_line(text + STRING_SIZE("author "),
5416 &state->author, &state->author_time);
5418 } else if (*text == ':') {
5419 char *pos;
5420 size_t annotated = 1;
5421 size_t i;
5423 pos = strchr(text, '\t');
5424 if (!pos)
5425 return TRUE;
5426 text = pos + 1;
5427 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
5428 text += strlen(opt_path);
5429 pos = strchr(text, '/');
5430 if (pos)
5431 *pos = 0;
5433 for (i = 1; i < view->lines; i++) {
5434 struct line *line = &view->line[i];
5435 struct tree_entry *entry = line->data;
5437 annotated += !!entry->author;
5438 if (entry->author || strcmp(entry->name, text))
5439 continue;
5441 string_copy_rev(entry->commit, state->commit);
5442 entry->author = state->author;
5443 entry->time = state->author_time;
5444 line->dirty = 1;
5445 break;
5448 if (annotated == view->lines)
5449 io_kill(view->pipe);
5451 return TRUE;
5454 static inline size_t
5455 parse_size(const char *text, int *max_digits)
5457 size_t size = 0;
5458 int digits = 0;
5460 while (*text == ' ')
5461 text++;
5463 while (isdigit(*text)) {
5464 size = (size * 10) + (*text++ - '0');
5465 digits++;
5468 if (digits > *max_digits)
5469 *max_digits = digits;
5471 return size;
5474 static bool
5475 tree_read(struct view *view, char *text)
5477 struct tree_state *state = view->private;
5478 struct tree_entry *data;
5479 struct line *entry, *line;
5480 enum line_type type;
5481 size_t textlen = text ? strlen(text) : 0;
5482 const char *attr_offset = text + SIZEOF_TREE_ATTR;
5483 char *path;
5484 size_t size;
5486 if (state->read_date || !text)
5487 return tree_read_date(view, text, state);
5489 if (textlen <= SIZEOF_TREE_ATTR)
5490 return FALSE;
5491 if (view->lines == 0 &&
5492 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL, 0))
5493 return FALSE;
5495 size = parse_size(attr_offset, &state->size_width);
5496 path = strchr(attr_offset, '\t');
5497 if (!path)
5498 return FALSE;
5499 path++;
5501 /* Strip the path part ... */
5502 if (*opt_path) {
5503 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
5504 size_t striplen = strlen(opt_path);
5506 if (pathlen > striplen)
5507 memmove(path, path + striplen,
5508 pathlen - striplen + 1);
5510 /* Insert "link" to parent directory. */
5511 if (view->lines == 1 &&
5512 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref, 0))
5513 return FALSE;
5516 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
5517 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET, size);
5518 if (!entry)
5519 return FALSE;
5520 data = entry->data;
5522 /* Skip "Directory ..." and ".." line. */
5523 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
5524 if (tree_compare_entry(line, entry) <= 0)
5525 continue;
5527 memmove(line + 1, line, (entry - line) * sizeof(*entry));
5529 line->data = data;
5530 line->type = type;
5531 for (; line <= entry; line++)
5532 line->dirty = line->cleareol = 1;
5533 return TRUE;
5536 /* Move the current line to the first tree entry. */
5537 if (!check_position(&view->prev_pos) && !check_position(&view->pos))
5538 goto_view_line(view, 0, 1);
5540 return TRUE;
5543 static bool
5544 tree_draw(struct view *view, struct line *line, unsigned int lineno)
5546 struct tree_state *state = view->private;
5547 struct tree_entry *entry = line->data;
5549 if (line->type == LINE_TREE_HEAD) {
5550 if (draw_text(view, line->type, "Directory path /"))
5551 return TRUE;
5552 } else {
5553 if (draw_mode(view, entry->mode))
5554 return TRUE;
5556 if (draw_author(view, entry->author))
5557 return TRUE;
5559 if (draw_file_size(view, entry->size, state->size_width,
5560 line->type != LINE_TREE_FILE))
5561 return TRUE;
5563 if (draw_date(view, &entry->time))
5564 return TRUE;
5566 if (draw_id(view, entry->commit))
5567 return TRUE;
5570 draw_text(view, line->type, entry->name);
5571 return TRUE;
5574 static void
5575 open_blob_editor(const char *id, const char *name, unsigned int lineno)
5577 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
5578 char file[SIZEOF_STR];
5579 int fd;
5581 if (!name)
5582 name = "unknown";
5584 if (!string_format(file, "%s/tigblob.XXXXXX.%s", get_temp_dir(), name)) {
5585 report("Temporary file name is too long");
5586 return;
5589 fd = mkstemps(file, strlen(name) + 1);
5591 if (fd == -1)
5592 report("Failed to create temporary file");
5593 else if (!io_run_append(blob_argv, fd))
5594 report("Failed to save blob data to file");
5595 else
5596 open_editor(file, lineno);
5597 if (fd != -1)
5598 unlink(file);
5601 static enum request
5602 tree_request(struct view *view, enum request request, struct line *line)
5604 enum open_flags flags;
5605 struct tree_entry *entry = line->data;
5607 switch (request) {
5608 case REQ_VIEW_BLAME:
5609 if (line->type != LINE_TREE_FILE) {
5610 report("Blame only supported for files");
5611 return REQ_NONE;
5614 string_copy(opt_ref, view->vid);
5615 return request;
5617 case REQ_EDIT:
5618 if (line->type != LINE_TREE_FILE) {
5619 report("Edit only supported for files");
5620 } else if (!is_head_commit(view->vid)) {
5621 open_blob_editor(entry->id, entry->name, 0);
5622 } else {
5623 open_editor(opt_file, 0);
5625 return REQ_NONE;
5627 case REQ_TOGGLE_SORT_FIELD:
5628 case REQ_TOGGLE_SORT_ORDER:
5629 sort_view(view, request, &tree_sort_state, tree_compare);
5630 return REQ_NONE;
5632 case REQ_PARENT:
5633 case REQ_BACK:
5634 if (!*opt_path) {
5635 /* quit view if at top of tree */
5636 return REQ_VIEW_CLOSE;
5638 /* fake 'cd ..' */
5639 line = &view->line[1];
5640 break;
5642 case REQ_ENTER:
5643 break;
5645 default:
5646 return request;
5649 /* Cleanup the stack if the tree view is at a different tree. */
5650 if (!*opt_path)
5651 reset_view_history(&tree_view_history);
5653 switch (line->type) {
5654 case LINE_TREE_DIR:
5655 /* Depending on whether it is a subdirectory or parent link
5656 * mangle the path buffer. */
5657 if (line == &view->line[1] && *opt_path) {
5658 pop_tree_stack_entry(&view->pos);
5660 } else {
5661 const char *basename = tree_path(line);
5663 push_tree_stack_entry(basename, &view->pos);
5666 /* Trees and subtrees share the same ID, so they are not not
5667 * unique like blobs. */
5668 flags = OPEN_RELOAD;
5669 request = REQ_VIEW_TREE;
5670 break;
5672 case LINE_TREE_FILE:
5673 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5674 request = REQ_VIEW_BLOB;
5675 break;
5677 default:
5678 return REQ_NONE;
5681 open_view(view, request, flags);
5683 return REQ_NONE;
5686 static bool
5687 tree_grep(struct view *view, struct line *line)
5689 struct tree_entry *entry = line->data;
5690 const char *text[] = {
5691 entry->name,
5692 mkauthor(entry->author, opt_author_width, opt_author),
5693 mkdate(&entry->time, opt_date),
5694 NULL
5697 return grep_text(view, text);
5700 static void
5701 tree_select(struct view *view, struct line *line)
5703 struct tree_entry *entry = line->data;
5705 if (line->type == LINE_TREE_HEAD) {
5706 string_format(view->ref, "Files in /%s", opt_path);
5707 return;
5710 if (line->type == LINE_TREE_DIR && tree_path_is_parent(entry->name)) {
5711 string_copy(view->ref, "Open parent directory");
5712 ref_blob[0] = 0;
5713 return;
5716 if (line->type == LINE_TREE_FILE) {
5717 string_copy_rev(ref_blob, entry->id);
5718 string_format(opt_file, "%s%s", opt_path, tree_path(line));
5721 string_copy_rev(view->ref, entry->id);
5724 static bool
5725 tree_open(struct view *view, enum open_flags flags)
5727 static const char *tree_argv[] = {
5728 "git", "ls-tree", "-l", "%(commit)", "%(directory)", NULL
5731 if (string_rev_is_null(ref_commit)) {
5732 report("No tree exists for this commit");
5733 return FALSE;
5736 if (view->lines == 0 && opt_prefix[0]) {
5737 char *pos = opt_prefix;
5739 while (pos && *pos) {
5740 char *end = strchr(pos, '/');
5742 if (end)
5743 *end = 0;
5744 push_tree_stack_entry(pos, &view->pos);
5745 pos = end;
5746 if (end) {
5747 *end = '/';
5748 pos++;
5752 } else if (strcmp(view->vid, view->id)) {
5753 opt_path[0] = 0;
5756 return begin_update(view, opt_cdup, tree_argv, flags);
5759 static struct view_ops tree_ops = {
5760 "file",
5761 { "tree" },
5762 VIEW_SEND_CHILD_ENTER,
5763 sizeof(struct tree_state),
5764 tree_open,
5765 tree_read,
5766 tree_draw,
5767 tree_request,
5768 tree_grep,
5769 tree_select,
5772 static bool
5773 blob_open(struct view *view, enum open_flags flags)
5775 static const char *blob_argv[] = {
5776 "git", "cat-file", "blob", "%(blob)", NULL
5779 if (!ref_blob[0] && opt_file[0]) {
5780 const char *commit = ref_commit[0] ? ref_commit : "HEAD";
5781 char blob_spec[SIZEOF_STR];
5782 const char *rev_parse_argv[] = {
5783 "git", "rev-parse", blob_spec, NULL
5786 if (!string_format(blob_spec, "%s:%s", commit, opt_file) ||
5787 !io_run_buf(rev_parse_argv, ref_blob, sizeof(ref_blob))) {
5788 report("Failed to resolve blob from file name");
5789 return FALSE;
5793 if (!ref_blob[0]) {
5794 report("No file chosen, press %s to open tree view",
5795 get_view_key(view, REQ_VIEW_TREE));
5796 return FALSE;
5799 view->encoding = get_path_encoding(opt_file, default_encoding);
5801 return begin_update(view, NULL, blob_argv, flags);
5804 static bool
5805 blob_read(struct view *view, char *line)
5807 if (!line)
5808 return TRUE;
5809 return add_line_text(view, line, LINE_DEFAULT) != NULL;
5812 static enum request
5813 blob_request(struct view *view, enum request request, struct line *line)
5815 switch (request) {
5816 case REQ_EDIT:
5817 open_blob_editor(view->vid, NULL, (line - view->line) + 1);
5818 return REQ_NONE;
5819 default:
5820 return pager_request(view, request, line);
5824 static struct view_ops blob_ops = {
5825 "line",
5826 { "blob" },
5827 VIEW_NO_FLAGS,
5829 blob_open,
5830 blob_read,
5831 pager_draw,
5832 blob_request,
5833 pager_grep,
5834 pager_select,
5838 * Blame backend
5840 * Loading the blame view is a two phase job:
5842 * 1. File content is read either using opt_file from the
5843 * filesystem or using git-cat-file.
5844 * 2. Then blame information is incrementally added by
5845 * reading output from git-blame.
5848 struct blame_history_state {
5849 char id[SIZEOF_REV]; /* SHA1 ID. */
5850 const char *filename; /* Name of file. */
5853 static struct view_history blame_view_history = { sizeof(struct blame_history_state) };
5855 struct blame {
5856 struct blame_commit *commit;
5857 unsigned long lineno;
5858 char text[1];
5861 struct blame_state {
5862 struct blame_commit *commit;
5863 int blamed;
5864 bool done_reading;
5865 bool auto_filename_display;
5866 /* The history state for the current view is cached in the view
5867 * state so it always matches what was used to load the current blame
5868 * view. */
5869 struct blame_history_state history_state;
5872 static bool
5873 blame_detect_filename_display(struct view *view)
5875 bool show_filenames = FALSE;
5876 const char *filename = NULL;
5877 int i;
5879 if (opt_blame_argv) {
5880 for (i = 0; opt_blame_argv[i]; i++) {
5881 if (prefixcmp(opt_blame_argv[i], "-C"))
5882 continue;
5884 show_filenames = TRUE;
5888 for (i = 0; i < view->lines; i++) {
5889 struct blame *blame = view->line[i].data;
5891 if (blame->commit && blame->commit->id[0]) {
5892 if (!filename)
5893 filename = blame->commit->filename;
5894 else if (strcmp(filename, blame->commit->filename))
5895 show_filenames = TRUE;
5899 return show_filenames;
5902 static bool
5903 blame_open(struct view *view, enum open_flags flags)
5905 struct blame_state *state = view->private;
5906 const char *file_argv[] = { opt_cdup, opt_file , NULL };
5907 char path[SIZEOF_STR];
5908 size_t i;
5910 if (!opt_file[0]) {
5911 report("No file chosen, press %s to open tree view",
5912 get_view_key(view, REQ_VIEW_TREE));
5913 return FALSE;
5916 if (!view->prev && *opt_prefix && !(flags & (OPEN_RELOAD | OPEN_REFRESH))) {
5917 string_copy(path, opt_file);
5918 if (!string_format(opt_file, "%s%s", opt_prefix, path)) {
5919 report("Failed to setup the blame view");
5920 return FALSE;
5924 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
5925 const char *blame_cat_file_argv[] = {
5926 "git", "cat-file", "blob", "%(ref):%(file)", NULL
5929 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
5930 return FALSE;
5933 /* First pass: remove multiple references to the same commit. */
5934 for (i = 0; i < view->lines; i++) {
5935 struct blame *blame = view->line[i].data;
5937 if (blame->commit && blame->commit->id[0])
5938 blame->commit->id[0] = 0;
5939 else
5940 blame->commit = NULL;
5943 /* Second pass: free existing references. */
5944 for (i = 0; i < view->lines; i++) {
5945 struct blame *blame = view->line[i].data;
5947 if (blame->commit)
5948 free(blame->commit);
5951 if (!(flags & OPEN_RELOAD))
5952 reset_view_history(&blame_view_history);
5953 string_copy_rev(state->history_state.id, opt_ref);
5954 state->history_state.filename = get_path(opt_file);
5955 if (!state->history_state.filename)
5956 return FALSE;
5957 string_format(view->vid, "%s", opt_file);
5958 string_format(view->ref, "%s ...", opt_file);
5960 return TRUE;
5963 static struct blame_commit *
5964 get_blame_commit(struct view *view, const char *id)
5966 size_t i;
5968 for (i = 0; i < view->lines; i++) {
5969 struct blame *blame = view->line[i].data;
5971 if (!blame->commit)
5972 continue;
5974 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
5975 return blame->commit;
5979 struct blame_commit *commit = calloc(1, sizeof(*commit));
5981 if (commit)
5982 string_ncopy(commit->id, id, SIZEOF_REV);
5983 return commit;
5987 static struct blame_commit *
5988 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
5990 struct blame_header header;
5991 struct blame_commit *commit;
5992 struct blame *blame;
5994 if (!parse_blame_header(&header, text, view->lines))
5995 return NULL;
5997 commit = get_blame_commit(view, text);
5998 if (!commit)
5999 return NULL;
6001 state->blamed += header.group;
6002 while (header.group--) {
6003 struct line *line = &view->line[header.lineno + header.group - 1];
6005 blame = line->data;
6006 blame->commit = commit;
6007 blame->lineno = header.orig_lineno + header.group - 1;
6008 line->dirty = 1;
6011 return commit;
6014 static bool
6015 blame_read_file(struct view *view, const char *text, struct blame_state *state)
6017 if (!text) {
6018 const char *blame_argv[] = {
6019 "git", "blame", encoding_arg, "%(blameargs)", "--incremental",
6020 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
6023 if (view->lines == 0 && !view->prev)
6024 die("No blame exist for %s", view->vid);
6026 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
6027 report("Failed to load blame data");
6028 return TRUE;
6031 if (opt_goto_line > 0) {
6032 select_view_line(view, opt_goto_line);
6033 opt_goto_line = 0;
6036 state->done_reading = TRUE;
6037 return FALSE;
6039 } else {
6040 size_t textlen = strlen(text);
6041 struct blame *blame;
6043 if (!add_line_alloc(view, &blame, LINE_ID, textlen, FALSE))
6044 return FALSE;
6046 blame->commit = NULL;
6047 strncpy(blame->text, text, textlen);
6048 blame->text[textlen] = 0;
6049 return TRUE;
6053 static bool
6054 blame_read(struct view *view, char *line)
6056 struct blame_state *state = view->private;
6058 if (!state->done_reading)
6059 return blame_read_file(view, line, state);
6061 if (!line) {
6062 state->auto_filename_display = blame_detect_filename_display(view);
6063 string_format(view->ref, "%s", view->vid);
6064 if (view_is_displayed(view)) {
6065 update_view_title(view);
6066 redraw_view_from(view, 0);
6068 return TRUE;
6071 if (!state->commit) {
6072 state->commit = read_blame_commit(view, line, state);
6073 string_format(view->ref, "%s %2zd%%", view->vid,
6074 view->lines ? state->blamed * 100 / view->lines : 0);
6076 } else if (parse_blame_info(state->commit, line)) {
6077 if (!state->commit->filename)
6078 return FALSE;
6079 state->commit = NULL;
6082 return TRUE;
6085 static bool
6086 blame_draw(struct view *view, struct line *line, unsigned int lineno)
6088 struct blame_state *state = view->private;
6089 struct blame *blame = line->data;
6090 struct time *time = NULL;
6091 const char *id = NULL, *filename = NULL;
6092 const struct ident *author = NULL;
6093 enum line_type id_type = LINE_ID;
6094 static const enum line_type blame_colors[] = {
6095 LINE_PALETTE_0,
6096 LINE_PALETTE_1,
6097 LINE_PALETTE_2,
6098 LINE_PALETTE_3,
6099 LINE_PALETTE_4,
6100 LINE_PALETTE_5,
6101 LINE_PALETTE_6,
6104 #define BLAME_COLOR(i) \
6105 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
6107 if (blame->commit && *blame->commit->filename) {
6108 id = blame->commit->id;
6109 author = blame->commit->author;
6110 filename = blame->commit->filename;
6111 time = &blame->commit->time;
6112 id_type = BLAME_COLOR((long) blame->commit);
6115 if (draw_date(view, time))
6116 return TRUE;
6118 if (draw_author(view, author))
6119 return TRUE;
6121 if (draw_filename(view, filename, state->auto_filename_display))
6122 return TRUE;
6124 if (draw_id_custom(view, id_type, id, opt_id_cols))
6125 return TRUE;
6127 if (draw_lineno(view, lineno))
6128 return TRUE;
6130 draw_text(view, LINE_DEFAULT, blame->text);
6131 return TRUE;
6134 static bool
6135 check_blame_commit(struct blame *blame, bool check_null_id)
6137 if (!blame->commit)
6138 report("Commit data not loaded yet");
6139 else if (check_null_id && string_rev_is_null(blame->commit->id))
6140 report("No commit exist for the selected line");
6141 else
6142 return TRUE;
6143 return FALSE;
6146 static void
6147 setup_blame_parent_line(struct view *view, struct blame *blame)
6149 char from[SIZEOF_REF + SIZEOF_STR];
6150 char to[SIZEOF_REF + SIZEOF_STR];
6151 const char *diff_tree_argv[] = {
6152 "git", "diff", encoding_arg, "--no-textconv", "--no-extdiff",
6153 "--no-color", "-U0", from, to, "--", NULL
6155 struct io io;
6156 int parent_lineno = -1;
6157 int blamed_lineno = -1;
6158 char *line;
6160 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
6161 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
6162 !io_run(&io, IO_RD, NULL, opt_env, diff_tree_argv))
6163 return;
6165 while ((line = io_get(&io, '\n', TRUE))) {
6166 if (*line == '@') {
6167 char *pos = strchr(line, '+');
6169 parent_lineno = atoi(line + 4);
6170 if (pos)
6171 blamed_lineno = atoi(pos + 1);
6173 } else if (*line == '+' && parent_lineno != -1) {
6174 if (blame->lineno == blamed_lineno - 1 &&
6175 !strcmp(blame->text, line + 1)) {
6176 view->pos.lineno = parent_lineno ? parent_lineno - 1 : 0;
6177 break;
6179 blamed_lineno++;
6183 io_done(&io);
6186 static void
6187 blame_go_forward(struct view *view, struct blame *blame, bool parent)
6189 struct blame_state *state = view->private;
6190 struct blame_history_state *history_state = &state->history_state;
6191 struct blame_commit *commit = blame->commit;
6192 const char *id = parent ? commit->parent_id : commit->id;
6193 const char *filename = parent ? commit->parent_filename : commit->filename;
6195 if (!*id && parent) {
6196 report("The selected commit has no parents");
6197 return;
6200 if (!strcmp(history_state->id, id) && !strcmp(history_state->filename, filename)) {
6201 report("The selected commit is already displayed");
6202 return;
6205 if (!push_view_history_state(&blame_view_history, &view->pos, history_state)) {
6206 report("Failed to save current view state");
6207 return;
6210 string_ncopy(opt_ref, id, sizeof(commit->id));
6211 string_ncopy(opt_file, filename, strlen(filename));
6212 if (parent)
6213 setup_blame_parent_line(view, blame);
6214 opt_goto_line = blame->lineno;
6215 reload_view(view);
6218 static void
6219 blame_go_back(struct view *view)
6221 struct blame_history_state history_state;
6223 if (!pop_view_history_state(&blame_view_history, &view->pos, &history_state)) {
6224 report("Already at start of history");
6225 return;
6228 string_copy(opt_ref, history_state.id);
6229 string_ncopy(opt_file, history_state.filename, strlen(history_state.filename));
6230 opt_goto_line = view->pos.lineno;
6231 reload_view(view);
6234 static enum request
6235 blame_request(struct view *view, enum request request, struct line *line)
6237 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6238 struct blame *blame = line->data;
6240 switch (request) {
6241 case REQ_VIEW_BLAME:
6242 case REQ_PARENT:
6243 if (!check_blame_commit(blame, TRUE))
6244 break;
6245 blame_go_forward(view, blame, request == REQ_PARENT);
6246 break;
6248 case REQ_BACK:
6249 blame_go_back(view);
6250 break;
6252 case REQ_ENTER:
6253 if (!check_blame_commit(blame, FALSE))
6254 break;
6256 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
6257 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
6258 break;
6260 if (string_rev_is_null(blame->commit->id)) {
6261 struct view *diff = VIEW(REQ_VIEW_DIFF);
6262 const char *diff_parent_argv[] = {
6263 GIT_DIFF_BLAME(encoding_arg,
6264 opt_diff_context_arg,
6265 opt_ignore_space_arg, view->vid)
6267 const char *diff_no_parent_argv[] = {
6268 GIT_DIFF_BLAME_NO_PARENT(encoding_arg,
6269 opt_diff_context_arg,
6270 opt_ignore_space_arg, view->vid)
6272 const char **diff_index_argv = *blame->commit->parent_id
6273 ? diff_parent_argv : diff_no_parent_argv;
6275 open_argv(view, diff, diff_index_argv, NULL, flags);
6276 if (diff->pipe)
6277 string_copy_rev(diff->ref, NULL_ID);
6278 } else {
6279 open_view(view, REQ_VIEW_DIFF, flags);
6281 break;
6283 default:
6284 return request;
6287 return REQ_NONE;
6290 static bool
6291 blame_grep(struct view *view, struct line *line)
6293 struct blame *blame = line->data;
6294 struct blame_commit *commit = blame->commit;
6295 const char *text[] = {
6296 blame->text,
6297 commit ? commit->title : "",
6298 commit ? commit->id : "",
6299 commit ? mkauthor(commit->author, opt_author_width, opt_author) : "",
6300 commit ? mkdate(&commit->time, opt_date) : "",
6301 NULL
6304 return grep_text(view, text);
6307 static void
6308 blame_select(struct view *view, struct line *line)
6310 struct blame *blame = line->data;
6311 struct blame_commit *commit = blame->commit;
6313 if (!commit)
6314 return;
6316 if (string_rev_is_null(commit->id))
6317 string_ncopy(ref_commit, "HEAD", 4);
6318 else
6319 string_copy_rev(ref_commit, commit->id);
6322 static struct view_ops blame_ops = {
6323 "line",
6324 { "blame" },
6325 VIEW_ALWAYS_LINENO | VIEW_SEND_CHILD_ENTER,
6326 sizeof(struct blame_state),
6327 blame_open,
6328 blame_read,
6329 blame_draw,
6330 blame_request,
6331 blame_grep,
6332 blame_select,
6336 * Branch backend
6339 struct branch {
6340 const struct ident *author; /* Author of the last commit. */
6341 struct time time; /* Date of the last activity. */
6342 char title[128]; /* First line of the commit message. */
6343 const struct ref *ref; /* Name and commit ID information. */
6346 static const struct ref branch_all;
6347 #define BRANCH_ALL_NAME "All branches"
6348 #define branch_is_all(branch) ((branch)->ref == &branch_all)
6350 static const enum sort_field branch_sort_fields[] = {
6351 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
6353 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
6355 struct branch_state {
6356 char id[SIZEOF_REV];
6357 size_t max_ref_length;
6360 static int
6361 branch_compare(const void *l1, const void *l2)
6363 const struct branch *branch1 = ((const struct line *) l1)->data;
6364 const struct branch *branch2 = ((const struct line *) l2)->data;
6366 if (branch_is_all(branch1))
6367 return -1;
6368 else if (branch_is_all(branch2))
6369 return 1;
6371 switch (get_sort_field(branch_sort_state)) {
6372 case ORDERBY_DATE:
6373 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
6375 case ORDERBY_AUTHOR:
6376 return sort_order(branch_sort_state, ident_compare(branch1->author, branch2->author));
6378 case ORDERBY_NAME:
6379 default:
6380 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
6384 static bool
6385 branch_draw(struct view *view, struct line *line, unsigned int lineno)
6387 struct branch_state *state = view->private;
6388 struct branch *branch = line->data;
6389 enum line_type type = branch_is_all(branch) ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
6390 const char *branch_name = branch_is_all(branch) ? BRANCH_ALL_NAME : branch->ref->name;
6392 if (draw_lineno(view, lineno))
6393 return TRUE;
6395 if (draw_date(view, &branch->time))
6396 return TRUE;
6398 if (draw_author(view, branch->author))
6399 return TRUE;
6401 if (draw_field(view, type, branch_name, state->max_ref_length, ALIGN_LEFT, FALSE))
6402 return TRUE;
6404 if (draw_id(view, branch->ref->id))
6405 return TRUE;
6407 draw_text(view, LINE_DEFAULT, branch->title);
6408 return TRUE;
6411 static enum request
6412 branch_request(struct view *view, enum request request, struct line *line)
6414 struct branch *branch = line->data;
6416 switch (request) {
6417 case REQ_REFRESH:
6418 load_refs(TRUE);
6419 refresh_view(view);
6420 return REQ_NONE;
6422 case REQ_TOGGLE_SORT_FIELD:
6423 case REQ_TOGGLE_SORT_ORDER:
6424 sort_view(view, request, &branch_sort_state, branch_compare);
6425 return REQ_NONE;
6427 case REQ_ENTER:
6429 const struct ref *ref = branch->ref;
6430 const char *all_branches_argv[] = {
6431 GIT_MAIN_LOG(encoding_arg, "", branch_is_all(branch) ? "--all" : ref->name, "")
6433 struct view *main_view = VIEW(REQ_VIEW_MAIN);
6435 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
6436 return REQ_NONE;
6438 case REQ_JUMP_COMMIT:
6440 int lineno;
6442 for (lineno = 0; lineno < view->lines; lineno++) {
6443 struct branch *branch = view->line[lineno].data;
6445 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
6446 select_view_line(view, lineno);
6447 report_clear();
6448 return REQ_NONE;
6452 default:
6453 return request;
6457 static bool
6458 branch_read(struct view *view, char *line)
6460 struct branch_state *state = view->private;
6461 const char *title = NULL;
6462 const struct ident *author = NULL;
6463 struct time time = {};
6464 size_t i;
6466 if (!line)
6467 return TRUE;
6469 switch (get_line_type(line)) {
6470 case LINE_COMMIT:
6471 string_copy_rev_from_commit_line(state->id, line);
6472 return TRUE;
6474 case LINE_AUTHOR:
6475 parse_author_line(line + STRING_SIZE("author "), &author, &time);
6476 break;
6478 default:
6479 title = line + STRING_SIZE("title ");
6482 for (i = 0; i < view->lines; i++) {
6483 struct branch *branch = view->line[i].data;
6485 if (strcmp(branch->ref->id, state->id))
6486 continue;
6488 if (author) {
6489 branch->author = author;
6490 branch->time = time;
6493 if (title)
6494 string_expand(branch->title, sizeof(branch->title), title, 1);
6496 view->line[i].dirty = TRUE;
6499 return TRUE;
6502 static bool
6503 branch_open_visitor(void *data, const struct ref *ref)
6505 struct view *view = data;
6506 struct branch_state *state = view->private;
6507 struct branch *branch;
6508 bool is_all = ref == &branch_all;
6509 size_t ref_length;
6511 if (ref->tag || ref->ltag)
6512 return TRUE;
6514 if (!add_line_alloc(view, &branch, LINE_DEFAULT, 0, is_all))
6515 return FALSE;
6517 ref_length = is_all ? STRING_SIZE(BRANCH_ALL_NAME) : strlen(ref->name);
6518 if (ref_length > state->max_ref_length)
6519 state->max_ref_length = ref_length;
6521 branch->ref = ref;
6522 return TRUE;
6525 static bool
6526 branch_open(struct view *view, enum open_flags flags)
6528 const char *branch_log[] = {
6529 "git", "log", encoding_arg, "--no-color", "--date=raw",
6530 "--pretty=format:commit %H%nauthor %an <%ae> %ad%ntitle %s",
6531 "--all", "--simplify-by-decoration", NULL
6534 if (!begin_update(view, NULL, branch_log, OPEN_RELOAD)) {
6535 report("Failed to load branch data");
6536 return FALSE;
6539 branch_open_visitor(view, &branch_all);
6540 foreach_ref(branch_open_visitor, view);
6542 return TRUE;
6545 static bool
6546 branch_grep(struct view *view, struct line *line)
6548 struct branch *branch = line->data;
6549 const char *text[] = {
6550 branch->ref->name,
6551 mkauthor(branch->author, opt_author_width, opt_author),
6552 NULL
6555 return grep_text(view, text);
6558 static void
6559 branch_select(struct view *view, struct line *line)
6561 struct branch *branch = line->data;
6563 if (branch_is_all(branch)) {
6564 string_copy(view->ref, BRANCH_ALL_NAME);
6565 return;
6567 string_copy_rev(view->ref, branch->ref->id);
6568 string_copy_rev(ref_commit, branch->ref->id);
6569 string_copy_rev(ref_head, branch->ref->id);
6570 string_copy_rev(ref_branch, branch->ref->name);
6573 static struct view_ops branch_ops = {
6574 "branch",
6575 { "branch" },
6576 VIEW_NO_FLAGS,
6577 sizeof(struct branch_state),
6578 branch_open,
6579 branch_read,
6580 branch_draw,
6581 branch_request,
6582 branch_grep,
6583 branch_select,
6587 * Status backend
6590 struct status {
6591 char status;
6592 struct {
6593 mode_t mode;
6594 char rev[SIZEOF_REV];
6595 char name[SIZEOF_STR];
6596 } old;
6597 struct {
6598 mode_t mode;
6599 char rev[SIZEOF_REV];
6600 char name[SIZEOF_STR];
6601 } new;
6604 static char status_onbranch[SIZEOF_STR];
6605 static struct status stage_status;
6606 static enum line_type stage_line_type;
6608 DEFINE_ALLOCATOR(realloc_ints, int, 32)
6610 /* This should work even for the "On branch" line. */
6611 static inline bool
6612 status_has_none(struct view *view, struct line *line)
6614 return view_has_line(view, line) && !line[1].data;
6617 /* Get fields from the diff line:
6618 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
6620 static inline bool
6621 status_get_diff(struct status *file, const char *buf, size_t bufsize)
6623 const char *old_mode = buf + 1;
6624 const char *new_mode = buf + 8;
6625 const char *old_rev = buf + 15;
6626 const char *new_rev = buf + 56;
6627 const char *status = buf + 97;
6629 if (bufsize < 98 ||
6630 old_mode[-1] != ':' ||
6631 new_mode[-1] != ' ' ||
6632 old_rev[-1] != ' ' ||
6633 new_rev[-1] != ' ' ||
6634 status[-1] != ' ')
6635 return FALSE;
6637 file->status = *status;
6639 string_copy_rev(file->old.rev, old_rev);
6640 string_copy_rev(file->new.rev, new_rev);
6642 file->old.mode = strtoul(old_mode, NULL, 8);
6643 file->new.mode = strtoul(new_mode, NULL, 8);
6645 file->old.name[0] = file->new.name[0] = 0;
6647 return TRUE;
6650 static bool
6651 status_run(struct view *view, const char *argv[], char status, enum line_type type)
6653 struct status *unmerged = NULL;
6654 char *buf;
6655 struct io io;
6657 if (!io_run(&io, IO_RD, opt_cdup, opt_env, argv))
6658 return FALSE;
6660 add_line_nodata(view, type);
6662 while ((buf = io_get(&io, 0, TRUE))) {
6663 struct status *file = unmerged;
6665 if (!file) {
6666 if (!add_line_alloc(view, &file, type, 0, FALSE))
6667 goto error_out;
6670 /* Parse diff info part. */
6671 if (status) {
6672 file->status = status;
6673 if (status == 'A')
6674 string_copy(file->old.rev, NULL_ID);
6676 } else if (!file->status || file == unmerged) {
6677 if (!status_get_diff(file, buf, strlen(buf)))
6678 goto error_out;
6680 buf = io_get(&io, 0, TRUE);
6681 if (!buf)
6682 break;
6684 /* Collapse all modified entries that follow an
6685 * associated unmerged entry. */
6686 if (unmerged == file) {
6687 unmerged->status = 'U';
6688 unmerged = NULL;
6689 } else if (file->status == 'U') {
6690 unmerged = file;
6694 /* Grab the old name for rename/copy. */
6695 if (!*file->old.name &&
6696 (file->status == 'R' || file->status == 'C')) {
6697 string_ncopy(file->old.name, buf, strlen(buf));
6699 buf = io_get(&io, 0, TRUE);
6700 if (!buf)
6701 break;
6704 /* git-ls-files just delivers a NUL separated list of
6705 * file names similar to the second half of the
6706 * git-diff-* output. */
6707 string_ncopy(file->new.name, buf, strlen(buf));
6708 if (!*file->old.name)
6709 string_copy(file->old.name, file->new.name);
6710 file = NULL;
6713 if (io_error(&io)) {
6714 error_out:
6715 io_done(&io);
6716 return FALSE;
6719 if (!view->line[view->lines - 1].data)
6720 add_line_nodata(view, LINE_STAT_NONE);
6722 io_done(&io);
6723 return TRUE;
6726 static const char *status_diff_index_argv[] = { GIT_DIFF_STAGED_FILES("-z") };
6727 static const char *status_diff_files_argv[] = { GIT_DIFF_UNSTAGED_FILES("-z") };
6729 static const char *status_list_other_argv[] = {
6730 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
6733 static const char *status_list_no_head_argv[] = {
6734 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
6737 static const char *update_index_argv[] = {
6738 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
6741 /* Restore the previous line number to stay in the context or select a
6742 * line with something that can be updated. */
6743 static void
6744 status_restore(struct view *view)
6746 if (!check_position(&view->prev_pos))
6747 return;
6749 if (view->prev_pos.lineno >= view->lines)
6750 view->prev_pos.lineno = view->lines - 1;
6751 while (view->prev_pos.lineno < view->lines && !view->line[view->prev_pos.lineno].data)
6752 view->prev_pos.lineno++;
6753 while (view->prev_pos.lineno > 0 && !view->line[view->prev_pos.lineno].data)
6754 view->prev_pos.lineno--;
6756 /* If the above fails, always skip the "On branch" line. */
6757 if (view->prev_pos.lineno < view->lines)
6758 view->pos.lineno = view->prev_pos.lineno;
6759 else
6760 view->pos.lineno = 1;
6762 if (view->prev_pos.offset > view->pos.lineno)
6763 view->pos.offset = view->pos.lineno;
6764 else if (view->prev_pos.offset < view->lines)
6765 view->pos.offset = view->prev_pos.offset;
6767 clear_position(&view->prev_pos);
6770 static void
6771 status_update_onbranch(void)
6773 static const char *paths[][2] = {
6774 { "rebase-apply/rebasing", "Rebasing" },
6775 { "rebase-apply/applying", "Applying mailbox" },
6776 { "rebase-apply/", "Rebasing mailbox" },
6777 { "rebase-merge/interactive", "Interactive rebase" },
6778 { "rebase-merge/", "Rebase merge" },
6779 { "MERGE_HEAD", "Merging" },
6780 { "BISECT_LOG", "Bisecting" },
6781 { "HEAD", "On branch" },
6783 char buf[SIZEOF_STR];
6784 struct stat stat;
6785 int i;
6787 if (is_initial_commit()) {
6788 string_copy(status_onbranch, "Initial commit");
6789 return;
6792 for (i = 0; i < ARRAY_SIZE(paths); i++) {
6793 char *head = opt_head;
6795 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
6796 lstat(buf, &stat) < 0)
6797 continue;
6799 if (!*opt_head) {
6800 struct io io;
6802 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
6803 io_read_buf(&io, buf, sizeof(buf))) {
6804 head = buf;
6805 if (!prefixcmp(head, "refs/heads/"))
6806 head += STRING_SIZE("refs/heads/");
6810 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
6811 string_copy(status_onbranch, opt_head);
6812 return;
6815 string_copy(status_onbranch, "Not currently on any branch");
6818 /* First parse staged info using git-diff-index(1), then parse unstaged
6819 * info using git-diff-files(1), and finally untracked files using
6820 * git-ls-files(1). */
6821 static bool
6822 status_open(struct view *view, enum open_flags flags)
6824 const char **staged_argv = is_initial_commit() ?
6825 status_list_no_head_argv : status_diff_index_argv;
6826 char staged_status = staged_argv == status_list_no_head_argv ? 'A' : 0;
6828 if (opt_is_inside_work_tree == FALSE) {
6829 report("The status view requires a working tree");
6830 return FALSE;
6833 reset_view(view);
6835 add_line_nodata(view, LINE_STAT_HEAD);
6836 status_update_onbranch();
6838 io_run_bg(update_index_argv);
6840 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] =
6841 opt_untracked_dirs_content ? NULL : "--directory";
6843 if (!status_run(view, staged_argv, staged_status, LINE_STAT_STAGED) ||
6844 !status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
6845 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED)) {
6846 report("Failed to load status data");
6847 return FALSE;
6850 /* Restore the exact position or use the specialized restore
6851 * mode? */
6852 status_restore(view);
6853 return TRUE;
6856 static bool
6857 status_draw(struct view *view, struct line *line, unsigned int lineno)
6859 struct status *status = line->data;
6860 enum line_type type;
6861 const char *text;
6863 if (!status) {
6864 switch (line->type) {
6865 case LINE_STAT_STAGED:
6866 type = LINE_STAT_SECTION;
6867 text = "Changes to be committed:";
6868 break;
6870 case LINE_STAT_UNSTAGED:
6871 type = LINE_STAT_SECTION;
6872 text = "Changed but not updated:";
6873 break;
6875 case LINE_STAT_UNTRACKED:
6876 type = LINE_STAT_SECTION;
6877 text = "Untracked files:";
6878 break;
6880 case LINE_STAT_NONE:
6881 type = LINE_DEFAULT;
6882 text = " (no files)";
6883 break;
6885 case LINE_STAT_HEAD:
6886 type = LINE_STAT_HEAD;
6887 text = status_onbranch;
6888 break;
6890 default:
6891 return FALSE;
6893 } else {
6894 static char buf[] = { '?', ' ', ' ', ' ', 0 };
6896 buf[0] = status->status;
6897 if (draw_text(view, line->type, buf))
6898 return TRUE;
6899 type = LINE_DEFAULT;
6900 text = status->new.name;
6903 draw_text(view, type, text);
6904 return TRUE;
6907 static enum request
6908 status_enter(struct view *view, struct line *line)
6910 struct status *status = line->data;
6911 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6913 if (line->type == LINE_STAT_NONE ||
6914 (!status && line[1].type == LINE_STAT_NONE)) {
6915 report("No file to diff");
6916 return REQ_NONE;
6919 switch (line->type) {
6920 case LINE_STAT_STAGED:
6921 case LINE_STAT_UNSTAGED:
6922 break;
6924 case LINE_STAT_UNTRACKED:
6925 if (!status) {
6926 report("No file to show");
6927 return REQ_NONE;
6930 if (!suffixcmp(status->new.name, -1, "/")) {
6931 report("Cannot display a directory");
6932 return REQ_NONE;
6934 break;
6936 case LINE_STAT_HEAD:
6937 return REQ_NONE;
6939 default:
6940 die("line type %d not handled in switch", line->type);
6943 if (status) {
6944 stage_status = *status;
6945 } else {
6946 memset(&stage_status, 0, sizeof(stage_status));
6949 stage_line_type = line->type;
6951 open_view(view, REQ_VIEW_STAGE, flags);
6952 return REQ_NONE;
6955 static bool
6956 status_exists(struct view *view, struct status *status, enum line_type type)
6958 unsigned long lineno;
6960 for (lineno = 0; lineno < view->lines; lineno++) {
6961 struct line *line = &view->line[lineno];
6962 struct status *pos = line->data;
6964 if (line->type != type)
6965 continue;
6966 if (!pos && (!status || !status->status) && line[1].data) {
6967 select_view_line(view, lineno);
6968 return TRUE;
6970 if (pos && !strcmp(status->new.name, pos->new.name)) {
6971 select_view_line(view, lineno);
6972 return TRUE;
6976 return FALSE;
6980 static bool
6981 status_update_prepare(struct io *io, enum line_type type)
6983 const char *staged_argv[] = {
6984 "git", "update-index", "-z", "--index-info", NULL
6986 const char *others_argv[] = {
6987 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
6990 switch (type) {
6991 case LINE_STAT_STAGED:
6992 return io_run(io, IO_WR, opt_cdup, opt_env, staged_argv);
6994 case LINE_STAT_UNSTAGED:
6995 case LINE_STAT_UNTRACKED:
6996 return io_run(io, IO_WR, opt_cdup, opt_env, others_argv);
6998 default:
6999 die("line type %d not handled in switch", type);
7000 return FALSE;
7004 static bool
7005 status_update_write(struct io *io, struct status *status, enum line_type type)
7007 switch (type) {
7008 case LINE_STAT_STAGED:
7009 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
7010 status->old.rev, status->old.name, 0);
7012 case LINE_STAT_UNSTAGED:
7013 case LINE_STAT_UNTRACKED:
7014 return io_printf(io, "%s%c", status->new.name, 0);
7016 default:
7017 die("line type %d not handled in switch", type);
7018 return FALSE;
7022 static bool
7023 status_update_file(struct status *status, enum line_type type)
7025 struct io io;
7026 bool result;
7028 if (!status_update_prepare(&io, type))
7029 return FALSE;
7031 result = status_update_write(&io, status, type);
7032 return io_done(&io) && result;
7035 static bool
7036 status_update_files(struct view *view, struct line *line)
7038 char buf[sizeof(view->ref)];
7039 struct io io;
7040 bool result = TRUE;
7041 struct line *pos;
7042 int files = 0;
7043 int file, done;
7044 int cursor_y = -1, cursor_x = -1;
7046 if (!status_update_prepare(&io, line->type))
7047 return FALSE;
7049 for (pos = line; view_has_line(view, pos) && pos->data; pos++)
7050 files++;
7052 string_copy(buf, view->ref);
7053 getsyx(cursor_y, cursor_x);
7054 for (file = 0, done = 5; result && file < files; line++, file++) {
7055 int almost_done = file * 100 / files;
7057 if (almost_done > done) {
7058 done = almost_done;
7059 string_format(view->ref, "updating file %u of %u (%d%% done)",
7060 file, files, done);
7061 update_view_title(view);
7062 setsyx(cursor_y, cursor_x);
7063 doupdate();
7065 result = status_update_write(&io, line->data, line->type);
7067 string_copy(view->ref, buf);
7069 return io_done(&io) && result;
7072 static bool
7073 status_update(struct view *view)
7075 struct line *line = &view->line[view->pos.lineno];
7077 assert(view->lines);
7079 if (!line->data) {
7080 if (status_has_none(view, line)) {
7081 report("Nothing to update");
7082 return FALSE;
7085 if (!status_update_files(view, line + 1)) {
7086 report("Failed to update file status");
7087 return FALSE;
7090 } else if (!status_update_file(line->data, line->type)) {
7091 report("Failed to update file status");
7092 return FALSE;
7095 return TRUE;
7098 static bool
7099 status_revert(struct status *status, enum line_type type, bool has_none)
7101 if (!status || type != LINE_STAT_UNSTAGED) {
7102 if (type == LINE_STAT_STAGED) {
7103 report("Cannot revert changes to staged files");
7104 } else if (type == LINE_STAT_UNTRACKED) {
7105 report("Cannot revert changes to untracked files");
7106 } else if (has_none) {
7107 report("Nothing to revert");
7108 } else {
7109 report("Cannot revert changes to multiple files");
7112 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
7113 char mode[10] = "100644";
7114 const char *reset_argv[] = {
7115 "git", "update-index", "--cacheinfo", mode,
7116 status->old.rev, status->old.name, NULL
7118 const char *checkout_argv[] = {
7119 "git", "checkout", "--", status->old.name, NULL
7122 if (status->status == 'U') {
7123 string_format(mode, "%5o", status->old.mode);
7125 if (status->old.mode == 0 && status->new.mode == 0) {
7126 reset_argv[2] = "--force-remove";
7127 reset_argv[3] = status->old.name;
7128 reset_argv[4] = NULL;
7131 if (!io_run_fg(reset_argv, opt_cdup))
7132 return FALSE;
7133 if (status->old.mode == 0 && status->new.mode == 0)
7134 return TRUE;
7137 return io_run_fg(checkout_argv, opt_cdup);
7140 return FALSE;
7143 static enum request
7144 status_request(struct view *view, enum request request, struct line *line)
7146 struct status *status = line->data;
7148 switch (request) {
7149 case REQ_STATUS_UPDATE:
7150 if (!status_update(view))
7151 return REQ_NONE;
7152 break;
7154 case REQ_STATUS_REVERT:
7155 if (!status_revert(status, line->type, status_has_none(view, line)))
7156 return REQ_NONE;
7157 break;
7159 case REQ_STATUS_MERGE:
7160 if (!status || status->status != 'U') {
7161 report("Merging only possible for files with unmerged status ('U').");
7162 return REQ_NONE;
7164 open_mergetool(status->new.name);
7165 break;
7167 case REQ_EDIT:
7168 if (!status)
7169 return request;
7170 if (status->status == 'D') {
7171 report("File has been deleted.");
7172 return REQ_NONE;
7175 open_editor(status->new.name, 0);
7176 break;
7178 case REQ_VIEW_BLAME:
7179 if (status)
7180 opt_ref[0] = 0;
7181 return request;
7183 case REQ_ENTER:
7184 /* After returning the status view has been split to
7185 * show the stage view. No further reloading is
7186 * necessary. */
7187 return status_enter(view, line);
7189 case REQ_REFRESH:
7190 /* Load the current branch information and then the view. */
7191 load_refs(TRUE);
7192 break;
7194 default:
7195 return request;
7198 refresh_view(view);
7200 return REQ_NONE;
7203 static bool
7204 status_stage_info_(char *buf, size_t bufsize,
7205 enum line_type type, struct status *status)
7207 const char *file = status ? status->new.name : "";
7208 const char *info;
7210 switch (type) {
7211 case LINE_STAT_STAGED:
7212 if (status && status->status)
7213 info = "Staged changes to %s";
7214 else
7215 info = "Staged changes";
7216 break;
7218 case LINE_STAT_UNSTAGED:
7219 if (status && status->status)
7220 info = "Unstaged changes to %s";
7221 else
7222 info = "Unstaged changes";
7223 break;
7225 case LINE_STAT_UNTRACKED:
7226 info = "Untracked file %s";
7227 break;
7229 case LINE_STAT_HEAD:
7230 default:
7231 info = "";
7234 return string_nformat(buf, bufsize, NULL, info, file);
7236 #define status_stage_info(buf, type, status) \
7237 status_stage_info_(buf, sizeof(buf), type, status)
7239 static void
7240 status_select(struct view *view, struct line *line)
7242 struct status *status = line->data;
7243 char file[SIZEOF_STR] = "all files";
7244 const char *text;
7245 const char *key;
7247 if (status && !string_format(file, "'%s'", status->new.name))
7248 return;
7250 if (!status && line[1].type == LINE_STAT_NONE)
7251 line++;
7253 switch (line->type) {
7254 case LINE_STAT_STAGED:
7255 text = "Press %s to unstage %s for commit";
7256 break;
7258 case LINE_STAT_UNSTAGED:
7259 text = "Press %s to stage %s for commit";
7260 break;
7262 case LINE_STAT_UNTRACKED:
7263 text = "Press %s to stage %s for addition";
7264 break;
7266 case LINE_STAT_HEAD:
7267 case LINE_STAT_NONE:
7268 text = "Nothing to update";
7269 break;
7271 default:
7272 die("line type %d not handled in switch", line->type);
7275 if (status && status->status == 'U') {
7276 text = "Press %s to resolve conflict in %s";
7277 key = get_view_key(view, REQ_STATUS_MERGE);
7279 } else {
7280 key = get_view_key(view, REQ_STATUS_UPDATE);
7283 string_format(view->ref, text, key, file);
7284 status_stage_info(ref_status, line->type, status);
7285 if (status)
7286 string_copy(opt_file, status->new.name);
7289 static bool
7290 status_grep(struct view *view, struct line *line)
7292 struct status *status = line->data;
7294 if (status) {
7295 const char buf[2] = { status->status, 0 };
7296 const char *text[] = { status->new.name, buf, NULL };
7298 return grep_text(view, text);
7301 return FALSE;
7304 static struct view_ops status_ops = {
7305 "file",
7306 { "status" },
7307 VIEW_CUSTOM_STATUS | VIEW_SEND_CHILD_ENTER | VIEW_STATUS_LIKE,
7309 status_open,
7310 NULL,
7311 status_draw,
7312 status_request,
7313 status_grep,
7314 status_select,
7318 struct stage_state {
7319 struct diff_state diff;
7320 size_t chunks;
7321 int *chunk;
7324 static bool
7325 stage_diff_write(struct io *io, struct line *line, struct line *end)
7327 while (line < end) {
7328 if (!io_write(io, line->data, strlen(line->data)) ||
7329 !io_write(io, "\n", 1))
7330 return FALSE;
7331 line++;
7332 if (line->type == LINE_DIFF_CHUNK ||
7333 line->type == LINE_DIFF_HEADER)
7334 break;
7337 return TRUE;
7340 static bool
7341 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
7343 const char *apply_argv[SIZEOF_ARG] = {
7344 "git", "apply", "--whitespace=nowarn", NULL
7346 struct line *diff_hdr;
7347 struct io io;
7348 int argc = 3;
7350 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
7351 if (!diff_hdr)
7352 return FALSE;
7354 if (!revert)
7355 apply_argv[argc++] = "--cached";
7356 if (line != NULL)
7357 apply_argv[argc++] = "--unidiff-zero";
7358 if (revert || stage_line_type == LINE_STAT_STAGED)
7359 apply_argv[argc++] = "-R";
7360 apply_argv[argc++] = "-";
7361 apply_argv[argc++] = NULL;
7362 if (!io_run(&io, IO_WR, opt_cdup, opt_env, apply_argv))
7363 return FALSE;
7365 if (line != NULL) {
7366 unsigned long lineno = 0;
7367 struct line *context = chunk + 1;
7368 const char *markers[] = {
7369 line->type == LINE_DIFF_DEL ? "" : ",0",
7370 line->type == LINE_DIFF_DEL ? ",0" : "",
7373 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
7375 while (context < line) {
7376 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
7377 break;
7378 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
7379 lineno++;
7381 context++;
7384 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7385 !io_printf(&io, "@@ -%lu%s +%lu%s @@\n",
7386 lineno, markers[0], lineno, markers[1]) ||
7387 !stage_diff_write(&io, line, line + 1)) {
7388 chunk = NULL;
7390 } else {
7391 if (!stage_diff_write(&io, diff_hdr, chunk) ||
7392 !stage_diff_write(&io, chunk, view->line + view->lines))
7393 chunk = NULL;
7396 io_done(&io);
7398 return chunk ? TRUE : FALSE;
7401 static bool
7402 stage_update(struct view *view, struct line *line, bool single)
7404 struct line *chunk = NULL;
7406 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
7407 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7409 if (chunk) {
7410 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
7411 report("Failed to apply chunk");
7412 return FALSE;
7415 } else if (!stage_status.status) {
7416 view = view->parent;
7418 for (line = view->line; view_has_line(view, line); line++)
7419 if (line->type == stage_line_type)
7420 break;
7422 if (!status_update_files(view, line + 1)) {
7423 report("Failed to update files");
7424 return FALSE;
7427 } else if (!status_update_file(&stage_status, stage_line_type)) {
7428 report("Failed to update file");
7429 return FALSE;
7432 return TRUE;
7435 static bool
7436 stage_revert(struct view *view, struct line *line)
7438 struct line *chunk = NULL;
7440 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
7441 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
7443 if (chunk) {
7444 if (!prompt_yesno("Are you sure you want to revert changes?"))
7445 return FALSE;
7447 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
7448 report("Failed to revert chunk");
7449 return FALSE;
7451 return TRUE;
7453 } else {
7454 return status_revert(stage_status.status ? &stage_status : NULL,
7455 stage_line_type, FALSE);
7460 static void
7461 stage_next(struct view *view, struct line *line)
7463 struct stage_state *state = view->private;
7464 int i;
7466 if (!state->chunks) {
7467 for (line = view->line; view_has_line(view, line); line++) {
7468 if (line->type != LINE_DIFF_CHUNK)
7469 continue;
7471 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
7472 report("Allocation failure");
7473 return;
7476 state->chunk[state->chunks++] = line - view->line;
7480 for (i = 0; i < state->chunks; i++) {
7481 if (state->chunk[i] > view->pos.lineno) {
7482 do_scroll_view(view, state->chunk[i] - view->pos.lineno);
7483 report("Chunk %d of %zd", i + 1, state->chunks);
7484 return;
7488 report("No next chunk found");
7491 static enum request
7492 stage_request(struct view *view, enum request request, struct line *line)
7494 switch (request) {
7495 case REQ_STATUS_UPDATE:
7496 if (!stage_update(view, line, FALSE))
7497 return REQ_NONE;
7498 break;
7500 case REQ_STATUS_REVERT:
7501 if (!stage_revert(view, line))
7502 return REQ_NONE;
7503 break;
7505 case REQ_STAGE_UPDATE_LINE:
7506 if (stage_line_type == LINE_STAT_UNTRACKED ||
7507 stage_status.status == 'A') {
7508 report("Staging single lines is not supported for new files");
7509 return REQ_NONE;
7511 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
7512 report("Please select a change to stage");
7513 return REQ_NONE;
7515 if (!stage_update(view, line, TRUE))
7516 return REQ_NONE;
7517 break;
7519 case REQ_STAGE_NEXT:
7520 if (stage_line_type == LINE_STAT_UNTRACKED) {
7521 report("File is untracked; press %s to add",
7522 get_view_key(view, REQ_STATUS_UPDATE));
7523 return REQ_NONE;
7525 stage_next(view, line);
7526 return REQ_NONE;
7528 case REQ_EDIT:
7529 if (!stage_status.new.name[0])
7530 return diff_common_edit(view, request, line);
7532 if (stage_status.status == 'D') {
7533 report("File has been deleted.");
7534 return REQ_NONE;
7537 if (stage_line_type == LINE_STAT_UNTRACKED) {
7538 open_editor(stage_status.new.name, (line - view->line) + 1);
7539 } else {
7540 open_editor(stage_status.new.name, diff_get_lineno(view, line));
7542 break;
7544 case REQ_REFRESH:
7545 /* Reload everything(including current branch information) ... */
7546 load_refs(TRUE);
7547 break;
7549 case REQ_VIEW_BLAME:
7550 if (stage_status.new.name[0]) {
7551 string_copy(opt_file, stage_status.new.name);
7552 opt_ref[0] = 0;
7554 return request;
7556 case REQ_ENTER:
7557 return diff_common_enter(view, request, line);
7559 case REQ_DIFF_CONTEXT_UP:
7560 case REQ_DIFF_CONTEXT_DOWN:
7561 if (!update_diff_context(request))
7562 return REQ_NONE;
7563 break;
7565 default:
7566 return request;
7569 refresh_view(view->parent);
7571 /* Check whether the staged entry still exists, and close the
7572 * stage view if it doesn't. */
7573 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
7574 status_restore(view->parent);
7575 return REQ_VIEW_CLOSE;
7578 refresh_view(view);
7580 return REQ_NONE;
7583 static bool
7584 stage_open(struct view *view, enum open_flags flags)
7586 static const char *no_head_diff_argv[] = {
7587 GIT_DIFF_STAGED_INITIAL(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7588 stage_status.new.name)
7590 static const char *index_show_argv[] = {
7591 GIT_DIFF_STAGED(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7592 stage_status.old.name, stage_status.new.name)
7594 static const char *files_show_argv[] = {
7595 GIT_DIFF_UNSTAGED(encoding_arg, opt_diff_context_arg, opt_ignore_space_arg,
7596 stage_status.old.name, stage_status.new.name)
7598 /* Diffs for unmerged entries are empty when passing the new
7599 * path, so leave out the new path. */
7600 static const char *files_unmerged_argv[] = {
7601 "git", "diff-files", encoding_arg, "--root", "--patch-with-stat",
7602 opt_diff_context_arg, opt_ignore_space_arg, "--",
7603 stage_status.old.name, NULL
7605 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
7606 const char **argv = NULL;
7608 if (!stage_line_type) {
7609 report("No stage content, press %s to open the status view and choose file",
7610 get_view_key(view, REQ_VIEW_STATUS));
7611 return FALSE;
7614 view->encoding = NULL;
7616 switch (stage_line_type) {
7617 case LINE_STAT_STAGED:
7618 if (is_initial_commit()) {
7619 argv = no_head_diff_argv;
7620 } else {
7621 argv = index_show_argv;
7623 break;
7625 case LINE_STAT_UNSTAGED:
7626 if (stage_status.status != 'U')
7627 argv = files_show_argv;
7628 else
7629 argv = files_unmerged_argv;
7630 break;
7632 case LINE_STAT_UNTRACKED:
7633 argv = file_argv;
7634 view->encoding = get_path_encoding(stage_status.old.name, default_encoding);
7635 break;
7637 case LINE_STAT_HEAD:
7638 default:
7639 die("line type %d not handled in switch", stage_line_type);
7642 if (!status_stage_info(view->ref, stage_line_type, &stage_status)
7643 || !argv_copy(&view->argv, argv)) {
7644 report("Failed to open staged view");
7645 return FALSE;
7648 view->vid[0] = 0;
7649 view->dir = opt_cdup;
7650 return begin_update(view, NULL, NULL, flags);
7653 static bool
7654 stage_read(struct view *view, char *data)
7656 struct stage_state *state = view->private;
7658 if (stage_line_type == LINE_STAT_UNTRACKED)
7659 return pager_common_read(view, data, LINE_DEFAULT);
7661 if (data && diff_common_read(view, data, &state->diff))
7662 return TRUE;
7664 return pager_read(view, data);
7667 static struct view_ops stage_ops = {
7668 "line",
7669 { "stage" },
7670 VIEW_DIFF_LIKE,
7671 sizeof(struct stage_state),
7672 stage_open,
7673 stage_read,
7674 diff_common_draw,
7675 stage_request,
7676 pager_grep,
7677 pager_select,
7682 * Revision graph
7685 static const enum line_type graph_colors[] = {
7686 LINE_PALETTE_0,
7687 LINE_PALETTE_1,
7688 LINE_PALETTE_2,
7689 LINE_PALETTE_3,
7690 LINE_PALETTE_4,
7691 LINE_PALETTE_5,
7692 LINE_PALETTE_6,
7695 static enum line_type get_graph_color(struct graph_symbol *symbol)
7697 if (symbol->commit)
7698 return LINE_GRAPH_COMMIT;
7699 assert(symbol->color < ARRAY_SIZE(graph_colors));
7700 return graph_colors[symbol->color];
7703 static bool
7704 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7706 const char *chars = graph_symbol_to_utf8(symbol);
7708 return draw_text(view, color, chars + !!first);
7711 static bool
7712 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7714 const char *chars = graph_symbol_to_ascii(symbol);
7716 return draw_text(view, color, chars + !!first);
7719 static bool
7720 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
7722 const chtype *chars = graph_symbol_to_chtype(symbol);
7724 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
7727 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
7729 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
7731 static const draw_graph_fn fns[] = {
7732 draw_graph_ascii,
7733 draw_graph_chtype,
7734 draw_graph_utf8
7736 draw_graph_fn fn = fns[opt_line_graphics];
7737 int i;
7739 for (i = 0; i < canvas->size; i++) {
7740 struct graph_symbol *symbol = &canvas->symbols[i];
7741 enum line_type color = get_graph_color(symbol);
7743 if (fn(view, symbol, color, i == 0))
7744 return TRUE;
7747 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
7751 * Main view backend
7754 DEFINE_ALLOCATOR(realloc_reflogs, char *, 32)
7756 struct commit {
7757 char id[SIZEOF_REV]; /* SHA1 ID. */
7758 const struct ident *author; /* Author of the commit. */
7759 struct time time; /* Date from the author ident. */
7760 struct graph_canvas graph; /* Ancestry chain graphics. */
7761 char title[1]; /* First line of the commit message. */
7764 struct main_state {
7765 struct graph graph;
7766 struct commit current;
7767 char **reflog;
7768 size_t reflogs;
7769 int reflog_width;
7770 char reflogmsg[SIZEOF_STR / 2];
7771 bool in_header;
7772 bool added_changes_commits;
7773 bool with_graph;
7776 static void
7777 main_register_commit(struct view *view, struct commit *commit, const char *ids, bool is_boundary)
7779 struct main_state *state = view->private;
7781 string_copy_rev(commit->id, ids);
7782 if (state->with_graph)
7783 graph_add_commit(&state->graph, &commit->graph, commit->id, ids, is_boundary);
7786 static struct commit *
7787 main_add_commit(struct view *view, enum line_type type, struct commit *template,
7788 const char *title, bool custom)
7790 struct main_state *state = view->private;
7791 size_t titlelen = strlen(title);
7792 struct commit *commit;
7793 char buf[SIZEOF_STR / 2];
7795 /* FIXME: More graceful handling of titles; append "..." to
7796 * shortened titles, etc. */
7797 string_expand(buf, sizeof(buf), title, 1);
7798 title = buf;
7799 titlelen = strlen(title);
7801 if (!add_line_alloc(view, &commit, type, titlelen, custom))
7802 return NULL;
7804 *commit = *template;
7805 strncpy(commit->title, title, titlelen);
7806 state->graph.canvas = &commit->graph;
7807 memset(template, 0, sizeof(*template));
7808 state->reflogmsg[0] = 0;
7809 return commit;
7812 static inline void
7813 main_flush_commit(struct view *view, struct commit *commit)
7815 if (*commit->id)
7816 main_add_commit(view, LINE_MAIN_COMMIT, commit, "", FALSE);
7819 static bool
7820 main_has_changes(const char *argv[])
7822 struct io io;
7824 if (!io_run(&io, IO_BG, NULL, opt_env, argv, -1))
7825 return FALSE;
7826 io_done(&io);
7827 return io.status == 1;
7830 static void
7831 main_add_changes_commit(struct view *view, enum line_type type, const char *parent, const char *title)
7833 char ids[SIZEOF_STR] = NULL_ID " ";
7834 struct main_state *state = view->private;
7835 struct commit commit = {};
7836 struct timeval now;
7837 struct timezone tz;
7839 if (!parent)
7840 return;
7842 string_copy_rev(ids + STRING_SIZE(NULL_ID " "), parent);
7844 if (!gettimeofday(&now, &tz)) {
7845 commit.time.tz = tz.tz_minuteswest * 60;
7846 commit.time.sec = now.tv_sec - commit.time.tz;
7849 commit.author = &unknown_ident;
7850 main_register_commit(view, &commit, ids, FALSE);
7851 if (main_add_commit(view, type, &commit, title, TRUE) && state->with_graph)
7852 graph_render_parents(&state->graph);
7855 static void
7856 main_add_changes_commits(struct view *view, struct main_state *state, const char *parent)
7858 const char *staged_argv[] = { GIT_DIFF_STAGED_FILES("--quiet") };
7859 const char *unstaged_argv[] = { GIT_DIFF_UNSTAGED_FILES("--quiet") };
7860 const char *staged_parent = NULL_ID;
7861 const char *unstaged_parent = parent;
7863 if (!is_head_commit(parent))
7864 return;
7866 state->added_changes_commits = TRUE;
7868 io_run_bg(update_index_argv);
7870 if (!main_has_changes(unstaged_argv)) {
7871 unstaged_parent = NULL;
7872 staged_parent = parent;
7875 if (!main_has_changes(staged_argv)) {
7876 staged_parent = NULL;
7879 main_add_changes_commit(view, LINE_STAT_STAGED, staged_parent, "Staged changes");
7880 main_add_changes_commit(view, LINE_STAT_UNSTAGED, unstaged_parent, "Unstaged changes");
7883 static bool
7884 main_open(struct view *view, enum open_flags flags)
7886 static const char *main_argv[] = {
7887 GIT_MAIN_LOG(encoding_arg, "%(diffargs)", "%(revargs)", "%(fileargs)")
7889 struct main_state *state = view->private;
7891 state->with_graph = opt_rev_graph;
7893 if (flags & OPEN_PAGER_MODE) {
7894 state->added_changes_commits = TRUE;
7895 state->with_graph = FALSE;
7898 return begin_update(view, NULL, main_argv, flags);
7901 static void
7902 main_done(struct view *view)
7904 struct main_state *state = view->private;
7905 int i;
7907 for (i = 0; i < view->lines; i++) {
7908 struct commit *commit = view->line[i].data;
7910 free(commit->graph.symbols);
7913 for (i = 0; i < state->reflogs; i++)
7914 free(state->reflog[i]);
7915 free(state->reflog);
7918 #define MAIN_NO_COMMIT_REFS 1
7919 #define main_check_commit_refs(line) !((line)->user_flags & MAIN_NO_COMMIT_REFS)
7920 #define main_mark_no_commit_refs(line) ((line)->user_flags |= MAIN_NO_COMMIT_REFS)
7922 static inline struct ref_list *
7923 main_get_commit_refs(struct line *line, struct commit *commit)
7925 struct ref_list *refs = NULL;
7927 if (main_check_commit_refs(line) && !(refs = get_ref_list(commit->id)))
7928 main_mark_no_commit_refs(line);
7930 return refs;
7933 static bool
7934 main_draw(struct view *view, struct line *line, unsigned int lineno)
7936 struct main_state *state = view->private;
7937 struct commit *commit = line->data;
7938 struct ref_list *refs = NULL;
7940 if (!commit->author)
7941 return FALSE;
7943 if (draw_lineno(view, lineno))
7944 return TRUE;
7946 if (opt_show_id) {
7947 if (state->reflogs) {
7948 const char *id = state->reflog[line->lineno - 1];
7950 if (draw_id_custom(view, LINE_ID, id, state->reflog_width))
7951 return TRUE;
7952 } else if (draw_id(view, commit->id)) {
7953 return TRUE;
7957 if (draw_date(view, &commit->time))
7958 return TRUE;
7960 if (draw_author(view, commit->author))
7961 return TRUE;
7963 if (state->with_graph && draw_graph(view, &commit->graph))
7964 return TRUE;
7966 if ((refs = main_get_commit_refs(line, commit)) && draw_refs(view, refs))
7967 return TRUE;
7969 if (commit->title)
7970 draw_commit_title(view, commit->title, 0);
7971 return TRUE;
7974 static bool
7975 main_add_reflog(struct view *view, struct main_state *state, char *reflog)
7977 char *end = strchr(reflog, ' ');
7978 int id_width;
7980 if (!end)
7981 return FALSE;
7982 *end = 0;
7984 if (!realloc_reflogs(&state->reflog, state->reflogs, 1)
7985 || !(reflog = strdup(reflog)))
7986 return FALSE;
7988 state->reflog[state->reflogs++] = reflog;
7989 id_width = strlen(reflog);
7990 if (state->reflog_width < id_width) {
7991 state->reflog_width = id_width;
7992 if (opt_show_id)
7993 view->force_redraw = TRUE;
7996 return TRUE;
7999 /* Reads git log --pretty=raw output and parses it into the commit struct. */
8000 static bool
8001 main_read(struct view *view, char *line)
8003 struct main_state *state = view->private;
8004 struct graph *graph = &state->graph;
8005 enum line_type type;
8006 struct commit *commit = &state->current;
8008 if (!line) {
8009 main_flush_commit(view, commit);
8011 if (!view->lines && !view->prev)
8012 die("No revisions match the given arguments.");
8013 if (view->lines > 0) {
8014 struct commit *last = view->line[view->lines - 1].data;
8016 view->line[view->lines - 1].dirty = 1;
8017 if (!last->author) {
8018 view->lines--;
8019 free(last);
8023 if (state->with_graph)
8024 done_graph(graph);
8025 return TRUE;
8028 type = get_line_type(line);
8029 if (type == LINE_COMMIT) {
8030 bool is_boundary;
8032 state->in_header = TRUE;
8033 line += STRING_SIZE("commit ");
8034 is_boundary = *line == '-';
8035 if (is_boundary || !isalnum(*line))
8036 line++;
8038 if (!state->added_changes_commits && opt_show_changes && opt_is_inside_work_tree)
8039 main_add_changes_commits(view, state, line);
8040 else
8041 main_flush_commit(view, commit);
8043 main_register_commit(view, &state->current, line, is_boundary);
8044 return TRUE;
8047 if (!*commit->id)
8048 return TRUE;
8050 /* Empty line separates the commit header from the log itself. */
8051 if (*line == '\0')
8052 state->in_header = FALSE;
8054 switch (type) {
8055 case LINE_PP_REFLOG:
8056 if (!main_add_reflog(view, state, line + STRING_SIZE("Reflog: ")))
8057 return FALSE;
8058 break;
8060 case LINE_PP_REFLOGMSG:
8061 line += STRING_SIZE("Reflog message: ");
8062 string_ncopy(state->reflogmsg, line, strlen(line));
8063 break;
8065 case LINE_PARENT:
8066 if (state->with_graph && !graph->has_parents)
8067 graph_add_parent(graph, line + STRING_SIZE("parent "));
8068 break;
8070 case LINE_AUTHOR:
8071 parse_author_line(line + STRING_SIZE("author "),
8072 &commit->author, &commit->time);
8073 if (state->with_graph)
8074 graph_render_parents(graph);
8075 break;
8077 default:
8078 /* Fill in the commit title if it has not already been set. */
8079 if (*commit->title)
8080 break;
8082 /* Skip lines in the commit header. */
8083 if (state->in_header)
8084 break;
8086 /* Require titles to start with a non-space character at the
8087 * offset used by git log. */
8088 if (strncmp(line, " ", 4))
8089 break;
8090 line += 4;
8091 /* Well, if the title starts with a whitespace character,
8092 * try to be forgiving. Otherwise we end up with no title. */
8093 while (isspace(*line))
8094 line++;
8095 if (*line == '\0')
8096 break;
8097 if (*state->reflogmsg)
8098 line = state->reflogmsg;
8099 main_add_commit(view, LINE_MAIN_COMMIT, commit, line, FALSE);
8102 return TRUE;
8105 static enum request
8106 main_request(struct view *view, enum request request, struct line *line)
8108 enum open_flags flags = (view_is_displayed(view) && request != REQ_VIEW_DIFF)
8109 ? OPEN_SPLIT : OPEN_DEFAULT;
8111 switch (request) {
8112 case REQ_NEXT:
8113 case REQ_PREVIOUS:
8114 if (view_is_displayed(view) && display[0] != view)
8115 return request;
8116 /* Do not pass navigation requests to the branch view
8117 * when the main view is maximized. (GH #38) */
8118 return request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
8120 case REQ_VIEW_DIFF:
8121 case REQ_ENTER:
8122 if (view_is_displayed(view) && display[0] != view)
8123 maximize_view(view, TRUE);
8125 if (line->type == LINE_STAT_UNSTAGED
8126 || line->type == LINE_STAT_STAGED) {
8127 struct view *diff = VIEW(REQ_VIEW_DIFF);
8128 const char *diff_staged_argv[] = {
8129 GIT_DIFF_STAGED(encoding_arg,
8130 opt_diff_context_arg,
8131 opt_ignore_space_arg, NULL, NULL)
8133 const char *diff_unstaged_argv[] = {
8134 GIT_DIFF_UNSTAGED(encoding_arg,
8135 opt_diff_context_arg,
8136 opt_ignore_space_arg, NULL, NULL)
8138 const char **diff_argv = line->type == LINE_STAT_STAGED
8139 ? diff_staged_argv : diff_unstaged_argv;
8141 open_argv(view, diff, diff_argv, NULL, flags);
8142 break;
8145 open_view(view, REQ_VIEW_DIFF, flags);
8146 break;
8148 case REQ_REFRESH:
8149 load_refs(TRUE);
8150 refresh_view(view);
8151 break;
8153 case REQ_JUMP_COMMIT:
8155 int lineno;
8157 for (lineno = 0; lineno < view->lines; lineno++) {
8158 struct commit *commit = view->line[lineno].data;
8160 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
8161 select_view_line(view, lineno);
8162 report_clear();
8163 return REQ_NONE;
8167 report("Unable to find commit '%s'", opt_search);
8168 break;
8170 default:
8171 return request;
8174 return REQ_NONE;
8177 static bool
8178 grep_refs(struct line *line, struct commit *commit, regex_t *regex)
8180 struct ref_list *list;
8181 regmatch_t pmatch;
8182 size_t i;
8184 if (!opt_show_refs || !(list = main_get_commit_refs(line, commit)))
8185 return FALSE;
8187 for (i = 0; i < list->size; i++) {
8188 if (!regexec(regex, list->refs[i]->name, 1, &pmatch, 0))
8189 return TRUE;
8192 return FALSE;
8195 static bool
8196 main_grep(struct view *view, struct line *line)
8198 struct commit *commit = line->data;
8199 const char *text[] = {
8200 commit->id,
8201 commit->title,
8202 mkauthor(commit->author, opt_author_width, opt_author),
8203 mkdate(&commit->time, opt_date),
8204 NULL
8207 return grep_text(view, text) || grep_refs(line, commit, view->regex);
8210 static void
8211 main_select(struct view *view, struct line *line)
8213 struct commit *commit = line->data;
8215 if (line->type == LINE_STAT_STAGED || line->type == LINE_STAT_UNSTAGED)
8216 string_ncopy(view->ref, commit->title, strlen(commit->title));
8217 else
8218 string_copy_rev(view->ref, commit->id);
8219 string_copy_rev(ref_commit, commit->id);
8222 static struct view_ops main_ops = {
8223 "commit",
8224 { "main" },
8225 VIEW_SEND_CHILD_ENTER | VIEW_FILE_FILTER | VIEW_LOG_LIKE,
8226 sizeof(struct main_state),
8227 main_open,
8228 main_read,
8229 main_draw,
8230 main_request,
8231 main_grep,
8232 main_select,
8233 main_done,
8236 static bool
8237 stash_open(struct view *view, enum open_flags flags)
8239 static const char *stash_argv[] = { "git", "stash", "list",
8240 encoding_arg, "--no-color", "--pretty=raw", NULL };
8241 struct main_state *state = view->private;
8243 state->added_changes_commits = TRUE;
8244 state->with_graph = FALSE;
8245 return begin_update(view, NULL, stash_argv, flags | OPEN_RELOAD);
8248 static void
8249 stash_select(struct view *view, struct line *line)
8251 main_select(view, line);
8252 string_format(ref_stash, "stash@{%d}", line->lineno - 1);
8253 string_copy(view->ref, ref_stash);
8256 static struct view_ops stash_ops = {
8257 "stash",
8258 { "stash" },
8259 VIEW_SEND_CHILD_ENTER,
8260 sizeof(struct main_state),
8261 stash_open,
8262 main_read,
8263 main_draw,
8264 main_request,
8265 main_grep,
8266 stash_select,
8270 * Status management
8273 /* Whether or not the curses interface has been initialized. */
8274 static bool cursed = FALSE;
8276 /* Terminal hacks and workarounds. */
8277 static bool use_scroll_redrawwin;
8278 static bool use_scroll_status_wclear;
8280 /* The status window is used for polling keystrokes. */
8281 static WINDOW *status_win;
8283 /* Reading from the prompt? */
8284 static bool input_mode = FALSE;
8286 static bool status_empty = FALSE;
8288 /* Update status and title window. */
8289 static void
8290 report(const char *msg, ...)
8292 struct view *view = display[current_view];
8294 if (input_mode)
8295 return;
8297 if (!view) {
8298 char buf[SIZEOF_STR];
8299 int retval;
8301 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
8302 die("%s", buf);
8305 if (!status_empty || *msg) {
8306 va_list args;
8308 va_start(args, msg);
8310 wmove(status_win, 0, 0);
8311 if (view->has_scrolled && use_scroll_status_wclear)
8312 wclear(status_win);
8313 if (*msg) {
8314 vwprintw(status_win, msg, args);
8315 status_empty = FALSE;
8316 } else {
8317 status_empty = TRUE;
8319 wclrtoeol(status_win);
8320 wnoutrefresh(status_win);
8322 va_end(args);
8325 update_view_title(view);
8328 static void
8329 done_display(void)
8331 endwin();
8334 static void
8335 init_display(void)
8337 const char *term;
8338 int x, y;
8340 die_callback = done_display;
8342 /* Initialize the curses library */
8343 if (isatty(STDIN_FILENO)) {
8344 cursed = !!initscr();
8345 opt_tty = stdin;
8346 } else {
8347 /* Leave stdin and stdout alone when acting as a pager. */
8348 opt_tty = fopen("/dev/tty", "r+");
8349 if (!opt_tty)
8350 die("Failed to open /dev/tty");
8351 cursed = !!newterm(NULL, opt_tty, opt_tty);
8354 if (!cursed)
8355 die("Failed to initialize curses");
8357 nonl(); /* Disable conversion and detect newlines from input. */
8358 cbreak(); /* Take input chars one at a time, no wait for \n */
8359 noecho(); /* Don't echo input */
8360 leaveok(stdscr, FALSE);
8362 if (has_colors())
8363 init_colors();
8365 getmaxyx(stdscr, y, x);
8366 status_win = newwin(1, x, y - 1, 0);
8367 if (!status_win)
8368 die("Failed to create status window");
8370 /* Enable keyboard mapping */
8371 keypad(status_win, TRUE);
8372 wbkgdset(status_win, get_line_attr(LINE_STATUS));
8374 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
8375 set_tabsize(opt_tab_size);
8376 #else
8377 TABSIZE = opt_tab_size;
8378 #endif
8380 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
8381 if (term && !strcmp(term, "gnome-terminal")) {
8382 /* In the gnome-terminal-emulator, the message from
8383 * scrolling up one line when impossible followed by
8384 * scrolling down one line causes corruption of the
8385 * status line. This is fixed by calling wclear. */
8386 use_scroll_status_wclear = TRUE;
8387 use_scroll_redrawwin = FALSE;
8389 } else if (term && !strcmp(term, "xrvt-xpm")) {
8390 /* No problems with full optimizations in xrvt-(unicode)
8391 * and aterm. */
8392 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
8394 } else {
8395 /* When scrolling in (u)xterm the last line in the
8396 * scrolling direction will update slowly. */
8397 use_scroll_redrawwin = TRUE;
8398 use_scroll_status_wclear = FALSE;
8402 static int
8403 get_input(int prompt_position)
8405 struct view *view;
8406 int i, key, cursor_y, cursor_x;
8408 if (prompt_position)
8409 input_mode = TRUE;
8411 while (TRUE) {
8412 bool loading = FALSE;
8414 foreach_view (view, i) {
8415 update_view(view);
8416 if (view_is_displayed(view) && view->has_scrolled &&
8417 use_scroll_redrawwin)
8418 redrawwin(view->win);
8419 view->has_scrolled = FALSE;
8420 if (view->pipe)
8421 loading = TRUE;
8424 /* Update the cursor position. */
8425 if (prompt_position) {
8426 getbegyx(status_win, cursor_y, cursor_x);
8427 cursor_x = prompt_position;
8428 } else {
8429 view = display[current_view];
8430 getbegyx(view->win, cursor_y, cursor_x);
8431 cursor_x = view->width - 1;
8432 cursor_y += view->pos.lineno - view->pos.offset;
8434 setsyx(cursor_y, cursor_x);
8436 /* Refresh, accept single keystroke of input */
8437 doupdate();
8438 nodelay(status_win, loading);
8439 key = wgetch(status_win);
8441 /* wgetch() with nodelay() enabled returns ERR when
8442 * there's no input. */
8443 if (key == ERR) {
8445 } else if (key == KEY_RESIZE) {
8446 int height, width;
8448 getmaxyx(stdscr, height, width);
8450 wresize(status_win, 1, width);
8451 mvwin(status_win, height - 1, 0);
8452 wnoutrefresh(status_win);
8453 resize_display();
8454 redraw_display(TRUE);
8456 } else {
8457 input_mode = FALSE;
8458 if (key == erasechar())
8459 key = KEY_BACKSPACE;
8460 return key;
8465 static char *
8466 prompt_input(const char *prompt, input_handler handler, void *data)
8468 enum input_status status = INPUT_OK;
8469 static char buf[SIZEOF_STR];
8470 size_t pos = 0;
8472 buf[pos] = 0;
8474 while (status == INPUT_OK || status == INPUT_SKIP) {
8475 int key;
8477 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
8478 wclrtoeol(status_win);
8480 key = get_input(pos + 1);
8481 switch (key) {
8482 case KEY_RETURN:
8483 case KEY_ENTER:
8484 case '\n':
8485 status = pos ? INPUT_STOP : INPUT_CANCEL;
8486 break;
8488 case KEY_BACKSPACE:
8489 if (pos > 0)
8490 buf[--pos] = 0;
8491 else
8492 status = INPUT_CANCEL;
8493 break;
8495 case KEY_ESC:
8496 status = INPUT_CANCEL;
8497 break;
8499 default:
8500 if (pos >= sizeof(buf)) {
8501 report("Input string too long");
8502 return NULL;
8505 status = handler(data, buf, key);
8506 if (status == INPUT_OK)
8507 buf[pos++] = (char) key;
8511 /* Clear the status window */
8512 status_empty = FALSE;
8513 report_clear();
8515 if (status == INPUT_CANCEL)
8516 return NULL;
8518 buf[pos++] = 0;
8520 return buf;
8523 static enum input_status
8524 prompt_yesno_handler(void *data, char *buf, int c)
8526 if (c == 'y' || c == 'Y')
8527 return INPUT_STOP;
8528 if (c == 'n' || c == 'N')
8529 return INPUT_CANCEL;
8530 return INPUT_SKIP;
8533 static bool
8534 prompt_yesno(const char *prompt)
8536 char prompt2[SIZEOF_STR];
8538 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
8539 return FALSE;
8541 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
8544 static enum input_status
8545 read_prompt_handler(void *data, char *buf, int c)
8547 return isprint(c) ? INPUT_OK : INPUT_SKIP;
8550 static char *
8551 read_prompt(const char *prompt)
8553 return prompt_input(prompt, read_prompt_handler, NULL);
8556 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
8558 enum input_status status = INPUT_OK;
8559 int size = 0;
8561 while (items[size].text)
8562 size++;
8564 assert(size > 0);
8566 while (status == INPUT_OK) {
8567 const struct menu_item *item = &items[*selected];
8568 int key;
8569 int i;
8571 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
8572 prompt, *selected + 1, size);
8573 if (item->hotkey)
8574 wprintw(status_win, "[%c] ", (char) item->hotkey);
8575 wprintw(status_win, "%s", item->text);
8576 wclrtoeol(status_win);
8578 key = get_input(COLS - 1);
8579 switch (key) {
8580 case KEY_RETURN:
8581 case KEY_ENTER:
8582 case '\n':
8583 status = INPUT_STOP;
8584 break;
8586 case KEY_LEFT:
8587 case KEY_UP:
8588 *selected = *selected - 1;
8589 if (*selected < 0)
8590 *selected = size - 1;
8591 break;
8593 case KEY_RIGHT:
8594 case KEY_DOWN:
8595 *selected = (*selected + 1) % size;
8596 break;
8598 case KEY_ESC:
8599 status = INPUT_CANCEL;
8600 break;
8602 default:
8603 for (i = 0; items[i].text; i++)
8604 if (items[i].hotkey == key) {
8605 *selected = i;
8606 status = INPUT_STOP;
8607 break;
8612 /* Clear the status window */
8613 status_empty = FALSE;
8614 report_clear();
8616 return status != INPUT_CANCEL;
8620 * Repository properties
8624 static void
8625 set_remote_branch(const char *name, const char *value, size_t valuelen)
8627 if (!strcmp(name, ".remote")) {
8628 string_ncopy(opt_remote, value, valuelen);
8630 } else if (*opt_remote && !strcmp(name, ".merge")) {
8631 size_t from = strlen(opt_remote);
8633 if (!prefixcmp(value, "refs/heads/"))
8634 value += STRING_SIZE("refs/heads/");
8636 if (!string_format_from(opt_remote, &from, "/%s", value))
8637 opt_remote[0] = 0;
8641 static void
8642 set_repo_config_option(char *name, char *value, enum status_code (*cmd)(int, const char **))
8644 const char *argv[SIZEOF_ARG] = { name, "=" };
8645 int argc = 1 + (cmd == option_set_command);
8646 enum status_code error;
8648 if (!argv_from_string(argv, &argc, value))
8649 error = ERROR_TOO_MANY_OPTION_ARGUMENTS;
8650 else
8651 error = cmd(argc, argv);
8653 if (error != SUCCESS)
8654 warn("Option 'tig.%s': %s", name, get_status_message(error));
8657 static void
8658 set_work_tree(const char *value)
8660 char cwd[SIZEOF_STR];
8662 if (!getcwd(cwd, sizeof(cwd)))
8663 die("Failed to get cwd path: %s", strerror(errno));
8664 if (chdir(cwd) < 0)
8665 die("Failed to chdir(%s): %s", cwd, strerror(errno));
8666 if (chdir(opt_git_dir) < 0)
8667 die("Failed to chdir(%s): %s", opt_git_dir, strerror(errno));
8668 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
8669 die("Failed to get git path: %s", strerror(errno));
8670 if (chdir(value) < 0)
8671 die("Failed to chdir(%s): %s", value, strerror(errno));
8672 if (!getcwd(cwd, sizeof(cwd)))
8673 die("Failed to get cwd path: %s", strerror(errno));
8674 if (setenv("GIT_WORK_TREE", cwd, TRUE))
8675 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
8676 if (setenv("GIT_DIR", opt_git_dir, TRUE))
8677 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
8678 opt_is_inside_work_tree = TRUE;
8681 static void
8682 parse_git_color_option(enum line_type type, char *value)
8684 struct line_info *info = &line_info[type];
8685 const char *argv[SIZEOF_ARG];
8686 int argc = 0;
8687 bool first_color = TRUE;
8688 int i;
8690 if (!argv_from_string(argv, &argc, value))
8691 return;
8693 info->fg = COLOR_DEFAULT;
8694 info->bg = COLOR_DEFAULT;
8695 info->attr = 0;
8697 for (i = 0; i < argc; i++) {
8698 int attr = 0;
8700 if (set_attribute(&attr, argv[i])) {
8701 info->attr |= attr;
8703 } else if (set_color(&attr, argv[i])) {
8704 if (first_color)
8705 info->fg = attr;
8706 else
8707 info->bg = attr;
8708 first_color = FALSE;
8713 static void
8714 set_git_color_option(const char *name, char *value)
8716 static const struct enum_map color_option_map[] = {
8717 ENUM_MAP("branch.current", LINE_MAIN_HEAD),
8718 ENUM_MAP("branch.local", LINE_MAIN_REF),
8719 ENUM_MAP("branch.plain", LINE_MAIN_REF),
8720 ENUM_MAP("branch.remote", LINE_MAIN_REMOTE),
8722 ENUM_MAP("diff.meta", LINE_DIFF_HEADER),
8723 ENUM_MAP("diff.meta", LINE_DIFF_INDEX),
8724 ENUM_MAP("diff.meta", LINE_DIFF_OLDMODE),
8725 ENUM_MAP("diff.meta", LINE_DIFF_NEWMODE),
8726 ENUM_MAP("diff.frag", LINE_DIFF_CHUNK),
8727 ENUM_MAP("diff.old", LINE_DIFF_DEL),
8728 ENUM_MAP("diff.new", LINE_DIFF_ADD),
8730 //ENUM_MAP("diff.commit", LINE_DIFF_ADD),
8732 ENUM_MAP("status.branch", LINE_STAT_HEAD),
8733 //ENUM_MAP("status.nobranch", LINE_STAT_HEAD),
8734 ENUM_MAP("status.added", LINE_STAT_STAGED),
8735 ENUM_MAP("status.updated", LINE_STAT_STAGED),
8736 ENUM_MAP("status.changed", LINE_STAT_UNSTAGED),
8737 ENUM_MAP("status.untracked", LINE_STAT_UNTRACKED),
8740 int type = LINE_NONE;
8742 if (opt_read_git_colors && map_enum(&type, color_option_map, name)) {
8743 parse_git_color_option(type, value);
8747 static void
8748 set_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
8750 if (parse_encoding(encoding_ref, arg, priority) == SUCCESS)
8751 encoding_arg[0] = 0;
8754 static int
8755 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8757 if (!strcmp(name, "i18n.commitencoding"))
8758 set_encoding(&default_encoding, value, FALSE);
8760 else if (!strcmp(name, "gui.encoding"))
8761 set_encoding(&default_encoding, value, TRUE);
8763 else if (!strcmp(name, "core.editor"))
8764 string_ncopy(opt_editor, value, valuelen);
8766 else if (!strcmp(name, "core.worktree"))
8767 set_work_tree(value);
8769 else if (!strcmp(name, "core.abbrev"))
8770 parse_id(&opt_id_cols, value);
8772 else if (!prefixcmp(name, "tig.color."))
8773 set_repo_config_option(name + 10, value, option_color_command);
8775 else if (!prefixcmp(name, "tig.bind."))
8776 set_repo_config_option(name + 9, value, option_bind_command);
8778 else if (!prefixcmp(name, "tig."))
8779 set_repo_config_option(name + 4, value, option_set_command);
8781 else if (!prefixcmp(name, "color."))
8782 set_git_color_option(name + STRING_SIZE("color."), value);
8784 else if (*opt_head && !prefixcmp(name, "branch.") &&
8785 !strncmp(name + 7, opt_head, strlen(opt_head)))
8786 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
8788 return OK;
8791 static int
8792 load_git_config(void)
8794 const char *config_list_argv[] = { "git", "config", "--list", NULL };
8796 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
8799 #define REPO_INFO_GIT_DIR "--git-dir"
8800 #define REPO_INFO_WORK_TREE "--is-inside-work-tree"
8801 #define REPO_INFO_SHOW_CDUP "--show-cdup"
8802 #define REPO_INFO_SHOW_PREFIX "--show-prefix"
8803 #define REPO_INFO_SYMBOLIC_HEAD "--symbolic-full-name"
8804 #define REPO_INFO_RESOLVED_HEAD "HEAD"
8806 struct repo_info_state {
8807 const char **argv;
8808 char head_id[SIZEOF_REV];
8811 static int
8812 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8814 struct repo_info_state *state = data;
8815 const char *arg = *state->argv ? *state->argv++ : "";
8817 if (!strcmp(arg, REPO_INFO_GIT_DIR)) {
8818 string_ncopy(opt_git_dir, name, namelen);
8820 } else if (!strcmp(arg, REPO_INFO_WORK_TREE)) {
8821 /* This can be 3 different values depending on the
8822 * version of git being used. If git-rev-parse does not
8823 * understand --is-inside-work-tree it will simply echo
8824 * the option else either "true" or "false" is printed.
8825 * Default to true for the unknown case. */
8826 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
8828 } else if (!strcmp(arg, REPO_INFO_SHOW_CDUP)) {
8829 string_ncopy(opt_cdup, name, namelen);
8831 } else if (!strcmp(arg, REPO_INFO_SHOW_PREFIX)) {
8832 string_ncopy(opt_prefix, name, namelen);
8834 } else if (!strcmp(arg, REPO_INFO_RESOLVED_HEAD)) {
8835 string_ncopy(state->head_id, name, namelen);
8837 } else if (!strcmp(arg, REPO_INFO_SYMBOLIC_HEAD)) {
8838 if (!prefixcmp(name, "refs/heads/")) {
8839 char *offset = name + STRING_SIZE("refs/heads/");
8841 string_ncopy(opt_head, offset, strlen(offset) + 1);
8842 add_ref(state->head_id, name, opt_remote, opt_head);
8844 state->argv++;
8847 return OK;
8850 static int
8851 load_repo_info(void)
8853 const char *rev_parse_argv[] = {
8854 "git", "rev-parse", REPO_INFO_GIT_DIR, REPO_INFO_WORK_TREE,
8855 REPO_INFO_SHOW_CDUP, REPO_INFO_SHOW_PREFIX, \
8856 REPO_INFO_RESOLVED_HEAD, REPO_INFO_SYMBOLIC_HEAD, "HEAD",
8857 NULL
8859 struct repo_info_state state = { rev_parse_argv + 2 };
8861 return io_run_load(rev_parse_argv, "=", read_repo_info, &state);
8866 * Main
8869 static const char usage[] =
8870 "tig " TIG_VERSION " (" __DATE__ ")\n"
8871 "\n"
8872 "Usage: tig [options] [revs] [--] [paths]\n"
8873 " or: tig log [options] [revs] [--] [paths]\n"
8874 " or: tig show [options] [revs] [--] [paths]\n"
8875 " or: tig blame [options] [rev] [--] path\n"
8876 " or: tig stash\n"
8877 " or: tig status\n"
8878 " or: tig < [git command output]\n"
8879 "\n"
8880 "Options:\n"
8881 " +<number> Select line <number> in the first view\n"
8882 " -v, --version Show version and exit\n"
8883 " -h, --help Show help message and exit";
8885 static void TIG_NORETURN
8886 quit(int sig)
8888 if (sig)
8889 signal(sig, SIG_DFL);
8891 /* XXX: Restore tty modes and let the OS cleanup the rest! */
8892 if (cursed)
8893 endwin();
8894 exit(0);
8897 static int
8898 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
8900 const char ***filter_args = data;
8902 return argv_append(filter_args, name) ? OK : ERR;
8905 static void
8906 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
8908 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
8909 const char **all_argv = NULL;
8911 if (!argv_append_array(&all_argv, rev_parse_argv) ||
8912 !argv_append_array(&all_argv, argv) ||
8913 io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
8914 die("Failed to split arguments");
8915 argv_free(all_argv);
8916 free(all_argv);
8919 static bool
8920 is_rev_flag(const char *flag)
8922 static const char *rev_flags[] = { GIT_REV_FLAGS };
8923 int i;
8925 for (i = 0; i < ARRAY_SIZE(rev_flags); i++)
8926 if (!strcmp(flag, rev_flags[i]))
8927 return TRUE;
8929 return FALSE;
8932 static void
8933 filter_options(const char *argv[], bool blame)
8935 const char **flags = NULL;
8937 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
8938 filter_rev_parse(&flags, "--flags", "--no-revs", argv);
8940 if (flags) {
8941 int next, flags_pos;
8943 for (next = flags_pos = 0; flags && flags[next]; next++) {
8944 const char *flag = flags[next];
8946 if (is_rev_flag(flag))
8947 argv_append(&opt_rev_argv, flag);
8948 else
8949 flags[flags_pos++] = flag;
8952 flags[flags_pos] = NULL;
8954 if (blame)
8955 opt_blame_argv = flags;
8956 else
8957 opt_diff_argv = flags;
8960 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
8963 static enum request
8964 parse_options(int argc, const char *argv[], bool pager_mode)
8966 enum request request;
8967 const char *subcommand;
8968 bool seen_dashdash = FALSE;
8969 const char **filter_argv = NULL;
8970 int i;
8972 request = pager_mode ? REQ_VIEW_PAGER : REQ_VIEW_MAIN;
8974 if (argc <= 1)
8975 return request;
8977 subcommand = argv[1];
8978 if (!strcmp(subcommand, "status")) {
8979 request = REQ_VIEW_STATUS;
8981 } else if (!strcmp(subcommand, "blame")) {
8982 request = REQ_VIEW_BLAME;
8984 } else if (!strcmp(subcommand, "show")) {
8985 request = REQ_VIEW_DIFF;
8987 } else if (!strcmp(subcommand, "log")) {
8988 request = REQ_VIEW_LOG;
8990 } else if (!strcmp(subcommand, "stash")) {
8991 request = REQ_VIEW_STASH;
8993 } else {
8994 subcommand = NULL;
8997 for (i = 1 + !!subcommand; i < argc; i++) {
8998 const char *opt = argv[i];
9000 // stop parsing our options after -- and let rev-parse handle the rest
9001 if (!seen_dashdash) {
9002 if (!strcmp(opt, "--")) {
9003 seen_dashdash = TRUE;
9004 continue;
9006 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
9007 printf("tig version %s\n", TIG_VERSION);
9008 quit(0);
9010 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
9011 printf("%s\n", usage);
9012 quit(0);
9014 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
9015 opt_lineno = atoi(opt + 1);
9016 continue;
9021 if (!argv_append(&filter_argv, opt))
9022 die("command too long");
9025 if (filter_argv)
9026 filter_options(filter_argv, request == REQ_VIEW_BLAME);
9028 /* Finish validating and setting up blame options */
9029 if (request == REQ_VIEW_BLAME) {
9030 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
9031 die("invalid number of options to blame\n\n%s", usage);
9033 if (opt_rev_argv) {
9034 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
9037 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
9040 return request;
9043 static enum request
9044 open_pager_mode(enum request request)
9046 enum open_flags flags = OPEN_DEFAULT;
9048 if (request == REQ_VIEW_PAGER) {
9049 /* Detect if the user requested the main view. */
9050 if (argv_contains(opt_rev_argv, "--stdin")) {
9051 request = REQ_VIEW_MAIN;
9052 flags |= OPEN_FORWARD_STDIN;
9053 } else if (argv_contains(opt_diff_argv, "--pretty=raw")) {
9054 request = REQ_VIEW_MAIN;
9055 flags |= OPEN_STDIN;
9056 } else {
9057 flags |= OPEN_STDIN;
9060 } else if (request == REQ_VIEW_DIFF) {
9061 if (argv_contains(opt_rev_argv, "--stdin"))
9062 flags |= OPEN_FORWARD_STDIN;
9065 /* Open the requested view even if the pager mode is enabled so
9066 * the warning message below is displayed correctly. */
9067 open_view(NULL, request, flags);
9069 if (!open_in_pager_mode(flags)) {
9070 close(STDIN_FILENO);
9071 report("Ignoring stdin.");
9074 return REQ_NONE;
9077 static enum request
9078 run_prompt_command(struct view *view, char *cmd) {
9079 enum request request;
9081 if (cmd && string_isnumber(cmd)) {
9082 int lineno = view->pos.lineno + 1;
9084 if (parse_int(&lineno, cmd, 1, view->lines + 1) == SUCCESS) {
9085 select_view_line(view, lineno - 1);
9086 report_clear();
9087 } else {
9088 report("Unable to parse '%s' as a line number", cmd);
9090 } else if (cmd && iscommit(cmd)) {
9091 string_ncopy(opt_search, cmd, strlen(cmd));
9093 request = view_request(view, REQ_JUMP_COMMIT);
9094 if (request == REQ_JUMP_COMMIT) {
9095 report("Jumping to commits is not supported by the '%s' view", view->name);
9098 } else if (cmd && strlen(cmd) == 1) {
9099 request = get_keybinding(&view->ops->keymap, cmd[0]);
9100 return request;
9102 } else if (cmd && cmd[0] == '!') {
9103 struct view *next = VIEW(REQ_VIEW_PAGER);
9104 const char *argv[SIZEOF_ARG];
9105 int argc = 0;
9107 cmd++;
9108 /* When running random commands, initially show the
9109 * command in the title. However, it maybe later be
9110 * overwritten if a commit line is selected. */
9111 string_ncopy(next->ref, cmd, strlen(cmd));
9113 if (!argv_from_string(argv, &argc, cmd)) {
9114 report("Too many arguments");
9115 } else if (!format_argv(view, &next->argv, argv, FALSE, TRUE)) {
9116 report("Argument formatting failed");
9117 } else {
9118 next->dir = NULL;
9119 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
9122 } else if (cmd) {
9123 request = get_request(cmd);
9124 if (request != REQ_UNKNOWN)
9125 return request;
9127 char *args = strchr(cmd, ' ');
9128 if (args) {
9129 *args++ = 0;
9130 if (set_option(cmd, args) == SUCCESS) {
9131 request = !view->unrefreshable ? REQ_REFRESH : REQ_SCREEN_REDRAW;
9132 if (!strcmp(cmd, "color"))
9133 init_colors();
9136 return request;
9138 return REQ_NONE;
9142 main(int argc, const char *argv[])
9144 const char *codeset = ENCODING_UTF8;
9145 bool pager_mode = !isatty(STDIN_FILENO);
9146 enum request request = parse_options(argc, argv, pager_mode);
9147 struct view *view;
9148 int i;
9150 signal(SIGINT, quit);
9151 signal(SIGQUIT, quit);
9152 signal(SIGPIPE, SIG_IGN);
9154 if (setlocale(LC_ALL, "")) {
9155 codeset = nl_langinfo(CODESET);
9158 foreach_view(view, i) {
9159 add_keymap(&view->ops->keymap);
9162 if (load_repo_info() == ERR)
9163 die("Failed to load repo info.");
9165 if (load_options() == ERR)
9166 die("Failed to load user config.");
9168 if (load_git_config() == ERR)
9169 die("Failed to load repo config.");
9171 /* Require a git repository unless when running in pager mode. */
9172 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
9173 die("Not a git repository");
9175 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
9176 char translit[SIZEOF_STR];
9178 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
9179 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
9180 else
9181 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
9182 if (opt_iconv_out == ICONV_NONE)
9183 die("Failed to initialize character set conversion");
9186 if (load_refs(FALSE) == ERR)
9187 die("Failed to load refs.");
9189 init_display();
9191 if (pager_mode)
9192 request = open_pager_mode(request);
9194 while (view_driver(display[current_view], request)) {
9195 int key = get_input(0);
9197 if (key == KEY_ESC)
9198 key = get_input(0) + 0x80;
9200 view = display[current_view];
9201 request = get_keybinding(&view->ops->keymap, key);
9203 /* Some low-level request handling. This keeps access to
9204 * status_win restricted. */
9205 switch (request) {
9206 case REQ_NONE:
9207 report("Unknown key, press %s for help",
9208 get_view_key(view, REQ_VIEW_HELP));
9209 break;
9210 case REQ_PROMPT:
9212 char *cmd = read_prompt(":");
9213 request = run_prompt_command(view, cmd);
9214 break;
9216 case REQ_SEARCH:
9217 case REQ_SEARCH_BACK:
9219 const char *prompt = request == REQ_SEARCH ? "/" : "?";
9220 char *search = read_prompt(prompt);
9222 if (search)
9223 string_ncopy(opt_search, search, strlen(search));
9224 else if (*opt_search)
9225 request = request == REQ_SEARCH ?
9226 REQ_FIND_NEXT :
9227 REQ_FIND_PREV;
9228 else
9229 request = REQ_NONE;
9230 break;
9232 default:
9233 break;
9237 quit(0);
9239 return 0;
9242 /* vim: set ts=8 sw=8 noexpandtab: */