Fix mistake in tigrc: line-graphic expects utf8, not utf-8
[tig.git] / tig.c
blobf00e96d5cc323d5cae78b71b15ce434789e912d5
1 /* Copyright (c) 2006-2010 Jonas Fonseca <fonseca@diku.dk>
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU General Public License as
5 * published by the Free Software Foundation; either version 2 of
6 * the License, or (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
14 #include "tig.h"
15 #include "io.h"
16 #include "graph.h"
18 static void __NORETURN die(const char *err, ...);
19 static void warn(const char *msg, ...);
20 static void report(const char *msg, ...);
23 struct ref {
24 char id[SIZEOF_REV]; /* Commit SHA1 ID */
25 unsigned int head:1; /* Is it the current HEAD? */
26 unsigned int tag:1; /* Is it a tag? */
27 unsigned int ltag:1; /* If so, is the tag local? */
28 unsigned int remote:1; /* Is it a remote ref? */
29 unsigned int replace:1; /* Is it a replace ref? */
30 unsigned int tracked:1; /* Is it the remote for the current HEAD? */
31 char name[1]; /* Ref name; tag or head names are shortened. */
34 struct ref_list {
35 char id[SIZEOF_REV]; /* Commit SHA1 ID */
36 size_t size; /* Number of refs. */
37 struct ref **refs; /* References for this ID. */
40 static struct ref *get_ref_head();
41 static struct ref_list *get_ref_list(const char *id);
42 static void foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data);
43 static int load_refs(void);
45 enum input_status {
46 INPUT_OK,
47 INPUT_SKIP,
48 INPUT_STOP,
49 INPUT_CANCEL
52 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
54 static char *prompt_input(const char *prompt, input_handler handler, void *data);
55 static bool prompt_yesno(const char *prompt);
57 struct menu_item {
58 int hotkey;
59 const char *text;
60 void *data;
63 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
65 #define GRAPHIC_ENUM(_) \
66 _(GRAPHIC, ASCII), \
67 _(GRAPHIC, DEFAULT), \
68 _(GRAPHIC, UTF_8)
70 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
72 #define DATE_ENUM(_) \
73 _(DATE, NO), \
74 _(DATE, DEFAULT), \
75 _(DATE, LOCAL), \
76 _(DATE, RELATIVE), \
77 _(DATE, SHORT)
79 DEFINE_ENUM(date, DATE_ENUM);
81 struct time {
82 time_t sec;
83 int tz;
86 static inline int timecmp(const struct time *t1, const struct time *t2)
88 return t1->sec - t2->sec;
91 static const char *
92 mkdate(const struct time *time, enum date date)
94 static char buf[DATE_COLS + 1];
95 static const struct enum_map reldate[] = {
96 { "second", 1, 60 * 2 },
97 { "minute", 60, 60 * 60 * 2 },
98 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
99 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
100 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
101 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 30 * 12 },
103 struct tm tm;
105 if (!date || !time || !time->sec)
106 return "";
108 if (date == DATE_RELATIVE) {
109 struct timeval now;
110 time_t date = time->sec + time->tz;
111 time_t seconds;
112 int i;
114 gettimeofday(&now, NULL);
115 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
116 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
117 if (seconds >= reldate[i].value)
118 continue;
120 seconds /= reldate[i].namelen;
121 if (!string_format(buf, "%ld %s%s %s",
122 seconds, reldate[i].name,
123 seconds > 1 ? "s" : "",
124 now.tv_sec >= date ? "ago" : "ahead"))
125 break;
126 return buf;
130 if (date == DATE_LOCAL) {
131 time_t date = time->sec + time->tz;
132 localtime_r(&date, &tm);
134 else {
135 gmtime_r(&time->sec, &tm);
137 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
141 #define AUTHOR_ENUM(_) \
142 _(AUTHOR, NO), \
143 _(AUTHOR, FULL), \
144 _(AUTHOR, ABBREVIATED)
146 DEFINE_ENUM(author, AUTHOR_ENUM);
148 static const char *
149 get_author_initials(const char *author)
151 static char initials[AUTHOR_COLS * 6 + 1];
152 size_t pos = 0;
153 const char *end = strchr(author, '\0');
155 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
157 memset(initials, 0, sizeof(initials));
158 while (author < end) {
159 unsigned char bytes;
160 size_t i;
162 while (author < end && is_initial_sep(*author))
163 author++;
165 bytes = utf8_char_length(author, end);
166 if (bytes >= sizeof(initials) - 1 - pos)
167 break;
168 while (bytes--) {
169 initials[pos++] = *author++;
172 i = pos;
173 while (author < end && !is_initial_sep(*author)) {
174 bytes = utf8_char_length(author, end);
175 if (bytes >= sizeof(initials) - 1 - i) {
176 while (author < end && !is_initial_sep(*author))
177 author++;
178 break;
180 while (bytes--) {
181 initials[i++] = *author++;
185 initials[i++] = 0;
188 return initials;
191 #define author_trim(cols) (cols == 0 || cols > 5)
193 static const char *
194 mkauthor(const char *text, int cols, enum author author)
196 bool trim = author_trim(cols);
197 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
199 if (author == AUTHOR_NO)
200 return "";
201 if (abbreviate && text)
202 return get_author_initials(text);
203 return text;
206 static const char *
207 mkmode(mode_t mode)
209 if (S_ISDIR(mode))
210 return "drwxr-xr-x";
211 else if (S_ISLNK(mode))
212 return "lrwxrwxrwx";
213 else if (S_ISGITLINK(mode))
214 return "m---------";
215 else if (S_ISREG(mode) && mode & S_IXUSR)
216 return "-rwxr-xr-x";
217 else if (S_ISREG(mode))
218 return "-rw-r--r--";
219 else
220 return "----------";
223 #define FILENAME_ENUM(_) \
224 _(FILENAME, NO), \
225 _(FILENAME, ALWAYS), \
226 _(FILENAME, AUTO)
228 DEFINE_ENUM(filename, FILENAME_ENUM);
230 #define IGNORE_SPACE_ENUM(_) \
231 _(IGNORE_SPACE, NO), \
232 _(IGNORE_SPACE, ALL), \
233 _(IGNORE_SPACE, SOME), \
234 _(IGNORE_SPACE, AT_EOL)
236 DEFINE_ENUM(ignore_space, IGNORE_SPACE_ENUM);
238 #define VIEW_INFO(_) \
239 _(MAIN, main, ref_head), \
240 _(DIFF, diff, ref_commit), \
241 _(LOG, log, ref_head), \
242 _(TREE, tree, ref_commit), \
243 _(BLOB, blob, ref_blob), \
244 _(BLAME, blame, ref_commit), \
245 _(BRANCH, branch, ref_head), \
246 _(HELP, help, ""), \
247 _(PAGER, pager, ""), \
248 _(STATUS, status, "status"), \
249 _(STAGE, stage, "stage")
251 static struct encoding *
252 get_path_encoding(const char *path, struct encoding *default_encoding)
254 const char *check_attr_argv[] = {
255 "git", "check-attr", "encoding", "--", path, NULL
257 char buf[SIZEOF_STR];
258 char *encoding;
260 /* <path>: encoding: <encoding> */
262 if (!*path || !io_run_buf(check_attr_argv, buf, sizeof(buf))
263 || !(encoding = strstr(buf, ENCODING_SEP)))
264 return default_encoding;
266 encoding += STRING_SIZE(ENCODING_SEP);
267 if (!strcmp(encoding, ENCODING_UTF8)
268 || !strcmp(encoding, "unspecified")
269 || !strcmp(encoding, "set"))
270 return default_encoding;
272 return encoding_open(encoding);
276 * User requests
279 #define VIEW_REQ(id, name, ref) REQ_(VIEW_##id, "Show " #name " view")
281 #define REQ_INFO \
282 REQ_GROUP("View switching") \
283 VIEW_INFO(VIEW_REQ), \
285 REQ_GROUP("View manipulation") \
286 REQ_(ENTER, "Enter current line and scroll"), \
287 REQ_(NEXT, "Move to next"), \
288 REQ_(PREVIOUS, "Move to previous"), \
289 REQ_(PARENT, "Move to parent"), \
290 REQ_(VIEW_NEXT, "Move focus to next view"), \
291 REQ_(REFRESH, "Reload and refresh"), \
292 REQ_(MAXIMIZE, "Maximize the current view"), \
293 REQ_(VIEW_CLOSE, "Close the current view"), \
294 REQ_(QUIT, "Close all views and quit"), \
296 REQ_GROUP("View specific requests") \
297 REQ_(STATUS_UPDATE, "Update file status"), \
298 REQ_(STATUS_REVERT, "Revert file changes"), \
299 REQ_(STATUS_MERGE, "Merge file using external tool"), \
300 REQ_(STAGE_UPDATE_LINE, "Update single line"), \
301 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
302 REQ_(DIFF_CONTEXT_DOWN, "Decrease the diff context"), \
303 REQ_(DIFF_CONTEXT_UP, "Increase the diff context"), \
305 REQ_GROUP("Cursor navigation") \
306 REQ_(MOVE_UP, "Move cursor one line up"), \
307 REQ_(MOVE_DOWN, "Move cursor one line down"), \
308 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
309 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
310 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
311 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
313 REQ_GROUP("Scrolling") \
314 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
315 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
316 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
317 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
318 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
319 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
320 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
322 REQ_GROUP("Searching") \
323 REQ_(SEARCH, "Search the view"), \
324 REQ_(SEARCH_BACK, "Search backwards in the view"), \
325 REQ_(FIND_NEXT, "Find next search match"), \
326 REQ_(FIND_PREV, "Find previous search match"), \
328 REQ_GROUP("Option manipulation") \
329 REQ_(OPTIONS, "Open option menu"), \
330 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
331 REQ_(TOGGLE_DATE, "Toggle date display"), \
332 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
333 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
334 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
335 REQ_(TOGGLE_FILENAME, "Toggle file name display"), \
336 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
337 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
338 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
339 REQ_(TOGGLE_IGNORE_SPACE, "Toggle ignoring whitespace in diffs"), \
341 REQ_GROUP("Misc") \
342 REQ_(PROMPT, "Bring up the prompt"), \
343 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
344 REQ_(SHOW_VERSION, "Show version information"), \
345 REQ_(STOP_LOADING, "Stop all loading views"), \
346 REQ_(EDIT, "Open in editor"), \
347 REQ_(NONE, "Do nothing")
350 /* User action requests. */
351 enum request {
352 #define REQ_GROUP(help)
353 #define REQ_(req, help) REQ_##req
355 /* Offset all requests to avoid conflicts with ncurses getch values. */
356 REQ_UNKNOWN = KEY_MAX + 1,
357 REQ_OFFSET,
358 REQ_INFO,
360 /* Internal requests. */
361 REQ_JUMP_COMMIT,
363 #undef REQ_GROUP
364 #undef REQ_
367 struct request_info {
368 enum request request;
369 const char *name;
370 int namelen;
371 const char *help;
374 static const struct request_info req_info[] = {
375 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
376 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
377 REQ_INFO
378 #undef REQ_GROUP
379 #undef REQ_
382 static enum request
383 get_request(const char *name)
385 int namelen = strlen(name);
386 int i;
388 for (i = 0; i < ARRAY_SIZE(req_info); i++)
389 if (enum_equals(req_info[i], name, namelen))
390 return req_info[i].request;
392 return REQ_UNKNOWN;
397 * Options
400 /* Option and state variables. */
401 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
402 static enum date opt_date = DATE_DEFAULT;
403 static enum author opt_author = AUTHOR_FULL;
404 static enum filename opt_filename = FILENAME_AUTO;
405 static bool opt_rev_graph = TRUE;
406 static bool opt_line_number = FALSE;
407 static bool opt_show_refs = TRUE;
408 static bool opt_untracked_dirs_content = TRUE;
409 static int opt_diff_context = 3;
410 static char opt_diff_context_arg[9] = "";
411 static enum ignore_space opt_ignore_space = IGNORE_SPACE_NO;
412 static char opt_ignore_space_arg[22] = "";
413 static char opt_notes_arg[SIZEOF_STR] = "--no-notes";
414 static int opt_num_interval = 5;
415 static double opt_hscroll = 0.50;
416 static double opt_scale_split_view = 2.0 / 3.0;
417 static int opt_tab_size = 8;
418 static int opt_author_cols = AUTHOR_COLS;
419 static int opt_filename_cols = FILENAME_COLS;
420 static char opt_path[SIZEOF_STR] = "";
421 static char opt_file[SIZEOF_STR] = "";
422 static char opt_ref[SIZEOF_REF] = "";
423 static unsigned long opt_goto_line = 0;
424 static char opt_head[SIZEOF_REF] = "";
425 static char opt_remote[SIZEOF_REF] = "";
426 static struct encoding *opt_encoding = NULL;
427 static iconv_t opt_iconv_out = ICONV_NONE;
428 static char opt_search[SIZEOF_STR] = "";
429 static char opt_cdup[SIZEOF_STR] = "";
430 static char opt_prefix[SIZEOF_STR] = "";
431 static char opt_git_dir[SIZEOF_STR] = "";
432 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
433 static char opt_editor[SIZEOF_STR] = "";
434 static FILE *opt_tty = NULL;
435 static const char **opt_diff_argv = NULL;
436 static const char **opt_rev_argv = NULL;
437 static const char **opt_file_argv = NULL;
438 static const char **opt_blame_argv = NULL;
439 static int opt_lineno = 0;
441 #define is_initial_commit() (!get_ref_head())
442 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
444 static inline void
445 update_diff_context_arg(int diff_context)
447 if (!string_format(opt_diff_context_arg, "-U%u", diff_context))
448 string_ncopy(opt_diff_context_arg, "-U3", 3);
451 static inline void
452 update_ignore_space_arg()
454 if (opt_ignore_space == IGNORE_SPACE_ALL) {
455 string_copy(opt_ignore_space_arg, "--ignore-all-space");
456 } else if (opt_ignore_space == IGNORE_SPACE_SOME) {
457 string_copy(opt_ignore_space_arg, "--ignore-space-change");
458 } else if (opt_ignore_space == IGNORE_SPACE_AT_EOL) {
459 string_copy(opt_ignore_space_arg, "--ignore-space-at-eol");
460 } else {
461 string_copy(opt_ignore_space_arg, "");
466 * Line-oriented content detection.
469 #define LINE_INFO \
470 LINE(DIFF_HEADER, "diff --", COLOR_YELLOW, COLOR_DEFAULT, 0), \
471 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
472 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
473 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
474 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
475 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
476 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
477 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
478 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
479 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
480 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
481 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
482 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
483 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
484 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
485 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
486 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
487 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
488 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
489 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
490 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
491 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
492 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
493 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
494 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
495 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
496 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
497 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
498 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
499 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
500 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
501 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
502 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
503 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
504 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
505 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
506 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
507 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
508 LINE(FILENAME, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
509 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
510 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
511 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
512 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
513 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
514 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
515 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
516 LINE(MAIN_REPLACE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
517 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
518 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
519 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
520 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
521 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
522 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
523 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
524 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
525 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
526 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
527 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
528 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
529 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
530 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
531 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
532 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
533 LINE(DIFF_STAT, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
534 LINE(PALETTE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
535 LINE(PALETTE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
536 LINE(PALETTE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
537 LINE(PALETTE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
538 LINE(PALETTE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
539 LINE(PALETTE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
540 LINE(PALETTE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
541 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
543 enum line_type {
544 #define LINE(type, line, fg, bg, attr) \
545 LINE_##type
546 LINE_INFO,
547 LINE_NONE
548 #undef LINE
551 struct line_info {
552 const char *name; /* Option name. */
553 int namelen; /* Size of option name. */
554 const char *line; /* The start of line to match. */
555 int linelen; /* Size of string to match. */
556 int fg, bg, attr; /* Color and text attributes for the lines. */
559 static struct line_info line_info[] = {
560 #define LINE(type, line, fg, bg, attr) \
561 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
562 LINE_INFO
563 #undef LINE
566 static struct line_info *custom_color;
567 static size_t custom_colors;
569 DEFINE_ALLOCATOR(realloc_custom_color, struct line_info, 8)
571 #define TO_CUSTOM_COLOR_TYPE(type) (LINE_NONE + 1 + (type))
572 #define TO_CUSTOM_COLOR_OFFSET(type) ((type) - LINE_NONE - 1)
574 /* Color IDs must be 1 or higher. [GH #15] */
575 #define COLOR_ID(line_type) ((line_type) + 1)
577 static enum line_type
578 get_line_type(const char *line)
580 int linelen = strlen(line);
581 enum line_type type;
583 for (type = 0; type < custom_colors; type++)
584 /* Case insensitive search matches Signed-off-by lines better. */
585 if (linelen >= custom_color[type].linelen &&
586 !strncasecmp(custom_color[type].line, line, custom_color[type].linelen))
587 return TO_CUSTOM_COLOR_TYPE(type);
589 for (type = 0; type < ARRAY_SIZE(line_info); type++)
590 /* Case insensitive search matches Signed-off-by lines better. */
591 if (linelen >= line_info[type].linelen &&
592 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
593 return type;
595 return LINE_DEFAULT;
598 static enum line_type
599 get_line_type_from_ref(const struct ref *ref)
601 if (ref->head)
602 return LINE_MAIN_HEAD;
603 else if (ref->ltag)
604 return LINE_MAIN_LOCAL_TAG;
605 else if (ref->tag)
606 return LINE_MAIN_TAG;
607 else if (ref->tracked)
608 return LINE_MAIN_TRACKED;
609 else if (ref->remote)
610 return LINE_MAIN_REMOTE;
611 else if (ref->replace)
612 return LINE_MAIN_REPLACE;
614 return LINE_MAIN_REF;
617 static inline int
618 get_line_attr(enum line_type type)
620 if (type > LINE_NONE) {
621 assert(TO_CUSTOM_COLOR_OFFSET(type) < custom_colors);
622 return COLOR_PAIR(COLOR_ID(type)) | custom_color[TO_CUSTOM_COLOR_OFFSET(type)].attr;
624 assert(type < ARRAY_SIZE(line_info));
625 return COLOR_PAIR(COLOR_ID(type)) | line_info[type].attr;
628 static struct line_info *
629 get_line_info(const char *name)
631 size_t namelen = strlen(name);
632 enum line_type type;
634 for (type = 0; type < ARRAY_SIZE(line_info); type++)
635 if (enum_equals(line_info[type], name, namelen))
636 return &line_info[type];
638 return NULL;
641 static struct line_info *
642 add_custom_color(const char *quoted_line)
644 struct line_info *info;
645 char *line;
646 size_t linelen;
648 if (!realloc_custom_color(&custom_color, custom_colors, 1))
649 die("Failed to alloc custom line info");
651 linelen = strlen(quoted_line) - 1;
652 line = malloc(linelen);
653 if (!line)
654 return NULL;
656 strncpy(line, quoted_line + 1, linelen);
657 line[linelen - 1] = 0;
659 info = &custom_color[custom_colors++];
660 info->name = info->line = line;
661 info->namelen = info->linelen = strlen(line);
663 return info;
666 static void
667 init_line_info_color_pair(struct line_info *info, enum line_type type,
668 int default_bg, int default_fg)
670 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
671 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
673 init_pair(COLOR_ID(type), fg, bg);
676 static void
677 init_colors(void)
679 int default_bg = line_info[LINE_DEFAULT].bg;
680 int default_fg = line_info[LINE_DEFAULT].fg;
681 enum line_type type;
683 start_color();
685 if (assume_default_colors(default_fg, default_bg) == ERR) {
686 default_bg = COLOR_BLACK;
687 default_fg = COLOR_WHITE;
690 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
691 struct line_info *info = &line_info[type];
693 init_line_info_color_pair(info, type, default_bg, default_fg);
696 for (type = 0; type < custom_colors; type++) {
697 struct line_info *info = &custom_color[type];
699 init_line_info_color_pair(info, TO_CUSTOM_COLOR_TYPE(type),
700 default_bg, default_fg);
704 struct line {
705 enum line_type type;
707 /* State flags */
708 unsigned int selected:1;
709 unsigned int dirty:1;
710 unsigned int cleareol:1;
711 unsigned int other:16;
713 void *data; /* User data */
718 * Keys
721 struct keybinding {
722 int alias;
723 enum request request;
726 static struct keybinding default_keybindings[] = {
727 /* View switching */
728 { 'm', REQ_VIEW_MAIN },
729 { 'd', REQ_VIEW_DIFF },
730 { 'l', REQ_VIEW_LOG },
731 { 't', REQ_VIEW_TREE },
732 { 'f', REQ_VIEW_BLOB },
733 { 'B', REQ_VIEW_BLAME },
734 { 'H', REQ_VIEW_BRANCH },
735 { 'p', REQ_VIEW_PAGER },
736 { 'h', REQ_VIEW_HELP },
737 { 'S', REQ_VIEW_STATUS },
738 { 'c', REQ_VIEW_STAGE },
740 /* View manipulation */
741 { 'q', REQ_VIEW_CLOSE },
742 { KEY_TAB, REQ_VIEW_NEXT },
743 { KEY_RETURN, REQ_ENTER },
744 { KEY_UP, REQ_PREVIOUS },
745 { KEY_CTL('P'), REQ_PREVIOUS },
746 { KEY_DOWN, REQ_NEXT },
747 { KEY_CTL('N'), REQ_NEXT },
748 { 'R', REQ_REFRESH },
749 { KEY_F(5), REQ_REFRESH },
750 { 'O', REQ_MAXIMIZE },
751 { ',', REQ_PARENT },
753 /* View specific */
754 { 'u', REQ_STATUS_UPDATE },
755 { '!', REQ_STATUS_REVERT },
756 { 'M', REQ_STATUS_MERGE },
757 { '1', REQ_STAGE_UPDATE_LINE },
758 { '@', REQ_STAGE_NEXT },
759 { '[', REQ_DIFF_CONTEXT_DOWN },
760 { ']', REQ_DIFF_CONTEXT_UP },
762 /* Cursor navigation */
763 { 'k', REQ_MOVE_UP },
764 { 'j', REQ_MOVE_DOWN },
765 { KEY_HOME, REQ_MOVE_FIRST_LINE },
766 { KEY_END, REQ_MOVE_LAST_LINE },
767 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
768 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
769 { ' ', REQ_MOVE_PAGE_DOWN },
770 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
771 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
772 { 'b', REQ_MOVE_PAGE_UP },
773 { '-', REQ_MOVE_PAGE_UP },
775 /* Scrolling */
776 { '|', REQ_SCROLL_FIRST_COL },
777 { KEY_LEFT, REQ_SCROLL_LEFT },
778 { KEY_RIGHT, REQ_SCROLL_RIGHT },
779 { KEY_IC, REQ_SCROLL_LINE_UP },
780 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
781 { KEY_DC, REQ_SCROLL_LINE_DOWN },
782 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
783 { 'w', REQ_SCROLL_PAGE_UP },
784 { 's', REQ_SCROLL_PAGE_DOWN },
786 /* Searching */
787 { '/', REQ_SEARCH },
788 { '?', REQ_SEARCH_BACK },
789 { 'n', REQ_FIND_NEXT },
790 { 'N', REQ_FIND_PREV },
792 /* Misc */
793 { 'Q', REQ_QUIT },
794 { 'z', REQ_STOP_LOADING },
795 { 'v', REQ_SHOW_VERSION },
796 { 'r', REQ_SCREEN_REDRAW },
797 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
798 { 'o', REQ_OPTIONS },
799 { '.', REQ_TOGGLE_LINENO },
800 { 'D', REQ_TOGGLE_DATE },
801 { 'A', REQ_TOGGLE_AUTHOR },
802 { 'g', REQ_TOGGLE_REV_GRAPH },
803 { '~', REQ_TOGGLE_GRAPHIC },
804 { '#', REQ_TOGGLE_FILENAME },
805 { 'F', REQ_TOGGLE_REFS },
806 { 'I', REQ_TOGGLE_SORT_ORDER },
807 { 'i', REQ_TOGGLE_SORT_FIELD },
808 { 'W', REQ_TOGGLE_IGNORE_SPACE },
809 { ':', REQ_PROMPT },
810 { 'e', REQ_EDIT },
813 #define KEYMAP_ENUM(_) \
814 _(KEYMAP, GENERIC), \
815 _(KEYMAP, MAIN), \
816 _(KEYMAP, DIFF), \
817 _(KEYMAP, LOG), \
818 _(KEYMAP, TREE), \
819 _(KEYMAP, BLOB), \
820 _(KEYMAP, BLAME), \
821 _(KEYMAP, BRANCH), \
822 _(KEYMAP, PAGER), \
823 _(KEYMAP, HELP), \
824 _(KEYMAP, STATUS), \
825 _(KEYMAP, STAGE)
827 DEFINE_ENUM(keymap, KEYMAP_ENUM);
829 #define set_keymap(map, name) map_enum(map, keymap_map, name)
831 struct keybinding_table {
832 struct keybinding *data;
833 size_t size;
836 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_map)];
838 static void
839 add_keybinding(enum keymap keymap, enum request request, int key)
841 struct keybinding_table *table = &keybindings[keymap];
842 size_t i;
844 for (i = 0; i < table->size; i++) {
845 if (table->data[i].alias == key) {
846 table->data[i].request = request;
847 return;
851 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
852 if (!table->data)
853 die("Failed to allocate keybinding");
854 table->data[table->size].alias = key;
855 table->data[table->size++].request = request;
857 if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
858 int i;
860 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
861 if (default_keybindings[i].alias == key)
862 default_keybindings[i].request = REQ_NONE;
866 /* Looks for a key binding first in the given map, then in the generic map, and
867 * lastly in the default keybindings. */
868 static enum request
869 get_keybinding(enum keymap keymap, int key)
871 size_t i;
873 for (i = 0; i < keybindings[keymap].size; i++)
874 if (keybindings[keymap].data[i].alias == key)
875 return keybindings[keymap].data[i].request;
877 for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
878 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
879 return keybindings[KEYMAP_GENERIC].data[i].request;
881 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
882 if (default_keybindings[i].alias == key)
883 return default_keybindings[i].request;
885 return (enum request) key;
889 struct key {
890 const char *name;
891 int value;
894 static const struct key key_table[] = {
895 { "Enter", KEY_RETURN },
896 { "Space", ' ' },
897 { "Backspace", KEY_BACKSPACE },
898 { "Tab", KEY_TAB },
899 { "Escape", KEY_ESC },
900 { "Left", KEY_LEFT },
901 { "Right", KEY_RIGHT },
902 { "Up", KEY_UP },
903 { "Down", KEY_DOWN },
904 { "Insert", KEY_IC },
905 { "Delete", KEY_DC },
906 { "Hash", '#' },
907 { "Home", KEY_HOME },
908 { "End", KEY_END },
909 { "PageUp", KEY_PPAGE },
910 { "PageDown", KEY_NPAGE },
911 { "F1", KEY_F(1) },
912 { "F2", KEY_F(2) },
913 { "F3", KEY_F(3) },
914 { "F4", KEY_F(4) },
915 { "F5", KEY_F(5) },
916 { "F6", KEY_F(6) },
917 { "F7", KEY_F(7) },
918 { "F8", KEY_F(8) },
919 { "F9", KEY_F(9) },
920 { "F10", KEY_F(10) },
921 { "F11", KEY_F(11) },
922 { "F12", KEY_F(12) },
925 static int
926 get_key_value(const char *name)
928 int i;
930 for (i = 0; i < ARRAY_SIZE(key_table); i++)
931 if (!strcasecmp(key_table[i].name, name))
932 return key_table[i].value;
934 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
935 return (int)name[1] & 0x1f;
936 if (strlen(name) == 1 && isprint(*name))
937 return (int) *name;
938 return ERR;
941 static const char *
942 get_key_name(int key_value)
944 static char key_char[] = "'X'\0";
945 const char *seq = NULL;
946 int key;
948 for (key = 0; key < ARRAY_SIZE(key_table); key++)
949 if (key_table[key].value == key_value)
950 seq = key_table[key].name;
952 if (seq == NULL && key_value < 0x7f) {
953 char *s = key_char + 1;
955 if (key_value >= 0x20) {
956 *s++ = key_value;
957 } else {
958 *s++ = '^';
959 *s++ = 0x40 | (key_value & 0x1f);
961 *s++ = '\'';
962 *s++ = '\0';
963 seq = key_char;
966 return seq ? seq : "(no key)";
969 static bool
970 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
972 const char *sep = *pos > 0 ? ", " : "";
973 const char *keyname = get_key_name(keybinding->alias);
975 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
978 static bool
979 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
980 enum keymap keymap, bool all)
982 int i;
984 for (i = 0; i < keybindings[keymap].size; i++) {
985 if (keybindings[keymap].data[i].request == request) {
986 if (!append_key(buf, pos, &keybindings[keymap].data[i]))
987 return FALSE;
988 if (!all)
989 break;
993 return TRUE;
996 #define get_view_key(view, request) get_keys((view)->keymap, request, FALSE)
998 static const char *
999 get_keys(enum keymap keymap, enum request request, bool all)
1001 static char buf[BUFSIZ];
1002 size_t pos = 0;
1003 int i;
1005 buf[pos] = 0;
1007 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
1008 return "Too many keybindings!";
1009 if (pos > 0 && !all)
1010 return buf;
1012 if (keymap != KEYMAP_GENERIC) {
1013 /* Only the generic keymap includes the default keybindings when
1014 * listing all keys. */
1015 if (all)
1016 return buf;
1018 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
1019 return "Too many keybindings!";
1020 if (pos)
1021 return buf;
1024 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
1025 if (default_keybindings[i].request == request) {
1026 if (!append_key(buf, &pos, &default_keybindings[i]))
1027 return "Too many keybindings!";
1028 if (!all)
1029 return buf;
1033 return buf;
1036 struct run_request {
1037 enum keymap keymap;
1038 int key;
1039 const char **argv;
1042 static struct run_request *run_request;
1043 static size_t run_requests;
1045 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
1047 static enum request
1048 add_run_request(enum keymap keymap, int key, const char **argv)
1050 struct run_request *req;
1052 if (!realloc_run_requests(&run_request, run_requests, 1))
1053 return REQ_NONE;
1055 req = &run_request[run_requests];
1056 req->keymap = keymap;
1057 req->key = key;
1058 req->argv = NULL;
1060 if (!argv_copy(&req->argv, argv))
1061 return REQ_NONE;
1063 return REQ_NONE + ++run_requests;
1066 static struct run_request *
1067 get_run_request(enum request request)
1069 if (request <= REQ_NONE)
1070 return NULL;
1071 return &run_request[request - REQ_NONE - 1];
1074 static void
1075 add_builtin_run_requests(void)
1077 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
1078 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
1079 const char *commit[] = { "git", "commit", NULL };
1080 const char *gc[] = { "git", "gc", NULL };
1081 struct run_request reqs[] = {
1082 { KEYMAP_MAIN, 'C', cherry_pick },
1083 { KEYMAP_STATUS, 'C', commit },
1084 { KEYMAP_BRANCH, 'C', checkout },
1085 { KEYMAP_GENERIC, 'G', gc },
1087 int i;
1089 for (i = 0; i < ARRAY_SIZE(reqs); i++) {
1090 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
1092 if (req != reqs[i].key)
1093 continue;
1094 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
1095 if (req != REQ_NONE)
1096 add_keybinding(reqs[i].keymap, req, reqs[i].key);
1101 * User config file handling.
1104 #define OPT_ERR_INFO \
1105 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
1106 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
1107 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
1108 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
1109 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
1110 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
1111 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
1112 OPT_ERR_(FILE_DOES_NOT_EXIST, "File does not exist"), \
1113 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
1114 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
1115 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
1116 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
1117 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
1118 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
1119 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
1120 OPT_ERR_(OBSOLETE_VARIABLE_NAME, "Obsolete variable name"), \
1121 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
1122 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
1123 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
1125 enum option_code {
1126 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
1127 OPT_ERR_INFO
1128 #undef OPT_ERR_
1129 OPT_OK
1132 static const char *option_errors[] = {
1133 #define OPT_ERR_(name, msg) msg
1134 OPT_ERR_INFO
1135 #undef OPT_ERR_
1138 static const struct enum_map color_map[] = {
1139 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1140 COLOR_MAP(DEFAULT),
1141 COLOR_MAP(BLACK),
1142 COLOR_MAP(BLUE),
1143 COLOR_MAP(CYAN),
1144 COLOR_MAP(GREEN),
1145 COLOR_MAP(MAGENTA),
1146 COLOR_MAP(RED),
1147 COLOR_MAP(WHITE),
1148 COLOR_MAP(YELLOW),
1151 static const struct enum_map attr_map[] = {
1152 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1153 ATTR_MAP(NORMAL),
1154 ATTR_MAP(BLINK),
1155 ATTR_MAP(BOLD),
1156 ATTR_MAP(DIM),
1157 ATTR_MAP(REVERSE),
1158 ATTR_MAP(STANDOUT),
1159 ATTR_MAP(UNDERLINE),
1162 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1164 static enum option_code
1165 parse_step(double *opt, const char *arg)
1167 *opt = atoi(arg);
1168 if (!strchr(arg, '%'))
1169 return OPT_OK;
1171 /* "Shift down" so 100% and 1 does not conflict. */
1172 *opt = (*opt - 1) / 100;
1173 if (*opt >= 1.0) {
1174 *opt = 0.99;
1175 return OPT_ERR_INVALID_STEP_VALUE;
1177 if (*opt < 0.0) {
1178 *opt = 1;
1179 return OPT_ERR_INVALID_STEP_VALUE;
1181 return OPT_OK;
1184 static enum option_code
1185 parse_int(int *opt, const char *arg, int min, int max)
1187 int value = atoi(arg);
1189 if (min <= value && value <= max) {
1190 *opt = value;
1191 return OPT_OK;
1194 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1197 static bool
1198 set_color(int *color, const char *name)
1200 if (map_enum(color, color_map, name))
1201 return TRUE;
1202 if (!prefixcmp(name, "color"))
1203 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1204 return FALSE;
1207 /* Wants: object fgcolor bgcolor [attribute] */
1208 static enum option_code
1209 option_color_command(int argc, const char *argv[])
1211 struct line_info *info;
1213 if (argc < 3)
1214 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1216 if (*argv[0] == '"' || *argv[0] == '\'') {
1217 info = add_custom_color(argv[0]);
1218 } else {
1219 info = get_line_info(argv[0]);
1221 if (!info) {
1222 static const struct enum_map obsolete[] = {
1223 ENUM_MAP("main-delim", LINE_DELIMITER),
1224 ENUM_MAP("main-date", LINE_DATE),
1225 ENUM_MAP("main-author", LINE_AUTHOR),
1227 int index;
1229 if (!map_enum(&index, obsolete, argv[0]))
1230 return OPT_ERR_UNKNOWN_COLOR_NAME;
1231 info = &line_info[index];
1234 if (!set_color(&info->fg, argv[1]) ||
1235 !set_color(&info->bg, argv[2]))
1236 return OPT_ERR_UNKNOWN_COLOR;
1238 info->attr = 0;
1239 while (argc-- > 3) {
1240 int attr;
1242 if (!set_attribute(&attr, argv[argc]))
1243 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1244 info->attr |= attr;
1247 return OPT_OK;
1250 static enum option_code
1251 parse_bool(bool *opt, const char *arg)
1253 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1254 ? TRUE : FALSE;
1255 return OPT_OK;
1258 static enum option_code
1259 parse_enum_do(unsigned int *opt, const char *arg,
1260 const struct enum_map *map, size_t map_size)
1262 bool is_true;
1264 assert(map_size > 1);
1266 if (map_enum_do(map, map_size, (int *) opt, arg))
1267 return OPT_OK;
1269 parse_bool(&is_true, arg);
1270 *opt = is_true ? map[1].value : map[0].value;
1271 return OPT_OK;
1274 #define parse_enum(opt, arg, map) \
1275 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1277 static enum option_code
1278 parse_string(char *opt, const char *arg, size_t optsize)
1280 int arglen = strlen(arg);
1282 switch (arg[0]) {
1283 case '\"':
1284 case '\'':
1285 if (arglen == 1 || arg[arglen - 1] != arg[0])
1286 return OPT_ERR_UNMATCHED_QUOTATION;
1287 arg += 1; arglen -= 2;
1288 default:
1289 string_ncopy_do(opt, optsize, arg, arglen);
1290 return OPT_OK;
1294 static enum option_code
1295 parse_encoding(struct encoding **encoding_ref, const char *arg, bool priority)
1297 char buf[SIZEOF_STR];
1298 enum option_code code = parse_string(buf, arg, sizeof(buf));
1300 if (code == OPT_OK) {
1301 struct encoding *encoding = *encoding_ref;
1303 if (encoding && !priority)
1304 return code;
1305 encoding = encoding_open(buf);
1306 if (encoding)
1307 *encoding_ref = encoding;
1310 return code;
1313 static enum option_code
1314 parse_args(const char ***args, const char *argv[])
1316 if (*args == NULL && !argv_copy(args, argv))
1317 return OPT_ERR_OUT_OF_MEMORY;
1318 return OPT_OK;
1321 /* Wants: name = value */
1322 static enum option_code
1323 option_set_command(int argc, const char *argv[])
1325 if (argc < 3)
1326 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1328 if (strcmp(argv[1], "="))
1329 return OPT_ERR_NO_VALUE_ASSIGNED;
1331 if (!strcmp(argv[0], "blame-options"))
1332 return parse_args(&opt_blame_argv, argv + 2);
1334 if (argc != 3)
1335 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1337 if (!strcmp(argv[0], "show-author"))
1338 return parse_enum(&opt_author, argv[2], author_map);
1340 if (!strcmp(argv[0], "show-date"))
1341 return parse_enum(&opt_date, argv[2], date_map);
1343 if (!strcmp(argv[0], "show-rev-graph"))
1344 return parse_bool(&opt_rev_graph, argv[2]);
1346 if (!strcmp(argv[0], "show-refs"))
1347 return parse_bool(&opt_show_refs, argv[2]);
1349 if (!strcmp(argv[0], "show-notes")) {
1350 int res;
1352 strcpy(opt_notes_arg, "--notes=");
1353 res = parse_string(opt_notes_arg + 8, argv[2],
1354 sizeof(opt_notes_arg) - 8);
1355 if (res == OPT_OK && opt_notes_arg[8] == '\0')
1356 opt_notes_arg[7] = '\0';
1357 return res;
1360 if (!strcmp(argv[0], "show-line-numbers"))
1361 return parse_bool(&opt_line_number, argv[2]);
1363 if (!strcmp(argv[0], "line-graphics"))
1364 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1366 if (!strcmp(argv[0], "line-number-interval"))
1367 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1369 if (!strcmp(argv[0], "author-width"))
1370 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1372 if (!strcmp(argv[0], "filename-width"))
1373 return parse_int(&opt_filename_cols, argv[2], 0, 1024);
1375 if (!strcmp(argv[0], "show-filename"))
1376 return parse_enum(&opt_filename, argv[2], filename_map);
1378 if (!strcmp(argv[0], "horizontal-scroll"))
1379 return parse_step(&opt_hscroll, argv[2]);
1381 if (!strcmp(argv[0], "split-view-height"))
1382 return parse_step(&opt_scale_split_view, argv[2]);
1384 if (!strcmp(argv[0], "tab-size"))
1385 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1387 if (!strcmp(argv[0], "diff-context")) {
1388 enum option_code code = parse_int(&opt_diff_context, argv[2], 1, 999999);
1390 if (code == OPT_OK)
1391 update_diff_context_arg(opt_diff_context);
1392 return code;
1395 if (!strcmp(argv[0], "ignore-space")) {
1396 enum option_code code = parse_enum(&opt_ignore_space, argv[2], ignore_space_map);
1398 if (code == OPT_OK)
1399 update_ignore_space_arg();
1400 return code;
1403 if (!strcmp(argv[0], "status-untracked-dirs"))
1404 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1406 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1409 /* Wants: mode request key */
1410 static enum option_code
1411 option_bind_command(int argc, const char *argv[])
1413 enum request request;
1414 int keymap = -1;
1415 int key;
1417 if (argc < 3)
1418 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1420 if (!set_keymap(&keymap, argv[0]))
1421 return OPT_ERR_UNKNOWN_KEY_MAP;
1423 key = get_key_value(argv[1]);
1424 if (key == ERR)
1425 return OPT_ERR_UNKNOWN_KEY;
1427 request = get_request(argv[2]);
1428 if (request == REQ_UNKNOWN) {
1429 static const struct enum_map obsolete[] = {
1430 ENUM_MAP("cherry-pick", REQ_NONE),
1431 ENUM_MAP("screen-resize", REQ_NONE),
1432 ENUM_MAP("tree-parent", REQ_PARENT),
1434 int alias;
1436 if (map_enum(&alias, obsolete, argv[2])) {
1437 if (alias != REQ_NONE)
1438 add_keybinding(keymap, alias, key);
1439 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1442 if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1443 request = add_run_request(keymap, key, argv + 2);
1444 if (request == REQ_UNKNOWN)
1445 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1447 add_keybinding(keymap, request, key);
1449 return OPT_OK;
1453 static enum option_code load_option_file(const char *path);
1455 static enum option_code
1456 option_source_command(int argc, const char *argv[])
1458 if (argc < 1)
1459 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1461 return load_option_file(argv[0]);
1464 static enum option_code
1465 set_option(const char *opt, char *value)
1467 const char *argv[SIZEOF_ARG];
1468 int argc = 0;
1470 if (!argv_from_string(argv, &argc, value))
1471 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1473 if (!strcmp(opt, "color"))
1474 return option_color_command(argc, argv);
1476 if (!strcmp(opt, "set"))
1477 return option_set_command(argc, argv);
1479 if (!strcmp(opt, "bind"))
1480 return option_bind_command(argc, argv);
1482 if (!strcmp(opt, "source"))
1483 return option_source_command(argc, argv);
1485 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1488 struct config_state {
1489 const char *path;
1490 int lineno;
1491 bool errors;
1494 static int
1495 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1497 struct config_state *config = data;
1498 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1500 config->lineno++;
1502 /* Check for comment markers, since read_properties() will
1503 * only ensure opt and value are split at first " \t". */
1504 optlen = strcspn(opt, "#");
1505 if (optlen == 0)
1506 return OK;
1508 if (opt[optlen] == 0) {
1509 /* Look for comment endings in the value. */
1510 size_t len = strcspn(value, "#");
1512 if (len < valuelen) {
1513 valuelen = len;
1514 value[valuelen] = 0;
1517 status = set_option(opt, value);
1520 if (status != OPT_OK) {
1521 warn("%s line %d: %s near '%.*s'", config->path, config->lineno,
1522 option_errors[status], (int) optlen, opt);
1523 config->errors = TRUE;
1526 /* Always keep going if errors are encountered. */
1527 return OK;
1530 static enum option_code
1531 load_option_file(const char *path)
1533 struct config_state config = { path, 0, FALSE };
1534 struct io io;
1536 /* Do not read configuration from stdin if set to "" */
1537 if (!path || !strlen(path))
1538 return OPT_OK;
1540 /* It's OK that the file doesn't exist. */
1541 if (!io_open(&io, "%s", path))
1542 return OPT_ERR_FILE_DOES_NOT_EXIST;
1544 if (io_load(&io, " \t", read_option, &config) == ERR ||
1545 config.errors == TRUE)
1546 warn("Errors while loading %s.", path);
1547 return OPT_OK;
1550 static int
1551 load_options(void)
1553 const char *home = getenv("HOME");
1554 const char *tigrc_user = getenv("TIGRC_USER");
1555 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1556 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1557 char buf[SIZEOF_STR];
1559 if (!tigrc_system)
1560 tigrc_system = SYSCONFDIR "/tigrc";
1561 load_option_file(tigrc_system);
1563 if (!tigrc_user) {
1564 if (!home || !string_format(buf, "%s/.tigrc", home))
1565 return ERR;
1566 tigrc_user = buf;
1568 load_option_file(tigrc_user);
1570 /* Add _after_ loading config files to avoid adding run requests
1571 * that conflict with keybindings. */
1572 add_builtin_run_requests();
1574 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1575 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1576 int argc = 0;
1578 if (!string_format(buf, "%s", tig_diff_opts) ||
1579 !argv_from_string(diff_opts, &argc, buf))
1580 die("TIG_DIFF_OPTS contains too many arguments");
1581 else if (!argv_copy(&opt_diff_argv, diff_opts))
1582 die("Failed to format TIG_DIFF_OPTS arguments");
1585 return OK;
1590 * The viewer
1593 struct view;
1594 struct view_ops;
1596 /* The display array of active views and the index of the current view. */
1597 static struct view *display[2];
1598 static WINDOW *display_win[2];
1599 static WINDOW *display_title[2];
1600 static unsigned int current_view;
1602 #define foreach_displayed_view(view, i) \
1603 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1605 #define displayed_views() (display[1] != NULL ? 2 : 1)
1607 /* Current head and commit ID */
1608 static char ref_blob[SIZEOF_REF] = "";
1609 static char ref_commit[SIZEOF_REF] = "HEAD";
1610 static char ref_head[SIZEOF_REF] = "HEAD";
1611 static char ref_branch[SIZEOF_REF] = "";
1613 enum view_flag {
1614 VIEW_NO_FLAGS = 0,
1615 VIEW_ALWAYS_LINENO = 1 << 0,
1616 VIEW_CUSTOM_STATUS = 1 << 1,
1617 VIEW_ADD_DESCRIBE_REF = 1 << 2,
1618 VIEW_ADD_PAGER_REFS = 1 << 3,
1619 VIEW_OPEN_DIFF = 1 << 4,
1620 VIEW_NO_REF = 1 << 5,
1621 VIEW_NO_GIT_DIR = 1 << 6,
1622 VIEW_DIFF_LIKE = 1 << 7,
1625 #define view_has_flags(view, flag) ((view)->ops->flags & (flag))
1627 struct view {
1628 const char *name; /* View name */
1629 const char *id; /* Points to either of ref_{head,commit,blob} */
1631 struct view_ops *ops; /* View operations */
1633 enum keymap keymap; /* What keymap does this view have */
1635 char ref[SIZEOF_REF]; /* Hovered commit reference */
1636 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1638 int height, width; /* The width and height of the main window */
1639 WINDOW *win; /* The main window */
1641 /* Navigation */
1642 unsigned long offset; /* Offset of the window top */
1643 unsigned long yoffset; /* Offset from the window side. */
1644 unsigned long lineno; /* Current line number */
1645 unsigned long p_offset; /* Previous offset of the window top */
1646 unsigned long p_yoffset;/* Previous offset from the window side */
1647 unsigned long p_lineno; /* Previous current line number */
1648 bool p_restore; /* Should the previous position be restored. */
1650 /* Searching */
1651 char grep[SIZEOF_STR]; /* Search string */
1652 regex_t *regex; /* Pre-compiled regexp */
1654 /* If non-NULL, points to the view that opened this view. If this view
1655 * is closed tig will switch back to the parent view. */
1656 struct view *parent;
1657 struct view *prev;
1659 /* Buffering */
1660 size_t lines; /* Total number of lines */
1661 struct line *line; /* Line index */
1662 unsigned int digits; /* Number of digits in the lines member. */
1664 /* Drawing */
1665 struct line *curline; /* Line currently being drawn. */
1666 enum line_type curtype; /* Attribute currently used for drawing. */
1667 unsigned long col; /* Column when drawing. */
1668 bool has_scrolled; /* View was scrolled. */
1670 /* Loading */
1671 const char **argv; /* Shell command arguments. */
1672 const char *dir; /* Directory from which to execute. */
1673 struct io io;
1674 struct io *pipe;
1675 time_t start_time;
1676 time_t update_secs;
1677 struct encoding *encoding;
1679 /* Private data */
1680 void *private;
1683 enum open_flags {
1684 OPEN_DEFAULT = 0, /* Use default view switching. */
1685 OPEN_SPLIT = 1, /* Split current view. */
1686 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1687 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1688 OPEN_PREPARED = 32, /* Open already prepared command. */
1689 OPEN_EXTRA = 64, /* Open extra data from command. */
1692 struct view_ops {
1693 /* What type of content being displayed. Used in the title bar. */
1694 const char *type;
1695 /* Flags to control the view behavior. */
1696 enum view_flag flags;
1697 /* Size of private data. */
1698 size_t private_size;
1699 /* Open and reads in all view content. */
1700 bool (*open)(struct view *view, enum open_flags flags);
1701 /* Read one line; updates view->line. */
1702 bool (*read)(struct view *view, char *data);
1703 /* Draw one line; @lineno must be < view->height. */
1704 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1705 /* Depending on view handle a special requests. */
1706 enum request (*request)(struct view *view, enum request request, struct line *line);
1707 /* Search for regexp in a line. */
1708 bool (*grep)(struct view *view, struct line *line);
1709 /* Select line */
1710 void (*select)(struct view *view, struct line *line);
1713 #define VIEW_OPS(id, name, ref) name##_ops
1714 static struct view_ops VIEW_INFO(VIEW_OPS);
1716 static struct view views[] = {
1717 #define VIEW_DATA(id, name, ref) \
1718 { #name, ref, &name##_ops, KEYMAP_##id }
1719 VIEW_INFO(VIEW_DATA)
1722 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1724 #define foreach_view(view, i) \
1725 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1727 #define view_is_displayed(view) \
1728 (view == display[0] || view == display[1])
1730 static enum request
1731 view_request(struct view *view, enum request request)
1733 if (!view || !view->lines)
1734 return request;
1735 return view->ops->request(view, request, &view->line[view->lineno]);
1740 * View drawing.
1743 static inline void
1744 set_view_attr(struct view *view, enum line_type type)
1746 if (!view->curline->selected && view->curtype != type) {
1747 (void) wattrset(view->win, get_line_attr(type));
1748 wchgat(view->win, -1, 0, COLOR_ID(type), NULL);
1749 view->curtype = type;
1753 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1755 static bool
1756 draw_chars(struct view *view, enum line_type type, const char *string,
1757 int max_len, bool use_tilde)
1759 static char out_buffer[BUFSIZ * 2];
1760 int len = 0;
1761 int col = 0;
1762 int trimmed = FALSE;
1763 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1765 if (max_len <= 0)
1766 return VIEW_MAX_LEN(view) <= 0;
1768 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1770 set_view_attr(view, type);
1771 if (len > 0) {
1772 if (opt_iconv_out != ICONV_NONE) {
1773 size_t inlen = len + 1;
1774 char *instr = calloc(1, inlen);
1775 ICONV_CONST char *inbuf = (ICONV_CONST char *) instr;
1776 if (!instr)
1777 return VIEW_MAX_LEN(view) <= 0;
1779 strncpy(instr, string, len);
1781 char *outbuf = out_buffer;
1782 size_t outlen = sizeof(out_buffer);
1784 size_t ret;
1786 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1787 if (ret != (size_t) -1) {
1788 string = out_buffer;
1789 len = sizeof(out_buffer) - outlen;
1791 free(instr);
1794 waddnstr(view->win, string, len);
1796 if (trimmed && use_tilde) {
1797 set_view_attr(view, LINE_DELIMITER);
1798 waddch(view->win, '~');
1799 col++;
1803 view->col += col;
1804 return VIEW_MAX_LEN(view) <= 0;
1807 static bool
1808 draw_space(struct view *view, enum line_type type, int max, int spaces)
1810 static char space[] = " ";
1812 spaces = MIN(max, spaces);
1814 while (spaces > 0) {
1815 int len = MIN(spaces, sizeof(space) - 1);
1817 if (draw_chars(view, type, space, len, FALSE))
1818 return TRUE;
1819 spaces -= len;
1822 return VIEW_MAX_LEN(view) <= 0;
1825 static bool
1826 draw_text(struct view *view, enum line_type type, const char *string)
1828 char text[SIZEOF_STR];
1830 do {
1831 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1833 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1834 return TRUE;
1835 string += pos;
1836 } while (*string);
1838 return VIEW_MAX_LEN(view) <= 0;
1841 static bool
1842 draw_formatted(struct view *view, enum line_type type, const char *format, ...)
1844 char text[SIZEOF_STR];
1845 int retval;
1847 FORMAT_BUFFER(text, sizeof(text), format, retval, TRUE);
1848 return retval >= 0 ? draw_text(view, type, text) : VIEW_MAX_LEN(view) <= 0;
1851 static bool
1852 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1854 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1855 int max = VIEW_MAX_LEN(view);
1856 int i;
1858 if (max < size)
1859 size = max;
1861 set_view_attr(view, type);
1862 /* Using waddch() instead of waddnstr() ensures that
1863 * they'll be rendered correctly for the cursor line. */
1864 for (i = skip; i < size; i++)
1865 waddch(view->win, graphic[i]);
1867 view->col += size;
1868 if (separator) {
1869 if (size < max && skip <= size)
1870 waddch(view->win, ' ');
1871 view->col++;
1874 return VIEW_MAX_LEN(view) <= 0;
1877 static bool
1878 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1880 int max = MIN(VIEW_MAX_LEN(view), len);
1881 int col = view->col;
1883 if (!text)
1884 return draw_space(view, type, max, max);
1886 return draw_chars(view, type, text, max - 1, trim)
1887 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1890 static bool
1891 draw_date(struct view *view, struct time *time)
1893 const char *date = mkdate(time, opt_date);
1894 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1896 if (opt_date == DATE_NO)
1897 return FALSE;
1899 return draw_field(view, LINE_DATE, date, cols, FALSE);
1902 static bool
1903 draw_author(struct view *view, const char *author)
1905 bool trim = author_trim(opt_author_cols);
1906 const char *text = mkauthor(author, opt_author_cols, opt_author);
1908 if (opt_author == AUTHOR_NO)
1909 return FALSE;
1911 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1914 static bool
1915 draw_filename(struct view *view, const char *filename, bool auto_enabled)
1917 bool trim = filename && strlen(filename) >= opt_filename_cols;
1919 if (opt_filename == FILENAME_NO)
1920 return FALSE;
1922 if (opt_filename == FILENAME_AUTO && !auto_enabled)
1923 return FALSE;
1925 return draw_field(view, LINE_FILENAME, filename, opt_filename_cols, trim);
1928 static bool
1929 draw_mode(struct view *view, mode_t mode)
1931 const char *str = mkmode(mode);
1933 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1936 static bool
1937 draw_lineno(struct view *view, unsigned int lineno)
1939 char number[10];
1940 int digits3 = view->digits < 3 ? 3 : view->digits;
1941 int max = MIN(VIEW_MAX_LEN(view), digits3);
1942 char *text = NULL;
1943 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1945 if (!opt_line_number)
1946 return FALSE;
1948 lineno += view->offset + 1;
1949 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1950 static char fmt[] = "%1ld";
1952 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1953 if (string_format(number, fmt, lineno))
1954 text = number;
1956 if (text)
1957 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1958 else
1959 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1960 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1963 static bool
1964 draw_refs(struct view *view, struct ref_list *refs)
1966 size_t i;
1968 if (!opt_show_refs || !refs)
1969 return FALSE;
1971 for (i = 0; i < refs->size; i++) {
1972 struct ref *ref = refs->refs[i];
1973 enum line_type type = get_line_type_from_ref(ref);
1975 if (draw_formatted(view, type, "[%s]", ref->name))
1976 return TRUE;
1978 if (draw_text(view, LINE_DEFAULT, " "))
1979 return TRUE;
1982 return FALSE;
1985 static bool
1986 draw_view_line(struct view *view, unsigned int lineno)
1988 struct line *line;
1989 bool selected = (view->offset + lineno == view->lineno);
1991 assert(view_is_displayed(view));
1993 if (view->offset + lineno >= view->lines)
1994 return FALSE;
1996 line = &view->line[view->offset + lineno];
1998 wmove(view->win, lineno, 0);
1999 if (line->cleareol)
2000 wclrtoeol(view->win);
2001 view->col = 0;
2002 view->curline = line;
2003 view->curtype = LINE_NONE;
2004 line->selected = FALSE;
2005 line->dirty = line->cleareol = 0;
2007 if (selected) {
2008 set_view_attr(view, LINE_CURSOR);
2009 line->selected = TRUE;
2010 view->ops->select(view, line);
2013 return view->ops->draw(view, line, lineno);
2016 static void
2017 redraw_view_dirty(struct view *view)
2019 bool dirty = FALSE;
2020 int lineno;
2022 for (lineno = 0; lineno < view->height; lineno++) {
2023 if (view->offset + lineno >= view->lines)
2024 break;
2025 if (!view->line[view->offset + lineno].dirty)
2026 continue;
2027 dirty = TRUE;
2028 if (!draw_view_line(view, lineno))
2029 break;
2032 if (!dirty)
2033 return;
2034 wnoutrefresh(view->win);
2037 static void
2038 redraw_view_from(struct view *view, int lineno)
2040 assert(0 <= lineno && lineno < view->height);
2042 for (; lineno < view->height; lineno++) {
2043 if (!draw_view_line(view, lineno))
2044 break;
2047 wnoutrefresh(view->win);
2050 static void
2051 redraw_view(struct view *view)
2053 werase(view->win);
2054 redraw_view_from(view, 0);
2058 static void
2059 update_view_title(struct view *view)
2061 char buf[SIZEOF_STR];
2062 char state[SIZEOF_STR];
2063 size_t bufpos = 0, statelen = 0;
2064 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
2066 assert(view_is_displayed(view));
2068 if (!view_has_flags(view, VIEW_CUSTOM_STATUS) && view->lines) {
2069 unsigned int view_lines = view->offset + view->height;
2070 unsigned int lines = view->lines
2071 ? MIN(view_lines, view->lines) * 100 / view->lines
2072 : 0;
2074 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
2075 view->ops->type,
2076 view->lineno + 1,
2077 view->lines,
2078 lines);
2082 if (view->pipe) {
2083 time_t secs = time(NULL) - view->start_time;
2085 /* Three git seconds are a long time ... */
2086 if (secs > 2)
2087 string_format_from(state, &statelen, " loading %lds", secs);
2090 string_format_from(buf, &bufpos, "[%s]", view->name);
2091 if (*view->ref && bufpos < view->width) {
2092 size_t refsize = strlen(view->ref);
2093 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
2095 if (minsize < view->width)
2096 refsize = view->width - minsize + 7;
2097 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
2100 if (statelen && bufpos < view->width) {
2101 string_format_from(buf, &bufpos, "%s", state);
2104 if (view == display[current_view])
2105 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
2106 else
2107 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
2109 mvwaddnstr(window, 0, 0, buf, bufpos);
2110 wclrtoeol(window);
2111 wnoutrefresh(window);
2114 static int
2115 apply_step(double step, int value)
2117 if (step >= 1)
2118 return (int) step;
2119 value *= step + 0.01;
2120 return value ? value : 1;
2123 static void
2124 resize_display(void)
2126 int offset, i;
2127 struct view *base = display[0];
2128 struct view *view = display[1] ? display[1] : display[0];
2130 /* Setup window dimensions */
2132 getmaxyx(stdscr, base->height, base->width);
2134 /* Make room for the status window. */
2135 base->height -= 1;
2137 if (view != base) {
2138 /* Horizontal split. */
2139 view->width = base->width;
2140 view->height = apply_step(opt_scale_split_view, base->height);
2141 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
2142 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
2143 base->height -= view->height;
2145 /* Make room for the title bar. */
2146 view->height -= 1;
2149 /* Make room for the title bar. */
2150 base->height -= 1;
2152 offset = 0;
2154 foreach_displayed_view (view, i) {
2155 if (!display_win[i]) {
2156 display_win[i] = newwin(view->height, view->width, offset, 0);
2157 if (!display_win[i])
2158 die("Failed to create %s view", view->name);
2160 scrollok(display_win[i], FALSE);
2162 display_title[i] = newwin(1, view->width, offset + view->height, 0);
2163 if (!display_title[i])
2164 die("Failed to create title window");
2166 } else {
2167 wresize(display_win[i], view->height, view->width);
2168 mvwin(display_win[i], offset, 0);
2169 mvwin(display_title[i], offset + view->height, 0);
2172 view->win = display_win[i];
2174 offset += view->height + 1;
2178 static void
2179 redraw_display(bool clear)
2181 struct view *view;
2182 int i;
2184 foreach_displayed_view (view, i) {
2185 if (clear)
2186 wclear(view->win);
2187 redraw_view(view);
2188 update_view_title(view);
2194 * Option management
2197 #define TOGGLE_MENU \
2198 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
2199 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
2200 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
2201 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
2202 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
2203 TOGGLE_(FILENAME, '#', "file names", &opt_filename, filename_map) \
2204 TOGGLE_(IGNORE_SPACE, 'W', "space changes", &opt_ignore_space, ignore_space_map) \
2205 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL)
2207 static bool
2208 toggle_option(enum request request)
2210 const struct {
2211 enum request request;
2212 const struct enum_map *map;
2213 size_t map_size;
2214 } data[] = {
2215 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
2216 TOGGLE_MENU
2217 #undef TOGGLE_
2219 const struct menu_item menu[] = {
2220 #define TOGGLE_(id, key, help, value, map) { key, help, value },
2221 TOGGLE_MENU
2222 #undef TOGGLE_
2223 { 0 }
2225 int i = 0;
2227 if (request == REQ_OPTIONS) {
2228 if (!prompt_menu("Toggle option", menu, &i))
2229 return FALSE;
2230 } else {
2231 while (i < ARRAY_SIZE(data) && data[i].request != request)
2232 i++;
2233 if (i >= ARRAY_SIZE(data))
2234 die("Invalid request (%d)", request);
2237 if (data[i].map != NULL) {
2238 unsigned int *opt = menu[i].data;
2240 *opt = (*opt + 1) % data[i].map_size;
2241 if (data[i].map == ignore_space_map) {
2242 update_ignore_space_arg();
2243 report("Ignoring %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2244 return TRUE;
2247 redraw_display(FALSE);
2248 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2250 } else {
2251 bool *option = menu[i].data;
2253 *option = !*option;
2254 redraw_display(FALSE);
2255 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2258 return FALSE;
2261 static void
2262 maximize_view(struct view *view, bool redraw)
2264 memset(display, 0, sizeof(display));
2265 current_view = 0;
2266 display[current_view] = view;
2267 resize_display();
2268 if (redraw) {
2269 redraw_display(FALSE);
2270 report("");
2276 * Navigation
2279 static bool
2280 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2282 if (lineno >= view->lines)
2283 lineno = view->lines > 0 ? view->lines - 1 : 0;
2285 if (offset > lineno || offset + view->height <= lineno) {
2286 unsigned long half = view->height / 2;
2288 if (lineno > half)
2289 offset = lineno - half;
2290 else
2291 offset = 0;
2294 if (offset != view->offset || lineno != view->lineno) {
2295 view->offset = offset;
2296 view->lineno = lineno;
2297 return TRUE;
2300 return FALSE;
2303 /* Scrolling backend */
2304 static void
2305 do_scroll_view(struct view *view, int lines)
2307 bool redraw_current_line = FALSE;
2309 /* The rendering expects the new offset. */
2310 view->offset += lines;
2312 assert(0 <= view->offset && view->offset < view->lines);
2313 assert(lines);
2315 /* Move current line into the view. */
2316 if (view->lineno < view->offset) {
2317 view->lineno = view->offset;
2318 redraw_current_line = TRUE;
2319 } else if (view->lineno >= view->offset + view->height) {
2320 view->lineno = view->offset + view->height - 1;
2321 redraw_current_line = TRUE;
2324 assert(view->offset <= view->lineno && view->lineno < view->lines);
2326 /* Redraw the whole screen if scrolling is pointless. */
2327 if (view->height < ABS(lines)) {
2328 redraw_view(view);
2330 } else {
2331 int line = lines > 0 ? view->height - lines : 0;
2332 int end = line + ABS(lines);
2334 scrollok(view->win, TRUE);
2335 wscrl(view->win, lines);
2336 scrollok(view->win, FALSE);
2338 while (line < end && draw_view_line(view, line))
2339 line++;
2341 if (redraw_current_line)
2342 draw_view_line(view, view->lineno - view->offset);
2343 wnoutrefresh(view->win);
2346 view->has_scrolled = TRUE;
2347 report("");
2350 /* Scroll frontend */
2351 static void
2352 scroll_view(struct view *view, enum request request)
2354 int lines = 1;
2356 assert(view_is_displayed(view));
2358 switch (request) {
2359 case REQ_SCROLL_FIRST_COL:
2360 view->yoffset = 0;
2361 redraw_view_from(view, 0);
2362 report("");
2363 return;
2364 case REQ_SCROLL_LEFT:
2365 if (view->yoffset == 0) {
2366 report("Cannot scroll beyond the first column");
2367 return;
2369 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2370 view->yoffset = 0;
2371 else
2372 view->yoffset -= apply_step(opt_hscroll, view->width);
2373 redraw_view_from(view, 0);
2374 report("");
2375 return;
2376 case REQ_SCROLL_RIGHT:
2377 view->yoffset += apply_step(opt_hscroll, view->width);
2378 redraw_view(view);
2379 report("");
2380 return;
2381 case REQ_SCROLL_PAGE_DOWN:
2382 lines = view->height;
2383 case REQ_SCROLL_LINE_DOWN:
2384 if (view->offset + lines > view->lines)
2385 lines = view->lines - view->offset;
2387 if (lines == 0 || view->offset + view->height >= view->lines) {
2388 report("Cannot scroll beyond the last line");
2389 return;
2391 break;
2393 case REQ_SCROLL_PAGE_UP:
2394 lines = view->height;
2395 case REQ_SCROLL_LINE_UP:
2396 if (lines > view->offset)
2397 lines = view->offset;
2399 if (lines == 0) {
2400 report("Cannot scroll beyond the first line");
2401 return;
2404 lines = -lines;
2405 break;
2407 default:
2408 die("request %d not handled in switch", request);
2411 do_scroll_view(view, lines);
2414 /* Cursor moving */
2415 static void
2416 move_view(struct view *view, enum request request)
2418 int scroll_steps = 0;
2419 int steps;
2421 switch (request) {
2422 case REQ_MOVE_FIRST_LINE:
2423 steps = -view->lineno;
2424 break;
2426 case REQ_MOVE_LAST_LINE:
2427 steps = view->lines - view->lineno - 1;
2428 break;
2430 case REQ_MOVE_PAGE_UP:
2431 steps = view->height > view->lineno
2432 ? -view->lineno : -view->height;
2433 break;
2435 case REQ_MOVE_PAGE_DOWN:
2436 steps = view->lineno + view->height >= view->lines
2437 ? view->lines - view->lineno - 1 : view->height;
2438 break;
2440 case REQ_MOVE_UP:
2441 steps = -1;
2442 break;
2444 case REQ_MOVE_DOWN:
2445 steps = 1;
2446 break;
2448 default:
2449 die("request %d not handled in switch", request);
2452 if (steps <= 0 && view->lineno == 0) {
2453 report("Cannot move beyond the first line");
2454 return;
2456 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2457 report("Cannot move beyond the last line");
2458 return;
2461 /* Move the current line */
2462 view->lineno += steps;
2463 assert(0 <= view->lineno && view->lineno < view->lines);
2465 /* Check whether the view needs to be scrolled */
2466 if (view->lineno < view->offset ||
2467 view->lineno >= view->offset + view->height) {
2468 scroll_steps = steps;
2469 if (steps < 0 && -steps > view->offset) {
2470 scroll_steps = -view->offset;
2472 } else if (steps > 0) {
2473 if (view->lineno == view->lines - 1 &&
2474 view->lines > view->height) {
2475 scroll_steps = view->lines - view->offset - 1;
2476 if (scroll_steps >= view->height)
2477 scroll_steps -= view->height - 1;
2482 if (!view_is_displayed(view)) {
2483 view->offset += scroll_steps;
2484 assert(0 <= view->offset && view->offset < view->lines);
2485 view->ops->select(view, &view->line[view->lineno]);
2486 return;
2489 /* Repaint the old "current" line if we be scrolling */
2490 if (ABS(steps) < view->height)
2491 draw_view_line(view, view->lineno - steps - view->offset);
2493 if (scroll_steps) {
2494 do_scroll_view(view, scroll_steps);
2495 return;
2498 /* Draw the current line */
2499 draw_view_line(view, view->lineno - view->offset);
2501 wnoutrefresh(view->win);
2502 report("");
2507 * Searching
2510 static void search_view(struct view *view, enum request request);
2512 static bool
2513 grep_text(struct view *view, const char *text[])
2515 regmatch_t pmatch;
2516 size_t i;
2518 for (i = 0; text[i]; i++)
2519 if (*text[i] &&
2520 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2521 return TRUE;
2522 return FALSE;
2525 static void
2526 select_view_line(struct view *view, unsigned long lineno)
2528 unsigned long old_lineno = view->lineno;
2529 unsigned long old_offset = view->offset;
2531 if (goto_view_line(view, view->offset, lineno)) {
2532 if (view_is_displayed(view)) {
2533 if (old_offset != view->offset) {
2534 redraw_view(view);
2535 } else {
2536 draw_view_line(view, old_lineno - view->offset);
2537 draw_view_line(view, view->lineno - view->offset);
2538 wnoutrefresh(view->win);
2540 } else {
2541 view->ops->select(view, &view->line[view->lineno]);
2546 static void
2547 find_next(struct view *view, enum request request)
2549 unsigned long lineno = view->lineno;
2550 int direction;
2552 if (!*view->grep) {
2553 if (!*opt_search)
2554 report("No previous search");
2555 else
2556 search_view(view, request);
2557 return;
2560 switch (request) {
2561 case REQ_SEARCH:
2562 case REQ_FIND_NEXT:
2563 direction = 1;
2564 break;
2566 case REQ_SEARCH_BACK:
2567 case REQ_FIND_PREV:
2568 direction = -1;
2569 break;
2571 default:
2572 return;
2575 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2576 lineno += direction;
2578 /* Note, lineno is unsigned long so will wrap around in which case it
2579 * will become bigger than view->lines. */
2580 for (; lineno < view->lines; lineno += direction) {
2581 if (view->ops->grep(view, &view->line[lineno])) {
2582 select_view_line(view, lineno);
2583 report("Line %ld matches '%s'", lineno + 1, view->grep);
2584 return;
2588 report("No match found for '%s'", view->grep);
2591 static void
2592 search_view(struct view *view, enum request request)
2594 int regex_err;
2596 if (view->regex) {
2597 regfree(view->regex);
2598 *view->grep = 0;
2599 } else {
2600 view->regex = calloc(1, sizeof(*view->regex));
2601 if (!view->regex)
2602 return;
2605 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2606 if (regex_err != 0) {
2607 char buf[SIZEOF_STR] = "unknown error";
2609 regerror(regex_err, view->regex, buf, sizeof(buf));
2610 report("Search failed: %s", buf);
2611 return;
2614 string_copy(view->grep, opt_search);
2616 find_next(view, request);
2620 * Incremental updating
2623 static void
2624 reset_view(struct view *view)
2626 int i;
2628 for (i = 0; i < view->lines; i++)
2629 free(view->line[i].data);
2630 free(view->line);
2632 view->p_offset = view->offset;
2633 view->p_yoffset = view->yoffset;
2634 view->p_lineno = view->lineno;
2636 view->line = NULL;
2637 view->offset = 0;
2638 view->yoffset = 0;
2639 view->lines = 0;
2640 view->lineno = 0;
2641 view->vid[0] = 0;
2642 view->update_secs = 0;
2645 static const char *
2646 format_arg(const char *name)
2648 static struct {
2649 const char *name;
2650 size_t namelen;
2651 const char *value;
2652 const char *value_if_empty;
2653 } vars[] = {
2654 #define FORMAT_VAR(name, value, value_if_empty) \
2655 { name, STRING_SIZE(name), value, value_if_empty }
2656 FORMAT_VAR("%(directory)", opt_path, "."),
2657 FORMAT_VAR("%(file)", opt_file, ""),
2658 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2659 FORMAT_VAR("%(head)", ref_head, ""),
2660 FORMAT_VAR("%(commit)", ref_commit, ""),
2661 FORMAT_VAR("%(blob)", ref_blob, ""),
2662 FORMAT_VAR("%(branch)", ref_branch, ""),
2664 int i;
2666 for (i = 0; i < ARRAY_SIZE(vars); i++)
2667 if (!strncmp(name, vars[i].name, vars[i].namelen))
2668 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2670 report("Unknown replacement: `%s`", name);
2671 return NULL;
2674 static bool
2675 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2677 char buf[SIZEOF_STR];
2678 int argc;
2680 argv_free(*dst_argv);
2682 for (argc = 0; src_argv[argc]; argc++) {
2683 const char *arg = src_argv[argc];
2684 size_t bufpos = 0;
2686 if (!strcmp(arg, "%(fileargs)")) {
2687 if (!argv_append_array(dst_argv, opt_file_argv))
2688 break;
2689 continue;
2691 } else if (!strcmp(arg, "%(diffargs)")) {
2692 if (!argv_append_array(dst_argv, opt_diff_argv))
2693 break;
2694 continue;
2696 } else if (!strcmp(arg, "%(blameargs)")) {
2697 if (!argv_append_array(dst_argv, opt_blame_argv))
2698 break;
2699 continue;
2701 } else if (!strcmp(arg, "%(revargs)") ||
2702 (first && !strcmp(arg, "%(commit)"))) {
2703 if (!argv_append_array(dst_argv, opt_rev_argv))
2704 break;
2705 continue;
2708 while (arg) {
2709 char *next = strstr(arg, "%(");
2710 int len = next - arg;
2711 const char *value;
2713 if (!next) {
2714 len = strlen(arg);
2715 value = "";
2717 } else {
2718 value = format_arg(next);
2720 if (!value) {
2721 return FALSE;
2725 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2726 return FALSE;
2728 arg = next ? strchr(next, ')') + 1 : NULL;
2731 if (!argv_append(dst_argv, buf))
2732 break;
2735 return src_argv[argc] == NULL;
2738 static bool
2739 restore_view_position(struct view *view)
2741 /* A view without a previous view is the first view */
2742 if (!view->prev && opt_lineno && opt_lineno <= view->lines) {
2743 select_view_line(view, opt_lineno - 1);
2744 opt_lineno = 0;
2747 if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2748 return FALSE;
2750 /* Changing the view position cancels the restoring. */
2751 /* FIXME: Changing back to the first line is not detected. */
2752 if (view->offset != 0 || view->lineno != 0) {
2753 view->p_restore = FALSE;
2754 return FALSE;
2757 if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2758 view_is_displayed(view))
2759 werase(view->win);
2761 view->yoffset = view->p_yoffset;
2762 view->p_restore = FALSE;
2764 return TRUE;
2767 static void
2768 end_update(struct view *view, bool force)
2770 if (!view->pipe)
2771 return;
2772 while (!view->ops->read(view, NULL))
2773 if (!force)
2774 return;
2775 if (force)
2776 io_kill(view->pipe);
2777 io_done(view->pipe);
2778 view->pipe = NULL;
2781 static void
2782 setup_update(struct view *view, const char *vid)
2784 reset_view(view);
2785 string_copy_rev(view->vid, vid);
2786 view->pipe = &view->io;
2787 view->start_time = time(NULL);
2790 static bool
2791 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2793 bool extra = !!(flags & (OPEN_EXTRA));
2794 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2795 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2797 if (!reload && !strcmp(view->vid, view->id))
2798 return TRUE;
2800 if (view->pipe) {
2801 if (extra)
2802 io_done(view->pipe);
2803 else
2804 end_update(view, TRUE);
2807 if (!refresh && argv) {
2808 view->dir = dir;
2809 if (!format_argv(&view->argv, argv, !view->prev))
2810 return FALSE;
2812 /* Put the current ref_* value to the view title ref
2813 * member. This is needed by the blob view. Most other
2814 * views sets it automatically after loading because the
2815 * first line is a commit line. */
2816 string_copy_rev(view->ref, view->id);
2819 if (view->argv && view->argv[0] &&
2820 !io_run(&view->io, IO_RD, view->dir, view->argv))
2821 return FALSE;
2823 if (!extra)
2824 setup_update(view, view->id);
2826 return TRUE;
2829 static bool
2830 update_view(struct view *view)
2832 char *line;
2833 /* Clear the view and redraw everything since the tree sorting
2834 * might have rearranged things. */
2835 bool redraw = view->lines == 0;
2836 bool can_read = TRUE;
2838 if (!view->pipe)
2839 return TRUE;
2841 if (!io_can_read(view->pipe, FALSE)) {
2842 if (view->lines == 0 && view_is_displayed(view)) {
2843 time_t secs = time(NULL) - view->start_time;
2845 if (secs > 1 && secs > view->update_secs) {
2846 if (view->update_secs == 0)
2847 redraw_view(view);
2848 update_view_title(view);
2849 view->update_secs = secs;
2852 return TRUE;
2855 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2856 if (view->encoding) {
2857 line = encoding_convert(view->encoding, line);
2860 if (!view->ops->read(view, line)) {
2861 report("Allocation failure");
2862 end_update(view, TRUE);
2863 return FALSE;
2868 unsigned long lines = view->lines;
2869 int digits;
2871 for (digits = 0; lines; digits++)
2872 lines /= 10;
2874 /* Keep the displayed view in sync with line number scaling. */
2875 if (digits != view->digits) {
2876 view->digits = digits;
2877 if (opt_line_number || view_has_flags(view, VIEW_ALWAYS_LINENO))
2878 redraw = TRUE;
2882 if (io_error(view->pipe)) {
2883 report("Failed to read: %s", io_strerror(view->pipe));
2884 end_update(view, TRUE);
2886 } else if (io_eof(view->pipe)) {
2887 if (view_is_displayed(view))
2888 report("");
2889 end_update(view, FALSE);
2892 if (restore_view_position(view))
2893 redraw = TRUE;
2895 if (!view_is_displayed(view))
2896 return TRUE;
2898 if (redraw)
2899 redraw_view_from(view, 0);
2900 else
2901 redraw_view_dirty(view);
2903 /* Update the title _after_ the redraw so that if the redraw picks up a
2904 * commit reference in view->ref it'll be available here. */
2905 update_view_title(view);
2906 return TRUE;
2909 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2911 static struct line *
2912 add_line_data(struct view *view, void *data, enum line_type type)
2914 struct line *line;
2916 if (!realloc_lines(&view->line, view->lines, 1))
2917 return NULL;
2919 line = &view->line[view->lines++];
2920 memset(line, 0, sizeof(*line));
2921 line->type = type;
2922 line->data = data;
2923 line->dirty = 1;
2925 return line;
2928 static struct line *
2929 add_line_text(struct view *view, const char *text, enum line_type type)
2931 char *data = text ? strdup(text) : NULL;
2933 return data ? add_line_data(view, data, type) : NULL;
2936 static struct line *
2937 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2939 char buf[SIZEOF_STR];
2940 int retval;
2942 FORMAT_BUFFER(buf, sizeof(buf), fmt, retval, FALSE);
2943 return retval >= 0 ? add_line_text(view, buf, type) : NULL;
2947 * View opening
2950 static void
2951 load_view(struct view *view, enum open_flags flags)
2953 if (view->pipe)
2954 end_update(view, TRUE);
2955 if (view->ops->private_size) {
2956 if (!view->private)
2957 view->private = calloc(1, view->ops->private_size);
2958 else
2959 memset(view->private, 0, view->ops->private_size);
2961 if (!view->ops->open(view, flags)) {
2962 report("Failed to load %s view", view->name);
2963 return;
2965 restore_view_position(view);
2967 if (view->pipe && view->lines == 0) {
2968 /* Clear the old view and let the incremental updating refill
2969 * the screen. */
2970 werase(view->win);
2971 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2972 report("");
2973 } else if (view_is_displayed(view)) {
2974 redraw_view(view);
2975 report("");
2979 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2980 #define reload_view(view) load_view(view, OPEN_RELOAD)
2982 static void
2983 split_view(struct view *prev, struct view *view)
2985 display[1] = view;
2986 current_view = 1;
2987 view->parent = prev;
2988 resize_display();
2990 if (prev->lineno - prev->offset >= prev->height) {
2991 /* Take the title line into account. */
2992 int lines = prev->lineno - prev->offset - prev->height + 1;
2994 /* Scroll the view that was split if the current line is
2995 * outside the new limited view. */
2996 do_scroll_view(prev, lines);
2999 if (view != prev && view_is_displayed(prev)) {
3000 /* "Blur" the previous view. */
3001 update_view_title(prev);
3005 static void
3006 open_view(struct view *prev, enum request request, enum open_flags flags)
3008 bool split = !!(flags & OPEN_SPLIT);
3009 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
3010 struct view *view = VIEW(request);
3011 int nviews = displayed_views();
3013 assert(flags ^ OPEN_REFRESH);
3015 if (view == prev && nviews == 1 && !reload) {
3016 report("Already in %s view", view->name);
3017 return;
3020 if (!view_has_flags(view, VIEW_NO_GIT_DIR) && !opt_git_dir[0]) {
3021 report("The %s view is disabled in pager view", view->name);
3022 return;
3025 if (split) {
3026 split_view(prev, view);
3027 } else {
3028 maximize_view(view, FALSE);
3031 /* No prev signals that this is the first loaded view. */
3032 if (prev && view != prev) {
3033 view->prev = prev;
3036 load_view(view, flags);
3039 static void
3040 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
3042 enum request request = view - views + REQ_OFFSET + 1;
3044 if (view->pipe)
3045 end_update(view, TRUE);
3046 view->dir = dir;
3048 if (!argv_copy(&view->argv, argv)) {
3049 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
3050 } else {
3051 open_view(prev, request, flags | OPEN_PREPARED);
3055 static void
3056 open_external_viewer(const char *argv[], const char *dir)
3058 def_prog_mode(); /* save current tty modes */
3059 endwin(); /* restore original tty modes */
3060 io_run_fg(argv, dir);
3061 fprintf(stderr, "Press Enter to continue");
3062 getc(opt_tty);
3063 reset_prog_mode();
3064 redraw_display(TRUE);
3067 static void
3068 open_mergetool(const char *file)
3070 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
3072 open_external_viewer(mergetool_argv, opt_cdup);
3075 static void
3076 open_editor(const char *file)
3078 const char *editor_argv[SIZEOF_ARG + 1] = { "vi", file, NULL };
3079 char editor_cmd[SIZEOF_STR];
3080 const char *editor;
3081 int argc = 0;
3083 editor = getenv("GIT_EDITOR");
3084 if (!editor && *opt_editor)
3085 editor = opt_editor;
3086 if (!editor)
3087 editor = getenv("VISUAL");
3088 if (!editor)
3089 editor = getenv("EDITOR");
3090 if (!editor)
3091 editor = "vi";
3093 string_ncopy(editor_cmd, editor, strlen(editor));
3094 if (!argv_from_string_no_quotes(editor_argv, &argc, editor_cmd)) {
3095 report("Failed to read editor command");
3096 return;
3099 editor_argv[argc] = file;
3100 open_external_viewer(editor_argv, opt_cdup);
3103 static void
3104 open_run_request(enum request request)
3106 struct run_request *req = get_run_request(request);
3107 const char **argv = NULL;
3109 if (!req) {
3110 report("Unknown run request");
3111 return;
3114 if (format_argv(&argv, req->argv, FALSE))
3115 open_external_viewer(argv, NULL);
3116 if (argv)
3117 argv_free(argv);
3118 free(argv);
3122 * User request switch noodle
3125 static int
3126 view_driver(struct view *view, enum request request)
3128 int i;
3130 if (request == REQ_NONE)
3131 return TRUE;
3133 if (request > REQ_NONE) {
3134 open_run_request(request);
3135 view_request(view, REQ_REFRESH);
3136 return TRUE;
3139 request = view_request(view, request);
3140 if (request == REQ_NONE)
3141 return TRUE;
3143 switch (request) {
3144 case REQ_MOVE_UP:
3145 case REQ_MOVE_DOWN:
3146 case REQ_MOVE_PAGE_UP:
3147 case REQ_MOVE_PAGE_DOWN:
3148 case REQ_MOVE_FIRST_LINE:
3149 case REQ_MOVE_LAST_LINE:
3150 move_view(view, request);
3151 break;
3153 case REQ_SCROLL_FIRST_COL:
3154 case REQ_SCROLL_LEFT:
3155 case REQ_SCROLL_RIGHT:
3156 case REQ_SCROLL_LINE_DOWN:
3157 case REQ_SCROLL_LINE_UP:
3158 case REQ_SCROLL_PAGE_DOWN:
3159 case REQ_SCROLL_PAGE_UP:
3160 scroll_view(view, request);
3161 break;
3163 case REQ_VIEW_BLAME:
3164 if (!opt_file[0]) {
3165 report("No file chosen, press %s to open tree view",
3166 get_view_key(view, REQ_VIEW_TREE));
3167 break;
3169 open_view(view, request, OPEN_DEFAULT);
3170 break;
3172 case REQ_VIEW_BLOB:
3173 if (!ref_blob[0]) {
3174 report("No file chosen, press %s to open tree view",
3175 get_view_key(view, REQ_VIEW_TREE));
3176 break;
3178 open_view(view, request, OPEN_DEFAULT);
3179 break;
3181 case REQ_VIEW_PAGER:
3182 if (view == NULL) {
3183 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
3184 die("Failed to open stdin");
3185 open_view(view, request, OPEN_PREPARED);
3186 break;
3189 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
3190 report("No pager content, press %s to run command from prompt",
3191 get_view_key(view, REQ_PROMPT));
3192 break;
3194 open_view(view, request, OPEN_DEFAULT);
3195 break;
3197 case REQ_VIEW_STAGE:
3198 if (!VIEW(REQ_VIEW_STAGE)->lines) {
3199 report("No stage content, press %s to open the status view and choose file",
3200 get_view_key(view, REQ_VIEW_STATUS));
3201 break;
3203 open_view(view, request, OPEN_DEFAULT);
3204 break;
3206 case REQ_VIEW_STATUS:
3207 if (opt_is_inside_work_tree == FALSE) {
3208 report("The status view requires a working tree");
3209 break;
3211 open_view(view, request, OPEN_DEFAULT);
3212 break;
3214 case REQ_VIEW_MAIN:
3215 case REQ_VIEW_DIFF:
3216 case REQ_VIEW_LOG:
3217 case REQ_VIEW_TREE:
3218 case REQ_VIEW_HELP:
3219 case REQ_VIEW_BRANCH:
3220 open_view(view, request, OPEN_DEFAULT);
3221 break;
3223 case REQ_NEXT:
3224 case REQ_PREVIOUS:
3225 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
3227 if (view->parent) {
3228 int line;
3230 view = view->parent;
3231 line = view->lineno;
3232 move_view(view, request);
3233 if (view_is_displayed(view))
3234 update_view_title(view);
3235 if (line != view->lineno)
3236 view_request(view, REQ_ENTER);
3237 } else {
3238 move_view(view, request);
3240 break;
3242 case REQ_VIEW_NEXT:
3244 int nviews = displayed_views();
3245 int next_view = (current_view + 1) % nviews;
3247 if (next_view == current_view) {
3248 report("Only one view is displayed");
3249 break;
3252 current_view = next_view;
3253 /* Blur out the title of the previous view. */
3254 update_view_title(view);
3255 report("");
3256 break;
3258 case REQ_REFRESH:
3259 report("Refreshing is not yet supported for the %s view", view->name);
3260 break;
3262 case REQ_MAXIMIZE:
3263 if (displayed_views() == 2)
3264 maximize_view(view, TRUE);
3265 break;
3267 case REQ_OPTIONS:
3268 case REQ_TOGGLE_LINENO:
3269 case REQ_TOGGLE_DATE:
3270 case REQ_TOGGLE_AUTHOR:
3271 case REQ_TOGGLE_FILENAME:
3272 case REQ_TOGGLE_GRAPHIC:
3273 case REQ_TOGGLE_REV_GRAPH:
3274 case REQ_TOGGLE_REFS:
3275 case REQ_TOGGLE_IGNORE_SPACE:
3276 if (toggle_option(request) && view_has_flags(view, VIEW_DIFF_LIKE))
3277 reload_view(view);
3278 break;
3280 case REQ_TOGGLE_SORT_FIELD:
3281 case REQ_TOGGLE_SORT_ORDER:
3282 report("Sorting is not yet supported for the %s view", view->name);
3283 break;
3285 case REQ_DIFF_CONTEXT_UP:
3286 case REQ_DIFF_CONTEXT_DOWN:
3287 report("Changing the diff context is not yet supported for the %s view", view->name);
3288 break;
3290 case REQ_SEARCH:
3291 case REQ_SEARCH_BACK:
3292 search_view(view, request);
3293 break;
3295 case REQ_FIND_NEXT:
3296 case REQ_FIND_PREV:
3297 find_next(view, request);
3298 break;
3300 case REQ_STOP_LOADING:
3301 foreach_view(view, i) {
3302 if (view->pipe)
3303 report("Stopped loading the %s view", view->name),
3304 end_update(view, TRUE);
3306 break;
3308 case REQ_SHOW_VERSION:
3309 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3310 return TRUE;
3312 case REQ_SCREEN_REDRAW:
3313 redraw_display(TRUE);
3314 break;
3316 case REQ_EDIT:
3317 report("Nothing to edit");
3318 break;
3320 case REQ_ENTER:
3321 report("Nothing to enter");
3322 break;
3324 case REQ_VIEW_CLOSE:
3325 /* XXX: Mark closed views by letting view->prev point to the
3326 * view itself. Parents to closed view should never be
3327 * followed. */
3328 if (view->prev && view->prev != view) {
3329 maximize_view(view->prev, TRUE);
3330 view->prev = view;
3331 break;
3333 /* Fall-through */
3334 case REQ_QUIT:
3335 return FALSE;
3337 default:
3338 report("Unknown key, press %s for help",
3339 get_view_key(view, REQ_VIEW_HELP));
3340 return TRUE;
3343 return TRUE;
3348 * View backend utilities
3351 enum sort_field {
3352 ORDERBY_NAME,
3353 ORDERBY_DATE,
3354 ORDERBY_AUTHOR,
3357 struct sort_state {
3358 const enum sort_field *fields;
3359 size_t size, current;
3360 bool reverse;
3363 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3364 #define get_sort_field(state) ((state).fields[(state).current])
3365 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3367 static void
3368 sort_view(struct view *view, enum request request, struct sort_state *state,
3369 int (*compare)(const void *, const void *))
3371 switch (request) {
3372 case REQ_TOGGLE_SORT_FIELD:
3373 state->current = (state->current + 1) % state->size;
3374 break;
3376 case REQ_TOGGLE_SORT_ORDER:
3377 state->reverse = !state->reverse;
3378 break;
3379 default:
3380 die("Not a sort request");
3383 qsort(view->line, view->lines, sizeof(*view->line), compare);
3384 redraw_view(view);
3387 static bool
3388 update_diff_context(enum request request)
3390 int diff_context = opt_diff_context;
3392 switch (request) {
3393 case REQ_DIFF_CONTEXT_UP:
3394 opt_diff_context += 1;
3395 update_diff_context_arg(opt_diff_context);
3396 break;
3398 case REQ_DIFF_CONTEXT_DOWN:
3399 if (opt_diff_context == 0) {
3400 report("Diff context cannot be less than zero");
3401 break;
3403 opt_diff_context -= 1;
3404 update_diff_context_arg(opt_diff_context);
3405 break;
3407 default:
3408 die("Not a diff context request");
3411 return diff_context != opt_diff_context;
3414 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3416 /* Small author cache to reduce memory consumption. It uses binary
3417 * search to lookup or find place to position new entries. No entries
3418 * are ever freed. */
3419 static const char *
3420 get_author(const char *name)
3422 static const char **authors;
3423 static size_t authors_size;
3424 int from = 0, to = authors_size - 1;
3426 while (from <= to) {
3427 size_t pos = (to + from) / 2;
3428 int cmp = strcmp(name, authors[pos]);
3430 if (!cmp)
3431 return authors[pos];
3433 if (cmp < 0)
3434 to = pos - 1;
3435 else
3436 from = pos + 1;
3439 if (!realloc_authors(&authors, authors_size, 1))
3440 return NULL;
3441 name = strdup(name);
3442 if (!name)
3443 return NULL;
3445 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3446 authors[from] = name;
3447 authors_size++;
3449 return name;
3452 static void
3453 parse_timesec(struct time *time, const char *sec)
3455 time->sec = (time_t) atol(sec);
3458 static void
3459 parse_timezone(struct time *time, const char *zone)
3461 long tz;
3463 tz = ('0' - zone[1]) * 60 * 60 * 10;
3464 tz += ('0' - zone[2]) * 60 * 60;
3465 tz += ('0' - zone[3]) * 60 * 10;
3466 tz += ('0' - zone[4]) * 60;
3468 if (zone[0] == '-')
3469 tz = -tz;
3471 time->tz = tz;
3472 time->sec -= tz;
3475 /* Parse author lines where the name may be empty:
3476 * author <email@address.tld> 1138474660 +0100
3478 static void
3479 parse_author_line(char *ident, const char **author, struct time *time)
3481 char *nameend = strchr(ident, '<');
3482 char *emailend = strchr(ident, '>');
3484 if (nameend && emailend)
3485 *nameend = *emailend = 0;
3486 ident = chomp_string(ident);
3487 if (!*ident) {
3488 if (nameend)
3489 ident = chomp_string(nameend + 1);
3490 if (!*ident)
3491 ident = "Unknown";
3494 *author = get_author(ident);
3496 /* Parse epoch and timezone */
3497 if (emailend && emailend[1] == ' ') {
3498 char *secs = emailend + 2;
3499 char *zone = strchr(secs, ' ');
3501 parse_timesec(time, secs);
3503 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3504 parse_timezone(time, zone + 1);
3508 static struct line *
3509 find_prev_line_by_type(struct view *view, struct line *line, enum line_type type)
3511 for (; view->line < line; line--)
3512 if (line->type == type)
3513 return line;
3515 return NULL;
3519 * Blame
3522 struct blame_commit {
3523 char id[SIZEOF_REV]; /* SHA1 ID. */
3524 char title[128]; /* First line of the commit message. */
3525 const char *author; /* Author of the commit. */
3526 struct time time; /* Date from the author ident. */
3527 char filename[128]; /* Name of file. */
3528 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
3529 char parent_filename[128]; /* Parent/previous name of file. */
3532 struct blame_header {
3533 char id[SIZEOF_REV]; /* SHA1 ID. */
3534 size_t orig_lineno;
3535 size_t lineno;
3536 size_t group;
3539 static bool
3540 parse_number(const char **posref, size_t *number, size_t min, size_t max)
3542 const char *pos = *posref;
3544 *posref = NULL;
3545 pos = strchr(pos + 1, ' ');
3546 if (!pos || !isdigit(pos[1]))
3547 return FALSE;
3548 *number = atoi(pos + 1);
3549 if (*number < min || *number > max)
3550 return FALSE;
3552 *posref = pos;
3553 return TRUE;
3556 static bool
3557 parse_blame_header(struct blame_header *header, const char *text, size_t max_lineno)
3559 const char *pos = text + SIZEOF_REV - 2;
3561 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
3562 return FALSE;
3564 string_ncopy(header->id, text, SIZEOF_REV);
3566 if (!parse_number(&pos, &header->orig_lineno, 1, 9999999) ||
3567 !parse_number(&pos, &header->lineno, 1, max_lineno) ||
3568 !parse_number(&pos, &header->group, 1, max_lineno - header->lineno + 1))
3569 return FALSE;
3571 return TRUE;
3574 static bool
3575 match_blame_header(const char *name, char **line)
3577 size_t namelen = strlen(name);
3578 bool matched = !strncmp(name, *line, namelen);
3580 if (matched)
3581 *line += namelen;
3583 return matched;
3586 static bool
3587 parse_blame_info(struct blame_commit *commit, char *line)
3589 if (match_blame_header("author ", &line)) {
3590 commit->author = get_author(line);
3592 } else if (match_blame_header("author-time ", &line)) {
3593 parse_timesec(&commit->time, line);
3595 } else if (match_blame_header("author-tz ", &line)) {
3596 parse_timezone(&commit->time, line);
3598 } else if (match_blame_header("summary ", &line)) {
3599 string_ncopy(commit->title, line, strlen(line));
3601 } else if (match_blame_header("previous ", &line)) {
3602 if (strlen(line) <= SIZEOF_REV)
3603 return FALSE;
3604 string_copy_rev(commit->parent_id, line);
3605 line += SIZEOF_REV;
3606 string_ncopy(commit->parent_filename, line, strlen(line));
3608 } else if (match_blame_header("filename ", &line)) {
3609 string_ncopy(commit->filename, line, strlen(line));
3610 return TRUE;
3613 return FALSE;
3617 * Pager backend
3620 static bool
3621 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3623 if (draw_lineno(view, lineno))
3624 return TRUE;
3626 draw_text(view, line->type, line->data);
3627 return TRUE;
3630 static bool
3631 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3633 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3634 char ref[SIZEOF_STR];
3636 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3637 return TRUE;
3639 /* This is the only fatal call, since it can "corrupt" the buffer. */
3640 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3641 return FALSE;
3643 return TRUE;
3646 static void
3647 add_pager_refs(struct view *view, struct line *line)
3649 char buf[SIZEOF_STR];
3650 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3651 struct ref_list *list;
3652 size_t bufpos = 0, i;
3653 const char *sep = "Refs: ";
3654 bool is_tag = FALSE;
3656 assert(line->type == LINE_COMMIT);
3658 list = get_ref_list(commit_id);
3659 if (!list) {
3660 if (view_has_flags(view, VIEW_ADD_DESCRIBE_REF))
3661 goto try_add_describe_ref;
3662 return;
3665 for (i = 0; i < list->size; i++) {
3666 struct ref *ref = list->refs[i];
3667 const char *fmt = ref->tag ? "%s[%s]" :
3668 ref->remote ? "%s<%s>" : "%s%s";
3670 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3671 return;
3672 sep = ", ";
3673 if (ref->tag)
3674 is_tag = TRUE;
3677 if (!is_tag && view_has_flags(view, VIEW_ADD_DESCRIBE_REF)) {
3678 try_add_describe_ref:
3679 /* Add <tag>-g<commit_id> "fake" reference. */
3680 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3681 return;
3684 if (bufpos == 0)
3685 return;
3687 add_line_text(view, buf, LINE_PP_REFS);
3690 static bool
3691 pager_common_read(struct view *view, char *data, enum line_type type)
3693 struct line *line;
3695 if (!data)
3696 return TRUE;
3698 line = add_line_text(view, data, type);
3699 if (!line)
3700 return FALSE;
3702 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_ADD_PAGER_REFS))
3703 add_pager_refs(view, line);
3705 return TRUE;
3708 static bool
3709 pager_read(struct view *view, char *data)
3711 if (!data)
3712 return TRUE;
3714 return pager_common_read(view, data, get_line_type(data));
3717 static enum request
3718 pager_request(struct view *view, enum request request, struct line *line)
3720 int split = 0;
3722 if (request != REQ_ENTER)
3723 return request;
3725 if (line->type == LINE_COMMIT && view_has_flags(view, VIEW_OPEN_DIFF)) {
3726 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3727 split = 1;
3730 /* Always scroll the view even if it was split. That way
3731 * you can use Enter to scroll through the log view and
3732 * split open each commit diff. */
3733 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3735 /* FIXME: A minor workaround. Scrolling the view will call report("")
3736 * but if we are scrolling a non-current view this won't properly
3737 * update the view title. */
3738 if (split)
3739 update_view_title(view);
3741 return REQ_NONE;
3744 static bool
3745 pager_grep(struct view *view, struct line *line)
3747 const char *text[] = { line->data, NULL };
3749 return grep_text(view, text);
3752 static void
3753 pager_select(struct view *view, struct line *line)
3755 if (line->type == LINE_COMMIT) {
3756 char *text = (char *)line->data + STRING_SIZE("commit ");
3758 if (!view_has_flags(view, VIEW_NO_REF))
3759 string_copy_rev(view->ref, text);
3760 string_copy_rev(ref_commit, text);
3764 static bool
3765 pager_open(struct view *view, enum open_flags flags)
3767 return begin_update(view, NULL, NULL, flags);
3770 static struct view_ops pager_ops = {
3771 "line",
3772 VIEW_OPEN_DIFF | VIEW_NO_REF | VIEW_NO_GIT_DIR,
3774 pager_open,
3775 pager_read,
3776 pager_draw,
3777 pager_request,
3778 pager_grep,
3779 pager_select,
3782 static bool
3783 log_open(struct view *view, enum open_flags flags)
3785 static const char *log_argv[] = {
3786 "git", "log", ENCODING_ARG, "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3789 return begin_update(view, NULL, log_argv, flags);
3792 static enum request
3793 log_request(struct view *view, enum request request, struct line *line)
3795 switch (request) {
3796 case REQ_REFRESH:
3797 load_refs();
3798 refresh_view(view);
3799 return REQ_NONE;
3800 default:
3801 return pager_request(view, request, line);
3805 static struct view_ops log_ops = {
3806 "line",
3807 VIEW_ADD_PAGER_REFS | VIEW_OPEN_DIFF,
3809 log_open,
3810 pager_read,
3811 pager_draw,
3812 log_request,
3813 pager_grep,
3814 pager_select,
3817 struct diff_state {
3818 bool reading_diff_stat;
3819 bool combined_diff;
3822 static bool
3823 diff_open(struct view *view, enum open_flags flags)
3825 static const char *diff_argv[] = {
3826 "git", "show", ENCODING_ARG, "--pretty=fuller", "--no-color", "--root",
3827 "--patch-with-stat", "--find-copies-harder", "-C",
3828 opt_notes_arg, opt_diff_context_arg, opt_ignore_space_arg,
3829 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3832 return begin_update(view, NULL, diff_argv, flags);
3835 static bool
3836 diff_common_read(struct view *view, char *data, struct diff_state *state)
3838 enum line_type type;
3840 if (state->reading_diff_stat) {
3841 size_t len = strlen(data);
3842 char *pipe = strchr(data, '|');
3843 bool has_histogram = data[len - 1] == '-' || data[len - 1] == '+';
3844 bool has_bin_diff = pipe && strstr(pipe, "Bin") && strstr(pipe, "->");
3846 if (pipe && (has_histogram || has_bin_diff)) {
3847 return add_line_text(view, data, LINE_DIFF_STAT) != NULL;
3848 } else {
3849 state->reading_diff_stat = FALSE;
3852 } else if (!strcmp(data, "---")) {
3853 state->reading_diff_stat = TRUE;
3856 type = get_line_type(data);
3858 if (type == LINE_DIFF_HEADER) {
3859 const int len = line_info[LINE_DIFF_HEADER].linelen;
3861 if (!strncmp(data + len, "combined ", strlen("combined ")) ||
3862 !strncmp(data + len, "cc ", strlen("cc ")))
3863 state->combined_diff = TRUE;
3866 /* ADD2 and DEL2 are only valid in combined diff hunks */
3867 if (!state->combined_diff && (type == LINE_DIFF_ADD2 || type == LINE_DIFF_DEL2))
3868 type = LINE_DEFAULT;
3870 return pager_common_read(view, data, type);
3873 static enum request
3874 diff_common_enter(struct view *view, enum request request, struct line *line)
3876 if (line->type == LINE_DIFF_STAT) {
3877 int file_number = 0;
3879 while (line >= view->line && line->type == LINE_DIFF_STAT) {
3880 file_number++;
3881 line--;
3884 while (line < view->line + view->lines) {
3885 if (line->type == LINE_DIFF_HEADER) {
3886 if (file_number == 1) {
3887 break;
3889 file_number--;
3891 line++;
3895 select_view_line(view, line - view->line);
3896 report("");
3897 return REQ_NONE;
3899 } else {
3900 return pager_request(view, request, line);
3904 static bool
3905 diff_common_draw_part(struct view *view, enum line_type *type, char **text, char c, enum line_type next_type)
3907 char *sep = strchr(*text, c);
3909 if (sep != NULL) {
3910 *sep = 0;
3911 draw_text(view, *type, *text);
3912 *sep = c;
3913 *text = sep;
3914 *type = next_type;
3917 return sep != NULL;
3920 static bool
3921 diff_common_draw(struct view *view, struct line *line, unsigned int lineno)
3923 char *text = line->data;
3924 enum line_type type = line->type;
3926 if (draw_lineno(view, lineno))
3927 return TRUE;
3929 if (type == LINE_DIFF_STAT) {
3930 diff_common_draw_part(view, &type, &text, '|', LINE_DEFAULT);
3931 if (diff_common_draw_part(view, &type, &text, 'B', LINE_DEFAULT)) {
3932 /* Handle binary diffstat: Bin <deleted> -> <added> bytes */
3933 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_DEL);
3934 diff_common_draw_part(view, &type, &text, '-', LINE_DEFAULT);
3935 diff_common_draw_part(view, &type, &text, ' ', LINE_DIFF_ADD);
3936 diff_common_draw_part(view, &type, &text, 'b', LINE_DEFAULT);
3938 } else {
3939 diff_common_draw_part(view, &type, &text, '+', LINE_DIFF_ADD);
3940 diff_common_draw_part(view, &type, &text, '-', LINE_DIFF_DEL);
3944 draw_text(view, type, text);
3945 return TRUE;
3948 static bool
3949 diff_read(struct view *view, char *data)
3951 struct diff_state *state = view->private;
3953 if (!data) {
3954 /* Fall back to retry if no diff will be shown. */
3955 if (view->lines == 0 && opt_file_argv) {
3956 int pos = argv_size(view->argv)
3957 - argv_size(opt_file_argv) - 1;
3959 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3960 for (; view->argv[pos]; pos++) {
3961 free((void *) view->argv[pos]);
3962 view->argv[pos] = NULL;
3965 if (view->pipe)
3966 io_done(view->pipe);
3967 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3968 return FALSE;
3971 return TRUE;
3974 return diff_common_read(view, data, state);
3977 static bool
3978 diff_blame_line(const char *ref, const char *file, unsigned long lineno,
3979 struct blame_header *header, struct blame_commit *commit)
3981 char line_arg[SIZEOF_STR];
3982 const char *blame_argv[] = {
3983 "git", "blame", ENCODING_ARG, "-p", line_arg, ref, "--", file, NULL
3985 struct io io;
3986 bool ok = FALSE;
3987 char *buf;
3989 if (!string_format(line_arg, "-L%d,+1", lineno))
3990 return FALSE;
3992 if (!io_run(&io, IO_RD, opt_cdup, blame_argv))
3993 return FALSE;
3995 while ((buf = io_get(&io, '\n', TRUE))) {
3996 if (header) {
3997 if (!parse_blame_header(header, buf, 9999999))
3998 break;
3999 header = NULL;
4001 } else if (parse_blame_info(commit, buf)) {
4002 ok = TRUE;
4003 break;
4007 if (io_error(&io))
4008 ok = FALSE;
4010 io_done(&io);
4011 return ok;
4014 static bool
4015 parse_chunk_lineno(int *lineno, const char *chunk, int marker)
4017 return prefixcmp(chunk, "@@ -") ||
4018 !(chunk = strchr(chunk, marker)) ||
4019 parse_int(lineno, chunk + 1, 0, 9999999) != OPT_OK;
4022 static enum request
4023 diff_trace_origin(struct view *view, struct line *line)
4025 struct line *diff = find_prev_line_by_type(view, line, LINE_DIFF_HEADER);
4026 struct line *chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
4027 const char *chunk_data;
4028 int chunk_marker = line->type == LINE_DIFF_DEL ? '-' : '+';
4029 int lineno = 0;
4030 const char *file = NULL;
4031 char ref[SIZEOF_REF];
4032 struct blame_header header;
4033 struct blame_commit commit;
4035 if (!diff || !chunk || chunk == line) {
4036 report("The line to trace must be inside a diff chunk");
4037 return REQ_NONE;
4040 for (; diff < line && !file; diff++) {
4041 const char *data = diff->data;
4043 if (!prefixcmp(data, "--- a/")) {
4044 file = data + STRING_SIZE("--- a/");
4045 break;
4049 if (diff == line || !file) {
4050 report("Failed to read the file name");
4051 return REQ_NONE;
4054 chunk_data = chunk->data;
4056 if (parse_chunk_lineno(&lineno, chunk_data, chunk_marker)) {
4057 report("Failed to read the line number");
4058 return REQ_NONE;
4061 if (lineno == 0) {
4062 report("This is the origin of the line");
4063 return REQ_NONE;
4066 for (chunk += 1; chunk < line; chunk++) {
4067 if (chunk->type == LINE_DIFF_ADD) {
4068 lineno += chunk_marker == '+';
4069 } else if (chunk->type == LINE_DIFF_DEL) {
4070 lineno += chunk_marker == '-';
4071 } else {
4072 lineno++;
4076 if (chunk_marker == '+')
4077 string_copy(ref, view->vid);
4078 else
4079 string_format(ref, "%s^", view->vid);
4081 if (!diff_blame_line(ref, file, lineno, &header, &commit)) {
4082 report("Failed to read blame data");
4083 return REQ_NONE;
4086 string_ncopy(opt_file, commit.filename, strlen(commit.filename));
4087 string_copy(opt_ref, header.id);
4088 opt_goto_line = header.orig_lineno - 1;
4090 return REQ_VIEW_BLAME;
4093 static enum request
4094 diff_request(struct view *view, enum request request, struct line *line)
4096 switch (request) {
4097 case REQ_VIEW_BLAME:
4098 return diff_trace_origin(view, line);
4100 case REQ_DIFF_CONTEXT_UP:
4101 case REQ_DIFF_CONTEXT_DOWN:
4102 if (!update_diff_context(request))
4103 return REQ_NONE;
4104 reload_view(view);
4105 return REQ_NONE;
4108 case REQ_ENTER:
4109 return diff_common_enter(view, request, line);
4111 default:
4112 return pager_request(view, request, line);
4116 static void
4117 diff_select(struct view *view, struct line *line)
4119 if (line->type == LINE_DIFF_STAT) {
4120 const char *key = get_view_key(view, REQ_ENTER);
4122 string_format(view->ref, "Press '%s' to jump to file diff", key);
4123 } else {
4124 string_ncopy(view->ref, view->id, strlen(view->id));
4125 return pager_select(view, line);
4129 static struct view_ops diff_ops = {
4130 "line",
4131 VIEW_DIFF_LIKE | VIEW_ADD_DESCRIBE_REF | VIEW_ADD_PAGER_REFS,
4132 sizeof(struct diff_state),
4133 diff_open,
4134 diff_read,
4135 diff_common_draw,
4136 diff_request,
4137 pager_grep,
4138 diff_select,
4142 * Help backend
4145 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
4147 static bool
4148 help_open_keymap_title(struct view *view, enum keymap keymap)
4150 struct line *line;
4152 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
4153 help_keymap_hidden[keymap] ? '+' : '-',
4154 enum_name(keymap_map[keymap]));
4155 if (line)
4156 line->other = keymap;
4158 return help_keymap_hidden[keymap];
4161 static void
4162 help_open_keymap(struct view *view, enum keymap keymap)
4164 const char *group = NULL;
4165 char buf[SIZEOF_STR];
4166 size_t bufpos;
4167 bool add_title = TRUE;
4168 int i;
4170 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
4171 const char *key = NULL;
4173 if (req_info[i].request == REQ_NONE)
4174 continue;
4176 if (!req_info[i].request) {
4177 group = req_info[i].help;
4178 continue;
4181 key = get_keys(keymap, req_info[i].request, TRUE);
4182 if (!key || !*key)
4183 continue;
4185 if (add_title && help_open_keymap_title(view, keymap))
4186 return;
4187 add_title = FALSE;
4189 if (group) {
4190 add_line_text(view, group, LINE_HELP_GROUP);
4191 group = NULL;
4194 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
4195 enum_name(req_info[i]), req_info[i].help);
4198 group = "External commands:";
4200 for (i = 0; i < run_requests; i++) {
4201 struct run_request *req = get_run_request(REQ_NONE + i + 1);
4202 const char *key;
4203 int argc;
4205 if (!req || req->keymap != keymap)
4206 continue;
4208 key = get_key_name(req->key);
4209 if (!*key)
4210 key = "(no key defined)";
4212 if (add_title && help_open_keymap_title(view, keymap))
4213 return;
4214 if (group) {
4215 add_line_text(view, group, LINE_HELP_GROUP);
4216 group = NULL;
4219 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
4220 if (!string_format_from(buf, &bufpos, "%s%s",
4221 argc ? " " : "", req->argv[argc]))
4222 return;
4224 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
4228 static bool
4229 help_open(struct view *view, enum open_flags flags)
4231 enum keymap keymap;
4233 reset_view(view);
4234 view->p_restore = TRUE;
4235 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
4236 add_line_text(view, "", LINE_DEFAULT);
4238 for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
4239 help_open_keymap(view, keymap);
4241 return TRUE;
4244 static enum request
4245 help_request(struct view *view, enum request request, struct line *line)
4247 switch (request) {
4248 case REQ_ENTER:
4249 if (line->type == LINE_HELP_KEYMAP) {
4250 help_keymap_hidden[line->other] =
4251 !help_keymap_hidden[line->other];
4252 refresh_view(view);
4255 return REQ_NONE;
4256 default:
4257 return pager_request(view, request, line);
4261 static struct view_ops help_ops = {
4262 "line",
4263 VIEW_NO_GIT_DIR,
4265 help_open,
4266 NULL,
4267 pager_draw,
4268 help_request,
4269 pager_grep,
4270 pager_select,
4275 * Tree backend
4278 struct tree_stack_entry {
4279 struct tree_stack_entry *prev; /* Entry below this in the stack */
4280 unsigned long lineno; /* Line number to restore */
4281 char *name; /* Position of name in opt_path */
4284 /* The top of the path stack. */
4285 static struct tree_stack_entry *tree_stack = NULL;
4286 unsigned long tree_lineno = 0;
4288 static void
4289 pop_tree_stack_entry(void)
4291 struct tree_stack_entry *entry = tree_stack;
4293 tree_lineno = entry->lineno;
4294 entry->name[0] = 0;
4295 tree_stack = entry->prev;
4296 free(entry);
4299 static void
4300 push_tree_stack_entry(const char *name, unsigned long lineno)
4302 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
4303 size_t pathlen = strlen(opt_path);
4305 if (!entry)
4306 return;
4308 entry->prev = tree_stack;
4309 entry->name = opt_path + pathlen;
4310 tree_stack = entry;
4312 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
4313 pop_tree_stack_entry();
4314 return;
4317 /* Move the current line to the first tree entry. */
4318 tree_lineno = 1;
4319 entry->lineno = lineno;
4322 /* Parse output from git-ls-tree(1):
4324 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4327 #define SIZEOF_TREE_ATTR \
4328 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4330 #define SIZEOF_TREE_MODE \
4331 STRING_SIZE("100644 ")
4333 #define TREE_ID_OFFSET \
4334 STRING_SIZE("100644 blob ")
4336 struct tree_entry {
4337 char id[SIZEOF_REV];
4338 mode_t mode;
4339 struct time time; /* Date from the author ident. */
4340 const char *author; /* Author of the commit. */
4341 char name[1];
4344 struct tree_state {
4345 const char *author_name;
4346 struct time author_time;
4347 bool read_date;
4350 static const char *
4351 tree_path(const struct line *line)
4353 return ((struct tree_entry *) line->data)->name;
4356 static int
4357 tree_compare_entry(const struct line *line1, const struct line *line2)
4359 if (line1->type != line2->type)
4360 return line1->type == LINE_TREE_DIR ? -1 : 1;
4361 return strcmp(tree_path(line1), tree_path(line2));
4364 static const enum sort_field tree_sort_fields[] = {
4365 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4367 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
4369 static int
4370 tree_compare(const void *l1, const void *l2)
4372 const struct line *line1 = (const struct line *) l1;
4373 const struct line *line2 = (const struct line *) l2;
4374 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
4375 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
4377 if (line1->type == LINE_TREE_HEAD)
4378 return -1;
4379 if (line2->type == LINE_TREE_HEAD)
4380 return 1;
4382 switch (get_sort_field(tree_sort_state)) {
4383 case ORDERBY_DATE:
4384 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
4386 case ORDERBY_AUTHOR:
4387 return sort_order(tree_sort_state, strcmp_null(entry1->author, entry2->author));
4389 case ORDERBY_NAME:
4390 default:
4391 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
4396 static struct line *
4397 tree_entry(struct view *view, enum line_type type, const char *path,
4398 const char *mode, const char *id)
4400 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
4401 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
4403 if (!entry || !line) {
4404 free(entry);
4405 return NULL;
4408 strncpy(entry->name, path, strlen(path));
4409 if (mode)
4410 entry->mode = strtoul(mode, NULL, 8);
4411 if (id)
4412 string_copy_rev(entry->id, id);
4414 return line;
4417 static bool
4418 tree_read_date(struct view *view, char *text, struct tree_state *state)
4420 if (!text && state->read_date) {
4421 state->read_date = FALSE;
4422 return TRUE;
4424 } else if (!text) {
4425 /* Find next entry to process */
4426 const char *log_file[] = {
4427 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
4428 "--cc", "--raw", view->id, "--", "%(directory)", NULL
4431 if (!view->lines) {
4432 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
4433 report("Tree is empty");
4434 return TRUE;
4437 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
4438 report("Failed to load tree data");
4439 return TRUE;
4442 state->read_date = TRUE;
4443 return FALSE;
4445 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
4446 parse_author_line(text + STRING_SIZE("author "),
4447 &state->author_name, &state->author_time);
4449 } else if (*text == ':') {
4450 char *pos;
4451 size_t annotated = 1;
4452 size_t i;
4454 pos = strchr(text, '\t');
4455 if (!pos)
4456 return TRUE;
4457 text = pos + 1;
4458 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
4459 text += strlen(opt_path);
4460 pos = strchr(text, '/');
4461 if (pos)
4462 *pos = 0;
4464 for (i = 1; i < view->lines; i++) {
4465 struct line *line = &view->line[i];
4466 struct tree_entry *entry = line->data;
4468 annotated += !!entry->author;
4469 if (entry->author || strcmp(entry->name, text))
4470 continue;
4472 entry->author = state->author_name;
4473 entry->time = state->author_time;
4474 line->dirty = 1;
4475 break;
4478 if (annotated == view->lines)
4479 io_kill(view->pipe);
4481 return TRUE;
4484 static bool
4485 tree_read(struct view *view, char *text)
4487 struct tree_state *state = view->private;
4488 struct tree_entry *data;
4489 struct line *entry, *line;
4490 enum line_type type;
4491 size_t textlen = text ? strlen(text) : 0;
4492 char *path = text + SIZEOF_TREE_ATTR;
4494 if (state->read_date || !text)
4495 return tree_read_date(view, text, state);
4497 if (textlen <= SIZEOF_TREE_ATTR)
4498 return FALSE;
4499 if (view->lines == 0 &&
4500 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
4501 return FALSE;
4503 /* Strip the path part ... */
4504 if (*opt_path) {
4505 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
4506 size_t striplen = strlen(opt_path);
4508 if (pathlen > striplen)
4509 memmove(path, path + striplen,
4510 pathlen - striplen + 1);
4512 /* Insert "link" to parent directory. */
4513 if (view->lines == 1 &&
4514 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
4515 return FALSE;
4518 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
4519 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
4520 if (!entry)
4521 return FALSE;
4522 data = entry->data;
4524 /* Skip "Directory ..." and ".." line. */
4525 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
4526 if (tree_compare_entry(line, entry) <= 0)
4527 continue;
4529 memmove(line + 1, line, (entry - line) * sizeof(*entry));
4531 line->data = data;
4532 line->type = type;
4533 for (; line <= entry; line++)
4534 line->dirty = line->cleareol = 1;
4535 return TRUE;
4538 if (tree_lineno > view->lineno) {
4539 view->lineno = tree_lineno;
4540 tree_lineno = 0;
4543 return TRUE;
4546 static bool
4547 tree_draw(struct view *view, struct line *line, unsigned int lineno)
4549 struct tree_entry *entry = line->data;
4551 if (line->type == LINE_TREE_HEAD) {
4552 if (draw_text(view, line->type, "Directory path /"))
4553 return TRUE;
4554 } else {
4555 if (draw_mode(view, entry->mode))
4556 return TRUE;
4558 if (draw_author(view, entry->author))
4559 return TRUE;
4561 if (draw_date(view, &entry->time))
4562 return TRUE;
4565 draw_text(view, line->type, entry->name);
4566 return TRUE;
4569 static void
4570 open_blob_editor(const char *id)
4572 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
4573 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
4574 int fd = mkstemp(file);
4576 if (fd == -1)
4577 report("Failed to create temporary file");
4578 else if (!io_run_append(blob_argv, fd))
4579 report("Failed to save blob data to file");
4580 else
4581 open_editor(file);
4582 if (fd != -1)
4583 unlink(file);
4586 static enum request
4587 tree_request(struct view *view, enum request request, struct line *line)
4589 enum open_flags flags;
4590 struct tree_entry *entry = line->data;
4592 switch (request) {
4593 case REQ_VIEW_BLAME:
4594 if (line->type != LINE_TREE_FILE) {
4595 report("Blame only supported for files");
4596 return REQ_NONE;
4599 string_copy(opt_ref, view->vid);
4600 return request;
4602 case REQ_EDIT:
4603 if (line->type != LINE_TREE_FILE) {
4604 report("Edit only supported for files");
4605 } else if (!is_head_commit(view->vid)) {
4606 open_blob_editor(entry->id);
4607 } else {
4608 open_editor(opt_file);
4610 return REQ_NONE;
4612 case REQ_TOGGLE_SORT_FIELD:
4613 case REQ_TOGGLE_SORT_ORDER:
4614 sort_view(view, request, &tree_sort_state, tree_compare);
4615 return REQ_NONE;
4617 case REQ_PARENT:
4618 if (!*opt_path) {
4619 /* quit view if at top of tree */
4620 return REQ_VIEW_CLOSE;
4622 /* fake 'cd ..' */
4623 line = &view->line[1];
4624 break;
4626 case REQ_ENTER:
4627 break;
4629 default:
4630 return request;
4633 /* Cleanup the stack if the tree view is at a different tree. */
4634 while (!*opt_path && tree_stack)
4635 pop_tree_stack_entry();
4637 switch (line->type) {
4638 case LINE_TREE_DIR:
4639 /* Depending on whether it is a subdirectory or parent link
4640 * mangle the path buffer. */
4641 if (line == &view->line[1] && *opt_path) {
4642 pop_tree_stack_entry();
4644 } else {
4645 const char *basename = tree_path(line);
4647 push_tree_stack_entry(basename, view->lineno);
4650 /* Trees and subtrees share the same ID, so they are not not
4651 * unique like blobs. */
4652 flags = OPEN_RELOAD;
4653 request = REQ_VIEW_TREE;
4654 break;
4656 case LINE_TREE_FILE:
4657 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4658 request = REQ_VIEW_BLOB;
4659 break;
4661 default:
4662 return REQ_NONE;
4665 open_view(view, request, flags);
4666 if (request == REQ_VIEW_TREE)
4667 view->lineno = tree_lineno;
4669 return REQ_NONE;
4672 static bool
4673 tree_grep(struct view *view, struct line *line)
4675 struct tree_entry *entry = line->data;
4676 const char *text[] = {
4677 entry->name,
4678 mkauthor(entry->author, opt_author_cols, opt_author),
4679 mkdate(&entry->time, opt_date),
4680 NULL
4683 return grep_text(view, text);
4686 static void
4687 tree_select(struct view *view, struct line *line)
4689 struct tree_entry *entry = line->data;
4691 if (line->type == LINE_TREE_FILE) {
4692 string_copy_rev(ref_blob, entry->id);
4693 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4695 } else if (line->type != LINE_TREE_DIR) {
4696 return;
4699 string_copy_rev(view->ref, entry->id);
4702 static bool
4703 tree_open(struct view *view, enum open_flags flags)
4705 static const char *tree_argv[] = {
4706 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4709 if (view->lines == 0 && opt_prefix[0]) {
4710 char *pos = opt_prefix;
4712 while (pos && *pos) {
4713 char *end = strchr(pos, '/');
4715 if (end)
4716 *end = 0;
4717 push_tree_stack_entry(pos, 0);
4718 pos = end;
4719 if (end) {
4720 *end = '/';
4721 pos++;
4725 } else if (strcmp(view->vid, view->id)) {
4726 opt_path[0] = 0;
4729 return begin_update(view, opt_cdup, tree_argv, flags);
4732 static struct view_ops tree_ops = {
4733 "file",
4734 VIEW_NO_FLAGS,
4735 sizeof(struct tree_state),
4736 tree_open,
4737 tree_read,
4738 tree_draw,
4739 tree_request,
4740 tree_grep,
4741 tree_select,
4744 static bool
4745 blob_open(struct view *view, enum open_flags flags)
4747 static const char *blob_argv[] = {
4748 "git", "cat-file", "blob", "%(blob)", NULL
4751 view->encoding = get_path_encoding(opt_file, opt_encoding);
4753 return begin_update(view, NULL, blob_argv, flags);
4756 static bool
4757 blob_read(struct view *view, char *line)
4759 if (!line)
4760 return TRUE;
4761 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4764 static enum request
4765 blob_request(struct view *view, enum request request, struct line *line)
4767 switch (request) {
4768 case REQ_EDIT:
4769 open_blob_editor(view->vid);
4770 return REQ_NONE;
4771 default:
4772 return pager_request(view, request, line);
4776 static struct view_ops blob_ops = {
4777 "line",
4778 VIEW_NO_FLAGS,
4780 blob_open,
4781 blob_read,
4782 pager_draw,
4783 blob_request,
4784 pager_grep,
4785 pager_select,
4789 * Blame backend
4791 * Loading the blame view is a two phase job:
4793 * 1. File content is read either using opt_file from the
4794 * filesystem or using git-cat-file.
4795 * 2. Then blame information is incrementally added by
4796 * reading output from git-blame.
4799 struct blame {
4800 struct blame_commit *commit;
4801 unsigned long lineno;
4802 char text[1];
4805 struct blame_state {
4806 struct blame_commit *commit;
4807 int blamed;
4808 bool done_reading;
4809 bool auto_filename_display;
4812 static bool
4813 blame_detect_filename_display(struct view *view)
4815 bool show_filenames = FALSE;
4816 const char *filename = NULL;
4817 int i;
4819 if (opt_blame_argv) {
4820 for (i = 0; opt_blame_argv[i]; i++) {
4821 if (prefixcmp(opt_blame_argv[i], "-C"))
4822 continue;
4824 show_filenames = TRUE;
4828 for (i = 0; i < view->lines; i++) {
4829 struct blame *blame = view->line[i].data;
4831 if (blame->commit && blame->commit->id[0]) {
4832 if (!filename)
4833 filename = blame->commit->filename;
4834 else if (strcmp(filename, blame->commit->filename))
4835 show_filenames = TRUE;
4839 return show_filenames;
4842 static bool
4843 blame_open(struct view *view, enum open_flags flags)
4845 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4846 char path[SIZEOF_STR];
4847 size_t i;
4849 if (!view->prev && *opt_prefix) {
4850 string_copy(path, opt_file);
4851 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4852 return FALSE;
4855 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4856 const char *blame_cat_file_argv[] = {
4857 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4860 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4861 return FALSE;
4864 /* First pass: remove multiple references to the same commit. */
4865 for (i = 0; i < view->lines; i++) {
4866 struct blame *blame = view->line[i].data;
4868 if (blame->commit && blame->commit->id[0])
4869 blame->commit->id[0] = 0;
4870 else
4871 blame->commit = NULL;
4874 /* Second pass: free existing references. */
4875 for (i = 0; i < view->lines; i++) {
4876 struct blame *blame = view->line[i].data;
4878 if (blame->commit)
4879 free(blame->commit);
4882 string_format(view->vid, "%s", opt_file);
4883 string_format(view->ref, "%s ...", opt_file);
4885 return TRUE;
4888 static struct blame_commit *
4889 get_blame_commit(struct view *view, const char *id)
4891 size_t i;
4893 for (i = 0; i < view->lines; i++) {
4894 struct blame *blame = view->line[i].data;
4896 if (!blame->commit)
4897 continue;
4899 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4900 return blame->commit;
4904 struct blame_commit *commit = calloc(1, sizeof(*commit));
4906 if (commit)
4907 string_ncopy(commit->id, id, SIZEOF_REV);
4908 return commit;
4912 static struct blame_commit *
4913 read_blame_commit(struct view *view, const char *text, struct blame_state *state)
4915 struct blame_header header;
4916 struct blame_commit *commit;
4917 struct blame *blame;
4919 if (!parse_blame_header(&header, text, view->lines))
4920 return NULL;
4922 commit = get_blame_commit(view, text);
4923 if (!commit)
4924 return NULL;
4926 state->blamed += header.group;
4927 while (header.group--) {
4928 struct line *line = &view->line[header.lineno + header.group - 1];
4930 blame = line->data;
4931 blame->commit = commit;
4932 blame->lineno = header.orig_lineno + header.group - 1;
4933 line->dirty = 1;
4936 return commit;
4939 static bool
4940 blame_read_file(struct view *view, const char *line, struct blame_state *state)
4942 if (!line) {
4943 const char *blame_argv[] = {
4944 "git", "blame", ENCODING_ARG, "%(blameargs)", "--incremental",
4945 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4948 if (view->lines == 0 && !view->prev)
4949 die("No blame exist for %s", view->vid);
4951 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
4952 report("Failed to load blame data");
4953 return TRUE;
4956 if (opt_goto_line > 0) {
4957 select_view_line(view, opt_goto_line);
4958 opt_goto_line = 0;
4961 state->done_reading = TRUE;
4962 return FALSE;
4964 } else {
4965 size_t linelen = strlen(line);
4966 struct blame *blame = malloc(sizeof(*blame) + linelen);
4968 if (!blame)
4969 return FALSE;
4971 blame->commit = NULL;
4972 strncpy(blame->text, line, linelen);
4973 blame->text[linelen] = 0;
4974 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4978 static bool
4979 blame_read(struct view *view, char *line)
4981 struct blame_state *state = view->private;
4983 if (!state->done_reading)
4984 return blame_read_file(view, line, state);
4986 if (!line) {
4987 state->auto_filename_display = blame_detect_filename_display(view);
4988 string_format(view->ref, "%s", view->vid);
4989 if (view_is_displayed(view)) {
4990 update_view_title(view);
4991 redraw_view_from(view, 0);
4993 return TRUE;
4996 if (!state->commit) {
4997 state->commit = read_blame_commit(view, line, state);
4998 string_format(view->ref, "%s %2d%%", view->vid,
4999 view->lines ? state->blamed * 100 / view->lines : 0);
5001 } else if (parse_blame_info(state->commit, line)) {
5002 state->commit = NULL;
5005 return TRUE;
5008 static bool
5009 blame_draw(struct view *view, struct line *line, unsigned int lineno)
5011 struct blame_state *state = view->private;
5012 struct blame *blame = line->data;
5013 struct time *time = NULL;
5014 const char *id = NULL, *author = NULL, *filename = NULL;
5015 enum line_type id_type = LINE_BLAME_ID;
5016 static const enum line_type blame_colors[] = {
5017 LINE_PALETTE_0,
5018 LINE_PALETTE_1,
5019 LINE_PALETTE_2,
5020 LINE_PALETTE_3,
5021 LINE_PALETTE_4,
5022 LINE_PALETTE_5,
5023 LINE_PALETTE_6,
5026 #define BLAME_COLOR(i) \
5027 (blame_colors[(i) % ARRAY_SIZE(blame_colors)])
5029 if (blame->commit && *blame->commit->filename) {
5030 id = blame->commit->id;
5031 author = blame->commit->author;
5032 filename = blame->commit->filename;
5033 time = &blame->commit->time;
5034 id_type = BLAME_COLOR((long) blame->commit);
5037 if (draw_date(view, time))
5038 return TRUE;
5040 if (draw_author(view, author))
5041 return TRUE;
5043 if (draw_filename(view, filename, state->auto_filename_display))
5044 return TRUE;
5046 if (draw_field(view, id_type, id, ID_COLS, FALSE))
5047 return TRUE;
5049 if (draw_lineno(view, lineno))
5050 return TRUE;
5052 draw_text(view, LINE_DEFAULT, blame->text);
5053 return TRUE;
5056 static bool
5057 check_blame_commit(struct blame *blame, bool check_null_id)
5059 if (!blame->commit)
5060 report("Commit data not loaded yet");
5061 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
5062 report("No commit exist for the selected line");
5063 else
5064 return TRUE;
5065 return FALSE;
5068 static void
5069 setup_blame_parent_line(struct view *view, struct blame *blame)
5071 char from[SIZEOF_REF + SIZEOF_STR];
5072 char to[SIZEOF_REF + SIZEOF_STR];
5073 const char *diff_tree_argv[] = {
5074 "git", "diff", ENCODING_ARG, "--no-textconv", "--no-extdiff",
5075 "--no-color", "-U0", from, to, "--", NULL
5077 struct io io;
5078 int parent_lineno = -1;
5079 int blamed_lineno = -1;
5080 char *line;
5082 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
5083 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
5084 !io_run(&io, IO_RD, NULL, diff_tree_argv))
5085 return;
5087 while ((line = io_get(&io, '\n', TRUE))) {
5088 if (*line == '@') {
5089 char *pos = strchr(line, '+');
5091 parent_lineno = atoi(line + 4);
5092 if (pos)
5093 blamed_lineno = atoi(pos + 1);
5095 } else if (*line == '+' && parent_lineno != -1) {
5096 if (blame->lineno == blamed_lineno - 1 &&
5097 !strcmp(blame->text, line + 1)) {
5098 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
5099 break;
5101 blamed_lineno++;
5105 io_done(&io);
5108 static enum request
5109 blame_request(struct view *view, enum request request, struct line *line)
5111 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5112 struct blame *blame = line->data;
5114 switch (request) {
5115 case REQ_VIEW_BLAME:
5116 if (check_blame_commit(blame, TRUE)) {
5117 string_copy(opt_ref, blame->commit->id);
5118 string_copy(opt_file, blame->commit->filename);
5119 if (blame->lineno)
5120 view->lineno = blame->lineno;
5121 reload_view(view);
5123 break;
5125 case REQ_PARENT:
5126 if (!check_blame_commit(blame, TRUE))
5127 break;
5128 if (!*blame->commit->parent_id) {
5129 report("The selected commit has no parents");
5130 } else {
5131 string_copy_rev(opt_ref, blame->commit->parent_id);
5132 string_copy(opt_file, blame->commit->parent_filename);
5133 setup_blame_parent_line(view, blame);
5134 opt_goto_line = blame->lineno;
5135 reload_view(view);
5137 break;
5139 case REQ_ENTER:
5140 if (!check_blame_commit(blame, FALSE))
5141 break;
5143 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
5144 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
5145 break;
5147 if (!strcmp(blame->commit->id, NULL_ID)) {
5148 struct view *diff = VIEW(REQ_VIEW_DIFF);
5149 const char *diff_index_argv[] = {
5150 "git", "diff-index", ENCODING_ARG, "--root",
5151 "--patch-with-stat",
5152 "-C", "-M", opt_diff_context_arg,
5153 opt_ignore_space_arg,
5154 "HEAD", "--", view->vid, NULL
5157 if (!*blame->commit->parent_id) {
5158 diff_index_argv[1] = "diff";
5159 diff_index_argv[2] = "--no-color";
5160 diff_index_argv[8] = "--";
5161 diff_index_argv[9] = "/dev/null";
5164 open_argv(view, diff, diff_index_argv, NULL, flags);
5165 if (diff->pipe)
5166 string_copy_rev(diff->ref, NULL_ID);
5167 } else {
5168 open_view(view, REQ_VIEW_DIFF, flags);
5170 break;
5172 default:
5173 return request;
5176 return REQ_NONE;
5179 static bool
5180 blame_grep(struct view *view, struct line *line)
5182 struct blame *blame = line->data;
5183 struct blame_commit *commit = blame->commit;
5184 const char *text[] = {
5185 blame->text,
5186 commit ? commit->title : "",
5187 commit ? commit->id : "",
5188 commit && opt_author ? commit->author : "",
5189 commit ? mkdate(&commit->time, opt_date) : "",
5190 NULL
5193 return grep_text(view, text);
5196 static void
5197 blame_select(struct view *view, struct line *line)
5199 struct blame *blame = line->data;
5200 struct blame_commit *commit = blame->commit;
5202 if (!commit)
5203 return;
5205 if (!strcmp(commit->id, NULL_ID))
5206 string_ncopy(ref_commit, "HEAD", 4);
5207 else
5208 string_copy_rev(ref_commit, commit->id);
5211 static struct view_ops blame_ops = {
5212 "line",
5213 VIEW_ALWAYS_LINENO,
5214 sizeof(struct blame_state),
5215 blame_open,
5216 blame_read,
5217 blame_draw,
5218 blame_request,
5219 blame_grep,
5220 blame_select,
5224 * Branch backend
5227 struct branch {
5228 const char *author; /* Author of the last commit. */
5229 struct time time; /* Date of the last activity. */
5230 const struct ref *ref; /* Name and commit ID information. */
5233 static const struct ref branch_all;
5235 static const enum sort_field branch_sort_fields[] = {
5236 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
5238 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
5240 struct branch_state {
5241 char id[SIZEOF_REV];
5244 static int
5245 branch_compare(const void *l1, const void *l2)
5247 const struct branch *branch1 = ((const struct line *) l1)->data;
5248 const struct branch *branch2 = ((const struct line *) l2)->data;
5250 if (branch1->ref == &branch_all)
5251 return -1;
5252 else if (branch2->ref == &branch_all)
5253 return 1;
5255 switch (get_sort_field(branch_sort_state)) {
5256 case ORDERBY_DATE:
5257 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
5259 case ORDERBY_AUTHOR:
5260 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
5262 case ORDERBY_NAME:
5263 default:
5264 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
5268 static bool
5269 branch_draw(struct view *view, struct line *line, unsigned int lineno)
5271 struct branch *branch = line->data;
5272 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
5274 if (draw_date(view, &branch->time))
5275 return TRUE;
5277 if (draw_author(view, branch->author))
5278 return TRUE;
5280 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
5281 return TRUE;
5284 static enum request
5285 branch_request(struct view *view, enum request request, struct line *line)
5287 struct branch *branch = line->data;
5289 switch (request) {
5290 case REQ_REFRESH:
5291 load_refs();
5292 refresh_view(view);
5293 return REQ_NONE;
5295 case REQ_TOGGLE_SORT_FIELD:
5296 case REQ_TOGGLE_SORT_ORDER:
5297 sort_view(view, request, &branch_sort_state, branch_compare);
5298 return REQ_NONE;
5300 case REQ_ENTER:
5302 const struct ref *ref = branch->ref;
5303 const char *all_branches_argv[] = {
5304 "git", "log", ENCODING_ARG, "--no-color",
5305 "--pretty=raw", "--parents", "--topo-order",
5306 ref == &branch_all ? "--all" : ref->name, NULL
5308 struct view *main_view = VIEW(REQ_VIEW_MAIN);
5310 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
5311 return REQ_NONE;
5313 case REQ_JUMP_COMMIT:
5315 int lineno;
5317 for (lineno = 0; lineno < view->lines; lineno++) {
5318 struct branch *branch = view->line[lineno].data;
5320 if (!strncasecmp(branch->ref->id, opt_search, strlen(opt_search))) {
5321 select_view_line(view, lineno);
5322 report("");
5323 return REQ_NONE;
5327 default:
5328 return request;
5332 static bool
5333 branch_read(struct view *view, char *line)
5335 struct branch_state *state = view->private;
5336 struct branch *reference;
5337 size_t i;
5339 if (!line)
5340 return TRUE;
5342 switch (get_line_type(line)) {
5343 case LINE_COMMIT:
5344 string_copy_rev(state->id, line + STRING_SIZE("commit "));
5345 return TRUE;
5347 case LINE_AUTHOR:
5348 for (i = 0, reference = NULL; i < view->lines; i++) {
5349 struct branch *branch = view->line[i].data;
5351 if (strcmp(branch->ref->id, state->id))
5352 continue;
5354 view->line[i].dirty = TRUE;
5355 if (reference) {
5356 branch->author = reference->author;
5357 branch->time = reference->time;
5358 continue;
5361 parse_author_line(line + STRING_SIZE("author "),
5362 &branch->author, &branch->time);
5363 reference = branch;
5365 return TRUE;
5367 default:
5368 return TRUE;
5373 static bool
5374 branch_open_visitor(void *data, const struct ref *ref)
5376 struct view *view = data;
5377 struct branch *branch;
5379 if (ref->tag || ref->ltag)
5380 return TRUE;
5382 branch = calloc(1, sizeof(*branch));
5383 if (!branch)
5384 return FALSE;
5386 branch->ref = ref;
5387 return !!add_line_data(view, branch, LINE_DEFAULT);
5390 static bool
5391 branch_open(struct view *view, enum open_flags flags)
5393 const char *branch_log[] = {
5394 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw",
5395 "--simplify-by-decoration", "--all", NULL
5398 if (!begin_update(view, NULL, branch_log, flags)) {
5399 report("Failed to load branch data");
5400 return TRUE;
5403 branch_open_visitor(view, &branch_all);
5404 foreach_ref(branch_open_visitor, view);
5405 view->p_restore = TRUE;
5407 return TRUE;
5410 static bool
5411 branch_grep(struct view *view, struct line *line)
5413 struct branch *branch = line->data;
5414 const char *text[] = {
5415 branch->ref->name,
5416 mkauthor(branch->author, opt_author_cols, opt_author),
5417 NULL
5420 return grep_text(view, text);
5423 static void
5424 branch_select(struct view *view, struct line *line)
5426 struct branch *branch = line->data;
5428 string_copy_rev(view->ref, branch->ref->id);
5429 string_copy_rev(ref_commit, branch->ref->id);
5430 string_copy_rev(ref_head, branch->ref->id);
5431 string_copy_rev(ref_branch, branch->ref->name);
5434 static struct view_ops branch_ops = {
5435 "branch",
5436 VIEW_NO_FLAGS,
5437 sizeof(struct branch_state),
5438 branch_open,
5439 branch_read,
5440 branch_draw,
5441 branch_request,
5442 branch_grep,
5443 branch_select,
5447 * Status backend
5450 struct status {
5451 char status;
5452 struct {
5453 mode_t mode;
5454 char rev[SIZEOF_REV];
5455 char name[SIZEOF_STR];
5456 } old;
5457 struct {
5458 mode_t mode;
5459 char rev[SIZEOF_REV];
5460 char name[SIZEOF_STR];
5461 } new;
5464 static char status_onbranch[SIZEOF_STR];
5465 static struct status stage_status;
5466 static enum line_type stage_line_type;
5468 DEFINE_ALLOCATOR(realloc_ints, int, 32)
5470 /* This should work even for the "On branch" line. */
5471 static inline bool
5472 status_has_none(struct view *view, struct line *line)
5474 return line < view->line + view->lines && !line[1].data;
5477 /* Get fields from the diff line:
5478 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5480 static inline bool
5481 status_get_diff(struct status *file, const char *buf, size_t bufsize)
5483 const char *old_mode = buf + 1;
5484 const char *new_mode = buf + 8;
5485 const char *old_rev = buf + 15;
5486 const char *new_rev = buf + 56;
5487 const char *status = buf + 97;
5489 if (bufsize < 98 ||
5490 old_mode[-1] != ':' ||
5491 new_mode[-1] != ' ' ||
5492 old_rev[-1] != ' ' ||
5493 new_rev[-1] != ' ' ||
5494 status[-1] != ' ')
5495 return FALSE;
5497 file->status = *status;
5499 string_copy_rev(file->old.rev, old_rev);
5500 string_copy_rev(file->new.rev, new_rev);
5502 file->old.mode = strtoul(old_mode, NULL, 8);
5503 file->new.mode = strtoul(new_mode, NULL, 8);
5505 file->old.name[0] = file->new.name[0] = 0;
5507 return TRUE;
5510 static bool
5511 status_run(struct view *view, const char *argv[], char status, enum line_type type)
5513 struct status *unmerged = NULL;
5514 char *buf;
5515 struct io io;
5517 if (!io_run(&io, IO_RD, opt_cdup, argv))
5518 return FALSE;
5520 add_line_data(view, NULL, type);
5522 while ((buf = io_get(&io, 0, TRUE))) {
5523 struct status *file = unmerged;
5525 if (!file) {
5526 file = calloc(1, sizeof(*file));
5527 if (!file || !add_line_data(view, file, type))
5528 goto error_out;
5531 /* Parse diff info part. */
5532 if (status) {
5533 file->status = status;
5534 if (status == 'A')
5535 string_copy(file->old.rev, NULL_ID);
5537 } else if (!file->status || file == unmerged) {
5538 if (!status_get_diff(file, buf, strlen(buf)))
5539 goto error_out;
5541 buf = io_get(&io, 0, TRUE);
5542 if (!buf)
5543 break;
5545 /* Collapse all modified entries that follow an
5546 * associated unmerged entry. */
5547 if (unmerged == file) {
5548 unmerged->status = 'U';
5549 unmerged = NULL;
5550 } else if (file->status == 'U') {
5551 unmerged = file;
5555 /* Grab the old name for rename/copy. */
5556 if (!*file->old.name &&
5557 (file->status == 'R' || file->status == 'C')) {
5558 string_ncopy(file->old.name, buf, strlen(buf));
5560 buf = io_get(&io, 0, TRUE);
5561 if (!buf)
5562 break;
5565 /* git-ls-files just delivers a NUL separated list of
5566 * file names similar to the second half of the
5567 * git-diff-* output. */
5568 string_ncopy(file->new.name, buf, strlen(buf));
5569 if (!*file->old.name)
5570 string_copy(file->old.name, file->new.name);
5571 file = NULL;
5574 if (io_error(&io)) {
5575 error_out:
5576 io_done(&io);
5577 return FALSE;
5580 if (!view->line[view->lines - 1].data)
5581 add_line_data(view, NULL, LINE_STAT_NONE);
5583 io_done(&io);
5584 return TRUE;
5587 /* Don't show unmerged entries in the staged section. */
5588 static const char *status_diff_index_argv[] = {
5589 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
5590 "--cached", "-M", "HEAD", NULL
5593 static const char *status_diff_files_argv[] = {
5594 "git", "diff-files", "-z", NULL
5597 static const char *status_list_other_argv[] = {
5598 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
5601 static const char *status_list_no_head_argv[] = {
5602 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5605 static const char *update_index_argv[] = {
5606 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5609 /* Restore the previous line number to stay in the context or select a
5610 * line with something that can be updated. */
5611 static void
5612 status_restore(struct view *view)
5614 if (view->p_lineno >= view->lines)
5615 view->p_lineno = view->lines - 1;
5616 while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
5617 view->p_lineno++;
5618 while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
5619 view->p_lineno--;
5621 /* If the above fails, always skip the "On branch" line. */
5622 if (view->p_lineno < view->lines)
5623 view->lineno = view->p_lineno;
5624 else
5625 view->lineno = 1;
5627 if (view->lineno < view->offset)
5628 view->offset = view->lineno;
5629 else if (view->offset + view->height <= view->lineno)
5630 view->offset = view->lineno - view->height + 1;
5632 view->p_restore = FALSE;
5635 static void
5636 status_update_onbranch(void)
5638 static const char *paths[][2] = {
5639 { "rebase-apply/rebasing", "Rebasing" },
5640 { "rebase-apply/applying", "Applying mailbox" },
5641 { "rebase-apply/", "Rebasing mailbox" },
5642 { "rebase-merge/interactive", "Interactive rebase" },
5643 { "rebase-merge/", "Rebase merge" },
5644 { "MERGE_HEAD", "Merging" },
5645 { "BISECT_LOG", "Bisecting" },
5646 { "HEAD", "On branch" },
5648 char buf[SIZEOF_STR];
5649 struct stat stat;
5650 int i;
5652 if (is_initial_commit()) {
5653 string_copy(status_onbranch, "Initial commit");
5654 return;
5657 for (i = 0; i < ARRAY_SIZE(paths); i++) {
5658 char *head = opt_head;
5660 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
5661 lstat(buf, &stat) < 0)
5662 continue;
5664 if (!*opt_head) {
5665 struct io io;
5667 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
5668 io_read_buf(&io, buf, sizeof(buf))) {
5669 head = buf;
5670 if (!prefixcmp(head, "refs/heads/"))
5671 head += STRING_SIZE("refs/heads/");
5675 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
5676 string_copy(status_onbranch, opt_head);
5677 return;
5680 string_copy(status_onbranch, "Not currently on any branch");
5683 /* First parse staged info using git-diff-index(1), then parse unstaged
5684 * info using git-diff-files(1), and finally untracked files using
5685 * git-ls-files(1). */
5686 static bool
5687 status_open(struct view *view, enum open_flags flags)
5689 reset_view(view);
5691 add_line_data(view, NULL, LINE_STAT_HEAD);
5692 status_update_onbranch();
5694 io_run_bg(update_index_argv);
5696 if (is_initial_commit()) {
5697 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5698 return FALSE;
5699 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5700 return FALSE;
5703 if (!opt_untracked_dirs_content)
5704 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5706 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5707 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5708 return FALSE;
5710 /* Restore the exact position or use the specialized restore
5711 * mode? */
5712 if (!view->p_restore)
5713 status_restore(view);
5714 return TRUE;
5717 static bool
5718 status_draw(struct view *view, struct line *line, unsigned int lineno)
5720 struct status *status = line->data;
5721 enum line_type type;
5722 const char *text;
5724 if (!status) {
5725 switch (line->type) {
5726 case LINE_STAT_STAGED:
5727 type = LINE_STAT_SECTION;
5728 text = "Changes to be committed:";
5729 break;
5731 case LINE_STAT_UNSTAGED:
5732 type = LINE_STAT_SECTION;
5733 text = "Changed but not updated:";
5734 break;
5736 case LINE_STAT_UNTRACKED:
5737 type = LINE_STAT_SECTION;
5738 text = "Untracked files:";
5739 break;
5741 case LINE_STAT_NONE:
5742 type = LINE_DEFAULT;
5743 text = " (no files)";
5744 break;
5746 case LINE_STAT_HEAD:
5747 type = LINE_STAT_HEAD;
5748 text = status_onbranch;
5749 break;
5751 default:
5752 return FALSE;
5754 } else {
5755 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5757 buf[0] = status->status;
5758 if (draw_text(view, line->type, buf))
5759 return TRUE;
5760 type = LINE_DEFAULT;
5761 text = status->new.name;
5764 draw_text(view, type, text);
5765 return TRUE;
5768 static enum request
5769 status_enter(struct view *view, struct line *line)
5771 struct status *status = line->data;
5772 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5774 if (line->type == LINE_STAT_NONE ||
5775 (!status && line[1].type == LINE_STAT_NONE)) {
5776 report("No file to diff");
5777 return REQ_NONE;
5780 switch (line->type) {
5781 case LINE_STAT_STAGED:
5782 case LINE_STAT_UNSTAGED:
5783 break;
5785 case LINE_STAT_UNTRACKED:
5786 if (!status) {
5787 report("No file to show");
5788 return REQ_NONE;
5791 if (!suffixcmp(status->new.name, -1, "/")) {
5792 report("Cannot display a directory");
5793 return REQ_NONE;
5795 break;
5797 case LINE_STAT_HEAD:
5798 return REQ_NONE;
5800 default:
5801 die("line type %d not handled in switch", line->type);
5804 if (status) {
5805 stage_status = *status;
5806 } else {
5807 memset(&stage_status, 0, sizeof(stage_status));
5810 stage_line_type = line->type;
5812 open_view(view, REQ_VIEW_STAGE, flags);
5813 return REQ_NONE;
5816 static bool
5817 status_exists(struct view *view, struct status *status, enum line_type type)
5819 unsigned long lineno;
5821 for (lineno = 0; lineno < view->lines; lineno++) {
5822 struct line *line = &view->line[lineno];
5823 struct status *pos = line->data;
5825 if (line->type != type)
5826 continue;
5827 if (!pos && (!status || !status->status) && line[1].data) {
5828 select_view_line(view, lineno);
5829 return TRUE;
5831 if (pos && !strcmp(status->new.name, pos->new.name)) {
5832 select_view_line(view, lineno);
5833 return TRUE;
5837 return FALSE;
5841 static bool
5842 status_update_prepare(struct io *io, enum line_type type)
5844 const char *staged_argv[] = {
5845 "git", "update-index", "-z", "--index-info", NULL
5847 const char *others_argv[] = {
5848 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5851 switch (type) {
5852 case LINE_STAT_STAGED:
5853 return io_run(io, IO_WR, opt_cdup, staged_argv);
5855 case LINE_STAT_UNSTAGED:
5856 case LINE_STAT_UNTRACKED:
5857 return io_run(io, IO_WR, opt_cdup, others_argv);
5859 default:
5860 die("line type %d not handled in switch", type);
5861 return FALSE;
5865 static bool
5866 status_update_write(struct io *io, struct status *status, enum line_type type)
5868 switch (type) {
5869 case LINE_STAT_STAGED:
5870 return io_printf(io, "%06o %s\t%s%c", status->old.mode,
5871 status->old.rev, status->old.name, 0);
5873 case LINE_STAT_UNSTAGED:
5874 case LINE_STAT_UNTRACKED:
5875 return io_printf(io, "%s%c", status->new.name, 0);
5877 default:
5878 die("line type %d not handled in switch", type);
5879 return FALSE;
5883 static bool
5884 status_update_file(struct status *status, enum line_type type)
5886 struct io io;
5887 bool result;
5889 if (!status_update_prepare(&io, type))
5890 return FALSE;
5892 result = status_update_write(&io, status, type);
5893 return io_done(&io) && result;
5896 static bool
5897 status_update_files(struct view *view, struct line *line)
5899 char buf[sizeof(view->ref)];
5900 struct io io;
5901 bool result = TRUE;
5902 struct line *pos = view->line + view->lines;
5903 int files = 0;
5904 int file, done;
5905 int cursor_y = -1, cursor_x = -1;
5907 if (!status_update_prepare(&io, line->type))
5908 return FALSE;
5910 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5911 files++;
5913 string_copy(buf, view->ref);
5914 getsyx(cursor_y, cursor_x);
5915 for (file = 0, done = 5; result && file < files; line++, file++) {
5916 int almost_done = file * 100 / files;
5918 if (almost_done > done) {
5919 done = almost_done;
5920 string_format(view->ref, "updating file %u of %u (%d%% done)",
5921 file, files, done);
5922 update_view_title(view);
5923 setsyx(cursor_y, cursor_x);
5924 doupdate();
5926 result = status_update_write(&io, line->data, line->type);
5928 string_copy(view->ref, buf);
5930 return io_done(&io) && result;
5933 static bool
5934 status_update(struct view *view)
5936 struct line *line = &view->line[view->lineno];
5938 assert(view->lines);
5940 if (!line->data) {
5941 /* This should work even for the "On branch" line. */
5942 if (line < view->line + view->lines && !line[1].data) {
5943 report("Nothing to update");
5944 return FALSE;
5947 if (!status_update_files(view, line + 1)) {
5948 report("Failed to update file status");
5949 return FALSE;
5952 } else if (!status_update_file(line->data, line->type)) {
5953 report("Failed to update file status");
5954 return FALSE;
5957 return TRUE;
5960 static bool
5961 status_revert(struct status *status, enum line_type type, bool has_none)
5963 if (!status || type != LINE_STAT_UNSTAGED) {
5964 if (type == LINE_STAT_STAGED) {
5965 report("Cannot revert changes to staged files");
5966 } else if (type == LINE_STAT_UNTRACKED) {
5967 report("Cannot revert changes to untracked files");
5968 } else if (has_none) {
5969 report("Nothing to revert");
5970 } else {
5971 report("Cannot revert changes to multiple files");
5974 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5975 char mode[10] = "100644";
5976 const char *reset_argv[] = {
5977 "git", "update-index", "--cacheinfo", mode,
5978 status->old.rev, status->old.name, NULL
5980 const char *checkout_argv[] = {
5981 "git", "checkout", "--", status->old.name, NULL
5984 if (status->status == 'U') {
5985 string_format(mode, "%5o", status->old.mode);
5987 if (status->old.mode == 0 && status->new.mode == 0) {
5988 reset_argv[2] = "--force-remove";
5989 reset_argv[3] = status->old.name;
5990 reset_argv[4] = NULL;
5993 if (!io_run_fg(reset_argv, opt_cdup))
5994 return FALSE;
5995 if (status->old.mode == 0 && status->new.mode == 0)
5996 return TRUE;
5999 return io_run_fg(checkout_argv, opt_cdup);
6002 return FALSE;
6005 static enum request
6006 status_request(struct view *view, enum request request, struct line *line)
6008 struct status *status = line->data;
6010 switch (request) {
6011 case REQ_STATUS_UPDATE:
6012 if (!status_update(view))
6013 return REQ_NONE;
6014 break;
6016 case REQ_STATUS_REVERT:
6017 if (!status_revert(status, line->type, status_has_none(view, line)))
6018 return REQ_NONE;
6019 break;
6021 case REQ_STATUS_MERGE:
6022 if (!status || status->status != 'U') {
6023 report("Merging only possible for files with unmerged status ('U').");
6024 return REQ_NONE;
6026 open_mergetool(status->new.name);
6027 break;
6029 case REQ_EDIT:
6030 if (!status)
6031 return request;
6032 if (status->status == 'D') {
6033 report("File has been deleted.");
6034 return REQ_NONE;
6037 open_editor(status->new.name);
6038 break;
6040 case REQ_VIEW_BLAME:
6041 if (status)
6042 opt_ref[0] = 0;
6043 return request;
6045 case REQ_ENTER:
6046 /* After returning the status view has been split to
6047 * show the stage view. No further reloading is
6048 * necessary. */
6049 return status_enter(view, line);
6051 case REQ_REFRESH:
6052 /* Simply reload the view. */
6053 break;
6055 default:
6056 return request;
6059 refresh_view(view);
6061 return REQ_NONE;
6064 static void
6065 status_select(struct view *view, struct line *line)
6067 struct status *status = line->data;
6068 char file[SIZEOF_STR] = "all files";
6069 const char *text;
6070 const char *key;
6072 if (status && !string_format(file, "'%s'", status->new.name))
6073 return;
6075 if (!status && line[1].type == LINE_STAT_NONE)
6076 line++;
6078 switch (line->type) {
6079 case LINE_STAT_STAGED:
6080 text = "Press %s to unstage %s for commit";
6081 break;
6083 case LINE_STAT_UNSTAGED:
6084 text = "Press %s to stage %s for commit";
6085 break;
6087 case LINE_STAT_UNTRACKED:
6088 text = "Press %s to stage %s for addition";
6089 break;
6091 case LINE_STAT_HEAD:
6092 case LINE_STAT_NONE:
6093 text = "Nothing to update";
6094 break;
6096 default:
6097 die("line type %d not handled in switch", line->type);
6100 if (status && status->status == 'U') {
6101 text = "Press %s to resolve conflict in %s";
6102 key = get_view_key(view, REQ_STATUS_MERGE);
6104 } else {
6105 key = get_view_key(view, REQ_STATUS_UPDATE);
6108 string_format(view->ref, text, key, file);
6109 if (status)
6110 string_copy(opt_file, status->new.name);
6113 static bool
6114 status_grep(struct view *view, struct line *line)
6116 struct status *status = line->data;
6118 if (status) {
6119 const char buf[2] = { status->status, 0 };
6120 const char *text[] = { status->new.name, buf, NULL };
6122 return grep_text(view, text);
6125 return FALSE;
6128 static struct view_ops status_ops = {
6129 "file",
6130 VIEW_CUSTOM_STATUS,
6132 status_open,
6133 NULL,
6134 status_draw,
6135 status_request,
6136 status_grep,
6137 status_select,
6141 struct stage_state {
6142 struct diff_state diff;
6143 size_t chunks;
6144 int *chunk;
6147 static bool
6148 stage_diff_write(struct io *io, struct line *line, struct line *end)
6150 while (line < end) {
6151 if (!io_write(io, line->data, strlen(line->data)) ||
6152 !io_write(io, "\n", 1))
6153 return FALSE;
6154 line++;
6155 if (line->type == LINE_DIFF_CHUNK ||
6156 line->type == LINE_DIFF_HEADER)
6157 break;
6160 return TRUE;
6163 static bool
6164 stage_apply_chunk(struct view *view, struct line *chunk, struct line *line, bool revert)
6166 const char *apply_argv[SIZEOF_ARG] = {
6167 "git", "apply", "--whitespace=nowarn", NULL
6169 struct line *diff_hdr;
6170 struct io io;
6171 int argc = 3;
6173 diff_hdr = find_prev_line_by_type(view, chunk, LINE_DIFF_HEADER);
6174 if (!diff_hdr)
6175 return FALSE;
6177 if (!revert)
6178 apply_argv[argc++] = "--cached";
6179 if (line != NULL)
6180 apply_argv[argc++] = "--unidiff-zero";
6181 if (revert || stage_line_type == LINE_STAT_STAGED)
6182 apply_argv[argc++] = "-R";
6183 apply_argv[argc++] = "-";
6184 apply_argv[argc++] = NULL;
6185 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
6186 return FALSE;
6188 if (line != NULL) {
6189 int lineno = 0;
6190 struct line *context = chunk + 1;
6191 const char *markers[] = {
6192 line->type == LINE_DIFF_DEL ? "" : ",0",
6193 line->type == LINE_DIFF_DEL ? ",0" : "",
6196 parse_chunk_lineno(&lineno, chunk->data, line->type == LINE_DIFF_DEL ? '+' : '-');
6198 while (context < line) {
6199 if (context->type == LINE_DIFF_CHUNK || context->type == LINE_DIFF_HEADER) {
6200 break;
6201 } else if (context->type != LINE_DIFF_DEL && context->type != LINE_DIFF_ADD) {
6202 lineno++;
6204 context++;
6207 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6208 !io_printf(&io, "@@ -%d%s +%d%s @@\n",
6209 lineno, markers[0], lineno, markers[1]) ||
6210 !stage_diff_write(&io, line, line + 1)) {
6211 chunk = NULL;
6213 } else {
6214 if (!stage_diff_write(&io, diff_hdr, chunk) ||
6215 !stage_diff_write(&io, chunk, view->line + view->lines))
6216 chunk = NULL;
6219 io_done(&io);
6220 io_run_bg(update_index_argv);
6222 return chunk ? TRUE : FALSE;
6225 static bool
6226 stage_update(struct view *view, struct line *line, bool single)
6228 struct line *chunk = NULL;
6230 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
6231 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6233 if (chunk) {
6234 if (!stage_apply_chunk(view, chunk, single ? line : NULL, FALSE)) {
6235 report("Failed to apply chunk");
6236 return FALSE;
6239 } else if (!stage_status.status) {
6240 view = view->parent;
6242 for (line = view->line; line < view->line + view->lines; line++)
6243 if (line->type == stage_line_type)
6244 break;
6246 if (!status_update_files(view, line + 1)) {
6247 report("Failed to update files");
6248 return FALSE;
6251 } else if (!status_update_file(&stage_status, stage_line_type)) {
6252 report("Failed to update file");
6253 return FALSE;
6256 return TRUE;
6259 static bool
6260 stage_revert(struct view *view, struct line *line)
6262 struct line *chunk = NULL;
6264 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
6265 chunk = find_prev_line_by_type(view, line, LINE_DIFF_CHUNK);
6267 if (chunk) {
6268 if (!prompt_yesno("Are you sure you want to revert changes?"))
6269 return FALSE;
6271 if (!stage_apply_chunk(view, chunk, NULL, TRUE)) {
6272 report("Failed to revert chunk");
6273 return FALSE;
6275 return TRUE;
6277 } else {
6278 return status_revert(stage_status.status ? &stage_status : NULL,
6279 stage_line_type, FALSE);
6284 static void
6285 stage_next(struct view *view, struct line *line)
6287 struct stage_state *state = view->private;
6288 int i;
6290 if (!state->chunks) {
6291 for (line = view->line; line < view->line + view->lines; line++) {
6292 if (line->type != LINE_DIFF_CHUNK)
6293 continue;
6295 if (!realloc_ints(&state->chunk, state->chunks, 1)) {
6296 report("Allocation failure");
6297 return;
6300 state->chunk[state->chunks++] = line - view->line;
6304 for (i = 0; i < state->chunks; i++) {
6305 if (state->chunk[i] > view->lineno) {
6306 do_scroll_view(view, state->chunk[i] - view->lineno);
6307 report("Chunk %d of %d", i + 1, state->chunks);
6308 return;
6312 report("No next chunk found");
6315 static enum request
6316 stage_request(struct view *view, enum request request, struct line *line)
6318 switch (request) {
6319 case REQ_STATUS_UPDATE:
6320 if (!stage_update(view, line, FALSE))
6321 return REQ_NONE;
6322 break;
6324 case REQ_STATUS_REVERT:
6325 if (!stage_revert(view, line))
6326 return REQ_NONE;
6327 break;
6329 case REQ_STAGE_UPDATE_LINE:
6330 if (stage_line_type == LINE_STAT_UNTRACKED ||
6331 stage_status.status == 'A') {
6332 report("Staging single lines is not supported for new files");
6333 return REQ_NONE;
6335 if (line->type != LINE_DIFF_DEL && line->type != LINE_DIFF_ADD) {
6336 report("Please select a change to stage");
6337 return REQ_NONE;
6339 if (!stage_update(view, line, TRUE))
6340 return REQ_NONE;
6341 break;
6343 case REQ_STAGE_NEXT:
6344 if (stage_line_type == LINE_STAT_UNTRACKED) {
6345 report("File is untracked; press %s to add",
6346 get_view_key(view, REQ_STATUS_UPDATE));
6347 return REQ_NONE;
6349 stage_next(view, line);
6350 return REQ_NONE;
6352 case REQ_EDIT:
6353 if (!stage_status.new.name[0])
6354 return request;
6355 if (stage_status.status == 'D') {
6356 report("File has been deleted.");
6357 return REQ_NONE;
6360 open_editor(stage_status.new.name);
6361 break;
6363 case REQ_REFRESH:
6364 /* Reload everything ... */
6365 break;
6367 case REQ_VIEW_BLAME:
6368 if (stage_status.new.name[0]) {
6369 string_copy(opt_file, stage_status.new.name);
6370 opt_ref[0] = 0;
6372 return request;
6374 case REQ_ENTER:
6375 return diff_common_enter(view, request, line);
6377 case REQ_DIFF_CONTEXT_UP:
6378 case REQ_DIFF_CONTEXT_DOWN:
6379 if (!update_diff_context(request))
6380 return REQ_NONE;
6381 break;
6383 default:
6384 return request;
6387 refresh_view(view->parent);
6389 /* Check whether the staged entry still exists, and close the
6390 * stage view if it doesn't. */
6391 if (!status_exists(view->parent, &stage_status, stage_line_type)) {
6392 status_restore(view->parent);
6393 return REQ_VIEW_CLOSE;
6396 refresh_view(view);
6398 return REQ_NONE;
6401 static bool
6402 stage_open(struct view *view, enum open_flags flags)
6404 static const char *no_head_diff_argv[] = {
6405 "git", "diff", ENCODING_ARG, "--no-color", "--patch-with-stat",
6406 opt_diff_context_arg, opt_ignore_space_arg,
6407 "--", "/dev/null", stage_status.new.name, NULL
6409 static const char *index_show_argv[] = {
6410 "git", "diff-index", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6411 "--cached", opt_diff_context_arg, opt_ignore_space_arg,
6412 "HEAD", "--",
6413 stage_status.old.name, stage_status.new.name, NULL
6415 static const char *files_show_argv[] = {
6416 "git", "diff-files", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6417 opt_diff_context_arg, opt_ignore_space_arg, "--",
6418 stage_status.old.name, stage_status.new.name, NULL
6420 /* Diffs for unmerged entries are empty when passing the new
6421 * path, so leave out the new path. */
6422 static const char *files_unmerged_argv[] = {
6423 "git", "diff-files", ENCODING_ARG, "--root", "--patch-with-stat", "-C", "-M",
6424 opt_diff_context_arg, opt_ignore_space_arg, "--",
6425 stage_status.old.name, NULL
6427 static const char *file_argv[] = { opt_cdup, stage_status.new.name, NULL };
6428 const char **argv = NULL;
6429 const char *info;
6431 view->encoding = NULL;
6433 switch (stage_line_type) {
6434 case LINE_STAT_STAGED:
6435 if (is_initial_commit()) {
6436 argv = no_head_diff_argv;
6437 } else {
6438 argv = index_show_argv;
6440 if (stage_status.status)
6441 info = "Staged changes to %s";
6442 else
6443 info = "Staged changes";
6444 break;
6446 case LINE_STAT_UNSTAGED:
6447 if (stage_status.status != 'U')
6448 argv = files_show_argv;
6449 else
6450 argv = files_unmerged_argv;
6451 if (stage_status.status)
6452 info = "Unstaged changes to %s";
6453 else
6454 info = "Unstaged changes";
6455 break;
6457 case LINE_STAT_UNTRACKED:
6458 info = "Untracked file %s";
6459 argv = file_argv;
6460 view->encoding = get_path_encoding(stage_status.old.name, opt_encoding);
6461 break;
6463 case LINE_STAT_HEAD:
6464 default:
6465 die("line type %d not handled in switch", stage_line_type);
6468 string_format(view->ref, info, stage_status.new.name);
6469 view->vid[0] = 0;
6470 view->dir = opt_cdup;
6471 return argv_copy(&view->argv, argv)
6472 && begin_update(view, NULL, NULL, flags);
6475 static bool
6476 stage_read(struct view *view, char *data)
6478 struct stage_state *state = view->private;
6480 if (data && diff_common_read(view, data, &state->diff))
6481 return TRUE;
6483 return pager_read(view, data);
6486 static struct view_ops stage_ops = {
6487 "line",
6488 VIEW_DIFF_LIKE,
6489 sizeof(struct stage_state),
6490 stage_open,
6491 stage_read,
6492 diff_common_draw,
6493 stage_request,
6494 pager_grep,
6495 pager_select,
6500 * Revision graph
6503 static const enum line_type graph_colors[] = {
6504 LINE_PALETTE_0,
6505 LINE_PALETTE_1,
6506 LINE_PALETTE_2,
6507 LINE_PALETTE_3,
6508 LINE_PALETTE_4,
6509 LINE_PALETTE_5,
6510 LINE_PALETTE_6,
6513 static enum line_type get_graph_color(struct graph_symbol *symbol)
6515 if (symbol->commit)
6516 return LINE_GRAPH_COMMIT;
6517 assert(symbol->color < ARRAY_SIZE(graph_colors));
6518 return graph_colors[symbol->color];
6521 static bool
6522 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6524 const char *chars = graph_symbol_to_utf8(symbol);
6526 return draw_text(view, color, chars + !!first);
6529 static bool
6530 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6532 const char *chars = graph_symbol_to_ascii(symbol);
6534 return draw_text(view, color, chars + !!first);
6537 static bool
6538 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
6540 const chtype *chars = graph_symbol_to_chtype(symbol);
6542 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
6545 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
6547 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
6549 static const draw_graph_fn fns[] = {
6550 draw_graph_ascii,
6551 draw_graph_chtype,
6552 draw_graph_utf8
6554 draw_graph_fn fn = fns[opt_line_graphics];
6555 int i;
6557 for (i = 0; i < canvas->size; i++) {
6558 struct graph_symbol *symbol = &canvas->symbols[i];
6559 enum line_type color = get_graph_color(symbol);
6561 if (fn(view, symbol, color, i == 0))
6562 return TRUE;
6565 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
6569 * Main view backend
6572 struct commit {
6573 char id[SIZEOF_REV]; /* SHA1 ID. */
6574 char title[128]; /* First line of the commit message. */
6575 const char *author; /* Author of the commit. */
6576 struct time time; /* Date from the author ident. */
6577 struct ref_list *refs; /* Repository references. */
6578 struct graph_canvas graph; /* Ancestry chain graphics. */
6581 static bool
6582 main_open(struct view *view, enum open_flags flags)
6584 static const char *main_argv[] = {
6585 "git", "log", ENCODING_ARG, "--no-color", "--pretty=raw", "--parents",
6586 "--topo-order", "%(diffargs)", "%(revargs)",
6587 "--", "%(fileargs)", NULL
6590 return begin_update(view, NULL, main_argv, flags);
6593 static bool
6594 main_draw(struct view *view, struct line *line, unsigned int lineno)
6596 struct commit *commit = line->data;
6598 if (!commit->author)
6599 return FALSE;
6601 if (draw_lineno(view, lineno))
6602 return TRUE;
6604 if (draw_date(view, &commit->time))
6605 return TRUE;
6607 if (draw_author(view, commit->author))
6608 return TRUE;
6610 if (opt_rev_graph && draw_graph(view, &commit->graph))
6611 return TRUE;
6613 if (draw_refs(view, commit->refs))
6614 return TRUE;
6616 draw_text(view, LINE_DEFAULT, commit->title);
6617 return TRUE;
6620 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6621 static bool
6622 main_read(struct view *view, char *line)
6624 struct graph *graph = view->private;
6625 enum line_type type;
6626 struct commit *commit;
6628 if (!line) {
6629 if (!view->lines && !view->prev)
6630 die("No revisions match the given arguments.");
6631 if (view->lines > 0) {
6632 commit = view->line[view->lines - 1].data;
6633 view->line[view->lines - 1].dirty = 1;
6634 if (!commit->author) {
6635 view->lines--;
6636 free(commit);
6640 done_graph(graph);
6641 return TRUE;
6644 type = get_line_type(line);
6645 if (type == LINE_COMMIT) {
6646 bool is_boundary;
6648 commit = calloc(1, sizeof(struct commit));
6649 if (!commit)
6650 return FALSE;
6652 line += STRING_SIZE("commit ");
6653 is_boundary = *line == '-';
6654 if (is_boundary)
6655 line++;
6657 string_copy_rev(commit->id, line);
6658 commit->refs = get_ref_list(commit->id);
6659 add_line_data(view, commit, LINE_MAIN_COMMIT);
6660 graph_add_commit(graph, &commit->graph, commit->id, line, is_boundary);
6661 return TRUE;
6664 if (!view->lines)
6665 return TRUE;
6666 commit = view->line[view->lines - 1].data;
6668 switch (type) {
6669 case LINE_PARENT:
6670 if (!graph->has_parents)
6671 graph_add_parent(graph, line + STRING_SIZE("parent "));
6672 break;
6674 case LINE_AUTHOR:
6675 parse_author_line(line + STRING_SIZE("author "),
6676 &commit->author, &commit->time);
6677 graph_render_parents(graph);
6678 break;
6680 default:
6681 /* Fill in the commit title if it has not already been set. */
6682 if (commit->title[0])
6683 break;
6685 /* Require titles to start with a non-space character at the
6686 * offset used by git log. */
6687 if (strncmp(line, " ", 4))
6688 break;
6689 line += 4;
6690 /* Well, if the title starts with a whitespace character,
6691 * try to be forgiving. Otherwise we end up with no title. */
6692 while (isspace(*line))
6693 line++;
6694 if (*line == '\0')
6695 break;
6696 /* FIXME: More graceful handling of titles; append "..." to
6697 * shortened titles, etc. */
6699 string_expand(commit->title, sizeof(commit->title), line, 1);
6700 view->line[view->lines - 1].dirty = 1;
6703 return TRUE;
6706 static enum request
6707 main_request(struct view *view, enum request request, struct line *line)
6709 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
6711 switch (request) {
6712 case REQ_ENTER:
6713 if (view_is_displayed(view) && display[0] != view)
6714 maximize_view(view, TRUE);
6715 open_view(view, REQ_VIEW_DIFF, flags);
6716 break;
6717 case REQ_REFRESH:
6718 load_refs();
6719 refresh_view(view);
6720 break;
6722 case REQ_JUMP_COMMIT:
6724 int lineno;
6726 for (lineno = 0; lineno < view->lines; lineno++) {
6727 struct commit *commit = view->line[lineno].data;
6729 if (!strncasecmp(commit->id, opt_search, strlen(opt_search))) {
6730 select_view_line(view, lineno);
6731 report("");
6732 return REQ_NONE;
6736 report("Unable to find commit '%s'", opt_search);
6737 break;
6739 default:
6740 return request;
6743 return REQ_NONE;
6746 static bool
6747 grep_refs(struct ref_list *list, regex_t *regex)
6749 regmatch_t pmatch;
6750 size_t i;
6752 if (!opt_show_refs || !list)
6753 return FALSE;
6755 for (i = 0; i < list->size; i++) {
6756 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
6757 return TRUE;
6760 return FALSE;
6763 static bool
6764 main_grep(struct view *view, struct line *line)
6766 struct commit *commit = line->data;
6767 const char *text[] = {
6768 commit->title,
6769 mkauthor(commit->author, opt_author_cols, opt_author),
6770 mkdate(&commit->time, opt_date),
6771 NULL
6774 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
6777 static void
6778 main_select(struct view *view, struct line *line)
6780 struct commit *commit = line->data;
6782 string_copy_rev(view->ref, commit->id);
6783 string_copy_rev(ref_commit, view->ref);
6786 static struct view_ops main_ops = {
6787 "commit",
6788 VIEW_NO_FLAGS,
6789 sizeof(struct graph),
6790 main_open,
6791 main_read,
6792 main_draw,
6793 main_request,
6794 main_grep,
6795 main_select,
6800 * Status management
6803 /* Whether or not the curses interface has been initialized. */
6804 static bool cursed = FALSE;
6806 /* Terminal hacks and workarounds. */
6807 static bool use_scroll_redrawwin;
6808 static bool use_scroll_status_wclear;
6810 /* The status window is used for polling keystrokes. */
6811 static WINDOW *status_win;
6813 /* Reading from the prompt? */
6814 static bool input_mode = FALSE;
6816 static bool status_empty = FALSE;
6818 /* Update status and title window. */
6819 static void
6820 report(const char *msg, ...)
6822 struct view *view = display[current_view];
6824 if (input_mode)
6825 return;
6827 if (!view) {
6828 char buf[SIZEOF_STR];
6829 int retval;
6831 FORMAT_BUFFER(buf, sizeof(buf), msg, retval, TRUE);
6832 die("%s", buf);
6835 if (!status_empty || *msg) {
6836 va_list args;
6838 va_start(args, msg);
6840 wmove(status_win, 0, 0);
6841 if (view->has_scrolled && use_scroll_status_wclear)
6842 wclear(status_win);
6843 if (*msg) {
6844 vwprintw(status_win, msg, args);
6845 status_empty = FALSE;
6846 } else {
6847 status_empty = TRUE;
6849 wclrtoeol(status_win);
6850 wnoutrefresh(status_win);
6852 va_end(args);
6855 update_view_title(view);
6858 static void
6859 init_display(void)
6861 const char *term;
6862 int x, y;
6864 /* Initialize the curses library */
6865 if (isatty(STDIN_FILENO)) {
6866 cursed = !!initscr();
6867 opt_tty = stdin;
6868 } else {
6869 /* Leave stdin and stdout alone when acting as a pager. */
6870 opt_tty = fopen("/dev/tty", "r+");
6871 if (!opt_tty)
6872 die("Failed to open /dev/tty");
6873 cursed = !!newterm(NULL, opt_tty, opt_tty);
6876 if (!cursed)
6877 die("Failed to initialize curses");
6879 nonl(); /* Disable conversion and detect newlines from input. */
6880 cbreak(); /* Take input chars one at a time, no wait for \n */
6881 noecho(); /* Don't echo input */
6882 leaveok(stdscr, FALSE);
6884 if (has_colors())
6885 init_colors();
6887 getmaxyx(stdscr, y, x);
6888 status_win = newwin(1, x, y - 1, 0);
6889 if (!status_win)
6890 die("Failed to create status window");
6892 /* Enable keyboard mapping */
6893 keypad(status_win, TRUE);
6894 wbkgdset(status_win, get_line_attr(LINE_STATUS));
6896 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6897 set_tabsize(opt_tab_size);
6898 #else
6899 TABSIZE = opt_tab_size;
6900 #endif
6902 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6903 if (term && !strcmp(term, "gnome-terminal")) {
6904 /* In the gnome-terminal-emulator, the message from
6905 * scrolling up one line when impossible followed by
6906 * scrolling down one line causes corruption of the
6907 * status line. This is fixed by calling wclear. */
6908 use_scroll_status_wclear = TRUE;
6909 use_scroll_redrawwin = FALSE;
6911 } else if (term && !strcmp(term, "xrvt-xpm")) {
6912 /* No problems with full optimizations in xrvt-(unicode)
6913 * and aterm. */
6914 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6916 } else {
6917 /* When scrolling in (u)xterm the last line in the
6918 * scrolling direction will update slowly. */
6919 use_scroll_redrawwin = TRUE;
6920 use_scroll_status_wclear = FALSE;
6924 static int
6925 get_input(int prompt_position)
6927 struct view *view;
6928 int i, key, cursor_y, cursor_x;
6930 if (prompt_position)
6931 input_mode = TRUE;
6933 while (TRUE) {
6934 bool loading = FALSE;
6936 foreach_view (view, i) {
6937 update_view(view);
6938 if (view_is_displayed(view) && view->has_scrolled &&
6939 use_scroll_redrawwin)
6940 redrawwin(view->win);
6941 view->has_scrolled = FALSE;
6942 if (view->pipe)
6943 loading = TRUE;
6946 /* Update the cursor position. */
6947 if (prompt_position) {
6948 getbegyx(status_win, cursor_y, cursor_x);
6949 cursor_x = prompt_position;
6950 } else {
6951 view = display[current_view];
6952 getbegyx(view->win, cursor_y, cursor_x);
6953 cursor_x = view->width - 1;
6954 cursor_y += view->lineno - view->offset;
6956 setsyx(cursor_y, cursor_x);
6958 /* Refresh, accept single keystroke of input */
6959 doupdate();
6960 nodelay(status_win, loading);
6961 key = wgetch(status_win);
6963 /* wgetch() with nodelay() enabled returns ERR when
6964 * there's no input. */
6965 if (key == ERR) {
6967 } else if (key == KEY_RESIZE) {
6968 int height, width;
6970 getmaxyx(stdscr, height, width);
6972 wresize(status_win, 1, width);
6973 mvwin(status_win, height - 1, 0);
6974 wnoutrefresh(status_win);
6975 resize_display();
6976 redraw_display(TRUE);
6978 } else {
6979 input_mode = FALSE;
6980 if (key == erasechar())
6981 key = KEY_BACKSPACE;
6982 return key;
6987 static char *
6988 prompt_input(const char *prompt, input_handler handler, void *data)
6990 enum input_status status = INPUT_OK;
6991 static char buf[SIZEOF_STR];
6992 size_t pos = 0;
6994 buf[pos] = 0;
6996 while (status == INPUT_OK || status == INPUT_SKIP) {
6997 int key;
6999 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
7000 wclrtoeol(status_win);
7002 key = get_input(pos + 1);
7003 switch (key) {
7004 case KEY_RETURN:
7005 case KEY_ENTER:
7006 case '\n':
7007 status = pos ? INPUT_STOP : INPUT_CANCEL;
7008 break;
7010 case KEY_BACKSPACE:
7011 if (pos > 0)
7012 buf[--pos] = 0;
7013 else
7014 status = INPUT_CANCEL;
7015 break;
7017 case KEY_ESC:
7018 status = INPUT_CANCEL;
7019 break;
7021 default:
7022 if (pos >= sizeof(buf)) {
7023 report("Input string too long");
7024 return NULL;
7027 status = handler(data, buf, key);
7028 if (status == INPUT_OK)
7029 buf[pos++] = (char) key;
7033 /* Clear the status window */
7034 status_empty = FALSE;
7035 report("");
7037 if (status == INPUT_CANCEL)
7038 return NULL;
7040 buf[pos++] = 0;
7042 return buf;
7045 static enum input_status
7046 prompt_yesno_handler(void *data, char *buf, int c)
7048 if (c == 'y' || c == 'Y')
7049 return INPUT_STOP;
7050 if (c == 'n' || c == 'N')
7051 return INPUT_CANCEL;
7052 return INPUT_SKIP;
7055 static bool
7056 prompt_yesno(const char *prompt)
7058 char prompt2[SIZEOF_STR];
7060 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
7061 return FALSE;
7063 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
7066 static enum input_status
7067 read_prompt_handler(void *data, char *buf, int c)
7069 return isprint(c) ? INPUT_OK : INPUT_SKIP;
7072 static char *
7073 read_prompt(const char *prompt)
7075 return prompt_input(prompt, read_prompt_handler, NULL);
7078 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
7080 enum input_status status = INPUT_OK;
7081 int size = 0;
7083 while (items[size].text)
7084 size++;
7086 while (status == INPUT_OK) {
7087 const struct menu_item *item = &items[*selected];
7088 int key;
7089 int i;
7091 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
7092 prompt, *selected + 1, size);
7093 if (item->hotkey)
7094 wprintw(status_win, "[%c] ", (char) item->hotkey);
7095 wprintw(status_win, "%s", item->text);
7096 wclrtoeol(status_win);
7098 key = get_input(COLS - 1);
7099 switch (key) {
7100 case KEY_RETURN:
7101 case KEY_ENTER:
7102 case '\n':
7103 status = INPUT_STOP;
7104 break;
7106 case KEY_LEFT:
7107 case KEY_UP:
7108 *selected = *selected - 1;
7109 if (*selected < 0)
7110 *selected = size - 1;
7111 break;
7113 case KEY_RIGHT:
7114 case KEY_DOWN:
7115 *selected = (*selected + 1) % size;
7116 break;
7118 case KEY_ESC:
7119 status = INPUT_CANCEL;
7120 break;
7122 default:
7123 for (i = 0; items[i].text; i++)
7124 if (items[i].hotkey == key) {
7125 *selected = i;
7126 status = INPUT_STOP;
7127 break;
7132 /* Clear the status window */
7133 status_empty = FALSE;
7134 report("");
7136 return status != INPUT_CANCEL;
7140 * Repository properties
7143 static struct ref **refs = NULL;
7144 static size_t refs_size = 0;
7145 static struct ref *refs_head = NULL;
7147 static struct ref_list **ref_lists = NULL;
7148 static size_t ref_lists_size = 0;
7150 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
7151 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
7152 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
7154 static int
7155 compare_refs(const void *ref1_, const void *ref2_)
7157 const struct ref *ref1 = *(const struct ref **)ref1_;
7158 const struct ref *ref2 = *(const struct ref **)ref2_;
7160 if (ref1->tag != ref2->tag)
7161 return ref2->tag - ref1->tag;
7162 if (ref1->ltag != ref2->ltag)
7163 return ref2->ltag - ref1->ltag;
7164 if (ref1->head != ref2->head)
7165 return ref2->head - ref1->head;
7166 if (ref1->tracked != ref2->tracked)
7167 return ref2->tracked - ref1->tracked;
7168 if (ref1->replace != ref2->replace)
7169 return ref2->replace - ref1->replace;
7170 /* Order remotes last. */
7171 if (ref1->remote != ref2->remote)
7172 return ref1->remote - ref2->remote;
7173 return strcmp(ref1->name, ref2->name);
7176 static void
7177 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
7179 size_t i;
7181 for (i = 0; i < refs_size; i++)
7182 if (!visitor(data, refs[i]))
7183 break;
7186 static struct ref *
7187 get_ref_head()
7189 return refs_head;
7192 static struct ref_list *
7193 get_ref_list(const char *id)
7195 struct ref_list *list;
7196 size_t i;
7198 for (i = 0; i < ref_lists_size; i++)
7199 if (!strcmp(id, ref_lists[i]->id))
7200 return ref_lists[i];
7202 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
7203 return NULL;
7204 list = calloc(1, sizeof(*list));
7205 if (!list)
7206 return NULL;
7208 for (i = 0; i < refs_size; i++) {
7209 if (!strcmp(id, refs[i]->id) &&
7210 realloc_refs_list(&list->refs, list->size, 1))
7211 list->refs[list->size++] = refs[i];
7214 if (!list->refs) {
7215 free(list);
7216 return NULL;
7219 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
7220 ref_lists[ref_lists_size++] = list;
7221 return list;
7224 static int
7225 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
7227 struct ref *ref = NULL;
7228 bool tag = FALSE;
7229 bool ltag = FALSE;
7230 bool remote = FALSE;
7231 bool replace = FALSE;
7232 bool tracked = FALSE;
7233 bool head = FALSE;
7234 int from = 0, to = refs_size - 1;
7236 if (!prefixcmp(name, "refs/tags/")) {
7237 if (!suffixcmp(name, namelen, "^{}")) {
7238 namelen -= 3;
7239 name[namelen] = 0;
7240 } else {
7241 ltag = TRUE;
7244 tag = TRUE;
7245 namelen -= STRING_SIZE("refs/tags/");
7246 name += STRING_SIZE("refs/tags/");
7248 } else if (!prefixcmp(name, "refs/remotes/")) {
7249 remote = TRUE;
7250 namelen -= STRING_SIZE("refs/remotes/");
7251 name += STRING_SIZE("refs/remotes/");
7252 tracked = !strcmp(opt_remote, name);
7254 } else if (!prefixcmp(name, "refs/replace/")) {
7255 replace = TRUE;
7256 id = name + strlen("refs/replace/");
7257 idlen = namelen - strlen("refs/replace/");
7258 name = "replaced";
7259 namelen = strlen(name);
7261 } else if (!prefixcmp(name, "refs/heads/")) {
7262 namelen -= STRING_SIZE("refs/heads/");
7263 name += STRING_SIZE("refs/heads/");
7264 if (strlen(opt_head) == namelen
7265 && !strncmp(opt_head, name, namelen))
7266 return OK;
7268 } else if (!strcmp(name, "HEAD")) {
7269 head = TRUE;
7270 if (*opt_head) {
7271 namelen = strlen(opt_head);
7272 name = opt_head;
7276 /* If we are reloading or it's an annotated tag, replace the
7277 * previous SHA1 with the resolved commit id; relies on the fact
7278 * git-ls-remote lists the commit id of an annotated tag right
7279 * before the commit id it points to. */
7280 while ((from <= to) && !replace) {
7281 size_t pos = (to + from) / 2;
7282 int cmp = strcmp(name, refs[pos]->name);
7284 if (!cmp) {
7285 ref = refs[pos];
7286 break;
7289 if (cmp < 0)
7290 to = pos - 1;
7291 else
7292 from = pos + 1;
7295 if (!ref) {
7296 if (!realloc_refs(&refs, refs_size, 1))
7297 return ERR;
7298 ref = calloc(1, sizeof(*ref) + namelen);
7299 if (!ref)
7300 return ERR;
7301 memmove(refs + from + 1, refs + from,
7302 (refs_size - from) * sizeof(*refs));
7303 refs[from] = ref;
7304 strncpy(ref->name, name, namelen);
7305 refs_size++;
7308 ref->head = head;
7309 ref->tag = tag;
7310 ref->ltag = ltag;
7311 ref->remote = remote;
7312 ref->replace = replace;
7313 ref->tracked = tracked;
7314 string_copy_rev(ref->id, id);
7316 if (head)
7317 refs_head = ref;
7318 return OK;
7321 static int
7322 load_refs(void)
7324 const char *head_argv[] = {
7325 "git", "symbolic-ref", "HEAD", NULL
7327 static const char *ls_remote_argv[SIZEOF_ARG] = {
7328 "git", "ls-remote", opt_git_dir, NULL
7330 static bool init = FALSE;
7331 size_t i;
7333 if (!init) {
7334 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
7335 die("TIG_LS_REMOTE contains too many arguments");
7336 init = TRUE;
7339 if (!*opt_git_dir)
7340 return OK;
7342 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
7343 !prefixcmp(opt_head, "refs/heads/")) {
7344 char *offset = opt_head + STRING_SIZE("refs/heads/");
7346 memmove(opt_head, offset, strlen(offset) + 1);
7349 refs_head = NULL;
7350 for (i = 0; i < refs_size; i++)
7351 refs[i]->id[0] = 0;
7353 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
7354 return ERR;
7356 /* Update the ref lists to reflect changes. */
7357 for (i = 0; i < ref_lists_size; i++) {
7358 struct ref_list *list = ref_lists[i];
7359 size_t old, new;
7361 for (old = new = 0; old < list->size; old++)
7362 if (!strcmp(list->id, list->refs[old]->id))
7363 list->refs[new++] = list->refs[old];
7364 list->size = new;
7367 qsort(refs, refs_size, sizeof(*refs), compare_refs);
7369 return OK;
7372 static void
7373 set_remote_branch(const char *name, const char *value, size_t valuelen)
7375 if (!strcmp(name, ".remote")) {
7376 string_ncopy(opt_remote, value, valuelen);
7378 } else if (*opt_remote && !strcmp(name, ".merge")) {
7379 size_t from = strlen(opt_remote);
7381 if (!prefixcmp(value, "refs/heads/"))
7382 value += STRING_SIZE("refs/heads/");
7384 if (!string_format_from(opt_remote, &from, "/%s", value))
7385 opt_remote[0] = 0;
7389 static void
7390 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
7392 const char *argv[SIZEOF_ARG] = { name, "=" };
7393 int argc = 1 + (cmd == option_set_command);
7394 enum option_code error;
7396 if (!argv_from_string(argv, &argc, value))
7397 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
7398 else
7399 error = cmd(argc, argv);
7401 if (error != OPT_OK)
7402 warn("Option 'tig.%s': %s", name, option_errors[error]);
7405 static bool
7406 set_environment_variable(const char *name, const char *value)
7408 size_t len = strlen(name) + 1 + strlen(value) + 1;
7409 char *env = malloc(len);
7411 if (env &&
7412 string_nformat(env, len, NULL, "%s=%s", name, value) &&
7413 putenv(env) == 0)
7414 return TRUE;
7415 free(env);
7416 return FALSE;
7419 static void
7420 set_work_tree(const char *value)
7422 char cwd[SIZEOF_STR];
7424 if (!getcwd(cwd, sizeof(cwd)))
7425 die("Failed to get cwd path: %s", strerror(errno));
7426 if (chdir(opt_git_dir) < 0)
7427 die("Failed to chdir(%s): %s", strerror(errno));
7428 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
7429 die("Failed to get git path: %s", strerror(errno));
7430 if (chdir(cwd) < 0)
7431 die("Failed to chdir(%s): %s", cwd, strerror(errno));
7432 if (chdir(value) < 0)
7433 die("Failed to chdir(%s): %s", value, strerror(errno));
7434 if (!getcwd(cwd, sizeof(cwd)))
7435 die("Failed to get cwd path: %s", strerror(errno));
7436 if (!set_environment_variable("GIT_WORK_TREE", cwd))
7437 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
7438 if (!set_environment_variable("GIT_DIR", opt_git_dir))
7439 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
7440 opt_is_inside_work_tree = TRUE;
7443 static int
7444 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7446 if (!strcmp(name, "gui.encoding"))
7447 parse_encoding(&opt_encoding, value, TRUE);
7449 else if (!strcmp(name, "core.editor"))
7450 string_ncopy(opt_editor, value, valuelen);
7452 else if (!strcmp(name, "core.worktree"))
7453 set_work_tree(value);
7455 else if (!prefixcmp(name, "tig.color."))
7456 set_repo_config_option(name + 10, value, option_color_command);
7458 else if (!prefixcmp(name, "tig.bind."))
7459 set_repo_config_option(name + 9, value, option_bind_command);
7461 else if (!prefixcmp(name, "tig."))
7462 set_repo_config_option(name + 4, value, option_set_command);
7464 else if (*opt_head && !prefixcmp(name, "branch.") &&
7465 !strncmp(name + 7, opt_head, strlen(opt_head)))
7466 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
7468 return OK;
7471 static int
7472 load_git_config(void)
7474 const char *config_list_argv[] = { "git", "config", "--list", NULL };
7476 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
7479 static int
7480 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7482 if (!opt_git_dir[0]) {
7483 string_ncopy(opt_git_dir, name, namelen);
7485 } else if (opt_is_inside_work_tree == -1) {
7486 /* This can be 3 different values depending on the
7487 * version of git being used. If git-rev-parse does not
7488 * understand --is-inside-work-tree it will simply echo
7489 * the option else either "true" or "false" is printed.
7490 * Default to true for the unknown case. */
7491 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
7493 } else if (*name == '.') {
7494 string_ncopy(opt_cdup, name, namelen);
7496 } else {
7497 string_ncopy(opt_prefix, name, namelen);
7500 return OK;
7503 static int
7504 load_repo_info(void)
7506 const char *rev_parse_argv[] = {
7507 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7508 "--show-cdup", "--show-prefix", NULL
7511 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
7516 * Main
7519 static const char usage[] =
7520 "tig " TIG_VERSION " (" __DATE__ ")\n"
7521 "\n"
7522 "Usage: tig [options] [revs] [--] [paths]\n"
7523 " or: tig show [options] [revs] [--] [paths]\n"
7524 " or: tig blame [options] [rev] [--] path\n"
7525 " or: tig status\n"
7526 " or: tig < [git command output]\n"
7527 "\n"
7528 "Options:\n"
7529 " +<number> Select line <number> in the first view\n"
7530 " -v, --version Show version and exit\n"
7531 " -h, --help Show help message and exit";
7533 static void __NORETURN
7534 quit(int sig)
7536 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7537 if (cursed)
7538 endwin();
7539 exit(0);
7542 static void __NORETURN
7543 die(const char *err, ...)
7545 va_list args;
7547 endwin();
7549 va_start(args, err);
7550 fputs("tig: ", stderr);
7551 vfprintf(stderr, err, args);
7552 fputs("\n", stderr);
7553 va_end(args);
7555 exit(1);
7558 static void
7559 warn(const char *msg, ...)
7561 va_list args;
7563 va_start(args, msg);
7564 fputs("tig warning: ", stderr);
7565 vfprintf(stderr, msg, args);
7566 fputs("\n", stderr);
7567 va_end(args);
7570 static int
7571 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
7573 const char ***filter_args = data;
7575 return argv_append(filter_args, name) ? OK : ERR;
7578 static void
7579 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
7581 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
7582 const char **all_argv = NULL;
7584 if (!argv_append_array(&all_argv, rev_parse_argv) ||
7585 !argv_append_array(&all_argv, argv) ||
7586 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
7587 die("Failed to split arguments");
7588 argv_free(all_argv);
7589 free(all_argv);
7592 static void
7593 filter_options(const char *argv[], bool blame)
7595 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
7597 if (blame)
7598 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv);
7599 else
7600 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
7602 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
7605 static enum request
7606 parse_options(int argc, const char *argv[])
7608 enum request request = REQ_VIEW_MAIN;
7609 const char *subcommand;
7610 bool seen_dashdash = FALSE;
7611 const char **filter_argv = NULL;
7612 int i;
7614 if (!isatty(STDIN_FILENO))
7615 return REQ_VIEW_PAGER;
7617 if (argc <= 1)
7618 return REQ_VIEW_MAIN;
7620 subcommand = argv[1];
7621 if (!strcmp(subcommand, "status")) {
7622 if (argc > 2)
7623 warn("ignoring arguments after `%s'", subcommand);
7624 return REQ_VIEW_STATUS;
7626 } else if (!strcmp(subcommand, "blame")) {
7627 request = REQ_VIEW_BLAME;
7629 } else if (!strcmp(subcommand, "show")) {
7630 request = REQ_VIEW_DIFF;
7632 } else {
7633 subcommand = NULL;
7636 for (i = 1 + !!subcommand; i < argc; i++) {
7637 const char *opt = argv[i];
7639 // stop parsing our options after -- and let rev-parse handle the rest
7640 if (!seen_dashdash) {
7641 if (!strcmp(opt, "--")) {
7642 seen_dashdash = TRUE;
7643 continue;
7645 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
7646 printf("tig version %s\n", TIG_VERSION);
7647 quit(0);
7649 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
7650 printf("%s\n", usage);
7651 quit(0);
7653 } else if (strlen(opt) >= 2 && *opt == '+' && string_isnumber(opt + 1)) {
7654 opt_lineno = atoi(opt + 1);
7655 continue;
7660 if (!argv_append(&filter_argv, opt))
7661 die("command too long");
7664 if (filter_argv)
7665 filter_options(filter_argv, request == REQ_VIEW_BLAME);
7667 /* Finish validating and setting up blame options */
7668 if (request == REQ_VIEW_BLAME) {
7669 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
7670 die("invalid number of options to blame\n\n%s", usage);
7672 if (opt_rev_argv) {
7673 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
7676 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
7679 return request;
7683 main(int argc, const char *argv[])
7685 const char *codeset = ENCODING_UTF8;
7686 enum request request = parse_options(argc, argv);
7687 struct view *view;
7689 signal(SIGINT, quit);
7690 signal(SIGPIPE, SIG_IGN);
7692 if (setlocale(LC_ALL, "")) {
7693 codeset = nl_langinfo(CODESET);
7696 if (load_repo_info() == ERR)
7697 die("Failed to load repo info.");
7699 if (load_options() == ERR)
7700 die("Failed to load user config.");
7702 if (load_git_config() == ERR)
7703 die("Failed to load repo config.");
7705 /* Require a git repository unless when running in pager mode. */
7706 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
7707 die("Not a git repository");
7709 if (codeset && strcmp(codeset, ENCODING_UTF8)) {
7710 char translit[SIZEOF_STR];
7712 if (string_format(translit, "%s%s", codeset, ICONV_TRANSLIT))
7713 opt_iconv_out = iconv_open(translit, ENCODING_UTF8);
7714 else
7715 opt_iconv_out = iconv_open(codeset, ENCODING_UTF8);
7716 if (opt_iconv_out == ICONV_NONE)
7717 die("Failed to initialize character set conversion");
7720 if (load_refs() == ERR)
7721 die("Failed to load refs.");
7723 init_display();
7725 while (view_driver(display[current_view], request)) {
7726 int key = get_input(0);
7728 view = display[current_view];
7729 request = get_keybinding(view->keymap, key);
7731 /* Some low-level request handling. This keeps access to
7732 * status_win restricted. */
7733 switch (request) {
7734 case REQ_NONE:
7735 report("Unknown key, press %s for help",
7736 get_view_key(view, REQ_VIEW_HELP));
7737 break;
7738 case REQ_PROMPT:
7740 char *cmd = read_prompt(":");
7742 if (cmd && string_isnumber(cmd)) {
7743 int lineno = view->lineno + 1;
7745 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
7746 select_view_line(view, lineno - 1);
7747 report("");
7748 } else {
7749 report("Unable to parse '%s' as a line number", cmd);
7751 } else if (cmd && iscommit(cmd)) {
7752 string_ncopy(opt_search, cmd, strlen(cmd));
7754 request = view_request(view, REQ_JUMP_COMMIT);
7755 if (request == REQ_JUMP_COMMIT) {
7756 report("Jumping to commits is not supported by the '%s' view", view->name);
7759 } else if (cmd) {
7760 struct view *next = VIEW(REQ_VIEW_PAGER);
7761 const char *argv[SIZEOF_ARG] = { "git" };
7762 int argc = 1;
7764 /* When running random commands, initially show the
7765 * command in the title. However, it maybe later be
7766 * overwritten if a commit line is selected. */
7767 string_ncopy(next->ref, cmd, strlen(cmd));
7769 if (!argv_from_string(argv, &argc, cmd)) {
7770 report("Too many arguments");
7771 } else if (!format_argv(&next->argv, argv, FALSE)) {
7772 report("Argument formatting failed");
7773 } else {
7774 next->dir = NULL;
7775 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
7779 request = REQ_NONE;
7780 break;
7782 case REQ_SEARCH:
7783 case REQ_SEARCH_BACK:
7785 const char *prompt = request == REQ_SEARCH ? "/" : "?";
7786 char *search = read_prompt(prompt);
7788 if (search)
7789 string_ncopy(opt_search, search, strlen(search));
7790 else if (*opt_search)
7791 request = request == REQ_SEARCH ?
7792 REQ_FIND_NEXT :
7793 REQ_FIND_PREV;
7794 else
7795 request = REQ_NONE;
7796 break;
7798 default:
7799 break;
7803 quit(0);
7805 return 0;