Show remotes in branch view
[tig.git] / tig.c
blobff7c0b2663f2efa83b45c6487aea6b92f4313c7e
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 tracked:1; /* Is it the remote for the current HEAD? */
30 char name[1]; /* Ref name; tag or head names are shortened. */
33 struct ref_list {
34 char id[SIZEOF_REV]; /* Commit SHA1 ID */
35 size_t size; /* Number of refs. */
36 struct ref **refs; /* References for this ID. */
39 static struct ref *get_ref_head();
40 static struct ref_list *get_ref_list(const char *id);
41 static void foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data);
42 static int load_refs(void);
44 enum input_status {
45 INPUT_OK,
46 INPUT_SKIP,
47 INPUT_STOP,
48 INPUT_CANCEL
51 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
53 static char *prompt_input(const char *prompt, input_handler handler, void *data);
54 static bool prompt_yesno(const char *prompt);
56 struct menu_item {
57 int hotkey;
58 const char *text;
59 void *data;
62 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
64 #define GRAPHIC_ENUM(_) \
65 _(GRAPHIC, ASCII), \
66 _(GRAPHIC, DEFAULT), \
67 _(GRAPHIC, UTF_8)
69 DEFINE_ENUM(graphic, GRAPHIC_ENUM);
71 #define DATE_ENUM(_) \
72 _(DATE, NO), \
73 _(DATE, DEFAULT), \
74 _(DATE, LOCAL), \
75 _(DATE, RELATIVE), \
76 _(DATE, SHORT)
78 DEFINE_ENUM(date, DATE_ENUM);
80 struct time {
81 time_t sec;
82 int tz;
85 static inline int timecmp(const struct time *t1, const struct time *t2)
87 return t1->sec - t2->sec;
90 static const char *
91 mkdate(const struct time *time, enum date date)
93 static char buf[DATE_COLS + 1];
94 static const struct enum_map reldate[] = {
95 { "second", 1, 60 * 2 },
96 { "minute", 60, 60 * 60 * 2 },
97 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
98 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
99 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
100 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 30 * 12 },
102 struct tm tm;
104 if (!date || !time || !time->sec)
105 return "";
107 if (date == DATE_RELATIVE) {
108 struct timeval now;
109 time_t date = time->sec + time->tz;
110 time_t seconds;
111 int i;
113 gettimeofday(&now, NULL);
114 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
115 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
116 if (seconds >= reldate[i].value)
117 continue;
119 seconds /= reldate[i].namelen;
120 if (!string_format(buf, "%ld %s%s %s",
121 seconds, reldate[i].name,
122 seconds > 1 ? "s" : "",
123 now.tv_sec >= date ? "ago" : "ahead"))
124 break;
125 return buf;
129 if (date == DATE_LOCAL) {
130 time_t date = time->sec + time->tz;
131 localtime_r(&date, &tm);
133 else {
134 gmtime_r(&time->sec, &tm);
136 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
140 #define AUTHOR_ENUM(_) \
141 _(AUTHOR, NO), \
142 _(AUTHOR, FULL), \
143 _(AUTHOR, ABBREVIATED)
145 DEFINE_ENUM(author, AUTHOR_ENUM);
147 static const char *
148 get_author_initials(const char *author)
150 static char initials[AUTHOR_COLS * 6 + 1];
151 size_t pos = 0;
152 const char *end = strchr(author, '\0');
154 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
156 memset(initials, 0, sizeof(initials));
157 while (author < end) {
158 unsigned char bytes;
159 size_t i;
161 while (author < end && is_initial_sep(*author))
162 author++;
164 bytes = utf8_char_length(author, end);
165 if (bytes >= sizeof(initials) - 1 - pos)
166 break;
167 while (bytes--) {
168 initials[pos++] = *author++;
171 i = pos;
172 while (author < end && !is_initial_sep(*author)) {
173 bytes = utf8_char_length(author, end);
174 if (bytes >= sizeof(initials) - 1 - i) {
175 while (author < end && !is_initial_sep(*author))
176 author++;
177 break;
179 while (bytes--) {
180 initials[i++] = *author++;
184 initials[i++] = 0;
187 return initials;
190 #define author_trim(cols) (cols == 0 || cols > 5)
192 static const char *
193 mkauthor(const char *text, int cols, enum author author)
195 bool trim = author_trim(cols);
196 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
198 if (author == AUTHOR_NO)
199 return "";
200 if (abbreviate && text)
201 return get_author_initials(text);
202 return text;
205 static const char *
206 mkmode(mode_t mode)
208 if (S_ISDIR(mode))
209 return "drwxr-xr-x";
210 else if (S_ISLNK(mode))
211 return "lrwxrwxrwx";
212 else if (S_ISGITLINK(mode))
213 return "m---------";
214 else if (S_ISREG(mode) && mode & S_IXUSR)
215 return "-rwxr-xr-x";
216 else if (S_ISREG(mode))
217 return "-rw-r--r--";
218 else
219 return "----------";
224 * User requests
227 #define REQ_INFO \
228 /* XXX: Keep the view request first and in sync with views[]. */ \
229 REQ_GROUP("View switching") \
230 REQ_(VIEW_MAIN, "Show main view"), \
231 REQ_(VIEW_DIFF, "Show diff view"), \
232 REQ_(VIEW_LOG, "Show log view"), \
233 REQ_(VIEW_TREE, "Show tree view"), \
234 REQ_(VIEW_BLOB, "Show blob view"), \
235 REQ_(VIEW_BLAME, "Show blame view"), \
236 REQ_(VIEW_BRANCH, "Show branch view"), \
237 REQ_(VIEW_HELP, "Show help page"), \
238 REQ_(VIEW_PAGER, "Show pager view"), \
239 REQ_(VIEW_STATUS, "Show status view"), \
240 REQ_(VIEW_STAGE, "Show stage view"), \
242 REQ_GROUP("View manipulation") \
243 REQ_(ENTER, "Enter current line and scroll"), \
244 REQ_(NEXT, "Move to next"), \
245 REQ_(PREVIOUS, "Move to previous"), \
246 REQ_(PARENT, "Move to parent"), \
247 REQ_(VIEW_NEXT, "Move focus to next view"), \
248 REQ_(REFRESH, "Reload and refresh"), \
249 REQ_(MAXIMIZE, "Maximize the current view"), \
250 REQ_(VIEW_CLOSE, "Close the current view"), \
251 REQ_(QUIT, "Close all views and quit"), \
253 REQ_GROUP("View specific requests") \
254 REQ_(STATUS_UPDATE, "Update file status"), \
255 REQ_(STATUS_REVERT, "Revert file changes"), \
256 REQ_(STATUS_MERGE, "Merge file using external tool"), \
257 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
259 REQ_GROUP("Cursor navigation") \
260 REQ_(MOVE_UP, "Move cursor one line up"), \
261 REQ_(MOVE_DOWN, "Move cursor one line down"), \
262 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
263 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
264 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
265 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
267 REQ_GROUP("Scrolling") \
268 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
269 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
270 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
271 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
272 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
273 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
274 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
276 REQ_GROUP("Searching") \
277 REQ_(SEARCH, "Search the view"), \
278 REQ_(SEARCH_BACK, "Search backwards in the view"), \
279 REQ_(FIND_NEXT, "Find next search match"), \
280 REQ_(FIND_PREV, "Find previous search match"), \
282 REQ_GROUP("Option manipulation") \
283 REQ_(OPTIONS, "Open option menu"), \
284 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
285 REQ_(TOGGLE_DATE, "Toggle date display"), \
286 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
287 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
288 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
289 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
290 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
291 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
293 REQ_GROUP("Misc") \
294 REQ_(PROMPT, "Bring up the prompt"), \
295 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
296 REQ_(SHOW_VERSION, "Show version information"), \
297 REQ_(STOP_LOADING, "Stop all loading views"), \
298 REQ_(EDIT, "Open in editor"), \
299 REQ_(NONE, "Do nothing")
302 /* User action requests. */
303 enum request {
304 #define REQ_GROUP(help)
305 #define REQ_(req, help) REQ_##req
307 /* Offset all requests to avoid conflicts with ncurses getch values. */
308 REQ_UNKNOWN = KEY_MAX + 1,
309 REQ_OFFSET,
310 REQ_INFO
312 #undef REQ_GROUP
313 #undef REQ_
316 struct request_info {
317 enum request request;
318 const char *name;
319 int namelen;
320 const char *help;
323 static const struct request_info req_info[] = {
324 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
325 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
326 REQ_INFO
327 #undef REQ_GROUP
328 #undef REQ_
331 static enum request
332 get_request(const char *name)
334 int namelen = strlen(name);
335 int i;
337 for (i = 0; i < ARRAY_SIZE(req_info); i++)
338 if (enum_equals(req_info[i], name, namelen))
339 return req_info[i].request;
341 return REQ_UNKNOWN;
346 * Options
349 /* Option and state variables. */
350 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
351 static enum date opt_date = DATE_DEFAULT;
352 static enum author opt_author = AUTHOR_FULL;
353 static bool opt_rev_graph = TRUE;
354 static bool opt_line_number = FALSE;
355 static bool opt_show_refs = TRUE;
356 static bool opt_untracked_dirs_content = TRUE;
357 static int opt_num_interval = 5;
358 static double opt_hscroll = 0.50;
359 static double opt_scale_split_view = 2.0 / 3.0;
360 static int opt_tab_size = 8;
361 static int opt_author_cols = AUTHOR_COLS;
362 static char opt_path[SIZEOF_STR] = "";
363 static char opt_file[SIZEOF_STR] = "";
364 static char opt_ref[SIZEOF_REF] = "";
365 static char opt_head[SIZEOF_REF] = "";
366 static char opt_remote[SIZEOF_REF] = "";
367 static char opt_encoding[20] = "UTF-8";
368 static iconv_t opt_iconv_in = ICONV_NONE;
369 static iconv_t opt_iconv_out = ICONV_NONE;
370 static char opt_search[SIZEOF_STR] = "";
371 static char opt_cdup[SIZEOF_STR] = "";
372 static char opt_prefix[SIZEOF_STR] = "";
373 static char opt_git_dir[SIZEOF_STR] = "";
374 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
375 static char opt_editor[SIZEOF_STR] = "";
376 static FILE *opt_tty = NULL;
377 static const char **opt_diff_argv = NULL;
378 static const char **opt_rev_argv = NULL;
379 static const char **opt_file_argv = NULL;
380 static const char **opt_blame_argv = NULL;
382 #define is_initial_commit() (!get_ref_head())
383 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
387 * Line-oriented content detection.
390 #define LINE_INFO \
391 LINE(DIFF_HEADER, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
392 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
393 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
394 LINE(DIFF_ADD2, " +", COLOR_GREEN, COLOR_DEFAULT, 0), \
395 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
396 LINE(DIFF_DEL2, " -", COLOR_RED, COLOR_DEFAULT, 0), \
397 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
398 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
399 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
400 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
401 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
402 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
403 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
404 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
405 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
406 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
407 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
408 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
409 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
410 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
411 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
412 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
413 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
414 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
415 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
416 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
417 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
418 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
419 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
420 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
421 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
422 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
423 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
424 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
425 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
426 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
427 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
428 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
429 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
430 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
431 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
432 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
433 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
434 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
435 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
436 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
437 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
438 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
439 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
440 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
441 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
442 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
443 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
444 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
445 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
446 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
447 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
448 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
449 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
450 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
451 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
452 LINE(GRAPH_LINE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
453 LINE(GRAPH_LINE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
454 LINE(GRAPH_LINE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
455 LINE(GRAPH_LINE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
456 LINE(GRAPH_LINE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
457 LINE(GRAPH_LINE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
458 LINE(GRAPH_LINE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
459 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
461 enum line_type {
462 #define LINE(type, line, fg, bg, attr) \
463 LINE_##type
464 LINE_INFO,
465 LINE_NONE
466 #undef LINE
469 struct line_info {
470 const char *name; /* Option name. */
471 int namelen; /* Size of option name. */
472 const char *line; /* The start of line to match. */
473 int linelen; /* Size of string to match. */
474 int fg, bg, attr; /* Color and text attributes for the lines. */
477 static struct line_info line_info[] = {
478 #define LINE(type, line, fg, bg, attr) \
479 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
480 LINE_INFO
481 #undef LINE
484 static enum line_type
485 get_line_type(const char *line)
487 int linelen = strlen(line);
488 enum line_type type;
490 for (type = 0; type < ARRAY_SIZE(line_info); type++)
491 /* Case insensitive search matches Signed-off-by lines better. */
492 if (linelen >= line_info[type].linelen &&
493 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
494 return type;
496 return LINE_DEFAULT;
499 static enum line_type
500 get_line_type_from_ref(const struct ref *ref)
502 if (ref->head)
503 return LINE_MAIN_HEAD;
504 else if (ref->ltag)
505 return LINE_MAIN_LOCAL_TAG;
506 else if (ref->tag)
507 return LINE_MAIN_TAG;
508 else if (ref->tracked)
509 return LINE_MAIN_TRACKED;
510 else if (ref->remote)
511 return LINE_MAIN_REMOTE;
513 return LINE_MAIN_REF;
516 static inline int
517 get_line_attr(enum line_type type)
519 assert(type < ARRAY_SIZE(line_info));
520 return COLOR_PAIR(type) | line_info[type].attr;
523 static struct line_info *
524 get_line_info(const char *name)
526 size_t namelen = strlen(name);
527 enum line_type type;
529 for (type = 0; type < ARRAY_SIZE(line_info); type++)
530 if (enum_equals(line_info[type], name, namelen))
531 return &line_info[type];
533 return NULL;
536 static void
537 init_colors(void)
539 int default_bg = line_info[LINE_DEFAULT].bg;
540 int default_fg = line_info[LINE_DEFAULT].fg;
541 enum line_type type;
543 start_color();
545 if (assume_default_colors(default_fg, default_bg) == ERR) {
546 default_bg = COLOR_BLACK;
547 default_fg = COLOR_WHITE;
550 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
551 struct line_info *info = &line_info[type];
552 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
553 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
555 init_pair(type, fg, bg);
559 struct line {
560 enum line_type type;
562 /* State flags */
563 unsigned int selected:1;
564 unsigned int dirty:1;
565 unsigned int cleareol:1;
566 unsigned int other:16;
568 void *data; /* User data */
573 * Keys
576 struct keybinding {
577 int alias;
578 enum request request;
581 static struct keybinding default_keybindings[] = {
582 /* View switching */
583 { 'm', REQ_VIEW_MAIN },
584 { 'd', REQ_VIEW_DIFF },
585 { 'l', REQ_VIEW_LOG },
586 { 't', REQ_VIEW_TREE },
587 { 'f', REQ_VIEW_BLOB },
588 { 'B', REQ_VIEW_BLAME },
589 { 'H', REQ_VIEW_BRANCH },
590 { 'p', REQ_VIEW_PAGER },
591 { 'h', REQ_VIEW_HELP },
592 { 'S', REQ_VIEW_STATUS },
593 { 'c', REQ_VIEW_STAGE },
595 /* View manipulation */
596 { 'q', REQ_VIEW_CLOSE },
597 { KEY_TAB, REQ_VIEW_NEXT },
598 { KEY_RETURN, REQ_ENTER },
599 { KEY_UP, REQ_PREVIOUS },
600 { KEY_CTL('P'), REQ_PREVIOUS },
601 { KEY_DOWN, REQ_NEXT },
602 { KEY_CTL('N'), REQ_NEXT },
603 { 'R', REQ_REFRESH },
604 { KEY_F(5), REQ_REFRESH },
605 { 'O', REQ_MAXIMIZE },
607 /* Cursor navigation */
608 { 'k', REQ_MOVE_UP },
609 { 'j', REQ_MOVE_DOWN },
610 { KEY_HOME, REQ_MOVE_FIRST_LINE },
611 { KEY_END, REQ_MOVE_LAST_LINE },
612 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
613 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
614 { ' ', REQ_MOVE_PAGE_DOWN },
615 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
616 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
617 { 'b', REQ_MOVE_PAGE_UP },
618 { '-', REQ_MOVE_PAGE_UP },
620 /* Scrolling */
621 { '|', REQ_SCROLL_FIRST_COL },
622 { KEY_LEFT, REQ_SCROLL_LEFT },
623 { KEY_RIGHT, REQ_SCROLL_RIGHT },
624 { KEY_IC, REQ_SCROLL_LINE_UP },
625 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
626 { KEY_DC, REQ_SCROLL_LINE_DOWN },
627 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
628 { 'w', REQ_SCROLL_PAGE_UP },
629 { 's', REQ_SCROLL_PAGE_DOWN },
631 /* Searching */
632 { '/', REQ_SEARCH },
633 { '?', REQ_SEARCH_BACK },
634 { 'n', REQ_FIND_NEXT },
635 { 'N', REQ_FIND_PREV },
637 /* Misc */
638 { 'Q', REQ_QUIT },
639 { 'z', REQ_STOP_LOADING },
640 { 'v', REQ_SHOW_VERSION },
641 { 'r', REQ_SCREEN_REDRAW },
642 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
643 { 'o', REQ_OPTIONS },
644 { '.', REQ_TOGGLE_LINENO },
645 { 'D', REQ_TOGGLE_DATE },
646 { 'A', REQ_TOGGLE_AUTHOR },
647 { 'g', REQ_TOGGLE_REV_GRAPH },
648 { '~', REQ_TOGGLE_GRAPHIC },
649 { 'F', REQ_TOGGLE_REFS },
650 { 'I', REQ_TOGGLE_SORT_ORDER },
651 { 'i', REQ_TOGGLE_SORT_FIELD },
652 { ':', REQ_PROMPT },
653 { 'u', REQ_STATUS_UPDATE },
654 { '!', REQ_STATUS_REVERT },
655 { 'M', REQ_STATUS_MERGE },
656 { '@', REQ_STAGE_NEXT },
657 { ',', REQ_PARENT },
658 { 'e', REQ_EDIT },
661 #define KEYMAP_ENUM(_) \
662 _(KEYMAP, GENERIC), \
663 _(KEYMAP, MAIN), \
664 _(KEYMAP, DIFF), \
665 _(KEYMAP, LOG), \
666 _(KEYMAP, TREE), \
667 _(KEYMAP, BLOB), \
668 _(KEYMAP, BLAME), \
669 _(KEYMAP, BRANCH), \
670 _(KEYMAP, PAGER), \
671 _(KEYMAP, HELP), \
672 _(KEYMAP, STATUS), \
673 _(KEYMAP, STAGE)
675 DEFINE_ENUM(keymap, KEYMAP_ENUM);
677 #define set_keymap(map, name) map_enum(map, keymap_map, name)
679 struct keybinding_table {
680 struct keybinding *data;
681 size_t size;
684 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_map)];
686 static void
687 add_keybinding(enum keymap keymap, enum request request, int key)
689 struct keybinding_table *table = &keybindings[keymap];
690 size_t i;
692 for (i = 0; i < keybindings[keymap].size; i++) {
693 if (keybindings[keymap].data[i].alias == key) {
694 keybindings[keymap].data[i].request = request;
695 return;
699 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
700 if (!table->data)
701 die("Failed to allocate keybinding");
702 table->data[table->size].alias = key;
703 table->data[table->size++].request = request;
705 if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
706 int i;
708 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
709 if (default_keybindings[i].alias == key)
710 default_keybindings[i].request = REQ_NONE;
714 /* Looks for a key binding first in the given map, then in the generic map, and
715 * lastly in the default keybindings. */
716 static enum request
717 get_keybinding(enum keymap keymap, int key)
719 size_t i;
721 for (i = 0; i < keybindings[keymap].size; i++)
722 if (keybindings[keymap].data[i].alias == key)
723 return keybindings[keymap].data[i].request;
725 for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
726 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
727 return keybindings[KEYMAP_GENERIC].data[i].request;
729 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
730 if (default_keybindings[i].alias == key)
731 return default_keybindings[i].request;
733 return (enum request) key;
737 struct key {
738 const char *name;
739 int value;
742 static const struct key key_table[] = {
743 { "Enter", KEY_RETURN },
744 { "Space", ' ' },
745 { "Backspace", KEY_BACKSPACE },
746 { "Tab", KEY_TAB },
747 { "Escape", KEY_ESC },
748 { "Left", KEY_LEFT },
749 { "Right", KEY_RIGHT },
750 { "Up", KEY_UP },
751 { "Down", KEY_DOWN },
752 { "Insert", KEY_IC },
753 { "Delete", KEY_DC },
754 { "Hash", '#' },
755 { "Home", KEY_HOME },
756 { "End", KEY_END },
757 { "PageUp", KEY_PPAGE },
758 { "PageDown", KEY_NPAGE },
759 { "F1", KEY_F(1) },
760 { "F2", KEY_F(2) },
761 { "F3", KEY_F(3) },
762 { "F4", KEY_F(4) },
763 { "F5", KEY_F(5) },
764 { "F6", KEY_F(6) },
765 { "F7", KEY_F(7) },
766 { "F8", KEY_F(8) },
767 { "F9", KEY_F(9) },
768 { "F10", KEY_F(10) },
769 { "F11", KEY_F(11) },
770 { "F12", KEY_F(12) },
773 static int
774 get_key_value(const char *name)
776 int i;
778 for (i = 0; i < ARRAY_SIZE(key_table); i++)
779 if (!strcasecmp(key_table[i].name, name))
780 return key_table[i].value;
782 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
783 return (int)name[1] & 0x1f;
784 if (strlen(name) == 1 && isprint(*name))
785 return (int) *name;
786 return ERR;
789 static const char *
790 get_key_name(int key_value)
792 static char key_char[] = "'X'\0";
793 const char *seq = NULL;
794 int key;
796 for (key = 0; key < ARRAY_SIZE(key_table); key++)
797 if (key_table[key].value == key_value)
798 seq = key_table[key].name;
800 if (seq == NULL && key_value < 0x7f) {
801 char *s = key_char + 1;
803 if (key_value >= 0x20) {
804 *s++ = key_value;
805 } else {
806 *s++ = '^';
807 *s++ = 0x40 | (key_value & 0x1f);
809 *s++ = '\'';
810 *s++ = '\0';
811 seq = key_char;
814 return seq ? seq : "(no key)";
817 static bool
818 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
820 const char *sep = *pos > 0 ? ", " : "";
821 const char *keyname = get_key_name(keybinding->alias);
823 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
826 static bool
827 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
828 enum keymap keymap, bool all)
830 int i;
832 for (i = 0; i < keybindings[keymap].size; i++) {
833 if (keybindings[keymap].data[i].request == request) {
834 if (!append_key(buf, pos, &keybindings[keymap].data[i]))
835 return FALSE;
836 if (!all)
837 break;
841 return TRUE;
844 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
846 static const char *
847 get_keys(enum keymap keymap, enum request request, bool all)
849 static char buf[BUFSIZ];
850 size_t pos = 0;
851 int i;
853 buf[pos] = 0;
855 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
856 return "Too many keybindings!";
857 if (pos > 0 && !all)
858 return buf;
860 if (keymap != KEYMAP_GENERIC) {
861 /* Only the generic keymap includes the default keybindings when
862 * listing all keys. */
863 if (all)
864 return buf;
866 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
867 return "Too many keybindings!";
868 if (pos)
869 return buf;
872 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
873 if (default_keybindings[i].request == request) {
874 if (!append_key(buf, &pos, &default_keybindings[i]))
875 return "Too many keybindings!";
876 if (!all)
877 return buf;
881 return buf;
884 struct run_request {
885 enum keymap keymap;
886 int key;
887 const char **argv;
890 static struct run_request *run_request;
891 static size_t run_requests;
893 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
895 static enum request
896 add_run_request(enum keymap keymap, int key, const char **argv)
898 struct run_request *req;
900 if (!realloc_run_requests(&run_request, run_requests, 1))
901 return REQ_NONE;
903 req = &run_request[run_requests];
904 req->keymap = keymap;
905 req->key = key;
906 req->argv = NULL;
908 if (!argv_copy(&req->argv, argv))
909 return REQ_NONE;
911 return REQ_NONE + ++run_requests;
914 static struct run_request *
915 get_run_request(enum request request)
917 if (request <= REQ_NONE)
918 return NULL;
919 return &run_request[request - REQ_NONE - 1];
922 static void
923 add_builtin_run_requests(void)
925 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
926 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
927 const char *commit[] = { "git", "commit", NULL };
928 const char *gc[] = { "git", "gc", NULL };
929 struct run_request reqs[] = {
930 { KEYMAP_MAIN, 'C', cherry_pick },
931 { KEYMAP_STATUS, 'C', commit },
932 { KEYMAP_BRANCH, 'C', checkout },
933 { KEYMAP_GENERIC, 'G', gc },
935 int i;
937 for (i = 0; i < ARRAY_SIZE(reqs); i++) {
938 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
940 if (req != reqs[i].key)
941 continue;
942 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
943 if (req != REQ_NONE)
944 add_keybinding(reqs[i].keymap, req, reqs[i].key);
949 * User config file handling.
952 #define OPT_ERR_INFO \
953 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
954 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
955 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
956 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
957 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
958 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
959 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
960 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
961 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
962 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
963 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
964 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
965 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
966 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
967 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
968 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
969 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
971 enum option_code {
972 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
973 OPT_ERR_INFO
974 #undef OPT_ERR_
975 OPT_OK
978 static const char *option_errors[] = {
979 #define OPT_ERR_(name, msg) msg
980 OPT_ERR_INFO
981 #undef OPT_ERR_
984 static const struct enum_map color_map[] = {
985 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
986 COLOR_MAP(DEFAULT),
987 COLOR_MAP(BLACK),
988 COLOR_MAP(BLUE),
989 COLOR_MAP(CYAN),
990 COLOR_MAP(GREEN),
991 COLOR_MAP(MAGENTA),
992 COLOR_MAP(RED),
993 COLOR_MAP(WHITE),
994 COLOR_MAP(YELLOW),
997 static const struct enum_map attr_map[] = {
998 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
999 ATTR_MAP(NORMAL),
1000 ATTR_MAP(BLINK),
1001 ATTR_MAP(BOLD),
1002 ATTR_MAP(DIM),
1003 ATTR_MAP(REVERSE),
1004 ATTR_MAP(STANDOUT),
1005 ATTR_MAP(UNDERLINE),
1008 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1010 static enum option_code
1011 parse_step(double *opt, const char *arg)
1013 *opt = atoi(arg);
1014 if (!strchr(arg, '%'))
1015 return OPT_OK;
1017 /* "Shift down" so 100% and 1 does not conflict. */
1018 *opt = (*opt - 1) / 100;
1019 if (*opt >= 1.0) {
1020 *opt = 0.99;
1021 return OPT_ERR_INVALID_STEP_VALUE;
1023 if (*opt < 0.0) {
1024 *opt = 1;
1025 return OPT_ERR_INVALID_STEP_VALUE;
1027 return OPT_OK;
1030 static enum option_code
1031 parse_int(int *opt, const char *arg, int min, int max)
1033 int value = atoi(arg);
1035 if (min <= value && value <= max) {
1036 *opt = value;
1037 return OPT_OK;
1040 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1043 static bool
1044 set_color(int *color, const char *name)
1046 if (map_enum(color, color_map, name))
1047 return TRUE;
1048 if (!prefixcmp(name, "color"))
1049 return parse_int(color, name + 5, 0, 255) == OPT_OK;
1050 return FALSE;
1053 /* Wants: object fgcolor bgcolor [attribute] */
1054 static enum option_code
1055 option_color_command(int argc, const char *argv[])
1057 struct line_info *info;
1059 if (argc < 3)
1060 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1062 info = get_line_info(argv[0]);
1063 if (!info) {
1064 static const struct enum_map obsolete[] = {
1065 ENUM_MAP("main-delim", LINE_DELIMITER),
1066 ENUM_MAP("main-date", LINE_DATE),
1067 ENUM_MAP("main-author", LINE_AUTHOR),
1069 int index;
1071 if (!map_enum(&index, obsolete, argv[0]))
1072 return OPT_ERR_UNKNOWN_COLOR_NAME;
1073 info = &line_info[index];
1076 if (!set_color(&info->fg, argv[1]) ||
1077 !set_color(&info->bg, argv[2]))
1078 return OPT_ERR_UNKNOWN_COLOR;
1080 info->attr = 0;
1081 while (argc-- > 3) {
1082 int attr;
1084 if (!set_attribute(&attr, argv[argc]))
1085 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1086 info->attr |= attr;
1089 return OPT_OK;
1092 static enum option_code
1093 parse_bool(bool *opt, const char *arg)
1095 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1096 ? TRUE : FALSE;
1097 return OPT_OK;
1100 static enum option_code
1101 parse_enum_do(unsigned int *opt, const char *arg,
1102 const struct enum_map *map, size_t map_size)
1104 bool is_true;
1106 assert(map_size > 1);
1108 if (map_enum_do(map, map_size, (int *) opt, arg))
1109 return OPT_OK;
1111 parse_bool(&is_true, arg);
1112 *opt = is_true ? map[1].value : map[0].value;
1113 return OPT_OK;
1116 #define parse_enum(opt, arg, map) \
1117 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1119 static enum option_code
1120 parse_string(char *opt, const char *arg, size_t optsize)
1122 int arglen = strlen(arg);
1124 switch (arg[0]) {
1125 case '\"':
1126 case '\'':
1127 if (arglen == 1 || arg[arglen - 1] != arg[0])
1128 return OPT_ERR_UNMATCHED_QUOTATION;
1129 arg += 1; arglen -= 2;
1130 default:
1131 string_ncopy_do(opt, optsize, arg, arglen);
1132 return OPT_OK;
1136 static enum option_code
1137 parse_args(const char ***args, const char *argv[])
1139 if (*args == NULL && !argv_copy(args, argv))
1140 return OPT_ERR_OUT_OF_MEMORY;
1141 return OPT_OK;
1144 /* Wants: name = value */
1145 static enum option_code
1146 option_set_command(int argc, const char *argv[])
1148 if (argc < 3)
1149 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1151 if (strcmp(argv[1], "="))
1152 return OPT_ERR_NO_VALUE_ASSIGNED;
1154 if (!strcmp(argv[0], "blame-options"))
1155 return parse_args(&opt_blame_argv, argv + 2);
1157 if (argc != 3)
1158 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1160 if (!strcmp(argv[0], "show-author"))
1161 return parse_enum(&opt_author, argv[2], author_map);
1163 if (!strcmp(argv[0], "show-date"))
1164 return parse_enum(&opt_date, argv[2], date_map);
1166 if (!strcmp(argv[0], "show-rev-graph"))
1167 return parse_bool(&opt_rev_graph, argv[2]);
1169 if (!strcmp(argv[0], "show-refs"))
1170 return parse_bool(&opt_show_refs, argv[2]);
1172 if (!strcmp(argv[0], "show-line-numbers"))
1173 return parse_bool(&opt_line_number, argv[2]);
1175 if (!strcmp(argv[0], "line-graphics"))
1176 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1178 if (!strcmp(argv[0], "line-number-interval"))
1179 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1181 if (!strcmp(argv[0], "author-width"))
1182 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1184 if (!strcmp(argv[0], "horizontal-scroll"))
1185 return parse_step(&opt_hscroll, argv[2]);
1187 if (!strcmp(argv[0], "split-view-height"))
1188 return parse_step(&opt_scale_split_view, argv[2]);
1190 if (!strcmp(argv[0], "tab-size"))
1191 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1193 if (!strcmp(argv[0], "commit-encoding"))
1194 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1196 if (!strcmp(argv[0], "status-untracked-dirs"))
1197 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1199 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1202 /* Wants: mode request key */
1203 static enum option_code
1204 option_bind_command(int argc, const char *argv[])
1206 enum request request;
1207 int keymap = -1;
1208 int key;
1210 if (argc < 3)
1211 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1213 if (!set_keymap(&keymap, argv[0]))
1214 return OPT_ERR_UNKNOWN_KEY_MAP;
1216 key = get_key_value(argv[1]);
1217 if (key == ERR)
1218 return OPT_ERR_UNKNOWN_KEY;
1220 request = get_request(argv[2]);
1221 if (request == REQ_UNKNOWN) {
1222 static const struct enum_map obsolete[] = {
1223 ENUM_MAP("cherry-pick", REQ_NONE),
1224 ENUM_MAP("screen-resize", REQ_NONE),
1225 ENUM_MAP("tree-parent", REQ_PARENT),
1227 int alias;
1229 if (map_enum(&alias, obsolete, argv[2])) {
1230 if (alias != REQ_NONE)
1231 add_keybinding(keymap, alias, key);
1232 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1235 if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1236 request = add_run_request(keymap, key, argv + 2);
1237 if (request == REQ_UNKNOWN)
1238 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1240 add_keybinding(keymap, request, key);
1242 return OPT_OK;
1245 static enum option_code
1246 set_option(const char *opt, char *value)
1248 const char *argv[SIZEOF_ARG];
1249 int argc = 0;
1251 if (!argv_from_string(argv, &argc, value))
1252 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1254 if (!strcmp(opt, "color"))
1255 return option_color_command(argc, argv);
1257 if (!strcmp(opt, "set"))
1258 return option_set_command(argc, argv);
1260 if (!strcmp(opt, "bind"))
1261 return option_bind_command(argc, argv);
1263 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1266 struct config_state {
1267 int lineno;
1268 bool errors;
1271 static int
1272 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1274 struct config_state *config = data;
1275 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1277 config->lineno++;
1279 /* Check for comment markers, since read_properties() will
1280 * only ensure opt and value are split at first " \t". */
1281 optlen = strcspn(opt, "#");
1282 if (optlen == 0)
1283 return OK;
1285 if (opt[optlen] == 0) {
1286 /* Look for comment endings in the value. */
1287 size_t len = strcspn(value, "#");
1289 if (len < valuelen) {
1290 valuelen = len;
1291 value[valuelen] = 0;
1294 status = set_option(opt, value);
1297 if (status != OPT_OK) {
1298 warn("Error on line %d, near '%.*s': %s",
1299 config->lineno, (int) optlen, opt, option_errors[status]);
1300 config->errors = TRUE;
1303 /* Always keep going if errors are encountered. */
1304 return OK;
1307 static void
1308 load_option_file(const char *path)
1310 struct config_state config = { 0, FALSE };
1311 struct io io;
1313 /* It's OK that the file doesn't exist. */
1314 if (!io_open(&io, "%s", path))
1315 return;
1317 if (io_load(&io, " \t", read_option, &config) == ERR ||
1318 config.errors == TRUE)
1319 warn("Errors while loading %s.", path);
1322 static int
1323 load_options(void)
1325 const char *home = getenv("HOME");
1326 const char *tigrc_user = getenv("TIGRC_USER");
1327 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1328 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1329 char buf[SIZEOF_STR];
1331 if (!tigrc_system)
1332 tigrc_system = SYSCONFDIR "/tigrc";
1333 load_option_file(tigrc_system);
1335 if (!tigrc_user) {
1336 if (!home || !string_format(buf, "%s/.tigrc", home))
1337 return ERR;
1338 tigrc_user = buf;
1340 load_option_file(tigrc_user);
1342 /* Add _after_ loading config files to avoid adding run requests
1343 * that conflict with keybindings. */
1344 add_builtin_run_requests();
1346 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1347 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1348 int argc = 0;
1350 if (!string_format(buf, "%s", tig_diff_opts) ||
1351 !argv_from_string(diff_opts, &argc, buf))
1352 die("TIG_DIFF_OPTS contains too many arguments");
1353 else if (!argv_copy(&opt_diff_argv, diff_opts))
1354 die("Failed to format TIG_DIFF_OPTS arguments");
1357 return OK;
1362 * The viewer
1365 struct view;
1366 struct view_ops;
1368 /* The display array of active views and the index of the current view. */
1369 static struct view *display[2];
1370 static WINDOW *display_win[2];
1371 static WINDOW *display_title[2];
1372 static unsigned int current_view;
1374 #define foreach_displayed_view(view, i) \
1375 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1377 #define displayed_views() (display[1] != NULL ? 2 : 1)
1379 /* Current head and commit ID */
1380 static char ref_blob[SIZEOF_REF] = "";
1381 static char ref_commit[SIZEOF_REF] = "HEAD";
1382 static char ref_head[SIZEOF_REF] = "HEAD";
1383 static char ref_branch[SIZEOF_REF] = "";
1385 enum view_type {
1386 VIEW_MAIN,
1387 VIEW_DIFF,
1388 VIEW_LOG,
1389 VIEW_TREE,
1390 VIEW_BLOB,
1391 VIEW_BLAME,
1392 VIEW_BRANCH,
1393 VIEW_HELP,
1394 VIEW_PAGER,
1395 VIEW_STATUS,
1396 VIEW_STAGE,
1399 struct view {
1400 enum view_type type; /* View type */
1401 const char *name; /* View name */
1402 const char *id; /* Points to either of ref_{head,commit,blob} */
1404 struct view_ops *ops; /* View operations */
1406 enum keymap keymap; /* What keymap does this view have */
1407 bool git_dir; /* Whether the view requires a git directory. */
1409 char ref[SIZEOF_REF]; /* Hovered commit reference */
1410 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1412 int height, width; /* The width and height of the main window */
1413 WINDOW *win; /* The main window */
1415 /* Navigation */
1416 unsigned long offset; /* Offset of the window top */
1417 unsigned long yoffset; /* Offset from the window side. */
1418 unsigned long lineno; /* Current line number */
1419 unsigned long p_offset; /* Previous offset of the window top */
1420 unsigned long p_yoffset;/* Previous offset from the window side */
1421 unsigned long p_lineno; /* Previous current line number */
1422 bool p_restore; /* Should the previous position be restored. */
1424 /* Searching */
1425 char grep[SIZEOF_STR]; /* Search string */
1426 regex_t *regex; /* Pre-compiled regexp */
1428 /* If non-NULL, points to the view that opened this view. If this view
1429 * is closed tig will switch back to the parent view. */
1430 struct view *parent;
1431 struct view *prev;
1433 /* Buffering */
1434 size_t lines; /* Total number of lines */
1435 struct line *line; /* Line index */
1436 unsigned int digits; /* Number of digits in the lines member. */
1438 /* Drawing */
1439 struct line *curline; /* Line currently being drawn. */
1440 enum line_type curtype; /* Attribute currently used for drawing. */
1441 unsigned long col; /* Column when drawing. */
1442 bool has_scrolled; /* View was scrolled. */
1444 /* Loading */
1445 const char **argv; /* Shell command arguments. */
1446 const char *dir; /* Directory from which to execute. */
1447 struct io io;
1448 struct io *pipe;
1449 time_t start_time;
1450 time_t update_secs;
1453 enum open_flags {
1454 OPEN_DEFAULT = 0, /* Use default view switching. */
1455 OPEN_SPLIT = 1, /* Split current view. */
1456 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1457 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1458 OPEN_PREPARED = 32, /* Open already prepared command. */
1459 OPEN_EXTRA = 64, /* Open extra data from command. */
1462 struct view_ops {
1463 /* What type of content being displayed. Used in the title bar. */
1464 const char *type;
1465 /* Open and reads in all view content. */
1466 bool (*open)(struct view *view, enum open_flags flags);
1467 /* Read one line; updates view->line. */
1468 bool (*read)(struct view *view, char *data);
1469 /* Draw one line; @lineno must be < view->height. */
1470 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1471 /* Depending on view handle a special requests. */
1472 enum request (*request)(struct view *view, enum request request, struct line *line);
1473 /* Search for regexp in a line. */
1474 bool (*grep)(struct view *view, struct line *line);
1475 /* Select line */
1476 void (*select)(struct view *view, struct line *line);
1479 static struct view_ops blame_ops;
1480 static struct view_ops blob_ops;
1481 static struct view_ops diff_ops;
1482 static struct view_ops help_ops;
1483 static struct view_ops log_ops;
1484 static struct view_ops main_ops;
1485 static struct view_ops pager_ops;
1486 static struct view_ops stage_ops;
1487 static struct view_ops status_ops;
1488 static struct view_ops tree_ops;
1489 static struct view_ops branch_ops;
1491 #define VIEW_STR(type, name, ref, ops, map, git) \
1492 { type, name, ref, ops, map, git }
1494 #define VIEW_(id, name, ops, git, ref) \
1495 VIEW_STR(VIEW_##id, name, ref, ops, KEYMAP_##id, git)
1497 static struct view views[] = {
1498 VIEW_(MAIN, "main", &main_ops, TRUE, ref_head),
1499 VIEW_(DIFF, "diff", &diff_ops, TRUE, ref_commit),
1500 VIEW_(LOG, "log", &log_ops, TRUE, ref_head),
1501 VIEW_(TREE, "tree", &tree_ops, TRUE, ref_commit),
1502 VIEW_(BLOB, "blob", &blob_ops, TRUE, ref_blob),
1503 VIEW_(BLAME, "blame", &blame_ops, TRUE, ref_commit),
1504 VIEW_(BRANCH, "branch", &branch_ops, TRUE, ref_head),
1505 VIEW_(HELP, "help", &help_ops, FALSE, ""),
1506 VIEW_(PAGER, "pager", &pager_ops, FALSE, ""),
1507 VIEW_(STATUS, "status", &status_ops, TRUE, "status"),
1508 VIEW_(STAGE, "stage", &stage_ops, TRUE, ""),
1511 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1513 #define foreach_view(view, i) \
1514 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1516 #define view_is_displayed(view) \
1517 (view == display[0] || view == display[1])
1519 static enum request
1520 view_request(struct view *view, enum request request)
1522 if (!view || !view->lines)
1523 return request;
1524 return view->ops->request(view, request, &view->line[view->lineno]);
1529 * View drawing.
1532 static inline void
1533 set_view_attr(struct view *view, enum line_type type)
1535 if (!view->curline->selected && view->curtype != type) {
1536 (void) wattrset(view->win, get_line_attr(type));
1537 wchgat(view->win, -1, 0, type, NULL);
1538 view->curtype = type;
1542 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1544 static bool
1545 draw_chars(struct view *view, enum line_type type, const char *string,
1546 int max_len, bool use_tilde)
1548 static char out_buffer[BUFSIZ * 2];
1549 int len = 0;
1550 int col = 0;
1551 int trimmed = FALSE;
1552 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1554 if (max_len <= 0)
1555 return VIEW_MAX_LEN(view) <= 0;
1557 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1559 set_view_attr(view, type);
1560 if (len > 0) {
1561 if (opt_iconv_out != ICONV_NONE) {
1562 ICONV_CONST char *inbuf = (ICONV_CONST char *) string;
1563 size_t inlen = len + 1;
1565 char *outbuf = out_buffer;
1566 size_t outlen = sizeof(out_buffer);
1568 size_t ret;
1570 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1571 if (ret != (size_t) -1) {
1572 string = out_buffer;
1573 len = sizeof(out_buffer) - outlen;
1577 waddnstr(view->win, string, len);
1579 if (trimmed && use_tilde) {
1580 set_view_attr(view, LINE_DELIMITER);
1581 waddch(view->win, '~');
1582 col++;
1586 view->col += col;
1587 return VIEW_MAX_LEN(view) <= 0;
1590 static bool
1591 draw_space(struct view *view, enum line_type type, int max, int spaces)
1593 static char space[] = " ";
1595 spaces = MIN(max, spaces);
1597 while (spaces > 0) {
1598 int len = MIN(spaces, sizeof(space) - 1);
1600 if (draw_chars(view, type, space, len, FALSE))
1601 return TRUE;
1602 spaces -= len;
1605 return VIEW_MAX_LEN(view) <= 0;
1608 static bool
1609 draw_text(struct view *view, enum line_type type, const char *string)
1611 char text[SIZEOF_STR];
1613 do {
1614 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1616 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1617 return TRUE;
1618 string += pos;
1619 } while (*string);
1621 return VIEW_MAX_LEN(view) <= 0;
1624 static bool
1625 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1627 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1628 int max = VIEW_MAX_LEN(view);
1629 int i;
1631 if (max < size)
1632 size = max;
1634 set_view_attr(view, type);
1635 /* Using waddch() instead of waddnstr() ensures that
1636 * they'll be rendered correctly for the cursor line. */
1637 for (i = skip; i < size; i++)
1638 waddch(view->win, graphic[i]);
1640 view->col += size;
1641 if (separator) {
1642 if (size < max && skip <= size)
1643 waddch(view->win, ' ');
1644 view->col++;
1647 return VIEW_MAX_LEN(view) <= 0;
1650 static bool
1651 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1653 int max = MIN(VIEW_MAX_LEN(view), len);
1654 int col = view->col;
1656 if (!text)
1657 return draw_space(view, type, max, max);
1659 return draw_chars(view, type, text, max - 1, trim)
1660 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1663 static bool
1664 draw_date(struct view *view, struct time *time)
1666 const char *date = mkdate(time, opt_date);
1667 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1669 if (opt_date == DATE_NO)
1670 return FALSE;
1672 return draw_field(view, LINE_DATE, date, cols, FALSE);
1675 static bool
1676 draw_author(struct view *view, const char *author)
1678 bool trim = author_trim(opt_author_cols);
1679 const char *text = mkauthor(author, opt_author_cols, opt_author);
1681 if (opt_author == AUTHOR_NO)
1682 return FALSE;
1684 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1687 static bool
1688 draw_mode(struct view *view, mode_t mode)
1690 const char *str = mkmode(mode);
1692 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1695 static bool
1696 draw_lineno(struct view *view, unsigned int lineno)
1698 char number[10];
1699 int digits3 = view->digits < 3 ? 3 : view->digits;
1700 int max = MIN(VIEW_MAX_LEN(view), digits3);
1701 char *text = NULL;
1702 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1704 lineno += view->offset + 1;
1705 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1706 static char fmt[] = "%1ld";
1708 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1709 if (string_format(number, fmt, lineno))
1710 text = number;
1712 if (text)
1713 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1714 else
1715 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1716 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1719 static bool
1720 draw_refs(struct view *view, struct ref_list *refs)
1722 size_t i;
1724 if (!opt_show_refs || !refs)
1725 return FALSE;
1727 for (i = 0; i < refs->size; i++) {
1728 struct ref *ref = refs->refs[i];
1729 enum line_type type = get_line_type_from_ref(ref);
1731 if (draw_text(view, type, "[") ||
1732 draw_text(view, type, ref->name) ||
1733 draw_text(view, type, "]"))
1734 return TRUE;
1736 if (draw_text(view, LINE_DEFAULT, " "))
1737 return TRUE;
1740 return FALSE;
1743 static bool
1744 draw_view_line(struct view *view, unsigned int lineno)
1746 struct line *line;
1747 bool selected = (view->offset + lineno == view->lineno);
1749 assert(view_is_displayed(view));
1751 if (view->offset + lineno >= view->lines)
1752 return FALSE;
1754 line = &view->line[view->offset + lineno];
1756 wmove(view->win, lineno, 0);
1757 if (line->cleareol)
1758 wclrtoeol(view->win);
1759 view->col = 0;
1760 view->curline = line;
1761 view->curtype = LINE_NONE;
1762 line->selected = FALSE;
1763 line->dirty = line->cleareol = 0;
1765 if (selected) {
1766 set_view_attr(view, LINE_CURSOR);
1767 line->selected = TRUE;
1768 view->ops->select(view, line);
1771 return view->ops->draw(view, line, lineno);
1774 static void
1775 redraw_view_dirty(struct view *view)
1777 bool dirty = FALSE;
1778 int lineno;
1780 for (lineno = 0; lineno < view->height; lineno++) {
1781 if (view->offset + lineno >= view->lines)
1782 break;
1783 if (!view->line[view->offset + lineno].dirty)
1784 continue;
1785 dirty = TRUE;
1786 if (!draw_view_line(view, lineno))
1787 break;
1790 if (!dirty)
1791 return;
1792 wnoutrefresh(view->win);
1795 static void
1796 redraw_view_from(struct view *view, int lineno)
1798 assert(0 <= lineno && lineno < view->height);
1800 for (; lineno < view->height; lineno++) {
1801 if (!draw_view_line(view, lineno))
1802 break;
1805 wnoutrefresh(view->win);
1808 static void
1809 redraw_view(struct view *view)
1811 werase(view->win);
1812 redraw_view_from(view, 0);
1816 static void
1817 update_view_title(struct view *view)
1819 char buf[SIZEOF_STR];
1820 char state[SIZEOF_STR];
1821 size_t bufpos = 0, statelen = 0;
1822 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1824 assert(view_is_displayed(view));
1826 if (view->type != VIEW_STATUS && view->lines) {
1827 unsigned int view_lines = view->offset + view->height;
1828 unsigned int lines = view->lines
1829 ? MIN(view_lines, view->lines) * 100 / view->lines
1830 : 0;
1832 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
1833 view->ops->type,
1834 view->lineno + 1,
1835 view->lines,
1836 lines);
1840 if (view->pipe) {
1841 time_t secs = time(NULL) - view->start_time;
1843 /* Three git seconds are a long time ... */
1844 if (secs > 2)
1845 string_format_from(state, &statelen, " loading %lds", secs);
1848 string_format_from(buf, &bufpos, "[%s]", view->name);
1849 if (*view->ref && bufpos < view->width) {
1850 size_t refsize = strlen(view->ref);
1851 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
1853 if (minsize < view->width)
1854 refsize = view->width - minsize + 7;
1855 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
1858 if (statelen && bufpos < view->width) {
1859 string_format_from(buf, &bufpos, "%s", state);
1862 if (view == display[current_view])
1863 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
1864 else
1865 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
1867 mvwaddnstr(window, 0, 0, buf, bufpos);
1868 wclrtoeol(window);
1869 wnoutrefresh(window);
1872 static int
1873 apply_step(double step, int value)
1875 if (step >= 1)
1876 return (int) step;
1877 value *= step + 0.01;
1878 return value ? value : 1;
1881 static void
1882 resize_display(void)
1884 int offset, i;
1885 struct view *base = display[0];
1886 struct view *view = display[1] ? display[1] : display[0];
1888 /* Setup window dimensions */
1890 getmaxyx(stdscr, base->height, base->width);
1892 /* Make room for the status window. */
1893 base->height -= 1;
1895 if (view != base) {
1896 /* Horizontal split. */
1897 view->width = base->width;
1898 view->height = apply_step(opt_scale_split_view, base->height);
1899 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
1900 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
1901 base->height -= view->height;
1903 /* Make room for the title bar. */
1904 view->height -= 1;
1907 /* Make room for the title bar. */
1908 base->height -= 1;
1910 offset = 0;
1912 foreach_displayed_view (view, i) {
1913 if (!display_win[i]) {
1914 display_win[i] = newwin(view->height, view->width, offset, 0);
1915 if (!display_win[i])
1916 die("Failed to create %s view", view->name);
1918 scrollok(display_win[i], FALSE);
1920 display_title[i] = newwin(1, view->width, offset + view->height, 0);
1921 if (!display_title[i])
1922 die("Failed to create title window");
1924 } else {
1925 wresize(display_win[i], view->height, view->width);
1926 mvwin(display_win[i], offset, 0);
1927 mvwin(display_title[i], offset + view->height, 0);
1930 view->win = display_win[i];
1932 offset += view->height + 1;
1936 static void
1937 redraw_display(bool clear)
1939 struct view *view;
1940 int i;
1942 foreach_displayed_view (view, i) {
1943 if (clear)
1944 wclear(view->win);
1945 redraw_view(view);
1946 update_view_title(view);
1952 * Option management
1955 #define TOGGLE_MENU \
1956 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
1957 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
1958 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
1959 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
1960 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
1961 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL)
1963 static void
1964 toggle_option(enum request request)
1966 const struct {
1967 enum request request;
1968 const struct enum_map *map;
1969 size_t map_size;
1970 } data[] = {
1971 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
1972 TOGGLE_MENU
1973 #undef TOGGLE_
1975 const struct menu_item menu[] = {
1976 #define TOGGLE_(id, key, help, value, map) { key, help, value },
1977 TOGGLE_MENU
1978 #undef TOGGLE_
1979 { 0 }
1981 int i = 0;
1983 if (request == REQ_OPTIONS) {
1984 if (!prompt_menu("Toggle option", menu, &i))
1985 return;
1986 } else {
1987 while (i < ARRAY_SIZE(data) && data[i].request != request)
1988 i++;
1989 if (i >= ARRAY_SIZE(data))
1990 die("Invalid request (%d)", request);
1993 if (data[i].map != NULL) {
1994 unsigned int *opt = menu[i].data;
1996 *opt = (*opt + 1) % data[i].map_size;
1997 redraw_display(FALSE);
1998 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2000 } else {
2001 bool *option = menu[i].data;
2003 *option = !*option;
2004 redraw_display(FALSE);
2005 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2009 static void
2010 maximize_view(struct view *view, bool redraw)
2012 memset(display, 0, sizeof(display));
2013 current_view = 0;
2014 display[current_view] = view;
2015 resize_display();
2016 if (redraw) {
2017 redraw_display(FALSE);
2018 report("");
2024 * Navigation
2027 static bool
2028 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2030 if (lineno >= view->lines)
2031 lineno = view->lines > 0 ? view->lines - 1 : 0;
2033 if (offset > lineno || offset + view->height <= lineno) {
2034 unsigned long half = view->height / 2;
2036 if (lineno > half)
2037 offset = lineno - half;
2038 else
2039 offset = 0;
2042 if (offset != view->offset || lineno != view->lineno) {
2043 view->offset = offset;
2044 view->lineno = lineno;
2045 return TRUE;
2048 return FALSE;
2051 /* Scrolling backend */
2052 static void
2053 do_scroll_view(struct view *view, int lines)
2055 bool redraw_current_line = FALSE;
2057 /* The rendering expects the new offset. */
2058 view->offset += lines;
2060 assert(0 <= view->offset && view->offset < view->lines);
2061 assert(lines);
2063 /* Move current line into the view. */
2064 if (view->lineno < view->offset) {
2065 view->lineno = view->offset;
2066 redraw_current_line = TRUE;
2067 } else if (view->lineno >= view->offset + view->height) {
2068 view->lineno = view->offset + view->height - 1;
2069 redraw_current_line = TRUE;
2072 assert(view->offset <= view->lineno && view->lineno < view->lines);
2074 /* Redraw the whole screen if scrolling is pointless. */
2075 if (view->height < ABS(lines)) {
2076 redraw_view(view);
2078 } else {
2079 int line = lines > 0 ? view->height - lines : 0;
2080 int end = line + ABS(lines);
2082 scrollok(view->win, TRUE);
2083 wscrl(view->win, lines);
2084 scrollok(view->win, FALSE);
2086 while (line < end && draw_view_line(view, line))
2087 line++;
2089 if (redraw_current_line)
2090 draw_view_line(view, view->lineno - view->offset);
2091 wnoutrefresh(view->win);
2094 view->has_scrolled = TRUE;
2095 report("");
2098 /* Scroll frontend */
2099 static void
2100 scroll_view(struct view *view, enum request request)
2102 int lines = 1;
2104 assert(view_is_displayed(view));
2106 switch (request) {
2107 case REQ_SCROLL_FIRST_COL:
2108 view->yoffset = 0;
2109 redraw_view_from(view, 0);
2110 report("");
2111 return;
2112 case REQ_SCROLL_LEFT:
2113 if (view->yoffset == 0) {
2114 report("Cannot scroll beyond the first column");
2115 return;
2117 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2118 view->yoffset = 0;
2119 else
2120 view->yoffset -= apply_step(opt_hscroll, view->width);
2121 redraw_view_from(view, 0);
2122 report("");
2123 return;
2124 case REQ_SCROLL_RIGHT:
2125 view->yoffset += apply_step(opt_hscroll, view->width);
2126 redraw_view(view);
2127 report("");
2128 return;
2129 case REQ_SCROLL_PAGE_DOWN:
2130 lines = view->height;
2131 case REQ_SCROLL_LINE_DOWN:
2132 if (view->offset + lines > view->lines)
2133 lines = view->lines - view->offset;
2135 if (lines == 0 || view->offset + view->height >= view->lines) {
2136 report("Cannot scroll beyond the last line");
2137 return;
2139 break;
2141 case REQ_SCROLL_PAGE_UP:
2142 lines = view->height;
2143 case REQ_SCROLL_LINE_UP:
2144 if (lines > view->offset)
2145 lines = view->offset;
2147 if (lines == 0) {
2148 report("Cannot scroll beyond the first line");
2149 return;
2152 lines = -lines;
2153 break;
2155 default:
2156 die("request %d not handled in switch", request);
2159 do_scroll_view(view, lines);
2162 /* Cursor moving */
2163 static void
2164 move_view(struct view *view, enum request request)
2166 int scroll_steps = 0;
2167 int steps;
2169 switch (request) {
2170 case REQ_MOVE_FIRST_LINE:
2171 steps = -view->lineno;
2172 break;
2174 case REQ_MOVE_LAST_LINE:
2175 steps = view->lines - view->lineno - 1;
2176 break;
2178 case REQ_MOVE_PAGE_UP:
2179 steps = view->height > view->lineno
2180 ? -view->lineno : -view->height;
2181 break;
2183 case REQ_MOVE_PAGE_DOWN:
2184 steps = view->lineno + view->height >= view->lines
2185 ? view->lines - view->lineno - 1 : view->height;
2186 break;
2188 case REQ_MOVE_UP:
2189 steps = -1;
2190 break;
2192 case REQ_MOVE_DOWN:
2193 steps = 1;
2194 break;
2196 default:
2197 die("request %d not handled in switch", request);
2200 if (steps <= 0 && view->lineno == 0) {
2201 report("Cannot move beyond the first line");
2202 return;
2204 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2205 report("Cannot move beyond the last line");
2206 return;
2209 /* Move the current line */
2210 view->lineno += steps;
2211 assert(0 <= view->lineno && view->lineno < view->lines);
2213 /* Check whether the view needs to be scrolled */
2214 if (view->lineno < view->offset ||
2215 view->lineno >= view->offset + view->height) {
2216 scroll_steps = steps;
2217 if (steps < 0 && -steps > view->offset) {
2218 scroll_steps = -view->offset;
2220 } else if (steps > 0) {
2221 if (view->lineno == view->lines - 1 &&
2222 view->lines > view->height) {
2223 scroll_steps = view->lines - view->offset - 1;
2224 if (scroll_steps >= view->height)
2225 scroll_steps -= view->height - 1;
2230 if (!view_is_displayed(view)) {
2231 view->offset += scroll_steps;
2232 assert(0 <= view->offset && view->offset < view->lines);
2233 view->ops->select(view, &view->line[view->lineno]);
2234 return;
2237 /* Repaint the old "current" line if we be scrolling */
2238 if (ABS(steps) < view->height)
2239 draw_view_line(view, view->lineno - steps - view->offset);
2241 if (scroll_steps) {
2242 do_scroll_view(view, scroll_steps);
2243 return;
2246 /* Draw the current line */
2247 draw_view_line(view, view->lineno - view->offset);
2249 wnoutrefresh(view->win);
2250 report("");
2255 * Searching
2258 static void search_view(struct view *view, enum request request);
2260 static bool
2261 grep_text(struct view *view, const char *text[])
2263 regmatch_t pmatch;
2264 size_t i;
2266 for (i = 0; text[i]; i++)
2267 if (*text[i] &&
2268 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2269 return TRUE;
2270 return FALSE;
2273 static void
2274 select_view_line(struct view *view, unsigned long lineno)
2276 unsigned long old_lineno = view->lineno;
2277 unsigned long old_offset = view->offset;
2279 if (goto_view_line(view, view->offset, lineno)) {
2280 if (view_is_displayed(view)) {
2281 if (old_offset != view->offset) {
2282 redraw_view(view);
2283 } else {
2284 draw_view_line(view, old_lineno - view->offset);
2285 draw_view_line(view, view->lineno - view->offset);
2286 wnoutrefresh(view->win);
2288 } else {
2289 view->ops->select(view, &view->line[view->lineno]);
2294 static void
2295 find_next(struct view *view, enum request request)
2297 unsigned long lineno = view->lineno;
2298 int direction;
2300 if (!*view->grep) {
2301 if (!*opt_search)
2302 report("No previous search");
2303 else
2304 search_view(view, request);
2305 return;
2308 switch (request) {
2309 case REQ_SEARCH:
2310 case REQ_FIND_NEXT:
2311 direction = 1;
2312 break;
2314 case REQ_SEARCH_BACK:
2315 case REQ_FIND_PREV:
2316 direction = -1;
2317 break;
2319 default:
2320 return;
2323 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2324 lineno += direction;
2326 /* Note, lineno is unsigned long so will wrap around in which case it
2327 * will become bigger than view->lines. */
2328 for (; lineno < view->lines; lineno += direction) {
2329 if (view->ops->grep(view, &view->line[lineno])) {
2330 select_view_line(view, lineno);
2331 report("Line %ld matches '%s'", lineno + 1, view->grep);
2332 return;
2336 report("No match found for '%s'", view->grep);
2339 static void
2340 search_view(struct view *view, enum request request)
2342 int regex_err;
2344 if (view->regex) {
2345 regfree(view->regex);
2346 *view->grep = 0;
2347 } else {
2348 view->regex = calloc(1, sizeof(*view->regex));
2349 if (!view->regex)
2350 return;
2353 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2354 if (regex_err != 0) {
2355 char buf[SIZEOF_STR] = "unknown error";
2357 regerror(regex_err, view->regex, buf, sizeof(buf));
2358 report("Search failed: %s", buf);
2359 return;
2362 string_copy(view->grep, opt_search);
2364 find_next(view, request);
2368 * Incremental updating
2371 static void
2372 reset_view(struct view *view)
2374 int i;
2376 for (i = 0; i < view->lines; i++)
2377 free(view->line[i].data);
2378 free(view->line);
2380 view->p_offset = view->offset;
2381 view->p_yoffset = view->yoffset;
2382 view->p_lineno = view->lineno;
2384 view->line = NULL;
2385 view->offset = 0;
2386 view->yoffset = 0;
2387 view->lines = 0;
2388 view->lineno = 0;
2389 view->vid[0] = 0;
2390 view->update_secs = 0;
2393 static const char *
2394 format_arg(const char *name)
2396 static struct {
2397 const char *name;
2398 size_t namelen;
2399 const char *value;
2400 const char *value_if_empty;
2401 } vars[] = {
2402 #define FORMAT_VAR(name, value, value_if_empty) \
2403 { name, STRING_SIZE(name), value, value_if_empty }
2404 FORMAT_VAR("%(directory)", opt_path, "."),
2405 FORMAT_VAR("%(file)", opt_file, ""),
2406 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2407 FORMAT_VAR("%(head)", ref_head, ""),
2408 FORMAT_VAR("%(commit)", ref_commit, ""),
2409 FORMAT_VAR("%(blob)", ref_blob, ""),
2410 FORMAT_VAR("%(branch)", ref_branch, ""),
2412 int i;
2414 for (i = 0; i < ARRAY_SIZE(vars); i++)
2415 if (!strncmp(name, vars[i].name, vars[i].namelen))
2416 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2418 report("Unknown replacement: `%s`", name);
2419 return NULL;
2422 static bool
2423 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2425 char buf[SIZEOF_STR];
2426 int argc;
2428 argv_free(*dst_argv);
2430 for (argc = 0; src_argv[argc]; argc++) {
2431 const char *arg = src_argv[argc];
2432 size_t bufpos = 0;
2434 if (!strcmp(arg, "%(fileargs)")) {
2435 if (!argv_append_array(dst_argv, opt_file_argv))
2436 break;
2437 continue;
2439 } else if (!strcmp(arg, "%(diffargs)")) {
2440 if (!argv_append_array(dst_argv, opt_diff_argv))
2441 break;
2442 continue;
2444 } else if (!strcmp(arg, "%(blameargs)")) {
2445 if (!argv_append_array(dst_argv, opt_blame_argv))
2446 break;
2447 continue;
2449 } else if (!strcmp(arg, "%(revargs)") ||
2450 (first && !strcmp(arg, "%(commit)"))) {
2451 if (!argv_append_array(dst_argv, opt_rev_argv))
2452 break;
2453 continue;
2456 while (arg) {
2457 char *next = strstr(arg, "%(");
2458 int len = next - arg;
2459 const char *value;
2461 if (!next) {
2462 len = strlen(arg);
2463 value = "";
2465 } else {
2466 value = format_arg(next);
2468 if (!value) {
2469 return FALSE;
2473 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2474 return FALSE;
2476 arg = next ? strchr(next, ')') + 1 : NULL;
2479 if (!argv_append(dst_argv, buf))
2480 break;
2483 return src_argv[argc] == NULL;
2486 static bool
2487 restore_view_position(struct view *view)
2489 if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2490 return FALSE;
2492 /* Changing the view position cancels the restoring. */
2493 /* FIXME: Changing back to the first line is not detected. */
2494 if (view->offset != 0 || view->lineno != 0) {
2495 view->p_restore = FALSE;
2496 return FALSE;
2499 if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2500 view_is_displayed(view))
2501 werase(view->win);
2503 view->yoffset = view->p_yoffset;
2504 view->p_restore = FALSE;
2506 return TRUE;
2509 static void
2510 end_update(struct view *view, bool force)
2512 if (!view->pipe)
2513 return;
2514 while (!view->ops->read(view, NULL))
2515 if (!force)
2516 return;
2517 if (force)
2518 io_kill(view->pipe);
2519 io_done(view->pipe);
2520 view->pipe = NULL;
2523 static void
2524 setup_update(struct view *view, const char *vid)
2526 reset_view(view);
2527 string_copy_rev(view->vid, vid);
2528 view->pipe = &view->io;
2529 view->start_time = time(NULL);
2532 static bool
2533 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2535 bool extra = !!(flags & (OPEN_EXTRA));
2536 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2537 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2539 if (!reload && !strcmp(view->vid, view->id))
2540 return TRUE;
2542 if (view->pipe) {
2543 if (extra)
2544 io_done(view->pipe);
2545 else
2546 end_update(view, TRUE);
2549 if (!refresh) {
2550 view->dir = dir;
2551 if (!format_argv(&view->argv, argv, !view->prev))
2552 return FALSE;
2554 /* Put the current ref_* value to the view title ref
2555 * member. This is needed by the blob view. Most other
2556 * views sets it automatically after loading because the
2557 * first line is a commit line. */
2558 string_copy_rev(view->ref, view->id);
2561 if (view->argv && view->argv[0] &&
2562 !io_run(&view->io, IO_RD, view->dir, view->argv))
2563 return FALSE;
2565 if (!extra)
2566 setup_update(view, view->id);
2568 return TRUE;
2571 static bool
2572 view_open(struct view *view, enum open_flags flags)
2574 return begin_update(view, NULL, NULL, flags);
2577 static bool
2578 update_view(struct view *view)
2580 char out_buffer[BUFSIZ * 2];
2581 char *line;
2582 /* Clear the view and redraw everything since the tree sorting
2583 * might have rearranged things. */
2584 bool redraw = view->lines == 0;
2585 bool can_read = TRUE;
2587 if (!view->pipe)
2588 return TRUE;
2590 if (!io_can_read(view->pipe, FALSE)) {
2591 if (view->lines == 0 && view_is_displayed(view)) {
2592 time_t secs = time(NULL) - view->start_time;
2594 if (secs > 1 && secs > view->update_secs) {
2595 if (view->update_secs == 0)
2596 redraw_view(view);
2597 update_view_title(view);
2598 view->update_secs = secs;
2601 return TRUE;
2604 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2605 if (opt_iconv_in != ICONV_NONE) {
2606 ICONV_CONST char *inbuf = line;
2607 size_t inlen = strlen(line) + 1;
2609 char *outbuf = out_buffer;
2610 size_t outlen = sizeof(out_buffer);
2612 size_t ret;
2614 ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2615 if (ret != (size_t) -1)
2616 line = out_buffer;
2619 if (!view->ops->read(view, line)) {
2620 report("Allocation failure");
2621 end_update(view, TRUE);
2622 return FALSE;
2627 unsigned long lines = view->lines;
2628 int digits;
2630 for (digits = 0; lines; digits++)
2631 lines /= 10;
2633 /* Keep the displayed view in sync with line number scaling. */
2634 if (digits != view->digits) {
2635 view->digits = digits;
2636 if (opt_line_number || view->type == VIEW_BLAME)
2637 redraw = TRUE;
2641 if (io_error(view->pipe)) {
2642 report("Failed to read: %s", io_strerror(view->pipe));
2643 end_update(view, TRUE);
2645 } else if (io_eof(view->pipe)) {
2646 if (view_is_displayed(view))
2647 report("");
2648 end_update(view, FALSE);
2651 if (restore_view_position(view))
2652 redraw = TRUE;
2654 if (!view_is_displayed(view))
2655 return TRUE;
2657 if (redraw)
2658 redraw_view_from(view, 0);
2659 else
2660 redraw_view_dirty(view);
2662 /* Update the title _after_ the redraw so that if the redraw picks up a
2663 * commit reference in view->ref it'll be available here. */
2664 update_view_title(view);
2665 return TRUE;
2668 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2670 static struct line *
2671 add_line_data(struct view *view, void *data, enum line_type type)
2673 struct line *line;
2675 if (!realloc_lines(&view->line, view->lines, 1))
2676 return NULL;
2678 line = &view->line[view->lines++];
2679 memset(line, 0, sizeof(*line));
2680 line->type = type;
2681 line->data = data;
2682 line->dirty = 1;
2684 return line;
2687 static struct line *
2688 add_line_text(struct view *view, const char *text, enum line_type type)
2690 char *data = text ? strdup(text) : NULL;
2692 return data ? add_line_data(view, data, type) : NULL;
2695 static struct line *
2696 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2698 char buf[SIZEOF_STR];
2699 va_list args;
2701 va_start(args, fmt);
2702 if (vsnprintf(buf, sizeof(buf), fmt, args) >= sizeof(buf))
2703 buf[0] = 0;
2704 va_end(args);
2706 return buf[0] ? add_line_text(view, buf, type) : NULL;
2710 * View opening
2713 static void
2714 load_view(struct view *view, enum open_flags flags)
2716 if (view->pipe)
2717 end_update(view, TRUE);
2718 if (!view->ops->open(view, flags)) {
2719 report("Failed to load %s view", view->name);
2720 return;
2722 restore_view_position(view);
2724 if (view->pipe && view->lines == 0) {
2725 /* Clear the old view and let the incremental updating refill
2726 * the screen. */
2727 werase(view->win);
2728 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2729 report("");
2730 } else if (view_is_displayed(view)) {
2731 redraw_view(view);
2732 report("");
2736 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2737 #define reload_view(view) load_view(view, OPEN_RELOAD)
2739 static void
2740 split_view(struct view *prev, struct view *view)
2742 display[1] = view;
2743 current_view = 1;
2744 view->parent = prev;
2745 resize_display();
2747 if (prev->lineno - prev->offset >= prev->height) {
2748 /* Take the title line into account. */
2749 int lines = prev->lineno - prev->offset - prev->height + 1;
2751 /* Scroll the view that was split if the current line is
2752 * outside the new limited view. */
2753 do_scroll_view(prev, lines);
2756 if (view != prev && view_is_displayed(prev)) {
2757 /* "Blur" the previous view. */
2758 update_view_title(prev);
2762 static void
2763 open_view(struct view *prev, enum request request, enum open_flags flags)
2765 bool split = !!(flags & OPEN_SPLIT);
2766 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
2767 struct view *view = VIEW(request);
2768 int nviews = displayed_views();
2770 assert(flags ^ OPEN_REFRESH);
2772 if (view == prev && nviews == 1 && !reload) {
2773 report("Already in %s view", view->name);
2774 return;
2777 if (view->git_dir && !opt_git_dir[0]) {
2778 report("The %s view is disabled in pager view", view->name);
2779 return;
2782 if (split) {
2783 split_view(prev, view);
2784 } else {
2785 maximize_view(view, FALSE);
2788 /* No prev signals that this is the first loaded view. */
2789 if (prev && view != prev) {
2790 view->prev = prev;
2793 load_view(view, flags);
2796 static void
2797 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
2799 enum request request = view - views + REQ_OFFSET + 1;
2801 if (view->pipe)
2802 end_update(view, TRUE);
2803 view->dir = dir;
2805 if (!argv_copy(&view->argv, argv)) {
2806 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
2807 } else {
2808 open_view(prev, request, flags | OPEN_PREPARED);
2812 static void
2813 open_file(struct view *prev, struct view *view, const char *file, enum open_flags flags)
2815 const char *file_argv[] = { opt_cdup, file , NULL };
2817 open_argv(prev, view, file_argv, opt_cdup, flags);
2820 static void
2821 open_external_viewer(const char *argv[], const char *dir)
2823 def_prog_mode(); /* save current tty modes */
2824 endwin(); /* restore original tty modes */
2825 io_run_fg(argv, dir);
2826 fprintf(stderr, "Press Enter to continue");
2827 getc(opt_tty);
2828 reset_prog_mode();
2829 redraw_display(TRUE);
2832 static void
2833 open_mergetool(const char *file)
2835 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2837 open_external_viewer(mergetool_argv, opt_cdup);
2840 static void
2841 open_editor(const char *file)
2843 const char *editor_argv[] = { "vi", file, NULL };
2844 const char *editor;
2846 editor = getenv("GIT_EDITOR");
2847 if (!editor && *opt_editor)
2848 editor = opt_editor;
2849 if (!editor)
2850 editor = getenv("VISUAL");
2851 if (!editor)
2852 editor = getenv("EDITOR");
2853 if (!editor)
2854 editor = "vi";
2856 editor_argv[0] = editor;
2857 open_external_viewer(editor_argv, opt_cdup);
2860 static void
2861 open_run_request(enum request request)
2863 struct run_request *req = get_run_request(request);
2864 const char **argv = NULL;
2866 if (!req) {
2867 report("Unknown run request");
2868 return;
2871 if (format_argv(&argv, req->argv, FALSE))
2872 open_external_viewer(argv, NULL);
2873 if (argv)
2874 argv_free(argv);
2875 free(argv);
2879 * User request switch noodle
2882 static int
2883 view_driver(struct view *view, enum request request)
2885 int i;
2887 if (request == REQ_NONE)
2888 return TRUE;
2890 if (request > REQ_NONE) {
2891 open_run_request(request);
2892 view_request(view, REQ_REFRESH);
2893 return TRUE;
2896 request = view_request(view, request);
2897 if (request == REQ_NONE)
2898 return TRUE;
2900 switch (request) {
2901 case REQ_MOVE_UP:
2902 case REQ_MOVE_DOWN:
2903 case REQ_MOVE_PAGE_UP:
2904 case REQ_MOVE_PAGE_DOWN:
2905 case REQ_MOVE_FIRST_LINE:
2906 case REQ_MOVE_LAST_LINE:
2907 move_view(view, request);
2908 break;
2910 case REQ_SCROLL_FIRST_COL:
2911 case REQ_SCROLL_LEFT:
2912 case REQ_SCROLL_RIGHT:
2913 case REQ_SCROLL_LINE_DOWN:
2914 case REQ_SCROLL_LINE_UP:
2915 case REQ_SCROLL_PAGE_DOWN:
2916 case REQ_SCROLL_PAGE_UP:
2917 scroll_view(view, request);
2918 break;
2920 case REQ_VIEW_BLAME:
2921 if (!opt_file[0]) {
2922 report("No file chosen, press %s to open tree view",
2923 get_key(view->keymap, REQ_VIEW_TREE));
2924 break;
2926 open_view(view, request, OPEN_DEFAULT);
2927 break;
2929 case REQ_VIEW_BLOB:
2930 if (!ref_blob[0]) {
2931 report("No file chosen, press %s to open tree view",
2932 get_key(view->keymap, REQ_VIEW_TREE));
2933 break;
2935 open_view(view, request, OPEN_DEFAULT);
2936 break;
2938 case REQ_VIEW_PAGER:
2939 if (view == NULL) {
2940 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
2941 die("Failed to open stdin");
2942 open_view(view, request, OPEN_PREPARED);
2943 break;
2946 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
2947 report("No pager content, press %s to run command from prompt",
2948 get_key(view->keymap, REQ_PROMPT));
2949 break;
2951 open_view(view, request, OPEN_DEFAULT);
2952 break;
2954 case REQ_VIEW_STAGE:
2955 if (!VIEW(REQ_VIEW_STAGE)->lines) {
2956 report("No stage content, press %s to open the status view and choose file",
2957 get_key(view->keymap, REQ_VIEW_STATUS));
2958 break;
2960 open_view(view, request, OPEN_DEFAULT);
2961 break;
2963 case REQ_VIEW_STATUS:
2964 if (opt_is_inside_work_tree == FALSE) {
2965 report("The status view requires a working tree");
2966 break;
2968 open_view(view, request, OPEN_DEFAULT);
2969 break;
2971 case REQ_VIEW_MAIN:
2972 case REQ_VIEW_DIFF:
2973 case REQ_VIEW_LOG:
2974 case REQ_VIEW_TREE:
2975 case REQ_VIEW_HELP:
2976 case REQ_VIEW_BRANCH:
2977 open_view(view, request, OPEN_DEFAULT);
2978 break;
2980 case REQ_NEXT:
2981 case REQ_PREVIOUS:
2982 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
2984 if (view->parent) {
2985 int line;
2987 view = view->parent;
2988 line = view->lineno;
2989 move_view(view, request);
2990 if (view_is_displayed(view))
2991 update_view_title(view);
2992 if (line != view->lineno)
2993 view_request(view, REQ_ENTER);
2994 } else {
2995 move_view(view, request);
2997 break;
2999 case REQ_VIEW_NEXT:
3001 int nviews = displayed_views();
3002 int next_view = (current_view + 1) % nviews;
3004 if (next_view == current_view) {
3005 report("Only one view is displayed");
3006 break;
3009 current_view = next_view;
3010 /* Blur out the title of the previous view. */
3011 update_view_title(view);
3012 report("");
3013 break;
3015 case REQ_REFRESH:
3016 report("Refreshing is not yet supported for the %s view", view->name);
3017 break;
3019 case REQ_MAXIMIZE:
3020 if (displayed_views() == 2)
3021 maximize_view(view, TRUE);
3022 break;
3024 case REQ_OPTIONS:
3025 case REQ_TOGGLE_LINENO:
3026 case REQ_TOGGLE_DATE:
3027 case REQ_TOGGLE_AUTHOR:
3028 case REQ_TOGGLE_GRAPHIC:
3029 case REQ_TOGGLE_REV_GRAPH:
3030 case REQ_TOGGLE_REFS:
3031 toggle_option(request);
3032 break;
3034 case REQ_TOGGLE_SORT_FIELD:
3035 case REQ_TOGGLE_SORT_ORDER:
3036 report("Sorting is not yet supported for the %s view", view->name);
3037 break;
3039 case REQ_SEARCH:
3040 case REQ_SEARCH_BACK:
3041 search_view(view, request);
3042 break;
3044 case REQ_FIND_NEXT:
3045 case REQ_FIND_PREV:
3046 find_next(view, request);
3047 break;
3049 case REQ_STOP_LOADING:
3050 foreach_view(view, i) {
3051 if (view->pipe)
3052 report("Stopped loading the %s view", view->name),
3053 end_update(view, TRUE);
3055 break;
3057 case REQ_SHOW_VERSION:
3058 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3059 return TRUE;
3061 case REQ_SCREEN_REDRAW:
3062 redraw_display(TRUE);
3063 break;
3065 case REQ_EDIT:
3066 report("Nothing to edit");
3067 break;
3069 case REQ_ENTER:
3070 report("Nothing to enter");
3071 break;
3073 case REQ_VIEW_CLOSE:
3074 /* XXX: Mark closed views by letting view->prev point to the
3075 * view itself. Parents to closed view should never be
3076 * followed. */
3077 if (view->prev && view->prev != view) {
3078 maximize_view(view->prev, TRUE);
3079 view->prev = view;
3080 break;
3082 /* Fall-through */
3083 case REQ_QUIT:
3084 return FALSE;
3086 default:
3087 report("Unknown key, press %s for help",
3088 get_key(view->keymap, REQ_VIEW_HELP));
3089 return TRUE;
3092 return TRUE;
3097 * View backend utilities
3100 enum sort_field {
3101 ORDERBY_NAME,
3102 ORDERBY_DATE,
3103 ORDERBY_AUTHOR,
3106 struct sort_state {
3107 const enum sort_field *fields;
3108 size_t size, current;
3109 bool reverse;
3112 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3113 #define get_sort_field(state) ((state).fields[(state).current])
3114 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3116 static void
3117 sort_view(struct view *view, enum request request, struct sort_state *state,
3118 int (*compare)(const void *, const void *))
3120 switch (request) {
3121 case REQ_TOGGLE_SORT_FIELD:
3122 state->current = (state->current + 1) % state->size;
3123 break;
3125 case REQ_TOGGLE_SORT_ORDER:
3126 state->reverse = !state->reverse;
3127 break;
3128 default:
3129 die("Not a sort request");
3132 qsort(view->line, view->lines, sizeof(*view->line), compare);
3133 redraw_view(view);
3136 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3138 /* Small author cache to reduce memory consumption. It uses binary
3139 * search to lookup or find place to position new entries. No entries
3140 * are ever freed. */
3141 static const char *
3142 get_author(const char *name)
3144 static const char **authors;
3145 static size_t authors_size;
3146 int from = 0, to = authors_size - 1;
3148 while (from <= to) {
3149 size_t pos = (to + from) / 2;
3150 int cmp = strcmp(name, authors[pos]);
3152 if (!cmp)
3153 return authors[pos];
3155 if (cmp < 0)
3156 to = pos - 1;
3157 else
3158 from = pos + 1;
3161 if (!realloc_authors(&authors, authors_size, 1))
3162 return NULL;
3163 name = strdup(name);
3164 if (!name)
3165 return NULL;
3167 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3168 authors[from] = name;
3169 authors_size++;
3171 return name;
3174 static void
3175 parse_timesec(struct time *time, const char *sec)
3177 time->sec = (time_t) atol(sec);
3180 static void
3181 parse_timezone(struct time *time, const char *zone)
3183 long tz;
3185 tz = ('0' - zone[1]) * 60 * 60 * 10;
3186 tz += ('0' - zone[2]) * 60 * 60;
3187 tz += ('0' - zone[3]) * 60 * 10;
3188 tz += ('0' - zone[4]) * 60;
3190 if (zone[0] == '-')
3191 tz = -tz;
3193 time->tz = tz;
3194 time->sec -= tz;
3197 /* Parse author lines where the name may be empty:
3198 * author <email@address.tld> 1138474660 +0100
3200 static void
3201 parse_author_line(char *ident, const char **author, struct time *time)
3203 char *nameend = strchr(ident, '<');
3204 char *emailend = strchr(ident, '>');
3206 if (nameend && emailend)
3207 *nameend = *emailend = 0;
3208 ident = chomp_string(ident);
3209 if (!*ident) {
3210 if (nameend)
3211 ident = chomp_string(nameend + 1);
3212 if (!*ident)
3213 ident = "Unknown";
3216 *author = get_author(ident);
3218 /* Parse epoch and timezone */
3219 if (emailend && emailend[1] == ' ') {
3220 char *secs = emailend + 2;
3221 char *zone = strchr(secs, ' ');
3223 parse_timesec(time, secs);
3225 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3226 parse_timezone(time, zone + 1);
3231 * Pager backend
3234 static bool
3235 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3237 if (opt_line_number && draw_lineno(view, lineno))
3238 return TRUE;
3240 draw_text(view, line->type, line->data);
3241 return TRUE;
3244 static bool
3245 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3247 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3248 char ref[SIZEOF_STR];
3250 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3251 return TRUE;
3253 /* This is the only fatal call, since it can "corrupt" the buffer. */
3254 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3255 return FALSE;
3257 return TRUE;
3260 static void
3261 add_pager_refs(struct view *view, struct line *line)
3263 char buf[SIZEOF_STR];
3264 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3265 struct ref_list *list;
3266 size_t bufpos = 0, i;
3267 const char *sep = "Refs: ";
3268 bool is_tag = FALSE;
3270 assert(line->type == LINE_COMMIT);
3272 list = get_ref_list(commit_id);
3273 if (!list) {
3274 if (view->type == VIEW_DIFF)
3275 goto try_add_describe_ref;
3276 return;
3279 for (i = 0; i < list->size; i++) {
3280 struct ref *ref = list->refs[i];
3281 const char *fmt = ref->tag ? "%s[%s]" :
3282 ref->remote ? "%s<%s>" : "%s%s";
3284 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3285 return;
3286 sep = ", ";
3287 if (ref->tag)
3288 is_tag = TRUE;
3291 if (!is_tag && view->type == VIEW_DIFF) {
3292 try_add_describe_ref:
3293 /* Add <tag>-g<commit_id> "fake" reference. */
3294 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3295 return;
3298 if (bufpos == 0)
3299 return;
3301 add_line_text(view, buf, LINE_PP_REFS);
3304 static bool
3305 pager_read(struct view *view, char *data)
3307 struct line *line;
3309 if (!data)
3310 return TRUE;
3312 line = add_line_text(view, data, get_line_type(data));
3313 if (!line)
3314 return FALSE;
3316 if (line->type == LINE_COMMIT &&
3317 (view->type == VIEW_DIFF ||
3318 view->type == VIEW_LOG))
3319 add_pager_refs(view, line);
3321 return TRUE;
3324 static enum request
3325 pager_request(struct view *view, enum request request, struct line *line)
3327 int split = 0;
3329 if (request != REQ_ENTER)
3330 return request;
3332 if (line->type == LINE_COMMIT &&
3333 (view->type == VIEW_LOG ||
3334 view->type == VIEW_PAGER)) {
3335 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3336 split = 1;
3339 /* Always scroll the view even if it was split. That way
3340 * you can use Enter to scroll through the log view and
3341 * split open each commit diff. */
3342 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3344 /* FIXME: A minor workaround. Scrolling the view will call report("")
3345 * but if we are scrolling a non-current view this won't properly
3346 * update the view title. */
3347 if (split)
3348 update_view_title(view);
3350 return REQ_NONE;
3353 static bool
3354 pager_grep(struct view *view, struct line *line)
3356 const char *text[] = { line->data, NULL };
3358 return grep_text(view, text);
3361 static void
3362 pager_select(struct view *view, struct line *line)
3364 if (line->type == LINE_COMMIT) {
3365 char *text = (char *)line->data + STRING_SIZE("commit ");
3367 if (view->type != VIEW_PAGER)
3368 string_copy_rev(view->ref, text);
3369 string_copy_rev(ref_commit, text);
3373 static struct view_ops pager_ops = {
3374 "line",
3375 view_open,
3376 pager_read,
3377 pager_draw,
3378 pager_request,
3379 pager_grep,
3380 pager_select,
3383 static bool
3384 log_open(struct view *view, enum open_flags flags)
3386 static const char *log_argv[] = {
3387 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3390 return begin_update(view, NULL, log_argv, flags);
3393 static enum request
3394 log_request(struct view *view, enum request request, struct line *line)
3396 switch (request) {
3397 case REQ_REFRESH:
3398 load_refs();
3399 refresh_view(view);
3400 return REQ_NONE;
3401 default:
3402 return pager_request(view, request, line);
3406 static struct view_ops log_ops = {
3407 "line",
3408 log_open,
3409 pager_read,
3410 pager_draw,
3411 log_request,
3412 pager_grep,
3413 pager_select,
3416 static bool
3417 diff_open(struct view *view, enum open_flags flags)
3419 static const char *diff_argv[] = {
3420 "git", "show", "--pretty=fuller", "--no-color", "--root",
3421 "--patch-with-stat", "--find-copies-harder", "-C",
3422 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3425 return begin_update(view, NULL, diff_argv, flags);
3428 static bool
3429 diff_read(struct view *view, char *data)
3431 if (!data) {
3432 /* Fall back to retry if no diff will be shown. */
3433 if (view->lines == 0 && opt_file_argv) {
3434 int pos = argv_size(view->argv)
3435 - argv_size(opt_file_argv) - 1;
3437 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3438 for (; view->argv[pos]; pos++) {
3439 free((void *) view->argv[pos]);
3440 view->argv[pos] = NULL;
3443 if (view->pipe)
3444 io_done(view->pipe);
3445 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3446 return FALSE;
3449 return TRUE;
3452 return pager_read(view, data);
3455 static struct view_ops diff_ops = {
3456 "line",
3457 diff_open,
3458 diff_read,
3459 pager_draw,
3460 pager_request,
3461 pager_grep,
3462 pager_select,
3466 * Help backend
3469 static bool help_keymap_hidden[ARRAY_SIZE(keymap_map)];
3471 static bool
3472 help_open_keymap_title(struct view *view, enum keymap keymap)
3474 struct line *line;
3476 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
3477 help_keymap_hidden[keymap] ? '+' : '-',
3478 enum_name(keymap_map[keymap]));
3479 if (line)
3480 line->other = keymap;
3482 return help_keymap_hidden[keymap];
3485 static void
3486 help_open_keymap(struct view *view, enum keymap keymap)
3488 const char *group = NULL;
3489 char buf[SIZEOF_STR];
3490 size_t bufpos;
3491 bool add_title = TRUE;
3492 int i;
3494 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
3495 const char *key = NULL;
3497 if (req_info[i].request == REQ_NONE)
3498 continue;
3500 if (!req_info[i].request) {
3501 group = req_info[i].help;
3502 continue;
3505 key = get_keys(keymap, req_info[i].request, TRUE);
3506 if (!key || !*key)
3507 continue;
3509 if (add_title && help_open_keymap_title(view, keymap))
3510 return;
3511 add_title = FALSE;
3513 if (group) {
3514 add_line_text(view, group, LINE_HELP_GROUP);
3515 group = NULL;
3518 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
3519 enum_name(req_info[i]), req_info[i].help);
3522 group = "External commands:";
3524 for (i = 0; i < run_requests; i++) {
3525 struct run_request *req = get_run_request(REQ_NONE + i + 1);
3526 const char *key;
3527 int argc;
3529 if (!req || req->keymap != keymap)
3530 continue;
3532 key = get_key_name(req->key);
3533 if (!*key)
3534 key = "(no key defined)";
3536 if (add_title && help_open_keymap_title(view, keymap))
3537 return;
3538 if (group) {
3539 add_line_text(view, group, LINE_HELP_GROUP);
3540 group = NULL;
3543 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
3544 if (!string_format_from(buf, &bufpos, "%s%s",
3545 argc ? " " : "", req->argv[argc]))
3546 return;
3548 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
3552 static bool
3553 help_open(struct view *view, enum open_flags flags)
3555 enum keymap keymap;
3557 reset_view(view);
3558 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
3559 add_line_text(view, "", LINE_DEFAULT);
3561 for (keymap = 0; keymap < ARRAY_SIZE(keymap_map); keymap++)
3562 help_open_keymap(view, keymap);
3564 return TRUE;
3567 static enum request
3568 help_request(struct view *view, enum request request, struct line *line)
3570 switch (request) {
3571 case REQ_ENTER:
3572 if (line->type == LINE_HELP_KEYMAP) {
3573 help_keymap_hidden[line->other] =
3574 !help_keymap_hidden[line->other];
3575 refresh_view(view);
3578 return REQ_NONE;
3579 default:
3580 return pager_request(view, request, line);
3584 static struct view_ops help_ops = {
3585 "line",
3586 help_open,
3587 NULL,
3588 pager_draw,
3589 help_request,
3590 pager_grep,
3591 pager_select,
3596 * Tree backend
3599 struct tree_stack_entry {
3600 struct tree_stack_entry *prev; /* Entry below this in the stack */
3601 unsigned long lineno; /* Line number to restore */
3602 char *name; /* Position of name in opt_path */
3605 /* The top of the path stack. */
3606 static struct tree_stack_entry *tree_stack = NULL;
3607 unsigned long tree_lineno = 0;
3609 static void
3610 pop_tree_stack_entry(void)
3612 struct tree_stack_entry *entry = tree_stack;
3614 tree_lineno = entry->lineno;
3615 entry->name[0] = 0;
3616 tree_stack = entry->prev;
3617 free(entry);
3620 static void
3621 push_tree_stack_entry(const char *name, unsigned long lineno)
3623 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
3624 size_t pathlen = strlen(opt_path);
3626 if (!entry)
3627 return;
3629 entry->prev = tree_stack;
3630 entry->name = opt_path + pathlen;
3631 tree_stack = entry;
3633 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
3634 pop_tree_stack_entry();
3635 return;
3638 /* Move the current line to the first tree entry. */
3639 tree_lineno = 1;
3640 entry->lineno = lineno;
3643 /* Parse output from git-ls-tree(1):
3645 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
3648 #define SIZEOF_TREE_ATTR \
3649 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
3651 #define SIZEOF_TREE_MODE \
3652 STRING_SIZE("100644 ")
3654 #define TREE_ID_OFFSET \
3655 STRING_SIZE("100644 blob ")
3657 struct tree_entry {
3658 char id[SIZEOF_REV];
3659 mode_t mode;
3660 struct time time; /* Date from the author ident. */
3661 const char *author; /* Author of the commit. */
3662 char name[1];
3665 static const char *
3666 tree_path(const struct line *line)
3668 return ((struct tree_entry *) line->data)->name;
3671 static int
3672 tree_compare_entry(const struct line *line1, const struct line *line2)
3674 if (line1->type != line2->type)
3675 return line1->type == LINE_TREE_DIR ? -1 : 1;
3676 return strcmp(tree_path(line1), tree_path(line2));
3679 static const enum sort_field tree_sort_fields[] = {
3680 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
3682 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
3684 static int
3685 tree_compare(const void *l1, const void *l2)
3687 const struct line *line1 = (const struct line *) l1;
3688 const struct line *line2 = (const struct line *) l2;
3689 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
3690 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
3692 if (line1->type == LINE_TREE_HEAD)
3693 return -1;
3694 if (line2->type == LINE_TREE_HEAD)
3695 return 1;
3697 switch (get_sort_field(tree_sort_state)) {
3698 case ORDERBY_DATE:
3699 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
3701 case ORDERBY_AUTHOR:
3702 return sort_order(tree_sort_state, strcmp(entry1->author, entry2->author));
3704 case ORDERBY_NAME:
3705 default:
3706 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
3711 static struct line *
3712 tree_entry(struct view *view, enum line_type type, const char *path,
3713 const char *mode, const char *id)
3715 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
3716 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
3718 if (!entry || !line) {
3719 free(entry);
3720 return NULL;
3723 strncpy(entry->name, path, strlen(path));
3724 if (mode)
3725 entry->mode = strtoul(mode, NULL, 8);
3726 if (id)
3727 string_copy_rev(entry->id, id);
3729 return line;
3732 static bool
3733 tree_read_date(struct view *view, char *text, bool *read_date)
3735 static const char *author_name;
3736 static struct time author_time;
3738 if (!text && *read_date) {
3739 *read_date = FALSE;
3740 return TRUE;
3742 } else if (!text) {
3743 /* Find next entry to process */
3744 const char *log_file[] = {
3745 "git", "log", "--no-color", "--pretty=raw",
3746 "--cc", "--raw", view->id, "--", "%(directory)", NULL
3749 if (!view->lines) {
3750 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
3751 report("Tree is empty");
3752 return TRUE;
3755 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
3756 report("Failed to load tree data");
3757 return TRUE;
3760 *read_date = TRUE;
3761 return FALSE;
3763 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
3764 parse_author_line(text + STRING_SIZE("author "),
3765 &author_name, &author_time);
3767 } else if (*text == ':') {
3768 char *pos;
3769 size_t annotated = 1;
3770 size_t i;
3772 pos = strchr(text, '\t');
3773 if (!pos)
3774 return TRUE;
3775 text = pos + 1;
3776 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
3777 text += strlen(opt_path);
3778 pos = strchr(text, '/');
3779 if (pos)
3780 *pos = 0;
3782 for (i = 1; i < view->lines; i++) {
3783 struct line *line = &view->line[i];
3784 struct tree_entry *entry = line->data;
3786 annotated += !!entry->author;
3787 if (entry->author || strcmp(entry->name, text))
3788 continue;
3790 entry->author = author_name;
3791 entry->time = author_time;
3792 line->dirty = 1;
3793 break;
3796 if (annotated == view->lines)
3797 io_kill(view->pipe);
3799 return TRUE;
3802 static bool
3803 tree_read(struct view *view, char *text)
3805 static bool read_date = FALSE;
3806 struct tree_entry *data;
3807 struct line *entry, *line;
3808 enum line_type type;
3809 size_t textlen = text ? strlen(text) : 0;
3810 char *path = text + SIZEOF_TREE_ATTR;
3812 if (read_date || !text)
3813 return tree_read_date(view, text, &read_date);
3815 if (textlen <= SIZEOF_TREE_ATTR)
3816 return FALSE;
3817 if (view->lines == 0 &&
3818 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
3819 return FALSE;
3821 /* Strip the path part ... */
3822 if (*opt_path) {
3823 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
3824 size_t striplen = strlen(opt_path);
3826 if (pathlen > striplen)
3827 memmove(path, path + striplen,
3828 pathlen - striplen + 1);
3830 /* Insert "link" to parent directory. */
3831 if (view->lines == 1 &&
3832 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
3833 return FALSE;
3836 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
3837 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
3838 if (!entry)
3839 return FALSE;
3840 data = entry->data;
3842 /* Skip "Directory ..." and ".." line. */
3843 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
3844 if (tree_compare_entry(line, entry) <= 0)
3845 continue;
3847 memmove(line + 1, line, (entry - line) * sizeof(*entry));
3849 line->data = data;
3850 line->type = type;
3851 for (; line <= entry; line++)
3852 line->dirty = line->cleareol = 1;
3853 return TRUE;
3856 if (tree_lineno > view->lineno) {
3857 view->lineno = tree_lineno;
3858 tree_lineno = 0;
3861 return TRUE;
3864 static bool
3865 tree_draw(struct view *view, struct line *line, unsigned int lineno)
3867 struct tree_entry *entry = line->data;
3869 if (line->type == LINE_TREE_HEAD) {
3870 if (draw_text(view, line->type, "Directory path /"))
3871 return TRUE;
3872 } else {
3873 if (draw_mode(view, entry->mode))
3874 return TRUE;
3876 if (draw_author(view, entry->author))
3877 return TRUE;
3879 if (draw_date(view, &entry->time))
3880 return TRUE;
3883 draw_text(view, line->type, entry->name);
3884 return TRUE;
3887 static void
3888 open_blob_editor(const char *id)
3890 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
3891 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
3892 int fd = mkstemp(file);
3894 if (fd == -1)
3895 report("Failed to create temporary file");
3896 else if (!io_run_append(blob_argv, fd))
3897 report("Failed to save blob data to file");
3898 else
3899 open_editor(file);
3900 if (fd != -1)
3901 unlink(file);
3904 static enum request
3905 tree_request(struct view *view, enum request request, struct line *line)
3907 enum open_flags flags;
3908 struct tree_entry *entry = line->data;
3910 switch (request) {
3911 case REQ_VIEW_BLAME:
3912 if (line->type != LINE_TREE_FILE) {
3913 report("Blame only supported for files");
3914 return REQ_NONE;
3917 string_copy(opt_ref, view->vid);
3918 return request;
3920 case REQ_EDIT:
3921 if (line->type != LINE_TREE_FILE) {
3922 report("Edit only supported for files");
3923 } else if (!is_head_commit(view->vid)) {
3924 open_blob_editor(entry->id);
3925 } else {
3926 open_editor(opt_file);
3928 return REQ_NONE;
3930 case REQ_TOGGLE_SORT_FIELD:
3931 case REQ_TOGGLE_SORT_ORDER:
3932 sort_view(view, request, &tree_sort_state, tree_compare);
3933 return REQ_NONE;
3935 case REQ_PARENT:
3936 if (!*opt_path) {
3937 /* quit view if at top of tree */
3938 return REQ_VIEW_CLOSE;
3940 /* fake 'cd ..' */
3941 line = &view->line[1];
3942 break;
3944 case REQ_ENTER:
3945 break;
3947 default:
3948 return request;
3951 /* Cleanup the stack if the tree view is at a different tree. */
3952 while (!*opt_path && tree_stack)
3953 pop_tree_stack_entry();
3955 switch (line->type) {
3956 case LINE_TREE_DIR:
3957 /* Depending on whether it is a subdirectory or parent link
3958 * mangle the path buffer. */
3959 if (line == &view->line[1] && *opt_path) {
3960 pop_tree_stack_entry();
3962 } else {
3963 const char *basename = tree_path(line);
3965 push_tree_stack_entry(basename, view->lineno);
3968 /* Trees and subtrees share the same ID, so they are not not
3969 * unique like blobs. */
3970 flags = OPEN_RELOAD;
3971 request = REQ_VIEW_TREE;
3972 break;
3974 case LINE_TREE_FILE:
3975 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
3976 request = REQ_VIEW_BLOB;
3977 break;
3979 default:
3980 return REQ_NONE;
3983 open_view(view, request, flags);
3984 if (request == REQ_VIEW_TREE)
3985 view->lineno = tree_lineno;
3987 return REQ_NONE;
3990 static bool
3991 tree_grep(struct view *view, struct line *line)
3993 struct tree_entry *entry = line->data;
3994 const char *text[] = {
3995 entry->name,
3996 mkauthor(entry->author, opt_author_cols, opt_author),
3997 mkdate(&entry->time, opt_date),
3998 NULL
4001 return grep_text(view, text);
4004 static void
4005 tree_select(struct view *view, struct line *line)
4007 struct tree_entry *entry = line->data;
4009 if (line->type == LINE_TREE_FILE) {
4010 string_copy_rev(ref_blob, entry->id);
4011 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4013 } else if (line->type != LINE_TREE_DIR) {
4014 return;
4017 string_copy_rev(view->ref, entry->id);
4020 static bool
4021 tree_open(struct view *view, enum open_flags flags)
4023 static const char *tree_argv[] = {
4024 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4027 if (view->lines == 0 && opt_prefix[0]) {
4028 char *pos = opt_prefix;
4030 while (pos && *pos) {
4031 char *end = strchr(pos, '/');
4033 if (end)
4034 *end = 0;
4035 push_tree_stack_entry(pos, 0);
4036 pos = end;
4037 if (end) {
4038 *end = '/';
4039 pos++;
4043 } else if (strcmp(view->vid, view->id)) {
4044 opt_path[0] = 0;
4047 return begin_update(view, opt_cdup, tree_argv, flags);
4050 static struct view_ops tree_ops = {
4051 "file",
4052 tree_open,
4053 tree_read,
4054 tree_draw,
4055 tree_request,
4056 tree_grep,
4057 tree_select,
4060 static bool
4061 blob_open(struct view *view, enum open_flags flags)
4063 static const char *blob_argv[] = {
4064 "git", "cat-file", "blob", "%(blob)", NULL
4067 return begin_update(view, NULL, blob_argv, flags);
4070 static bool
4071 blob_read(struct view *view, char *line)
4073 if (!line)
4074 return TRUE;
4075 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4078 static enum request
4079 blob_request(struct view *view, enum request request, struct line *line)
4081 switch (request) {
4082 case REQ_EDIT:
4083 open_blob_editor(view->vid);
4084 return REQ_NONE;
4085 default:
4086 return pager_request(view, request, line);
4090 static struct view_ops blob_ops = {
4091 "line",
4092 blob_open,
4093 blob_read,
4094 pager_draw,
4095 blob_request,
4096 pager_grep,
4097 pager_select,
4101 * Blame backend
4103 * Loading the blame view is a two phase job:
4105 * 1. File content is read either using opt_file from the
4106 * filesystem or using git-cat-file.
4107 * 2. Then blame information is incrementally added by
4108 * reading output from git-blame.
4111 struct blame_commit {
4112 char id[SIZEOF_REV]; /* SHA1 ID. */
4113 char title[128]; /* First line of the commit message. */
4114 const char *author; /* Author of the commit. */
4115 struct time time; /* Date from the author ident. */
4116 char filename[128]; /* Name of file. */
4117 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
4118 char parent_filename[128]; /* Parent/previous name of file. */
4121 struct blame {
4122 struct blame_commit *commit;
4123 unsigned long lineno;
4124 char text[1];
4127 static bool
4128 blame_open(struct view *view, enum open_flags flags)
4130 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4131 char path[SIZEOF_STR];
4132 size_t i;
4134 if (!view->prev && *opt_prefix) {
4135 string_copy(path, opt_file);
4136 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4137 return FALSE;
4140 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4141 const char *blame_cat_file_argv[] = {
4142 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4145 if (!begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4146 return FALSE;
4149 /* First pass: remove multiple references to the same commit. */
4150 for (i = 0; i < view->lines; i++) {
4151 struct blame *blame = view->line[i].data;
4153 if (blame->commit && blame->commit->id[0])
4154 blame->commit->id[0] = 0;
4155 else
4156 blame->commit = NULL;
4159 /* Second pass: free existing references. */
4160 for (i = 0; i < view->lines; i++) {
4161 struct blame *blame = view->line[i].data;
4163 if (blame->commit)
4164 free(blame->commit);
4167 string_format(view->vid, "%s", opt_file);
4168 string_format(view->ref, "%s ...", opt_file);
4170 return TRUE;
4173 static struct blame_commit *
4174 get_blame_commit(struct view *view, const char *id)
4176 size_t i;
4178 for (i = 0; i < view->lines; i++) {
4179 struct blame *blame = view->line[i].data;
4181 if (!blame->commit)
4182 continue;
4184 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4185 return blame->commit;
4189 struct blame_commit *commit = calloc(1, sizeof(*commit));
4191 if (commit)
4192 string_ncopy(commit->id, id, SIZEOF_REV);
4193 return commit;
4197 static bool
4198 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4200 const char *pos = *posref;
4202 *posref = NULL;
4203 pos = strchr(pos + 1, ' ');
4204 if (!pos || !isdigit(pos[1]))
4205 return FALSE;
4206 *number = atoi(pos + 1);
4207 if (*number < min || *number > max)
4208 return FALSE;
4210 *posref = pos;
4211 return TRUE;
4214 static struct blame_commit *
4215 parse_blame_commit(struct view *view, const char *text, int *blamed)
4217 struct blame_commit *commit;
4218 struct blame *blame;
4219 const char *pos = text + SIZEOF_REV - 2;
4220 size_t orig_lineno = 0;
4221 size_t lineno;
4222 size_t group;
4224 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4225 return NULL;
4227 if (!parse_number(&pos, &orig_lineno, 1, 9999999) ||
4228 !parse_number(&pos, &lineno, 1, view->lines) ||
4229 !parse_number(&pos, &group, 1, view->lines - lineno + 1))
4230 return NULL;
4232 commit = get_blame_commit(view, text);
4233 if (!commit)
4234 return NULL;
4236 *blamed += group;
4237 while (group--) {
4238 struct line *line = &view->line[lineno + group - 1];
4240 blame = line->data;
4241 blame->commit = commit;
4242 blame->lineno = orig_lineno + group - 1;
4243 line->dirty = 1;
4246 return commit;
4249 static bool
4250 blame_read_file(struct view *view, const char *line, bool *read_file)
4252 if (!line) {
4253 const char *blame_argv[] = {
4254 "git", "blame", "%(blameargs)", "--incremental",
4255 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4258 if (view->lines == 0 && !view->prev)
4259 die("No blame exist for %s", view->vid);
4261 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
4262 report("Failed to load blame data");
4263 return TRUE;
4266 *read_file = FALSE;
4267 return FALSE;
4269 } else {
4270 size_t linelen = strlen(line);
4271 struct blame *blame = malloc(sizeof(*blame) + linelen);
4273 if (!blame)
4274 return FALSE;
4276 blame->commit = NULL;
4277 strncpy(blame->text, line, linelen);
4278 blame->text[linelen] = 0;
4279 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4283 static bool
4284 match_blame_header(const char *name, char **line)
4286 size_t namelen = strlen(name);
4287 bool matched = !strncmp(name, *line, namelen);
4289 if (matched)
4290 *line += namelen;
4292 return matched;
4295 static bool
4296 blame_read(struct view *view, char *line)
4298 static struct blame_commit *commit = NULL;
4299 static int blamed = 0;
4300 static bool read_file = TRUE;
4302 if (read_file)
4303 return blame_read_file(view, line, &read_file);
4305 if (!line) {
4306 /* Reset all! */
4307 commit = NULL;
4308 blamed = 0;
4309 read_file = TRUE;
4310 string_format(view->ref, "%s", view->vid);
4311 if (view_is_displayed(view)) {
4312 update_view_title(view);
4313 redraw_view_from(view, 0);
4315 return TRUE;
4318 if (!commit) {
4319 commit = parse_blame_commit(view, line, &blamed);
4320 string_format(view->ref, "%s %2d%%", view->vid,
4321 view->lines ? blamed * 100 / view->lines : 0);
4323 } else if (match_blame_header("author ", &line)) {
4324 commit->author = get_author(line);
4326 } else if (match_blame_header("author-time ", &line)) {
4327 parse_timesec(&commit->time, line);
4329 } else if (match_blame_header("author-tz ", &line)) {
4330 parse_timezone(&commit->time, line);
4332 } else if (match_blame_header("summary ", &line)) {
4333 string_ncopy(commit->title, line, strlen(line));
4335 } else if (match_blame_header("previous ", &line)) {
4336 if (strlen(line) <= SIZEOF_REV)
4337 return FALSE;
4338 string_copy_rev(commit->parent_id, line);
4339 line += SIZEOF_REV;
4340 string_ncopy(commit->parent_filename, line, strlen(line));
4342 } else if (match_blame_header("filename ", &line)) {
4343 string_ncopy(commit->filename, line, strlen(line));
4344 commit = NULL;
4347 return TRUE;
4350 static bool
4351 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4353 struct blame *blame = line->data;
4354 struct time *time = NULL;
4355 const char *id = NULL, *author = NULL;
4357 if (blame->commit && *blame->commit->filename) {
4358 id = blame->commit->id;
4359 author = blame->commit->author;
4360 time = &blame->commit->time;
4363 if (draw_date(view, time))
4364 return TRUE;
4366 if (draw_author(view, author))
4367 return TRUE;
4369 if (draw_field(view, LINE_BLAME_ID, id, ID_COLS, FALSE))
4370 return TRUE;
4372 if (draw_lineno(view, lineno))
4373 return TRUE;
4375 draw_text(view, LINE_DEFAULT, blame->text);
4376 return TRUE;
4379 static bool
4380 check_blame_commit(struct blame *blame, bool check_null_id)
4382 if (!blame->commit)
4383 report("Commit data not loaded yet");
4384 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4385 report("No commit exist for the selected line");
4386 else
4387 return TRUE;
4388 return FALSE;
4391 static void
4392 setup_blame_parent_line(struct view *view, struct blame *blame)
4394 char from[SIZEOF_REF + SIZEOF_STR];
4395 char to[SIZEOF_REF + SIZEOF_STR];
4396 const char *diff_tree_argv[] = {
4397 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4398 "-U0", from, to, "--", NULL
4400 struct io io;
4401 int parent_lineno = -1;
4402 int blamed_lineno = -1;
4403 char *line;
4405 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4406 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4407 !io_run(&io, IO_RD, NULL, diff_tree_argv))
4408 return;
4410 while ((line = io_get(&io, '\n', TRUE))) {
4411 if (*line == '@') {
4412 char *pos = strchr(line, '+');
4414 parent_lineno = atoi(line + 4);
4415 if (pos)
4416 blamed_lineno = atoi(pos + 1);
4418 } else if (*line == '+' && parent_lineno != -1) {
4419 if (blame->lineno == blamed_lineno - 1 &&
4420 !strcmp(blame->text, line + 1)) {
4421 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4422 break;
4424 blamed_lineno++;
4428 io_done(&io);
4431 static enum request
4432 blame_request(struct view *view, enum request request, struct line *line)
4434 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4435 struct blame *blame = line->data;
4437 switch (request) {
4438 case REQ_VIEW_BLAME:
4439 if (check_blame_commit(blame, TRUE)) {
4440 string_copy(opt_ref, blame->commit->id);
4441 string_copy(opt_file, blame->commit->filename);
4442 if (blame->lineno)
4443 view->lineno = blame->lineno;
4444 reload_view(view);
4446 break;
4448 case REQ_PARENT:
4449 if (!check_blame_commit(blame, TRUE))
4450 break;
4451 if (!*blame->commit->parent_id) {
4452 report("The selected commit has no parents");
4453 } else {
4454 string_copy_rev(opt_ref, blame->commit->parent_id);
4455 string_copy(opt_file, blame->commit->parent_filename);
4456 setup_blame_parent_line(view, blame);
4457 reload_view(view);
4459 break;
4461 case REQ_ENTER:
4462 if (!check_blame_commit(blame, FALSE))
4463 break;
4465 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
4466 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
4467 break;
4469 if (!strcmp(blame->commit->id, NULL_ID)) {
4470 struct view *diff = VIEW(REQ_VIEW_DIFF);
4471 const char *diff_index_argv[] = {
4472 "git", "diff-index", "--root", "--patch-with-stat",
4473 "-C", "-M", "HEAD", "--", view->vid, NULL
4476 if (!*blame->commit->parent_id) {
4477 diff_index_argv[1] = "diff";
4478 diff_index_argv[2] = "--no-color";
4479 diff_index_argv[6] = "--";
4480 diff_index_argv[7] = "/dev/null";
4483 open_argv(view, diff, diff_index_argv, NULL, flags);
4484 } else {
4485 open_view(view, REQ_VIEW_DIFF, flags);
4487 if (VIEW(REQ_VIEW_DIFF)->pipe && !strcmp(blame->commit->id, NULL_ID))
4488 string_copy_rev(VIEW(REQ_VIEW_DIFF)->ref, NULL_ID);
4489 break;
4491 default:
4492 return request;
4495 return REQ_NONE;
4498 static bool
4499 blame_grep(struct view *view, struct line *line)
4501 struct blame *blame = line->data;
4502 struct blame_commit *commit = blame->commit;
4503 const char *text[] = {
4504 blame->text,
4505 commit ? commit->title : "",
4506 commit ? commit->id : "",
4507 commit && opt_author ? commit->author : "",
4508 commit ? mkdate(&commit->time, opt_date) : "",
4509 NULL
4512 return grep_text(view, text);
4515 static void
4516 blame_select(struct view *view, struct line *line)
4518 struct blame *blame = line->data;
4519 struct blame_commit *commit = blame->commit;
4521 if (!commit)
4522 return;
4524 if (!strcmp(commit->id, NULL_ID))
4525 string_ncopy(ref_commit, "HEAD", 4);
4526 else
4527 string_copy_rev(ref_commit, commit->id);
4530 static struct view_ops blame_ops = {
4531 "line",
4532 blame_open,
4533 blame_read,
4534 blame_draw,
4535 blame_request,
4536 blame_grep,
4537 blame_select,
4541 * Branch backend
4544 struct branch {
4545 const char *author; /* Author of the last commit. */
4546 struct time time; /* Date of the last activity. */
4547 const struct ref *ref; /* Name and commit ID information. */
4550 static const struct ref branch_all;
4552 static const enum sort_field branch_sort_fields[] = {
4553 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4555 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
4557 static int
4558 branch_compare(const void *l1, const void *l2)
4560 const struct branch *branch1 = ((const struct line *) l1)->data;
4561 const struct branch *branch2 = ((const struct line *) l2)->data;
4563 if (branch1->ref == &branch_all)
4564 return -1;
4565 else if (branch2->ref == &branch_all)
4566 return 1;
4568 switch (get_sort_field(branch_sort_state)) {
4569 case ORDERBY_DATE:
4570 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
4572 case ORDERBY_AUTHOR:
4573 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
4575 case ORDERBY_NAME:
4576 default:
4577 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
4581 static bool
4582 branch_draw(struct view *view, struct line *line, unsigned int lineno)
4584 struct branch *branch = line->data;
4585 enum line_type type = branch->ref == &branch_all ? LINE_DEFAULT : get_line_type_from_ref(branch->ref);
4587 if (draw_date(view, &branch->time))
4588 return TRUE;
4590 if (draw_author(view, branch->author))
4591 return TRUE;
4593 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
4594 return TRUE;
4597 static enum request
4598 branch_request(struct view *view, enum request request, struct line *line)
4600 struct branch *branch = line->data;
4602 switch (request) {
4603 case REQ_REFRESH:
4604 load_refs();
4605 refresh_view(view);
4606 return REQ_NONE;
4608 case REQ_TOGGLE_SORT_FIELD:
4609 case REQ_TOGGLE_SORT_ORDER:
4610 sort_view(view, request, &branch_sort_state, branch_compare);
4611 return REQ_NONE;
4613 case REQ_ENTER:
4615 const struct ref *ref = branch->ref;
4616 const char *all_branches_argv[] = {
4617 "git", "log", "--no-color", "--pretty=raw", "--parents",
4618 "--topo-order",
4619 ref == &branch_all ? "--all" : ref->name, NULL
4621 struct view *main_view = VIEW(REQ_VIEW_MAIN);
4623 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
4624 return REQ_NONE;
4626 default:
4627 return request;
4631 static bool
4632 branch_read(struct view *view, char *line)
4634 static char id[SIZEOF_REV];
4635 struct branch *reference;
4636 size_t i;
4638 if (!line)
4639 return TRUE;
4641 switch (get_line_type(line)) {
4642 case LINE_COMMIT:
4643 string_copy_rev(id, line + STRING_SIZE("commit "));
4644 return TRUE;
4646 case LINE_AUTHOR:
4647 for (i = 0, reference = NULL; i < view->lines; i++) {
4648 struct branch *branch = view->line[i].data;
4650 if (strcmp(branch->ref->id, id))
4651 continue;
4653 view->line[i].dirty = TRUE;
4654 if (reference) {
4655 branch->author = reference->author;
4656 branch->time = reference->time;
4657 continue;
4660 parse_author_line(line + STRING_SIZE("author "),
4661 &branch->author, &branch->time);
4662 reference = branch;
4664 return TRUE;
4666 default:
4667 return TRUE;
4672 static bool
4673 branch_open_visitor(void *data, const struct ref *ref)
4675 struct view *view = data;
4676 struct branch *branch;
4678 if (ref->tag || ref->ltag)
4679 return TRUE;
4681 branch = calloc(1, sizeof(*branch));
4682 if (!branch)
4683 return FALSE;
4685 branch->ref = ref;
4686 return !!add_line_data(view, branch, LINE_DEFAULT);
4689 static bool
4690 branch_open(struct view *view, enum open_flags flags)
4692 const char *branch_log[] = {
4693 "git", "log", "--no-color", "--pretty=raw",
4694 "--simplify-by-decoration", "--all", NULL
4697 if (!begin_update(view, NULL, branch_log, flags)) {
4698 report("Failed to load branch data");
4699 return TRUE;
4702 branch_open_visitor(view, &branch_all);
4703 foreach_ref(branch_open_visitor, view);
4704 view->p_restore = TRUE;
4706 return TRUE;
4709 static bool
4710 branch_grep(struct view *view, struct line *line)
4712 struct branch *branch = line->data;
4713 const char *text[] = {
4714 branch->ref->name,
4715 mkauthor(branch->author, opt_author_cols, opt_author),
4716 NULL
4719 return grep_text(view, text);
4722 static void
4723 branch_select(struct view *view, struct line *line)
4725 struct branch *branch = line->data;
4727 string_copy_rev(view->ref, branch->ref->id);
4728 string_copy_rev(ref_commit, branch->ref->id);
4729 string_copy_rev(ref_head, branch->ref->id);
4730 string_copy_rev(ref_branch, branch->ref->name);
4733 static struct view_ops branch_ops = {
4734 "branch",
4735 branch_open,
4736 branch_read,
4737 branch_draw,
4738 branch_request,
4739 branch_grep,
4740 branch_select,
4744 * Status backend
4747 struct status {
4748 char status;
4749 struct {
4750 mode_t mode;
4751 char rev[SIZEOF_REV];
4752 char name[SIZEOF_STR];
4753 } old;
4754 struct {
4755 mode_t mode;
4756 char rev[SIZEOF_REV];
4757 char name[SIZEOF_STR];
4758 } new;
4761 static char status_onbranch[SIZEOF_STR];
4762 static struct status stage_status;
4763 static enum line_type stage_line_type;
4764 static size_t stage_chunks;
4765 static int *stage_chunk;
4767 DEFINE_ALLOCATOR(realloc_ints, int, 32)
4769 /* This should work even for the "On branch" line. */
4770 static inline bool
4771 status_has_none(struct view *view, struct line *line)
4773 return line < view->line + view->lines && !line[1].data;
4776 /* Get fields from the diff line:
4777 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
4779 static inline bool
4780 status_get_diff(struct status *file, const char *buf, size_t bufsize)
4782 const char *old_mode = buf + 1;
4783 const char *new_mode = buf + 8;
4784 const char *old_rev = buf + 15;
4785 const char *new_rev = buf + 56;
4786 const char *status = buf + 97;
4788 if (bufsize < 98 ||
4789 old_mode[-1] != ':' ||
4790 new_mode[-1] != ' ' ||
4791 old_rev[-1] != ' ' ||
4792 new_rev[-1] != ' ' ||
4793 status[-1] != ' ')
4794 return FALSE;
4796 file->status = *status;
4798 string_copy_rev(file->old.rev, old_rev);
4799 string_copy_rev(file->new.rev, new_rev);
4801 file->old.mode = strtoul(old_mode, NULL, 8);
4802 file->new.mode = strtoul(new_mode, NULL, 8);
4804 file->old.name[0] = file->new.name[0] = 0;
4806 return TRUE;
4809 static bool
4810 status_run(struct view *view, const char *argv[], char status, enum line_type type)
4812 struct status *unmerged = NULL;
4813 char *buf;
4814 struct io io;
4816 if (!io_run(&io, IO_RD, opt_cdup, argv))
4817 return FALSE;
4819 add_line_data(view, NULL, type);
4821 while ((buf = io_get(&io, 0, TRUE))) {
4822 struct status *file = unmerged;
4824 if (!file) {
4825 file = calloc(1, sizeof(*file));
4826 if (!file || !add_line_data(view, file, type))
4827 goto error_out;
4830 /* Parse diff info part. */
4831 if (status) {
4832 file->status = status;
4833 if (status == 'A')
4834 string_copy(file->old.rev, NULL_ID);
4836 } else if (!file->status || file == unmerged) {
4837 if (!status_get_diff(file, buf, strlen(buf)))
4838 goto error_out;
4840 buf = io_get(&io, 0, TRUE);
4841 if (!buf)
4842 break;
4844 /* Collapse all modified entries that follow an
4845 * associated unmerged entry. */
4846 if (unmerged == file) {
4847 unmerged->status = 'U';
4848 unmerged = NULL;
4849 } else if (file->status == 'U') {
4850 unmerged = file;
4854 /* Grab the old name for rename/copy. */
4855 if (!*file->old.name &&
4856 (file->status == 'R' || file->status == 'C')) {
4857 string_ncopy(file->old.name, buf, strlen(buf));
4859 buf = io_get(&io, 0, TRUE);
4860 if (!buf)
4861 break;
4864 /* git-ls-files just delivers a NUL separated list of
4865 * file names similar to the second half of the
4866 * git-diff-* output. */
4867 string_ncopy(file->new.name, buf, strlen(buf));
4868 if (!*file->old.name)
4869 string_copy(file->old.name, file->new.name);
4870 file = NULL;
4873 if (io_error(&io)) {
4874 error_out:
4875 io_done(&io);
4876 return FALSE;
4879 if (!view->line[view->lines - 1].data)
4880 add_line_data(view, NULL, LINE_STAT_NONE);
4882 io_done(&io);
4883 return TRUE;
4886 /* Don't show unmerged entries in the staged section. */
4887 static const char *status_diff_index_argv[] = {
4888 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
4889 "--cached", "-M", "HEAD", NULL
4892 static const char *status_diff_files_argv[] = {
4893 "git", "diff-files", "-z", NULL
4896 static const char *status_list_other_argv[] = {
4897 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
4900 static const char *status_list_no_head_argv[] = {
4901 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
4904 static const char *update_index_argv[] = {
4905 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
4908 /* Restore the previous line number to stay in the context or select a
4909 * line with something that can be updated. */
4910 static void
4911 status_restore(struct view *view)
4913 if (view->p_lineno >= view->lines)
4914 view->p_lineno = view->lines - 1;
4915 while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
4916 view->p_lineno++;
4917 while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
4918 view->p_lineno--;
4920 /* If the above fails, always skip the "On branch" line. */
4921 if (view->p_lineno < view->lines)
4922 view->lineno = view->p_lineno;
4923 else
4924 view->lineno = 1;
4926 if (view->lineno < view->offset)
4927 view->offset = view->lineno;
4928 else if (view->offset + view->height <= view->lineno)
4929 view->offset = view->lineno - view->height + 1;
4931 view->p_restore = FALSE;
4934 static void
4935 status_update_onbranch(void)
4937 static const char *paths[][2] = {
4938 { "rebase-apply/rebasing", "Rebasing" },
4939 { "rebase-apply/applying", "Applying mailbox" },
4940 { "rebase-apply/", "Rebasing mailbox" },
4941 { "rebase-merge/interactive", "Interactive rebase" },
4942 { "rebase-merge/", "Rebase merge" },
4943 { "MERGE_HEAD", "Merging" },
4944 { "BISECT_LOG", "Bisecting" },
4945 { "HEAD", "On branch" },
4947 char buf[SIZEOF_STR];
4948 struct stat stat;
4949 int i;
4951 if (is_initial_commit()) {
4952 string_copy(status_onbranch, "Initial commit");
4953 return;
4956 for (i = 0; i < ARRAY_SIZE(paths); i++) {
4957 char *head = opt_head;
4959 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
4960 lstat(buf, &stat) < 0)
4961 continue;
4963 if (!*opt_head) {
4964 struct io io;
4966 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
4967 io_read_buf(&io, buf, sizeof(buf))) {
4968 head = buf;
4969 if (!prefixcmp(head, "refs/heads/"))
4970 head += STRING_SIZE("refs/heads/");
4974 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
4975 string_copy(status_onbranch, opt_head);
4976 return;
4979 string_copy(status_onbranch, "Not currently on any branch");
4982 /* First parse staged info using git-diff-index(1), then parse unstaged
4983 * info using git-diff-files(1), and finally untracked files using
4984 * git-ls-files(1). */
4985 static bool
4986 status_open(struct view *view, enum open_flags flags)
4988 reset_view(view);
4990 add_line_data(view, NULL, LINE_STAT_HEAD);
4991 status_update_onbranch();
4993 io_run_bg(update_index_argv);
4995 if (is_initial_commit()) {
4996 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
4997 return FALSE;
4998 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
4999 return FALSE;
5002 if (!opt_untracked_dirs_content)
5003 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5005 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5006 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5007 return FALSE;
5009 /* Restore the exact position or use the specialized restore
5010 * mode? */
5011 if (!view->p_restore)
5012 status_restore(view);
5013 return TRUE;
5016 static bool
5017 status_draw(struct view *view, struct line *line, unsigned int lineno)
5019 struct status *status = line->data;
5020 enum line_type type;
5021 const char *text;
5023 if (!status) {
5024 switch (line->type) {
5025 case LINE_STAT_STAGED:
5026 type = LINE_STAT_SECTION;
5027 text = "Changes to be committed:";
5028 break;
5030 case LINE_STAT_UNSTAGED:
5031 type = LINE_STAT_SECTION;
5032 text = "Changed but not updated:";
5033 break;
5035 case LINE_STAT_UNTRACKED:
5036 type = LINE_STAT_SECTION;
5037 text = "Untracked files:";
5038 break;
5040 case LINE_STAT_NONE:
5041 type = LINE_DEFAULT;
5042 text = " (no files)";
5043 break;
5045 case LINE_STAT_HEAD:
5046 type = LINE_STAT_HEAD;
5047 text = status_onbranch;
5048 break;
5050 default:
5051 return FALSE;
5053 } else {
5054 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5056 buf[0] = status->status;
5057 if (draw_text(view, line->type, buf))
5058 return TRUE;
5059 type = LINE_DEFAULT;
5060 text = status->new.name;
5063 draw_text(view, type, text);
5064 return TRUE;
5067 static enum request
5068 status_enter(struct view *view, struct line *line)
5070 struct status *status = line->data;
5071 const char *oldpath = status ? status->old.name : NULL;
5072 /* Diffs for unmerged entries are empty when passing the new
5073 * path, so leave it empty. */
5074 const char *newpath = status && status->status != 'U' ? status->new.name : NULL;
5075 const char *info;
5076 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5077 struct view *stage = VIEW(REQ_VIEW_STAGE);
5079 if (line->type == LINE_STAT_NONE ||
5080 (!status && line[1].type == LINE_STAT_NONE)) {
5081 report("No file to diff");
5082 return REQ_NONE;
5085 switch (line->type) {
5086 case LINE_STAT_STAGED:
5087 if (is_initial_commit()) {
5088 const char *no_head_diff_argv[] = {
5089 "git", "diff", "--no-color", "--patch-with-stat",
5090 "--", "/dev/null", newpath, NULL
5093 open_argv(view, stage, no_head_diff_argv, opt_cdup, flags);
5094 } else {
5095 const char *index_show_argv[] = {
5096 "git", "diff-index", "--root", "--patch-with-stat",
5097 "-C", "-M", "--cached", "HEAD", "--",
5098 oldpath, newpath, NULL
5101 open_argv(view, stage, index_show_argv, opt_cdup, flags);
5104 if (status)
5105 info = "Staged changes to %s";
5106 else
5107 info = "Staged changes";
5108 break;
5110 case LINE_STAT_UNSTAGED:
5112 const char *files_show_argv[] = {
5113 "git", "diff-files", "--root", "--patch-with-stat",
5114 "-C", "-M", "--", oldpath, newpath, NULL
5117 open_argv(view, stage, files_show_argv, opt_cdup, flags);
5118 if (status)
5119 info = "Unstaged changes to %s";
5120 else
5121 info = "Unstaged changes";
5122 break;
5124 case LINE_STAT_UNTRACKED:
5125 if (!newpath) {
5126 report("No file to show");
5127 return REQ_NONE;
5130 if (!suffixcmp(status->new.name, -1, "/")) {
5131 report("Cannot display a directory");
5132 return REQ_NONE;
5135 open_file(view, stage, newpath, flags);
5136 info = "Untracked file %s";
5137 break;
5139 case LINE_STAT_HEAD:
5140 return REQ_NONE;
5142 default:
5143 die("line type %d not handled in switch", line->type);
5146 if (view_is_displayed(VIEW(REQ_VIEW_STAGE))) {
5147 if (status) {
5148 stage_status = *status;
5149 } else {
5150 memset(&stage_status, 0, sizeof(stage_status));
5153 stage_line_type = line->type;
5154 stage_chunks = 0;
5155 string_format(VIEW(REQ_VIEW_STAGE)->ref, info, stage_status.new.name);
5158 return REQ_NONE;
5161 static bool
5162 status_exists(struct status *status, enum line_type type)
5164 struct view *view = VIEW(REQ_VIEW_STATUS);
5165 unsigned long lineno;
5167 for (lineno = 0; lineno < view->lines; lineno++) {
5168 struct line *line = &view->line[lineno];
5169 struct status *pos = line->data;
5171 if (line->type != type)
5172 continue;
5173 if (!pos && (!status || !status->status) && line[1].data) {
5174 select_view_line(view, lineno);
5175 return TRUE;
5177 if (pos && !strcmp(status->new.name, pos->new.name)) {
5178 select_view_line(view, lineno);
5179 return TRUE;
5183 return FALSE;
5187 static bool
5188 status_update_prepare(struct io *io, enum line_type type)
5190 const char *staged_argv[] = {
5191 "git", "update-index", "-z", "--index-info", NULL
5193 const char *others_argv[] = {
5194 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5197 switch (type) {
5198 case LINE_STAT_STAGED:
5199 return io_run(io, IO_WR, opt_cdup, staged_argv);
5201 case LINE_STAT_UNSTAGED:
5202 case LINE_STAT_UNTRACKED:
5203 return io_run(io, IO_WR, opt_cdup, others_argv);
5205 default:
5206 die("line type %d not handled in switch", type);
5207 return FALSE;
5211 static bool
5212 status_update_write(struct io *io, struct status *status, enum line_type type)
5214 char buf[SIZEOF_STR];
5215 size_t bufsize = 0;
5217 switch (type) {
5218 case LINE_STAT_STAGED:
5219 if (!string_format_from(buf, &bufsize, "%06o %s\t%s%c",
5220 status->old.mode,
5221 status->old.rev,
5222 status->old.name, 0))
5223 return FALSE;
5224 break;
5226 case LINE_STAT_UNSTAGED:
5227 case LINE_STAT_UNTRACKED:
5228 if (!string_format_from(buf, &bufsize, "%s%c", status->new.name, 0))
5229 return FALSE;
5230 break;
5232 default:
5233 die("line type %d not handled in switch", type);
5236 return io_write(io, buf, bufsize);
5239 static bool
5240 status_update_file(struct status *status, enum line_type type)
5242 struct io io;
5243 bool result;
5245 if (!status_update_prepare(&io, type))
5246 return FALSE;
5248 result = status_update_write(&io, status, type);
5249 return io_done(&io) && result;
5252 static bool
5253 status_update_files(struct view *view, struct line *line)
5255 char buf[sizeof(view->ref)];
5256 struct io io;
5257 bool result = TRUE;
5258 struct line *pos = view->line + view->lines;
5259 int files = 0;
5260 int file, done;
5261 int cursor_y = -1, cursor_x = -1;
5263 if (!status_update_prepare(&io, line->type))
5264 return FALSE;
5266 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5267 files++;
5269 string_copy(buf, view->ref);
5270 getsyx(cursor_y, cursor_x);
5271 for (file = 0, done = 5; result && file < files; line++, file++) {
5272 int almost_done = file * 100 / files;
5274 if (almost_done > done) {
5275 done = almost_done;
5276 string_format(view->ref, "updating file %u of %u (%d%% done)",
5277 file, files, done);
5278 update_view_title(view);
5279 setsyx(cursor_y, cursor_x);
5280 doupdate();
5282 result = status_update_write(&io, line->data, line->type);
5284 string_copy(view->ref, buf);
5286 return io_done(&io) && result;
5289 static bool
5290 status_update(struct view *view)
5292 struct line *line = &view->line[view->lineno];
5294 assert(view->lines);
5296 if (!line->data) {
5297 /* This should work even for the "On branch" line. */
5298 if (line < view->line + view->lines && !line[1].data) {
5299 report("Nothing to update");
5300 return FALSE;
5303 if (!status_update_files(view, line + 1)) {
5304 report("Failed to update file status");
5305 return FALSE;
5308 } else if (!status_update_file(line->data, line->type)) {
5309 report("Failed to update file status");
5310 return FALSE;
5313 return TRUE;
5316 static bool
5317 status_revert(struct status *status, enum line_type type, bool has_none)
5319 if (!status || type != LINE_STAT_UNSTAGED) {
5320 if (type == LINE_STAT_STAGED) {
5321 report("Cannot revert changes to staged files");
5322 } else if (type == LINE_STAT_UNTRACKED) {
5323 report("Cannot revert changes to untracked files");
5324 } else if (has_none) {
5325 report("Nothing to revert");
5326 } else {
5327 report("Cannot revert changes to multiple files");
5330 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5331 char mode[10] = "100644";
5332 const char *reset_argv[] = {
5333 "git", "update-index", "--cacheinfo", mode,
5334 status->old.rev, status->old.name, NULL
5336 const char *checkout_argv[] = {
5337 "git", "checkout", "--", status->old.name, NULL
5340 if (status->status == 'U') {
5341 string_format(mode, "%5o", status->old.mode);
5343 if (status->old.mode == 0 && status->new.mode == 0) {
5344 reset_argv[2] = "--force-remove";
5345 reset_argv[3] = status->old.name;
5346 reset_argv[4] = NULL;
5349 if (!io_run_fg(reset_argv, opt_cdup))
5350 return FALSE;
5351 if (status->old.mode == 0 && status->new.mode == 0)
5352 return TRUE;
5355 return io_run_fg(checkout_argv, opt_cdup);
5358 return FALSE;
5361 static enum request
5362 status_request(struct view *view, enum request request, struct line *line)
5364 struct status *status = line->data;
5366 switch (request) {
5367 case REQ_STATUS_UPDATE:
5368 if (!status_update(view))
5369 return REQ_NONE;
5370 break;
5372 case REQ_STATUS_REVERT:
5373 if (!status_revert(status, line->type, status_has_none(view, line)))
5374 return REQ_NONE;
5375 break;
5377 case REQ_STATUS_MERGE:
5378 if (!status || status->status != 'U') {
5379 report("Merging only possible for files with unmerged status ('U').");
5380 return REQ_NONE;
5382 open_mergetool(status->new.name);
5383 break;
5385 case REQ_EDIT:
5386 if (!status)
5387 return request;
5388 if (status->status == 'D') {
5389 report("File has been deleted.");
5390 return REQ_NONE;
5393 open_editor(status->new.name);
5394 break;
5396 case REQ_VIEW_BLAME:
5397 if (status)
5398 opt_ref[0] = 0;
5399 return request;
5401 case REQ_ENTER:
5402 /* After returning the status view has been split to
5403 * show the stage view. No further reloading is
5404 * necessary. */
5405 return status_enter(view, line);
5407 case REQ_REFRESH:
5408 /* Simply reload the view. */
5409 break;
5411 default:
5412 return request;
5415 refresh_view(view);
5417 return REQ_NONE;
5420 static void
5421 status_select(struct view *view, struct line *line)
5423 struct status *status = line->data;
5424 char file[SIZEOF_STR] = "all files";
5425 const char *text;
5426 const char *key;
5428 if (status && !string_format(file, "'%s'", status->new.name))
5429 return;
5431 if (!status && line[1].type == LINE_STAT_NONE)
5432 line++;
5434 switch (line->type) {
5435 case LINE_STAT_STAGED:
5436 text = "Press %s to unstage %s for commit";
5437 break;
5439 case LINE_STAT_UNSTAGED:
5440 text = "Press %s to stage %s for commit";
5441 break;
5443 case LINE_STAT_UNTRACKED:
5444 text = "Press %s to stage %s for addition";
5445 break;
5447 case LINE_STAT_HEAD:
5448 case LINE_STAT_NONE:
5449 text = "Nothing to update";
5450 break;
5452 default:
5453 die("line type %d not handled in switch", line->type);
5456 if (status && status->status == 'U') {
5457 text = "Press %s to resolve conflict in %s";
5458 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5460 } else {
5461 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5464 string_format(view->ref, text, key, file);
5465 if (status)
5466 string_copy(opt_file, status->new.name);
5469 static bool
5470 status_grep(struct view *view, struct line *line)
5472 struct status *status = line->data;
5474 if (status) {
5475 const char buf[2] = { status->status, 0 };
5476 const char *text[] = { status->new.name, buf, NULL };
5478 return grep_text(view, text);
5481 return FALSE;
5484 static struct view_ops status_ops = {
5485 "file",
5486 status_open,
5487 NULL,
5488 status_draw,
5489 status_request,
5490 status_grep,
5491 status_select,
5495 static bool
5496 stage_diff_write(struct io *io, struct line *line, struct line *end)
5498 while (line < end) {
5499 if (!io_write(io, line->data, strlen(line->data)) ||
5500 !io_write(io, "\n", 1))
5501 return FALSE;
5502 line++;
5503 if (line->type == LINE_DIFF_CHUNK ||
5504 line->type == LINE_DIFF_HEADER)
5505 break;
5508 return TRUE;
5511 static struct line *
5512 stage_diff_find(struct view *view, struct line *line, enum line_type type)
5514 for (; view->line < line; line--)
5515 if (line->type == type)
5516 return line;
5518 return NULL;
5521 static bool
5522 stage_apply_chunk(struct view *view, struct line *chunk, bool revert)
5524 const char *apply_argv[SIZEOF_ARG] = {
5525 "git", "apply", "--whitespace=nowarn", NULL
5527 struct line *diff_hdr;
5528 struct io io;
5529 int argc = 3;
5531 diff_hdr = stage_diff_find(view, chunk, LINE_DIFF_HEADER);
5532 if (!diff_hdr)
5533 return FALSE;
5535 if (!revert)
5536 apply_argv[argc++] = "--cached";
5537 if (revert || stage_line_type == LINE_STAT_STAGED)
5538 apply_argv[argc++] = "-R";
5539 apply_argv[argc++] = "-";
5540 apply_argv[argc++] = NULL;
5541 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
5542 return FALSE;
5544 if (!stage_diff_write(&io, diff_hdr, chunk) ||
5545 !stage_diff_write(&io, chunk, view->line + view->lines))
5546 chunk = NULL;
5548 io_done(&io);
5549 io_run_bg(update_index_argv);
5551 return chunk ? TRUE : FALSE;
5554 static bool
5555 stage_update(struct view *view, struct line *line)
5557 struct line *chunk = NULL;
5559 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
5560 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5562 if (chunk) {
5563 if (!stage_apply_chunk(view, chunk, FALSE)) {
5564 report("Failed to apply chunk");
5565 return FALSE;
5568 } else if (!stage_status.status) {
5569 view = VIEW(REQ_VIEW_STATUS);
5571 for (line = view->line; line < view->line + view->lines; line++)
5572 if (line->type == stage_line_type)
5573 break;
5575 if (!status_update_files(view, line + 1)) {
5576 report("Failed to update files");
5577 return FALSE;
5580 } else if (!status_update_file(&stage_status, stage_line_type)) {
5581 report("Failed to update file");
5582 return FALSE;
5585 return TRUE;
5588 static bool
5589 stage_revert(struct view *view, struct line *line)
5591 struct line *chunk = NULL;
5593 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
5594 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5596 if (chunk) {
5597 if (!prompt_yesno("Are you sure you want to revert changes?"))
5598 return FALSE;
5600 if (!stage_apply_chunk(view, chunk, TRUE)) {
5601 report("Failed to revert chunk");
5602 return FALSE;
5604 return TRUE;
5606 } else {
5607 return status_revert(stage_status.status ? &stage_status : NULL,
5608 stage_line_type, FALSE);
5613 static void
5614 stage_next(struct view *view, struct line *line)
5616 int i;
5618 if (!stage_chunks) {
5619 for (line = view->line; line < view->line + view->lines; line++) {
5620 if (line->type != LINE_DIFF_CHUNK)
5621 continue;
5623 if (!realloc_ints(&stage_chunk, stage_chunks, 1)) {
5624 report("Allocation failure");
5625 return;
5628 stage_chunk[stage_chunks++] = line - view->line;
5632 for (i = 0; i < stage_chunks; i++) {
5633 if (stage_chunk[i] > view->lineno) {
5634 do_scroll_view(view, stage_chunk[i] - view->lineno);
5635 report("Chunk %d of %d", i + 1, stage_chunks);
5636 return;
5640 report("No next chunk found");
5643 static enum request
5644 stage_request(struct view *view, enum request request, struct line *line)
5646 switch (request) {
5647 case REQ_STATUS_UPDATE:
5648 if (!stage_update(view, line))
5649 return REQ_NONE;
5650 break;
5652 case REQ_STATUS_REVERT:
5653 if (!stage_revert(view, line))
5654 return REQ_NONE;
5655 break;
5657 case REQ_STAGE_NEXT:
5658 if (stage_line_type == LINE_STAT_UNTRACKED) {
5659 report("File is untracked; press %s to add",
5660 get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
5661 return REQ_NONE;
5663 stage_next(view, line);
5664 return REQ_NONE;
5666 case REQ_EDIT:
5667 if (!stage_status.new.name[0])
5668 return request;
5669 if (stage_status.status == 'D') {
5670 report("File has been deleted.");
5671 return REQ_NONE;
5674 open_editor(stage_status.new.name);
5675 break;
5677 case REQ_REFRESH:
5678 /* Reload everything ... */
5679 break;
5681 case REQ_VIEW_BLAME:
5682 if (stage_status.new.name[0]) {
5683 string_copy(opt_file, stage_status.new.name);
5684 opt_ref[0] = 0;
5686 return request;
5688 case REQ_ENTER:
5689 return pager_request(view, request, line);
5691 default:
5692 return request;
5695 refresh_view(view->parent);
5697 /* Check whether the staged entry still exists, and close the
5698 * stage view if it doesn't. */
5699 if (!status_exists(&stage_status, stage_line_type)) {
5700 status_restore(VIEW(REQ_VIEW_STATUS));
5701 return REQ_VIEW_CLOSE;
5704 refresh_view(view);
5706 return REQ_NONE;
5709 static struct view_ops stage_ops = {
5710 "line",
5711 view_open,
5712 pager_read,
5713 pager_draw,
5714 stage_request,
5715 pager_grep,
5716 pager_select,
5721 * Revision graph
5724 static const enum line_type graph_colors[] = {
5725 LINE_GRAPH_LINE_0,
5726 LINE_GRAPH_LINE_1,
5727 LINE_GRAPH_LINE_2,
5728 LINE_GRAPH_LINE_3,
5729 LINE_GRAPH_LINE_4,
5730 LINE_GRAPH_LINE_5,
5731 LINE_GRAPH_LINE_6,
5734 static enum line_type get_graph_color(struct graph_symbol *symbol)
5736 if (symbol->commit)
5737 return LINE_GRAPH_COMMIT;
5738 assert(symbol->color < ARRAY_SIZE(graph_colors));
5739 return graph_colors[symbol->color];
5742 static bool
5743 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5745 const char *chars = graph_symbol_to_utf8(symbol);
5747 return draw_text(view, color, chars + !!first);
5750 static bool
5751 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5753 const char *chars = graph_symbol_to_ascii(symbol);
5755 return draw_text(view, color, chars + !!first);
5758 static bool
5759 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5761 const chtype *chars = graph_symbol_to_chtype(symbol);
5763 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
5766 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
5768 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
5770 static const draw_graph_fn fns[] = {
5771 draw_graph_ascii,
5772 draw_graph_chtype,
5773 draw_graph_utf8
5775 draw_graph_fn fn = fns[opt_line_graphics];
5776 int i;
5778 for (i = 0; i < canvas->size; i++) {
5779 struct graph_symbol *symbol = &canvas->symbols[i];
5780 enum line_type color = get_graph_color(symbol);
5782 if (fn(view, symbol, color, i == 0))
5783 return TRUE;
5786 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
5790 * Main view backend
5793 struct commit {
5794 char id[SIZEOF_REV]; /* SHA1 ID. */
5795 char title[128]; /* First line of the commit message. */
5796 const char *author; /* Author of the commit. */
5797 struct time time; /* Date from the author ident. */
5798 struct ref_list *refs; /* Repository references. */
5799 struct graph_canvas graph; /* Ancestry chain graphics. */
5802 static bool
5803 main_open(struct view *view, enum open_flags flags)
5805 static const char *main_argv[] = {
5806 "git", "log", "--no-color", "--pretty=raw", "--parents",
5807 "--topo-order", "%(diffargs)", "%(revargs)",
5808 "--", "%(fileargs)", NULL
5811 return begin_update(view, NULL, main_argv, flags);
5814 static bool
5815 main_draw(struct view *view, struct line *line, unsigned int lineno)
5817 struct commit *commit = line->data;
5819 if (!commit->author)
5820 return FALSE;
5822 if (draw_date(view, &commit->time))
5823 return TRUE;
5825 if (draw_author(view, commit->author))
5826 return TRUE;
5828 if (opt_rev_graph && draw_graph(view, &commit->graph))
5829 return TRUE;
5831 if (draw_refs(view, commit->refs))
5832 return TRUE;
5834 draw_text(view, LINE_DEFAULT, commit->title);
5835 return TRUE;
5838 /* Reads git log --pretty=raw output and parses it into the commit struct. */
5839 static bool
5840 main_read(struct view *view, char *line)
5842 static struct graph graph;
5843 enum line_type type;
5844 struct commit *commit;
5846 if (!line) {
5847 if (!view->lines && !view->prev)
5848 die("No revisions match the given arguments.");
5849 if (view->lines > 0) {
5850 commit = view->line[view->lines - 1].data;
5851 view->line[view->lines - 1].dirty = 1;
5852 if (!commit->author) {
5853 view->lines--;
5854 free(commit);
5858 done_graph(&graph);
5859 return TRUE;
5862 type = get_line_type(line);
5863 if (type == LINE_COMMIT) {
5864 bool is_boundary;
5866 commit = calloc(1, sizeof(struct commit));
5867 if (!commit)
5868 return FALSE;
5870 line += STRING_SIZE("commit ");
5871 is_boundary = *line == '-';
5872 if (is_boundary)
5873 line++;
5875 string_copy_rev(commit->id, line);
5876 commit->refs = get_ref_list(commit->id);
5877 add_line_data(view, commit, LINE_MAIN_COMMIT);
5878 graph_add_commit(&graph, &commit->graph, commit->id, line, is_boundary);
5879 return TRUE;
5882 if (!view->lines)
5883 return TRUE;
5884 commit = view->line[view->lines - 1].data;
5886 switch (type) {
5887 case LINE_PARENT:
5888 if (!graph.has_parents)
5889 graph_add_parent(&graph, line + STRING_SIZE("parent "));
5890 break;
5892 case LINE_AUTHOR:
5893 parse_author_line(line + STRING_SIZE("author "),
5894 &commit->author, &commit->time);
5895 graph_render_parents(&graph);
5896 break;
5898 default:
5899 /* Fill in the commit title if it has not already been set. */
5900 if (commit->title[0])
5901 break;
5903 /* Require titles to start with a non-space character at the
5904 * offset used by git log. */
5905 if (strncmp(line, " ", 4))
5906 break;
5907 line += 4;
5908 /* Well, if the title starts with a whitespace character,
5909 * try to be forgiving. Otherwise we end up with no title. */
5910 while (isspace(*line))
5911 line++;
5912 if (*line == '\0')
5913 break;
5914 /* FIXME: More graceful handling of titles; append "..." to
5915 * shortened titles, etc. */
5917 string_expand(commit->title, sizeof(commit->title), line, 1);
5918 view->line[view->lines - 1].dirty = 1;
5921 return TRUE;
5924 static enum request
5925 main_request(struct view *view, enum request request, struct line *line)
5927 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5929 switch (request) {
5930 case REQ_ENTER:
5931 if (view_is_displayed(view) && display[0] != view)
5932 maximize_view(view, TRUE);
5933 open_view(view, REQ_VIEW_DIFF, flags);
5934 break;
5935 case REQ_REFRESH:
5936 load_refs();
5937 refresh_view(view);
5938 break;
5939 default:
5940 return request;
5943 return REQ_NONE;
5946 static bool
5947 grep_refs(struct ref_list *list, regex_t *regex)
5949 regmatch_t pmatch;
5950 size_t i;
5952 if (!opt_show_refs || !list)
5953 return FALSE;
5955 for (i = 0; i < list->size; i++) {
5956 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
5957 return TRUE;
5960 return FALSE;
5963 static bool
5964 main_grep(struct view *view, struct line *line)
5966 struct commit *commit = line->data;
5967 const char *text[] = {
5968 commit->title,
5969 mkauthor(commit->author, opt_author_cols, opt_author),
5970 mkdate(&commit->time, opt_date),
5971 NULL
5974 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
5977 static void
5978 main_select(struct view *view, struct line *line)
5980 struct commit *commit = line->data;
5982 string_copy_rev(view->ref, commit->id);
5983 string_copy_rev(ref_commit, view->ref);
5986 static struct view_ops main_ops = {
5987 "commit",
5988 main_open,
5989 main_read,
5990 main_draw,
5991 main_request,
5992 main_grep,
5993 main_select,
5998 * Status management
6001 /* Whether or not the curses interface has been initialized. */
6002 static bool cursed = FALSE;
6004 /* Terminal hacks and workarounds. */
6005 static bool use_scroll_redrawwin;
6006 static bool use_scroll_status_wclear;
6008 /* The status window is used for polling keystrokes. */
6009 static WINDOW *status_win;
6011 /* Reading from the prompt? */
6012 static bool input_mode = FALSE;
6014 static bool status_empty = FALSE;
6016 /* Update status and title window. */
6017 static void
6018 report(const char *msg, ...)
6020 struct view *view = display[current_view];
6022 if (input_mode)
6023 return;
6025 if (!view) {
6026 char buf[SIZEOF_STR];
6027 va_list args;
6029 va_start(args, msg);
6030 if (vsnprintf(buf, sizeof(buf), msg, args) >= sizeof(buf)) {
6031 buf[sizeof(buf) - 1] = 0;
6032 buf[sizeof(buf) - 2] = '.';
6033 buf[sizeof(buf) - 3] = '.';
6034 buf[sizeof(buf) - 4] = '.';
6036 va_end(args);
6037 die("%s", buf);
6040 if (!status_empty || *msg) {
6041 va_list args;
6043 va_start(args, msg);
6045 wmove(status_win, 0, 0);
6046 if (view->has_scrolled && use_scroll_status_wclear)
6047 wclear(status_win);
6048 if (*msg) {
6049 vwprintw(status_win, msg, args);
6050 status_empty = FALSE;
6051 } else {
6052 status_empty = TRUE;
6054 wclrtoeol(status_win);
6055 wnoutrefresh(status_win);
6057 va_end(args);
6060 update_view_title(view);
6063 static void
6064 init_display(void)
6066 const char *term;
6067 int x, y;
6069 /* Initialize the curses library */
6070 if (isatty(STDIN_FILENO)) {
6071 cursed = !!initscr();
6072 opt_tty = stdin;
6073 } else {
6074 /* Leave stdin and stdout alone when acting as a pager. */
6075 opt_tty = fopen("/dev/tty", "r+");
6076 if (!opt_tty)
6077 die("Failed to open /dev/tty");
6078 cursed = !!newterm(NULL, opt_tty, opt_tty);
6081 if (!cursed)
6082 die("Failed to initialize curses");
6084 nonl(); /* Disable conversion and detect newlines from input. */
6085 cbreak(); /* Take input chars one at a time, no wait for \n */
6086 noecho(); /* Don't echo input */
6087 leaveok(stdscr, FALSE);
6089 if (has_colors())
6090 init_colors();
6092 getmaxyx(stdscr, y, x);
6093 status_win = newwin(1, x, y - 1, 0);
6094 if (!status_win)
6095 die("Failed to create status window");
6097 /* Enable keyboard mapping */
6098 keypad(status_win, TRUE);
6099 wbkgdset(status_win, get_line_attr(LINE_STATUS));
6101 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6102 set_tabsize(opt_tab_size);
6103 #else
6104 TABSIZE = opt_tab_size;
6105 #endif
6107 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6108 if (term && !strcmp(term, "gnome-terminal")) {
6109 /* In the gnome-terminal-emulator, the message from
6110 * scrolling up one line when impossible followed by
6111 * scrolling down one line causes corruption of the
6112 * status line. This is fixed by calling wclear. */
6113 use_scroll_status_wclear = TRUE;
6114 use_scroll_redrawwin = FALSE;
6116 } else if (term && !strcmp(term, "xrvt-xpm")) {
6117 /* No problems with full optimizations in xrvt-(unicode)
6118 * and aterm. */
6119 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6121 } else {
6122 /* When scrolling in (u)xterm the last line in the
6123 * scrolling direction will update slowly. */
6124 use_scroll_redrawwin = TRUE;
6125 use_scroll_status_wclear = FALSE;
6129 static int
6130 get_input(int prompt_position)
6132 struct view *view;
6133 int i, key, cursor_y, cursor_x;
6135 if (prompt_position)
6136 input_mode = TRUE;
6138 while (TRUE) {
6139 bool loading = FALSE;
6141 foreach_view (view, i) {
6142 update_view(view);
6143 if (view_is_displayed(view) && view->has_scrolled &&
6144 use_scroll_redrawwin)
6145 redrawwin(view->win);
6146 view->has_scrolled = FALSE;
6147 if (view->pipe)
6148 loading = TRUE;
6151 /* Update the cursor position. */
6152 if (prompt_position) {
6153 getbegyx(status_win, cursor_y, cursor_x);
6154 cursor_x = prompt_position;
6155 } else {
6156 view = display[current_view];
6157 getbegyx(view->win, cursor_y, cursor_x);
6158 cursor_x = view->width - 1;
6159 cursor_y += view->lineno - view->offset;
6161 setsyx(cursor_y, cursor_x);
6163 /* Refresh, accept single keystroke of input */
6164 doupdate();
6165 nodelay(status_win, loading);
6166 key = wgetch(status_win);
6168 /* wgetch() with nodelay() enabled returns ERR when
6169 * there's no input. */
6170 if (key == ERR) {
6172 } else if (key == KEY_RESIZE) {
6173 int height, width;
6175 getmaxyx(stdscr, height, width);
6177 wresize(status_win, 1, width);
6178 mvwin(status_win, height - 1, 0);
6179 wnoutrefresh(status_win);
6180 resize_display();
6181 redraw_display(TRUE);
6183 } else {
6184 input_mode = FALSE;
6185 return key;
6190 static char *
6191 prompt_input(const char *prompt, input_handler handler, void *data)
6193 enum input_status status = INPUT_OK;
6194 static char buf[SIZEOF_STR];
6195 size_t pos = 0;
6197 buf[pos] = 0;
6199 while (status == INPUT_OK || status == INPUT_SKIP) {
6200 int key;
6202 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6203 wclrtoeol(status_win);
6205 key = get_input(pos + 1);
6206 switch (key) {
6207 case KEY_RETURN:
6208 case KEY_ENTER:
6209 case '\n':
6210 status = pos ? INPUT_STOP : INPUT_CANCEL;
6211 break;
6213 case KEY_BACKSPACE:
6214 if (pos > 0)
6215 buf[--pos] = 0;
6216 else
6217 status = INPUT_CANCEL;
6218 break;
6220 case KEY_ESC:
6221 status = INPUT_CANCEL;
6222 break;
6224 default:
6225 if (pos >= sizeof(buf)) {
6226 report("Input string too long");
6227 return NULL;
6230 status = handler(data, buf, key);
6231 if (status == INPUT_OK)
6232 buf[pos++] = (char) key;
6236 /* Clear the status window */
6237 status_empty = FALSE;
6238 report("");
6240 if (status == INPUT_CANCEL)
6241 return NULL;
6243 buf[pos++] = 0;
6245 return buf;
6248 static enum input_status
6249 prompt_yesno_handler(void *data, char *buf, int c)
6251 if (c == 'y' || c == 'Y')
6252 return INPUT_STOP;
6253 if (c == 'n' || c == 'N')
6254 return INPUT_CANCEL;
6255 return INPUT_SKIP;
6258 static bool
6259 prompt_yesno(const char *prompt)
6261 char prompt2[SIZEOF_STR];
6263 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6264 return FALSE;
6266 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6269 static enum input_status
6270 read_prompt_handler(void *data, char *buf, int c)
6272 return isprint(c) ? INPUT_OK : INPUT_SKIP;
6275 static char *
6276 read_prompt(const char *prompt)
6278 return prompt_input(prompt, read_prompt_handler, NULL);
6281 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6283 enum input_status status = INPUT_OK;
6284 int size = 0;
6286 while (items[size].text)
6287 size++;
6289 while (status == INPUT_OK) {
6290 const struct menu_item *item = &items[*selected];
6291 int key;
6292 int i;
6294 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6295 prompt, *selected + 1, size);
6296 if (item->hotkey)
6297 wprintw(status_win, "[%c] ", (char) item->hotkey);
6298 wprintw(status_win, "%s", item->text);
6299 wclrtoeol(status_win);
6301 key = get_input(COLS - 1);
6302 switch (key) {
6303 case KEY_RETURN:
6304 case KEY_ENTER:
6305 case '\n':
6306 status = INPUT_STOP;
6307 break;
6309 case KEY_LEFT:
6310 case KEY_UP:
6311 *selected = *selected - 1;
6312 if (*selected < 0)
6313 *selected = size - 1;
6314 break;
6316 case KEY_RIGHT:
6317 case KEY_DOWN:
6318 *selected = (*selected + 1) % size;
6319 break;
6321 case KEY_ESC:
6322 status = INPUT_CANCEL;
6323 break;
6325 default:
6326 for (i = 0; items[i].text; i++)
6327 if (items[i].hotkey == key) {
6328 *selected = i;
6329 status = INPUT_STOP;
6330 break;
6335 /* Clear the status window */
6336 status_empty = FALSE;
6337 report("");
6339 return status != INPUT_CANCEL;
6343 * Repository properties
6346 static struct ref **refs = NULL;
6347 static size_t refs_size = 0;
6348 static struct ref *refs_head = NULL;
6350 static struct ref_list **ref_lists = NULL;
6351 static size_t ref_lists_size = 0;
6353 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
6354 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
6355 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
6357 static int
6358 compare_refs(const void *ref1_, const void *ref2_)
6360 const struct ref *ref1 = *(const struct ref **)ref1_;
6361 const struct ref *ref2 = *(const struct ref **)ref2_;
6363 if (ref1->tag != ref2->tag)
6364 return ref2->tag - ref1->tag;
6365 if (ref1->ltag != ref2->ltag)
6366 return ref2->ltag - ref2->ltag;
6367 if (ref1->head != ref2->head)
6368 return ref2->head - ref1->head;
6369 if (ref1->tracked != ref2->tracked)
6370 return ref2->tracked - ref1->tracked;
6371 if (ref1->remote != ref2->remote)
6372 return ref2->remote - ref1->remote;
6373 return strcmp(ref1->name, ref2->name);
6376 static void
6377 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
6379 size_t i;
6381 for (i = 0; i < refs_size; i++)
6382 if (!visitor(data, refs[i]))
6383 break;
6386 static struct ref *
6387 get_ref_head()
6389 return refs_head;
6392 static struct ref_list *
6393 get_ref_list(const char *id)
6395 struct ref_list *list;
6396 size_t i;
6398 for (i = 0; i < ref_lists_size; i++)
6399 if (!strcmp(id, ref_lists[i]->id))
6400 return ref_lists[i];
6402 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
6403 return NULL;
6404 list = calloc(1, sizeof(*list));
6405 if (!list)
6406 return NULL;
6408 for (i = 0; i < refs_size; i++) {
6409 if (!strcmp(id, refs[i]->id) &&
6410 realloc_refs_list(&list->refs, list->size, 1))
6411 list->refs[list->size++] = refs[i];
6414 if (!list->refs) {
6415 free(list);
6416 return NULL;
6419 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
6420 ref_lists[ref_lists_size++] = list;
6421 return list;
6424 static int
6425 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
6427 struct ref *ref = NULL;
6428 bool tag = FALSE;
6429 bool ltag = FALSE;
6430 bool remote = FALSE;
6431 bool tracked = FALSE;
6432 bool head = FALSE;
6433 int from = 0, to = refs_size - 1;
6435 if (!prefixcmp(name, "refs/tags/")) {
6436 if (!suffixcmp(name, namelen, "^{}")) {
6437 namelen -= 3;
6438 name[namelen] = 0;
6439 } else {
6440 ltag = TRUE;
6443 tag = TRUE;
6444 namelen -= STRING_SIZE("refs/tags/");
6445 name += STRING_SIZE("refs/tags/");
6447 } else if (!prefixcmp(name, "refs/remotes/")) {
6448 remote = TRUE;
6449 namelen -= STRING_SIZE("refs/remotes/");
6450 name += STRING_SIZE("refs/remotes/");
6451 tracked = !strcmp(opt_remote, name);
6453 } else if (!prefixcmp(name, "refs/heads/")) {
6454 namelen -= STRING_SIZE("refs/heads/");
6455 name += STRING_SIZE("refs/heads/");
6456 if (!strncmp(opt_head, name, namelen))
6457 return OK;
6459 } else if (!strcmp(name, "HEAD")) {
6460 head = TRUE;
6461 if (*opt_head) {
6462 namelen = strlen(opt_head);
6463 name = opt_head;
6467 /* If we are reloading or it's an annotated tag, replace the
6468 * previous SHA1 with the resolved commit id; relies on the fact
6469 * git-ls-remote lists the commit id of an annotated tag right
6470 * before the commit id it points to. */
6471 while (from <= to) {
6472 size_t pos = (to + from) / 2;
6473 int cmp = strcmp(name, refs[pos]->name);
6475 if (!cmp) {
6476 ref = refs[pos];
6477 break;
6480 if (cmp < 0)
6481 to = pos - 1;
6482 else
6483 from = pos + 1;
6486 if (!ref) {
6487 if (!realloc_refs(&refs, refs_size, 1))
6488 return ERR;
6489 ref = calloc(1, sizeof(*ref) + namelen);
6490 if (!ref)
6491 return ERR;
6492 memmove(refs + from + 1, refs + from,
6493 (refs_size - from) * sizeof(*refs));
6494 refs[from] = ref;
6495 strncpy(ref->name, name, namelen);
6496 refs_size++;
6499 ref->head = head;
6500 ref->tag = tag;
6501 ref->ltag = ltag;
6502 ref->remote = remote;
6503 ref->tracked = tracked;
6504 string_copy_rev(ref->id, id);
6506 if (head)
6507 refs_head = ref;
6508 return OK;
6511 static int
6512 load_refs(void)
6514 const char *head_argv[] = {
6515 "git", "symbolic-ref", "HEAD", NULL
6517 static const char *ls_remote_argv[SIZEOF_ARG] = {
6518 "git", "ls-remote", opt_git_dir, NULL
6520 static bool init = FALSE;
6521 size_t i;
6523 if (!init) {
6524 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
6525 die("TIG_LS_REMOTE contains too many arguments");
6526 init = TRUE;
6529 if (!*opt_git_dir)
6530 return OK;
6532 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
6533 !prefixcmp(opt_head, "refs/heads/")) {
6534 char *offset = opt_head + STRING_SIZE("refs/heads/");
6536 memmove(opt_head, offset, strlen(offset) + 1);
6539 refs_head = NULL;
6540 for (i = 0; i < refs_size; i++)
6541 refs[i]->id[0] = 0;
6543 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
6544 return ERR;
6546 /* Update the ref lists to reflect changes. */
6547 for (i = 0; i < ref_lists_size; i++) {
6548 struct ref_list *list = ref_lists[i];
6549 size_t old, new;
6551 for (old = new = 0; old < list->size; old++)
6552 if (!strcmp(list->id, list->refs[old]->id))
6553 list->refs[new++] = list->refs[old];
6554 list->size = new;
6557 return OK;
6560 static void
6561 set_remote_branch(const char *name, const char *value, size_t valuelen)
6563 if (!strcmp(name, ".remote")) {
6564 string_ncopy(opt_remote, value, valuelen);
6566 } else if (*opt_remote && !strcmp(name, ".merge")) {
6567 size_t from = strlen(opt_remote);
6569 if (!prefixcmp(value, "refs/heads/"))
6570 value += STRING_SIZE("refs/heads/");
6572 if (!string_format_from(opt_remote, &from, "/%s", value))
6573 opt_remote[0] = 0;
6577 static void
6578 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
6580 const char *argv[SIZEOF_ARG] = { name, "=" };
6581 int argc = 1 + (cmd == option_set_command);
6582 enum option_code error;
6584 if (!argv_from_string(argv, &argc, value))
6585 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
6586 else
6587 error = cmd(argc, argv);
6589 if (error != OPT_OK)
6590 warn("Option 'tig.%s': %s", name, option_errors[error]);
6593 static bool
6594 set_environment_variable(const char *name, const char *value)
6596 size_t len = strlen(name) + 1 + strlen(value) + 1;
6597 char *env = malloc(len);
6599 if (env &&
6600 string_nformat(env, len, NULL, "%s=%s", name, value) &&
6601 putenv(env) == 0)
6602 return TRUE;
6603 free(env);
6604 return FALSE;
6607 static void
6608 set_work_tree(const char *value)
6610 char cwd[SIZEOF_STR];
6612 if (!getcwd(cwd, sizeof(cwd)))
6613 die("Failed to get cwd path: %s", strerror(errno));
6614 if (chdir(opt_git_dir) < 0)
6615 die("Failed to chdir(%s): %s", strerror(errno));
6616 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
6617 die("Failed to get git path: %s", strerror(errno));
6618 if (chdir(cwd) < 0)
6619 die("Failed to chdir(%s): %s", cwd, strerror(errno));
6620 if (chdir(value) < 0)
6621 die("Failed to chdir(%s): %s", value, strerror(errno));
6622 if (!getcwd(cwd, sizeof(cwd)))
6623 die("Failed to get cwd path: %s", strerror(errno));
6624 if (!set_environment_variable("GIT_WORK_TREE", cwd))
6625 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
6626 if (!set_environment_variable("GIT_DIR", opt_git_dir))
6627 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
6628 opt_is_inside_work_tree = TRUE;
6631 static int
6632 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6634 if (!strcmp(name, "i18n.commitencoding"))
6635 string_ncopy(opt_encoding, value, valuelen);
6637 else if (!strcmp(name, "core.editor"))
6638 string_ncopy(opt_editor, value, valuelen);
6640 else if (!strcmp(name, "core.worktree"))
6641 set_work_tree(value);
6643 else if (!prefixcmp(name, "tig.color."))
6644 set_repo_config_option(name + 10, value, option_color_command);
6646 else if (!prefixcmp(name, "tig.bind."))
6647 set_repo_config_option(name + 9, value, option_bind_command);
6649 else if (!prefixcmp(name, "tig."))
6650 set_repo_config_option(name + 4, value, option_set_command);
6652 else if (*opt_head && !prefixcmp(name, "branch.") &&
6653 !strncmp(name + 7, opt_head, strlen(opt_head)))
6654 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
6656 return OK;
6659 static int
6660 load_git_config(void)
6662 const char *config_list_argv[] = { "git", "config", "--list", NULL };
6664 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
6667 static int
6668 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6670 if (!opt_git_dir[0]) {
6671 string_ncopy(opt_git_dir, name, namelen);
6673 } else if (opt_is_inside_work_tree == -1) {
6674 /* This can be 3 different values depending on the
6675 * version of git being used. If git-rev-parse does not
6676 * understand --is-inside-work-tree it will simply echo
6677 * the option else either "true" or "false" is printed.
6678 * Default to true for the unknown case. */
6679 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
6681 } else if (*name == '.') {
6682 string_ncopy(opt_cdup, name, namelen);
6684 } else {
6685 string_ncopy(opt_prefix, name, namelen);
6688 return OK;
6691 static int
6692 load_repo_info(void)
6694 const char *rev_parse_argv[] = {
6695 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
6696 "--show-cdup", "--show-prefix", NULL
6699 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
6704 * Main
6707 static const char usage[] =
6708 "tig " TIG_VERSION " (" __DATE__ ")\n"
6709 "\n"
6710 "Usage: tig [options] [revs] [--] [paths]\n"
6711 " or: tig show [options] [revs] [--] [paths]\n"
6712 " or: tig blame [options] [rev] [--] path\n"
6713 " or: tig status\n"
6714 " or: tig < [git command output]\n"
6715 "\n"
6716 "Options:\n"
6717 " -v, --version Show version and exit\n"
6718 " -h, --help Show help message and exit";
6720 static void __NORETURN
6721 quit(int sig)
6723 /* XXX: Restore tty modes and let the OS cleanup the rest! */
6724 if (cursed)
6725 endwin();
6726 exit(0);
6729 static void __NORETURN
6730 die(const char *err, ...)
6732 va_list args;
6734 endwin();
6736 va_start(args, err);
6737 fputs("tig: ", stderr);
6738 vfprintf(stderr, err, args);
6739 fputs("\n", stderr);
6740 va_end(args);
6742 exit(1);
6745 static void
6746 warn(const char *msg, ...)
6748 va_list args;
6750 va_start(args, msg);
6751 fputs("tig warning: ", stderr);
6752 vfprintf(stderr, msg, args);
6753 fputs("\n", stderr);
6754 va_end(args);
6757 static int
6758 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6760 const char ***filter_args = data;
6762 return argv_append(filter_args, name) ? OK : ERR;
6765 static void
6766 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
6768 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
6769 const char **all_argv = NULL;
6771 if (!argv_append_array(&all_argv, rev_parse_argv) ||
6772 !argv_append_array(&all_argv, argv) ||
6773 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
6774 die("Failed to split arguments");
6775 argv_free(all_argv);
6776 free(all_argv);
6779 static void
6780 filter_options(const char *argv[])
6782 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
6783 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
6784 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
6787 static enum request
6788 parse_options(int argc, const char *argv[])
6790 enum request request = REQ_VIEW_MAIN;
6791 const char *subcommand;
6792 bool seen_dashdash = FALSE;
6793 const char **filter_argv = NULL;
6794 int i;
6796 if (!isatty(STDIN_FILENO))
6797 return REQ_VIEW_PAGER;
6799 if (argc <= 1)
6800 return REQ_VIEW_MAIN;
6802 subcommand = argv[1];
6803 if (!strcmp(subcommand, "status")) {
6804 if (argc > 2)
6805 warn("ignoring arguments after `%s'", subcommand);
6806 return REQ_VIEW_STATUS;
6808 } else if (!strcmp(subcommand, "blame")) {
6809 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv + 2);
6810 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv + 2);
6811 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv + 2);
6813 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
6814 die("invalid number of options to blame\n\n%s", usage);
6816 if (opt_rev_argv) {
6817 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
6820 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
6821 return REQ_VIEW_BLAME;
6823 } else if (!strcmp(subcommand, "show")) {
6824 request = REQ_VIEW_DIFF;
6826 } else {
6827 subcommand = NULL;
6830 for (i = 1 + !!subcommand; i < argc; i++) {
6831 const char *opt = argv[i];
6833 if (seen_dashdash) {
6834 argv_append(&opt_file_argv, opt);
6835 continue;
6837 } else if (!strcmp(opt, "--")) {
6838 seen_dashdash = TRUE;
6839 continue;
6841 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
6842 printf("tig version %s\n", TIG_VERSION);
6843 quit(0);
6845 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
6846 printf("%s\n", usage);
6847 quit(0);
6849 } else if (!strcmp(opt, "--all")) {
6850 argv_append(&opt_rev_argv, opt);
6851 continue;
6854 if (!argv_append(&filter_argv, opt))
6855 die("command too long");
6858 if (filter_argv)
6859 filter_options(filter_argv);
6861 return request;
6865 main(int argc, const char *argv[])
6867 const char *codeset = "UTF-8";
6868 enum request request = parse_options(argc, argv);
6869 struct view *view;
6871 signal(SIGINT, quit);
6872 signal(SIGPIPE, SIG_IGN);
6874 if (setlocale(LC_ALL, "")) {
6875 codeset = nl_langinfo(CODESET);
6878 if (load_repo_info() == ERR)
6879 die("Failed to load repo info.");
6881 if (load_options() == ERR)
6882 die("Failed to load user config.");
6884 if (load_git_config() == ERR)
6885 die("Failed to load repo config.");
6887 /* Require a git repository unless when running in pager mode. */
6888 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
6889 die("Not a git repository");
6891 if (*opt_encoding && strcmp(codeset, "UTF-8")) {
6892 opt_iconv_in = iconv_open("UTF-8", opt_encoding);
6893 if (opt_iconv_in == ICONV_NONE)
6894 die("Failed to initialize character set conversion");
6897 if (codeset && strcmp(codeset, "UTF-8")) {
6898 opt_iconv_out = iconv_open(codeset, "UTF-8");
6899 if (opt_iconv_out == ICONV_NONE)
6900 die("Failed to initialize character set conversion");
6903 if (load_refs() == ERR)
6904 die("Failed to load refs.");
6906 init_display();
6908 while (view_driver(display[current_view], request)) {
6909 int key = get_input(0);
6911 view = display[current_view];
6912 request = get_keybinding(view->keymap, key);
6914 /* Some low-level request handling. This keeps access to
6915 * status_win restricted. */
6916 switch (request) {
6917 case REQ_NONE:
6918 report("Unknown key, press %s for help",
6919 get_key(view->keymap, REQ_VIEW_HELP));
6920 break;
6921 case REQ_PROMPT:
6923 char *cmd = read_prompt(":");
6925 if (cmd && isdigit(*cmd)) {
6926 int lineno = view->lineno + 1;
6928 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OPT_OK) {
6929 select_view_line(view, lineno - 1);
6930 report("");
6931 } else {
6932 report("Unable to parse '%s' as a line number", cmd);
6935 } else if (cmd) {
6936 struct view *next = VIEW(REQ_VIEW_PAGER);
6937 const char *argv[SIZEOF_ARG] = { "git" };
6938 int argc = 1;
6940 /* When running random commands, initially show the
6941 * command in the title. However, it maybe later be
6942 * overwritten if a commit line is selected. */
6943 string_ncopy(next->ref, cmd, strlen(cmd));
6945 if (!argv_from_string(argv, &argc, cmd)) {
6946 report("Too many arguments");
6947 } else {
6948 open_argv(view, next, argv, NULL, OPEN_DEFAULT);
6952 request = REQ_NONE;
6953 break;
6955 case REQ_SEARCH:
6956 case REQ_SEARCH_BACK:
6958 const char *prompt = request == REQ_SEARCH ? "/" : "?";
6959 char *search = read_prompt(prompt);
6961 if (search)
6962 string_ncopy(opt_search, search, strlen(search));
6963 else if (*opt_search)
6964 request = request == REQ_SEARCH ?
6965 REQ_FIND_NEXT :
6966 REQ_FIND_PREV;
6967 else
6968 request = REQ_NONE;
6969 break;
6971 default:
6972 break;
6976 quit(0);
6978 return 0;