1 /* Copyright (c) 2006-2010 Jonas Fonseca <fonseca@diku.dk>
2 *
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.
7 *
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.
12 */
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. */
31 };
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. */
37 };
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
49 };
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;
60 };
62 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
64 enum graphic {
65 GRAPHIC_ASCII = 0,
66 GRAPHIC_DEFAULT,
67 GRAPHIC_UTF8
68 };
70 static const struct enum_map graphic_map[] = {
71 #define GRAPHIC_(name) ENUM_MAP(#name, GRAPHIC_##name)
72 GRAPHIC_(ASCII),
73 GRAPHIC_(DEFAULT),
74 GRAPHIC_(UTF8)
75 #undef GRAPHIC_
76 };
78 #define DATE_INFO \
79 DATE_(NO), \
80 DATE_(DEFAULT), \
81 DATE_(LOCAL), \
82 DATE_(RELATIVE), \
83 DATE_(SHORT)
85 enum date {
86 #define DATE_(name) DATE_##name
87 DATE_INFO
88 #undef DATE_
89 };
91 static const struct enum_map date_map[] = {
92 #define DATE_(name) ENUM_MAP(#name, DATE_##name)
93 DATE_INFO
94 #undef DATE_
95 };
97 struct time {
98 time_t sec;
99 int tz;
100 };
102 static inline int timecmp(const struct time *t1, const struct time *t2)
103 {
104 return t1->sec - t2->sec;
105 }
107 static const char *
108 mkdate(const struct time *time, enum date date)
109 {
110 static char buf[DATE_COLS + 1];
111 static const struct enum_map reldate[] = {
112 { "second", 1, 60 * 2 },
113 { "minute", 60, 60 * 60 * 2 },
114 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
115 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
116 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
117 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 30 * 12 },
118 };
119 struct tm tm;
121 if (!date || !time || !time->sec)
122 return "";
124 if (date == DATE_RELATIVE) {
125 struct timeval now;
126 time_t date = time->sec + time->tz;
127 time_t seconds;
128 int i;
130 gettimeofday(&now, NULL);
131 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
132 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
133 if (seconds >= reldate[i].value)
134 continue;
136 seconds /= reldate[i].namelen;
137 if (!string_format(buf, "%ld %s%s %s",
138 seconds, reldate[i].name,
139 seconds > 1 ? "s" : "",
140 now.tv_sec >= date ? "ago" : "ahead"))
141 break;
142 return buf;
143 }
144 }
146 if (date == DATE_LOCAL) {
147 time_t date = time->sec + time->tz;
148 localtime_r(&date, &tm);
149 }
150 else {
151 gmtime_r(&time->sec, &tm);
152 }
153 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
154 }
157 #define AUTHOR_VALUES \
158 AUTHOR_(NO), \
159 AUTHOR_(FULL), \
160 AUTHOR_(ABBREVIATED)
162 enum author {
163 #define AUTHOR_(name) AUTHOR_##name
164 AUTHOR_VALUES,
165 #undef AUTHOR_
166 AUTHOR_DEFAULT = AUTHOR_FULL
167 };
169 static const struct enum_map author_map[] = {
170 #define AUTHOR_(name) ENUM_MAP(#name, AUTHOR_##name)
171 AUTHOR_VALUES
172 #undef AUTHOR_
173 };
175 static const char *
176 get_author_initials(const char *author)
177 {
178 static char initials[AUTHOR_COLS * 6 + 1];
179 size_t pos = 0;
180 const char *end = strchr(author, '\0');
182 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
184 memset(initials, 0, sizeof(initials));
185 while (author < end) {
186 unsigned char bytes;
187 size_t i;
189 while (is_initial_sep(*author))
190 author++;
192 bytes = utf8_char_length(author, end);
193 if (bytes < sizeof(initials) - 1 - pos) {
194 while (bytes--) {
195 initials[pos++] = *author++;
196 }
197 }
199 for (i = pos; author < end && !is_initial_sep(*author); author++) {
200 if (i < sizeof(initials) - 1)
201 initials[i++] = *author;
202 }
204 initials[i++] = 0;
205 }
207 return initials;
208 }
211 /*
212 * User requests
213 */
215 #define REQ_INFO \
216 /* XXX: Keep the view request first and in sync with views[]. */ \
217 REQ_GROUP("View switching") \
218 REQ_(VIEW_MAIN, "Show main view"), \
219 REQ_(VIEW_DIFF, "Show diff view"), \
220 REQ_(VIEW_LOG, "Show log view"), \
221 REQ_(VIEW_TREE, "Show tree view"), \
222 REQ_(VIEW_BLOB, "Show blob view"), \
223 REQ_(VIEW_BLAME, "Show blame view"), \
224 REQ_(VIEW_BRANCH, "Show branch view"), \
225 REQ_(VIEW_HELP, "Show help page"), \
226 REQ_(VIEW_PAGER, "Show pager view"), \
227 REQ_(VIEW_STATUS, "Show status view"), \
228 REQ_(VIEW_STAGE, "Show stage view"), \
229 \
230 REQ_GROUP("View manipulation") \
231 REQ_(ENTER, "Enter current line and scroll"), \
232 REQ_(NEXT, "Move to next"), \
233 REQ_(PREVIOUS, "Move to previous"), \
234 REQ_(PARENT, "Move to parent"), \
235 REQ_(VIEW_NEXT, "Move focus to next view"), \
236 REQ_(REFRESH, "Reload and refresh"), \
237 REQ_(MAXIMIZE, "Maximize the current view"), \
238 REQ_(VIEW_CLOSE, "Close the current view"), \
239 REQ_(QUIT, "Close all views and quit"), \
240 \
241 REQ_GROUP("View specific requests") \
242 REQ_(STATUS_UPDATE, "Update file status"), \
243 REQ_(STATUS_REVERT, "Revert file changes"), \
244 REQ_(STATUS_MERGE, "Merge file using external tool"), \
245 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
246 \
247 REQ_GROUP("Cursor navigation") \
248 REQ_(MOVE_UP, "Move cursor one line up"), \
249 REQ_(MOVE_DOWN, "Move cursor one line down"), \
250 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
251 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
252 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
253 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
254 \
255 REQ_GROUP("Scrolling") \
256 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
257 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
258 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
259 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
260 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
261 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
262 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
263 \
264 REQ_GROUP("Searching") \
265 REQ_(SEARCH, "Search the view"), \
266 REQ_(SEARCH_BACK, "Search backwards in the view"), \
267 REQ_(FIND_NEXT, "Find next search match"), \
268 REQ_(FIND_PREV, "Find previous search match"), \
269 \
270 REQ_GROUP("Option manipulation") \
271 REQ_(OPTIONS, "Open option menu"), \
272 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
273 REQ_(TOGGLE_DATE, "Toggle date display"), \
274 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
275 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
276 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
277 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
278 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
279 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
280 \
281 REQ_GROUP("Misc") \
282 REQ_(PROMPT, "Bring up the prompt"), \
283 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
284 REQ_(SHOW_VERSION, "Show version information"), \
285 REQ_(STOP_LOADING, "Stop all loading views"), \
286 REQ_(EDIT, "Open in editor"), \
287 REQ_(NONE, "Do nothing")
290 /* User action requests. */
291 enum request {
292 #define REQ_GROUP(help)
293 #define REQ_(req, help) REQ_##req
295 /* Offset all requests to avoid conflicts with ncurses getch values. */
296 REQ_UNKNOWN = KEY_MAX + 1,
297 REQ_OFFSET,
298 REQ_INFO
300 #undef REQ_GROUP
301 #undef REQ_
302 };
304 struct request_info {
305 enum request request;
306 const char *name;
307 int namelen;
308 const char *help;
309 };
311 static const struct request_info req_info[] = {
312 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
313 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
314 REQ_INFO
315 #undef REQ_GROUP
316 #undef REQ_
317 };
319 static enum request
320 get_request(const char *name)
321 {
322 int namelen = strlen(name);
323 int i;
325 for (i = 0; i < ARRAY_SIZE(req_info); i++)
326 if (enum_equals(req_info[i], name, namelen))
327 return req_info[i].request;
329 return REQ_UNKNOWN;
330 }
333 /*
334 * Options
335 */
337 /* Option and state variables. */
338 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
339 static enum date opt_date = DATE_DEFAULT;
340 static enum author opt_author = AUTHOR_DEFAULT;
341 static bool opt_rev_graph = TRUE;
342 static bool opt_line_number = FALSE;
343 static bool opt_show_refs = TRUE;
344 static bool opt_untracked_dirs_content = TRUE;
345 static int opt_num_interval = 5;
346 static double opt_hscroll = 0.50;
347 static double opt_scale_split_view = 2.0 / 3.0;
348 static int opt_tab_size = 8;
349 static int opt_author_cols = AUTHOR_COLS;
350 static char opt_path[SIZEOF_STR] = "";
351 static char opt_file[SIZEOF_STR] = "";
352 static char opt_ref[SIZEOF_REF] = "";
353 static char opt_head[SIZEOF_REF] = "";
354 static char opt_remote[SIZEOF_REF] = "";
355 static char opt_encoding[20] = "UTF-8";
356 static iconv_t opt_iconv_in = ICONV_NONE;
357 static iconv_t opt_iconv_out = ICONV_NONE;
358 static char opt_search[SIZEOF_STR] = "";
359 static char opt_cdup[SIZEOF_STR] = "";
360 static char opt_prefix[SIZEOF_STR] = "";
361 static char opt_git_dir[SIZEOF_STR] = "";
362 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
363 static char opt_editor[SIZEOF_STR] = "";
364 static FILE *opt_tty = NULL;
365 static const char **opt_diff_argv = NULL;
366 static const char **opt_rev_argv = NULL;
367 static const char **opt_file_argv = NULL;
368 static const char **opt_blame_argv = NULL;
370 #define is_initial_commit() (!get_ref_head())
371 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
374 /*
375 * Line-oriented content detection.
376 */
378 #define LINE_INFO \
379 LINE(DIFF_HEADER, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
380 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
381 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
382 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
383 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
384 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
385 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
386 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
387 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
388 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
389 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
390 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
391 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
392 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
393 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
394 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
395 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
396 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
397 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
398 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
399 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
400 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
401 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
402 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
403 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
404 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
405 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
406 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
407 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
408 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
409 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
410 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
411 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
412 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
413 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
414 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
415 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
416 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
417 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
418 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
419 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
420 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
421 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
422 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
423 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
424 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
425 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
426 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
427 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
428 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
429 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
430 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
431 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
432 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
433 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
434 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
435 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
436 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
437 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
438 LINE(GRAPH_LINE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
439 LINE(GRAPH_LINE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
440 LINE(GRAPH_LINE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
441 LINE(GRAPH_LINE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
442 LINE(GRAPH_LINE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
443 LINE(GRAPH_LINE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
444 LINE(GRAPH_LINE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
445 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
447 enum line_type {
448 #define LINE(type, line, fg, bg, attr) \
449 LINE_##type
450 LINE_INFO,
451 LINE_NONE
452 #undef LINE
453 };
455 struct line_info {
456 const char *name; /* Option name. */
457 int namelen; /* Size of option name. */
458 const char *line; /* The start of line to match. */
459 int linelen; /* Size of string to match. */
460 int fg, bg, attr; /* Color and text attributes for the lines. */
461 };
463 static struct line_info line_info[] = {
464 #define LINE(type, line, fg, bg, attr) \
465 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
466 LINE_INFO
467 #undef LINE
468 };
470 static enum line_type
471 get_line_type(const char *line)
472 {
473 int linelen = strlen(line);
474 enum line_type type;
476 for (type = 0; type < ARRAY_SIZE(line_info); type++)
477 /* Case insensitive search matches Signed-off-by lines better. */
478 if (linelen >= line_info[type].linelen &&
479 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
480 return type;
482 return LINE_DEFAULT;
483 }
485 static inline int
486 get_line_attr(enum line_type type)
487 {
488 assert(type < ARRAY_SIZE(line_info));
489 return COLOR_PAIR(type) | line_info[type].attr;
490 }
492 static struct line_info *
493 get_line_info(const char *name)
494 {
495 size_t namelen = strlen(name);
496 enum line_type type;
498 for (type = 0; type < ARRAY_SIZE(line_info); type++)
499 if (enum_equals(line_info[type], name, namelen))
500 return &line_info[type];
502 return NULL;
503 }
505 static void
506 init_colors(void)
507 {
508 int default_bg = line_info[LINE_DEFAULT].bg;
509 int default_fg = line_info[LINE_DEFAULT].fg;
510 enum line_type type;
512 start_color();
514 if (assume_default_colors(default_fg, default_bg) == ERR) {
515 default_bg = COLOR_BLACK;
516 default_fg = COLOR_WHITE;
517 }
519 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
520 struct line_info *info = &line_info[type];
521 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
522 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
524 init_pair(type, fg, bg);
525 }
526 }
528 struct line {
529 enum line_type type;
531 /* State flags */
532 unsigned int selected:1;
533 unsigned int dirty:1;
534 unsigned int cleareol:1;
535 unsigned int other:16;
537 void *data; /* User data */
538 };
541 /*
542 * Keys
543 */
545 struct keybinding {
546 int alias;
547 enum request request;
548 };
550 static struct keybinding default_keybindings[] = {
551 /* View switching */
552 { 'm', REQ_VIEW_MAIN },
553 { 'd', REQ_VIEW_DIFF },
554 { 'l', REQ_VIEW_LOG },
555 { 't', REQ_VIEW_TREE },
556 { 'f', REQ_VIEW_BLOB },
557 { 'B', REQ_VIEW_BLAME },
558 { 'H', REQ_VIEW_BRANCH },
559 { 'p', REQ_VIEW_PAGER },
560 { 'h', REQ_VIEW_HELP },
561 { 'S', REQ_VIEW_STATUS },
562 { 'c', REQ_VIEW_STAGE },
564 /* View manipulation */
565 { 'q', REQ_VIEW_CLOSE },
566 { KEY_TAB, REQ_VIEW_NEXT },
567 { KEY_RETURN, REQ_ENTER },
568 { KEY_UP, REQ_PREVIOUS },
569 { KEY_CTL('P'), REQ_PREVIOUS },
570 { KEY_DOWN, REQ_NEXT },
571 { KEY_CTL('N'), REQ_NEXT },
572 { 'R', REQ_REFRESH },
573 { KEY_F(5), REQ_REFRESH },
574 { 'O', REQ_MAXIMIZE },
576 /* Cursor navigation */
577 { 'k', REQ_MOVE_UP },
578 { 'j', REQ_MOVE_DOWN },
579 { KEY_HOME, REQ_MOVE_FIRST_LINE },
580 { KEY_END, REQ_MOVE_LAST_LINE },
581 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
582 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
583 { ' ', REQ_MOVE_PAGE_DOWN },
584 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
585 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
586 { 'b', REQ_MOVE_PAGE_UP },
587 { '-', REQ_MOVE_PAGE_UP },
589 /* Scrolling */
590 { '|', REQ_SCROLL_FIRST_COL },
591 { KEY_LEFT, REQ_SCROLL_LEFT },
592 { KEY_RIGHT, REQ_SCROLL_RIGHT },
593 { KEY_IC, REQ_SCROLL_LINE_UP },
594 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
595 { KEY_DC, REQ_SCROLL_LINE_DOWN },
596 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
597 { 'w', REQ_SCROLL_PAGE_UP },
598 { 's', REQ_SCROLL_PAGE_DOWN },
600 /* Searching */
601 { '/', REQ_SEARCH },
602 { '?', REQ_SEARCH_BACK },
603 { 'n', REQ_FIND_NEXT },
604 { 'N', REQ_FIND_PREV },
606 /* Misc */
607 { 'Q', REQ_QUIT },
608 { 'z', REQ_STOP_LOADING },
609 { 'v', REQ_SHOW_VERSION },
610 { 'r', REQ_SCREEN_REDRAW },
611 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
612 { 'o', REQ_OPTIONS },
613 { '.', REQ_TOGGLE_LINENO },
614 { 'D', REQ_TOGGLE_DATE },
615 { 'A', REQ_TOGGLE_AUTHOR },
616 { 'g', REQ_TOGGLE_REV_GRAPH },
617 { '~', REQ_TOGGLE_GRAPHIC },
618 { 'F', REQ_TOGGLE_REFS },
619 { 'I', REQ_TOGGLE_SORT_ORDER },
620 { 'i', REQ_TOGGLE_SORT_FIELD },
621 { ':', REQ_PROMPT },
622 { 'u', REQ_STATUS_UPDATE },
623 { '!', REQ_STATUS_REVERT },
624 { 'M', REQ_STATUS_MERGE },
625 { '@', REQ_STAGE_NEXT },
626 { ',', REQ_PARENT },
627 { 'e', REQ_EDIT },
628 };
630 #define KEYMAP_INFO \
631 KEYMAP_(GENERIC), \
632 KEYMAP_(MAIN), \
633 KEYMAP_(DIFF), \
634 KEYMAP_(LOG), \
635 KEYMAP_(TREE), \
636 KEYMAP_(BLOB), \
637 KEYMAP_(BLAME), \
638 KEYMAP_(BRANCH), \
639 KEYMAP_(PAGER), \
640 KEYMAP_(HELP), \
641 KEYMAP_(STATUS), \
642 KEYMAP_(STAGE)
644 enum keymap {
645 #define KEYMAP_(name) KEYMAP_##name
646 KEYMAP_INFO
647 #undef KEYMAP_
648 };
650 static const struct enum_map keymap_table[] = {
651 #define KEYMAP_(name) ENUM_MAP(#name, KEYMAP_##name)
652 KEYMAP_INFO
653 #undef KEYMAP_
654 };
656 #define set_keymap(map, name) map_enum(map, keymap_table, name)
658 struct keybinding_table {
659 struct keybinding *data;
660 size_t size;
661 };
663 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_table)];
665 static void
666 add_keybinding(enum keymap keymap, enum request request, int key)
667 {
668 struct keybinding_table *table = &keybindings[keymap];
669 size_t i;
671 for (i = 0; i < keybindings[keymap].size; i++) {
672 if (keybindings[keymap].data[i].alias == key) {
673 keybindings[keymap].data[i].request = request;
674 return;
675 }
676 }
678 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
679 if (!table->data)
680 die("Failed to allocate keybinding");
681 table->data[table->size].alias = key;
682 table->data[table->size++].request = request;
684 if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
685 int i;
687 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
688 if (default_keybindings[i].alias == key)
689 default_keybindings[i].request = REQ_NONE;
690 }
691 }
693 /* Looks for a key binding first in the given map, then in the generic map, and
694 * lastly in the default keybindings. */
695 static enum request
696 get_keybinding(enum keymap keymap, int key)
697 {
698 size_t i;
700 for (i = 0; i < keybindings[keymap].size; i++)
701 if (keybindings[keymap].data[i].alias == key)
702 return keybindings[keymap].data[i].request;
704 for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
705 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
706 return keybindings[KEYMAP_GENERIC].data[i].request;
708 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
709 if (default_keybindings[i].alias == key)
710 return default_keybindings[i].request;
712 return (enum request) key;
713 }
716 struct key {
717 const char *name;
718 int value;
719 };
721 static const struct key key_table[] = {
722 { "Enter", KEY_RETURN },
723 { "Space", ' ' },
724 { "Backspace", KEY_BACKSPACE },
725 { "Tab", KEY_TAB },
726 { "Escape", KEY_ESC },
727 { "Left", KEY_LEFT },
728 { "Right", KEY_RIGHT },
729 { "Up", KEY_UP },
730 { "Down", KEY_DOWN },
731 { "Insert", KEY_IC },
732 { "Delete", KEY_DC },
733 { "Hash", '#' },
734 { "Home", KEY_HOME },
735 { "End", KEY_END },
736 { "PageUp", KEY_PPAGE },
737 { "PageDown", KEY_NPAGE },
738 { "F1", KEY_F(1) },
739 { "F2", KEY_F(2) },
740 { "F3", KEY_F(3) },
741 { "F4", KEY_F(4) },
742 { "F5", KEY_F(5) },
743 { "F6", KEY_F(6) },
744 { "F7", KEY_F(7) },
745 { "F8", KEY_F(8) },
746 { "F9", KEY_F(9) },
747 { "F10", KEY_F(10) },
748 { "F11", KEY_F(11) },
749 { "F12", KEY_F(12) },
750 };
752 static int
753 get_key_value(const char *name)
754 {
755 int i;
757 for (i = 0; i < ARRAY_SIZE(key_table); i++)
758 if (!strcasecmp(key_table[i].name, name))
759 return key_table[i].value;
761 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
762 return (int)name[1] & 0x1f;
763 if (strlen(name) == 1 && isprint(*name))
764 return (int) *name;
765 return ERR;
766 }
768 static const char *
769 get_key_name(int key_value)
770 {
771 static char key_char[] = "'X'\0";
772 const char *seq = NULL;
773 int key;
775 for (key = 0; key < ARRAY_SIZE(key_table); key++)
776 if (key_table[key].value == key_value)
777 seq = key_table[key].name;
779 if (seq == NULL && key_value < 0x7f) {
780 char *s = key_char + 1;
782 if (key_value >= 0x20) {
783 *s++ = key_value;
784 } else {
785 *s++ = '^';
786 *s++ = 0x40 | (key_value & 0x1f);
787 }
788 *s++ = '\'';
789 *s++ = '\0';
790 seq = key_char;
791 }
793 return seq ? seq : "(no key)";
794 }
796 static bool
797 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
798 {
799 const char *sep = *pos > 0 ? ", " : "";
800 const char *keyname = get_key_name(keybinding->alias);
802 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
803 }
805 static bool
806 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
807 enum keymap keymap, bool all)
808 {
809 int i;
811 for (i = 0; i < keybindings[keymap].size; i++) {
812 if (keybindings[keymap].data[i].request == request) {
813 if (!append_key(buf, pos, &keybindings[keymap].data[i]))
814 return FALSE;
815 if (!all)
816 break;
817 }
818 }
820 return TRUE;
821 }
823 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
825 static const char *
826 get_keys(enum keymap keymap, enum request request, bool all)
827 {
828 static char buf[BUFSIZ];
829 size_t pos = 0;
830 int i;
832 buf[pos] = 0;
834 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
835 return "Too many keybindings!";
836 if (pos > 0 && !all)
837 return buf;
839 if (keymap != KEYMAP_GENERIC) {
840 /* Only the generic keymap includes the default keybindings when
841 * listing all keys. */
842 if (all)
843 return buf;
845 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
846 return "Too many keybindings!";
847 if (pos)
848 return buf;
849 }
851 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
852 if (default_keybindings[i].request == request) {
853 if (!append_key(buf, &pos, &default_keybindings[i]))
854 return "Too many keybindings!";
855 if (!all)
856 return buf;
857 }
858 }
860 return buf;
861 }
863 struct run_request {
864 enum keymap keymap;
865 int key;
866 const char **argv;
867 };
869 static struct run_request *run_request;
870 static size_t run_requests;
872 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
874 static enum request
875 add_run_request(enum keymap keymap, int key, const char **argv)
876 {
877 struct run_request *req;
879 if (!realloc_run_requests(&run_request, run_requests, 1))
880 return REQ_NONE;
882 req = &run_request[run_requests];
883 req->keymap = keymap;
884 req->key = key;
885 req->argv = NULL;
887 if (!argv_copy(&req->argv, argv))
888 return REQ_NONE;
890 return REQ_NONE + ++run_requests;
891 }
893 static struct run_request *
894 get_run_request(enum request request)
895 {
896 if (request <= REQ_NONE)
897 return NULL;
898 return &run_request[request - REQ_NONE - 1];
899 }
901 static void
902 add_builtin_run_requests(void)
903 {
904 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
905 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
906 const char *commit[] = { "git", "commit", NULL };
907 const char *gc[] = { "git", "gc", NULL };
908 struct run_request reqs[] = {
909 { KEYMAP_MAIN, 'C', cherry_pick },
910 { KEYMAP_STATUS, 'C', commit },
911 { KEYMAP_BRANCH, 'C', checkout },
912 { KEYMAP_GENERIC, 'G', gc },
913 };
914 int i;
916 for (i = 0; i < ARRAY_SIZE(reqs); i++) {
917 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
919 if (req != reqs[i].key)
920 continue;
921 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
922 if (req != REQ_NONE)
923 add_keybinding(reqs[i].keymap, req, reqs[i].key);
924 }
925 }
927 /*
928 * User config file handling.
929 */
931 #define OPT_ERR_INFO \
932 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
933 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
934 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
935 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
936 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
937 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
938 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
939 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
940 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
941 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
942 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
943 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
944 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
945 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
946 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
947 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
948 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
950 enum option_code {
951 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
952 OPT_ERR_INFO
953 #undef OPT_ERR_
954 OPT_OK
955 };
957 static const char *option_errors[] = {
958 #define OPT_ERR_(name, msg) msg
959 OPT_ERR_INFO
960 #undef OPT_ERR_
961 };
963 static const struct enum_map color_map[] = {
964 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
965 COLOR_MAP(DEFAULT),
966 COLOR_MAP(BLACK),
967 COLOR_MAP(BLUE),
968 COLOR_MAP(CYAN),
969 COLOR_MAP(GREEN),
970 COLOR_MAP(MAGENTA),
971 COLOR_MAP(RED),
972 COLOR_MAP(WHITE),
973 COLOR_MAP(YELLOW),
974 };
976 static const struct enum_map attr_map[] = {
977 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
978 ATTR_MAP(NORMAL),
979 ATTR_MAP(BLINK),
980 ATTR_MAP(BOLD),
981 ATTR_MAP(DIM),
982 ATTR_MAP(REVERSE),
983 ATTR_MAP(STANDOUT),
984 ATTR_MAP(UNDERLINE),
985 };
987 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
989 static enum option_code
990 parse_step(double *opt, const char *arg)
991 {
992 *opt = atoi(arg);
993 if (!strchr(arg, '%'))
994 return OPT_OK;
996 /* "Shift down" so 100% and 1 does not conflict. */
997 *opt = (*opt - 1) / 100;
998 if (*opt >= 1.0) {
999 *opt = 0.99;
1000 return OPT_ERR_INVALID_STEP_VALUE;
1001 }
1002 if (*opt < 0.0) {
1003 *opt = 1;
1004 return OPT_ERR_INVALID_STEP_VALUE;
1005 }
1006 return OPT_OK;
1007 }
1009 static enum option_code
1010 parse_int(int *opt, const char *arg, int min, int max)
1011 {
1012 int value = atoi(arg);
1014 if (min <= value && value <= max) {
1015 *opt = value;
1016 return OPT_OK;
1017 }
1019 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1020 }
1022 static bool
1023 set_color(int *color, const char *name)
1024 {
1025 if (map_enum(color, color_map, name))
1026 return TRUE;
1027 if (!prefixcmp(name, "color"))
1028 return parse_int(color, name + 5, 0, 255) == OK;
1029 return FALSE;
1030 }
1032 /* Wants: object fgcolor bgcolor [attribute] */
1033 static enum option_code
1034 option_color_command(int argc, const char *argv[])
1035 {
1036 struct line_info *info;
1038 if (argc < 3)
1039 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1041 info = get_line_info(argv[0]);
1042 if (!info) {
1043 static const struct enum_map obsolete[] = {
1044 ENUM_MAP("main-delim", LINE_DELIMITER),
1045 ENUM_MAP("main-date", LINE_DATE),
1046 ENUM_MAP("main-author", LINE_AUTHOR),
1047 };
1048 int index;
1050 if (!map_enum(&index, obsolete, argv[0]))
1051 return OPT_ERR_UNKNOWN_COLOR_NAME;
1052 info = &line_info[index];
1053 }
1055 if (!set_color(&info->fg, argv[1]) ||
1056 !set_color(&info->bg, argv[2]))
1057 return OPT_ERR_UNKNOWN_COLOR;
1059 info->attr = 0;
1060 while (argc-- > 3) {
1061 int attr;
1063 if (!set_attribute(&attr, argv[argc]))
1064 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1065 info->attr |= attr;
1066 }
1068 return OPT_OK;
1069 }
1071 static enum option_code
1072 parse_bool(bool *opt, const char *arg)
1073 {
1074 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1075 ? TRUE : FALSE;
1076 return OPT_OK;
1077 }
1079 static enum option_code
1080 parse_enum_do(unsigned int *opt, const char *arg,
1081 const struct enum_map *map, size_t map_size)
1082 {
1083 bool is_true;
1085 assert(map_size > 1);
1087 if (map_enum_do(map, map_size, (int *) opt, arg))
1088 return OPT_OK;
1090 parse_bool(&is_true, arg);
1091 *opt = is_true ? map[1].value : map[0].value;
1092 return OPT_OK;
1093 }
1095 #define parse_enum(opt, arg, map) \
1096 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1098 static enum option_code
1099 parse_string(char *opt, const char *arg, size_t optsize)
1100 {
1101 int arglen = strlen(arg);
1103 switch (arg[0]) {
1104 case '\"':
1105 case '\'':
1106 if (arglen == 1 || arg[arglen - 1] != arg[0])
1107 return OPT_ERR_UNMATCHED_QUOTATION;
1108 arg += 1; arglen -= 2;
1109 default:
1110 string_ncopy_do(opt, optsize, arg, arglen);
1111 return OPT_OK;
1112 }
1113 }
1115 static enum option_code
1116 parse_args(const char ***args, const char *argv[])
1117 {
1118 if (*args == NULL && !argv_copy(args, argv))
1119 return OPT_ERR_OUT_OF_MEMORY;
1120 return OPT_OK;
1121 }
1123 /* Wants: name = value */
1124 static enum option_code
1125 option_set_command(int argc, const char *argv[])
1126 {
1127 if (argc < 3)
1128 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1130 if (strcmp(argv[1], "="))
1131 return OPT_ERR_NO_VALUE_ASSIGNED;
1133 if (!strcmp(argv[0], "blame-options"))
1134 return parse_args(&opt_blame_argv, argv + 2);
1136 if (argc != 3)
1137 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1139 if (!strcmp(argv[0], "show-author"))
1140 return parse_enum(&opt_author, argv[2], author_map);
1142 if (!strcmp(argv[0], "show-date"))
1143 return parse_enum(&opt_date, argv[2], date_map);
1145 if (!strcmp(argv[0], "show-rev-graph"))
1146 return parse_bool(&opt_rev_graph, argv[2]);
1148 if (!strcmp(argv[0], "show-refs"))
1149 return parse_bool(&opt_show_refs, argv[2]);
1151 if (!strcmp(argv[0], "show-line-numbers"))
1152 return parse_bool(&opt_line_number, argv[2]);
1154 if (!strcmp(argv[0], "line-graphics"))
1155 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1157 if (!strcmp(argv[0], "line-number-interval"))
1158 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1160 if (!strcmp(argv[0], "author-width"))
1161 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1163 if (!strcmp(argv[0], "horizontal-scroll"))
1164 return parse_step(&opt_hscroll, argv[2]);
1166 if (!strcmp(argv[0], "split-view-height"))
1167 return parse_step(&opt_scale_split_view, argv[2]);
1169 if (!strcmp(argv[0], "tab-size"))
1170 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1172 if (!strcmp(argv[0], "commit-encoding"))
1173 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1175 if (!strcmp(argv[0], "status-untracked-dirs"))
1176 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1178 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1179 }
1181 /* Wants: mode request key */
1182 static enum option_code
1183 option_bind_command(int argc, const char *argv[])
1184 {
1185 enum request request;
1186 int keymap = -1;
1187 int key;
1189 if (argc < 3)
1190 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1192 if (!set_keymap(&keymap, argv[0]))
1193 return OPT_ERR_UNKNOWN_KEY_MAP;
1195 key = get_key_value(argv[1]);
1196 if (key == ERR)
1197 return OPT_ERR_UNKNOWN_KEY;
1199 request = get_request(argv[2]);
1200 if (request == REQ_UNKNOWN) {
1201 static const struct enum_map obsolete[] = {
1202 ENUM_MAP("cherry-pick", REQ_NONE),
1203 ENUM_MAP("screen-resize", REQ_NONE),
1204 ENUM_MAP("tree-parent", REQ_PARENT),
1205 };
1206 int alias;
1208 if (map_enum(&alias, obsolete, argv[2])) {
1209 if (alias != REQ_NONE)
1210 add_keybinding(keymap, alias, key);
1211 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1212 }
1213 }
1214 if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1215 request = add_run_request(keymap, key, argv + 2);
1216 if (request == REQ_UNKNOWN)
1217 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1219 add_keybinding(keymap, request, key);
1221 return OPT_OK;
1222 }
1224 static enum option_code
1225 set_option(const char *opt, char *value)
1226 {
1227 const char *argv[SIZEOF_ARG];
1228 int argc = 0;
1230 if (!argv_from_string(argv, &argc, value))
1231 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1233 if (!strcmp(opt, "color"))
1234 return option_color_command(argc, argv);
1236 if (!strcmp(opt, "set"))
1237 return option_set_command(argc, argv);
1239 if (!strcmp(opt, "bind"))
1240 return option_bind_command(argc, argv);
1242 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1243 }
1245 struct config_state {
1246 int lineno;
1247 bool errors;
1248 };
1250 static int
1251 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1252 {
1253 struct config_state *config = data;
1254 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1256 config->lineno++;
1258 /* Check for comment markers, since read_properties() will
1259 * only ensure opt and value are split at first " \t". */
1260 optlen = strcspn(opt, "#");
1261 if (optlen == 0)
1262 return OK;
1264 if (opt[optlen] == 0) {
1265 /* Look for comment endings in the value. */
1266 size_t len = strcspn(value, "#");
1268 if (len < valuelen) {
1269 valuelen = len;
1270 value[valuelen] = 0;
1271 }
1273 status = set_option(opt, value);
1274 }
1276 if (status != OPT_OK) {
1277 warn("Error on line %d, near '%.*s': %s",
1278 config->lineno, (int) optlen, opt, option_errors[status]);
1279 config->errors = TRUE;
1280 }
1282 /* Always keep going if errors are encountered. */
1283 return OK;
1284 }
1286 static void
1287 load_option_file(const char *path)
1288 {
1289 struct config_state config = { 0, FALSE };
1290 struct io io;
1292 /* It's OK that the file doesn't exist. */
1293 if (!io_open(&io, "%s", path))
1294 return;
1296 if (io_load(&io, " \t", read_option, &config) == ERR ||
1297 config.errors == TRUE)
1298 warn("Errors while loading %s.", path);
1299 }
1301 static int
1302 load_options(void)
1303 {
1304 const char *home = getenv("HOME");
1305 const char *tigrc_user = getenv("TIGRC_USER");
1306 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1307 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1308 char buf[SIZEOF_STR];
1310 if (!tigrc_system)
1311 tigrc_system = SYSCONFDIR "/tigrc";
1312 load_option_file(tigrc_system);
1314 if (!tigrc_user) {
1315 if (!home || !string_format(buf, "%s/.tigrc", home))
1316 return ERR;
1317 tigrc_user = buf;
1318 }
1319 load_option_file(tigrc_user);
1321 /* Add _after_ loading config files to avoid adding run requests
1322 * that conflict with keybindings. */
1323 add_builtin_run_requests();
1325 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1326 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1327 int argc = 0;
1329 if (!string_format(buf, "%s", tig_diff_opts) ||
1330 !argv_from_string(diff_opts, &argc, buf))
1331 die("TIG_DIFF_OPTS contains too many arguments");
1332 else if (!argv_copy(&opt_diff_argv, diff_opts))
1333 die("Failed to format TIG_DIFF_OPTS arguments");
1334 }
1336 return OK;
1337 }
1340 /*
1341 * The viewer
1342 */
1344 struct view;
1345 struct view_ops;
1347 /* The display array of active views and the index of the current view. */
1348 static struct view *display[2];
1349 static WINDOW *display_win[2];
1350 static WINDOW *display_title[2];
1351 static unsigned int current_view;
1353 #define foreach_displayed_view(view, i) \
1354 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1356 #define displayed_views() (display[1] != NULL ? 2 : 1)
1358 /* Current head and commit ID */
1359 static char ref_blob[SIZEOF_REF] = "";
1360 static char ref_commit[SIZEOF_REF] = "HEAD";
1361 static char ref_head[SIZEOF_REF] = "HEAD";
1362 static char ref_branch[SIZEOF_REF] = "";
1364 enum view_type {
1365 VIEW_MAIN,
1366 VIEW_DIFF,
1367 VIEW_LOG,
1368 VIEW_TREE,
1369 VIEW_BLOB,
1370 VIEW_BLAME,
1371 VIEW_BRANCH,
1372 VIEW_HELP,
1373 VIEW_PAGER,
1374 VIEW_STATUS,
1375 VIEW_STAGE,
1376 };
1378 struct view {
1379 enum view_type type; /* View type */
1380 const char *name; /* View name */
1381 const char *id; /* Points to either of ref_{head,commit,blob} */
1383 struct view_ops *ops; /* View operations */
1385 enum keymap keymap; /* What keymap does this view have */
1386 bool git_dir; /* Whether the view requires a git directory. */
1388 char ref[SIZEOF_REF]; /* Hovered commit reference */
1389 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1391 int height, width; /* The width and height of the main window */
1392 WINDOW *win; /* The main window */
1394 /* Navigation */
1395 unsigned long offset; /* Offset of the window top */
1396 unsigned long yoffset; /* Offset from the window side. */
1397 unsigned long lineno; /* Current line number */
1398 unsigned long p_offset; /* Previous offset of the window top */
1399 unsigned long p_yoffset;/* Previous offset from the window side */
1400 unsigned long p_lineno; /* Previous current line number */
1401 bool p_restore; /* Should the previous position be restored. */
1403 /* Searching */
1404 char grep[SIZEOF_STR]; /* Search string */
1405 regex_t *regex; /* Pre-compiled regexp */
1407 /* If non-NULL, points to the view that opened this view. If this view
1408 * is closed tig will switch back to the parent view. */
1409 struct view *parent;
1410 struct view *prev;
1412 /* Buffering */
1413 size_t lines; /* Total number of lines */
1414 struct line *line; /* Line index */
1415 unsigned int digits; /* Number of digits in the lines member. */
1417 /* Drawing */
1418 struct line *curline; /* Line currently being drawn. */
1419 enum line_type curtype; /* Attribute currently used for drawing. */
1420 unsigned long col; /* Column when drawing. */
1421 bool has_scrolled; /* View was scrolled. */
1423 /* Loading */
1424 const char **argv; /* Shell command arguments. */
1425 const char *dir; /* Directory from which to execute. */
1426 struct io io;
1427 struct io *pipe;
1428 time_t start_time;
1429 time_t update_secs;
1430 };
1432 struct view_ops {
1433 /* What type of content being displayed. Used in the title bar. */
1434 const char *type;
1435 /* Default command arguments. */
1436 const char **argv;
1437 /* Open and reads in all view content. */
1438 bool (*open)(struct view *view);
1439 /* Read one line; updates view->line. */
1440 bool (*read)(struct view *view, char *data);
1441 /* Draw one line; @lineno must be < view->height. */
1442 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1443 /* Depending on view handle a special requests. */
1444 enum request (*request)(struct view *view, enum request request, struct line *line);
1445 /* Search for regexp in a line. */
1446 bool (*grep)(struct view *view, struct line *line);
1447 /* Select line */
1448 void (*select)(struct view *view, struct line *line);
1449 /* Prepare view for loading */
1450 bool (*prepare)(struct view *view);
1451 };
1453 static struct view_ops blame_ops;
1454 static struct view_ops blob_ops;
1455 static struct view_ops diff_ops;
1456 static struct view_ops help_ops;
1457 static struct view_ops log_ops;
1458 static struct view_ops main_ops;
1459 static struct view_ops pager_ops;
1460 static struct view_ops stage_ops;
1461 static struct view_ops status_ops;
1462 static struct view_ops tree_ops;
1463 static struct view_ops branch_ops;
1465 #define VIEW_STR(type, name, ref, ops, map, git) \
1466 { type, name, ref, ops, map, git }
1468 #define VIEW_(id, name, ops, git, ref) \
1469 VIEW_STR(VIEW_##id, name, ref, ops, KEYMAP_##id, git)
1471 static struct view views[] = {
1472 VIEW_(MAIN, "main", &main_ops, TRUE, ref_head),
1473 VIEW_(DIFF, "diff", &diff_ops, TRUE, ref_commit),
1474 VIEW_(LOG, "log", &log_ops, TRUE, ref_head),
1475 VIEW_(TREE, "tree", &tree_ops, TRUE, ref_commit),
1476 VIEW_(BLOB, "blob", &blob_ops, TRUE, ref_blob),
1477 VIEW_(BLAME, "blame", &blame_ops, TRUE, ref_commit),
1478 VIEW_(BRANCH, "branch", &branch_ops, TRUE, ref_head),
1479 VIEW_(HELP, "help", &help_ops, FALSE, ""),
1480 VIEW_(PAGER, "pager", &pager_ops, FALSE, ""),
1481 VIEW_(STATUS, "status", &status_ops, TRUE, ""),
1482 VIEW_(STAGE, "stage", &stage_ops, TRUE, ""),
1483 };
1485 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1487 #define foreach_view(view, i) \
1488 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1490 #define view_is_displayed(view) \
1491 (view == display[0] || view == display[1])
1493 static enum request
1494 view_request(struct view *view, enum request request)
1495 {
1496 if (!view || !view->lines)
1497 return request;
1498 return view->ops->request(view, request, &view->line[view->lineno]);
1499 }
1502 /*
1503 * View drawing.
1504 */
1506 static inline void
1507 set_view_attr(struct view *view, enum line_type type)
1508 {
1509 if (!view->curline->selected && view->curtype != type) {
1510 (void) wattrset(view->win, get_line_attr(type));
1511 wchgat(view->win, -1, 0, type, NULL);
1512 view->curtype = type;
1513 }
1514 }
1516 static int
1517 draw_chars(struct view *view, enum line_type type, const char *string,
1518 int max_len, bool use_tilde)
1519 {
1520 static char out_buffer[BUFSIZ * 2];
1521 int len = 0;
1522 int col = 0;
1523 int trimmed = FALSE;
1524 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1526 if (max_len <= 0)
1527 return 0;
1529 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1531 set_view_attr(view, type);
1532 if (len > 0) {
1533 if (opt_iconv_out != ICONV_NONE) {
1534 ICONV_CONST char *inbuf = (ICONV_CONST char *) string;
1535 size_t inlen = len + 1;
1537 char *outbuf = out_buffer;
1538 size_t outlen = sizeof(out_buffer);
1540 size_t ret;
1542 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1543 if (ret != (size_t) -1) {
1544 string = out_buffer;
1545 len = sizeof(out_buffer) - outlen;
1546 }
1547 }
1549 waddnstr(view->win, string, len);
1551 if (trimmed && use_tilde) {
1552 set_view_attr(view, LINE_DELIMITER);
1553 waddch(view->win, '~');
1554 col++;
1555 }
1556 }
1558 return col;
1559 }
1561 static int
1562 draw_space(struct view *view, enum line_type type, int max, int spaces)
1563 {
1564 static char space[] = " ";
1565 int col = 0;
1567 spaces = MIN(max, spaces);
1569 while (spaces > 0) {
1570 int len = MIN(spaces, sizeof(space) - 1);
1572 col += draw_chars(view, type, space, len, FALSE);
1573 spaces -= len;
1574 }
1576 return col;
1577 }
1579 static bool
1580 draw_text(struct view *view, enum line_type type, const char *string)
1581 {
1582 char text[SIZEOF_STR];
1584 do {
1585 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1587 view->col += draw_chars(view, type, text, view->width + view->yoffset - view->col, TRUE);
1588 string += pos;
1589 } while (*string && view->width + view->yoffset > view->col);
1591 return view->width + view->yoffset <= view->col;
1592 }
1594 static bool
1595 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1596 {
1597 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1598 int max = view->width + view->yoffset - view->col;
1599 int i;
1601 if (max < size)
1602 size = max;
1604 set_view_attr(view, type);
1605 /* Using waddch() instead of waddnstr() ensures that
1606 * they'll be rendered correctly for the cursor line. */
1607 for (i = skip; i < size; i++)
1608 waddch(view->win, graphic[i]);
1610 view->col += size;
1611 if (separator) {
1612 if (size < max && skip <= size)
1613 waddch(view->win, ' ');
1614 view->col++;
1615 }
1617 return view->width + view->yoffset <= view->col;
1618 }
1620 static bool
1621 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1622 {
1623 int max = MIN(view->width + view->yoffset - view->col, len);
1624 int col;
1626 if (text)
1627 col = draw_chars(view, type, text, max - 1, trim);
1628 else
1629 col = draw_space(view, type, max - 1, max - 1);
1631 view->col += col;
1632 view->col += draw_space(view, LINE_DEFAULT, max - col, max - col);
1633 return view->width + view->yoffset <= view->col;
1634 }
1636 static bool
1637 draw_date(struct view *view, struct time *time)
1638 {
1639 const char *date = mkdate(time, opt_date);
1640 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1642 return draw_field(view, LINE_DATE, date, cols, FALSE);
1643 }
1645 static bool
1646 draw_author(struct view *view, const char *author)
1647 {
1648 bool trim = opt_author_cols == 0 || opt_author_cols > 5;
1649 bool abbreviate = opt_author == AUTHOR_ABBREVIATED || !trim;
1651 if (abbreviate && author)
1652 author = get_author_initials(author);
1654 return draw_field(view, LINE_AUTHOR, author, opt_author_cols, trim);
1655 }
1657 static bool
1658 draw_mode(struct view *view, mode_t mode)
1659 {
1660 const char *str;
1662 if (S_ISDIR(mode))
1663 str = "drwxr-xr-x";
1664 else if (S_ISLNK(mode))
1665 str = "lrwxrwxrwx";
1666 else if (S_ISGITLINK(mode))
1667 str = "m---------";
1668 else if (S_ISREG(mode) && mode & S_IXUSR)
1669 str = "-rwxr-xr-x";
1670 else if (S_ISREG(mode))
1671 str = "-rw-r--r--";
1672 else
1673 str = "----------";
1675 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1676 }
1678 static bool
1679 draw_lineno(struct view *view, unsigned int lineno)
1680 {
1681 char number[10];
1682 int digits3 = view->digits < 3 ? 3 : view->digits;
1683 int max = MIN(view->width + view->yoffset - view->col, digits3);
1684 char *text = NULL;
1685 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1687 lineno += view->offset + 1;
1688 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1689 static char fmt[] = "%1ld";
1691 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1692 if (string_format(number, fmt, lineno))
1693 text = number;
1694 }
1695 if (text)
1696 view->col += draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1697 else
1698 view->col += draw_space(view, LINE_LINE_NUMBER, max, digits3);
1699 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1700 }
1702 static bool
1703 draw_view_line(struct view *view, unsigned int lineno)
1704 {
1705 struct line *line;
1706 bool selected = (view->offset + lineno == view->lineno);
1708 assert(view_is_displayed(view));
1710 if (view->offset + lineno >= view->lines)
1711 return FALSE;
1713 line = &view->line[view->offset + lineno];
1715 wmove(view->win, lineno, 0);
1716 if (line->cleareol)
1717 wclrtoeol(view->win);
1718 view->col = 0;
1719 view->curline = line;
1720 view->curtype = LINE_NONE;
1721 line->selected = FALSE;
1722 line->dirty = line->cleareol = 0;
1724 if (selected) {
1725 set_view_attr(view, LINE_CURSOR);
1726 line->selected = TRUE;
1727 view->ops->select(view, line);
1728 }
1730 return view->ops->draw(view, line, lineno);
1731 }
1733 static void
1734 redraw_view_dirty(struct view *view)
1735 {
1736 bool dirty = FALSE;
1737 int lineno;
1739 for (lineno = 0; lineno < view->height; lineno++) {
1740 if (view->offset + lineno >= view->lines)
1741 break;
1742 if (!view->line[view->offset + lineno].dirty)
1743 continue;
1744 dirty = TRUE;
1745 if (!draw_view_line(view, lineno))
1746 break;
1747 }
1749 if (!dirty)
1750 return;
1751 wnoutrefresh(view->win);
1752 }
1754 static void
1755 redraw_view_from(struct view *view, int lineno)
1756 {
1757 assert(0 <= lineno && lineno < view->height);
1759 for (; lineno < view->height; lineno++) {
1760 if (!draw_view_line(view, lineno))
1761 break;
1762 }
1764 wnoutrefresh(view->win);
1765 }
1767 static void
1768 redraw_view(struct view *view)
1769 {
1770 werase(view->win);
1771 redraw_view_from(view, 0);
1772 }
1775 static void
1776 update_view_title(struct view *view)
1777 {
1778 char buf[SIZEOF_STR];
1779 char state[SIZEOF_STR];
1780 size_t bufpos = 0, statelen = 0;
1781 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1783 assert(view_is_displayed(view));
1785 if (view->type != VIEW_STATUS && view->lines) {
1786 unsigned int view_lines = view->offset + view->height;
1787 unsigned int lines = view->lines
1788 ? MIN(view_lines, view->lines) * 100 / view->lines
1789 : 0;
1791 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
1792 view->ops->type,
1793 view->lineno + 1,
1794 view->lines,
1795 lines);
1797 }
1799 if (view->pipe) {
1800 time_t secs = time(NULL) - view->start_time;
1802 /* Three git seconds are a long time ... */
1803 if (secs > 2)
1804 string_format_from(state, &statelen, " loading %lds", secs);
1805 }
1807 string_format_from(buf, &bufpos, "[%s]", view->name);
1808 if (*view->ref && bufpos < view->width) {
1809 size_t refsize = strlen(view->ref);
1810 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
1812 if (minsize < view->width)
1813 refsize = view->width - minsize + 7;
1814 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
1815 }
1817 if (statelen && bufpos < view->width) {
1818 string_format_from(buf, &bufpos, "%s", state);
1819 }
1821 if (view == display[current_view])
1822 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
1823 else
1824 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
1826 mvwaddnstr(window, 0, 0, buf, bufpos);
1827 wclrtoeol(window);
1828 wnoutrefresh(window);
1829 }
1831 static int
1832 apply_step(double step, int value)
1833 {
1834 if (step >= 1)
1835 return (int) step;
1836 value *= step + 0.01;
1837 return value ? value : 1;
1838 }
1840 static void
1841 resize_display(void)
1842 {
1843 int offset, i;
1844 struct view *base = display[0];
1845 struct view *view = display[1] ? display[1] : display[0];
1847 /* Setup window dimensions */
1849 getmaxyx(stdscr, base->height, base->width);
1851 /* Make room for the status window. */
1852 base->height -= 1;
1854 if (view != base) {
1855 /* Horizontal split. */
1856 view->width = base->width;
1857 view->height = apply_step(opt_scale_split_view, base->height);
1858 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
1859 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
1860 base->height -= view->height;
1862 /* Make room for the title bar. */
1863 view->height -= 1;
1864 }
1866 /* Make room for the title bar. */
1867 base->height -= 1;
1869 offset = 0;
1871 foreach_displayed_view (view, i) {
1872 if (!display_win[i]) {
1873 display_win[i] = newwin(view->height, view->width, offset, 0);
1874 if (!display_win[i])
1875 die("Failed to create %s view", view->name);
1877 scrollok(display_win[i], FALSE);
1879 display_title[i] = newwin(1, view->width, offset + view->height, 0);
1880 if (!display_title[i])
1881 die("Failed to create title window");
1883 } else {
1884 wresize(display_win[i], view->height, view->width);
1885 mvwin(display_win[i], offset, 0);
1886 mvwin(display_title[i], offset + view->height, 0);
1887 }
1889 view->win = display_win[i];
1891 offset += view->height + 1;
1892 }
1893 }
1895 static void
1896 redraw_display(bool clear)
1897 {
1898 struct view *view;
1899 int i;
1901 foreach_displayed_view (view, i) {
1902 if (clear)
1903 wclear(view->win);
1904 redraw_view(view);
1905 update_view_title(view);
1906 }
1907 }
1910 /*
1911 * Option management
1912 */
1914 #define TOGGLE_MENU \
1915 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
1916 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
1917 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
1918 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
1919 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
1920 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL)
1922 static void
1923 toggle_option(enum request request)
1924 {
1925 const struct {
1926 enum request request;
1927 const struct enum_map *map;
1928 size_t map_size;
1929 } data[] = {
1930 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
1931 TOGGLE_MENU
1932 #undef TOGGLE_
1933 };
1934 const struct menu_item menu[] = {
1935 #define TOGGLE_(id, key, help, value, map) { key, help, value },
1936 TOGGLE_MENU
1937 #undef TOGGLE_
1938 { 0 }
1939 };
1940 int i = 0;
1942 if (request == REQ_OPTIONS) {
1943 if (!prompt_menu("Toggle option", menu, &i))
1944 return;
1945 } else {
1946 while (i < ARRAY_SIZE(data) && data[i].request != request)
1947 i++;
1948 if (i >= ARRAY_SIZE(data))
1949 die("Invalid request (%d)", request);
1950 }
1952 if (data[i].map != NULL) {
1953 unsigned int *opt = menu[i].data;
1955 *opt = (*opt + 1) % data[i].map_size;
1956 redraw_display(FALSE);
1957 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
1959 } else {
1960 bool *option = menu[i].data;
1962 *option = !*option;
1963 redraw_display(FALSE);
1964 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
1965 }
1966 }
1968 static void
1969 maximize_view(struct view *view)
1970 {
1971 memset(display, 0, sizeof(display));
1972 current_view = 0;
1973 display[current_view] = view;
1974 resize_display();
1975 redraw_display(FALSE);
1976 report("");
1977 }
1980 /*
1981 * Navigation
1982 */
1984 static bool
1985 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
1986 {
1987 if (lineno >= view->lines)
1988 lineno = view->lines > 0 ? view->lines - 1 : 0;
1990 if (offset > lineno || offset + view->height <= lineno) {
1991 unsigned long half = view->height / 2;
1993 if (lineno > half)
1994 offset = lineno - half;
1995 else
1996 offset = 0;
1997 }
1999 if (offset != view->offset || lineno != view->lineno) {
2000 view->offset = offset;
2001 view->lineno = lineno;
2002 return TRUE;
2003 }
2005 return FALSE;
2006 }
2008 /* Scrolling backend */
2009 static void
2010 do_scroll_view(struct view *view, int lines)
2011 {
2012 bool redraw_current_line = FALSE;
2014 /* The rendering expects the new offset. */
2015 view->offset += lines;
2017 assert(0 <= view->offset && view->offset < view->lines);
2018 assert(lines);
2020 /* Move current line into the view. */
2021 if (view->lineno < view->offset) {
2022 view->lineno = view->offset;
2023 redraw_current_line = TRUE;
2024 } else if (view->lineno >= view->offset + view->height) {
2025 view->lineno = view->offset + view->height - 1;
2026 redraw_current_line = TRUE;
2027 }
2029 assert(view->offset <= view->lineno && view->lineno < view->lines);
2031 /* Redraw the whole screen if scrolling is pointless. */
2032 if (view->height < ABS(lines)) {
2033 redraw_view(view);
2035 } else {
2036 int line = lines > 0 ? view->height - lines : 0;
2037 int end = line + ABS(lines);
2039 scrollok(view->win, TRUE);
2040 wscrl(view->win, lines);
2041 scrollok(view->win, FALSE);
2043 while (line < end && draw_view_line(view, line))
2044 line++;
2046 if (redraw_current_line)
2047 draw_view_line(view, view->lineno - view->offset);
2048 wnoutrefresh(view->win);
2049 }
2051 view->has_scrolled = TRUE;
2052 report("");
2053 }
2055 /* Scroll frontend */
2056 static void
2057 scroll_view(struct view *view, enum request request)
2058 {
2059 int lines = 1;
2061 assert(view_is_displayed(view));
2063 switch (request) {
2064 case REQ_SCROLL_FIRST_COL:
2065 view->yoffset = 0;
2066 redraw_view_from(view, 0);
2067 report("");
2068 return;
2069 case REQ_SCROLL_LEFT:
2070 if (view->yoffset == 0) {
2071 report("Cannot scroll beyond the first column");
2072 return;
2073 }
2074 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2075 view->yoffset = 0;
2076 else
2077 view->yoffset -= apply_step(opt_hscroll, view->width);
2078 redraw_view_from(view, 0);
2079 report("");
2080 return;
2081 case REQ_SCROLL_RIGHT:
2082 view->yoffset += apply_step(opt_hscroll, view->width);
2083 redraw_view(view);
2084 report("");
2085 return;
2086 case REQ_SCROLL_PAGE_DOWN:
2087 lines = view->height;
2088 case REQ_SCROLL_LINE_DOWN:
2089 if (view->offset + lines > view->lines)
2090 lines = view->lines - view->offset;
2092 if (lines == 0 || view->offset + view->height >= view->lines) {
2093 report("Cannot scroll beyond the last line");
2094 return;
2095 }
2096 break;
2098 case REQ_SCROLL_PAGE_UP:
2099 lines = view->height;
2100 case REQ_SCROLL_LINE_UP:
2101 if (lines > view->offset)
2102 lines = view->offset;
2104 if (lines == 0) {
2105 report("Cannot scroll beyond the first line");
2106 return;
2107 }
2109 lines = -lines;
2110 break;
2112 default:
2113 die("request %d not handled in switch", request);
2114 }
2116 do_scroll_view(view, lines);
2117 }
2119 /* Cursor moving */
2120 static void
2121 move_view(struct view *view, enum request request)
2122 {
2123 int scroll_steps = 0;
2124 int steps;
2126 switch (request) {
2127 case REQ_MOVE_FIRST_LINE:
2128 steps = -view->lineno;
2129 break;
2131 case REQ_MOVE_LAST_LINE:
2132 steps = view->lines - view->lineno - 1;
2133 break;
2135 case REQ_MOVE_PAGE_UP:
2136 steps = view->height > view->lineno
2137 ? -view->lineno : -view->height;
2138 break;
2140 case REQ_MOVE_PAGE_DOWN:
2141 steps = view->lineno + view->height >= view->lines
2142 ? view->lines - view->lineno - 1 : view->height;
2143 break;
2145 case REQ_MOVE_UP:
2146 steps = -1;
2147 break;
2149 case REQ_MOVE_DOWN:
2150 steps = 1;
2151 break;
2153 default:
2154 die("request %d not handled in switch", request);
2155 }
2157 if (steps <= 0 && view->lineno == 0) {
2158 report("Cannot move beyond the first line");
2159 return;
2161 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2162 report("Cannot move beyond the last line");
2163 return;
2164 }
2166 /* Move the current line */
2167 view->lineno += steps;
2168 assert(0 <= view->lineno && view->lineno < view->lines);
2170 /* Check whether the view needs to be scrolled */
2171 if (view->lineno < view->offset ||
2172 view->lineno >= view->offset + view->height) {
2173 scroll_steps = steps;
2174 if (steps < 0 && -steps > view->offset) {
2175 scroll_steps = -view->offset;
2177 } else if (steps > 0) {
2178 if (view->lineno == view->lines - 1 &&
2179 view->lines > view->height) {
2180 scroll_steps = view->lines - view->offset - 1;
2181 if (scroll_steps >= view->height)
2182 scroll_steps -= view->height - 1;
2183 }
2184 }
2185 }
2187 if (!view_is_displayed(view)) {
2188 view->offset += scroll_steps;
2189 assert(0 <= view->offset && view->offset < view->lines);
2190 view->ops->select(view, &view->line[view->lineno]);
2191 return;
2192 }
2194 /* Repaint the old "current" line if we be scrolling */
2195 if (ABS(steps) < view->height)
2196 draw_view_line(view, view->lineno - steps - view->offset);
2198 if (scroll_steps) {
2199 do_scroll_view(view, scroll_steps);
2200 return;
2201 }
2203 /* Draw the current line */
2204 draw_view_line(view, view->lineno - view->offset);
2206 wnoutrefresh(view->win);
2207 report("");
2208 }
2211 /*
2212 * Searching
2213 */
2215 static void search_view(struct view *view, enum request request);
2217 static bool
2218 grep_text(struct view *view, const char *text[])
2219 {
2220 regmatch_t pmatch;
2221 size_t i;
2223 for (i = 0; text[i]; i++)
2224 if (*text[i] &&
2225 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2226 return TRUE;
2227 return FALSE;
2228 }
2230 static void
2231 select_view_line(struct view *view, unsigned long lineno)
2232 {
2233 unsigned long old_lineno = view->lineno;
2234 unsigned long old_offset = view->offset;
2236 if (goto_view_line(view, view->offset, lineno)) {
2237 if (view_is_displayed(view)) {
2238 if (old_offset != view->offset) {
2239 redraw_view(view);
2240 } else {
2241 draw_view_line(view, old_lineno - view->offset);
2242 draw_view_line(view, view->lineno - view->offset);
2243 wnoutrefresh(view->win);
2244 }
2245 } else {
2246 view->ops->select(view, &view->line[view->lineno]);
2247 }
2248 }
2249 }
2251 static void
2252 find_next(struct view *view, enum request request)
2253 {
2254 unsigned long lineno = view->lineno;
2255 int direction;
2257 if (!*view->grep) {
2258 if (!*opt_search)
2259 report("No previous search");
2260 else
2261 search_view(view, request);
2262 return;
2263 }
2265 switch (request) {
2266 case REQ_SEARCH:
2267 case REQ_FIND_NEXT:
2268 direction = 1;
2269 break;
2271 case REQ_SEARCH_BACK:
2272 case REQ_FIND_PREV:
2273 direction = -1;
2274 break;
2276 default:
2277 return;
2278 }
2280 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2281 lineno += direction;
2283 /* Note, lineno is unsigned long so will wrap around in which case it
2284 * will become bigger than view->lines. */
2285 for (; lineno < view->lines; lineno += direction) {
2286 if (view->ops->grep(view, &view->line[lineno])) {
2287 select_view_line(view, lineno);
2288 report("Line %ld matches '%s'", lineno + 1, view->grep);
2289 return;
2290 }
2291 }
2293 report("No match found for '%s'", view->grep);
2294 }
2296 static void
2297 search_view(struct view *view, enum request request)
2298 {
2299 int regex_err;
2301 if (view->regex) {
2302 regfree(view->regex);
2303 *view->grep = 0;
2304 } else {
2305 view->regex = calloc(1, sizeof(*view->regex));
2306 if (!view->regex)
2307 return;
2308 }
2310 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2311 if (regex_err != 0) {
2312 char buf[SIZEOF_STR] = "unknown error";
2314 regerror(regex_err, view->regex, buf, sizeof(buf));
2315 report("Search failed: %s", buf);
2316 return;
2317 }
2319 string_copy(view->grep, opt_search);
2321 find_next(view, request);
2322 }
2324 /*
2325 * Incremental updating
2326 */
2328 static void
2329 reset_view(struct view *view)
2330 {
2331 int i;
2333 for (i = 0; i < view->lines; i++)
2334 free(view->line[i].data);
2335 free(view->line);
2337 view->p_offset = view->offset;
2338 view->p_yoffset = view->yoffset;
2339 view->p_lineno = view->lineno;
2341 view->line = NULL;
2342 view->offset = 0;
2343 view->yoffset = 0;
2344 view->lines = 0;
2345 view->lineno = 0;
2346 view->vid[0] = 0;
2347 view->update_secs = 0;
2348 }
2350 static const char *
2351 format_arg(const char *name)
2352 {
2353 static struct {
2354 const char *name;
2355 size_t namelen;
2356 const char *value;
2357 const char *value_if_empty;
2358 } vars[] = {
2359 #define FORMAT_VAR(name, value, value_if_empty) \
2360 { name, STRING_SIZE(name), value, value_if_empty }
2361 FORMAT_VAR("%(directory)", opt_path, "."),
2362 FORMAT_VAR("%(file)", opt_file, ""),
2363 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2364 FORMAT_VAR("%(head)", ref_head, ""),
2365 FORMAT_VAR("%(commit)", ref_commit, ""),
2366 FORMAT_VAR("%(blob)", ref_blob, ""),
2367 FORMAT_VAR("%(branch)", ref_branch, ""),
2368 };
2369 int i;
2371 for (i = 0; i < ARRAY_SIZE(vars); i++)
2372 if (!strncmp(name, vars[i].name, vars[i].namelen))
2373 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2375 report("Unknown replacement: `%s`", name);
2376 return NULL;
2377 }
2379 static bool
2380 format_argv(const char ***dst_argv, const char *src_argv[], bool replace, bool first)
2381 {
2382 char buf[SIZEOF_STR];
2383 int argc;
2385 argv_free(*dst_argv);
2387 for (argc = 0; src_argv[argc]; argc++) {
2388 const char *arg = src_argv[argc];
2389 size_t bufpos = 0;
2391 if (!strcmp(arg, "%(fileargs)")) {
2392 if (!argv_append_array(dst_argv, opt_file_argv))
2393 break;
2394 continue;
2396 } else if (!strcmp(arg, "%(diffargs)")) {
2397 if (!argv_append_array(dst_argv, opt_diff_argv))
2398 break;
2399 continue;
2401 } else if (!strcmp(arg, "%(blameargs)")) {
2402 if (!argv_append_array(dst_argv, opt_blame_argv))
2403 break;
2404 continue;
2406 } else if (!strcmp(arg, "%(revargs)") ||
2407 (first && !strcmp(arg, "%(commit)"))) {
2408 if (!argv_append_array(dst_argv, opt_rev_argv))
2409 break;
2410 continue;
2411 }
2413 while (arg) {
2414 char *next = strstr(arg, "%(");
2415 int len = next - arg;
2416 const char *value;
2418 if (!next || !replace) {
2419 len = strlen(arg);
2420 value = "";
2422 } else {
2423 value = format_arg(next);
2425 if (!value) {
2426 return FALSE;
2427 }
2428 }
2430 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2431 return FALSE;
2433 arg = next && replace ? strchr(next, ')') + 1 : NULL;
2434 }
2436 if (!argv_append(dst_argv, buf))
2437 break;
2438 }
2440 return src_argv[argc] == NULL;
2441 }
2443 static bool
2444 restore_view_position(struct view *view)
2445 {
2446 if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2447 return FALSE;
2449 /* Changing the view position cancels the restoring. */
2450 /* FIXME: Changing back to the first line is not detected. */
2451 if (view->offset != 0 || view->lineno != 0) {
2452 view->p_restore = FALSE;
2453 return FALSE;
2454 }
2456 if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2457 view_is_displayed(view))
2458 werase(view->win);
2460 view->yoffset = view->p_yoffset;
2461 view->p_restore = FALSE;
2463 return TRUE;
2464 }
2466 static void
2467 end_update(struct view *view, bool force)
2468 {
2469 if (!view->pipe)
2470 return;
2471 while (!view->ops->read(view, NULL))
2472 if (!force)
2473 return;
2474 if (force)
2475 io_kill(view->pipe);
2476 io_done(view->pipe);
2477 view->pipe = NULL;
2478 }
2480 static void
2481 setup_update(struct view *view, const char *vid)
2482 {
2483 reset_view(view);
2484 string_copy_rev(view->vid, vid);
2485 view->pipe = &view->io;
2486 view->start_time = time(NULL);
2487 }
2489 static bool
2490 prepare_io(struct view *view, const char *dir, const char *argv[], bool replace)
2491 {
2492 view->dir = dir;
2493 return format_argv(&view->argv, argv, replace, !view->prev);
2494 }
2496 static bool
2497 prepare_update(struct view *view, const char *argv[], const char *dir)
2498 {
2499 if (view->pipe)
2500 end_update(view, TRUE);
2501 return prepare_io(view, dir, argv, FALSE);
2502 }
2504 static bool
2505 start_update(struct view *view, const char **argv, const char *dir)
2506 {
2507 if (view->pipe)
2508 io_done(view->pipe);
2509 return prepare_io(view, dir, argv, FALSE) &&
2510 io_run(&view->io, IO_RD, dir, view->argv);
2511 }
2513 static bool
2514 prepare_update_file(struct view *view, const char *name)
2515 {
2516 if (view->pipe)
2517 end_update(view, TRUE);
2518 argv_free(view->argv);
2519 return io_open(&view->io, "%s/%s", opt_cdup[0] ? opt_cdup : ".", name);
2520 }
2522 static bool
2523 begin_update(struct view *view, bool refresh)
2524 {
2525 if (view->pipe)
2526 end_update(view, TRUE);
2528 if (!refresh) {
2529 if (view->ops->prepare) {
2530 if (!view->ops->prepare(view))
2531 return FALSE;
2532 } else if (!prepare_io(view, NULL, view->ops->argv, TRUE)) {
2533 return FALSE;
2534 }
2536 /* Put the current ref_* value to the view title ref
2537 * member. This is needed by the blob view. Most other
2538 * views sets it automatically after loading because the
2539 * first line is a commit line. */
2540 string_copy_rev(view->ref, view->id);
2541 }
2543 if (view->argv && view->argv[0] &&
2544 !io_run(&view->io, IO_RD, view->dir, view->argv))
2545 return FALSE;
2547 setup_update(view, view->id);
2549 return TRUE;
2550 }
2552 static bool
2553 update_view(struct view *view)
2554 {
2555 char out_buffer[BUFSIZ * 2];
2556 char *line;
2557 /* Clear the view and redraw everything since the tree sorting
2558 * might have rearranged things. */
2559 bool redraw = view->lines == 0;
2560 bool can_read = TRUE;
2562 if (!view->pipe)
2563 return TRUE;
2565 if (!io_can_read(view->pipe, FALSE)) {
2566 if (view->lines == 0 && view_is_displayed(view)) {
2567 time_t secs = time(NULL) - view->start_time;
2569 if (secs > 1 && secs > view->update_secs) {
2570 if (view->update_secs == 0)
2571 redraw_view(view);
2572 update_view_title(view);
2573 view->update_secs = secs;
2574 }
2575 }
2576 return TRUE;
2577 }
2579 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2580 if (opt_iconv_in != ICONV_NONE) {
2581 ICONV_CONST char *inbuf = line;
2582 size_t inlen = strlen(line) + 1;
2584 char *outbuf = out_buffer;
2585 size_t outlen = sizeof(out_buffer);
2587 size_t ret;
2589 ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2590 if (ret != (size_t) -1)
2591 line = out_buffer;
2592 }
2594 if (!view->ops->read(view, line)) {
2595 report("Allocation failure");
2596 end_update(view, TRUE);
2597 return FALSE;
2598 }
2599 }
2601 {
2602 unsigned long lines = view->lines;
2603 int digits;
2605 for (digits = 0; lines; digits++)
2606 lines /= 10;
2608 /* Keep the displayed view in sync with line number scaling. */
2609 if (digits != view->digits) {
2610 view->digits = digits;
2611 if (opt_line_number || view->type == VIEW_BLAME)
2612 redraw = TRUE;
2613 }
2614 }
2616 if (io_error(view->pipe)) {
2617 report("Failed to read: %s", io_strerror(view->pipe));
2618 end_update(view, TRUE);
2620 } else if (io_eof(view->pipe)) {
2621 if (view_is_displayed(view))
2622 report("");
2623 end_update(view, FALSE);
2624 }
2626 if (restore_view_position(view))
2627 redraw = TRUE;
2629 if (!view_is_displayed(view))
2630 return TRUE;
2632 if (redraw)
2633 redraw_view_from(view, 0);
2634 else
2635 redraw_view_dirty(view);
2637 /* Update the title _after_ the redraw so that if the redraw picks up a
2638 * commit reference in view->ref it'll be available here. */
2639 update_view_title(view);
2640 return TRUE;
2641 }
2643 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2645 static struct line *
2646 add_line_data(struct view *view, void *data, enum line_type type)
2647 {
2648 struct line *line;
2650 if (!realloc_lines(&view->line, view->lines, 1))
2651 return NULL;
2653 line = &view->line[view->lines++];
2654 memset(line, 0, sizeof(*line));
2655 line->type = type;
2656 line->data = data;
2657 line->dirty = 1;
2659 return line;
2660 }
2662 static struct line *
2663 add_line_text(struct view *view, const char *text, enum line_type type)
2664 {
2665 char *data = text ? strdup(text) : NULL;
2667 return data ? add_line_data(view, data, type) : NULL;
2668 }
2670 static struct line *
2671 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2672 {
2673 char buf[SIZEOF_STR];
2674 va_list args;
2676 va_start(args, fmt);
2677 if (vsnprintf(buf, sizeof(buf), fmt, args) >= sizeof(buf))
2678 buf[0] = 0;
2679 va_end(args);
2681 return buf[0] ? add_line_text(view, buf, type) : NULL;
2682 }
2684 /*
2685 * View opening
2686 */
2688 enum open_flags {
2689 OPEN_DEFAULT = 0, /* Use default view switching. */
2690 OPEN_SPLIT = 1, /* Split current view. */
2691 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
2692 OPEN_REFRESH = 16, /* Refresh view using previous command. */
2693 OPEN_PREPARED = 32, /* Open already prepared command. */
2694 };
2696 static void
2697 open_view(struct view *prev, enum request request, enum open_flags flags)
2698 {
2699 bool split = !!(flags & OPEN_SPLIT);
2700 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED));
2701 bool nomaximize = !!(flags & OPEN_REFRESH);
2702 struct view *view = VIEW(request);
2703 int nviews = displayed_views();
2704 struct view *base_view = display[0];
2706 if (view == prev && nviews == 1 && !reload) {
2707 report("Already in %s view", view->name);
2708 return;
2709 }
2711 if (view->git_dir && !opt_git_dir[0]) {
2712 report("The %s view is disabled in pager view", view->name);
2713 return;
2714 }
2716 if (split) {
2717 display[1] = view;
2718 current_view = 1;
2719 view->parent = prev;
2720 } else if (!nomaximize) {
2721 /* Maximize the current view. */
2722 memset(display, 0, sizeof(display));
2723 current_view = 0;
2724 display[current_view] = view;
2725 }
2727 /* No prev signals that this is the first loaded view. */
2728 if (prev && view != prev) {
2729 view->prev = prev;
2730 }
2732 /* Resize the view when switching between split- and full-screen,
2733 * or when switching between two different full-screen views. */
2734 if (nviews != displayed_views() ||
2735 (nviews == 1 && base_view != display[0]))
2736 resize_display();
2738 if (view->ops->open) {
2739 if (view->pipe)
2740 end_update(view, TRUE);
2741 if (!view->ops->open(view)) {
2742 report("Failed to load %s view", view->name);
2743 return;
2744 }
2745 restore_view_position(view);
2747 } else if ((reload || strcmp(view->vid, view->id)) &&
2748 !begin_update(view, flags & (OPEN_REFRESH | OPEN_PREPARED))) {
2749 report("Failed to load %s view", view->name);
2750 return;
2751 }
2753 if (split && prev->lineno - prev->offset >= prev->height) {
2754 /* Take the title line into account. */
2755 int lines = prev->lineno - prev->offset - prev->height + 1;
2757 /* Scroll the view that was split if the current line is
2758 * outside the new limited view. */
2759 do_scroll_view(prev, lines);
2760 }
2762 if (prev && view != prev && split && view_is_displayed(prev)) {
2763 /* "Blur" the previous view. */
2764 update_view_title(prev);
2765 }
2767 if (view->pipe && view->lines == 0) {
2768 /* Clear the old view and let the incremental updating refill
2769 * the screen. */
2770 werase(view->win);
2771 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2772 report("");
2773 } else if (view_is_displayed(view)) {
2774 redraw_view(view);
2775 report("");
2776 }
2777 }
2779 static void
2780 open_external_viewer(const char *argv[], const char *dir)
2781 {
2782 def_prog_mode(); /* save current tty modes */
2783 endwin(); /* restore original tty modes */
2784 io_run_fg(argv, dir);
2785 fprintf(stderr, "Press Enter to continue");
2786 getc(opt_tty);
2787 reset_prog_mode();
2788 redraw_display(TRUE);
2789 }
2791 static void
2792 open_mergetool(const char *file)
2793 {
2794 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2796 open_external_viewer(mergetool_argv, opt_cdup);
2797 }
2799 static void
2800 open_editor(const char *file)
2801 {
2802 const char *editor_argv[] = { "vi", file, NULL };
2803 const char *editor;
2805 editor = getenv("GIT_EDITOR");
2806 if (!editor && *opt_editor)
2807 editor = opt_editor;
2808 if (!editor)
2809 editor = getenv("VISUAL");
2810 if (!editor)
2811 editor = getenv("EDITOR");
2812 if (!editor)
2813 editor = "vi";
2815 editor_argv[0] = editor;
2816 open_external_viewer(editor_argv, opt_cdup);
2817 }
2819 static void
2820 open_run_request(enum request request)
2821 {
2822 struct run_request *req = get_run_request(request);
2823 const char **argv = NULL;
2825 if (!req) {
2826 report("Unknown run request");
2827 return;
2828 }
2830 if (format_argv(&argv, req->argv, TRUE, FALSE))
2831 open_external_viewer(argv, NULL);
2832 if (argv)
2833 argv_free(argv);
2834 free(argv);
2835 }
2837 /*
2838 * User request switch noodle
2839 */
2841 static int
2842 view_driver(struct view *view, enum request request)
2843 {
2844 int i;
2846 if (request == REQ_NONE)
2847 return TRUE;
2849 if (request > REQ_NONE) {
2850 open_run_request(request);
2851 view_request(view, REQ_REFRESH);
2852 return TRUE;
2853 }
2855 request = view_request(view, request);
2856 if (request == REQ_NONE)
2857 return TRUE;
2859 switch (request) {
2860 case REQ_MOVE_UP:
2861 case REQ_MOVE_DOWN:
2862 case REQ_MOVE_PAGE_UP:
2863 case REQ_MOVE_PAGE_DOWN:
2864 case REQ_MOVE_FIRST_LINE:
2865 case REQ_MOVE_LAST_LINE:
2866 move_view(view, request);
2867 break;
2869 case REQ_SCROLL_FIRST_COL:
2870 case REQ_SCROLL_LEFT:
2871 case REQ_SCROLL_RIGHT:
2872 case REQ_SCROLL_LINE_DOWN:
2873 case REQ_SCROLL_LINE_UP:
2874 case REQ_SCROLL_PAGE_DOWN:
2875 case REQ_SCROLL_PAGE_UP:
2876 scroll_view(view, request);
2877 break;
2879 case REQ_VIEW_BLAME:
2880 if (!opt_file[0]) {
2881 report("No file chosen, press %s to open tree view",
2882 get_key(view->keymap, REQ_VIEW_TREE));
2883 break;
2884 }
2885 open_view(view, request, OPEN_DEFAULT);
2886 break;
2888 case REQ_VIEW_BLOB:
2889 if (!ref_blob[0]) {
2890 report("No file chosen, press %s to open tree view",
2891 get_key(view->keymap, REQ_VIEW_TREE));
2892 break;
2893 }
2894 open_view(view, request, OPEN_DEFAULT);
2895 break;
2897 case REQ_VIEW_PAGER:
2898 if (view == NULL) {
2899 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
2900 die("Failed to open stdin");
2901 open_view(view, request, OPEN_PREPARED);
2902 break;
2903 }
2905 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
2906 report("No pager content, press %s to run command from prompt",
2907 get_key(view->keymap, REQ_PROMPT));
2908 break;
2909 }
2910 open_view(view, request, OPEN_DEFAULT);
2911 break;
2913 case REQ_VIEW_STAGE:
2914 if (!VIEW(REQ_VIEW_STAGE)->lines) {
2915 report("No stage content, press %s to open the status view and choose file",
2916 get_key(view->keymap, REQ_VIEW_STATUS));
2917 break;
2918 }
2919 open_view(view, request, OPEN_DEFAULT);
2920 break;
2922 case REQ_VIEW_STATUS:
2923 if (opt_is_inside_work_tree == FALSE) {
2924 report("The status view requires a working tree");
2925 break;
2926 }
2927 open_view(view, request, OPEN_DEFAULT);
2928 break;
2930 case REQ_VIEW_MAIN:
2931 case REQ_VIEW_DIFF:
2932 case REQ_VIEW_LOG:
2933 case REQ_VIEW_TREE:
2934 case REQ_VIEW_HELP:
2935 case REQ_VIEW_BRANCH:
2936 open_view(view, request, OPEN_DEFAULT);
2937 break;
2939 case REQ_NEXT:
2940 case REQ_PREVIOUS:
2941 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
2943 if (view->parent) {
2944 int line;
2946 view = view->parent;
2947 line = view->lineno;
2948 move_view(view, request);
2949 if (view_is_displayed(view))
2950 update_view_title(view);
2951 if (line != view->lineno)
2952 view_request(view, REQ_ENTER);
2953 } else {
2954 move_view(view, request);
2955 }
2956 break;
2958 case REQ_VIEW_NEXT:
2959 {
2960 int nviews = displayed_views();
2961 int next_view = (current_view + 1) % nviews;
2963 if (next_view == current_view) {
2964 report("Only one view is displayed");
2965 break;
2966 }
2968 current_view = next_view;
2969 /* Blur out the title of the previous view. */
2970 update_view_title(view);
2971 report("");
2972 break;
2973 }
2974 case REQ_REFRESH:
2975 report("Refreshing is not yet supported for the %s view", view->name);
2976 break;
2978 case REQ_MAXIMIZE:
2979 if (displayed_views() == 2)
2980 maximize_view(view);
2981 break;
2983 case REQ_OPTIONS:
2984 case REQ_TOGGLE_LINENO:
2985 case REQ_TOGGLE_DATE:
2986 case REQ_TOGGLE_AUTHOR:
2987 case REQ_TOGGLE_GRAPHIC:
2988 case REQ_TOGGLE_REV_GRAPH:
2989 case REQ_TOGGLE_REFS:
2990 toggle_option(request);
2991 break;
2993 case REQ_TOGGLE_SORT_FIELD:
2994 case REQ_TOGGLE_SORT_ORDER:
2995 report("Sorting is not yet supported for the %s view", view->name);
2996 break;
2998 case REQ_SEARCH:
2999 case REQ_SEARCH_BACK:
3000 search_view(view, request);
3001 break;
3003 case REQ_FIND_NEXT:
3004 case REQ_FIND_PREV:
3005 find_next(view, request);
3006 break;
3008 case REQ_STOP_LOADING:
3009 foreach_view(view, i) {
3010 if (view->pipe)
3011 report("Stopped loading the %s view", view->name),
3012 end_update(view, TRUE);
3013 }
3014 break;
3016 case REQ_SHOW_VERSION:
3017 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3018 return TRUE;
3020 case REQ_SCREEN_REDRAW:
3021 redraw_display(TRUE);
3022 break;
3024 case REQ_EDIT:
3025 report("Nothing to edit");
3026 break;
3028 case REQ_ENTER:
3029 report("Nothing to enter");
3030 break;
3032 case REQ_VIEW_CLOSE:
3033 /* XXX: Mark closed views by letting view->prev point to the
3034 * view itself. Parents to closed view should never be
3035 * followed. */
3036 if (view->prev && view->prev != view) {
3037 maximize_view(view->prev);
3038 view->prev = view;
3039 break;
3040 }
3041 /* Fall-through */
3042 case REQ_QUIT:
3043 return FALSE;
3045 default:
3046 report("Unknown key, press %s for help",
3047 get_key(view->keymap, REQ_VIEW_HELP));
3048 return TRUE;
3049 }
3051 return TRUE;
3052 }
3055 /*
3056 * View backend utilities
3057 */
3059 enum sort_field {
3060 ORDERBY_NAME,
3061 ORDERBY_DATE,
3062 ORDERBY_AUTHOR,
3063 };
3065 struct sort_state {
3066 const enum sort_field *fields;
3067 size_t size, current;
3068 bool reverse;
3069 };
3071 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3072 #define get_sort_field(state) ((state).fields[(state).current])
3073 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3075 static void
3076 sort_view(struct view *view, enum request request, struct sort_state *state,
3077 int (*compare)(const void *, const void *))
3078 {
3079 switch (request) {
3080 case REQ_TOGGLE_SORT_FIELD:
3081 state->current = (state->current + 1) % state->size;
3082 break;
3084 case REQ_TOGGLE_SORT_ORDER:
3085 state->reverse = !state->reverse;
3086 break;
3087 default:
3088 die("Not a sort request");
3089 }
3091 qsort(view->line, view->lines, sizeof(*view->line), compare);
3092 redraw_view(view);
3093 }
3095 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3097 /* Small author cache to reduce memory consumption. It uses binary
3098 * search to lookup or find place to position new entries. No entries
3099 * are ever freed. */
3100 static const char *
3101 get_author(const char *name)
3102 {
3103 static const char **authors;
3104 static size_t authors_size;
3105 int from = 0, to = authors_size - 1;
3107 while (from <= to) {
3108 size_t pos = (to + from) / 2;
3109 int cmp = strcmp(name, authors[pos]);
3111 if (!cmp)
3112 return authors[pos];
3114 if (cmp < 0)
3115 to = pos - 1;
3116 else
3117 from = pos + 1;
3118 }
3120 if (!realloc_authors(&authors, authors_size, 1))
3121 return NULL;
3122 name = strdup(name);
3123 if (!name)
3124 return NULL;
3126 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3127 authors[from] = name;
3128 authors_size++;
3130 return name;
3131 }
3133 static void
3134 parse_timesec(struct time *time, const char *sec)
3135 {
3136 time->sec = (time_t) atol(sec);
3137 }
3139 static void
3140 parse_timezone(struct time *time, const char *zone)
3141 {
3142 long tz;
3144 tz = ('0' - zone[1]) * 60 * 60 * 10;
3145 tz += ('0' - zone[2]) * 60 * 60;
3146 tz += ('0' - zone[3]) * 60 * 10;
3147 tz += ('0' - zone[4]) * 60;
3149 if (zone[0] == '-')
3150 tz = -tz;
3152 time->tz = tz;
3153 time->sec -= tz;
3154 }
3156 /* Parse author lines where the name may be empty:
3157 * author <email@address.tld> 1138474660 +0100
3158 */
3159 static void
3160 parse_author_line(char *ident, const char **author, struct time *time)
3161 {
3162 char *nameend = strchr(ident, '<');
3163 char *emailend = strchr(ident, '>');
3165 if (nameend && emailend)
3166 *nameend = *emailend = 0;
3167 ident = chomp_string(ident);
3168 if (!*ident) {
3169 if (nameend)
3170 ident = chomp_string(nameend + 1);
3171 if (!*ident)
3172 ident = "Unknown";
3173 }
3175 *author = get_author(ident);
3177 /* Parse epoch and timezone */
3178 if (emailend && emailend[1] == ' ') {
3179 char *secs = emailend + 2;
3180 char *zone = strchr(secs, ' ');
3182 parse_timesec(time, secs);
3184 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3185 parse_timezone(time, zone + 1);
3186 }
3187 }
3189 /*
3190 * Pager backend
3191 */
3193 static bool
3194 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3195 {
3196 if (opt_line_number && draw_lineno(view, lineno))
3197 return TRUE;
3199 draw_text(view, line->type, line->data);
3200 return TRUE;
3201 }
3203 static bool
3204 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3205 {
3206 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3207 char ref[SIZEOF_STR];
3209 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3210 return TRUE;
3212 /* This is the only fatal call, since it can "corrupt" the buffer. */
3213 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3214 return FALSE;
3216 return TRUE;
3217 }
3219 static void
3220 add_pager_refs(struct view *view, struct line *line)
3221 {
3222 char buf[SIZEOF_STR];
3223 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3224 struct ref_list *list;
3225 size_t bufpos = 0, i;
3226 const char *sep = "Refs: ";
3227 bool is_tag = FALSE;
3229 assert(line->type == LINE_COMMIT);
3231 list = get_ref_list(commit_id);
3232 if (!list) {
3233 if (view->type == VIEW_DIFF)
3234 goto try_add_describe_ref;
3235 return;
3236 }
3238 for (i = 0; i < list->size; i++) {
3239 struct ref *ref = list->refs[i];
3240 const char *fmt = ref->tag ? "%s[%s]" :
3241 ref->remote ? "%s<%s>" : "%s%s";
3243 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3244 return;
3245 sep = ", ";
3246 if (ref->tag)
3247 is_tag = TRUE;
3248 }
3250 if (!is_tag && view->type == VIEW_DIFF) {
3251 try_add_describe_ref:
3252 /* Add <tag>-g<commit_id> "fake" reference. */
3253 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3254 return;
3255 }
3257 if (bufpos == 0)
3258 return;
3260 add_line_text(view, buf, LINE_PP_REFS);
3261 }
3263 static bool
3264 pager_read(struct view *view, char *data)
3265 {
3266 struct line *line;
3268 if (!data)
3269 return TRUE;
3271 line = add_line_text(view, data, get_line_type(data));
3272 if (!line)
3273 return FALSE;
3275 if (line->type == LINE_COMMIT &&
3276 (view->type == VIEW_DIFF ||
3277 view->type == VIEW_LOG))
3278 add_pager_refs(view, line);
3280 return TRUE;
3281 }
3283 static enum request
3284 pager_request(struct view *view, enum request request, struct line *line)
3285 {
3286 int split = 0;
3288 if (request != REQ_ENTER)
3289 return request;
3291 if (line->type == LINE_COMMIT &&
3292 (view->type == VIEW_LOG ||
3293 view->type == VIEW_PAGER)) {
3294 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3295 split = 1;
3296 }
3298 /* Always scroll the view even if it was split. That way
3299 * you can use Enter to scroll through the log view and
3300 * split open each commit diff. */
3301 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3303 /* FIXME: A minor workaround. Scrolling the view will call report("")
3304 * but if we are scrolling a non-current view this won't properly
3305 * update the view title. */
3306 if (split)
3307 update_view_title(view);
3309 return REQ_NONE;
3310 }
3312 static bool
3313 pager_grep(struct view *view, struct line *line)
3314 {
3315 const char *text[] = { line->data, NULL };
3317 return grep_text(view, text);
3318 }
3320 static void
3321 pager_select(struct view *view, struct line *line)
3322 {
3323 if (line->type == LINE_COMMIT) {
3324 char *text = (char *)line->data + STRING_SIZE("commit ");
3326 if (view->type != VIEW_PAGER)
3327 string_copy_rev(view->ref, text);
3328 string_copy_rev(ref_commit, text);
3329 }
3330 }
3332 static struct view_ops pager_ops = {
3333 "line",
3334 NULL,
3335 NULL,
3336 pager_read,
3337 pager_draw,
3338 pager_request,
3339 pager_grep,
3340 pager_select,
3341 };
3343 static const char *log_argv[SIZEOF_ARG] = {
3344 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3345 };
3347 static enum request
3348 log_request(struct view *view, enum request request, struct line *line)
3349 {
3350 switch (request) {
3351 case REQ_REFRESH:
3352 load_refs();
3353 open_view(view, REQ_VIEW_LOG, OPEN_REFRESH);
3354 return REQ_NONE;
3355 default:
3356 return pager_request(view, request, line);
3357 }
3358 }
3360 static struct view_ops log_ops = {
3361 "line",
3362 log_argv,
3363 NULL,
3364 pager_read,
3365 pager_draw,
3366 log_request,
3367 pager_grep,
3368 pager_select,
3369 };
3371 static const char *diff_argv[SIZEOF_ARG] = {
3372 "git", "show", "--pretty=fuller", "--no-color", "--root",
3373 "--patch-with-stat", "--find-copies-harder", "-C",
3374 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3375 };
3377 static bool
3378 diff_read(struct view *view, char *data)
3379 {
3380 if (!data) {
3381 /* Fall back to retry if no diff will be shown. */
3382 if (view->lines == 0 && opt_file_argv) {
3383 int pos = argv_size(view->argv)
3384 - argv_size(opt_file_argv) - 1;
3386 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3387 for (; view->argv[pos]; pos++) {
3388 free((void *) view->argv[pos]);
3389 view->argv[pos] = NULL;
3390 }
3392 if (view->pipe)
3393 io_done(view->pipe);
3394 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3395 return FALSE;
3396 }
3397 }
3398 return TRUE;
3399 }
3401 return pager_read(view, data);
3402 }
3404 static struct view_ops diff_ops = {
3405 "line",
3406 diff_argv,
3407 NULL,
3408 diff_read,
3409 pager_draw,
3410 pager_request,
3411 pager_grep,
3412 pager_select,
3413 };
3415 /*
3416 * Help backend
3417 */
3419 static bool help_keymap_hidden[ARRAY_SIZE(keymap_table)];
3421 static bool
3422 help_open_keymap_title(struct view *view, enum keymap keymap)
3423 {
3424 struct line *line;
3426 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
3427 help_keymap_hidden[keymap] ? '+' : '-',
3428 enum_name(keymap_table[keymap]));
3429 if (line)
3430 line->other = keymap;
3432 return help_keymap_hidden[keymap];
3433 }
3435 static void
3436 help_open_keymap(struct view *view, enum keymap keymap)
3437 {
3438 const char *group = NULL;
3439 char buf[SIZEOF_STR];
3440 size_t bufpos;
3441 bool add_title = TRUE;
3442 int i;
3444 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
3445 const char *key = NULL;
3447 if (req_info[i].request == REQ_NONE)
3448 continue;
3450 if (!req_info[i].request) {
3451 group = req_info[i].help;
3452 continue;
3453 }
3455 key = get_keys(keymap, req_info[i].request, TRUE);
3456 if (!key || !*key)
3457 continue;
3459 if (add_title && help_open_keymap_title(view, keymap))
3460 return;
3461 add_title = FALSE;
3463 if (group) {
3464 add_line_text(view, group, LINE_HELP_GROUP);
3465 group = NULL;
3466 }
3468 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
3469 enum_name(req_info[i]), req_info[i].help);
3470 }
3472 group = "External commands:";
3474 for (i = 0; i < run_requests; i++) {
3475 struct run_request *req = get_run_request(REQ_NONE + i + 1);
3476 const char *key;
3477 int argc;
3479 if (!req || req->keymap != keymap)
3480 continue;
3482 key = get_key_name(req->key);
3483 if (!*key)
3484 key = "(no key defined)";
3486 if (add_title && help_open_keymap_title(view, keymap))
3487 return;
3488 if (group) {
3489 add_line_text(view, group, LINE_HELP_GROUP);
3490 group = NULL;
3491 }
3493 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
3494 if (!string_format_from(buf, &bufpos, "%s%s",
3495 argc ? " " : "", req->argv[argc]))
3496 return;
3498 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
3499 }
3500 }
3502 static bool
3503 help_open(struct view *view)
3504 {
3505 enum keymap keymap;
3507 reset_view(view);
3508 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
3509 add_line_text(view, "", LINE_DEFAULT);
3511 for (keymap = 0; keymap < ARRAY_SIZE(keymap_table); keymap++)
3512 help_open_keymap(view, keymap);
3514 return TRUE;
3515 }
3517 static enum request
3518 help_request(struct view *view, enum request request, struct line *line)
3519 {
3520 switch (request) {
3521 case REQ_ENTER:
3522 if (line->type == LINE_HELP_KEYMAP) {
3523 help_keymap_hidden[line->other] =
3524 !help_keymap_hidden[line->other];
3525 view->p_restore = TRUE;
3526 open_view(view, REQ_VIEW_HELP, OPEN_REFRESH);
3527 }
3529 return REQ_NONE;
3530 default:
3531 return pager_request(view, request, line);
3532 }
3533 }
3535 static struct view_ops help_ops = {
3536 "line",
3537 NULL,
3538 help_open,
3539 NULL,
3540 pager_draw,
3541 help_request,
3542 pager_grep,
3543 pager_select,
3544 };
3547 /*
3548 * Tree backend
3549 */
3551 struct tree_stack_entry {
3552 struct tree_stack_entry *prev; /* Entry below this in the stack */
3553 unsigned long lineno; /* Line number to restore */
3554 char *name; /* Position of name in opt_path */
3555 };
3557 /* The top of the path stack. */
3558 static struct tree_stack_entry *tree_stack = NULL;
3559 unsigned long tree_lineno = 0;
3561 static void
3562 pop_tree_stack_entry(void)
3563 {
3564 struct tree_stack_entry *entry = tree_stack;
3566 tree_lineno = entry->lineno;
3567 entry->name[0] = 0;
3568 tree_stack = entry->prev;
3569 free(entry);
3570 }
3572 static void
3573 push_tree_stack_entry(const char *name, unsigned long lineno)
3574 {
3575 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
3576 size_t pathlen = strlen(opt_path);
3578 if (!entry)
3579 return;
3581 entry->prev = tree_stack;
3582 entry->name = opt_path + pathlen;
3583 tree_stack = entry;
3585 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
3586 pop_tree_stack_entry();
3587 return;
3588 }
3590 /* Move the current line to the first tree entry. */
3591 tree_lineno = 1;
3592 entry->lineno = lineno;
3593 }
3595 /* Parse output from git-ls-tree(1):
3596 *
3597 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
3598 */
3600 #define SIZEOF_TREE_ATTR \
3601 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
3603 #define SIZEOF_TREE_MODE \
3604 STRING_SIZE("100644 ")
3606 #define TREE_ID_OFFSET \
3607 STRING_SIZE("100644 blob ")
3609 struct tree_entry {
3610 char id[SIZEOF_REV];
3611 mode_t mode;
3612 struct time time; /* Date from the author ident. */
3613 const char *author; /* Author of the commit. */
3614 char name[1];
3615 };
3617 static const char *
3618 tree_path(const struct line *line)
3619 {
3620 return ((struct tree_entry *) line->data)->name;
3621 }
3623 static int
3624 tree_compare_entry(const struct line *line1, const struct line *line2)
3625 {
3626 if (line1->type != line2->type)
3627 return line1->type == LINE_TREE_DIR ? -1 : 1;
3628 return strcmp(tree_path(line1), tree_path(line2));
3629 }
3631 static const enum sort_field tree_sort_fields[] = {
3632 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
3633 };
3634 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
3636 static int
3637 tree_compare(const void *l1, const void *l2)
3638 {
3639 const struct line *line1 = (const struct line *) l1;
3640 const struct line *line2 = (const struct line *) l2;
3641 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
3642 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
3644 if (line1->type == LINE_TREE_HEAD)
3645 return -1;
3646 if (line2->type == LINE_TREE_HEAD)
3647 return 1;
3649 switch (get_sort_field(tree_sort_state)) {
3650 case ORDERBY_DATE:
3651 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
3653 case ORDERBY_AUTHOR:
3654 return sort_order(tree_sort_state, strcmp(entry1->author, entry2->author));
3656 case ORDERBY_NAME:
3657 default:
3658 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
3659 }
3660 }
3663 static struct line *
3664 tree_entry(struct view *view, enum line_type type, const char *path,
3665 const char *mode, const char *id)
3666 {
3667 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
3668 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
3670 if (!entry || !line) {
3671 free(entry);
3672 return NULL;
3673 }
3675 strncpy(entry->name, path, strlen(path));
3676 if (mode)
3677 entry->mode = strtoul(mode, NULL, 8);
3678 if (id)
3679 string_copy_rev(entry->id, id);
3681 return line;
3682 }
3684 static bool
3685 tree_read_date(struct view *view, char *text, bool *read_date)
3686 {
3687 static const char *author_name;
3688 static struct time author_time;
3690 if (!text && *read_date) {
3691 *read_date = FALSE;
3692 return TRUE;
3694 } else if (!text) {
3695 char *path = *opt_path ? opt_path : ".";
3696 /* Find next entry to process */
3697 const char *log_file[] = {
3698 "git", "log", "--no-color", "--pretty=raw",
3699 "--cc", "--raw", view->id, "--", path, NULL
3700 };
3702 if (!view->lines) {
3703 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
3704 report("Tree is empty");
3705 return TRUE;
3706 }
3708 if (!start_update(view, log_file, opt_cdup)) {
3709 report("Failed to load tree data");
3710 return TRUE;
3711 }
3713 *read_date = TRUE;
3714 return FALSE;
3716 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
3717 parse_author_line(text + STRING_SIZE("author "),
3718 &author_name, &author_time);
3720 } else if (*text == ':') {
3721 char *pos;
3722 size_t annotated = 1;
3723 size_t i;
3725 pos = strchr(text, '\t');
3726 if (!pos)
3727 return TRUE;
3728 text = pos + 1;
3729 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
3730 text += strlen(opt_path);
3731 pos = strchr(text, '/');
3732 if (pos)
3733 *pos = 0;
3735 for (i = 1; i < view->lines; i++) {
3736 struct line *line = &view->line[i];
3737 struct tree_entry *entry = line->data;
3739 annotated += !!entry->author;
3740 if (entry->author || strcmp(entry->name, text))
3741 continue;
3743 entry->author = author_name;
3744 entry->time = author_time;
3745 line->dirty = 1;
3746 break;
3747 }
3749 if (annotated == view->lines)
3750 io_kill(view->pipe);
3751 }
3752 return TRUE;
3753 }
3755 static bool
3756 tree_read(struct view *view, char *text)
3757 {
3758 static bool read_date = FALSE;
3759 struct tree_entry *data;
3760 struct line *entry, *line;
3761 enum line_type type;
3762 size_t textlen = text ? strlen(text) : 0;
3763 char *path = text + SIZEOF_TREE_ATTR;
3765 if (read_date || !text)
3766 return tree_read_date(view, text, &read_date);
3768 if (textlen <= SIZEOF_TREE_ATTR)
3769 return FALSE;
3770 if (view->lines == 0 &&
3771 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
3772 return FALSE;
3774 /* Strip the path part ... */
3775 if (*opt_path) {
3776 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
3777 size_t striplen = strlen(opt_path);
3779 if (pathlen > striplen)
3780 memmove(path, path + striplen,
3781 pathlen - striplen + 1);
3783 /* Insert "link" to parent directory. */
3784 if (view->lines == 1 &&
3785 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
3786 return FALSE;
3787 }
3789 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
3790 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
3791 if (!entry)
3792 return FALSE;
3793 data = entry->data;
3795 /* Skip "Directory ..." and ".." line. */
3796 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
3797 if (tree_compare_entry(line, entry) <= 0)
3798 continue;
3800 memmove(line + 1, line, (entry - line) * sizeof(*entry));
3802 line->data = data;
3803 line->type = type;
3804 for (; line <= entry; line++)
3805 line->dirty = line->cleareol = 1;
3806 return TRUE;
3807 }
3809 if (tree_lineno > view->lineno) {
3810 view->lineno = tree_lineno;
3811 tree_lineno = 0;
3812 }
3814 return TRUE;
3815 }
3817 static bool
3818 tree_draw(struct view *view, struct line *line, unsigned int lineno)
3819 {
3820 struct tree_entry *entry = line->data;
3822 if (line->type == LINE_TREE_HEAD) {
3823 if (draw_text(view, line->type, "Directory path /"))
3824 return TRUE;
3825 } else {
3826 if (draw_mode(view, entry->mode))
3827 return TRUE;
3829 if (opt_author && draw_author(view, entry->author))
3830 return TRUE;
3832 if (opt_date && draw_date(view, &entry->time))
3833 return TRUE;
3834 }
3836 draw_text(view, line->type, entry->name);
3837 return TRUE;
3838 }
3840 static void
3841 open_blob_editor(const char *id)
3842 {
3843 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
3844 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
3845 int fd = mkstemp(file);
3847 if (fd == -1)
3848 report("Failed to create temporary file");
3849 else if (!io_run_append(blob_argv, fd))
3850 report("Failed to save blob data to file");
3851 else
3852 open_editor(file);
3853 if (fd != -1)
3854 unlink(file);
3855 }
3857 static enum request
3858 tree_request(struct view *view, enum request request, struct line *line)
3859 {
3860 enum open_flags flags;
3861 struct tree_entry *entry = line->data;
3863 switch (request) {
3864 case REQ_VIEW_BLAME:
3865 if (line->type != LINE_TREE_FILE) {
3866 report("Blame only supported for files");
3867 return REQ_NONE;
3868 }
3870 string_copy(opt_ref, view->vid);
3871 return request;
3873 case REQ_EDIT:
3874 if (line->type != LINE_TREE_FILE) {
3875 report("Edit only supported for files");
3876 } else if (!is_head_commit(view->vid)) {
3877 open_blob_editor(entry->id);
3878 } else {
3879 open_editor(opt_file);
3880 }
3881 return REQ_NONE;
3883 case REQ_TOGGLE_SORT_FIELD:
3884 case REQ_TOGGLE_SORT_ORDER:
3885 sort_view(view, request, &tree_sort_state, tree_compare);
3886 return REQ_NONE;
3888 case REQ_PARENT:
3889 if (!*opt_path) {
3890 /* quit view if at top of tree */
3891 return REQ_VIEW_CLOSE;
3892 }
3893 /* fake 'cd ..' */
3894 line = &view->line[1];
3895 break;
3897 case REQ_ENTER:
3898 break;
3900 default:
3901 return request;
3902 }
3904 /* Cleanup the stack if the tree view is at a different tree. */
3905 while (!*opt_path && tree_stack)
3906 pop_tree_stack_entry();
3908 switch (line->type) {
3909 case LINE_TREE_DIR:
3910 /* Depending on whether it is a subdirectory or parent link
3911 * mangle the path buffer. */
3912 if (line == &view->line[1] && *opt_path) {
3913 pop_tree_stack_entry();
3915 } else {
3916 const char *basename = tree_path(line);
3918 push_tree_stack_entry(basename, view->lineno);
3919 }
3921 /* Trees and subtrees share the same ID, so they are not not
3922 * unique like blobs. */
3923 flags = OPEN_RELOAD;
3924 request = REQ_VIEW_TREE;
3925 break;
3927 case LINE_TREE_FILE:
3928 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
3929 request = REQ_VIEW_BLOB;
3930 break;
3932 default:
3933 return REQ_NONE;
3934 }
3936 open_view(view, request, flags);
3937 if (request == REQ_VIEW_TREE)
3938 view->lineno = tree_lineno;
3940 return REQ_NONE;
3941 }
3943 static bool
3944 tree_grep(struct view *view, struct line *line)
3945 {
3946 struct tree_entry *entry = line->data;
3947 const char *text[] = {
3948 entry->name,
3949 opt_author ? entry->author : "",
3950 mkdate(&entry->time, opt_date),
3951 NULL
3952 };
3954 return grep_text(view, text);
3955 }
3957 static void
3958 tree_select(struct view *view, struct line *line)
3959 {
3960 struct tree_entry *entry = line->data;
3962 if (line->type == LINE_TREE_FILE) {
3963 string_copy_rev(ref_blob, entry->id);
3964 string_format(opt_file, "%s%s", opt_path, tree_path(line));
3966 } else if (line->type != LINE_TREE_DIR) {
3967 return;
3968 }
3970 string_copy_rev(view->ref, entry->id);
3971 }
3973 static bool
3974 tree_prepare(struct view *view)
3975 {
3976 if (view->lines == 0 && opt_prefix[0]) {
3977 char *pos = opt_prefix;
3979 while (pos && *pos) {
3980 char *end = strchr(pos, '/');
3982 if (end)
3983 *end = 0;
3984 push_tree_stack_entry(pos, 0);
3985 pos = end;
3986 if (end) {
3987 *end = '/';
3988 pos++;
3989 }
3990 }
3992 } else if (strcmp(view->vid, view->id)) {
3993 opt_path[0] = 0;
3994 }
3996 return prepare_io(view, opt_cdup, view->ops->argv, TRUE);
3997 }
3999 static const char *tree_argv[SIZEOF_ARG] = {
4000 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4001 };
4003 static struct view_ops tree_ops = {
4004 "file",
4005 tree_argv,
4006 NULL,
4007 tree_read,
4008 tree_draw,
4009 tree_request,
4010 tree_grep,
4011 tree_select,
4012 tree_prepare,
4013 };
4015 static bool
4016 blob_read(struct view *view, char *line)
4017 {
4018 if (!line)
4019 return TRUE;
4020 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4021 }
4023 static enum request
4024 blob_request(struct view *view, enum request request, struct line *line)
4025 {
4026 switch (request) {
4027 case REQ_EDIT:
4028 open_blob_editor(view->vid);
4029 return REQ_NONE;
4030 default:
4031 return pager_request(view, request, line);
4032 }
4033 }
4035 static const char *blob_argv[SIZEOF_ARG] = {
4036 "git", "cat-file", "blob", "%(blob)", NULL
4037 };
4039 static struct view_ops blob_ops = {
4040 "line",
4041 blob_argv,
4042 NULL,
4043 blob_read,
4044 pager_draw,
4045 blob_request,
4046 pager_grep,
4047 pager_select,
4048 };
4050 /*
4051 * Blame backend
4052 *
4053 * Loading the blame view is a two phase job:
4054 *
4055 * 1. File content is read either using opt_file from the
4056 * filesystem or using git-cat-file.
4057 * 2. Then blame information is incrementally added by
4058 * reading output from git-blame.
4059 */
4061 struct blame_commit {
4062 char id[SIZEOF_REV]; /* SHA1 ID. */
4063 char title[128]; /* First line of the commit message. */
4064 const char *author; /* Author of the commit. */
4065 struct time time; /* Date from the author ident. */
4066 char filename[128]; /* Name of file. */
4067 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
4068 char parent_filename[128]; /* Parent/previous name of file. */
4069 };
4071 struct blame {
4072 struct blame_commit *commit;
4073 unsigned long lineno;
4074 char text[1];
4075 };
4077 static bool
4078 blame_open(struct view *view)
4079 {
4080 char path[SIZEOF_STR];
4081 size_t i;
4083 if (!view->prev && *opt_prefix) {
4084 string_copy(path, opt_file);
4085 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4086 return FALSE;
4087 }
4089 if (*opt_ref || !io_open(&view->io, "%s%s", opt_cdup, opt_file)) {
4090 const char *blame_cat_file_argv[] = {
4091 "git", "cat-file", "blob", path, NULL
4092 };
4094 if (!string_format(path, "%s:%s", opt_ref, opt_file) ||
4095 !start_update(view, blame_cat_file_argv, opt_cdup))
4096 return FALSE;
4097 }
4099 /* First pass: remove multiple references to the same commit. */
4100 for (i = 0; i < view->lines; i++) {
4101 struct blame *blame = view->line[i].data;
4103 if (blame->commit && blame->commit->id[0])
4104 blame->commit->id[0] = 0;
4105 else
4106 blame->commit = NULL;
4107 }
4109 /* Second pass: free existing references. */
4110 for (i = 0; i < view->lines; i++) {
4111 struct blame *blame = view->line[i].data;
4113 if (blame->commit)
4114 free(blame->commit);
4115 }
4117 setup_update(view, opt_file);
4118 string_format(view->ref, "%s ...", opt_file);
4120 return TRUE;
4121 }
4123 static struct blame_commit *
4124 get_blame_commit(struct view *view, const char *id)
4125 {
4126 size_t i;
4128 for (i = 0; i < view->lines; i++) {
4129 struct blame *blame = view->line[i].data;
4131 if (!blame->commit)
4132 continue;
4134 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4135 return blame->commit;
4136 }
4138 {
4139 struct blame_commit *commit = calloc(1, sizeof(*commit));
4141 if (commit)
4142 string_ncopy(commit->id, id, SIZEOF_REV);
4143 return commit;
4144 }
4145 }
4147 static bool
4148 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4149 {
4150 const char *pos = *posref;
4152 *posref = NULL;
4153 pos = strchr(pos + 1, ' ');
4154 if (!pos || !isdigit(pos[1]))
4155 return FALSE;
4156 *number = atoi(pos + 1);
4157 if (*number < min || *number > max)
4158 return FALSE;
4160 *posref = pos;
4161 return TRUE;
4162 }
4164 static struct blame_commit *
4165 parse_blame_commit(struct view *view, const char *text, int *blamed)
4166 {
4167 struct blame_commit *commit;
4168 struct blame *blame;
4169 const char *pos = text + SIZEOF_REV - 2;
4170 size_t orig_lineno = 0;
4171 size_t lineno;
4172 size_t group;
4174 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4175 return NULL;
4177 if (!parse_number(&pos, &orig_lineno, 1, 9999999) ||
4178 !parse_number(&pos, &lineno, 1, view->lines) ||
4179 !parse_number(&pos, &group, 1, view->lines - lineno + 1))
4180 return NULL;
4182 commit = get_blame_commit(view, text);
4183 if (!commit)
4184 return NULL;
4186 *blamed += group;
4187 while (group--) {
4188 struct line *line = &view->line[lineno + group - 1];
4190 blame = line->data;
4191 blame->commit = commit;
4192 blame->lineno = orig_lineno + group - 1;
4193 line->dirty = 1;
4194 }
4196 return commit;
4197 }
4199 static bool
4200 blame_read_file(struct view *view, const char *line, bool *read_file)
4201 {
4202 if (!line) {
4203 const char *blame_argv[] = {
4204 "git", "blame", "%(blameargs)", "--incremental",
4205 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4206 };
4208 if (view->lines == 0 && !view->prev)
4209 die("No blame exist for %s", view->vid);
4211 if (view->lines == 0 || !start_update(view, blame_argv, opt_cdup)) {
4212 report("Failed to load blame data");
4213 return TRUE;
4214 }
4216 *read_file = FALSE;
4217 return FALSE;
4219 } else {
4220 size_t linelen = strlen(line);
4221 struct blame *blame = malloc(sizeof(*blame) + linelen);
4223 if (!blame)
4224 return FALSE;
4226 blame->commit = NULL;
4227 strncpy(blame->text, line, linelen);
4228 blame->text[linelen] = 0;
4229 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4230 }
4231 }
4233 static bool
4234 match_blame_header(const char *name, char **line)
4235 {
4236 size_t namelen = strlen(name);
4237 bool matched = !strncmp(name, *line, namelen);
4239 if (matched)
4240 *line += namelen;
4242 return matched;
4243 }
4245 static bool
4246 blame_read(struct view *view, char *line)
4247 {
4248 static struct blame_commit *commit = NULL;
4249 static int blamed = 0;
4250 static bool read_file = TRUE;
4252 if (read_file)
4253 return blame_read_file(view, line, &read_file);
4255 if (!line) {
4256 /* Reset all! */
4257 commit = NULL;
4258 blamed = 0;
4259 read_file = TRUE;
4260 string_format(view->ref, "%s", view->vid);
4261 if (view_is_displayed(view)) {
4262 update_view_title(view);
4263 redraw_view_from(view, 0);
4264 }
4265 return TRUE;
4266 }
4268 if (!commit) {
4269 commit = parse_blame_commit(view, line, &blamed);
4270 string_format(view->ref, "%s %2d%%", view->vid,
4271 view->lines ? blamed * 100 / view->lines : 0);
4273 } else if (match_blame_header("author ", &line)) {
4274 commit->author = get_author(line);
4276 } else if (match_blame_header("author-time ", &line)) {
4277 parse_timesec(&commit->time, line);
4279 } else if (match_blame_header("author-tz ", &line)) {
4280 parse_timezone(&commit->time, line);
4282 } else if (match_blame_header("summary ", &line)) {
4283 string_ncopy(commit->title, line, strlen(line));
4285 } else if (match_blame_header("previous ", &line)) {
4286 if (strlen(line) <= SIZEOF_REV)
4287 return FALSE;
4288 string_copy_rev(commit->parent_id, line);
4289 line += SIZEOF_REV;
4290 string_ncopy(commit->parent_filename, line, strlen(line));
4292 } else if (match_blame_header("filename ", &line)) {
4293 string_ncopy(commit->filename, line, strlen(line));
4294 commit = NULL;
4295 }
4297 return TRUE;
4298 }
4300 static bool
4301 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4302 {
4303 struct blame *blame = line->data;
4304 struct time *time = NULL;
4305 const char *id = NULL, *author = NULL;
4307 if (blame->commit && *blame->commit->filename) {
4308 id = blame->commit->id;
4309 author = blame->commit->author;
4310 time = &blame->commit->time;
4311 }
4313 if (opt_date && draw_date(view, time))
4314 return TRUE;
4316 if (opt_author && draw_author(view, author))
4317 return TRUE;
4319 if (draw_field(view, LINE_BLAME_ID, id, ID_COLS, FALSE))
4320 return TRUE;
4322 if (draw_lineno(view, lineno))
4323 return TRUE;
4325 draw_text(view, LINE_DEFAULT, blame->text);
4326 return TRUE;
4327 }
4329 static bool
4330 check_blame_commit(struct blame *blame, bool check_null_id)
4331 {
4332 if (!blame->commit)
4333 report("Commit data not loaded yet");
4334 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4335 report("No commit exist for the selected line");
4336 else
4337 return TRUE;
4338 return FALSE;
4339 }
4341 static void
4342 setup_blame_parent_line(struct view *view, struct blame *blame)
4343 {
4344 char from[SIZEOF_REF + SIZEOF_STR];
4345 char to[SIZEOF_REF + SIZEOF_STR];
4346 const char *diff_tree_argv[] = {
4347 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4348 "-U0", from, to, "--", NULL
4349 };
4350 struct io io;
4351 int parent_lineno = -1;
4352 int blamed_lineno = -1;
4353 char *line;
4355 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4356 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4357 !io_run(&io, IO_RD, NULL, diff_tree_argv))
4358 return;
4360 while ((line = io_get(&io, '\n', TRUE))) {
4361 if (*line == '@') {
4362 char *pos = strchr(line, '+');
4364 parent_lineno = atoi(line + 4);
4365 if (pos)
4366 blamed_lineno = atoi(pos + 1);
4368 } else if (*line == '+' && parent_lineno != -1) {
4369 if (blame->lineno == blamed_lineno - 1 &&
4370 !strcmp(blame->text, line + 1)) {
4371 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4372 break;
4373 }
4374 blamed_lineno++;
4375 }
4376 }
4378 io_done(&io);
4379 }
4381 static enum request
4382 blame_request(struct view *view, enum request request, struct line *line)
4383 {
4384 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4385 struct blame *blame = line->data;
4387 switch (request) {
4388 case REQ_VIEW_BLAME:
4389 if (check_blame_commit(blame, TRUE)) {
4390 string_copy(opt_ref, blame->commit->id);
4391 string_copy(opt_file, blame->commit->filename);
4392 if (blame->lineno)
4393 view->lineno = blame->lineno;
4394 open_view(view, REQ_VIEW_BLAME, OPEN_REFRESH);
4395 }
4396 break;
4398 case REQ_PARENT:
4399 if (!check_blame_commit(blame, TRUE))
4400 break;
4401 if (!*blame->commit->parent_id) {
4402 report("The selected commit has no parents");
4403 } else {
4404 string_copy_rev(opt_ref, blame->commit->parent_id);
4405 string_copy(opt_file, blame->commit->parent_filename);
4406 setup_blame_parent_line(view, blame);
4407 open_view(view, REQ_VIEW_BLAME, OPEN_REFRESH);
4408 }
4409 break;
4411 case REQ_ENTER:
4412 if (!check_blame_commit(blame, FALSE))
4413 break;
4415 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
4416 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
4417 break;
4419 if (!strcmp(blame->commit->id, NULL_ID)) {
4420 struct view *diff = VIEW(REQ_VIEW_DIFF);
4421 const char *diff_index_argv[] = {
4422 "git", "diff-index", "--root", "--patch-with-stat",
4423 "-C", "-M", "HEAD", "--", view->vid, NULL
4424 };
4426 if (!*blame->commit->parent_id) {
4427 diff_index_argv[1] = "diff";
4428 diff_index_argv[2] = "--no-color";
4429 diff_index_argv[6] = "--";
4430 diff_index_argv[7] = "/dev/null";
4431 }
4433 if (!prepare_update(diff, diff_index_argv, NULL)) {
4434 report("Failed to allocate diff command");
4435 break;
4436 }
4437 flags |= OPEN_PREPARED;
4438 }
4440 open_view(view, REQ_VIEW_DIFF, flags);
4441 if (VIEW(REQ_VIEW_DIFF)->pipe && !strcmp(blame->commit->id, NULL_ID))
4442 string_copy_rev(VIEW(REQ_VIEW_DIFF)->ref, NULL_ID);
4443 break;
4445 default:
4446 return request;
4447 }
4449 return REQ_NONE;
4450 }
4452 static bool
4453 blame_grep(struct view *view, struct line *line)
4454 {
4455 struct blame *blame = line->data;
4456 struct blame_commit *commit = blame->commit;
4457 const char *text[] = {
4458 blame->text,
4459 commit ? commit->title : "",
4460 commit ? commit->id : "",
4461 commit && opt_author ? commit->author : "",
4462 commit ? mkdate(&commit->time, opt_date) : "",
4463 NULL
4464 };
4466 return grep_text(view, text);
4467 }
4469 static void
4470 blame_select(struct view *view, struct line *line)
4471 {
4472 struct blame *blame = line->data;
4473 struct blame_commit *commit = blame->commit;
4475 if (!commit)
4476 return;
4478 if (!strcmp(commit->id, NULL_ID))
4479 string_ncopy(ref_commit, "HEAD", 4);
4480 else
4481 string_copy_rev(ref_commit, commit->id);
4482 }
4484 static struct view_ops blame_ops = {
4485 "line",
4486 NULL,
4487 blame_open,
4488 blame_read,
4489 blame_draw,
4490 blame_request,
4491 blame_grep,
4492 blame_select,
4493 };
4495 /*
4496 * Branch backend
4497 */
4499 struct branch {
4500 const char *author; /* Author of the last commit. */
4501 struct time time; /* Date of the last activity. */
4502 const struct ref *ref; /* Name and commit ID information. */
4503 };
4505 static const struct ref branch_all;
4507 static const enum sort_field branch_sort_fields[] = {
4508 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4509 };
4510 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
4512 static int
4513 branch_compare(const void *l1, const void *l2)
4514 {
4515 const struct branch *branch1 = ((const struct line *) l1)->data;
4516 const struct branch *branch2 = ((const struct line *) l2)->data;
4518 switch (get_sort_field(branch_sort_state)) {
4519 case ORDERBY_DATE:
4520 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
4522 case ORDERBY_AUTHOR:
4523 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
4525 case ORDERBY_NAME:
4526 default:
4527 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
4528 }
4529 }
4531 static bool
4532 branch_draw(struct view *view, struct line *line, unsigned int lineno)
4533 {
4534 struct branch *branch = line->data;
4535 enum line_type type = branch->ref->head ? LINE_MAIN_HEAD : LINE_DEFAULT;
4537 if (opt_date && draw_date(view, &branch->time))
4538 return TRUE;
4540 if (opt_author && draw_author(view, branch->author))
4541 return TRUE;
4543 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
4544 return TRUE;
4545 }
4547 static enum request
4548 branch_request(struct view *view, enum request request, struct line *line)
4549 {
4550 struct branch *branch = line->data;
4552 switch (request) {
4553 case REQ_REFRESH:
4554 load_refs();
4555 open_view(view, REQ_VIEW_BRANCH, OPEN_REFRESH);
4556 return REQ_NONE;
4558 case REQ_TOGGLE_SORT_FIELD:
4559 case REQ_TOGGLE_SORT_ORDER:
4560 sort_view(view, request, &branch_sort_state, branch_compare);
4561 return REQ_NONE;
4563 case REQ_ENTER:
4564 {
4565 const struct ref *ref = branch->ref;
4566 const char *all_branches_argv[] = {
4567 "git", "log", "--no-color", "--pretty=raw", "--parents",
4568 "--topo-order",
4569 ref == &branch_all ? "--all" : ref->name, NULL
4570 };
4571 struct view *main_view = VIEW(REQ_VIEW_MAIN);
4573 if (!prepare_update(main_view, all_branches_argv, NULL))
4574 report("Failed to load view of all branches");
4575 else
4576 open_view(view, REQ_VIEW_MAIN, OPEN_PREPARED | OPEN_SPLIT);
4577 return REQ_NONE;
4578 }
4579 default:
4580 return request;
4581 }
4582 }
4584 static bool
4585 branch_read(struct view *view, char *line)
4586 {
4587 static char id[SIZEOF_REV];
4588 struct branch *reference;
4589 size_t i;
4591 if (!line)
4592 return TRUE;
4594 switch (get_line_type(line)) {
4595 case LINE_COMMIT:
4596 string_copy_rev(id, line + STRING_SIZE("commit "));
4597 return TRUE;
4599 case LINE_AUTHOR:
4600 for (i = 0, reference = NULL; i < view->lines; i++) {
4601 struct branch *branch = view->line[i].data;
4603 if (strcmp(branch->ref->id, id))
4604 continue;
4606 view->line[i].dirty = TRUE;
4607 if (reference) {
4608 branch->author = reference->author;
4609 branch->time = reference->time;
4610 continue;
4611 }
4613 parse_author_line(line + STRING_SIZE("author "),
4614 &branch->author, &branch->time);
4615 reference = branch;
4616 }
4617 return TRUE;
4619 default:
4620 return TRUE;
4621 }
4623 }
4625 static bool
4626 branch_open_visitor(void *data, const struct ref *ref)
4627 {
4628 struct view *view = data;
4629 struct branch *branch;
4631 if (ref->tag || ref->ltag || ref->remote)
4632 return TRUE;
4634 branch = calloc(1, sizeof(*branch));
4635 if (!branch)
4636 return FALSE;
4638 branch->ref = ref;
4639 return !!add_line_data(view, branch, LINE_DEFAULT);
4640 }
4642 static bool
4643 branch_open(struct view *view)
4644 {
4645 const char *branch_log[] = {
4646 "git", "log", "--no-color", "--pretty=raw",
4647 "--simplify-by-decoration", "--all", NULL
4648 };
4650 if (!start_update(view, branch_log, NULL)) {
4651 report("Failed to load branch data");
4652 return TRUE;
4653 }
4655 setup_update(view, view->id);
4656 branch_open_visitor(view, &branch_all);
4657 foreach_ref(branch_open_visitor, view);
4658 view->p_restore = TRUE;
4660 return TRUE;
4661 }
4663 static bool
4664 branch_grep(struct view *view, struct line *line)
4665 {
4666 struct branch *branch = line->data;
4667 const char *text[] = {
4668 branch->ref->name,
4669 branch->author,
4670 NULL
4671 };
4673 return grep_text(view, text);
4674 }
4676 static void
4677 branch_select(struct view *view, struct line *line)
4678 {
4679 struct branch *branch = line->data;
4681 string_copy_rev(view->ref, branch->ref->id);
4682 string_copy_rev(ref_commit, branch->ref->id);
4683 string_copy_rev(ref_head, branch->ref->id);
4684 string_copy_rev(ref_branch, branch->ref->name);
4685 }
4687 static struct view_ops branch_ops = {
4688 "branch",
4689 NULL,
4690 branch_open,
4691 branch_read,
4692 branch_draw,
4693 branch_request,
4694 branch_grep,
4695 branch_select,
4696 };
4698 /*
4699 * Status backend
4700 */
4702 struct status {
4703 char status;
4704 struct {
4705 mode_t mode;
4706 char rev[SIZEOF_REV];
4707 char name[SIZEOF_STR];
4708 } old;
4709 struct {
4710 mode_t mode;
4711 char rev[SIZEOF_REV];
4712 char name[SIZEOF_STR];
4713 } new;
4714 };
4716 static char status_onbranch[SIZEOF_STR];
4717 static struct status stage_status;
4718 static enum line_type stage_line_type;
4719 static size_t stage_chunks;
4720 static int *stage_chunk;
4722 DEFINE_ALLOCATOR(realloc_ints, int, 32)
4724 /* This should work even for the "On branch" line. */
4725 static inline bool
4726 status_has_none(struct view *view, struct line *line)
4727 {
4728 return line < view->line + view->lines && !line[1].data;
4729 }
4731 /* Get fields from the diff line:
4732 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
4733 */
4734 static inline bool
4735 status_get_diff(struct status *file, const char *buf, size_t bufsize)
4736 {
4737 const char *old_mode = buf + 1;
4738 const char *new_mode = buf + 8;
4739 const char *old_rev = buf + 15;
4740 const char *new_rev = buf + 56;
4741 const char *status = buf + 97;
4743 if (bufsize < 98 ||
4744 old_mode[-1] != ':' ||
4745 new_mode[-1] != ' ' ||
4746 old_rev[-1] != ' ' ||
4747 new_rev[-1] != ' ' ||
4748 status[-1] != ' ')
4749 return FALSE;
4751 file->status = *status;
4753 string_copy_rev(file->old.rev, old_rev);
4754 string_copy_rev(file->new.rev, new_rev);
4756 file->old.mode = strtoul(old_mode, NULL, 8);
4757 file->new.mode = strtoul(new_mode, NULL, 8);
4759 file->old.name[0] = file->new.name[0] = 0;
4761 return TRUE;
4762 }
4764 static bool
4765 status_run(struct view *view, const char *argv[], char status, enum line_type type)
4766 {
4767 struct status *unmerged = NULL;
4768 char *buf;
4769 struct io io;
4771 if (!io_run(&io, IO_RD, opt_cdup, argv))
4772 return FALSE;
4774 add_line_data(view, NULL, type);
4776 while ((buf = io_get(&io, 0, TRUE))) {
4777 struct status *file = unmerged;
4779 if (!file) {
4780 file = calloc(1, sizeof(*file));
4781 if (!file || !add_line_data(view, file, type))
4782 goto error_out;
4783 }
4785 /* Parse diff info part. */
4786 if (status) {
4787 file->status = status;
4788 if (status == 'A')
4789 string_copy(file->old.rev, NULL_ID);
4791 } else if (!file->status || file == unmerged) {
4792 if (!status_get_diff(file, buf, strlen(buf)))
4793 goto error_out;
4795 buf = io_get(&io, 0, TRUE);
4796 if (!buf)
4797 break;
4799 /* Collapse all modified entries that follow an
4800 * associated unmerged entry. */
4801 if (unmerged == file) {
4802 unmerged->status = 'U';
4803 unmerged = NULL;
4804 } else if (file->status == 'U') {
4805 unmerged = file;
4806 }
4807 }
4809 /* Grab the old name for rename/copy. */
4810 if (!*file->old.name &&
4811 (file->status == 'R' || file->status == 'C')) {
4812 string_ncopy(file->old.name, buf, strlen(buf));
4814 buf = io_get(&io, 0, TRUE);
4815 if (!buf)
4816 break;
4817 }
4819 /* git-ls-files just delivers a NUL separated list of
4820 * file names similar to the second half of the
4821 * git-diff-* output. */
4822 string_ncopy(file->new.name, buf, strlen(buf));
4823 if (!*file->old.name)
4824 string_copy(file->old.name, file->new.name);
4825 file = NULL;
4826 }
4828 if (io_error(&io)) {
4829 error_out:
4830 io_done(&io);
4831 return FALSE;
4832 }
4834 if (!view->line[view->lines - 1].data)
4835 add_line_data(view, NULL, LINE_STAT_NONE);
4837 io_done(&io);
4838 return TRUE;
4839 }
4841 /* Don't show unmerged entries in the staged section. */
4842 static const char *status_diff_index_argv[] = {
4843 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
4844 "--cached", "-M", "HEAD", NULL
4845 };
4847 static const char *status_diff_files_argv[] = {
4848 "git", "diff-files", "-z", NULL
4849 };
4851 static const char *status_list_other_argv[] = {
4852 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
4853 };
4855 static const char *status_list_no_head_argv[] = {
4856 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
4857 };
4859 static const char *update_index_argv[] = {
4860 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
4861 };
4863 /* Restore the previous line number to stay in the context or select a
4864 * line with something that can be updated. */
4865 static void
4866 status_restore(struct view *view)
4867 {
4868 if (view->p_lineno >= view->lines)
4869 view->p_lineno = view->lines - 1;
4870 while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
4871 view->p_lineno++;
4872 while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
4873 view->p_lineno--;
4875 /* If the above fails, always skip the "On branch" line. */
4876 if (view->p_lineno < view->lines)
4877 view->lineno = view->p_lineno;
4878 else
4879 view->lineno = 1;
4881 if (view->lineno < view->offset)
4882 view->offset = view->lineno;
4883 else if (view->offset + view->height <= view->lineno)
4884 view->offset = view->lineno - view->height + 1;
4886 view->p_restore = FALSE;
4887 }
4889 static void
4890 status_update_onbranch(void)
4891 {
4892 static const char *paths[][2] = {
4893 { "rebase-apply/rebasing", "Rebasing" },
4894 { "rebase-apply/applying", "Applying mailbox" },
4895 { "rebase-apply/", "Rebasing mailbox" },
4896 { "rebase-merge/interactive", "Interactive rebase" },
4897 { "rebase-merge/", "Rebase merge" },
4898 { "MERGE_HEAD", "Merging" },
4899 { "BISECT_LOG", "Bisecting" },
4900 { "HEAD", "On branch" },
4901 };
4902 char buf[SIZEOF_STR];
4903 struct stat stat;
4904 int i;
4906 if (is_initial_commit()) {
4907 string_copy(status_onbranch, "Initial commit");
4908 return;
4909 }
4911 for (i = 0; i < ARRAY_SIZE(paths); i++) {
4912 char *head = opt_head;
4914 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
4915 lstat(buf, &stat) < 0)
4916 continue;
4918 if (!*opt_head) {
4919 struct io io;
4921 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
4922 io_read_buf(&io, buf, sizeof(buf))) {
4923 head = buf;
4924 if (!prefixcmp(head, "refs/heads/"))
4925 head += STRING_SIZE("refs/heads/");
4926 }
4927 }
4929 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
4930 string_copy(status_onbranch, opt_head);
4931 return;
4932 }
4934 string_copy(status_onbranch, "Not currently on any branch");
4935 }
4937 /* First parse staged info using git-diff-index(1), then parse unstaged
4938 * info using git-diff-files(1), and finally untracked files using
4939 * git-ls-files(1). */
4940 static bool
4941 status_open(struct view *view)
4942 {
4943 reset_view(view);
4945 add_line_data(view, NULL, LINE_STAT_HEAD);
4946 status_update_onbranch();
4948 io_run_bg(update_index_argv);
4950 if (is_initial_commit()) {
4951 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
4952 return FALSE;
4953 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
4954 return FALSE;
4955 }
4957 if (!opt_untracked_dirs_content)
4958 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
4960 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
4961 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
4962 return FALSE;
4964 /* Restore the exact position or use the specialized restore
4965 * mode? */
4966 if (!view->p_restore)
4967 status_restore(view);
4968 return TRUE;
4969 }
4971 static bool
4972 status_draw(struct view *view, struct line *line, unsigned int lineno)
4973 {
4974 struct status *status = line->data;
4975 enum line_type type;
4976 const char *text;
4978 if (!status) {
4979 switch (line->type) {
4980 case LINE_STAT_STAGED:
4981 type = LINE_STAT_SECTION;
4982 text = "Changes to be committed:";
4983 break;
4985 case LINE_STAT_UNSTAGED:
4986 type = LINE_STAT_SECTION;
4987 text = "Changed but not updated:";
4988 break;
4990 case LINE_STAT_UNTRACKED:
4991 type = LINE_STAT_SECTION;
4992 text = "Untracked files:";
4993 break;
4995 case LINE_STAT_NONE:
4996 type = LINE_DEFAULT;
4997 text = " (no files)";
4998 break;
5000 case LINE_STAT_HEAD:
5001 type = LINE_STAT_HEAD;
5002 text = status_onbranch;
5003 break;
5005 default:
5006 return FALSE;
5007 }
5008 } else {
5009 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5011 buf[0] = status->status;
5012 if (draw_text(view, line->type, buf))
5013 return TRUE;
5014 type = LINE_DEFAULT;
5015 text = status->new.name;
5016 }
5018 draw_text(view, type, text);
5019 return TRUE;
5020 }
5022 static enum request
5023 status_load_error(struct view *view, struct view *stage, const char *path)
5024 {
5025 if (displayed_views() == 2 || display[current_view] != view)
5026 maximize_view(view);
5027 report("Failed to load '%s': %s", path, io_strerror(&stage->io));
5028 return REQ_NONE;
5029 }
5031 static enum request
5032 status_enter(struct view *view, struct line *line)
5033 {
5034 struct status *status = line->data;
5035 const char *oldpath = status ? status->old.name : NULL;
5036 /* Diffs for unmerged entries are empty when passing the new
5037 * path, so leave it empty. */
5038 const char *newpath = status && status->status != 'U' ? status->new.name : NULL;
5039 const char *info;
5040 enum open_flags split;
5041 struct view *stage = VIEW(REQ_VIEW_STAGE);
5043 if (line->type == LINE_STAT_NONE ||
5044 (!status && line[1].type == LINE_STAT_NONE)) {
5045 report("No file to diff");
5046 return REQ_NONE;
5047 }
5049 switch (line->type) {
5050 case LINE_STAT_STAGED:
5051 if (is_initial_commit()) {
5052 const char *no_head_diff_argv[] = {
5053 "git", "diff", "--no-color", "--patch-with-stat",
5054 "--", "/dev/null", newpath, NULL
5055 };
5057 if (!prepare_update(stage, no_head_diff_argv, opt_cdup))
5058 return status_load_error(view, stage, newpath);
5059 } else {
5060 const char *index_show_argv[] = {
5061 "git", "diff-index", "--root", "--patch-with-stat",
5062 "-C", "-M", "--cached", "HEAD", "--",
5063 oldpath, newpath, NULL
5064 };
5066 if (!prepare_update(stage, index_show_argv, opt_cdup))
5067 return status_load_error(view, stage, newpath);
5068 }
5070 if (status)
5071 info = "Staged changes to %s";
5072 else
5073 info = "Staged changes";
5074 break;
5076 case LINE_STAT_UNSTAGED:
5077 {
5078 const char *files_show_argv[] = {
5079 "git", "diff-files", "--root", "--patch-with-stat",
5080 "-C", "-M", "--", oldpath, newpath, NULL
5081 };
5083 if (!prepare_update(stage, files_show_argv, opt_cdup))
5084 return status_load_error(view, stage, newpath);
5085 if (status)
5086 info = "Unstaged changes to %s";
5087 else
5088 info = "Unstaged changes";
5089 break;
5090 }
5091 case LINE_STAT_UNTRACKED:
5092 if (!newpath) {
5093 report("No file to show");
5094 return REQ_NONE;
5095 }
5097 if (!suffixcmp(status->new.name, -1, "/")) {
5098 report("Cannot display a directory");
5099 return REQ_NONE;
5100 }
5102 if (!prepare_update_file(stage, newpath))
5103 return status_load_error(view, stage, newpath);
5104 info = "Untracked file %s";
5105 break;
5107 case LINE_STAT_HEAD:
5108 return REQ_NONE;
5110 default:
5111 die("line type %d not handled in switch", line->type);
5112 }
5114 split = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5115 open_view(view, REQ_VIEW_STAGE, OPEN_PREPARED | split);
5116 if (view_is_displayed(VIEW(REQ_VIEW_STAGE))) {
5117 if (status) {
5118 stage_status = *status;
5119 } else {
5120 memset(&stage_status, 0, sizeof(stage_status));
5121 }
5123 stage_line_type = line->type;
5124 stage_chunks = 0;
5125 string_format(VIEW(REQ_VIEW_STAGE)->ref, info, stage_status.new.name);
5126 }
5128 return REQ_NONE;
5129 }
5131 static bool
5132 status_exists(struct status *status, enum line_type type)
5133 {
5134 struct view *view = VIEW(REQ_VIEW_STATUS);
5135 unsigned long lineno;
5137 for (lineno = 0; lineno < view->lines; lineno++) {
5138 struct line *line = &view->line[lineno];
5139 struct status *pos = line->data;
5141 if (line->type != type)
5142 continue;
5143 if (!pos && (!status || !status->status) && line[1].data) {
5144 select_view_line(view, lineno);
5145 return TRUE;
5146 }
5147 if (pos && !strcmp(status->new.name, pos->new.name)) {
5148 select_view_line(view, lineno);
5149 return TRUE;
5150 }
5151 }
5153 return FALSE;
5154 }
5157 static bool
5158 status_update_prepare(struct io *io, enum line_type type)
5159 {
5160 const char *staged_argv[] = {
5161 "git", "update-index", "-z", "--index-info", NULL
5162 };
5163 const char *others_argv[] = {
5164 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5165 };
5167 switch (type) {
5168 case LINE_STAT_STAGED:
5169 return io_run(io, IO_WR, opt_cdup, staged_argv);
5171 case LINE_STAT_UNSTAGED:
5172 case LINE_STAT_UNTRACKED:
5173 return io_run(io, IO_WR, opt_cdup, others_argv);
5175 default:
5176 die("line type %d not handled in switch", type);
5177 return FALSE;
5178 }
5179 }
5181 static bool
5182 status_update_write(struct io *io, struct status *status, enum line_type type)
5183 {
5184 char buf[SIZEOF_STR];
5185 size_t bufsize = 0;
5187 switch (type) {
5188 case LINE_STAT_STAGED:
5189 if (!string_format_from(buf, &bufsize, "%06o %s\t%s%c",
5190 status->old.mode,
5191 status->old.rev,
5192 status->old.name, 0))
5193 return FALSE;
5194 break;
5196 case LINE_STAT_UNSTAGED:
5197 case LINE_STAT_UNTRACKED:
5198 if (!string_format_from(buf, &bufsize, "%s%c", status->new.name, 0))
5199 return FALSE;
5200 break;
5202 default:
5203 die("line type %d not handled in switch", type);
5204 }
5206 return io_write(io, buf, bufsize);
5207 }
5209 static bool
5210 status_update_file(struct status *status, enum line_type type)
5211 {
5212 struct io io;
5213 bool result;
5215 if (!status_update_prepare(&io, type))
5216 return FALSE;
5218 result = status_update_write(&io, status, type);
5219 return io_done(&io) && result;
5220 }
5222 static bool
5223 status_update_files(struct view *view, struct line *line)
5224 {
5225 char buf[sizeof(view->ref)];
5226 struct io io;
5227 bool result = TRUE;
5228 struct line *pos = view->line + view->lines;
5229 int files = 0;
5230 int file, done;
5231 int cursor_y = -1, cursor_x = -1;
5233 if (!status_update_prepare(&io, line->type))
5234 return FALSE;
5236 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5237 files++;
5239 string_copy(buf, view->ref);
5240 getsyx(cursor_y, cursor_x);
5241 for (file = 0, done = 5; result && file < files; line++, file++) {
5242 int almost_done = file * 100 / files;
5244 if (almost_done > done) {
5245 done = almost_done;
5246 string_format(view->ref, "updating file %u of %u (%d%% done)",
5247 file, files, done);
5248 update_view_title(view);
5249 setsyx(cursor_y, cursor_x);
5250 doupdate();
5251 }
5252 result = status_update_write(&io, line->data, line->type);
5253 }
5254 string_copy(view->ref, buf);
5256 return io_done(&io) && result;
5257 }
5259 static bool
5260 status_update(struct view *view)
5261 {
5262 struct line *line = &view->line[view->lineno];
5264 assert(view->lines);
5266 if (!line->data) {
5267 /* This should work even for the "On branch" line. */
5268 if (line < view->line + view->lines && !line[1].data) {
5269 report("Nothing to update");
5270 return FALSE;
5271 }
5273 if (!status_update_files(view, line + 1)) {
5274 report("Failed to update file status");
5275 return FALSE;
5276 }
5278 } else if (!status_update_file(line->data, line->type)) {
5279 report("Failed to update file status");
5280 return FALSE;
5281 }
5283 return TRUE;
5284 }
5286 static bool
5287 status_revert(struct status *status, enum line_type type, bool has_none)
5288 {
5289 if (!status || type != LINE_STAT_UNSTAGED) {
5290 if (type == LINE_STAT_STAGED) {
5291 report("Cannot revert changes to staged files");
5292 } else if (type == LINE_STAT_UNTRACKED) {
5293 report("Cannot revert changes to untracked files");
5294 } else if (has_none) {
5295 report("Nothing to revert");
5296 } else {
5297 report("Cannot revert changes to multiple files");
5298 }
5300 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5301 char mode[10] = "100644";
5302 const char *reset_argv[] = {
5303 "git", "update-index", "--cacheinfo", mode,
5304 status->old.rev, status->old.name, NULL
5305 };
5306 const char *checkout_argv[] = {
5307 "git", "checkout", "--", status->old.name, NULL
5308 };
5310 if (status->status == 'U') {
5311 string_format(mode, "%5o", status->old.mode);
5313 if (status->old.mode == 0 && status->new.mode == 0) {
5314 reset_argv[2] = "--force-remove";
5315 reset_argv[3] = status->old.name;
5316 reset_argv[4] = NULL;
5317 }
5319 if (!io_run_fg(reset_argv, opt_cdup))
5320 return FALSE;
5321 if (status->old.mode == 0 && status->new.mode == 0)
5322 return TRUE;
5323 }
5325 return io_run_fg(checkout_argv, opt_cdup);
5326 }
5328 return FALSE;
5329 }
5331 static enum request
5332 status_request(struct view *view, enum request request, struct line *line)
5333 {
5334 struct status *status = line->data;
5336 switch (request) {
5337 case REQ_STATUS_UPDATE:
5338 if (!status_update(view))
5339 return REQ_NONE;
5340 break;
5342 case REQ_STATUS_REVERT:
5343 if (!status_revert(status, line->type, status_has_none(view, line)))
5344 return REQ_NONE;
5345 break;
5347 case REQ_STATUS_MERGE:
5348 if (!status || status->status != 'U') {
5349 report("Merging only possible for files with unmerged status ('U').");
5350 return REQ_NONE;
5351 }
5352 open_mergetool(status->new.name);
5353 break;
5355 case REQ_EDIT:
5356 if (!status)
5357 return request;
5358 if (status->status == 'D') {
5359 report("File has been deleted.");
5360 return REQ_NONE;
5361 }
5363 open_editor(status->new.name);
5364 break;
5366 case REQ_VIEW_BLAME:
5367 if (status)
5368 opt_ref[0] = 0;
5369 return request;
5371 case REQ_ENTER:
5372 /* After returning the status view has been split to
5373 * show the stage view. No further reloading is
5374 * necessary. */
5375 return status_enter(view, line);
5377 case REQ_REFRESH:
5378 /* Simply reload the view. */
5379 break;
5381 default:
5382 return request;
5383 }
5385 open_view(view, REQ_VIEW_STATUS, OPEN_RELOAD);
5387 return REQ_NONE;
5388 }
5390 static void
5391 status_select(struct view *view, struct line *line)
5392 {
5393 struct status *status = line->data;
5394 char file[SIZEOF_STR] = "all files";
5395 const char *text;
5396 const char *key;
5398 if (status && !string_format(file, "'%s'", status->new.name))
5399 return;
5401 if (!status && line[1].type == LINE_STAT_NONE)
5402 line++;
5404 switch (line->type) {
5405 case LINE_STAT_STAGED:
5406 text = "Press %s to unstage %s for commit";
5407 break;
5409 case LINE_STAT_UNSTAGED:
5410 text = "Press %s to stage %s for commit";
5411 break;
5413 case LINE_STAT_UNTRACKED:
5414 text = "Press %s to stage %s for addition";
5415 break;
5417 case LINE_STAT_HEAD:
5418 case LINE_STAT_NONE:
5419 text = "Nothing to update";
5420 break;
5422 default:
5423 die("line type %d not handled in switch", line->type);
5424 }
5426 if (status && status->status == 'U') {
5427 text = "Press %s to resolve conflict in %s";
5428 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5430 } else {
5431 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5432 }
5434 string_format(view->ref, text, key, file);
5435 if (status)
5436 string_copy(opt_file, status->new.name);
5437 }
5439 static bool
5440 status_grep(struct view *view, struct line *line)
5441 {
5442 struct status *status = line->data;
5444 if (status) {
5445 const char buf[2] = { status->status, 0 };
5446 const char *text[] = { status->new.name, buf, NULL };
5448 return grep_text(view, text);
5449 }
5451 return FALSE;
5452 }
5454 static struct view_ops status_ops = {
5455 "file",
5456 NULL,
5457 status_open,
5458 NULL,
5459 status_draw,
5460 status_request,
5461 status_grep,
5462 status_select,
5463 };
5466 static bool
5467 stage_diff_write(struct io *io, struct line *line, struct line *end)
5468 {
5469 while (line < end) {
5470 if (!io_write(io, line->data, strlen(line->data)) ||
5471 !io_write(io, "\n", 1))
5472 return FALSE;
5473 line++;
5474 if (line->type == LINE_DIFF_CHUNK ||
5475 line->type == LINE_DIFF_HEADER)
5476 break;
5477 }
5479 return TRUE;
5480 }
5482 static struct line *
5483 stage_diff_find(struct view *view, struct line *line, enum line_type type)
5484 {
5485 for (; view->line < line; line--)
5486 if (line->type == type)
5487 return line;
5489 return NULL;
5490 }
5492 static bool
5493 stage_apply_chunk(struct view *view, struct line *chunk, bool revert)
5494 {
5495 const char *apply_argv[SIZEOF_ARG] = {
5496 "git", "apply", "--whitespace=nowarn", NULL
5497 };
5498 struct line *diff_hdr;
5499 struct io io;
5500 int argc = 3;
5502 diff_hdr = stage_diff_find(view, chunk, LINE_DIFF_HEADER);
5503 if (!diff_hdr)
5504 return FALSE;
5506 if (!revert)
5507 apply_argv[argc++] = "--cached";
5508 if (revert || stage_line_type == LINE_STAT_STAGED)
5509 apply_argv[argc++] = "-R";
5510 apply_argv[argc++] = "-";
5511 apply_argv[argc++] = NULL;
5512 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
5513 return FALSE;
5515 if (!stage_diff_write(&io, diff_hdr, chunk) ||
5516 !stage_diff_write(&io, chunk, view->line + view->lines))
5517 chunk = NULL;
5519 io_done(&io);
5520 io_run_bg(update_index_argv);
5522 return chunk ? TRUE : FALSE;
5523 }
5525 static bool
5526 stage_update(struct view *view, struct line *line)
5527 {
5528 struct line *chunk = NULL;
5530 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
5531 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5533 if (chunk) {
5534 if (!stage_apply_chunk(view, chunk, FALSE)) {
5535 report("Failed to apply chunk");
5536 return FALSE;
5537 }
5539 } else if (!stage_status.status) {
5540 view = VIEW(REQ_VIEW_STATUS);
5542 for (line = view->line; line < view->line + view->lines; line++)
5543 if (line->type == stage_line_type)
5544 break;
5546 if (!status_update_files(view, line + 1)) {
5547 report("Failed to update files");
5548 return FALSE;
5549 }
5551 } else if (!status_update_file(&stage_status, stage_line_type)) {
5552 report("Failed to update file");
5553 return FALSE;
5554 }
5556 return TRUE;
5557 }
5559 static bool
5560 stage_revert(struct view *view, struct line *line)
5561 {
5562 struct line *chunk = NULL;
5564 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
5565 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5567 if (chunk) {
5568 if (!prompt_yesno("Are you sure you want to revert changes?"))
5569 return FALSE;
5571 if (!stage_apply_chunk(view, chunk, TRUE)) {
5572 report("Failed to revert chunk");
5573 return FALSE;
5574 }
5575 return TRUE;
5577 } else {
5578 return status_revert(stage_status.status ? &stage_status : NULL,
5579 stage_line_type, FALSE);
5580 }
5581 }
5584 static void
5585 stage_next(struct view *view, struct line *line)
5586 {
5587 int i;
5589 if (!stage_chunks) {
5590 for (line = view->line; line < view->line + view->lines; line++) {
5591 if (line->type != LINE_DIFF_CHUNK)
5592 continue;
5594 if (!realloc_ints(&stage_chunk, stage_chunks, 1)) {
5595 report("Allocation failure");
5596 return;
5597 }
5599 stage_chunk[stage_chunks++] = line - view->line;
5600 }
5601 }
5603 for (i = 0; i < stage_chunks; i++) {
5604 if (stage_chunk[i] > view->lineno) {
5605 do_scroll_view(view, stage_chunk[i] - view->lineno);
5606 report("Chunk %d of %d", i + 1, stage_chunks);
5607 return;
5608 }
5609 }
5611 report("No next chunk found");
5612 }
5614 static enum request
5615 stage_request(struct view *view, enum request request, struct line *line)
5616 {
5617 switch (request) {
5618 case REQ_STATUS_UPDATE:
5619 if (!stage_update(view, line))
5620 return REQ_NONE;
5621 break;
5623 case REQ_STATUS_REVERT:
5624 if (!stage_revert(view, line))
5625 return REQ_NONE;
5626 break;
5628 case REQ_STAGE_NEXT:
5629 if (stage_line_type == LINE_STAT_UNTRACKED) {
5630 report("File is untracked; press %s to add",
5631 get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
5632 return REQ_NONE;
5633 }
5634 stage_next(view, line);
5635 return REQ_NONE;
5637 case REQ_EDIT:
5638 if (!stage_status.new.name[0])
5639 return request;
5640 if (stage_status.status == 'D') {
5641 report("File has been deleted.");
5642 return REQ_NONE;
5643 }
5645 open_editor(stage_status.new.name);
5646 break;
5648 case REQ_REFRESH:
5649 /* Reload everything ... */
5650 break;
5652 case REQ_VIEW_BLAME:
5653 if (stage_status.new.name[0]) {
5654 string_copy(opt_file, stage_status.new.name);
5655 opt_ref[0] = 0;
5656 }
5657 return request;
5659 case REQ_ENTER:
5660 return pager_request(view, request, line);
5662 default:
5663 return request;
5664 }
5666 VIEW(REQ_VIEW_STATUS)->p_restore = TRUE;
5667 open_view(view, REQ_VIEW_STATUS, OPEN_REFRESH);
5669 /* Check whether the staged entry still exists, and close the
5670 * stage view if it doesn't. */
5671 if (!status_exists(&stage_status, stage_line_type)) {
5672 status_restore(VIEW(REQ_VIEW_STATUS));
5673 return REQ_VIEW_CLOSE;
5674 }
5676 if (stage_line_type == LINE_STAT_UNTRACKED) {
5677 if (!suffixcmp(stage_status.new.name, -1, "/")) {
5678 report("Cannot display a directory");
5679 return REQ_NONE;
5680 }
5682 if (!prepare_update_file(view, stage_status.new.name)) {
5683 report("Failed to open file: %s", strerror(errno));
5684 return REQ_NONE;
5685 }
5686 }
5687 open_view(view, REQ_VIEW_STAGE, OPEN_REFRESH);
5689 return REQ_NONE;
5690 }
5692 static struct view_ops stage_ops = {
5693 "line",
5694 NULL,
5695 NULL,
5696 pager_read,
5697 pager_draw,
5698 stage_request,
5699 pager_grep,
5700 pager_select,
5701 };
5704 /*
5705 * Revision graph
5706 */
5708 static const enum line_type graph_colors[] = {
5709 LINE_GRAPH_LINE_0,
5710 LINE_GRAPH_LINE_1,
5711 LINE_GRAPH_LINE_2,
5712 LINE_GRAPH_LINE_3,
5713 LINE_GRAPH_LINE_4,
5714 LINE_GRAPH_LINE_5,
5715 LINE_GRAPH_LINE_6,
5716 };
5718 static enum line_type get_graph_color(struct graph_symbol *symbol)
5719 {
5720 if (symbol->commit)
5721 return LINE_GRAPH_COMMIT;
5722 assert(symbol->color < ARRAY_SIZE(graph_colors));
5723 return graph_colors[symbol->color];
5724 }
5726 static bool
5727 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5728 {
5729 const char *chars = graph_symbol_to_utf8(symbol);
5731 return draw_text(view, color, chars + !!first);
5732 }
5734 static bool
5735 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5736 {
5737 const char *chars = graph_symbol_to_ascii(symbol);
5739 return draw_text(view, color, chars + !!first);
5740 }
5742 static bool
5743 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5744 {
5745 const chtype *chars = graph_symbol_to_chtype(symbol);
5747 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
5748 }
5750 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
5752 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
5753 {
5754 static const draw_graph_fn fns[] = {
5755 draw_graph_ascii,
5756 draw_graph_chtype,
5757 draw_graph_utf8
5758 };
5759 draw_graph_fn fn = fns[opt_line_graphics];
5760 int i;
5762 for (i = 0; i < canvas->size; i++) {
5763 struct graph_symbol *symbol = &canvas->symbols[i];
5764 enum line_type color = get_graph_color(symbol);
5766 if (fn(view, symbol, color, i == 0))
5767 return TRUE;
5768 }
5770 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
5771 }
5773 /*
5774 * Main view backend
5775 */
5777 struct commit {
5778 char id[SIZEOF_REV]; /* SHA1 ID. */
5779 char title[128]; /* First line of the commit message. */
5780 const char *author; /* Author of the commit. */
5781 struct time time; /* Date from the author ident. */
5782 struct ref_list *refs; /* Repository references. */
5783 struct graph_canvas graph; /* Ancestry chain graphics. */
5784 };
5786 static const char *main_argv[SIZEOF_ARG] = {
5787 "git", "log", "--no-color", "--pretty=raw", "--parents",
5788 "--topo-order", "%(diffargs)", "%(revargs)",
5789 "--", "%(fileargs)", NULL
5790 };
5792 static bool
5793 main_draw(struct view *view, struct line *line, unsigned int lineno)
5794 {
5795 struct commit *commit = line->data;
5797 if (!commit->author)
5798 return FALSE;
5800 if (opt_date && draw_date(view, &commit->time))
5801 return TRUE;
5803 if (opt_author && draw_author(view, commit->author))
5804 return TRUE;
5806 if (opt_rev_graph && draw_graph(view, &commit->graph))
5807 return TRUE;
5809 if (opt_show_refs && commit->refs) {
5810 size_t i;
5812 for (i = 0; i < commit->refs->size; i++) {
5813 struct ref *ref = commit->refs->refs[i];
5814 enum line_type type;
5816 if (ref->head)
5817 type = LINE_MAIN_HEAD;
5818 else if (ref->ltag)
5819 type = LINE_MAIN_LOCAL_TAG;
5820 else if (ref->tag)
5821 type = LINE_MAIN_TAG;
5822 else if (ref->tracked)
5823 type = LINE_MAIN_TRACKED;
5824 else if (ref->remote)
5825 type = LINE_MAIN_REMOTE;
5826 else
5827 type = LINE_MAIN_REF;
5829 if (draw_text(view, type, "[") ||
5830 draw_text(view, type, ref->name) ||
5831 draw_text(view, type, "]"))
5832 return TRUE;
5834 if (draw_text(view, LINE_DEFAULT, " "))
5835 return TRUE;
5836 }
5837 }
5839 draw_text(view, LINE_DEFAULT, commit->title);
5840 return TRUE;
5841 }
5843 /* Reads git log --pretty=raw output and parses it into the commit struct. */
5844 static bool
5845 main_read(struct view *view, char *line)
5846 {
5847 static struct graph graph;
5848 enum line_type type;
5849 struct commit *commit;
5851 if (!line) {
5852 if (!view->lines && !view->prev)
5853 die("No revisions match the given arguments.");
5854 if (view->lines > 0) {
5855 commit = view->line[view->lines - 1].data;
5856 view->line[view->lines - 1].dirty = 1;
5857 if (!commit->author) {
5858 view->lines--;
5859 free(commit);
5860 }
5861 }
5863 done_graph(&graph);
5864 return TRUE;
5865 }
5867 type = get_line_type(line);
5868 if (type == LINE_COMMIT) {
5869 bool is_boundary;
5871 commit = calloc(1, sizeof(struct commit));
5872 if (!commit)
5873 return FALSE;
5875 line += STRING_SIZE("commit ");
5876 is_boundary = *line == '-';
5877 if (is_boundary)
5878 line++;
5880 string_copy_rev(commit->id, line);
5881 commit->refs = get_ref_list(commit->id);
5882 add_line_data(view, commit, LINE_MAIN_COMMIT);
5883 graph_add_commit(&graph, &commit->graph, commit->id, line, is_boundary);
5884 return TRUE;
5885 }
5887 if (!view->lines)
5888 return TRUE;
5889 commit = view->line[view->lines - 1].data;
5891 switch (type) {
5892 case LINE_PARENT:
5893 if (!graph.has_parents)
5894 graph_add_parent(&graph, line + STRING_SIZE("parent "));
5895 break;
5897 case LINE_AUTHOR:
5898 parse_author_line(line + STRING_SIZE("author "),
5899 &commit->author, &commit->time);
5900 graph_render_parents(&graph);
5901 break;
5903 default:
5904 /* Fill in the commit title if it has not already been set. */
5905 if (commit->title[0])
5906 break;
5908 /* Require titles to start with a non-space character at the
5909 * offset used by git log. */
5910 if (strncmp(line, " ", 4))
5911 break;
5912 line += 4;
5913 /* Well, if the title starts with a whitespace character,
5914 * try to be forgiving. Otherwise we end up with no title. */
5915 while (isspace(*line))
5916 line++;
5917 if (*line == '\0')
5918 break;
5919 /* FIXME: More graceful handling of titles; append "..." to
5920 * shortened titles, etc. */
5922 string_expand(commit->title, sizeof(commit->title), line, 1);
5923 view->line[view->lines - 1].dirty = 1;
5924 }
5926 return TRUE;
5927 }
5929 static enum request
5930 main_request(struct view *view, enum request request, struct line *line)
5931 {
5932 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5934 switch (request) {
5935 case REQ_ENTER:
5936 if (view_is_displayed(view) && display[0] != view)
5937 maximize_view(view);
5938 open_view(view, REQ_VIEW_DIFF, flags);
5939 break;
5940 case REQ_REFRESH:
5941 load_refs();
5942 open_view(view, REQ_VIEW_MAIN, OPEN_REFRESH);
5943 break;
5944 default:
5945 return request;
5946 }
5948 return REQ_NONE;
5949 }
5951 static bool
5952 grep_refs(struct ref_list *list, regex_t *regex)
5953 {
5954 regmatch_t pmatch;
5955 size_t i;
5957 if (!opt_show_refs || !list)
5958 return FALSE;
5960 for (i = 0; i < list->size; i++) {
5961 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
5962 return TRUE;
5963 }
5965 return FALSE;
5966 }
5968 static bool
5969 main_grep(struct view *view, struct line *line)
5970 {
5971 struct commit *commit = line->data;
5972 const char *text[] = {
5973 commit->title,
5974 opt_author ? commit->author : "",
5975 mkdate(&commit->time, opt_date),
5976 NULL
5977 };
5979 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
5980 }
5982 static void
5983 main_select(struct view *view, struct line *line)
5984 {
5985 struct commit *commit = line->data;
5987 string_copy_rev(view->ref, commit->id);
5988 string_copy_rev(ref_commit, view->ref);
5989 }
5991 static struct view_ops main_ops = {
5992 "commit",
5993 main_argv,
5994 NULL,
5995 main_read,
5996 main_draw,
5997 main_request,
5998 main_grep,
5999 main_select,
6000 };
6003 /*
6004 * Status management
6005 */
6007 /* Whether or not the curses interface has been initialized. */
6008 static bool cursed = FALSE;
6010 /* Terminal hacks and workarounds. */
6011 static bool use_scroll_redrawwin;
6012 static bool use_scroll_status_wclear;
6014 /* The status window is used for polling keystrokes. */
6015 static WINDOW *status_win;
6017 /* Reading from the prompt? */
6018 static bool input_mode = FALSE;
6020 static bool status_empty = FALSE;
6022 /* Update status and title window. */
6023 static void
6024 report(const char *msg, ...)
6025 {
6026 struct view *view = display[current_view];
6028 if (input_mode)
6029 return;
6031 if (!view) {
6032 char buf[SIZEOF_STR];
6033 va_list args;
6035 va_start(args, msg);
6036 if (vsnprintf(buf, sizeof(buf), msg, args) >= sizeof(buf)) {
6037 buf[sizeof(buf) - 1] = 0;
6038 buf[sizeof(buf) - 2] = '.';
6039 buf[sizeof(buf) - 3] = '.';
6040 buf[sizeof(buf) - 4] = '.';
6041 }
6042 va_end(args);
6043 die("%s", buf);
6044 }
6046 if (!status_empty || *msg) {
6047 va_list args;
6049 va_start(args, msg);
6051 wmove(status_win, 0, 0);
6052 if (view->has_scrolled && use_scroll_status_wclear)
6053 wclear(status_win);
6054 if (*msg) {
6055 vwprintw(status_win, msg, args);
6056 status_empty = FALSE;
6057 } else {
6058 status_empty = TRUE;
6059 }
6060 wclrtoeol(status_win);
6061 wnoutrefresh(status_win);
6063 va_end(args);
6064 }
6066 update_view_title(view);
6067 }
6069 static void
6070 init_display(void)
6071 {
6072 const char *term;
6073 int x, y;
6075 /* Initialize the curses library */
6076 if (isatty(STDIN_FILENO)) {
6077 cursed = !!initscr();
6078 opt_tty = stdin;
6079 } else {
6080 /* Leave stdin and stdout alone when acting as a pager. */
6081 opt_tty = fopen("/dev/tty", "r+");
6082 if (!opt_tty)
6083 die("Failed to open /dev/tty");
6084 cursed = !!newterm(NULL, opt_tty, opt_tty);
6085 }
6087 if (!cursed)
6088 die("Failed to initialize curses");
6090 nonl(); /* Disable conversion and detect newlines from input. */
6091 cbreak(); /* Take input chars one at a time, no wait for \n */
6092 noecho(); /* Don't echo input */
6093 leaveok(stdscr, FALSE);
6095 if (has_colors())
6096 init_colors();
6098 getmaxyx(stdscr, y, x);
6099 status_win = newwin(1, x, y - 1, 0);
6100 if (!status_win)
6101 die("Failed to create status window");
6103 /* Enable keyboard mapping */
6104 keypad(status_win, TRUE);
6105 wbkgdset(status_win, get_line_attr(LINE_STATUS));
6107 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6108 set_tabsize(opt_tab_size);
6109 #else
6110 TABSIZE = opt_tab_size;
6111 #endif
6113 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6114 if (term && !strcmp(term, "gnome-terminal")) {
6115 /* In the gnome-terminal-emulator, the message from
6116 * scrolling up one line when impossible followed by
6117 * scrolling down one line causes corruption of the
6118 * status line. This is fixed by calling wclear. */
6119 use_scroll_status_wclear = TRUE;
6120 use_scroll_redrawwin = FALSE;
6122 } else if (term && !strcmp(term, "xrvt-xpm")) {
6123 /* No problems with full optimizations in xrvt-(unicode)
6124 * and aterm. */
6125 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6127 } else {
6128 /* When scrolling in (u)xterm the last line in the
6129 * scrolling direction will update slowly. */
6130 use_scroll_redrawwin = TRUE;
6131 use_scroll_status_wclear = FALSE;
6132 }
6133 }
6135 static int
6136 get_input(int prompt_position)
6137 {
6138 struct view *view;
6139 int i, key, cursor_y, cursor_x;
6141 if (prompt_position)
6142 input_mode = TRUE;
6144 while (TRUE) {
6145 bool loading = FALSE;
6147 foreach_view (view, i) {
6148 update_view(view);
6149 if (view_is_displayed(view) && view->has_scrolled &&
6150 use_scroll_redrawwin)
6151 redrawwin(view->win);
6152 view->has_scrolled = FALSE;
6153 if (view->pipe)
6154 loading = TRUE;
6155 }
6157 /* Update the cursor position. */
6158 if (prompt_position) {
6159 getbegyx(status_win, cursor_y, cursor_x);
6160 cursor_x = prompt_position;
6161 } else {
6162 view = display[current_view];
6163 getbegyx(view->win, cursor_y, cursor_x);
6164 cursor_x = view->width - 1;
6165 cursor_y += view->lineno - view->offset;
6166 }
6167 setsyx(cursor_y, cursor_x);
6169 /* Refresh, accept single keystroke of input */
6170 doupdate();
6171 nodelay(status_win, loading);
6172 key = wgetch(status_win);
6174 /* wgetch() with nodelay() enabled returns ERR when
6175 * there's no input. */
6176 if (key == ERR) {
6178 } else if (key == KEY_RESIZE) {
6179 int height, width;
6181 getmaxyx(stdscr, height, width);
6183 wresize(status_win, 1, width);
6184 mvwin(status_win, height - 1, 0);
6185 wnoutrefresh(status_win);
6186 resize_display();
6187 redraw_display(TRUE);
6189 } else {
6190 input_mode = FALSE;
6191 return key;
6192 }
6193 }
6194 }
6196 static char *
6197 prompt_input(const char *prompt, input_handler handler, void *data)
6198 {
6199 enum input_status status = INPUT_OK;
6200 static char buf[SIZEOF_STR];
6201 size_t pos = 0;
6203 buf[pos] = 0;
6205 while (status == INPUT_OK || status == INPUT_SKIP) {
6206 int key;
6208 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6209 wclrtoeol(status_win);
6211 key = get_input(pos + 1);
6212 switch (key) {
6213 case KEY_RETURN:
6214 case KEY_ENTER:
6215 case '\n':
6216 status = pos ? INPUT_STOP : INPUT_CANCEL;
6217 break;
6219 case KEY_BACKSPACE:
6220 if (pos > 0)
6221 buf[--pos] = 0;
6222 else
6223 status = INPUT_CANCEL;
6224 break;
6226 case KEY_ESC:
6227 status = INPUT_CANCEL;
6228 break;
6230 default:
6231 if (pos >= sizeof(buf)) {
6232 report("Input string too long");
6233 return NULL;
6234 }
6236 status = handler(data, buf, key);
6237 if (status == INPUT_OK)
6238 buf[pos++] = (char) key;
6239 }
6240 }
6242 /* Clear the status window */
6243 status_empty = FALSE;
6244 report("");
6246 if (status == INPUT_CANCEL)
6247 return NULL;
6249 buf[pos++] = 0;
6251 return buf;
6252 }
6254 static enum input_status
6255 prompt_yesno_handler(void *data, char *buf, int c)
6256 {
6257 if (c == 'y' || c == 'Y')
6258 return INPUT_STOP;
6259 if (c == 'n' || c == 'N')
6260 return INPUT_CANCEL;
6261 return INPUT_SKIP;
6262 }
6264 static bool
6265 prompt_yesno(const char *prompt)
6266 {
6267 char prompt2[SIZEOF_STR];
6269 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6270 return FALSE;
6272 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6273 }
6275 static enum input_status
6276 read_prompt_handler(void *data, char *buf, int c)
6277 {
6278 return isprint(c) ? INPUT_OK : INPUT_SKIP;
6279 }
6281 static char *
6282 read_prompt(const char *prompt)
6283 {
6284 return prompt_input(prompt, read_prompt_handler, NULL);
6285 }
6287 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6288 {
6289 enum input_status status = INPUT_OK;
6290 int size = 0;
6292 while (items[size].text)
6293 size++;
6295 while (status == INPUT_OK) {
6296 const struct menu_item *item = &items[*selected];
6297 int key;
6298 int i;
6300 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6301 prompt, *selected + 1, size);
6302 if (item->hotkey)
6303 wprintw(status_win, "[%c] ", (char) item->hotkey);
6304 wprintw(status_win, "%s", item->text);
6305 wclrtoeol(status_win);
6307 key = get_input(COLS - 1);
6308 switch (key) {
6309 case KEY_RETURN:
6310 case KEY_ENTER:
6311 case '\n':
6312 status = INPUT_STOP;
6313 break;
6315 case KEY_LEFT:
6316 case KEY_UP:
6317 *selected = *selected - 1;
6318 if (*selected < 0)
6319 *selected = size - 1;
6320 break;
6322 case KEY_RIGHT:
6323 case KEY_DOWN:
6324 *selected = (*selected + 1) % size;
6325 break;
6327 case KEY_ESC:
6328 status = INPUT_CANCEL;
6329 break;
6331 default:
6332 for (i = 0; items[i].text; i++)
6333 if (items[i].hotkey == key) {
6334 *selected = i;
6335 status = INPUT_STOP;
6336 break;
6337 }
6338 }
6339 }
6341 /* Clear the status window */
6342 status_empty = FALSE;
6343 report("");
6345 return status != INPUT_CANCEL;
6346 }
6348 /*
6349 * Repository properties
6350 */
6352 static struct ref **refs = NULL;
6353 static size_t refs_size = 0;
6354 static struct ref *refs_head = NULL;
6356 static struct ref_list **ref_lists = NULL;
6357 static size_t ref_lists_size = 0;
6359 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
6360 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
6361 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
6363 static int
6364 compare_refs(const void *ref1_, const void *ref2_)
6365 {
6366 const struct ref *ref1 = *(const struct ref **)ref1_;
6367 const struct ref *ref2 = *(const struct ref **)ref2_;
6369 if (ref1->tag != ref2->tag)
6370 return ref2->tag - ref1->tag;
6371 if (ref1->ltag != ref2->ltag)
6372 return ref2->ltag - ref2->ltag;
6373 if (ref1->head != ref2->head)
6374 return ref2->head - ref1->head;
6375 if (ref1->tracked != ref2->tracked)
6376 return ref2->tracked - ref1->tracked;
6377 if (ref1->remote != ref2->remote)
6378 return ref2->remote - ref1->remote;
6379 return strcmp(ref1->name, ref2->name);
6380 }
6382 static void
6383 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
6384 {
6385 size_t i;
6387 for (i = 0; i < refs_size; i++)
6388 if (!visitor(data, refs[i]))
6389 break;
6390 }
6392 static struct ref *
6393 get_ref_head()
6394 {
6395 return refs_head;
6396 }
6398 static struct ref_list *
6399 get_ref_list(const char *id)
6400 {
6401 struct ref_list *list;
6402 size_t i;
6404 for (i = 0; i < ref_lists_size; i++)
6405 if (!strcmp(id, ref_lists[i]->id))
6406 return ref_lists[i];
6408 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
6409 return NULL;
6410 list = calloc(1, sizeof(*list));
6411 if (!list)
6412 return NULL;
6414 for (i = 0; i < refs_size; i++) {
6415 if (!strcmp(id, refs[i]->id) &&
6416 realloc_refs_list(&list->refs, list->size, 1))
6417 list->refs[list->size++] = refs[i];
6418 }
6420 if (!list->refs) {
6421 free(list);
6422 return NULL;
6423 }
6425 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
6426 ref_lists[ref_lists_size++] = list;
6427 return list;
6428 }
6430 static int
6431 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
6432 {
6433 struct ref *ref = NULL;
6434 bool tag = FALSE;
6435 bool ltag = FALSE;
6436 bool remote = FALSE;
6437 bool tracked = FALSE;
6438 bool head = FALSE;
6439 int from = 0, to = refs_size - 1;
6441 if (!prefixcmp(name, "refs/tags/")) {
6442 if (!suffixcmp(name, namelen, "^{}")) {
6443 namelen -= 3;
6444 name[namelen] = 0;
6445 } else {
6446 ltag = TRUE;
6447 }
6449 tag = TRUE;
6450 namelen -= STRING_SIZE("refs/tags/");
6451 name += STRING_SIZE("refs/tags/");
6453 } else if (!prefixcmp(name, "refs/remotes/")) {
6454 remote = TRUE;
6455 namelen -= STRING_SIZE("refs/remotes/");
6456 name += STRING_SIZE("refs/remotes/");
6457 tracked = !strcmp(opt_remote, name);
6459 } else if (!prefixcmp(name, "refs/heads/")) {
6460 namelen -= STRING_SIZE("refs/heads/");
6461 name += STRING_SIZE("refs/heads/");
6462 if (!strncmp(opt_head, name, namelen))
6463 return OK;
6465 } else if (!strcmp(name, "HEAD")) {
6466 head = TRUE;
6467 if (*opt_head) {
6468 namelen = strlen(opt_head);
6469 name = opt_head;
6470 }
6471 }
6473 /* If we are reloading or it's an annotated tag, replace the
6474 * previous SHA1 with the resolved commit id; relies on the fact
6475 * git-ls-remote lists the commit id of an annotated tag right
6476 * before the commit id it points to. */
6477 while (from <= to) {
6478 size_t pos = (to + from) / 2;
6479 int cmp = strcmp(name, refs[pos]->name);
6481 if (!cmp) {
6482 ref = refs[pos];
6483 break;
6484 }
6486 if (cmp < 0)
6487 to = pos - 1;
6488 else
6489 from = pos + 1;
6490 }
6492 if (!ref) {
6493 if (!realloc_refs(&refs, refs_size, 1))
6494 return ERR;
6495 ref = calloc(1, sizeof(*ref) + namelen);
6496 if (!ref)
6497 return ERR;
6498 memmove(refs + from + 1, refs + from,
6499 (refs_size - from) * sizeof(*refs));
6500 refs[from] = ref;
6501 strncpy(ref->name, name, namelen);
6502 refs_size++;
6503 }
6505 ref->head = head;
6506 ref->tag = tag;
6507 ref->ltag = ltag;
6508 ref->remote = remote;
6509 ref->tracked = tracked;
6510 string_copy_rev(ref->id, id);
6512 if (head)
6513 refs_head = ref;
6514 return OK;
6515 }
6517 static int
6518 load_refs(void)
6519 {
6520 const char *head_argv[] = {
6521 "git", "symbolic-ref", "HEAD", NULL
6522 };
6523 static const char *ls_remote_argv[SIZEOF_ARG] = {
6524 "git", "ls-remote", opt_git_dir, NULL
6525 };
6526 static bool init = FALSE;
6527 size_t i;
6529 if (!init) {
6530 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
6531 die("TIG_LS_REMOTE contains too many arguments");
6532 init = TRUE;
6533 }
6535 if (!*opt_git_dir)
6536 return OK;
6538 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
6539 !prefixcmp(opt_head, "refs/heads/")) {
6540 char *offset = opt_head + STRING_SIZE("refs/heads/");
6542 memmove(opt_head, offset, strlen(offset) + 1);
6543 }
6545 refs_head = NULL;
6546 for (i = 0; i < refs_size; i++)
6547 refs[i]->id[0] = 0;
6549 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
6550 return ERR;
6552 /* Update the ref lists to reflect changes. */
6553 for (i = 0; i < ref_lists_size; i++) {
6554 struct ref_list *list = ref_lists[i];
6555 size_t old, new;
6557 for (old = new = 0; old < list->size; old++)
6558 if (!strcmp(list->id, list->refs[old]->id))
6559 list->refs[new++] = list->refs[old];
6560 list->size = new;
6561 }
6563 return OK;
6564 }
6566 static void
6567 set_remote_branch(const char *name, const char *value, size_t valuelen)
6568 {
6569 if (!strcmp(name, ".remote")) {
6570 string_ncopy(opt_remote, value, valuelen);
6572 } else if (*opt_remote && !strcmp(name, ".merge")) {
6573 size_t from = strlen(opt_remote);
6575 if (!prefixcmp(value, "refs/heads/"))
6576 value += STRING_SIZE("refs/heads/");
6578 if (!string_format_from(opt_remote, &from, "/%s", value))
6579 opt_remote[0] = 0;
6580 }
6581 }
6583 static void
6584 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
6585 {
6586 const char *argv[SIZEOF_ARG] = { name, "=" };
6587 int argc = 1 + (cmd == option_set_command);
6588 enum option_code error;
6590 if (!argv_from_string(argv, &argc, value))
6591 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
6592 else
6593 error = cmd(argc, argv);
6595 if (error != OPT_OK)
6596 warn("Option 'tig.%s': %s", name, option_errors[error]);
6597 }
6599 static bool
6600 set_environment_variable(const char *name, const char *value)
6601 {
6602 size_t len = strlen(name) + 1 + strlen(value) + 1;
6603 char *env = malloc(len);
6605 if (env &&
6606 string_nformat(env, len, NULL, "%s=%s", name, value) &&
6607 putenv(env) == 0)
6608 return TRUE;
6609 free(env);
6610 return FALSE;
6611 }
6613 static void
6614 set_work_tree(const char *value)
6615 {
6616 char cwd[SIZEOF_STR];
6618 if (!getcwd(cwd, sizeof(cwd)))
6619 die("Failed to get cwd path: %s", strerror(errno));
6620 if (chdir(opt_git_dir) < 0)
6621 die("Failed to chdir(%s): %s", strerror(errno));
6622 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
6623 die("Failed to get git path: %s", strerror(errno));
6624 if (chdir(cwd) < 0)
6625 die("Failed to chdir(%s): %s", cwd, strerror(errno));
6626 if (chdir(value) < 0)
6627 die("Failed to chdir(%s): %s", value, strerror(errno));
6628 if (!getcwd(cwd, sizeof(cwd)))
6629 die("Failed to get cwd path: %s", strerror(errno));
6630 if (!set_environment_variable("GIT_WORK_TREE", cwd))
6631 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
6632 if (!set_environment_variable("GIT_DIR", opt_git_dir))
6633 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
6634 opt_is_inside_work_tree = TRUE;
6635 }
6637 static int
6638 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6639 {
6640 if (!strcmp(name, "i18n.commitencoding"))
6641 string_ncopy(opt_encoding, value, valuelen);
6643 else if (!strcmp(name, "core.editor"))
6644 string_ncopy(opt_editor, value, valuelen);
6646 else if (!strcmp(name, "core.worktree"))
6647 set_work_tree(value);
6649 else if (!prefixcmp(name, "tig.color."))
6650 set_repo_config_option(name + 10, value, option_color_command);
6652 else if (!prefixcmp(name, "tig.bind."))
6653 set_repo_config_option(name + 9, value, option_bind_command);
6655 else if (!prefixcmp(name, "tig."))
6656 set_repo_config_option(name + 4, value, option_set_command);
6658 else if (*opt_head && !prefixcmp(name, "branch.") &&
6659 !strncmp(name + 7, opt_head, strlen(opt_head)))
6660 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
6662 return OK;
6663 }
6665 static int
6666 load_git_config(void)
6667 {
6668 const char *config_list_argv[] = { "git", "config", "--list", NULL };
6670 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
6671 }
6673 static int
6674 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6675 {
6676 if (!opt_git_dir[0]) {
6677 string_ncopy(opt_git_dir, name, namelen);
6679 } else if (opt_is_inside_work_tree == -1) {
6680 /* This can be 3 different values depending on the
6681 * version of git being used. If git-rev-parse does not
6682 * understand --is-inside-work-tree it will simply echo
6683 * the option else either "true" or "false" is printed.
6684 * Default to true for the unknown case. */
6685 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
6687 } else if (*name == '.') {
6688 string_ncopy(opt_cdup, name, namelen);
6690 } else {
6691 string_ncopy(opt_prefix, name, namelen);
6692 }
6694 return OK;
6695 }
6697 static int
6698 load_repo_info(void)
6699 {
6700 const char *rev_parse_argv[] = {
6701 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
6702 "--show-cdup", "--show-prefix", NULL
6703 };
6705 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
6706 }
6709 /*
6710 * Main
6711 */
6713 static const char usage[] =
6714 "tig " TIG_VERSION " (" __DATE__ ")\n"
6715 "\n"
6716 "Usage: tig [options] [revs] [--] [paths]\n"
6717 " or: tig show [options] [revs] [--] [paths]\n"
6718 " or: tig blame [options] [rev] [--] path\n"
6719 " or: tig status\n"
6720 " or: tig < [git command output]\n"
6721 "\n"
6722 "Options:\n"
6723 " -v, --version Show version and exit\n"
6724 " -h, --help Show help message and exit";
6726 static void __NORETURN
6727 quit(int sig)
6728 {
6729 /* XXX: Restore tty modes and let the OS cleanup the rest! */
6730 if (cursed)
6731 endwin();
6732 exit(0);
6733 }
6735 static void __NORETURN
6736 die(const char *err, ...)
6737 {
6738 va_list args;
6740 endwin();
6742 va_start(args, err);
6743 fputs("tig: ", stderr);
6744 vfprintf(stderr, err, args);
6745 fputs("\n", stderr);
6746 va_end(args);
6748 exit(1);
6749 }
6751 static void
6752 warn(const char *msg, ...)
6753 {
6754 va_list args;
6756 va_start(args, msg);
6757 fputs("tig warning: ", stderr);
6758 vfprintf(stderr, msg, args);
6759 fputs("\n", stderr);
6760 va_end(args);
6761 }
6763 static int
6764 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6765 {
6766 const char ***filter_args = data;
6768 return argv_append(filter_args, name) ? OK : ERR;
6769 }
6771 static void
6772 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
6773 {
6774 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
6775 const char **all_argv = NULL;
6777 if (!argv_append_array(&all_argv, rev_parse_argv) ||
6778 !argv_append_array(&all_argv, argv) ||
6779 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
6780 die("Failed to split arguments");
6781 argv_free(all_argv);
6782 free(all_argv);
6783 }
6785 static void
6786 filter_options(const char *argv[])
6787 {
6788 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
6789 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
6790 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
6791 }
6793 static enum request
6794 parse_options(int argc, const char *argv[])
6795 {
6796 enum request request = REQ_VIEW_MAIN;
6797 const char *subcommand;
6798 bool seen_dashdash = FALSE;
6799 const char **filter_argv = NULL;
6800 int i;
6802 if (!isatty(STDIN_FILENO))
6803 return REQ_VIEW_PAGER;
6805 if (argc <= 1)
6806 return REQ_VIEW_MAIN;
6808 subcommand = argv[1];
6809 if (!strcmp(subcommand, "status")) {
6810 if (argc > 2)
6811 warn("ignoring arguments after `%s'", subcommand);
6812 return REQ_VIEW_STATUS;
6814 } else if (!strcmp(subcommand, "blame")) {
6815 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv + 2);
6816 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv + 2);
6817 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv + 2);
6819 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
6820 die("invalid number of options to blame\n\n%s", usage);
6822 if (opt_rev_argv) {
6823 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
6824 }
6826 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
6827 return REQ_VIEW_BLAME;
6829 } else if (!strcmp(subcommand, "show")) {
6830 request = REQ_VIEW_DIFF;
6832 } else {
6833 subcommand = NULL;
6834 }
6836 for (i = 1 + !!subcommand; i < argc; i++) {
6837 const char *opt = argv[i];
6839 if (seen_dashdash) {
6840 argv_append(&opt_file_argv, opt);
6841 continue;
6843 } else if (!strcmp(opt, "--")) {
6844 seen_dashdash = TRUE;
6845 continue;
6847 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
6848 printf("tig version %s\n", TIG_VERSION);
6849 quit(0);
6851 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
6852 printf("%s\n", usage);
6853 quit(0);
6855 } else if (!strcmp(opt, "--all")) {
6856 argv_append(&opt_rev_argv, opt);
6857 continue;
6858 }
6860 if (!argv_append(&filter_argv, opt))
6861 die("command too long");
6862 }
6864 if (filter_argv)
6865 filter_options(filter_argv);
6867 return request;
6868 }
6870 int
6871 main(int argc, const char *argv[])
6872 {
6873 const char *codeset = "UTF-8";
6874 enum request request = parse_options(argc, argv);
6875 struct view *view;
6877 signal(SIGINT, quit);
6878 signal(SIGPIPE, SIG_IGN);
6880 if (setlocale(LC_ALL, "")) {
6881 codeset = nl_langinfo(CODESET);
6882 }
6884 if (load_repo_info() == ERR)
6885 die("Failed to load repo info.");
6887 if (load_options() == ERR)
6888 die("Failed to load user config.");
6890 if (load_git_config() == ERR)
6891 die("Failed to load repo config.");
6893 /* Require a git repository unless when running in pager mode. */
6894 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
6895 die("Not a git repository");
6897 if (*opt_encoding && strcmp(codeset, "UTF-8")) {
6898 opt_iconv_in = iconv_open("UTF-8", opt_encoding);
6899 if (opt_iconv_in == ICONV_NONE)
6900 die("Failed to initialize character set conversion");
6901 }
6903 if (codeset && strcmp(codeset, "UTF-8")) {
6904 opt_iconv_out = iconv_open(codeset, "UTF-8");
6905 if (opt_iconv_out == ICONV_NONE)
6906 die("Failed to initialize character set conversion");
6907 }
6909 if (load_refs() == ERR)
6910 die("Failed to load refs.");
6912 init_display();
6914 while (view_driver(display[current_view], request)) {
6915 int key = get_input(0);
6917 view = display[current_view];
6918 request = get_keybinding(view->keymap, key);
6920 /* Some low-level request handling. This keeps access to
6921 * status_win restricted. */
6922 switch (request) {
6923 case REQ_NONE:
6924 report("Unknown key, press %s for help",
6925 get_key(view->keymap, REQ_VIEW_HELP));
6926 break;
6927 case REQ_PROMPT:
6928 {
6929 char *cmd = read_prompt(":");
6931 if (cmd && isdigit(*cmd)) {
6932 int lineno = view->lineno + 1;
6934 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OK) {
6935 select_view_line(view, lineno - 1);
6936 report("");
6937 } else {
6938 report("Unable to parse '%s' as a line number", cmd);
6939 }
6941 } else if (cmd) {
6942 struct view *next = VIEW(REQ_VIEW_PAGER);
6943 const char *argv[SIZEOF_ARG] = { "git" };
6944 int argc = 1;
6946 /* When running random commands, initially show the
6947 * command in the title. However, it maybe later be
6948 * overwritten if a commit line is selected. */
6949 string_ncopy(next->ref, cmd, strlen(cmd));
6951 if (!argv_from_string(argv, &argc, cmd)) {
6952 report("Too many arguments");
6953 } else if (!prepare_update(next, argv, NULL)) {
6954 report("Failed to format command");
6955 } else {
6956 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
6957 }
6958 }
6960 request = REQ_NONE;
6961 break;
6962 }
6963 case REQ_SEARCH:
6964 case REQ_SEARCH_BACK:
6965 {
6966 const char *prompt = request == REQ_SEARCH ? "/" : "?";
6967 char *search = read_prompt(prompt);
6969 if (search)
6970 string_ncopy(opt_search, search, strlen(search));
6971 else if (*opt_search)
6972 request = request == REQ_SEARCH ?
6973 REQ_FIND_NEXT :
6974 REQ_FIND_PREV;
6975 else
6976 request = REQ_NONE;
6977 break;
6978 }
6979 default:
6980 break;
6981 }
6982 }
6984 quit(0);
6986 return 0;
6987 }