e60b717c90d0d4f9be73f76aee418c214fce4731
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 }
210 #define author_trim(cols) (cols == 0 || cols > 5)
212 static const char *
213 mkauthor(const char *text, int cols, enum author author)
214 {
215 bool trim = author_trim(cols);
216 bool abbreviate = author == AUTHOR_ABBREVIATED || !trim;
218 if (!author)
219 return "";
220 if (abbreviate && text)
221 return get_author_initials(text);
222 return text;
223 }
225 static const char *
226 mkmode(mode_t mode)
227 {
228 if (S_ISDIR(mode))
229 return "drwxr-xr-x";
230 else if (S_ISLNK(mode))
231 return "lrwxrwxrwx";
232 else if (S_ISGITLINK(mode))
233 return "m---------";
234 else if (S_ISREG(mode) && mode & S_IXUSR)
235 return "-rwxr-xr-x";
236 else if (S_ISREG(mode))
237 return "-rw-r--r--";
238 else
239 return "----------";
240 }
243 /*
244 * User requests
245 */
247 #define REQ_INFO \
248 /* XXX: Keep the view request first and in sync with views[]. */ \
249 REQ_GROUP("View switching") \
250 REQ_(VIEW_MAIN, "Show main view"), \
251 REQ_(VIEW_DIFF, "Show diff view"), \
252 REQ_(VIEW_LOG, "Show log view"), \
253 REQ_(VIEW_TREE, "Show tree view"), \
254 REQ_(VIEW_BLOB, "Show blob view"), \
255 REQ_(VIEW_BLAME, "Show blame view"), \
256 REQ_(VIEW_BRANCH, "Show branch view"), \
257 REQ_(VIEW_HELP, "Show help page"), \
258 REQ_(VIEW_PAGER, "Show pager view"), \
259 REQ_(VIEW_STATUS, "Show status view"), \
260 REQ_(VIEW_STAGE, "Show stage view"), \
261 \
262 REQ_GROUP("View manipulation") \
263 REQ_(ENTER, "Enter current line and scroll"), \
264 REQ_(NEXT, "Move to next"), \
265 REQ_(PREVIOUS, "Move to previous"), \
266 REQ_(PARENT, "Move to parent"), \
267 REQ_(VIEW_NEXT, "Move focus to next view"), \
268 REQ_(REFRESH, "Reload and refresh"), \
269 REQ_(MAXIMIZE, "Maximize the current view"), \
270 REQ_(VIEW_CLOSE, "Close the current view"), \
271 REQ_(QUIT, "Close all views and quit"), \
272 \
273 REQ_GROUP("View specific requests") \
274 REQ_(STATUS_UPDATE, "Update file status"), \
275 REQ_(STATUS_REVERT, "Revert file changes"), \
276 REQ_(STATUS_MERGE, "Merge file using external tool"), \
277 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
278 \
279 REQ_GROUP("Cursor navigation") \
280 REQ_(MOVE_UP, "Move cursor one line up"), \
281 REQ_(MOVE_DOWN, "Move cursor one line down"), \
282 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
283 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
284 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
285 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
286 \
287 REQ_GROUP("Scrolling") \
288 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
289 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
290 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
291 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
292 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
293 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
294 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
295 \
296 REQ_GROUP("Searching") \
297 REQ_(SEARCH, "Search the view"), \
298 REQ_(SEARCH_BACK, "Search backwards in the view"), \
299 REQ_(FIND_NEXT, "Find next search match"), \
300 REQ_(FIND_PREV, "Find previous search match"), \
301 \
302 REQ_GROUP("Option manipulation") \
303 REQ_(OPTIONS, "Open option menu"), \
304 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
305 REQ_(TOGGLE_DATE, "Toggle date display"), \
306 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
307 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
308 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
309 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
310 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
311 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
312 \
313 REQ_GROUP("Misc") \
314 REQ_(PROMPT, "Bring up the prompt"), \
315 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
316 REQ_(SHOW_VERSION, "Show version information"), \
317 REQ_(STOP_LOADING, "Stop all loading views"), \
318 REQ_(EDIT, "Open in editor"), \
319 REQ_(NONE, "Do nothing")
322 /* User action requests. */
323 enum request {
324 #define REQ_GROUP(help)
325 #define REQ_(req, help) REQ_##req
327 /* Offset all requests to avoid conflicts with ncurses getch values. */
328 REQ_UNKNOWN = KEY_MAX + 1,
329 REQ_OFFSET,
330 REQ_INFO
332 #undef REQ_GROUP
333 #undef REQ_
334 };
336 struct request_info {
337 enum request request;
338 const char *name;
339 int namelen;
340 const char *help;
341 };
343 static const struct request_info req_info[] = {
344 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
345 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
346 REQ_INFO
347 #undef REQ_GROUP
348 #undef REQ_
349 };
351 static enum request
352 get_request(const char *name)
353 {
354 int namelen = strlen(name);
355 int i;
357 for (i = 0; i < ARRAY_SIZE(req_info); i++)
358 if (enum_equals(req_info[i], name, namelen))
359 return req_info[i].request;
361 return REQ_UNKNOWN;
362 }
365 /*
366 * Options
367 */
369 /* Option and state variables. */
370 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
371 static enum date opt_date = DATE_DEFAULT;
372 static enum author opt_author = AUTHOR_DEFAULT;
373 static bool opt_rev_graph = TRUE;
374 static bool opt_line_number = FALSE;
375 static bool opt_show_refs = TRUE;
376 static bool opt_untracked_dirs_content = TRUE;
377 static int opt_num_interval = 5;
378 static double opt_hscroll = 0.50;
379 static double opt_scale_split_view = 2.0 / 3.0;
380 static int opt_tab_size = 8;
381 static int opt_author_cols = AUTHOR_COLS;
382 static char opt_path[SIZEOF_STR] = "";
383 static char opt_file[SIZEOF_STR] = "";
384 static char opt_ref[SIZEOF_REF] = "";
385 static char opt_head[SIZEOF_REF] = "";
386 static char opt_remote[SIZEOF_REF] = "";
387 static char opt_encoding[20] = "UTF-8";
388 static iconv_t opt_iconv_in = ICONV_NONE;
389 static iconv_t opt_iconv_out = ICONV_NONE;
390 static char opt_search[SIZEOF_STR] = "";
391 static char opt_cdup[SIZEOF_STR] = "";
392 static char opt_prefix[SIZEOF_STR] = "";
393 static char opt_git_dir[SIZEOF_STR] = "";
394 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
395 static char opt_editor[SIZEOF_STR] = "";
396 static FILE *opt_tty = NULL;
397 static const char **opt_diff_argv = NULL;
398 static const char **opt_rev_argv = NULL;
399 static const char **opt_file_argv = NULL;
400 static const char **opt_blame_argv = NULL;
402 #define is_initial_commit() (!get_ref_head())
403 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
406 /*
407 * Line-oriented content detection.
408 */
410 #define LINE_INFO \
411 LINE(DIFF_HEADER, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
412 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
413 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
414 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
415 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
416 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
417 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
418 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
419 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
420 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
421 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
422 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
423 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
424 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
425 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
426 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
427 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
428 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
429 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
430 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
431 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
432 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
433 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
434 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
435 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
436 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
437 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
438 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
439 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
440 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
441 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
442 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
443 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
444 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
445 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
446 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
447 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
448 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
449 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
450 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
451 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
452 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
453 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
454 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
455 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
456 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
457 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
458 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
459 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
460 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
461 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
462 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
463 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
464 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
465 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
466 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
467 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
468 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
469 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
470 LINE(GRAPH_LINE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
471 LINE(GRAPH_LINE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
472 LINE(GRAPH_LINE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
473 LINE(GRAPH_LINE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
474 LINE(GRAPH_LINE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
475 LINE(GRAPH_LINE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
476 LINE(GRAPH_LINE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
477 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
479 enum line_type {
480 #define LINE(type, line, fg, bg, attr) \
481 LINE_##type
482 LINE_INFO,
483 LINE_NONE
484 #undef LINE
485 };
487 struct line_info {
488 const char *name; /* Option name. */
489 int namelen; /* Size of option name. */
490 const char *line; /* The start of line to match. */
491 int linelen; /* Size of string to match. */
492 int fg, bg, attr; /* Color and text attributes for the lines. */
493 };
495 static struct line_info line_info[] = {
496 #define LINE(type, line, fg, bg, attr) \
497 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
498 LINE_INFO
499 #undef LINE
500 };
502 static enum line_type
503 get_line_type(const char *line)
504 {
505 int linelen = strlen(line);
506 enum line_type type;
508 for (type = 0; type < ARRAY_SIZE(line_info); type++)
509 /* Case insensitive search matches Signed-off-by lines better. */
510 if (linelen >= line_info[type].linelen &&
511 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
512 return type;
514 return LINE_DEFAULT;
515 }
517 static inline int
518 get_line_attr(enum line_type type)
519 {
520 assert(type < ARRAY_SIZE(line_info));
521 return COLOR_PAIR(type) | line_info[type].attr;
522 }
524 static struct line_info *
525 get_line_info(const char *name)
526 {
527 size_t namelen = strlen(name);
528 enum line_type type;
530 for (type = 0; type < ARRAY_SIZE(line_info); type++)
531 if (enum_equals(line_info[type], name, namelen))
532 return &line_info[type];
534 return NULL;
535 }
537 static void
538 init_colors(void)
539 {
540 int default_bg = line_info[LINE_DEFAULT].bg;
541 int default_fg = line_info[LINE_DEFAULT].fg;
542 enum line_type type;
544 start_color();
546 if (assume_default_colors(default_fg, default_bg) == ERR) {
547 default_bg = COLOR_BLACK;
548 default_fg = COLOR_WHITE;
549 }
551 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
552 struct line_info *info = &line_info[type];
553 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
554 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
556 init_pair(type, fg, bg);
557 }
558 }
560 struct line {
561 enum line_type type;
563 /* State flags */
564 unsigned int selected:1;
565 unsigned int dirty:1;
566 unsigned int cleareol:1;
567 unsigned int other:16;
569 void *data; /* User data */
570 };
573 /*
574 * Keys
575 */
577 struct keybinding {
578 int alias;
579 enum request request;
580 };
582 static struct keybinding default_keybindings[] = {
583 /* View switching */
584 { 'm', REQ_VIEW_MAIN },
585 { 'd', REQ_VIEW_DIFF },
586 { 'l', REQ_VIEW_LOG },
587 { 't', REQ_VIEW_TREE },
588 { 'f', REQ_VIEW_BLOB },
589 { 'B', REQ_VIEW_BLAME },
590 { 'H', REQ_VIEW_BRANCH },
591 { 'p', REQ_VIEW_PAGER },
592 { 'h', REQ_VIEW_HELP },
593 { 'S', REQ_VIEW_STATUS },
594 { 'c', REQ_VIEW_STAGE },
596 /* View manipulation */
597 { 'q', REQ_VIEW_CLOSE },
598 { KEY_TAB, REQ_VIEW_NEXT },
599 { KEY_RETURN, REQ_ENTER },
600 { KEY_UP, REQ_PREVIOUS },
601 { KEY_CTL('P'), REQ_PREVIOUS },
602 { KEY_DOWN, REQ_NEXT },
603 { KEY_CTL('N'), REQ_NEXT },
604 { 'R', REQ_REFRESH },
605 { KEY_F(5), REQ_REFRESH },
606 { 'O', REQ_MAXIMIZE },
608 /* Cursor navigation */
609 { 'k', REQ_MOVE_UP },
610 { 'j', REQ_MOVE_DOWN },
611 { KEY_HOME, REQ_MOVE_FIRST_LINE },
612 { KEY_END, REQ_MOVE_LAST_LINE },
613 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
614 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
615 { ' ', REQ_MOVE_PAGE_DOWN },
616 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
617 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
618 { 'b', REQ_MOVE_PAGE_UP },
619 { '-', REQ_MOVE_PAGE_UP },
621 /* Scrolling */
622 { '|', REQ_SCROLL_FIRST_COL },
623 { KEY_LEFT, REQ_SCROLL_LEFT },
624 { KEY_RIGHT, REQ_SCROLL_RIGHT },
625 { KEY_IC, REQ_SCROLL_LINE_UP },
626 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
627 { KEY_DC, REQ_SCROLL_LINE_DOWN },
628 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
629 { 'w', REQ_SCROLL_PAGE_UP },
630 { 's', REQ_SCROLL_PAGE_DOWN },
632 /* Searching */
633 { '/', REQ_SEARCH },
634 { '?', REQ_SEARCH_BACK },
635 { 'n', REQ_FIND_NEXT },
636 { 'N', REQ_FIND_PREV },
638 /* Misc */
639 { 'Q', REQ_QUIT },
640 { 'z', REQ_STOP_LOADING },
641 { 'v', REQ_SHOW_VERSION },
642 { 'r', REQ_SCREEN_REDRAW },
643 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
644 { 'o', REQ_OPTIONS },
645 { '.', REQ_TOGGLE_LINENO },
646 { 'D', REQ_TOGGLE_DATE },
647 { 'A', REQ_TOGGLE_AUTHOR },
648 { 'g', REQ_TOGGLE_REV_GRAPH },
649 { '~', REQ_TOGGLE_GRAPHIC },
650 { 'F', REQ_TOGGLE_REFS },
651 { 'I', REQ_TOGGLE_SORT_ORDER },
652 { 'i', REQ_TOGGLE_SORT_FIELD },
653 { ':', REQ_PROMPT },
654 { 'u', REQ_STATUS_UPDATE },
655 { '!', REQ_STATUS_REVERT },
656 { 'M', REQ_STATUS_MERGE },
657 { '@', REQ_STAGE_NEXT },
658 { ',', REQ_PARENT },
659 { 'e', REQ_EDIT },
660 };
662 #define KEYMAP_INFO \
663 KEYMAP_(GENERIC), \
664 KEYMAP_(MAIN), \
665 KEYMAP_(DIFF), \
666 KEYMAP_(LOG), \
667 KEYMAP_(TREE), \
668 KEYMAP_(BLOB), \
669 KEYMAP_(BLAME), \
670 KEYMAP_(BRANCH), \
671 KEYMAP_(PAGER), \
672 KEYMAP_(HELP), \
673 KEYMAP_(STATUS), \
674 KEYMAP_(STAGE)
676 enum keymap {
677 #define KEYMAP_(name) KEYMAP_##name
678 KEYMAP_INFO
679 #undef KEYMAP_
680 };
682 static const struct enum_map keymap_table[] = {
683 #define KEYMAP_(name) ENUM_MAP(#name, KEYMAP_##name)
684 KEYMAP_INFO
685 #undef KEYMAP_
686 };
688 #define set_keymap(map, name) map_enum(map, keymap_table, name)
690 struct keybinding_table {
691 struct keybinding *data;
692 size_t size;
693 };
695 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_table)];
697 static void
698 add_keybinding(enum keymap keymap, enum request request, int key)
699 {
700 struct keybinding_table *table = &keybindings[keymap];
701 size_t i;
703 for (i = 0; i < keybindings[keymap].size; i++) {
704 if (keybindings[keymap].data[i].alias == key) {
705 keybindings[keymap].data[i].request = request;
706 return;
707 }
708 }
710 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
711 if (!table->data)
712 die("Failed to allocate keybinding");
713 table->data[table->size].alias = key;
714 table->data[table->size++].request = request;
716 if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
717 int i;
719 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
720 if (default_keybindings[i].alias == key)
721 default_keybindings[i].request = REQ_NONE;
722 }
723 }
725 /* Looks for a key binding first in the given map, then in the generic map, and
726 * lastly in the default keybindings. */
727 static enum request
728 get_keybinding(enum keymap keymap, int key)
729 {
730 size_t i;
732 for (i = 0; i < keybindings[keymap].size; i++)
733 if (keybindings[keymap].data[i].alias == key)
734 return keybindings[keymap].data[i].request;
736 for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
737 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
738 return keybindings[KEYMAP_GENERIC].data[i].request;
740 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
741 if (default_keybindings[i].alias == key)
742 return default_keybindings[i].request;
744 return (enum request) key;
745 }
748 struct key {
749 const char *name;
750 int value;
751 };
753 static const struct key key_table[] = {
754 { "Enter", KEY_RETURN },
755 { "Space", ' ' },
756 { "Backspace", KEY_BACKSPACE },
757 { "Tab", KEY_TAB },
758 { "Escape", KEY_ESC },
759 { "Left", KEY_LEFT },
760 { "Right", KEY_RIGHT },
761 { "Up", KEY_UP },
762 { "Down", KEY_DOWN },
763 { "Insert", KEY_IC },
764 { "Delete", KEY_DC },
765 { "Hash", '#' },
766 { "Home", KEY_HOME },
767 { "End", KEY_END },
768 { "PageUp", KEY_PPAGE },
769 { "PageDown", KEY_NPAGE },
770 { "F1", KEY_F(1) },
771 { "F2", KEY_F(2) },
772 { "F3", KEY_F(3) },
773 { "F4", KEY_F(4) },
774 { "F5", KEY_F(5) },
775 { "F6", KEY_F(6) },
776 { "F7", KEY_F(7) },
777 { "F8", KEY_F(8) },
778 { "F9", KEY_F(9) },
779 { "F10", KEY_F(10) },
780 { "F11", KEY_F(11) },
781 { "F12", KEY_F(12) },
782 };
784 static int
785 get_key_value(const char *name)
786 {
787 int i;
789 for (i = 0; i < ARRAY_SIZE(key_table); i++)
790 if (!strcasecmp(key_table[i].name, name))
791 return key_table[i].value;
793 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
794 return (int)name[1] & 0x1f;
795 if (strlen(name) == 1 && isprint(*name))
796 return (int) *name;
797 return ERR;
798 }
800 static const char *
801 get_key_name(int key_value)
802 {
803 static char key_char[] = "'X'\0";
804 const char *seq = NULL;
805 int key;
807 for (key = 0; key < ARRAY_SIZE(key_table); key++)
808 if (key_table[key].value == key_value)
809 seq = key_table[key].name;
811 if (seq == NULL && key_value < 0x7f) {
812 char *s = key_char + 1;
814 if (key_value >= 0x20) {
815 *s++ = key_value;
816 } else {
817 *s++ = '^';
818 *s++ = 0x40 | (key_value & 0x1f);
819 }
820 *s++ = '\'';
821 *s++ = '\0';
822 seq = key_char;
823 }
825 return seq ? seq : "(no key)";
826 }
828 static bool
829 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
830 {
831 const char *sep = *pos > 0 ? ", " : "";
832 const char *keyname = get_key_name(keybinding->alias);
834 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
835 }
837 static bool
838 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
839 enum keymap keymap, bool all)
840 {
841 int i;
843 for (i = 0; i < keybindings[keymap].size; i++) {
844 if (keybindings[keymap].data[i].request == request) {
845 if (!append_key(buf, pos, &keybindings[keymap].data[i]))
846 return FALSE;
847 if (!all)
848 break;
849 }
850 }
852 return TRUE;
853 }
855 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
857 static const char *
858 get_keys(enum keymap keymap, enum request request, bool all)
859 {
860 static char buf[BUFSIZ];
861 size_t pos = 0;
862 int i;
864 buf[pos] = 0;
866 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
867 return "Too many keybindings!";
868 if (pos > 0 && !all)
869 return buf;
871 if (keymap != KEYMAP_GENERIC) {
872 /* Only the generic keymap includes the default keybindings when
873 * listing all keys. */
874 if (all)
875 return buf;
877 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
878 return "Too many keybindings!";
879 if (pos)
880 return buf;
881 }
883 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
884 if (default_keybindings[i].request == request) {
885 if (!append_key(buf, &pos, &default_keybindings[i]))
886 return "Too many keybindings!";
887 if (!all)
888 return buf;
889 }
890 }
892 return buf;
893 }
895 struct run_request {
896 enum keymap keymap;
897 int key;
898 const char **argv;
899 };
901 static struct run_request *run_request;
902 static size_t run_requests;
904 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
906 static enum request
907 add_run_request(enum keymap keymap, int key, const char **argv)
908 {
909 struct run_request *req;
911 if (!realloc_run_requests(&run_request, run_requests, 1))
912 return REQ_NONE;
914 req = &run_request[run_requests];
915 req->keymap = keymap;
916 req->key = key;
917 req->argv = NULL;
919 if (!argv_copy(&req->argv, argv))
920 return REQ_NONE;
922 return REQ_NONE + ++run_requests;
923 }
925 static struct run_request *
926 get_run_request(enum request request)
927 {
928 if (request <= REQ_NONE)
929 return NULL;
930 return &run_request[request - REQ_NONE - 1];
931 }
933 static void
934 add_builtin_run_requests(void)
935 {
936 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
937 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
938 const char *commit[] = { "git", "commit", NULL };
939 const char *gc[] = { "git", "gc", NULL };
940 struct run_request reqs[] = {
941 { KEYMAP_MAIN, 'C', cherry_pick },
942 { KEYMAP_STATUS, 'C', commit },
943 { KEYMAP_BRANCH, 'C', checkout },
944 { KEYMAP_GENERIC, 'G', gc },
945 };
946 int i;
948 for (i = 0; i < ARRAY_SIZE(reqs); i++) {
949 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
951 if (req != reqs[i].key)
952 continue;
953 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
954 if (req != REQ_NONE)
955 add_keybinding(reqs[i].keymap, req, reqs[i].key);
956 }
957 }
959 /*
960 * User config file handling.
961 */
963 #define OPT_ERR_INFO \
964 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
965 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
966 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
967 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
968 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
969 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
970 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
971 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
972 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
973 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
974 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
975 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
976 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
977 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
978 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
979 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
980 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
982 enum option_code {
983 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
984 OPT_ERR_INFO
985 #undef OPT_ERR_
986 OPT_OK
987 };
989 static const char *option_errors[] = {
990 #define OPT_ERR_(name, msg) msg
991 OPT_ERR_INFO
992 #undef OPT_ERR_
993 };
995 static const struct enum_map color_map[] = {
996 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
997 COLOR_MAP(DEFAULT),
998 COLOR_MAP(BLACK),
999 COLOR_MAP(BLUE),
1000 COLOR_MAP(CYAN),
1001 COLOR_MAP(GREEN),
1002 COLOR_MAP(MAGENTA),
1003 COLOR_MAP(RED),
1004 COLOR_MAP(WHITE),
1005 COLOR_MAP(YELLOW),
1006 };
1008 static const struct enum_map attr_map[] = {
1009 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1010 ATTR_MAP(NORMAL),
1011 ATTR_MAP(BLINK),
1012 ATTR_MAP(BOLD),
1013 ATTR_MAP(DIM),
1014 ATTR_MAP(REVERSE),
1015 ATTR_MAP(STANDOUT),
1016 ATTR_MAP(UNDERLINE),
1017 };
1019 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1021 static enum option_code
1022 parse_step(double *opt, const char *arg)
1023 {
1024 *opt = atoi(arg);
1025 if (!strchr(arg, '%'))
1026 return OPT_OK;
1028 /* "Shift down" so 100% and 1 does not conflict. */
1029 *opt = (*opt - 1) / 100;
1030 if (*opt >= 1.0) {
1031 *opt = 0.99;
1032 return OPT_ERR_INVALID_STEP_VALUE;
1033 }
1034 if (*opt < 0.0) {
1035 *opt = 1;
1036 return OPT_ERR_INVALID_STEP_VALUE;
1037 }
1038 return OPT_OK;
1039 }
1041 static enum option_code
1042 parse_int(int *opt, const char *arg, int min, int max)
1043 {
1044 int value = atoi(arg);
1046 if (min <= value && value <= max) {
1047 *opt = value;
1048 return OPT_OK;
1049 }
1051 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1052 }
1054 static bool
1055 set_color(int *color, const char *name)
1056 {
1057 if (map_enum(color, color_map, name))
1058 return TRUE;
1059 if (!prefixcmp(name, "color"))
1060 return parse_int(color, name + 5, 0, 255) == OK;
1061 return FALSE;
1062 }
1064 /* Wants: object fgcolor bgcolor [attribute] */
1065 static enum option_code
1066 option_color_command(int argc, const char *argv[])
1067 {
1068 struct line_info *info;
1070 if (argc < 3)
1071 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1073 info = get_line_info(argv[0]);
1074 if (!info) {
1075 static const struct enum_map obsolete[] = {
1076 ENUM_MAP("main-delim", LINE_DELIMITER),
1077 ENUM_MAP("main-date", LINE_DATE),
1078 ENUM_MAP("main-author", LINE_AUTHOR),
1079 };
1080 int index;
1082 if (!map_enum(&index, obsolete, argv[0]))
1083 return OPT_ERR_UNKNOWN_COLOR_NAME;
1084 info = &line_info[index];
1085 }
1087 if (!set_color(&info->fg, argv[1]) ||
1088 !set_color(&info->bg, argv[2]))
1089 return OPT_ERR_UNKNOWN_COLOR;
1091 info->attr = 0;
1092 while (argc-- > 3) {
1093 int attr;
1095 if (!set_attribute(&attr, argv[argc]))
1096 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1097 info->attr |= attr;
1098 }
1100 return OPT_OK;
1101 }
1103 static enum option_code
1104 parse_bool(bool *opt, const char *arg)
1105 {
1106 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1107 ? TRUE : FALSE;
1108 return OPT_OK;
1109 }
1111 static enum option_code
1112 parse_enum_do(unsigned int *opt, const char *arg,
1113 const struct enum_map *map, size_t map_size)
1114 {
1115 bool is_true;
1117 assert(map_size > 1);
1119 if (map_enum_do(map, map_size, (int *) opt, arg))
1120 return OPT_OK;
1122 parse_bool(&is_true, arg);
1123 *opt = is_true ? map[1].value : map[0].value;
1124 return OPT_OK;
1125 }
1127 #define parse_enum(opt, arg, map) \
1128 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1130 static enum option_code
1131 parse_string(char *opt, const char *arg, size_t optsize)
1132 {
1133 int arglen = strlen(arg);
1135 switch (arg[0]) {
1136 case '\"':
1137 case '\'':
1138 if (arglen == 1 || arg[arglen - 1] != arg[0])
1139 return OPT_ERR_UNMATCHED_QUOTATION;
1140 arg += 1; arglen -= 2;
1141 default:
1142 string_ncopy_do(opt, optsize, arg, arglen);
1143 return OPT_OK;
1144 }
1145 }
1147 static enum option_code
1148 parse_args(const char ***args, const char *argv[])
1149 {
1150 if (*args == NULL && !argv_copy(args, argv))
1151 return OPT_ERR_OUT_OF_MEMORY;
1152 return OPT_OK;
1153 }
1155 /* Wants: name = value */
1156 static enum option_code
1157 option_set_command(int argc, const char *argv[])
1158 {
1159 if (argc < 3)
1160 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1162 if (strcmp(argv[1], "="))
1163 return OPT_ERR_NO_VALUE_ASSIGNED;
1165 if (!strcmp(argv[0], "blame-options"))
1166 return parse_args(&opt_blame_argv, argv + 2);
1168 if (argc != 3)
1169 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1171 if (!strcmp(argv[0], "show-author"))
1172 return parse_enum(&opt_author, argv[2], author_map);
1174 if (!strcmp(argv[0], "show-date"))
1175 return parse_enum(&opt_date, argv[2], date_map);
1177 if (!strcmp(argv[0], "show-rev-graph"))
1178 return parse_bool(&opt_rev_graph, argv[2]);
1180 if (!strcmp(argv[0], "show-refs"))
1181 return parse_bool(&opt_show_refs, argv[2]);
1183 if (!strcmp(argv[0], "show-line-numbers"))
1184 return parse_bool(&opt_line_number, argv[2]);
1186 if (!strcmp(argv[0], "line-graphics"))
1187 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1189 if (!strcmp(argv[0], "line-number-interval"))
1190 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1192 if (!strcmp(argv[0], "author-width"))
1193 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1195 if (!strcmp(argv[0], "horizontal-scroll"))
1196 return parse_step(&opt_hscroll, argv[2]);
1198 if (!strcmp(argv[0], "split-view-height"))
1199 return parse_step(&opt_scale_split_view, argv[2]);
1201 if (!strcmp(argv[0], "tab-size"))
1202 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1204 if (!strcmp(argv[0], "commit-encoding"))
1205 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1207 if (!strcmp(argv[0], "status-untracked-dirs"))
1208 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1210 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1211 }
1213 /* Wants: mode request key */
1214 static enum option_code
1215 option_bind_command(int argc, const char *argv[])
1216 {
1217 enum request request;
1218 int keymap = -1;
1219 int key;
1221 if (argc < 3)
1222 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1224 if (!set_keymap(&keymap, argv[0]))
1225 return OPT_ERR_UNKNOWN_KEY_MAP;
1227 key = get_key_value(argv[1]);
1228 if (key == ERR)
1229 return OPT_ERR_UNKNOWN_KEY;
1231 request = get_request(argv[2]);
1232 if (request == REQ_UNKNOWN) {
1233 static const struct enum_map obsolete[] = {
1234 ENUM_MAP("cherry-pick", REQ_NONE),
1235 ENUM_MAP("screen-resize", REQ_NONE),
1236 ENUM_MAP("tree-parent", REQ_PARENT),
1237 };
1238 int alias;
1240 if (map_enum(&alias, obsolete, argv[2])) {
1241 if (alias != REQ_NONE)
1242 add_keybinding(keymap, alias, key);
1243 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1244 }
1245 }
1246 if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1247 request = add_run_request(keymap, key, argv + 2);
1248 if (request == REQ_UNKNOWN)
1249 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1251 add_keybinding(keymap, request, key);
1253 return OPT_OK;
1254 }
1256 static enum option_code
1257 set_option(const char *opt, char *value)
1258 {
1259 const char *argv[SIZEOF_ARG];
1260 int argc = 0;
1262 if (!argv_from_string(argv, &argc, value))
1263 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1265 if (!strcmp(opt, "color"))
1266 return option_color_command(argc, argv);
1268 if (!strcmp(opt, "set"))
1269 return option_set_command(argc, argv);
1271 if (!strcmp(opt, "bind"))
1272 return option_bind_command(argc, argv);
1274 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1275 }
1277 struct config_state {
1278 int lineno;
1279 bool errors;
1280 };
1282 static int
1283 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1284 {
1285 struct config_state *config = data;
1286 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1288 config->lineno++;
1290 /* Check for comment markers, since read_properties() will
1291 * only ensure opt and value are split at first " \t". */
1292 optlen = strcspn(opt, "#");
1293 if (optlen == 0)
1294 return OK;
1296 if (opt[optlen] == 0) {
1297 /* Look for comment endings in the value. */
1298 size_t len = strcspn(value, "#");
1300 if (len < valuelen) {
1301 valuelen = len;
1302 value[valuelen] = 0;
1303 }
1305 status = set_option(opt, value);
1306 }
1308 if (status != OPT_OK) {
1309 warn("Error on line %d, near '%.*s': %s",
1310 config->lineno, (int) optlen, opt, option_errors[status]);
1311 config->errors = TRUE;
1312 }
1314 /* Always keep going if errors are encountered. */
1315 return OK;
1316 }
1318 static void
1319 load_option_file(const char *path)
1320 {
1321 struct config_state config = { 0, FALSE };
1322 struct io io;
1324 /* It's OK that the file doesn't exist. */
1325 if (!io_open(&io, "%s", path))
1326 return;
1328 if (io_load(&io, " \t", read_option, &config) == ERR ||
1329 config.errors == TRUE)
1330 warn("Errors while loading %s.", path);
1331 }
1333 static int
1334 load_options(void)
1335 {
1336 const char *home = getenv("HOME");
1337 const char *tigrc_user = getenv("TIGRC_USER");
1338 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1339 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1340 char buf[SIZEOF_STR];
1342 if (!tigrc_system)
1343 tigrc_system = SYSCONFDIR "/tigrc";
1344 load_option_file(tigrc_system);
1346 if (!tigrc_user) {
1347 if (!home || !string_format(buf, "%s/.tigrc", home))
1348 return ERR;
1349 tigrc_user = buf;
1350 }
1351 load_option_file(tigrc_user);
1353 /* Add _after_ loading config files to avoid adding run requests
1354 * that conflict with keybindings. */
1355 add_builtin_run_requests();
1357 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1358 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1359 int argc = 0;
1361 if (!string_format(buf, "%s", tig_diff_opts) ||
1362 !argv_from_string(diff_opts, &argc, buf))
1363 die("TIG_DIFF_OPTS contains too many arguments");
1364 else if (!argv_copy(&opt_diff_argv, diff_opts))
1365 die("Failed to format TIG_DIFF_OPTS arguments");
1366 }
1368 return OK;
1369 }
1372 /*
1373 * The viewer
1374 */
1376 struct view;
1377 struct view_ops;
1379 /* The display array of active views and the index of the current view. */
1380 static struct view *display[2];
1381 static WINDOW *display_win[2];
1382 static WINDOW *display_title[2];
1383 static unsigned int current_view;
1385 #define foreach_displayed_view(view, i) \
1386 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1388 #define displayed_views() (display[1] != NULL ? 2 : 1)
1390 /* Current head and commit ID */
1391 static char ref_blob[SIZEOF_REF] = "";
1392 static char ref_commit[SIZEOF_REF] = "HEAD";
1393 static char ref_head[SIZEOF_REF] = "HEAD";
1394 static char ref_branch[SIZEOF_REF] = "";
1396 enum view_type {
1397 VIEW_MAIN,
1398 VIEW_DIFF,
1399 VIEW_LOG,
1400 VIEW_TREE,
1401 VIEW_BLOB,
1402 VIEW_BLAME,
1403 VIEW_BRANCH,
1404 VIEW_HELP,
1405 VIEW_PAGER,
1406 VIEW_STATUS,
1407 VIEW_STAGE,
1408 };
1410 struct view {
1411 enum view_type type; /* View type */
1412 const char *name; /* View name */
1413 const char *id; /* Points to either of ref_{head,commit,blob} */
1415 struct view_ops *ops; /* View operations */
1417 enum keymap keymap; /* What keymap does this view have */
1418 bool git_dir; /* Whether the view requires a git directory. */
1420 char ref[SIZEOF_REF]; /* Hovered commit reference */
1421 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1423 int height, width; /* The width and height of the main window */
1424 WINDOW *win; /* The main window */
1426 /* Navigation */
1427 unsigned long offset; /* Offset of the window top */
1428 unsigned long yoffset; /* Offset from the window side. */
1429 unsigned long lineno; /* Current line number */
1430 unsigned long p_offset; /* Previous offset of the window top */
1431 unsigned long p_yoffset;/* Previous offset from the window side */
1432 unsigned long p_lineno; /* Previous current line number */
1433 bool p_restore; /* Should the previous position be restored. */
1435 /* Searching */
1436 char grep[SIZEOF_STR]; /* Search string */
1437 regex_t *regex; /* Pre-compiled regexp */
1439 /* If non-NULL, points to the view that opened this view. If this view
1440 * is closed tig will switch back to the parent view. */
1441 struct view *parent;
1442 struct view *prev;
1444 /* Buffering */
1445 size_t lines; /* Total number of lines */
1446 struct line *line; /* Line index */
1447 unsigned int digits; /* Number of digits in the lines member. */
1449 /* Drawing */
1450 struct line *curline; /* Line currently being drawn. */
1451 enum line_type curtype; /* Attribute currently used for drawing. */
1452 unsigned long col; /* Column when drawing. */
1453 bool has_scrolled; /* View was scrolled. */
1455 /* Loading */
1456 const char **argv; /* Shell command arguments. */
1457 const char *dir; /* Directory from which to execute. */
1458 struct io io;
1459 struct io *pipe;
1460 time_t start_time;
1461 time_t update_secs;
1462 };
1464 enum open_flags {
1465 OPEN_DEFAULT = 0, /* Use default view switching. */
1466 OPEN_SPLIT = 1, /* Split current view. */
1467 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1468 OPEN_REFRESH = 16, /* Refresh view using previous command. */
1469 OPEN_PREPARED = 32, /* Open already prepared command. */
1470 OPEN_EXTRA = 64, /* Open extra data from command. */
1471 };
1473 struct view_ops {
1474 /* What type of content being displayed. Used in the title bar. */
1475 const char *type;
1476 /* Open and reads in all view content. */
1477 bool (*open)(struct view *view, enum open_flags flags);
1478 /* Read one line; updates view->line. */
1479 bool (*read)(struct view *view, char *data);
1480 /* Draw one line; @lineno must be < view->height. */
1481 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1482 /* Depending on view handle a special requests. */
1483 enum request (*request)(struct view *view, enum request request, struct line *line);
1484 /* Search for regexp in a line. */
1485 bool (*grep)(struct view *view, struct line *line);
1486 /* Select line */
1487 void (*select)(struct view *view, struct line *line);
1488 };
1490 static struct view_ops blame_ops;
1491 static struct view_ops blob_ops;
1492 static struct view_ops diff_ops;
1493 static struct view_ops help_ops;
1494 static struct view_ops log_ops;
1495 static struct view_ops main_ops;
1496 static struct view_ops pager_ops;
1497 static struct view_ops stage_ops;
1498 static struct view_ops status_ops;
1499 static struct view_ops tree_ops;
1500 static struct view_ops branch_ops;
1502 #define VIEW_STR(type, name, ref, ops, map, git) \
1503 { type, name, ref, ops, map, git }
1505 #define VIEW_(id, name, ops, git, ref) \
1506 VIEW_STR(VIEW_##id, name, ref, ops, KEYMAP_##id, git)
1508 static struct view views[] = {
1509 VIEW_(MAIN, "main", &main_ops, TRUE, ref_head),
1510 VIEW_(DIFF, "diff", &diff_ops, TRUE, ref_commit),
1511 VIEW_(LOG, "log", &log_ops, TRUE, ref_head),
1512 VIEW_(TREE, "tree", &tree_ops, TRUE, ref_commit),
1513 VIEW_(BLOB, "blob", &blob_ops, TRUE, ref_blob),
1514 VIEW_(BLAME, "blame", &blame_ops, TRUE, ref_commit),
1515 VIEW_(BRANCH, "branch", &branch_ops, TRUE, ref_head),
1516 VIEW_(HELP, "help", &help_ops, FALSE, ""),
1517 VIEW_(PAGER, "pager", &pager_ops, FALSE, ""),
1518 VIEW_(STATUS, "status", &status_ops, TRUE, ""),
1519 VIEW_(STAGE, "stage", &stage_ops, TRUE, ""),
1520 };
1522 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1524 #define foreach_view(view, i) \
1525 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1527 #define view_is_displayed(view) \
1528 (view == display[0] || view == display[1])
1530 static enum request
1531 view_request(struct view *view, enum request request)
1532 {
1533 if (!view || !view->lines)
1534 return request;
1535 return view->ops->request(view, request, &view->line[view->lineno]);
1536 }
1539 /*
1540 * View drawing.
1541 */
1543 static inline void
1544 set_view_attr(struct view *view, enum line_type type)
1545 {
1546 if (!view->curline->selected && view->curtype != type) {
1547 (void) wattrset(view->win, get_line_attr(type));
1548 wchgat(view->win, -1, 0, type, NULL);
1549 view->curtype = type;
1550 }
1551 }
1553 #define VIEW_MAX_LEN(view) ((view)->width + (view)->yoffset - (view)->col)
1555 static bool
1556 draw_chars(struct view *view, enum line_type type, const char *string,
1557 int max_len, bool use_tilde)
1558 {
1559 static char out_buffer[BUFSIZ * 2];
1560 int len = 0;
1561 int col = 0;
1562 int trimmed = FALSE;
1563 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1565 if (max_len <= 0)
1566 return VIEW_MAX_LEN(view) <= 0;
1568 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1570 set_view_attr(view, type);
1571 if (len > 0) {
1572 if (opt_iconv_out != ICONV_NONE) {
1573 ICONV_CONST char *inbuf = (ICONV_CONST char *) string;
1574 size_t inlen = len + 1;
1576 char *outbuf = out_buffer;
1577 size_t outlen = sizeof(out_buffer);
1579 size_t ret;
1581 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1582 if (ret != (size_t) -1) {
1583 string = out_buffer;
1584 len = sizeof(out_buffer) - outlen;
1585 }
1586 }
1588 waddnstr(view->win, string, len);
1590 if (trimmed && use_tilde) {
1591 set_view_attr(view, LINE_DELIMITER);
1592 waddch(view->win, '~');
1593 col++;
1594 }
1595 }
1597 view->col += col;
1598 return VIEW_MAX_LEN(view) <= 0;
1599 }
1601 static bool
1602 draw_space(struct view *view, enum line_type type, int max, int spaces)
1603 {
1604 static char space[] = " ";
1606 spaces = MIN(max, spaces);
1608 while (spaces > 0) {
1609 int len = MIN(spaces, sizeof(space) - 1);
1611 if (draw_chars(view, type, space, len, FALSE))
1612 return TRUE;
1613 spaces -= len;
1614 }
1616 return VIEW_MAX_LEN(view) <= 0;
1617 }
1619 static bool
1620 draw_text(struct view *view, enum line_type type, const char *string)
1621 {
1622 char text[SIZEOF_STR];
1624 do {
1625 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1627 if (draw_chars(view, type, text, VIEW_MAX_LEN(view), TRUE))
1628 return TRUE;
1629 string += pos;
1630 } while (*string);
1632 return VIEW_MAX_LEN(view) <= 0;
1633 }
1635 static bool
1636 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1637 {
1638 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1639 int max = VIEW_MAX_LEN(view);
1640 int i;
1642 if (max < size)
1643 size = max;
1645 set_view_attr(view, type);
1646 /* Using waddch() instead of waddnstr() ensures that
1647 * they'll be rendered correctly for the cursor line. */
1648 for (i = skip; i < size; i++)
1649 waddch(view->win, graphic[i]);
1651 view->col += size;
1652 if (separator) {
1653 if (size < max && skip <= size)
1654 waddch(view->win, ' ');
1655 view->col++;
1656 }
1658 return VIEW_MAX_LEN(view) <= 0;
1659 }
1661 static bool
1662 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1663 {
1664 int max = MIN(VIEW_MAX_LEN(view), len);
1665 int col = view->col;
1667 if (!text)
1668 return draw_space(view, type, max, max);
1670 return draw_chars(view, type, text, max - 1, trim)
1671 || draw_space(view, LINE_DEFAULT, max - (view->col - col), max);
1672 }
1674 static bool
1675 draw_date(struct view *view, struct time *time)
1676 {
1677 const char *date = mkdate(time, opt_date);
1678 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1680 if (opt_date == DATE_NO)
1681 return FALSE;
1683 return draw_field(view, LINE_DATE, date, cols, FALSE);
1684 }
1686 static bool
1687 draw_author(struct view *view, const char *author)
1688 {
1689 bool trim = author_trim(opt_author_cols);
1690 const char *text = mkauthor(author, opt_author_cols, opt_author);
1692 return draw_field(view, LINE_AUTHOR, text, opt_author_cols, trim);
1693 }
1695 static bool
1696 draw_mode(struct view *view, mode_t mode)
1697 {
1698 const char *str = mkmode(mode);
1700 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1701 }
1703 static bool
1704 draw_lineno(struct view *view, unsigned int lineno)
1705 {
1706 char number[10];
1707 int digits3 = view->digits < 3 ? 3 : view->digits;
1708 int max = MIN(VIEW_MAX_LEN(view), digits3);
1709 char *text = NULL;
1710 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1712 lineno += view->offset + 1;
1713 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1714 static char fmt[] = "%1ld";
1716 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1717 if (string_format(number, fmt, lineno))
1718 text = number;
1719 }
1720 if (text)
1721 draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1722 else
1723 draw_space(view, LINE_LINE_NUMBER, max, digits3);
1724 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1725 }
1727 static bool
1728 draw_refs(struct view *view, struct ref_list *refs)
1729 {
1730 size_t i;
1732 if (!opt_show_refs || !refs)
1733 return FALSE;
1735 for (i = 0; i < refs->size; i++) {
1736 struct ref *ref = refs->refs[i];
1737 enum line_type type;
1739 if (ref->head)
1740 type = LINE_MAIN_HEAD;
1741 else if (ref->ltag)
1742 type = LINE_MAIN_LOCAL_TAG;
1743 else if (ref->tag)
1744 type = LINE_MAIN_TAG;
1745 else if (ref->tracked)
1746 type = LINE_MAIN_TRACKED;
1747 else if (ref->remote)
1748 type = LINE_MAIN_REMOTE;
1749 else
1750 type = LINE_MAIN_REF;
1752 if (draw_text(view, type, "[") ||
1753 draw_text(view, type, ref->name) ||
1754 draw_text(view, type, "]"))
1755 return TRUE;
1757 if (draw_text(view, LINE_DEFAULT, " "))
1758 return TRUE;
1759 }
1761 return FALSE;
1762 }
1764 static bool
1765 draw_view_line(struct view *view, unsigned int lineno)
1766 {
1767 struct line *line;
1768 bool selected = (view->offset + lineno == view->lineno);
1770 assert(view_is_displayed(view));
1772 if (view->offset + lineno >= view->lines)
1773 return FALSE;
1775 line = &view->line[view->offset + lineno];
1777 wmove(view->win, lineno, 0);
1778 if (line->cleareol)
1779 wclrtoeol(view->win);
1780 view->col = 0;
1781 view->curline = line;
1782 view->curtype = LINE_NONE;
1783 line->selected = FALSE;
1784 line->dirty = line->cleareol = 0;
1786 if (selected) {
1787 set_view_attr(view, LINE_CURSOR);
1788 line->selected = TRUE;
1789 view->ops->select(view, line);
1790 }
1792 return view->ops->draw(view, line, lineno);
1793 }
1795 static void
1796 redraw_view_dirty(struct view *view)
1797 {
1798 bool dirty = FALSE;
1799 int lineno;
1801 for (lineno = 0; lineno < view->height; lineno++) {
1802 if (view->offset + lineno >= view->lines)
1803 break;
1804 if (!view->line[view->offset + lineno].dirty)
1805 continue;
1806 dirty = TRUE;
1807 if (!draw_view_line(view, lineno))
1808 break;
1809 }
1811 if (!dirty)
1812 return;
1813 wnoutrefresh(view->win);
1814 }
1816 static void
1817 redraw_view_from(struct view *view, int lineno)
1818 {
1819 assert(0 <= lineno && lineno < view->height);
1821 for (; lineno < view->height; lineno++) {
1822 if (!draw_view_line(view, lineno))
1823 break;
1824 }
1826 wnoutrefresh(view->win);
1827 }
1829 static void
1830 redraw_view(struct view *view)
1831 {
1832 werase(view->win);
1833 redraw_view_from(view, 0);
1834 }
1837 static void
1838 update_view_title(struct view *view)
1839 {
1840 char buf[SIZEOF_STR];
1841 char state[SIZEOF_STR];
1842 size_t bufpos = 0, statelen = 0;
1843 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1845 assert(view_is_displayed(view));
1847 if (view->type != VIEW_STATUS && view->lines) {
1848 unsigned int view_lines = view->offset + view->height;
1849 unsigned int lines = view->lines
1850 ? MIN(view_lines, view->lines) * 100 / view->lines
1851 : 0;
1853 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
1854 view->ops->type,
1855 view->lineno + 1,
1856 view->lines,
1857 lines);
1859 }
1861 if (view->pipe) {
1862 time_t secs = time(NULL) - view->start_time;
1864 /* Three git seconds are a long time ... */
1865 if (secs > 2)
1866 string_format_from(state, &statelen, " loading %lds", secs);
1867 }
1869 string_format_from(buf, &bufpos, "[%s]", view->name);
1870 if (*view->ref && bufpos < view->width) {
1871 size_t refsize = strlen(view->ref);
1872 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
1874 if (minsize < view->width)
1875 refsize = view->width - minsize + 7;
1876 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
1877 }
1879 if (statelen && bufpos < view->width) {
1880 string_format_from(buf, &bufpos, "%s", state);
1881 }
1883 if (view == display[current_view])
1884 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
1885 else
1886 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
1888 mvwaddnstr(window, 0, 0, buf, bufpos);
1889 wclrtoeol(window);
1890 wnoutrefresh(window);
1891 }
1893 static int
1894 apply_step(double step, int value)
1895 {
1896 if (step >= 1)
1897 return (int) step;
1898 value *= step + 0.01;
1899 return value ? value : 1;
1900 }
1902 static void
1903 resize_display(void)
1904 {
1905 int offset, i;
1906 struct view *base = display[0];
1907 struct view *view = display[1] ? display[1] : display[0];
1909 /* Setup window dimensions */
1911 getmaxyx(stdscr, base->height, base->width);
1913 /* Make room for the status window. */
1914 base->height -= 1;
1916 if (view != base) {
1917 /* Horizontal split. */
1918 view->width = base->width;
1919 view->height = apply_step(opt_scale_split_view, base->height);
1920 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
1921 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
1922 base->height -= view->height;
1924 /* Make room for the title bar. */
1925 view->height -= 1;
1926 }
1928 /* Make room for the title bar. */
1929 base->height -= 1;
1931 offset = 0;
1933 foreach_displayed_view (view, i) {
1934 if (!display_win[i]) {
1935 display_win[i] = newwin(view->height, view->width, offset, 0);
1936 if (!display_win[i])
1937 die("Failed to create %s view", view->name);
1939 scrollok(display_win[i], FALSE);
1941 display_title[i] = newwin(1, view->width, offset + view->height, 0);
1942 if (!display_title[i])
1943 die("Failed to create title window");
1945 } else {
1946 wresize(display_win[i], view->height, view->width);
1947 mvwin(display_win[i], offset, 0);
1948 mvwin(display_title[i], offset + view->height, 0);
1949 }
1951 view->win = display_win[i];
1953 offset += view->height + 1;
1954 }
1955 }
1957 static void
1958 redraw_display(bool clear)
1959 {
1960 struct view *view;
1961 int i;
1963 foreach_displayed_view (view, i) {
1964 if (clear)
1965 wclear(view->win);
1966 redraw_view(view);
1967 update_view_title(view);
1968 }
1969 }
1972 /*
1973 * Option management
1974 */
1976 #define TOGGLE_MENU \
1977 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
1978 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
1979 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
1980 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
1981 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
1982 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL)
1984 static void
1985 toggle_option(enum request request)
1986 {
1987 const struct {
1988 enum request request;
1989 const struct enum_map *map;
1990 size_t map_size;
1991 } data[] = {
1992 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
1993 TOGGLE_MENU
1994 #undef TOGGLE_
1995 };
1996 const struct menu_item menu[] = {
1997 #define TOGGLE_(id, key, help, value, map) { key, help, value },
1998 TOGGLE_MENU
1999 #undef TOGGLE_
2000 { 0 }
2001 };
2002 int i = 0;
2004 if (request == REQ_OPTIONS) {
2005 if (!prompt_menu("Toggle option", menu, &i))
2006 return;
2007 } else {
2008 while (i < ARRAY_SIZE(data) && data[i].request != request)
2009 i++;
2010 if (i >= ARRAY_SIZE(data))
2011 die("Invalid request (%d)", request);
2012 }
2014 if (data[i].map != NULL) {
2015 unsigned int *opt = menu[i].data;
2017 *opt = (*opt + 1) % data[i].map_size;
2018 redraw_display(FALSE);
2019 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
2021 } else {
2022 bool *option = menu[i].data;
2024 *option = !*option;
2025 redraw_display(FALSE);
2026 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
2027 }
2028 }
2030 static void
2031 maximize_view(struct view *view, bool redraw)
2032 {
2033 memset(display, 0, sizeof(display));
2034 current_view = 0;
2035 display[current_view] = view;
2036 resize_display();
2037 if (redraw) {
2038 redraw_display(FALSE);
2039 report("");
2040 }
2041 }
2044 /*
2045 * Navigation
2046 */
2048 static bool
2049 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
2050 {
2051 if (lineno >= view->lines)
2052 lineno = view->lines > 0 ? view->lines - 1 : 0;
2054 if (offset > lineno || offset + view->height <= lineno) {
2055 unsigned long half = view->height / 2;
2057 if (lineno > half)
2058 offset = lineno - half;
2059 else
2060 offset = 0;
2061 }
2063 if (offset != view->offset || lineno != view->lineno) {
2064 view->offset = offset;
2065 view->lineno = lineno;
2066 return TRUE;
2067 }
2069 return FALSE;
2070 }
2072 /* Scrolling backend */
2073 static void
2074 do_scroll_view(struct view *view, int lines)
2075 {
2076 bool redraw_current_line = FALSE;
2078 /* The rendering expects the new offset. */
2079 view->offset += lines;
2081 assert(0 <= view->offset && view->offset < view->lines);
2082 assert(lines);
2084 /* Move current line into the view. */
2085 if (view->lineno < view->offset) {
2086 view->lineno = view->offset;
2087 redraw_current_line = TRUE;
2088 } else if (view->lineno >= view->offset + view->height) {
2089 view->lineno = view->offset + view->height - 1;
2090 redraw_current_line = TRUE;
2091 }
2093 assert(view->offset <= view->lineno && view->lineno < view->lines);
2095 /* Redraw the whole screen if scrolling is pointless. */
2096 if (view->height < ABS(lines)) {
2097 redraw_view(view);
2099 } else {
2100 int line = lines > 0 ? view->height - lines : 0;
2101 int end = line + ABS(lines);
2103 scrollok(view->win, TRUE);
2104 wscrl(view->win, lines);
2105 scrollok(view->win, FALSE);
2107 while (line < end && draw_view_line(view, line))
2108 line++;
2110 if (redraw_current_line)
2111 draw_view_line(view, view->lineno - view->offset);
2112 wnoutrefresh(view->win);
2113 }
2115 view->has_scrolled = TRUE;
2116 report("");
2117 }
2119 /* Scroll frontend */
2120 static void
2121 scroll_view(struct view *view, enum request request)
2122 {
2123 int lines = 1;
2125 assert(view_is_displayed(view));
2127 switch (request) {
2128 case REQ_SCROLL_FIRST_COL:
2129 view->yoffset = 0;
2130 redraw_view_from(view, 0);
2131 report("");
2132 return;
2133 case REQ_SCROLL_LEFT:
2134 if (view->yoffset == 0) {
2135 report("Cannot scroll beyond the first column");
2136 return;
2137 }
2138 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2139 view->yoffset = 0;
2140 else
2141 view->yoffset -= apply_step(opt_hscroll, view->width);
2142 redraw_view_from(view, 0);
2143 report("");
2144 return;
2145 case REQ_SCROLL_RIGHT:
2146 view->yoffset += apply_step(opt_hscroll, view->width);
2147 redraw_view(view);
2148 report("");
2149 return;
2150 case REQ_SCROLL_PAGE_DOWN:
2151 lines = view->height;
2152 case REQ_SCROLL_LINE_DOWN:
2153 if (view->offset + lines > view->lines)
2154 lines = view->lines - view->offset;
2156 if (lines == 0 || view->offset + view->height >= view->lines) {
2157 report("Cannot scroll beyond the last line");
2158 return;
2159 }
2160 break;
2162 case REQ_SCROLL_PAGE_UP:
2163 lines = view->height;
2164 case REQ_SCROLL_LINE_UP:
2165 if (lines > view->offset)
2166 lines = view->offset;
2168 if (lines == 0) {
2169 report("Cannot scroll beyond the first line");
2170 return;
2171 }
2173 lines = -lines;
2174 break;
2176 default:
2177 die("request %d not handled in switch", request);
2178 }
2180 do_scroll_view(view, lines);
2181 }
2183 /* Cursor moving */
2184 static void
2185 move_view(struct view *view, enum request request)
2186 {
2187 int scroll_steps = 0;
2188 int steps;
2190 switch (request) {
2191 case REQ_MOVE_FIRST_LINE:
2192 steps = -view->lineno;
2193 break;
2195 case REQ_MOVE_LAST_LINE:
2196 steps = view->lines - view->lineno - 1;
2197 break;
2199 case REQ_MOVE_PAGE_UP:
2200 steps = view->height > view->lineno
2201 ? -view->lineno : -view->height;
2202 break;
2204 case REQ_MOVE_PAGE_DOWN:
2205 steps = view->lineno + view->height >= view->lines
2206 ? view->lines - view->lineno - 1 : view->height;
2207 break;
2209 case REQ_MOVE_UP:
2210 steps = -1;
2211 break;
2213 case REQ_MOVE_DOWN:
2214 steps = 1;
2215 break;
2217 default:
2218 die("request %d not handled in switch", request);
2219 }
2221 if (steps <= 0 && view->lineno == 0) {
2222 report("Cannot move beyond the first line");
2223 return;
2225 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2226 report("Cannot move beyond the last line");
2227 return;
2228 }
2230 /* Move the current line */
2231 view->lineno += steps;
2232 assert(0 <= view->lineno && view->lineno < view->lines);
2234 /* Check whether the view needs to be scrolled */
2235 if (view->lineno < view->offset ||
2236 view->lineno >= view->offset + view->height) {
2237 scroll_steps = steps;
2238 if (steps < 0 && -steps > view->offset) {
2239 scroll_steps = -view->offset;
2241 } else if (steps > 0) {
2242 if (view->lineno == view->lines - 1 &&
2243 view->lines > view->height) {
2244 scroll_steps = view->lines - view->offset - 1;
2245 if (scroll_steps >= view->height)
2246 scroll_steps -= view->height - 1;
2247 }
2248 }
2249 }
2251 if (!view_is_displayed(view)) {
2252 view->offset += scroll_steps;
2253 assert(0 <= view->offset && view->offset < view->lines);
2254 view->ops->select(view, &view->line[view->lineno]);
2255 return;
2256 }
2258 /* Repaint the old "current" line if we be scrolling */
2259 if (ABS(steps) < view->height)
2260 draw_view_line(view, view->lineno - steps - view->offset);
2262 if (scroll_steps) {
2263 do_scroll_view(view, scroll_steps);
2264 return;
2265 }
2267 /* Draw the current line */
2268 draw_view_line(view, view->lineno - view->offset);
2270 wnoutrefresh(view->win);
2271 report("");
2272 }
2275 /*
2276 * Searching
2277 */
2279 static void search_view(struct view *view, enum request request);
2281 static bool
2282 grep_text(struct view *view, const char *text[])
2283 {
2284 regmatch_t pmatch;
2285 size_t i;
2287 for (i = 0; text[i]; i++)
2288 if (*text[i] &&
2289 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2290 return TRUE;
2291 return FALSE;
2292 }
2294 static void
2295 select_view_line(struct view *view, unsigned long lineno)
2296 {
2297 unsigned long old_lineno = view->lineno;
2298 unsigned long old_offset = view->offset;
2300 if (goto_view_line(view, view->offset, lineno)) {
2301 if (view_is_displayed(view)) {
2302 if (old_offset != view->offset) {
2303 redraw_view(view);
2304 } else {
2305 draw_view_line(view, old_lineno - view->offset);
2306 draw_view_line(view, view->lineno - view->offset);
2307 wnoutrefresh(view->win);
2308 }
2309 } else {
2310 view->ops->select(view, &view->line[view->lineno]);
2311 }
2312 }
2313 }
2315 static void
2316 find_next(struct view *view, enum request request)
2317 {
2318 unsigned long lineno = view->lineno;
2319 int direction;
2321 if (!*view->grep) {
2322 if (!*opt_search)
2323 report("No previous search");
2324 else
2325 search_view(view, request);
2326 return;
2327 }
2329 switch (request) {
2330 case REQ_SEARCH:
2331 case REQ_FIND_NEXT:
2332 direction = 1;
2333 break;
2335 case REQ_SEARCH_BACK:
2336 case REQ_FIND_PREV:
2337 direction = -1;
2338 break;
2340 default:
2341 return;
2342 }
2344 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2345 lineno += direction;
2347 /* Note, lineno is unsigned long so will wrap around in which case it
2348 * will become bigger than view->lines. */
2349 for (; lineno < view->lines; lineno += direction) {
2350 if (view->ops->grep(view, &view->line[lineno])) {
2351 select_view_line(view, lineno);
2352 report("Line %ld matches '%s'", lineno + 1, view->grep);
2353 return;
2354 }
2355 }
2357 report("No match found for '%s'", view->grep);
2358 }
2360 static void
2361 search_view(struct view *view, enum request request)
2362 {
2363 int regex_err;
2365 if (view->regex) {
2366 regfree(view->regex);
2367 *view->grep = 0;
2368 } else {
2369 view->regex = calloc(1, sizeof(*view->regex));
2370 if (!view->regex)
2371 return;
2372 }
2374 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2375 if (regex_err != 0) {
2376 char buf[SIZEOF_STR] = "unknown error";
2378 regerror(regex_err, view->regex, buf, sizeof(buf));
2379 report("Search failed: %s", buf);
2380 return;
2381 }
2383 string_copy(view->grep, opt_search);
2385 find_next(view, request);
2386 }
2388 /*
2389 * Incremental updating
2390 */
2392 static void
2393 reset_view(struct view *view)
2394 {
2395 int i;
2397 for (i = 0; i < view->lines; i++)
2398 free(view->line[i].data);
2399 free(view->line);
2401 view->p_offset = view->offset;
2402 view->p_yoffset = view->yoffset;
2403 view->p_lineno = view->lineno;
2405 view->line = NULL;
2406 view->offset = 0;
2407 view->yoffset = 0;
2408 view->lines = 0;
2409 view->lineno = 0;
2410 view->vid[0] = 0;
2411 view->update_secs = 0;
2412 }
2414 static const char *
2415 format_arg(const char *name)
2416 {
2417 static struct {
2418 const char *name;
2419 size_t namelen;
2420 const char *value;
2421 const char *value_if_empty;
2422 } vars[] = {
2423 #define FORMAT_VAR(name, value, value_if_empty) \
2424 { name, STRING_SIZE(name), value, value_if_empty }
2425 FORMAT_VAR("%(directory)", opt_path, "."),
2426 FORMAT_VAR("%(file)", opt_file, ""),
2427 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2428 FORMAT_VAR("%(head)", ref_head, ""),
2429 FORMAT_VAR("%(commit)", ref_commit, ""),
2430 FORMAT_VAR("%(blob)", ref_blob, ""),
2431 FORMAT_VAR("%(branch)", ref_branch, ""),
2432 };
2433 int i;
2435 for (i = 0; i < ARRAY_SIZE(vars); i++)
2436 if (!strncmp(name, vars[i].name, vars[i].namelen))
2437 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2439 report("Unknown replacement: `%s`", name);
2440 return NULL;
2441 }
2443 static bool
2444 format_argv(const char ***dst_argv, const char *src_argv[], bool first)
2445 {
2446 char buf[SIZEOF_STR];
2447 int argc;
2449 argv_free(*dst_argv);
2451 for (argc = 0; src_argv[argc]; argc++) {
2452 const char *arg = src_argv[argc];
2453 size_t bufpos = 0;
2455 if (!strcmp(arg, "%(fileargs)")) {
2456 if (!argv_append_array(dst_argv, opt_file_argv))
2457 break;
2458 continue;
2460 } else if (!strcmp(arg, "%(diffargs)")) {
2461 if (!argv_append_array(dst_argv, opt_diff_argv))
2462 break;
2463 continue;
2465 } else if (!strcmp(arg, "%(blameargs)")) {
2466 if (!argv_append_array(dst_argv, opt_blame_argv))
2467 break;
2468 continue;
2470 } else if (!strcmp(arg, "%(revargs)") ||
2471 (first && !strcmp(arg, "%(commit)"))) {
2472 if (!argv_append_array(dst_argv, opt_rev_argv))
2473 break;
2474 continue;
2475 }
2477 while (arg) {
2478 char *next = strstr(arg, "%(");
2479 int len = next - arg;
2480 const char *value;
2482 if (!next) {
2483 len = strlen(arg);
2484 value = "";
2486 } else {
2487 value = format_arg(next);
2489 if (!value) {
2490 return FALSE;
2491 }
2492 }
2494 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2495 return FALSE;
2497 arg = next ? strchr(next, ')') + 1 : NULL;
2498 }
2500 if (!argv_append(dst_argv, buf))
2501 break;
2502 }
2504 return src_argv[argc] == NULL;
2505 }
2507 static bool
2508 restore_view_position(struct view *view)
2509 {
2510 if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2511 return FALSE;
2513 /* Changing the view position cancels the restoring. */
2514 /* FIXME: Changing back to the first line is not detected. */
2515 if (view->offset != 0 || view->lineno != 0) {
2516 view->p_restore = FALSE;
2517 return FALSE;
2518 }
2520 if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2521 view_is_displayed(view))
2522 werase(view->win);
2524 view->yoffset = view->p_yoffset;
2525 view->p_restore = FALSE;
2527 return TRUE;
2528 }
2530 static void
2531 end_update(struct view *view, bool force)
2532 {
2533 if (!view->pipe)
2534 return;
2535 while (!view->ops->read(view, NULL))
2536 if (!force)
2537 return;
2538 if (force)
2539 io_kill(view->pipe);
2540 io_done(view->pipe);
2541 view->pipe = NULL;
2542 }
2544 static void
2545 setup_update(struct view *view, const char *vid)
2546 {
2547 reset_view(view);
2548 string_copy_rev(view->vid, vid);
2549 view->pipe = &view->io;
2550 view->start_time = time(NULL);
2551 }
2553 static bool
2554 begin_update(struct view *view, const char *dir, const char **argv, enum open_flags flags)
2555 {
2556 bool extra = !!(flags & (OPEN_EXTRA));
2557 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED | OPEN_EXTRA));
2558 bool refresh = flags & (OPEN_REFRESH | OPEN_PREPARED);
2560 if (!reload && !strcmp(view->vid, view->id))
2561 return TRUE;
2563 if (view->pipe) {
2564 if (extra)
2565 io_done(view->pipe);
2566 else
2567 end_update(view, TRUE);
2568 }
2570 if (!refresh) {
2571 view->dir = dir;
2572 if (!format_argv(&view->argv, argv, !view->prev))
2573 return FALSE;
2575 /* Put the current ref_* value to the view title ref
2576 * member. This is needed by the blob view. Most other
2577 * views sets it automatically after loading because the
2578 * first line is a commit line. */
2579 string_copy_rev(view->ref, view->id);
2580 }
2582 if (view->argv && view->argv[0] &&
2583 !io_run(&view->io, IO_RD, view->dir, view->argv))
2584 return FALSE;
2586 if (!extra)
2587 setup_update(view, view->id);
2589 return TRUE;
2590 }
2592 static bool
2593 view_open(struct view *view, enum open_flags flags)
2594 {
2595 return begin_update(view, NULL, NULL, flags);
2596 }
2598 static bool
2599 update_view(struct view *view)
2600 {
2601 char out_buffer[BUFSIZ * 2];
2602 char *line;
2603 /* Clear the view and redraw everything since the tree sorting
2604 * might have rearranged things. */
2605 bool redraw = view->lines == 0;
2606 bool can_read = TRUE;
2608 if (!view->pipe)
2609 return TRUE;
2611 if (!io_can_read(view->pipe, FALSE)) {
2612 if (view->lines == 0 && view_is_displayed(view)) {
2613 time_t secs = time(NULL) - view->start_time;
2615 if (secs > 1 && secs > view->update_secs) {
2616 if (view->update_secs == 0)
2617 redraw_view(view);
2618 update_view_title(view);
2619 view->update_secs = secs;
2620 }
2621 }
2622 return TRUE;
2623 }
2625 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2626 if (opt_iconv_in != ICONV_NONE) {
2627 ICONV_CONST char *inbuf = line;
2628 size_t inlen = strlen(line) + 1;
2630 char *outbuf = out_buffer;
2631 size_t outlen = sizeof(out_buffer);
2633 size_t ret;
2635 ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2636 if (ret != (size_t) -1)
2637 line = out_buffer;
2638 }
2640 if (!view->ops->read(view, line)) {
2641 report("Allocation failure");
2642 end_update(view, TRUE);
2643 return FALSE;
2644 }
2645 }
2647 {
2648 unsigned long lines = view->lines;
2649 int digits;
2651 for (digits = 0; lines; digits++)
2652 lines /= 10;
2654 /* Keep the displayed view in sync with line number scaling. */
2655 if (digits != view->digits) {
2656 view->digits = digits;
2657 if (opt_line_number || view->type == VIEW_BLAME)
2658 redraw = TRUE;
2659 }
2660 }
2662 if (io_error(view->pipe)) {
2663 report("Failed to read: %s", io_strerror(view->pipe));
2664 end_update(view, TRUE);
2666 } else if (io_eof(view->pipe)) {
2667 if (view_is_displayed(view))
2668 report("");
2669 end_update(view, FALSE);
2670 }
2672 if (restore_view_position(view))
2673 redraw = TRUE;
2675 if (!view_is_displayed(view))
2676 return TRUE;
2678 if (redraw)
2679 redraw_view_from(view, 0);
2680 else
2681 redraw_view_dirty(view);
2683 /* Update the title _after_ the redraw so that if the redraw picks up a
2684 * commit reference in view->ref it'll be available here. */
2685 update_view_title(view);
2686 return TRUE;
2687 }
2689 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2691 static struct line *
2692 add_line_data(struct view *view, void *data, enum line_type type)
2693 {
2694 struct line *line;
2696 if (!realloc_lines(&view->line, view->lines, 1))
2697 return NULL;
2699 line = &view->line[view->lines++];
2700 memset(line, 0, sizeof(*line));
2701 line->type = type;
2702 line->data = data;
2703 line->dirty = 1;
2705 return line;
2706 }
2708 static struct line *
2709 add_line_text(struct view *view, const char *text, enum line_type type)
2710 {
2711 char *data = text ? strdup(text) : NULL;
2713 return data ? add_line_data(view, data, type) : NULL;
2714 }
2716 static struct line *
2717 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2718 {
2719 char buf[SIZEOF_STR];
2720 va_list args;
2722 va_start(args, fmt);
2723 if (vsnprintf(buf, sizeof(buf), fmt, args) >= sizeof(buf))
2724 buf[0] = 0;
2725 va_end(args);
2727 return buf[0] ? add_line_text(view, buf, type) : NULL;
2728 }
2730 /*
2731 * View opening
2732 */
2734 static void
2735 load_view(struct view *view, enum open_flags flags)
2736 {
2737 if (view->pipe)
2738 end_update(view, TRUE);
2739 if (!view->ops->open(view, flags)) {
2740 report("Failed to load %s view", view->name);
2741 return;
2742 }
2743 restore_view_position(view);
2745 if (view->pipe && view->lines == 0) {
2746 /* Clear the old view and let the incremental updating refill
2747 * the screen. */
2748 werase(view->win);
2749 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2750 report("");
2751 } else if (view_is_displayed(view)) {
2752 redraw_view(view);
2753 report("");
2754 }
2755 }
2757 #define refresh_view(view) load_view(view, OPEN_REFRESH)
2759 static void
2760 split_view(struct view *prev, struct view *view)
2761 {
2762 display[1] = view;
2763 current_view = 1;
2764 view->parent = prev;
2765 resize_display();
2767 if (prev->lineno - prev->offset >= prev->height) {
2768 /* Take the title line into account. */
2769 int lines = prev->lineno - prev->offset - prev->height + 1;
2771 /* Scroll the view that was split if the current line is
2772 * outside the new limited view. */
2773 do_scroll_view(prev, lines);
2774 }
2776 if (view != prev && view_is_displayed(prev)) {
2777 /* "Blur" the previous view. */
2778 update_view_title(prev);
2779 }
2780 }
2782 static void
2783 open_view(struct view *prev, enum request request, enum open_flags flags)
2784 {
2785 bool split = !!(flags & OPEN_SPLIT);
2786 bool reload = !!(flags & (OPEN_RELOAD | OPEN_PREPARED));
2787 struct view *view = VIEW(request);
2788 int nviews = displayed_views();
2790 assert(flags ^ OPEN_REFRESH);
2792 if (view == prev && nviews == 1 && !reload) {
2793 report("Already in %s view", view->name);
2794 return;
2795 }
2797 if (view->git_dir && !opt_git_dir[0]) {
2798 report("The %s view is disabled in pager view", view->name);
2799 return;
2800 }
2802 if (split) {
2803 split_view(prev, view);
2804 } else {
2805 maximize_view(view, FALSE);
2806 }
2808 /* No prev signals that this is the first loaded view. */
2809 if (prev && view != prev) {
2810 view->prev = prev;
2811 }
2813 load_view(view, flags);
2814 }
2816 static void
2817 open_argv(struct view *prev, struct view *view, const char *argv[], const char *dir, enum open_flags flags)
2818 {
2819 enum request request = view - views + REQ_OFFSET + 1;
2821 if (view->pipe)
2822 end_update(view, TRUE);
2823 view->dir = dir;
2825 if (!argv_copy(&view->argv, argv)) {
2826 report("Failed to open %s view: %s", view->name, io_strerror(&view->io));
2827 } else {
2828 open_view(prev, request, flags | OPEN_PREPARED);
2829 }
2830 }
2832 static void
2833 open_file(struct view *prev, struct view *view, const char *file, enum open_flags flags)
2834 {
2835 const char *file_argv[] = { opt_cdup, file , NULL };
2837 open_argv(prev, view, file_argv, opt_cdup, flags);
2838 }
2840 static void
2841 open_external_viewer(const char *argv[], const char *dir)
2842 {
2843 def_prog_mode(); /* save current tty modes */
2844 endwin(); /* restore original tty modes */
2845 io_run_fg(argv, dir);
2846 fprintf(stderr, "Press Enter to continue");
2847 getc(opt_tty);
2848 reset_prog_mode();
2849 redraw_display(TRUE);
2850 }
2852 static void
2853 open_mergetool(const char *file)
2854 {
2855 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2857 open_external_viewer(mergetool_argv, opt_cdup);
2858 }
2860 static void
2861 open_editor(const char *file)
2862 {
2863 const char *editor_argv[] = { "vi", file, NULL };
2864 const char *editor;
2866 editor = getenv("GIT_EDITOR");
2867 if (!editor && *opt_editor)
2868 editor = opt_editor;
2869 if (!editor)
2870 editor = getenv("VISUAL");
2871 if (!editor)
2872 editor = getenv("EDITOR");
2873 if (!editor)
2874 editor = "vi";
2876 editor_argv[0] = editor;
2877 open_external_viewer(editor_argv, opt_cdup);
2878 }
2880 static void
2881 open_run_request(enum request request)
2882 {
2883 struct run_request *req = get_run_request(request);
2884 const char **argv = NULL;
2886 if (!req) {
2887 report("Unknown run request");
2888 return;
2889 }
2891 if (format_argv(&argv, req->argv, FALSE))
2892 open_external_viewer(argv, NULL);
2893 if (argv)
2894 argv_free(argv);
2895 free(argv);
2896 }
2898 /*
2899 * User request switch noodle
2900 */
2902 static int
2903 view_driver(struct view *view, enum request request)
2904 {
2905 int i;
2907 if (request == REQ_NONE)
2908 return TRUE;
2910 if (request > REQ_NONE) {
2911 open_run_request(request);
2912 view_request(view, REQ_REFRESH);
2913 return TRUE;
2914 }
2916 request = view_request(view, request);
2917 if (request == REQ_NONE)
2918 return TRUE;
2920 switch (request) {
2921 case REQ_MOVE_UP:
2922 case REQ_MOVE_DOWN:
2923 case REQ_MOVE_PAGE_UP:
2924 case REQ_MOVE_PAGE_DOWN:
2925 case REQ_MOVE_FIRST_LINE:
2926 case REQ_MOVE_LAST_LINE:
2927 move_view(view, request);
2928 break;
2930 case REQ_SCROLL_FIRST_COL:
2931 case REQ_SCROLL_LEFT:
2932 case REQ_SCROLL_RIGHT:
2933 case REQ_SCROLL_LINE_DOWN:
2934 case REQ_SCROLL_LINE_UP:
2935 case REQ_SCROLL_PAGE_DOWN:
2936 case REQ_SCROLL_PAGE_UP:
2937 scroll_view(view, request);
2938 break;
2940 case REQ_VIEW_BLAME:
2941 if (!opt_file[0]) {
2942 report("No file chosen, press %s to open tree view",
2943 get_key(view->keymap, REQ_VIEW_TREE));
2944 break;
2945 }
2946 open_view(view, request, OPEN_DEFAULT);
2947 break;
2949 case REQ_VIEW_BLOB:
2950 if (!ref_blob[0]) {
2951 report("No file chosen, press %s to open tree view",
2952 get_key(view->keymap, REQ_VIEW_TREE));
2953 break;
2954 }
2955 open_view(view, request, OPEN_DEFAULT);
2956 break;
2958 case REQ_VIEW_PAGER:
2959 if (view == NULL) {
2960 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
2961 die("Failed to open stdin");
2962 open_view(view, request, OPEN_PREPARED);
2963 break;
2964 }
2966 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
2967 report("No pager content, press %s to run command from prompt",
2968 get_key(view->keymap, REQ_PROMPT));
2969 break;
2970 }
2971 open_view(view, request, OPEN_DEFAULT);
2972 break;
2974 case REQ_VIEW_STAGE:
2975 if (!VIEW(REQ_VIEW_STAGE)->lines) {
2976 report("No stage content, press %s to open the status view and choose file",
2977 get_key(view->keymap, REQ_VIEW_STATUS));
2978 break;
2979 }
2980 open_view(view, request, OPEN_DEFAULT);
2981 break;
2983 case REQ_VIEW_STATUS:
2984 if (opt_is_inside_work_tree == FALSE) {
2985 report("The status view requires a working tree");
2986 break;
2987 }
2988 open_view(view, request, OPEN_DEFAULT);
2989 break;
2991 case REQ_VIEW_MAIN:
2992 case REQ_VIEW_DIFF:
2993 case REQ_VIEW_LOG:
2994 case REQ_VIEW_TREE:
2995 case REQ_VIEW_HELP:
2996 case REQ_VIEW_BRANCH:
2997 open_view(view, request, OPEN_DEFAULT);
2998 break;
3000 case REQ_NEXT:
3001 case REQ_PREVIOUS:
3002 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
3004 if (view->parent) {
3005 int line;
3007 view = view->parent;
3008 line = view->lineno;
3009 move_view(view, request);
3010 if (view_is_displayed(view))
3011 update_view_title(view);
3012 if (line != view->lineno)
3013 view_request(view, REQ_ENTER);
3014 } else {
3015 move_view(view, request);
3016 }
3017 break;
3019 case REQ_VIEW_NEXT:
3020 {
3021 int nviews = displayed_views();
3022 int next_view = (current_view + 1) % nviews;
3024 if (next_view == current_view) {
3025 report("Only one view is displayed");
3026 break;
3027 }
3029 current_view = next_view;
3030 /* Blur out the title of the previous view. */
3031 update_view_title(view);
3032 report("");
3033 break;
3034 }
3035 case REQ_REFRESH:
3036 report("Refreshing is not yet supported for the %s view", view->name);
3037 break;
3039 case REQ_MAXIMIZE:
3040 if (displayed_views() == 2)
3041 maximize_view(view, TRUE);
3042 break;
3044 case REQ_OPTIONS:
3045 case REQ_TOGGLE_LINENO:
3046 case REQ_TOGGLE_DATE:
3047 case REQ_TOGGLE_AUTHOR:
3048 case REQ_TOGGLE_GRAPHIC:
3049 case REQ_TOGGLE_REV_GRAPH:
3050 case REQ_TOGGLE_REFS:
3051 toggle_option(request);
3052 break;
3054 case REQ_TOGGLE_SORT_FIELD:
3055 case REQ_TOGGLE_SORT_ORDER:
3056 report("Sorting is not yet supported for the %s view", view->name);
3057 break;
3059 case REQ_SEARCH:
3060 case REQ_SEARCH_BACK:
3061 search_view(view, request);
3062 break;
3064 case REQ_FIND_NEXT:
3065 case REQ_FIND_PREV:
3066 find_next(view, request);
3067 break;
3069 case REQ_STOP_LOADING:
3070 foreach_view(view, i) {
3071 if (view->pipe)
3072 report("Stopped loading the %s view", view->name),
3073 end_update(view, TRUE);
3074 }
3075 break;
3077 case REQ_SHOW_VERSION:
3078 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3079 return TRUE;
3081 case REQ_SCREEN_REDRAW:
3082 redraw_display(TRUE);
3083 break;
3085 case REQ_EDIT:
3086 report("Nothing to edit");
3087 break;
3089 case REQ_ENTER:
3090 report("Nothing to enter");
3091 break;
3093 case REQ_VIEW_CLOSE:
3094 /* XXX: Mark closed views by letting view->prev point to the
3095 * view itself. Parents to closed view should never be
3096 * followed. */
3097 if (view->prev && view->prev != view) {
3098 maximize_view(view->prev, TRUE);
3099 view->prev = view;
3100 break;
3101 }
3102 /* Fall-through */
3103 case REQ_QUIT:
3104 return FALSE;
3106 default:
3107 report("Unknown key, press %s for help",
3108 get_key(view->keymap, REQ_VIEW_HELP));
3109 return TRUE;
3110 }
3112 return TRUE;
3113 }
3116 /*
3117 * View backend utilities
3118 */
3120 enum sort_field {
3121 ORDERBY_NAME,
3122 ORDERBY_DATE,
3123 ORDERBY_AUTHOR,
3124 };
3126 struct sort_state {
3127 const enum sort_field *fields;
3128 size_t size, current;
3129 bool reverse;
3130 };
3132 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3133 #define get_sort_field(state) ((state).fields[(state).current])
3134 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3136 static void
3137 sort_view(struct view *view, enum request request, struct sort_state *state,
3138 int (*compare)(const void *, const void *))
3139 {
3140 switch (request) {
3141 case REQ_TOGGLE_SORT_FIELD:
3142 state->current = (state->current + 1) % state->size;
3143 break;
3145 case REQ_TOGGLE_SORT_ORDER:
3146 state->reverse = !state->reverse;
3147 break;
3148 default:
3149 die("Not a sort request");
3150 }
3152 qsort(view->line, view->lines, sizeof(*view->line), compare);
3153 redraw_view(view);
3154 }
3156 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3158 /* Small author cache to reduce memory consumption. It uses binary
3159 * search to lookup or find place to position new entries. No entries
3160 * are ever freed. */
3161 static const char *
3162 get_author(const char *name)
3163 {
3164 static const char **authors;
3165 static size_t authors_size;
3166 int from = 0, to = authors_size - 1;
3168 while (from <= to) {
3169 size_t pos = (to + from) / 2;
3170 int cmp = strcmp(name, authors[pos]);
3172 if (!cmp)
3173 return authors[pos];
3175 if (cmp < 0)
3176 to = pos - 1;
3177 else
3178 from = pos + 1;
3179 }
3181 if (!realloc_authors(&authors, authors_size, 1))
3182 return NULL;
3183 name = strdup(name);
3184 if (!name)
3185 return NULL;
3187 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3188 authors[from] = name;
3189 authors_size++;
3191 return name;
3192 }
3194 static void
3195 parse_timesec(struct time *time, const char *sec)
3196 {
3197 time->sec = (time_t) atol(sec);
3198 }
3200 static void
3201 parse_timezone(struct time *time, const char *zone)
3202 {
3203 long tz;
3205 tz = ('0' - zone[1]) * 60 * 60 * 10;
3206 tz += ('0' - zone[2]) * 60 * 60;
3207 tz += ('0' - zone[3]) * 60 * 10;
3208 tz += ('0' - zone[4]) * 60;
3210 if (zone[0] == '-')
3211 tz = -tz;
3213 time->tz = tz;
3214 time->sec -= tz;
3215 }
3217 /* Parse author lines where the name may be empty:
3218 * author <email@address.tld> 1138474660 +0100
3219 */
3220 static void
3221 parse_author_line(char *ident, const char **author, struct time *time)
3222 {
3223 char *nameend = strchr(ident, '<');
3224 char *emailend = strchr(ident, '>');
3226 if (nameend && emailend)
3227 *nameend = *emailend = 0;
3228 ident = chomp_string(ident);
3229 if (!*ident) {
3230 if (nameend)
3231 ident = chomp_string(nameend + 1);
3232 if (!*ident)
3233 ident = "Unknown";
3234 }
3236 *author = get_author(ident);
3238 /* Parse epoch and timezone */
3239 if (emailend && emailend[1] == ' ') {
3240 char *secs = emailend + 2;
3241 char *zone = strchr(secs, ' ');
3243 parse_timesec(time, secs);
3245 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3246 parse_timezone(time, zone + 1);
3247 }
3248 }
3250 /*
3251 * Pager backend
3252 */
3254 static bool
3255 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3256 {
3257 if (opt_line_number && draw_lineno(view, lineno))
3258 return TRUE;
3260 draw_text(view, line->type, line->data);
3261 return TRUE;
3262 }
3264 static bool
3265 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3266 {
3267 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3268 char ref[SIZEOF_STR];
3270 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3271 return TRUE;
3273 /* This is the only fatal call, since it can "corrupt" the buffer. */
3274 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3275 return FALSE;
3277 return TRUE;
3278 }
3280 static void
3281 add_pager_refs(struct view *view, struct line *line)
3282 {
3283 char buf[SIZEOF_STR];
3284 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3285 struct ref_list *list;
3286 size_t bufpos = 0, i;
3287 const char *sep = "Refs: ";
3288 bool is_tag = FALSE;
3290 assert(line->type == LINE_COMMIT);
3292 list = get_ref_list(commit_id);
3293 if (!list) {
3294 if (view->type == VIEW_DIFF)
3295 goto try_add_describe_ref;
3296 return;
3297 }
3299 for (i = 0; i < list->size; i++) {
3300 struct ref *ref = list->refs[i];
3301 const char *fmt = ref->tag ? "%s[%s]" :
3302 ref->remote ? "%s<%s>" : "%s%s";
3304 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3305 return;
3306 sep = ", ";
3307 if (ref->tag)
3308 is_tag = TRUE;
3309 }
3311 if (!is_tag && view->type == VIEW_DIFF) {
3312 try_add_describe_ref:
3313 /* Add <tag>-g<commit_id> "fake" reference. */
3314 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3315 return;
3316 }
3318 if (bufpos == 0)
3319 return;
3321 add_line_text(view, buf, LINE_PP_REFS);
3322 }
3324 static bool
3325 pager_read(struct view *view, char *data)
3326 {
3327 struct line *line;
3329 if (!data)
3330 return TRUE;
3332 line = add_line_text(view, data, get_line_type(data));
3333 if (!line)
3334 return FALSE;
3336 if (line->type == LINE_COMMIT &&
3337 (view->type == VIEW_DIFF ||
3338 view->type == VIEW_LOG))
3339 add_pager_refs(view, line);
3341 return TRUE;
3342 }
3344 static enum request
3345 pager_request(struct view *view, enum request request, struct line *line)
3346 {
3347 int split = 0;
3349 if (request != REQ_ENTER)
3350 return request;
3352 if (line->type == LINE_COMMIT &&
3353 (view->type == VIEW_LOG ||
3354 view->type == VIEW_PAGER)) {
3355 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3356 split = 1;
3357 }
3359 /* Always scroll the view even if it was split. That way
3360 * you can use Enter to scroll through the log view and
3361 * split open each commit diff. */
3362 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3364 /* FIXME: A minor workaround. Scrolling the view will call report("")
3365 * but if we are scrolling a non-current view this won't properly
3366 * update the view title. */
3367 if (split)
3368 update_view_title(view);
3370 return REQ_NONE;
3371 }
3373 static bool
3374 pager_grep(struct view *view, struct line *line)
3375 {
3376 const char *text[] = { line->data, NULL };
3378 return grep_text(view, text);
3379 }
3381 static void
3382 pager_select(struct view *view, struct line *line)
3383 {
3384 if (line->type == LINE_COMMIT) {
3385 char *text = (char *)line->data + STRING_SIZE("commit ");
3387 if (view->type != VIEW_PAGER)
3388 string_copy_rev(view->ref, text);
3389 string_copy_rev(ref_commit, text);
3390 }
3391 }
3393 static struct view_ops pager_ops = {
3394 "line",
3395 view_open,
3396 pager_read,
3397 pager_draw,
3398 pager_request,
3399 pager_grep,
3400 pager_select,
3401 };
3403 static bool
3404 log_open(struct view *view, enum open_flags flags)
3405 {
3406 static const char *log_argv[] = {
3407 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3408 };
3410 return begin_update(view, NULL, log_argv, flags);
3411 }
3413 static enum request
3414 log_request(struct view *view, enum request request, struct line *line)
3415 {
3416 switch (request) {
3417 case REQ_REFRESH:
3418 load_refs();
3419 refresh_view(view);
3420 return REQ_NONE;
3421 default:
3422 return pager_request(view, request, line);
3423 }
3424 }
3426 static struct view_ops log_ops = {
3427 "line",
3428 log_open,
3429 pager_read,
3430 pager_draw,
3431 log_request,
3432 pager_grep,
3433 pager_select,
3434 };
3436 static bool
3437 diff_open(struct view *view, enum open_flags flags)
3438 {
3439 static const char *diff_argv[] = {
3440 "git", "show", "--pretty=fuller", "--no-color", "--root",
3441 "--patch-with-stat", "--find-copies-harder", "-C",
3442 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3443 };
3445 return begin_update(view, NULL, diff_argv, flags);
3446 }
3448 static bool
3449 diff_read(struct view *view, char *data)
3450 {
3451 if (!data) {
3452 /* Fall back to retry if no diff will be shown. */
3453 if (view->lines == 0 && opt_file_argv) {
3454 int pos = argv_size(view->argv)
3455 - argv_size(opt_file_argv) - 1;
3457 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3458 for (; view->argv[pos]; pos++) {
3459 free((void *) view->argv[pos]);
3460 view->argv[pos] = NULL;
3461 }
3463 if (view->pipe)
3464 io_done(view->pipe);
3465 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3466 return FALSE;
3467 }
3468 }
3469 return TRUE;
3470 }
3472 return pager_read(view, data);
3473 }
3475 static struct view_ops diff_ops = {
3476 "line",
3477 diff_open,
3478 diff_read,
3479 pager_draw,
3480 pager_request,
3481 pager_grep,
3482 pager_select,
3483 };
3485 /*
3486 * Help backend
3487 */
3489 static bool help_keymap_hidden[ARRAY_SIZE(keymap_table)];
3491 static bool
3492 help_open_keymap_title(struct view *view, enum keymap keymap)
3493 {
3494 struct line *line;
3496 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
3497 help_keymap_hidden[keymap] ? '+' : '-',
3498 enum_name(keymap_table[keymap]));
3499 if (line)
3500 line->other = keymap;
3502 return help_keymap_hidden[keymap];
3503 }
3505 static void
3506 help_open_keymap(struct view *view, enum keymap keymap)
3507 {
3508 const char *group = NULL;
3509 char buf[SIZEOF_STR];
3510 size_t bufpos;
3511 bool add_title = TRUE;
3512 int i;
3514 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
3515 const char *key = NULL;
3517 if (req_info[i].request == REQ_NONE)
3518 continue;
3520 if (!req_info[i].request) {
3521 group = req_info[i].help;
3522 continue;
3523 }
3525 key = get_keys(keymap, req_info[i].request, TRUE);
3526 if (!key || !*key)
3527 continue;
3529 if (add_title && help_open_keymap_title(view, keymap))
3530 return;
3531 add_title = FALSE;
3533 if (group) {
3534 add_line_text(view, group, LINE_HELP_GROUP);
3535 group = NULL;
3536 }
3538 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
3539 enum_name(req_info[i]), req_info[i].help);
3540 }
3542 group = "External commands:";
3544 for (i = 0; i < run_requests; i++) {
3545 struct run_request *req = get_run_request(REQ_NONE + i + 1);
3546 const char *key;
3547 int argc;
3549 if (!req || req->keymap != keymap)
3550 continue;
3552 key = get_key_name(req->key);
3553 if (!*key)
3554 key = "(no key defined)";
3556 if (add_title && help_open_keymap_title(view, keymap))
3557 return;
3558 if (group) {
3559 add_line_text(view, group, LINE_HELP_GROUP);
3560 group = NULL;
3561 }
3563 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
3564 if (!string_format_from(buf, &bufpos, "%s%s",
3565 argc ? " " : "", req->argv[argc]))
3566 return;
3568 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
3569 }
3570 }
3572 static bool
3573 help_open(struct view *view, enum open_flags flags)
3574 {
3575 enum keymap keymap;
3577 reset_view(view);
3578 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
3579 add_line_text(view, "", LINE_DEFAULT);
3581 for (keymap = 0; keymap < ARRAY_SIZE(keymap_table); keymap++)
3582 help_open_keymap(view, keymap);
3584 return TRUE;
3585 }
3587 static enum request
3588 help_request(struct view *view, enum request request, struct line *line)
3589 {
3590 switch (request) {
3591 case REQ_ENTER:
3592 if (line->type == LINE_HELP_KEYMAP) {
3593 help_keymap_hidden[line->other] =
3594 !help_keymap_hidden[line->other];
3595 refresh_view(view);
3596 }
3598 return REQ_NONE;
3599 default:
3600 return pager_request(view, request, line);
3601 }
3602 }
3604 static struct view_ops help_ops = {
3605 "line",
3606 help_open,
3607 NULL,
3608 pager_draw,
3609 help_request,
3610 pager_grep,
3611 pager_select,
3612 };
3615 /*
3616 * Tree backend
3617 */
3619 struct tree_stack_entry {
3620 struct tree_stack_entry *prev; /* Entry below this in the stack */
3621 unsigned long lineno; /* Line number to restore */
3622 char *name; /* Position of name in opt_path */
3623 };
3625 /* The top of the path stack. */
3626 static struct tree_stack_entry *tree_stack = NULL;
3627 unsigned long tree_lineno = 0;
3629 static void
3630 pop_tree_stack_entry(void)
3631 {
3632 struct tree_stack_entry *entry = tree_stack;
3634 tree_lineno = entry->lineno;
3635 entry->name[0] = 0;
3636 tree_stack = entry->prev;
3637 free(entry);
3638 }
3640 static void
3641 push_tree_stack_entry(const char *name, unsigned long lineno)
3642 {
3643 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
3644 size_t pathlen = strlen(opt_path);
3646 if (!entry)
3647 return;
3649 entry->prev = tree_stack;
3650 entry->name = opt_path + pathlen;
3651 tree_stack = entry;
3653 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
3654 pop_tree_stack_entry();
3655 return;
3656 }
3658 /* Move the current line to the first tree entry. */
3659 tree_lineno = 1;
3660 entry->lineno = lineno;
3661 }
3663 /* Parse output from git-ls-tree(1):
3664 *
3665 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
3666 */
3668 #define SIZEOF_TREE_ATTR \
3669 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
3671 #define SIZEOF_TREE_MODE \
3672 STRING_SIZE("100644 ")
3674 #define TREE_ID_OFFSET \
3675 STRING_SIZE("100644 blob ")
3677 struct tree_entry {
3678 char id[SIZEOF_REV];
3679 mode_t mode;
3680 struct time time; /* Date from the author ident. */
3681 const char *author; /* Author of the commit. */
3682 char name[1];
3683 };
3685 static const char *
3686 tree_path(const struct line *line)
3687 {
3688 return ((struct tree_entry *) line->data)->name;
3689 }
3691 static int
3692 tree_compare_entry(const struct line *line1, const struct line *line2)
3693 {
3694 if (line1->type != line2->type)
3695 return line1->type == LINE_TREE_DIR ? -1 : 1;
3696 return strcmp(tree_path(line1), tree_path(line2));
3697 }
3699 static const enum sort_field tree_sort_fields[] = {
3700 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
3701 };
3702 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
3704 static int
3705 tree_compare(const void *l1, const void *l2)
3706 {
3707 const struct line *line1 = (const struct line *) l1;
3708 const struct line *line2 = (const struct line *) l2;
3709 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
3710 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
3712 if (line1->type == LINE_TREE_HEAD)
3713 return -1;
3714 if (line2->type == LINE_TREE_HEAD)
3715 return 1;
3717 switch (get_sort_field(tree_sort_state)) {
3718 case ORDERBY_DATE:
3719 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
3721 case ORDERBY_AUTHOR:
3722 return sort_order(tree_sort_state, strcmp(entry1->author, entry2->author));
3724 case ORDERBY_NAME:
3725 default:
3726 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
3727 }
3728 }
3731 static struct line *
3732 tree_entry(struct view *view, enum line_type type, const char *path,
3733 const char *mode, const char *id)
3734 {
3735 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
3736 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
3738 if (!entry || !line) {
3739 free(entry);
3740 return NULL;
3741 }
3743 strncpy(entry->name, path, strlen(path));
3744 if (mode)
3745 entry->mode = strtoul(mode, NULL, 8);
3746 if (id)
3747 string_copy_rev(entry->id, id);
3749 return line;
3750 }
3752 static bool
3753 tree_read_date(struct view *view, char *text, bool *read_date)
3754 {
3755 static const char *author_name;
3756 static struct time author_time;
3758 if (!text && *read_date) {
3759 *read_date = FALSE;
3760 return TRUE;
3762 } else if (!text) {
3763 /* Find next entry to process */
3764 const char *log_file[] = {
3765 "git", "log", "--no-color", "--pretty=raw",
3766 "--cc", "--raw", view->id, "--", "%(directory)", NULL
3767 };
3769 if (!view->lines) {
3770 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
3771 report("Tree is empty");
3772 return TRUE;
3773 }
3775 if (!begin_update(view, opt_cdup, log_file, OPEN_EXTRA)) {
3776 report("Failed to load tree data");
3777 return TRUE;
3778 }
3780 *read_date = TRUE;
3781 return FALSE;
3783 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
3784 parse_author_line(text + STRING_SIZE("author "),
3785 &author_name, &author_time);
3787 } else if (*text == ':') {
3788 char *pos;
3789 size_t annotated = 1;
3790 size_t i;
3792 pos = strchr(text, '\t');
3793 if (!pos)
3794 return TRUE;
3795 text = pos + 1;
3796 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
3797 text += strlen(opt_path);
3798 pos = strchr(text, '/');
3799 if (pos)
3800 *pos = 0;
3802 for (i = 1; i < view->lines; i++) {
3803 struct line *line = &view->line[i];
3804 struct tree_entry *entry = line->data;
3806 annotated += !!entry->author;
3807 if (entry->author || strcmp(entry->name, text))
3808 continue;
3810 entry->author = author_name;
3811 entry->time = author_time;
3812 line->dirty = 1;
3813 break;
3814 }
3816 if (annotated == view->lines)
3817 io_kill(view->pipe);
3818 }
3819 return TRUE;
3820 }
3822 static bool
3823 tree_read(struct view *view, char *text)
3824 {
3825 static bool read_date = FALSE;
3826 struct tree_entry *data;
3827 struct line *entry, *line;
3828 enum line_type type;
3829 size_t textlen = text ? strlen(text) : 0;
3830 char *path = text + SIZEOF_TREE_ATTR;
3832 if (read_date || !text)
3833 return tree_read_date(view, text, &read_date);
3835 if (textlen <= SIZEOF_TREE_ATTR)
3836 return FALSE;
3837 if (view->lines == 0 &&
3838 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
3839 return FALSE;
3841 /* Strip the path part ... */
3842 if (*opt_path) {
3843 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
3844 size_t striplen = strlen(opt_path);
3846 if (pathlen > striplen)
3847 memmove(path, path + striplen,
3848 pathlen - striplen + 1);
3850 /* Insert "link" to parent directory. */
3851 if (view->lines == 1 &&
3852 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
3853 return FALSE;
3854 }
3856 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
3857 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
3858 if (!entry)
3859 return FALSE;
3860 data = entry->data;
3862 /* Skip "Directory ..." and ".." line. */
3863 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
3864 if (tree_compare_entry(line, entry) <= 0)
3865 continue;
3867 memmove(line + 1, line, (entry - line) * sizeof(*entry));
3869 line->data = data;
3870 line->type = type;
3871 for (; line <= entry; line++)
3872 line->dirty = line->cleareol = 1;
3873 return TRUE;
3874 }
3876 if (tree_lineno > view->lineno) {
3877 view->lineno = tree_lineno;
3878 tree_lineno = 0;
3879 }
3881 return TRUE;
3882 }
3884 static bool
3885 tree_draw(struct view *view, struct line *line, unsigned int lineno)
3886 {
3887 struct tree_entry *entry = line->data;
3889 if (line->type == LINE_TREE_HEAD) {
3890 if (draw_text(view, line->type, "Directory path /"))
3891 return TRUE;
3892 } else {
3893 if (draw_mode(view, entry->mode))
3894 return TRUE;
3896 if (draw_author(view, entry->author))
3897 return TRUE;
3899 if (draw_date(view, &entry->time))
3900 return TRUE;
3901 }
3903 draw_text(view, line->type, entry->name);
3904 return TRUE;
3905 }
3907 static void
3908 open_blob_editor(const char *id)
3909 {
3910 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
3911 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
3912 int fd = mkstemp(file);
3914 if (fd == -1)
3915 report("Failed to create temporary file");
3916 else if (!io_run_append(blob_argv, fd))
3917 report("Failed to save blob data to file");
3918 else
3919 open_editor(file);
3920 if (fd != -1)
3921 unlink(file);
3922 }
3924 static enum request
3925 tree_request(struct view *view, enum request request, struct line *line)
3926 {
3927 enum open_flags flags;
3928 struct tree_entry *entry = line->data;
3930 switch (request) {
3931 case REQ_VIEW_BLAME:
3932 if (line->type != LINE_TREE_FILE) {
3933 report("Blame only supported for files");
3934 return REQ_NONE;
3935 }
3937 string_copy(opt_ref, view->vid);
3938 return request;
3940 case REQ_EDIT:
3941 if (line->type != LINE_TREE_FILE) {
3942 report("Edit only supported for files");
3943 } else if (!is_head_commit(view->vid)) {
3944 open_blob_editor(entry->id);
3945 } else {
3946 open_editor(opt_file);
3947 }
3948 return REQ_NONE;
3950 case REQ_TOGGLE_SORT_FIELD:
3951 case REQ_TOGGLE_SORT_ORDER:
3952 sort_view(view, request, &tree_sort_state, tree_compare);
3953 return REQ_NONE;
3955 case REQ_PARENT:
3956 if (!*opt_path) {
3957 /* quit view if at top of tree */
3958 return REQ_VIEW_CLOSE;
3959 }
3960 /* fake 'cd ..' */
3961 line = &view->line[1];
3962 break;
3964 case REQ_ENTER:
3965 break;
3967 default:
3968 return request;
3969 }
3971 /* Cleanup the stack if the tree view is at a different tree. */
3972 while (!*opt_path && tree_stack)
3973 pop_tree_stack_entry();
3975 switch (line->type) {
3976 case LINE_TREE_DIR:
3977 /* Depending on whether it is a subdirectory or parent link
3978 * mangle the path buffer. */
3979 if (line == &view->line[1] && *opt_path) {
3980 pop_tree_stack_entry();
3982 } else {
3983 const char *basename = tree_path(line);
3985 push_tree_stack_entry(basename, view->lineno);
3986 }
3988 /* Trees and subtrees share the same ID, so they are not not
3989 * unique like blobs. */
3990 flags = OPEN_RELOAD;
3991 request = REQ_VIEW_TREE;
3992 break;
3994 case LINE_TREE_FILE:
3995 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
3996 request = REQ_VIEW_BLOB;
3997 break;
3999 default:
4000 return REQ_NONE;
4001 }
4003 open_view(view, request, flags);
4004 if (request == REQ_VIEW_TREE)
4005 view->lineno = tree_lineno;
4007 return REQ_NONE;
4008 }
4010 static bool
4011 tree_grep(struct view *view, struct line *line)
4012 {
4013 struct tree_entry *entry = line->data;
4014 const char *text[] = {
4015 entry->name,
4016 opt_author ? entry->author : "",
4017 mkdate(&entry->time, opt_date),
4018 NULL
4019 };
4021 return grep_text(view, text);
4022 }
4024 static void
4025 tree_select(struct view *view, struct line *line)
4026 {
4027 struct tree_entry *entry = line->data;
4029 if (line->type == LINE_TREE_FILE) {
4030 string_copy_rev(ref_blob, entry->id);
4031 string_format(opt_file, "%s%s", opt_path, tree_path(line));
4033 } else if (line->type != LINE_TREE_DIR) {
4034 return;
4035 }
4037 string_copy_rev(view->ref, entry->id);
4038 }
4040 static bool
4041 tree_open(struct view *view, enum open_flags flags)
4042 {
4043 static const char *tree_argv[] = {
4044 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4045 };
4047 if (view->lines == 0 && opt_prefix[0]) {
4048 char *pos = opt_prefix;
4050 while (pos && *pos) {
4051 char *end = strchr(pos, '/');
4053 if (end)
4054 *end = 0;
4055 push_tree_stack_entry(pos, 0);
4056 pos = end;
4057 if (end) {
4058 *end = '/';
4059 pos++;
4060 }
4061 }
4063 } else if (strcmp(view->vid, view->id)) {
4064 opt_path[0] = 0;
4065 }
4067 return begin_update(view, opt_cdup, tree_argv, flags);
4068 }
4070 static struct view_ops tree_ops = {
4071 "file",
4072 tree_open,
4073 tree_read,
4074 tree_draw,
4075 tree_request,
4076 tree_grep,
4077 tree_select,
4078 };
4080 static bool
4081 blob_open(struct view *view, enum open_flags flags)
4082 {
4083 static const char *blob_argv[] = {
4084 "git", "cat-file", "blob", "%(blob)", NULL
4085 };
4087 return begin_update(view, NULL, blob_argv, flags);
4088 }
4090 static bool
4091 blob_read(struct view *view, char *line)
4092 {
4093 if (!line)
4094 return TRUE;
4095 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4096 }
4098 static enum request
4099 blob_request(struct view *view, enum request request, struct line *line)
4100 {
4101 switch (request) {
4102 case REQ_EDIT:
4103 open_blob_editor(view->vid);
4104 return REQ_NONE;
4105 default:
4106 return pager_request(view, request, line);
4107 }
4108 }
4110 static struct view_ops blob_ops = {
4111 "line",
4112 blob_open,
4113 blob_read,
4114 pager_draw,
4115 blob_request,
4116 pager_grep,
4117 pager_select,
4118 };
4120 /*
4121 * Blame backend
4122 *
4123 * Loading the blame view is a two phase job:
4124 *
4125 * 1. File content is read either using opt_file from the
4126 * filesystem or using git-cat-file.
4127 * 2. Then blame information is incrementally added by
4128 * reading output from git-blame.
4129 */
4131 struct blame_commit {
4132 char id[SIZEOF_REV]; /* SHA1 ID. */
4133 char title[128]; /* First line of the commit message. */
4134 const char *author; /* Author of the commit. */
4135 struct time time; /* Date from the author ident. */
4136 char filename[128]; /* Name of file. */
4137 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
4138 char parent_filename[128]; /* Parent/previous name of file. */
4139 };
4141 struct blame {
4142 struct blame_commit *commit;
4143 unsigned long lineno;
4144 char text[1];
4145 };
4147 static bool
4148 blame_open(struct view *view, enum open_flags flags)
4149 {
4150 const char *file_argv[] = { opt_cdup, opt_file , NULL };
4151 char path[SIZEOF_STR];
4152 size_t i;
4154 if (!view->prev && *opt_prefix) {
4155 string_copy(path, opt_file);
4156 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4157 return FALSE;
4158 }
4160 if (*opt_ref || !begin_update(view, opt_cdup, file_argv, flags)) {
4161 const char *blame_cat_file_argv[] = {
4162 "git", "cat-file", "blob", path, NULL
4163 };
4165 if (!string_format(path, "%s:%s", opt_ref, opt_file) ||
4166 !begin_update(view, opt_cdup, blame_cat_file_argv, flags))
4167 return FALSE;
4168 }
4170 /* First pass: remove multiple references to the same commit. */
4171 for (i = 0; i < view->lines; i++) {
4172 struct blame *blame = view->line[i].data;
4174 if (blame->commit && blame->commit->id[0])
4175 blame->commit->id[0] = 0;
4176 else
4177 blame->commit = NULL;
4178 }
4180 /* Second pass: free existing references. */
4181 for (i = 0; i < view->lines; i++) {
4182 struct blame *blame = view->line[i].data;
4184 if (blame->commit)
4185 free(blame->commit);
4186 }
4188 string_format(view->vid, "%s:%s", opt_ref, opt_file);
4189 string_format(view->ref, "%s ...", opt_file);
4191 return TRUE;
4192 }
4194 static struct blame_commit *
4195 get_blame_commit(struct view *view, const char *id)
4196 {
4197 size_t i;
4199 for (i = 0; i < view->lines; i++) {
4200 struct blame *blame = view->line[i].data;
4202 if (!blame->commit)
4203 continue;
4205 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4206 return blame->commit;
4207 }
4209 {
4210 struct blame_commit *commit = calloc(1, sizeof(*commit));
4212 if (commit)
4213 string_ncopy(commit->id, id, SIZEOF_REV);
4214 return commit;
4215 }
4216 }
4218 static bool
4219 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4220 {
4221 const char *pos = *posref;
4223 *posref = NULL;
4224 pos = strchr(pos + 1, ' ');
4225 if (!pos || !isdigit(pos[1]))
4226 return FALSE;
4227 *number = atoi(pos + 1);
4228 if (*number < min || *number > max)
4229 return FALSE;
4231 *posref = pos;
4232 return TRUE;
4233 }
4235 static struct blame_commit *
4236 parse_blame_commit(struct view *view, const char *text, int *blamed)
4237 {
4238 struct blame_commit *commit;
4239 struct blame *blame;
4240 const char *pos = text + SIZEOF_REV - 2;
4241 size_t orig_lineno = 0;
4242 size_t lineno;
4243 size_t group;
4245 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4246 return NULL;
4248 if (!parse_number(&pos, &orig_lineno, 1, 9999999) ||
4249 !parse_number(&pos, &lineno, 1, view->lines) ||
4250 !parse_number(&pos, &group, 1, view->lines - lineno + 1))
4251 return NULL;
4253 commit = get_blame_commit(view, text);
4254 if (!commit)
4255 return NULL;
4257 *blamed += group;
4258 while (group--) {
4259 struct line *line = &view->line[lineno + group - 1];
4261 blame = line->data;
4262 blame->commit = commit;
4263 blame->lineno = orig_lineno + group - 1;
4264 line->dirty = 1;
4265 }
4267 return commit;
4268 }
4270 static bool
4271 blame_read_file(struct view *view, const char *line, bool *read_file)
4272 {
4273 if (!line) {
4274 const char *blame_argv[] = {
4275 "git", "blame", "%(blameargs)", "--incremental",
4276 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4277 };
4279 if (view->lines == 0 && !view->prev)
4280 die("No blame exist for %s", view->vid);
4282 if (view->lines == 0 || !begin_update(view, opt_cdup, blame_argv, OPEN_EXTRA)) {
4283 report("Failed to load blame data");
4284 return TRUE;
4285 }
4287 *read_file = FALSE;
4288 return FALSE;
4290 } else {
4291 size_t linelen = strlen(line);
4292 struct blame *blame = malloc(sizeof(*blame) + linelen);
4294 if (!blame)
4295 return FALSE;
4297 blame->commit = NULL;
4298 strncpy(blame->text, line, linelen);
4299 blame->text[linelen] = 0;
4300 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4301 }
4302 }
4304 static bool
4305 match_blame_header(const char *name, char **line)
4306 {
4307 size_t namelen = strlen(name);
4308 bool matched = !strncmp(name, *line, namelen);
4310 if (matched)
4311 *line += namelen;
4313 return matched;
4314 }
4316 static bool
4317 blame_read(struct view *view, char *line)
4318 {
4319 static struct blame_commit *commit = NULL;
4320 static int blamed = 0;
4321 static bool read_file = TRUE;
4323 if (read_file)
4324 return blame_read_file(view, line, &read_file);
4326 if (!line) {
4327 /* Reset all! */
4328 commit = NULL;
4329 blamed = 0;
4330 read_file = TRUE;
4331 string_format(view->ref, "%s", view->vid);
4332 if (view_is_displayed(view)) {
4333 update_view_title(view);
4334 redraw_view_from(view, 0);
4335 }
4336 return TRUE;
4337 }
4339 if (!commit) {
4340 commit = parse_blame_commit(view, line, &blamed);
4341 string_format(view->ref, "%s %2d%%", view->vid,
4342 view->lines ? blamed * 100 / view->lines : 0);
4344 } else if (match_blame_header("author ", &line)) {
4345 commit->author = get_author(line);
4347 } else if (match_blame_header("author-time ", &line)) {
4348 parse_timesec(&commit->time, line);
4350 } else if (match_blame_header("author-tz ", &line)) {
4351 parse_timezone(&commit->time, line);
4353 } else if (match_blame_header("summary ", &line)) {
4354 string_ncopy(commit->title, line, strlen(line));
4356 } else if (match_blame_header("previous ", &line)) {
4357 if (strlen(line) <= SIZEOF_REV)
4358 return FALSE;
4359 string_copy_rev(commit->parent_id, line);
4360 line += SIZEOF_REV;
4361 string_ncopy(commit->parent_filename, line, strlen(line));
4363 } else if (match_blame_header("filename ", &line)) {
4364 string_ncopy(commit->filename, line, strlen(line));
4365 commit = NULL;
4366 }
4368 return TRUE;
4369 }
4371 static bool
4372 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4373 {
4374 struct blame *blame = line->data;
4375 struct time *time = NULL;
4376 const char *id = NULL, *author = NULL;
4378 if (blame->commit && *blame->commit->filename) {
4379 id = blame->commit->id;
4380 author = blame->commit->author;
4381 time = &blame->commit->time;
4382 }
4384 if (draw_date(view, time))
4385 return TRUE;
4387 if (draw_author(view, author))
4388 return TRUE;
4390 if (draw_field(view, LINE_BLAME_ID, id, ID_COLS, FALSE))
4391 return TRUE;
4393 if (draw_lineno(view, lineno))
4394 return TRUE;
4396 draw_text(view, LINE_DEFAULT, blame->text);
4397 return TRUE;
4398 }
4400 static bool
4401 check_blame_commit(struct blame *blame, bool check_null_id)
4402 {
4403 if (!blame->commit)
4404 report("Commit data not loaded yet");
4405 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4406 report("No commit exist for the selected line");
4407 else
4408 return TRUE;
4409 return FALSE;
4410 }
4412 static void
4413 setup_blame_parent_line(struct view *view, struct blame *blame)
4414 {
4415 char from[SIZEOF_REF + SIZEOF_STR];
4416 char to[SIZEOF_REF + SIZEOF_STR];
4417 const char *diff_tree_argv[] = {
4418 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4419 "-U0", from, to, "--", NULL
4420 };
4421 struct io io;
4422 int parent_lineno = -1;
4423 int blamed_lineno = -1;
4424 char *line;
4426 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4427 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4428 !io_run(&io, IO_RD, NULL, diff_tree_argv))
4429 return;
4431 while ((line = io_get(&io, '\n', TRUE))) {
4432 if (*line == '@') {
4433 char *pos = strchr(line, '+');
4435 parent_lineno = atoi(line + 4);
4436 if (pos)
4437 blamed_lineno = atoi(pos + 1);
4439 } else if (*line == '+' && parent_lineno != -1) {
4440 if (blame->lineno == blamed_lineno - 1 &&
4441 !strcmp(blame->text, line + 1)) {
4442 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4443 break;
4444 }
4445 blamed_lineno++;
4446 }
4447 }
4449 io_done(&io);
4450 }
4452 static enum request
4453 blame_request(struct view *view, enum request request, struct line *line)
4454 {
4455 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4456 struct blame *blame = line->data;
4458 switch (request) {
4459 case REQ_VIEW_BLAME:
4460 if (check_blame_commit(blame, TRUE)) {
4461 string_copy(opt_ref, blame->commit->id);
4462 string_copy(opt_file, blame->commit->filename);
4463 if (blame->lineno)
4464 view->lineno = blame->lineno;
4465 refresh_view(view);
4466 }
4467 break;
4469 case REQ_PARENT:
4470 if (!check_blame_commit(blame, TRUE))
4471 break;
4472 if (!*blame->commit->parent_id) {
4473 report("The selected commit has no parents");
4474 } else {
4475 string_copy_rev(opt_ref, blame->commit->parent_id);
4476 string_copy(opt_file, blame->commit->parent_filename);
4477 setup_blame_parent_line(view, blame);
4478 refresh_view(view);
4479 }
4480 break;
4482 case REQ_ENTER:
4483 if (!check_blame_commit(blame, FALSE))
4484 break;
4486 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
4487 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
4488 break;
4490 if (!strcmp(blame->commit->id, NULL_ID)) {
4491 struct view *diff = VIEW(REQ_VIEW_DIFF);
4492 const char *diff_index_argv[] = {
4493 "git", "diff-index", "--root", "--patch-with-stat",
4494 "-C", "-M", "HEAD", "--", view->vid, NULL
4495 };
4497 if (!*blame->commit->parent_id) {
4498 diff_index_argv[1] = "diff";
4499 diff_index_argv[2] = "--no-color";
4500 diff_index_argv[6] = "--";
4501 diff_index_argv[7] = "/dev/null";
4502 }
4504 open_argv(view, diff, diff_index_argv, NULL, flags);
4505 } else {
4506 open_view(view, REQ_VIEW_DIFF, flags);
4507 }
4508 if (VIEW(REQ_VIEW_DIFF)->pipe && !strcmp(blame->commit->id, NULL_ID))
4509 string_copy_rev(VIEW(REQ_VIEW_DIFF)->ref, NULL_ID);
4510 break;
4512 default:
4513 return request;
4514 }
4516 return REQ_NONE;
4517 }
4519 static bool
4520 blame_grep(struct view *view, struct line *line)
4521 {
4522 struct blame *blame = line->data;
4523 struct blame_commit *commit = blame->commit;
4524 const char *text[] = {
4525 blame->text,
4526 commit ? commit->title : "",
4527 commit ? commit->id : "",
4528 commit && opt_author ? commit->author : "",
4529 commit ? mkdate(&commit->time, opt_date) : "",
4530 NULL
4531 };
4533 return grep_text(view, text);
4534 }
4536 static void
4537 blame_select(struct view *view, struct line *line)
4538 {
4539 struct blame *blame = line->data;
4540 struct blame_commit *commit = blame->commit;
4542 if (!commit)
4543 return;
4545 if (!strcmp(commit->id, NULL_ID))
4546 string_ncopy(ref_commit, "HEAD", 4);
4547 else
4548 string_copy_rev(ref_commit, commit->id);
4549 }
4551 static struct view_ops blame_ops = {
4552 "line",
4553 blame_open,
4554 blame_read,
4555 blame_draw,
4556 blame_request,
4557 blame_grep,
4558 blame_select,
4559 };
4561 /*
4562 * Branch backend
4563 */
4565 struct branch {
4566 const char *author; /* Author of the last commit. */
4567 struct time time; /* Date of the last activity. */
4568 const struct ref *ref; /* Name and commit ID information. */
4569 };
4571 static const struct ref branch_all;
4573 static const enum sort_field branch_sort_fields[] = {
4574 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4575 };
4576 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
4578 static int
4579 branch_compare(const void *l1, const void *l2)
4580 {
4581 const struct branch *branch1 = ((const struct line *) l1)->data;
4582 const struct branch *branch2 = ((const struct line *) l2)->data;
4584 switch (get_sort_field(branch_sort_state)) {
4585 case ORDERBY_DATE:
4586 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
4588 case ORDERBY_AUTHOR:
4589 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
4591 case ORDERBY_NAME:
4592 default:
4593 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
4594 }
4595 }
4597 static bool
4598 branch_draw(struct view *view, struct line *line, unsigned int lineno)
4599 {
4600 struct branch *branch = line->data;
4601 enum line_type type = branch->ref->head ? LINE_MAIN_HEAD : LINE_DEFAULT;
4603 if (draw_date(view, &branch->time))
4604 return TRUE;
4606 if (draw_author(view, branch->author))
4607 return TRUE;
4609 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
4610 return TRUE;
4611 }
4613 static enum request
4614 branch_request(struct view *view, enum request request, struct line *line)
4615 {
4616 struct branch *branch = line->data;
4618 switch (request) {
4619 case REQ_REFRESH:
4620 load_refs();
4621 refresh_view(view);
4622 return REQ_NONE;
4624 case REQ_TOGGLE_SORT_FIELD:
4625 case REQ_TOGGLE_SORT_ORDER:
4626 sort_view(view, request, &branch_sort_state, branch_compare);
4627 return REQ_NONE;
4629 case REQ_ENTER:
4630 {
4631 const struct ref *ref = branch->ref;
4632 const char *all_branches_argv[] = {
4633 "git", "log", "--no-color", "--pretty=raw", "--parents",
4634 "--topo-order",
4635 ref == &branch_all ? "--all" : ref->name, NULL
4636 };
4637 struct view *main_view = VIEW(REQ_VIEW_MAIN);
4639 open_argv(view, main_view, all_branches_argv, NULL, OPEN_SPLIT);
4640 return REQ_NONE;
4641 }
4642 default:
4643 return request;
4644 }
4645 }
4647 static bool
4648 branch_read(struct view *view, char *line)
4649 {
4650 static char id[SIZEOF_REV];
4651 struct branch *reference;
4652 size_t i;
4654 if (!line)
4655 return TRUE;
4657 switch (get_line_type(line)) {
4658 case LINE_COMMIT:
4659 string_copy_rev(id, line + STRING_SIZE("commit "));
4660 return TRUE;
4662 case LINE_AUTHOR:
4663 for (i = 0, reference = NULL; i < view->lines; i++) {
4664 struct branch *branch = view->line[i].data;
4666 if (strcmp(branch->ref->id, id))
4667 continue;
4669 view->line[i].dirty = TRUE;
4670 if (reference) {
4671 branch->author = reference->author;
4672 branch->time = reference->time;
4673 continue;
4674 }
4676 parse_author_line(line + STRING_SIZE("author "),
4677 &branch->author, &branch->time);
4678 reference = branch;
4679 }
4680 return TRUE;
4682 default:
4683 return TRUE;
4684 }
4686 }
4688 static bool
4689 branch_open_visitor(void *data, const struct ref *ref)
4690 {
4691 struct view *view = data;
4692 struct branch *branch;
4694 if (ref->tag || ref->ltag || ref->remote)
4695 return TRUE;
4697 branch = calloc(1, sizeof(*branch));
4698 if (!branch)
4699 return FALSE;
4701 branch->ref = ref;
4702 return !!add_line_data(view, branch, LINE_DEFAULT);
4703 }
4705 static bool
4706 branch_open(struct view *view, enum open_flags flags)
4707 {
4708 const char *branch_log[] = {
4709 "git", "log", "--no-color", "--pretty=raw",
4710 "--simplify-by-decoration", "--all", NULL
4711 };
4713 if (!begin_update(view, NULL, branch_log, flags)) {
4714 report("Failed to load branch data");
4715 return TRUE;
4716 }
4718 branch_open_visitor(view, &branch_all);
4719 foreach_ref(branch_open_visitor, view);
4720 view->p_restore = TRUE;
4722 return TRUE;
4723 }
4725 static bool
4726 branch_grep(struct view *view, struct line *line)
4727 {
4728 struct branch *branch = line->data;
4729 const char *text[] = {
4730 branch->ref->name,
4731 branch->author,
4732 NULL
4733 };
4735 return grep_text(view, text);
4736 }
4738 static void
4739 branch_select(struct view *view, struct line *line)
4740 {
4741 struct branch *branch = line->data;
4743 string_copy_rev(view->ref, branch->ref->id);
4744 string_copy_rev(ref_commit, branch->ref->id);
4745 string_copy_rev(ref_head, branch->ref->id);
4746 string_copy_rev(ref_branch, branch->ref->name);
4747 }
4749 static struct view_ops branch_ops = {
4750 "branch",
4751 branch_open,
4752 branch_read,
4753 branch_draw,
4754 branch_request,
4755 branch_grep,
4756 branch_select,
4757 };
4759 /*
4760 * Status backend
4761 */
4763 struct status {
4764 char status;
4765 struct {
4766 mode_t mode;
4767 char rev[SIZEOF_REV];
4768 char name[SIZEOF_STR];
4769 } old;
4770 struct {
4771 mode_t mode;
4772 char rev[SIZEOF_REV];
4773 char name[SIZEOF_STR];
4774 } new;
4775 };
4777 static char status_onbranch[SIZEOF_STR];
4778 static struct status stage_status;
4779 static enum line_type stage_line_type;
4780 static size_t stage_chunks;
4781 static int *stage_chunk;
4783 DEFINE_ALLOCATOR(realloc_ints, int, 32)
4785 /* This should work even for the "On branch" line. */
4786 static inline bool
4787 status_has_none(struct view *view, struct line *line)
4788 {
4789 return line < view->line + view->lines && !line[1].data;
4790 }
4792 /* Get fields from the diff line:
4793 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
4794 */
4795 static inline bool
4796 status_get_diff(struct status *file, const char *buf, size_t bufsize)
4797 {
4798 const char *old_mode = buf + 1;
4799 const char *new_mode = buf + 8;
4800 const char *old_rev = buf + 15;
4801 const char *new_rev = buf + 56;
4802 const char *status = buf + 97;
4804 if (bufsize < 98 ||
4805 old_mode[-1] != ':' ||
4806 new_mode[-1] != ' ' ||
4807 old_rev[-1] != ' ' ||
4808 new_rev[-1] != ' ' ||
4809 status[-1] != ' ')
4810 return FALSE;
4812 file->status = *status;
4814 string_copy_rev(file->old.rev, old_rev);
4815 string_copy_rev(file->new.rev, new_rev);
4817 file->old.mode = strtoul(old_mode, NULL, 8);
4818 file->new.mode = strtoul(new_mode, NULL, 8);
4820 file->old.name[0] = file->new.name[0] = 0;
4822 return TRUE;
4823 }
4825 static bool
4826 status_run(struct view *view, const char *argv[], char status, enum line_type type)
4827 {
4828 struct status *unmerged = NULL;
4829 char *buf;
4830 struct io io;
4832 if (!io_run(&io, IO_RD, opt_cdup, argv))
4833 return FALSE;
4835 add_line_data(view, NULL, type);
4837 while ((buf = io_get(&io, 0, TRUE))) {
4838 struct status *file = unmerged;
4840 if (!file) {
4841 file = calloc(1, sizeof(*file));
4842 if (!file || !add_line_data(view, file, type))
4843 goto error_out;
4844 }
4846 /* Parse diff info part. */
4847 if (status) {
4848 file->status = status;
4849 if (status == 'A')
4850 string_copy(file->old.rev, NULL_ID);
4852 } else if (!file->status || file == unmerged) {
4853 if (!status_get_diff(file, buf, strlen(buf)))
4854 goto error_out;
4856 buf = io_get(&io, 0, TRUE);
4857 if (!buf)
4858 break;
4860 /* Collapse all modified entries that follow an
4861 * associated unmerged entry. */
4862 if (unmerged == file) {
4863 unmerged->status = 'U';
4864 unmerged = NULL;
4865 } else if (file->status == 'U') {
4866 unmerged = file;
4867 }
4868 }
4870 /* Grab the old name for rename/copy. */
4871 if (!*file->old.name &&
4872 (file->status == 'R' || file->status == 'C')) {
4873 string_ncopy(file->old.name, buf, strlen(buf));
4875 buf = io_get(&io, 0, TRUE);
4876 if (!buf)
4877 break;
4878 }
4880 /* git-ls-files just delivers a NUL separated list of
4881 * file names similar to the second half of the
4882 * git-diff-* output. */
4883 string_ncopy(file->new.name, buf, strlen(buf));
4884 if (!*file->old.name)
4885 string_copy(file->old.name, file->new.name);
4886 file = NULL;
4887 }
4889 if (io_error(&io)) {
4890 error_out:
4891 io_done(&io);
4892 return FALSE;
4893 }
4895 if (!view->line[view->lines - 1].data)
4896 add_line_data(view, NULL, LINE_STAT_NONE);
4898 io_done(&io);
4899 return TRUE;
4900 }
4902 /* Don't show unmerged entries in the staged section. */
4903 static const char *status_diff_index_argv[] = {
4904 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
4905 "--cached", "-M", "HEAD", NULL
4906 };
4908 static const char *status_diff_files_argv[] = {
4909 "git", "diff-files", "-z", NULL
4910 };
4912 static const char *status_list_other_argv[] = {
4913 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
4914 };
4916 static const char *status_list_no_head_argv[] = {
4917 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
4918 };
4920 static const char *update_index_argv[] = {
4921 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
4922 };
4924 /* Restore the previous line number to stay in the context or select a
4925 * line with something that can be updated. */
4926 static void
4927 status_restore(struct view *view)
4928 {
4929 if (view->p_lineno >= view->lines)
4930 view->p_lineno = view->lines - 1;
4931 while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
4932 view->p_lineno++;
4933 while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
4934 view->p_lineno--;
4936 /* If the above fails, always skip the "On branch" line. */
4937 if (view->p_lineno < view->lines)
4938 view->lineno = view->p_lineno;
4939 else
4940 view->lineno = 1;
4942 if (view->lineno < view->offset)
4943 view->offset = view->lineno;
4944 else if (view->offset + view->height <= view->lineno)
4945 view->offset = view->lineno - view->height + 1;
4947 view->p_restore = FALSE;
4948 }
4950 static void
4951 status_update_onbranch(void)
4952 {
4953 static const char *paths[][2] = {
4954 { "rebase-apply/rebasing", "Rebasing" },
4955 { "rebase-apply/applying", "Applying mailbox" },
4956 { "rebase-apply/", "Rebasing mailbox" },
4957 { "rebase-merge/interactive", "Interactive rebase" },
4958 { "rebase-merge/", "Rebase merge" },
4959 { "MERGE_HEAD", "Merging" },
4960 { "BISECT_LOG", "Bisecting" },
4961 { "HEAD", "On branch" },
4962 };
4963 char buf[SIZEOF_STR];
4964 struct stat stat;
4965 int i;
4967 if (is_initial_commit()) {
4968 string_copy(status_onbranch, "Initial commit");
4969 return;
4970 }
4972 for (i = 0; i < ARRAY_SIZE(paths); i++) {
4973 char *head = opt_head;
4975 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
4976 lstat(buf, &stat) < 0)
4977 continue;
4979 if (!*opt_head) {
4980 struct io io;
4982 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
4983 io_read_buf(&io, buf, sizeof(buf))) {
4984 head = buf;
4985 if (!prefixcmp(head, "refs/heads/"))
4986 head += STRING_SIZE("refs/heads/");
4987 }
4988 }
4990 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
4991 string_copy(status_onbranch, opt_head);
4992 return;
4993 }
4995 string_copy(status_onbranch, "Not currently on any branch");
4996 }
4998 /* First parse staged info using git-diff-index(1), then parse unstaged
4999 * info using git-diff-files(1), and finally untracked files using
5000 * git-ls-files(1). */
5001 static bool
5002 status_open(struct view *view, enum open_flags flags)
5003 {
5004 reset_view(view);
5006 add_line_data(view, NULL, LINE_STAT_HEAD);
5007 status_update_onbranch();
5009 io_run_bg(update_index_argv);
5011 if (is_initial_commit()) {
5012 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
5013 return FALSE;
5014 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
5015 return FALSE;
5016 }
5018 if (!opt_untracked_dirs_content)
5019 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
5021 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
5022 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
5023 return FALSE;
5025 /* Restore the exact position or use the specialized restore
5026 * mode? */
5027 if (!view->p_restore)
5028 status_restore(view);
5029 return TRUE;
5030 }
5032 static bool
5033 status_draw(struct view *view, struct line *line, unsigned int lineno)
5034 {
5035 struct status *status = line->data;
5036 enum line_type type;
5037 const char *text;
5039 if (!status) {
5040 switch (line->type) {
5041 case LINE_STAT_STAGED:
5042 type = LINE_STAT_SECTION;
5043 text = "Changes to be committed:";
5044 break;
5046 case LINE_STAT_UNSTAGED:
5047 type = LINE_STAT_SECTION;
5048 text = "Changed but not updated:";
5049 break;
5051 case LINE_STAT_UNTRACKED:
5052 type = LINE_STAT_SECTION;
5053 text = "Untracked files:";
5054 break;
5056 case LINE_STAT_NONE:
5057 type = LINE_DEFAULT;
5058 text = " (no files)";
5059 break;
5061 case LINE_STAT_HEAD:
5062 type = LINE_STAT_HEAD;
5063 text = status_onbranch;
5064 break;
5066 default:
5067 return FALSE;
5068 }
5069 } else {
5070 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5072 buf[0] = status->status;
5073 if (draw_text(view, line->type, buf))
5074 return TRUE;
5075 type = LINE_DEFAULT;
5076 text = status->new.name;
5077 }
5079 draw_text(view, type, text);
5080 return TRUE;
5081 }
5083 static enum request
5084 status_enter(struct view *view, struct line *line)
5085 {
5086 struct status *status = line->data;
5087 const char *oldpath = status ? status->old.name : NULL;
5088 /* Diffs for unmerged entries are empty when passing the new
5089 * path, so leave it empty. */
5090 const char *newpath = status && status->status != 'U' ? status->new.name : NULL;
5091 const char *info;
5092 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5093 struct view *stage = VIEW(REQ_VIEW_STAGE);
5095 if (line->type == LINE_STAT_NONE ||
5096 (!status && line[1].type == LINE_STAT_NONE)) {
5097 report("No file to diff");
5098 return REQ_NONE;
5099 }
5101 switch (line->type) {
5102 case LINE_STAT_STAGED:
5103 if (is_initial_commit()) {
5104 const char *no_head_diff_argv[] = {
5105 "git", "diff", "--no-color", "--patch-with-stat",
5106 "--", "/dev/null", newpath, NULL
5107 };
5109 open_argv(view, stage, no_head_diff_argv, opt_cdup, flags);
5110 } else {
5111 const char *index_show_argv[] = {
5112 "git", "diff-index", "--root", "--patch-with-stat",
5113 "-C", "-M", "--cached", "HEAD", "--",
5114 oldpath, newpath, NULL
5115 };
5117 open_argv(view, stage, index_show_argv, opt_cdup, flags);
5118 }
5120 if (status)
5121 info = "Staged changes to %s";
5122 else
5123 info = "Staged changes";
5124 break;
5126 case LINE_STAT_UNSTAGED:
5127 {
5128 const char *files_show_argv[] = {
5129 "git", "diff-files", "--root", "--patch-with-stat",
5130 "-C", "-M", "--", oldpath, newpath, NULL
5131 };
5133 open_argv(view, stage, files_show_argv, opt_cdup, flags);
5134 if (status)
5135 info = "Unstaged changes to %s";
5136 else
5137 info = "Unstaged changes";
5138 break;
5139 }
5140 case LINE_STAT_UNTRACKED:
5141 if (!newpath) {
5142 report("No file to show");
5143 return REQ_NONE;
5144 }
5146 if (!suffixcmp(status->new.name, -1, "/")) {
5147 report("Cannot display a directory");
5148 return REQ_NONE;
5149 }
5151 open_file(view, stage, newpath, flags);
5152 info = "Untracked file %s";
5153 break;
5155 case LINE_STAT_HEAD:
5156 return REQ_NONE;
5158 default:
5159 die("line type %d not handled in switch", line->type);
5160 }
5162 if (view_is_displayed(VIEW(REQ_VIEW_STAGE))) {
5163 if (status) {
5164 stage_status = *status;
5165 } else {
5166 memset(&stage_status, 0, sizeof(stage_status));
5167 }
5169 stage_line_type = line->type;
5170 stage_chunks = 0;
5171 string_format(VIEW(REQ_VIEW_STAGE)->ref, info, stage_status.new.name);
5172 }
5174 return REQ_NONE;
5175 }
5177 static bool
5178 status_exists(struct status *status, enum line_type type)
5179 {
5180 struct view *view = VIEW(REQ_VIEW_STATUS);
5181 unsigned long lineno;
5183 for (lineno = 0; lineno < view->lines; lineno++) {
5184 struct line *line = &view->line[lineno];
5185 struct status *pos = line->data;
5187 if (line->type != type)
5188 continue;
5189 if (!pos && (!status || !status->status) && line[1].data) {
5190 select_view_line(view, lineno);
5191 return TRUE;
5192 }
5193 if (pos && !strcmp(status->new.name, pos->new.name)) {
5194 select_view_line(view, lineno);
5195 return TRUE;
5196 }
5197 }
5199 return FALSE;
5200 }
5203 static bool
5204 status_update_prepare(struct io *io, enum line_type type)
5205 {
5206 const char *staged_argv[] = {
5207 "git", "update-index", "-z", "--index-info", NULL
5208 };
5209 const char *others_argv[] = {
5210 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5211 };
5213 switch (type) {
5214 case LINE_STAT_STAGED:
5215 return io_run(io, IO_WR, opt_cdup, staged_argv);
5217 case LINE_STAT_UNSTAGED:
5218 case LINE_STAT_UNTRACKED:
5219 return io_run(io, IO_WR, opt_cdup, others_argv);
5221 default:
5222 die("line type %d not handled in switch", type);
5223 return FALSE;
5224 }
5225 }
5227 static bool
5228 status_update_write(struct io *io, struct status *status, enum line_type type)
5229 {
5230 char buf[SIZEOF_STR];
5231 size_t bufsize = 0;
5233 switch (type) {
5234 case LINE_STAT_STAGED:
5235 if (!string_format_from(buf, &bufsize, "%06o %s\t%s%c",
5236 status->old.mode,
5237 status->old.rev,
5238 status->old.name, 0))
5239 return FALSE;
5240 break;
5242 case LINE_STAT_UNSTAGED:
5243 case LINE_STAT_UNTRACKED:
5244 if (!string_format_from(buf, &bufsize, "%s%c", status->new.name, 0))
5245 return FALSE;
5246 break;
5248 default:
5249 die("line type %d not handled in switch", type);
5250 }
5252 return io_write(io, buf, bufsize);
5253 }
5255 static bool
5256 status_update_file(struct status *status, enum line_type type)
5257 {
5258 struct io io;
5259 bool result;
5261 if (!status_update_prepare(&io, type))
5262 return FALSE;
5264 result = status_update_write(&io, status, type);
5265 return io_done(&io) && result;
5266 }
5268 static bool
5269 status_update_files(struct view *view, struct line *line)
5270 {
5271 char buf[sizeof(view->ref)];
5272 struct io io;
5273 bool result = TRUE;
5274 struct line *pos = view->line + view->lines;
5275 int files = 0;
5276 int file, done;
5277 int cursor_y = -1, cursor_x = -1;
5279 if (!status_update_prepare(&io, line->type))
5280 return FALSE;
5282 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5283 files++;
5285 string_copy(buf, view->ref);
5286 getsyx(cursor_y, cursor_x);
5287 for (file = 0, done = 5; result && file < files; line++, file++) {
5288 int almost_done = file * 100 / files;
5290 if (almost_done > done) {
5291 done = almost_done;
5292 string_format(view->ref, "updating file %u of %u (%d%% done)",
5293 file, files, done);
5294 update_view_title(view);
5295 setsyx(cursor_y, cursor_x);
5296 doupdate();
5297 }
5298 result = status_update_write(&io, line->data, line->type);
5299 }
5300 string_copy(view->ref, buf);
5302 return io_done(&io) && result;
5303 }
5305 static bool
5306 status_update(struct view *view)
5307 {
5308 struct line *line = &view->line[view->lineno];
5310 assert(view->lines);
5312 if (!line->data) {
5313 /* This should work even for the "On branch" line. */
5314 if (line < view->line + view->lines && !line[1].data) {
5315 report("Nothing to update");
5316 return FALSE;
5317 }
5319 if (!status_update_files(view, line + 1)) {
5320 report("Failed to update file status");
5321 return FALSE;
5322 }
5324 } else if (!status_update_file(line->data, line->type)) {
5325 report("Failed to update file status");
5326 return FALSE;
5327 }
5329 return TRUE;
5330 }
5332 static bool
5333 status_revert(struct status *status, enum line_type type, bool has_none)
5334 {
5335 if (!status || type != LINE_STAT_UNSTAGED) {
5336 if (type == LINE_STAT_STAGED) {
5337 report("Cannot revert changes to staged files");
5338 } else if (type == LINE_STAT_UNTRACKED) {
5339 report("Cannot revert changes to untracked files");
5340 } else if (has_none) {
5341 report("Nothing to revert");
5342 } else {
5343 report("Cannot revert changes to multiple files");
5344 }
5346 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5347 char mode[10] = "100644";
5348 const char *reset_argv[] = {
5349 "git", "update-index", "--cacheinfo", mode,
5350 status->old.rev, status->old.name, NULL
5351 };
5352 const char *checkout_argv[] = {
5353 "git", "checkout", "--", status->old.name, NULL
5354 };
5356 if (status->status == 'U') {
5357 string_format(mode, "%5o", status->old.mode);
5359 if (status->old.mode == 0 && status->new.mode == 0) {
5360 reset_argv[2] = "--force-remove";
5361 reset_argv[3] = status->old.name;
5362 reset_argv[4] = NULL;
5363 }
5365 if (!io_run_fg(reset_argv, opt_cdup))
5366 return FALSE;
5367 if (status->old.mode == 0 && status->new.mode == 0)
5368 return TRUE;
5369 }
5371 return io_run_fg(checkout_argv, opt_cdup);
5372 }
5374 return FALSE;
5375 }
5377 static enum request
5378 status_request(struct view *view, enum request request, struct line *line)
5379 {
5380 struct status *status = line->data;
5382 switch (request) {
5383 case REQ_STATUS_UPDATE:
5384 if (!status_update(view))
5385 return REQ_NONE;
5386 break;
5388 case REQ_STATUS_REVERT:
5389 if (!status_revert(status, line->type, status_has_none(view, line)))
5390 return REQ_NONE;
5391 break;
5393 case REQ_STATUS_MERGE:
5394 if (!status || status->status != 'U') {
5395 report("Merging only possible for files with unmerged status ('U').");
5396 return REQ_NONE;
5397 }
5398 open_mergetool(status->new.name);
5399 break;
5401 case REQ_EDIT:
5402 if (!status)
5403 return request;
5404 if (status->status == 'D') {
5405 report("File has been deleted.");
5406 return REQ_NONE;
5407 }
5409 open_editor(status->new.name);
5410 break;
5412 case REQ_VIEW_BLAME:
5413 if (status)
5414 opt_ref[0] = 0;
5415 return request;
5417 case REQ_ENTER:
5418 /* After returning the status view has been split to
5419 * show the stage view. No further reloading is
5420 * necessary. */
5421 return status_enter(view, line);
5423 case REQ_REFRESH:
5424 /* Simply reload the view. */
5425 break;
5427 default:
5428 return request;
5429 }
5431 refresh_view(view);
5433 return REQ_NONE;
5434 }
5436 static void
5437 status_select(struct view *view, struct line *line)
5438 {
5439 struct status *status = line->data;
5440 char file[SIZEOF_STR] = "all files";
5441 const char *text;
5442 const char *key;
5444 if (status && !string_format(file, "'%s'", status->new.name))
5445 return;
5447 if (!status && line[1].type == LINE_STAT_NONE)
5448 line++;
5450 switch (line->type) {
5451 case LINE_STAT_STAGED:
5452 text = "Press %s to unstage %s for commit";
5453 break;
5455 case LINE_STAT_UNSTAGED:
5456 text = "Press %s to stage %s for commit";
5457 break;
5459 case LINE_STAT_UNTRACKED:
5460 text = "Press %s to stage %s for addition";
5461 break;
5463 case LINE_STAT_HEAD:
5464 case LINE_STAT_NONE:
5465 text = "Nothing to update";
5466 break;
5468 default:
5469 die("line type %d not handled in switch", line->type);
5470 }
5472 if (status && status->status == 'U') {
5473 text = "Press %s to resolve conflict in %s";
5474 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5476 } else {
5477 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5478 }
5480 string_format(view->ref, text, key, file);
5481 if (status)
5482 string_copy(opt_file, status->new.name);
5483 }
5485 static bool
5486 status_grep(struct view *view, struct line *line)
5487 {
5488 struct status *status = line->data;
5490 if (status) {
5491 const char buf[2] = { status->status, 0 };
5492 const char *text[] = { status->new.name, buf, NULL };
5494 return grep_text(view, text);
5495 }
5497 return FALSE;
5498 }
5500 static struct view_ops status_ops = {
5501 "file",
5502 status_open,
5503 NULL,
5504 status_draw,
5505 status_request,
5506 status_grep,
5507 status_select,
5508 };
5511 static bool
5512 stage_diff_write(struct io *io, struct line *line, struct line *end)
5513 {
5514 while (line < end) {
5515 if (!io_write(io, line->data, strlen(line->data)) ||
5516 !io_write(io, "\n", 1))
5517 return FALSE;
5518 line++;
5519 if (line->type == LINE_DIFF_CHUNK ||
5520 line->type == LINE_DIFF_HEADER)
5521 break;
5522 }
5524 return TRUE;
5525 }
5527 static struct line *
5528 stage_diff_find(struct view *view, struct line *line, enum line_type type)
5529 {
5530 for (; view->line < line; line--)
5531 if (line->type == type)
5532 return line;
5534 return NULL;
5535 }
5537 static bool
5538 stage_apply_chunk(struct view *view, struct line *chunk, bool revert)
5539 {
5540 const char *apply_argv[SIZEOF_ARG] = {
5541 "git", "apply", "--whitespace=nowarn", NULL
5542 };
5543 struct line *diff_hdr;
5544 struct io io;
5545 int argc = 3;
5547 diff_hdr = stage_diff_find(view, chunk, LINE_DIFF_HEADER);
5548 if (!diff_hdr)
5549 return FALSE;
5551 if (!revert)
5552 apply_argv[argc++] = "--cached";
5553 if (revert || stage_line_type == LINE_STAT_STAGED)
5554 apply_argv[argc++] = "-R";
5555 apply_argv[argc++] = "-";
5556 apply_argv[argc++] = NULL;
5557 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
5558 return FALSE;
5560 if (!stage_diff_write(&io, diff_hdr, chunk) ||
5561 !stage_diff_write(&io, chunk, view->line + view->lines))
5562 chunk = NULL;
5564 io_done(&io);
5565 io_run_bg(update_index_argv);
5567 return chunk ? TRUE : FALSE;
5568 }
5570 static bool
5571 stage_update(struct view *view, struct line *line)
5572 {
5573 struct line *chunk = NULL;
5575 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
5576 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5578 if (chunk) {
5579 if (!stage_apply_chunk(view, chunk, FALSE)) {
5580 report("Failed to apply chunk");
5581 return FALSE;
5582 }
5584 } else if (!stage_status.status) {
5585 view = VIEW(REQ_VIEW_STATUS);
5587 for (line = view->line; line < view->line + view->lines; line++)
5588 if (line->type == stage_line_type)
5589 break;
5591 if (!status_update_files(view, line + 1)) {
5592 report("Failed to update files");
5593 return FALSE;
5594 }
5596 } else if (!status_update_file(&stage_status, stage_line_type)) {
5597 report("Failed to update file");
5598 return FALSE;
5599 }
5601 return TRUE;
5602 }
5604 static bool
5605 stage_revert(struct view *view, struct line *line)
5606 {
5607 struct line *chunk = NULL;
5609 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
5610 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5612 if (chunk) {
5613 if (!prompt_yesno("Are you sure you want to revert changes?"))
5614 return FALSE;
5616 if (!stage_apply_chunk(view, chunk, TRUE)) {
5617 report("Failed to revert chunk");
5618 return FALSE;
5619 }
5620 return TRUE;
5622 } else {
5623 return status_revert(stage_status.status ? &stage_status : NULL,
5624 stage_line_type, FALSE);
5625 }
5626 }
5629 static void
5630 stage_next(struct view *view, struct line *line)
5631 {
5632 int i;
5634 if (!stage_chunks) {
5635 for (line = view->line; line < view->line + view->lines; line++) {
5636 if (line->type != LINE_DIFF_CHUNK)
5637 continue;
5639 if (!realloc_ints(&stage_chunk, stage_chunks, 1)) {
5640 report("Allocation failure");
5641 return;
5642 }
5644 stage_chunk[stage_chunks++] = line - view->line;
5645 }
5646 }
5648 for (i = 0; i < stage_chunks; i++) {
5649 if (stage_chunk[i] > view->lineno) {
5650 do_scroll_view(view, stage_chunk[i] - view->lineno);
5651 report("Chunk %d of %d", i + 1, stage_chunks);
5652 return;
5653 }
5654 }
5656 report("No next chunk found");
5657 }
5659 static enum request
5660 stage_request(struct view *view, enum request request, struct line *line)
5661 {
5662 switch (request) {
5663 case REQ_STATUS_UPDATE:
5664 if (!stage_update(view, line))
5665 return REQ_NONE;
5666 break;
5668 case REQ_STATUS_REVERT:
5669 if (!stage_revert(view, line))
5670 return REQ_NONE;
5671 break;
5673 case REQ_STAGE_NEXT:
5674 if (stage_line_type == LINE_STAT_UNTRACKED) {
5675 report("File is untracked; press %s to add",
5676 get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
5677 return REQ_NONE;
5678 }
5679 stage_next(view, line);
5680 return REQ_NONE;
5682 case REQ_EDIT:
5683 if (!stage_status.new.name[0])
5684 return request;
5685 if (stage_status.status == 'D') {
5686 report("File has been deleted.");
5687 return REQ_NONE;
5688 }
5690 open_editor(stage_status.new.name);
5691 break;
5693 case REQ_REFRESH:
5694 /* Reload everything ... */
5695 break;
5697 case REQ_VIEW_BLAME:
5698 if (stage_status.new.name[0]) {
5699 string_copy(opt_file, stage_status.new.name);
5700 opt_ref[0] = 0;
5701 }
5702 return request;
5704 case REQ_ENTER:
5705 return pager_request(view, request, line);
5707 default:
5708 return request;
5709 }
5711 refresh_view(view->parent);
5713 /* Check whether the staged entry still exists, and close the
5714 * stage view if it doesn't. */
5715 if (!status_exists(&stage_status, stage_line_type)) {
5716 status_restore(VIEW(REQ_VIEW_STATUS));
5717 return REQ_VIEW_CLOSE;
5718 }
5720 refresh_view(view);
5722 return REQ_NONE;
5723 }
5725 static struct view_ops stage_ops = {
5726 "line",
5727 view_open,
5728 pager_read,
5729 pager_draw,
5730 stage_request,
5731 pager_grep,
5732 pager_select,
5733 };
5736 /*
5737 * Revision graph
5738 */
5740 static const enum line_type graph_colors[] = {
5741 LINE_GRAPH_LINE_0,
5742 LINE_GRAPH_LINE_1,
5743 LINE_GRAPH_LINE_2,
5744 LINE_GRAPH_LINE_3,
5745 LINE_GRAPH_LINE_4,
5746 LINE_GRAPH_LINE_5,
5747 LINE_GRAPH_LINE_6,
5748 };
5750 static enum line_type get_graph_color(struct graph_symbol *symbol)
5751 {
5752 if (symbol->commit)
5753 return LINE_GRAPH_COMMIT;
5754 assert(symbol->color < ARRAY_SIZE(graph_colors));
5755 return graph_colors[symbol->color];
5756 }
5758 static bool
5759 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5760 {
5761 const char *chars = graph_symbol_to_utf8(symbol);
5763 return draw_text(view, color, chars + !!first);
5764 }
5766 static bool
5767 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5768 {
5769 const char *chars = graph_symbol_to_ascii(symbol);
5771 return draw_text(view, color, chars + !!first);
5772 }
5774 static bool
5775 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5776 {
5777 const chtype *chars = graph_symbol_to_chtype(symbol);
5779 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
5780 }
5782 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
5784 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
5785 {
5786 static const draw_graph_fn fns[] = {
5787 draw_graph_ascii,
5788 draw_graph_chtype,
5789 draw_graph_utf8
5790 };
5791 draw_graph_fn fn = fns[opt_line_graphics];
5792 int i;
5794 for (i = 0; i < canvas->size; i++) {
5795 struct graph_symbol *symbol = &canvas->symbols[i];
5796 enum line_type color = get_graph_color(symbol);
5798 if (fn(view, symbol, color, i == 0))
5799 return TRUE;
5800 }
5802 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
5803 }
5805 /*
5806 * Main view backend
5807 */
5809 struct commit {
5810 char id[SIZEOF_REV]; /* SHA1 ID. */
5811 char title[128]; /* First line of the commit message. */
5812 const char *author; /* Author of the commit. */
5813 struct time time; /* Date from the author ident. */
5814 struct ref_list *refs; /* Repository references. */
5815 struct graph_canvas graph; /* Ancestry chain graphics. */
5816 };
5818 static bool
5819 main_open(struct view *view, enum open_flags flags)
5820 {
5821 static const char *main_argv[] = {
5822 "git", "log", "--no-color", "--pretty=raw", "--parents",
5823 "--topo-order", "%(diffargs)", "%(revargs)",
5824 "--", "%(fileargs)", NULL
5825 };
5827 return begin_update(view, NULL, main_argv, flags);
5828 }
5830 static bool
5831 main_draw(struct view *view, struct line *line, unsigned int lineno)
5832 {
5833 struct commit *commit = line->data;
5835 if (!commit->author)
5836 return FALSE;
5838 if (draw_date(view, &commit->time))
5839 return TRUE;
5841 if (draw_author(view, commit->author))
5842 return TRUE;
5844 if (opt_rev_graph && draw_graph(view, &commit->graph))
5845 return TRUE;
5847 if (draw_refs(view, commit->refs))
5848 return TRUE;
5850 draw_text(view, LINE_DEFAULT, commit->title);
5851 return TRUE;
5852 }
5854 /* Reads git log --pretty=raw output and parses it into the commit struct. */
5855 static bool
5856 main_read(struct view *view, char *line)
5857 {
5858 static struct graph graph;
5859 enum line_type type;
5860 struct commit *commit;
5862 if (!line) {
5863 if (!view->lines && !view->prev)
5864 die("No revisions match the given arguments.");
5865 if (view->lines > 0) {
5866 commit = view->line[view->lines - 1].data;
5867 view->line[view->lines - 1].dirty = 1;
5868 if (!commit->author) {
5869 view->lines--;
5870 free(commit);
5871 }
5872 }
5874 done_graph(&graph);
5875 return TRUE;
5876 }
5878 type = get_line_type(line);
5879 if (type == LINE_COMMIT) {
5880 bool is_boundary;
5882 commit = calloc(1, sizeof(struct commit));
5883 if (!commit)
5884 return FALSE;
5886 line += STRING_SIZE("commit ");
5887 is_boundary = *line == '-';
5888 if (is_boundary)
5889 line++;
5891 string_copy_rev(commit->id, line);
5892 commit->refs = get_ref_list(commit->id);
5893 add_line_data(view, commit, LINE_MAIN_COMMIT);
5894 graph_add_commit(&graph, &commit->graph, commit->id, line, is_boundary);
5895 return TRUE;
5896 }
5898 if (!view->lines)
5899 return TRUE;
5900 commit = view->line[view->lines - 1].data;
5902 switch (type) {
5903 case LINE_PARENT:
5904 if (!graph.has_parents)
5905 graph_add_parent(&graph, line + STRING_SIZE("parent "));
5906 break;
5908 case LINE_AUTHOR:
5909 parse_author_line(line + STRING_SIZE("author "),
5910 &commit->author, &commit->time);
5911 graph_render_parents(&graph);
5912 break;
5914 default:
5915 /* Fill in the commit title if it has not already been set. */
5916 if (commit->title[0])
5917 break;
5919 /* Require titles to start with a non-space character at the
5920 * offset used by git log. */
5921 if (strncmp(line, " ", 4))
5922 break;
5923 line += 4;
5924 /* Well, if the title starts with a whitespace character,
5925 * try to be forgiving. Otherwise we end up with no title. */
5926 while (isspace(*line))
5927 line++;
5928 if (*line == '\0')
5929 break;
5930 /* FIXME: More graceful handling of titles; append "..." to
5931 * shortened titles, etc. */
5933 string_expand(commit->title, sizeof(commit->title), line, 1);
5934 view->line[view->lines - 1].dirty = 1;
5935 }
5937 return TRUE;
5938 }
5940 static enum request
5941 main_request(struct view *view, enum request request, struct line *line)
5942 {
5943 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5945 switch (request) {
5946 case REQ_ENTER:
5947 if (view_is_displayed(view) && display[0] != view)
5948 maximize_view(view, TRUE);
5949 open_view(view, REQ_VIEW_DIFF, flags);
5950 break;
5951 case REQ_REFRESH:
5952 load_refs();
5953 refresh_view(view);
5954 break;
5955 default:
5956 return request;
5957 }
5959 return REQ_NONE;
5960 }
5962 static bool
5963 grep_refs(struct ref_list *list, regex_t *regex)
5964 {
5965 regmatch_t pmatch;
5966 size_t i;
5968 if (!opt_show_refs || !list)
5969 return FALSE;
5971 for (i = 0; i < list->size; i++) {
5972 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
5973 return TRUE;
5974 }
5976 return FALSE;
5977 }
5979 static bool
5980 main_grep(struct view *view, struct line *line)
5981 {
5982 struct commit *commit = line->data;
5983 const char *text[] = {
5984 commit->title,
5985 opt_author ? commit->author : "",
5986 mkdate(&commit->time, opt_date),
5987 NULL
5988 };
5990 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
5991 }
5993 static void
5994 main_select(struct view *view, struct line *line)
5995 {
5996 struct commit *commit = line->data;
5998 string_copy_rev(view->ref, commit->id);
5999 string_copy_rev(ref_commit, view->ref);
6000 }
6002 static struct view_ops main_ops = {
6003 "commit",
6004 main_open,
6005 main_read,
6006 main_draw,
6007 main_request,
6008 main_grep,
6009 main_select,
6010 };
6013 /*
6014 * Status management
6015 */
6017 /* Whether or not the curses interface has been initialized. */
6018 static bool cursed = FALSE;
6020 /* Terminal hacks and workarounds. */
6021 static bool use_scroll_redrawwin;
6022 static bool use_scroll_status_wclear;
6024 /* The status window is used for polling keystrokes. */
6025 static WINDOW *status_win;
6027 /* Reading from the prompt? */
6028 static bool input_mode = FALSE;
6030 static bool status_empty = FALSE;
6032 /* Update status and title window. */
6033 static void
6034 report(const char *msg, ...)
6035 {
6036 struct view *view = display[current_view];
6038 if (input_mode)
6039 return;
6041 if (!view) {
6042 char buf[SIZEOF_STR];
6043 va_list args;
6045 va_start(args, msg);
6046 if (vsnprintf(buf, sizeof(buf), msg, args) >= sizeof(buf)) {
6047 buf[sizeof(buf) - 1] = 0;
6048 buf[sizeof(buf) - 2] = '.';
6049 buf[sizeof(buf) - 3] = '.';
6050 buf[sizeof(buf) - 4] = '.';
6051 }
6052 va_end(args);
6053 die("%s", buf);
6054 }
6056 if (!status_empty || *msg) {
6057 va_list args;
6059 va_start(args, msg);
6061 wmove(status_win, 0, 0);
6062 if (view->has_scrolled && use_scroll_status_wclear)
6063 wclear(status_win);
6064 if (*msg) {
6065 vwprintw(status_win, msg, args);
6066 status_empty = FALSE;
6067 } else {
6068 status_empty = TRUE;
6069 }
6070 wclrtoeol(status_win);
6071 wnoutrefresh(status_win);
6073 va_end(args);
6074 }
6076 update_view_title(view);
6077 }
6079 static void
6080 init_display(void)
6081 {
6082 const char *term;
6083 int x, y;
6085 /* Initialize the curses library */
6086 if (isatty(STDIN_FILENO)) {
6087 cursed = !!initscr();
6088 opt_tty = stdin;
6089 } else {
6090 /* Leave stdin and stdout alone when acting as a pager. */
6091 opt_tty = fopen("/dev/tty", "r+");
6092 if (!opt_tty)
6093 die("Failed to open /dev/tty");
6094 cursed = !!newterm(NULL, opt_tty, opt_tty);
6095 }
6097 if (!cursed)
6098 die("Failed to initialize curses");
6100 nonl(); /* Disable conversion and detect newlines from input. */
6101 cbreak(); /* Take input chars one at a time, no wait for \n */
6102 noecho(); /* Don't echo input */
6103 leaveok(stdscr, FALSE);
6105 if (has_colors())
6106 init_colors();
6108 getmaxyx(stdscr, y, x);
6109 status_win = newwin(1, x, y - 1, 0);
6110 if (!status_win)
6111 die("Failed to create status window");
6113 /* Enable keyboard mapping */
6114 keypad(status_win, TRUE);
6115 wbkgdset(status_win, get_line_attr(LINE_STATUS));
6117 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6118 set_tabsize(opt_tab_size);
6119 #else
6120 TABSIZE = opt_tab_size;
6121 #endif
6123 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6124 if (term && !strcmp(term, "gnome-terminal")) {
6125 /* In the gnome-terminal-emulator, the message from
6126 * scrolling up one line when impossible followed by
6127 * scrolling down one line causes corruption of the
6128 * status line. This is fixed by calling wclear. */
6129 use_scroll_status_wclear = TRUE;
6130 use_scroll_redrawwin = FALSE;
6132 } else if (term && !strcmp(term, "xrvt-xpm")) {
6133 /* No problems with full optimizations in xrvt-(unicode)
6134 * and aterm. */
6135 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6137 } else {
6138 /* When scrolling in (u)xterm the last line in the
6139 * scrolling direction will update slowly. */
6140 use_scroll_redrawwin = TRUE;
6141 use_scroll_status_wclear = FALSE;
6142 }
6143 }
6145 static int
6146 get_input(int prompt_position)
6147 {
6148 struct view *view;
6149 int i, key, cursor_y, cursor_x;
6151 if (prompt_position)
6152 input_mode = TRUE;
6154 while (TRUE) {
6155 bool loading = FALSE;
6157 foreach_view (view, i) {
6158 update_view(view);
6159 if (view_is_displayed(view) && view->has_scrolled &&
6160 use_scroll_redrawwin)
6161 redrawwin(view->win);
6162 view->has_scrolled = FALSE;
6163 if (view->pipe)
6164 loading = TRUE;
6165 }
6167 /* Update the cursor position. */
6168 if (prompt_position) {
6169 getbegyx(status_win, cursor_y, cursor_x);
6170 cursor_x = prompt_position;
6171 } else {
6172 view = display[current_view];
6173 getbegyx(view->win, cursor_y, cursor_x);
6174 cursor_x = view->width - 1;
6175 cursor_y += view->lineno - view->offset;
6176 }
6177 setsyx(cursor_y, cursor_x);
6179 /* Refresh, accept single keystroke of input */
6180 doupdate();
6181 nodelay(status_win, loading);
6182 key = wgetch(status_win);
6184 /* wgetch() with nodelay() enabled returns ERR when
6185 * there's no input. */
6186 if (key == ERR) {
6188 } else if (key == KEY_RESIZE) {
6189 int height, width;
6191 getmaxyx(stdscr, height, width);
6193 wresize(status_win, 1, width);
6194 mvwin(status_win, height - 1, 0);
6195 wnoutrefresh(status_win);
6196 resize_display();
6197 redraw_display(TRUE);
6199 } else {
6200 input_mode = FALSE;
6201 return key;
6202 }
6203 }
6204 }
6206 static char *
6207 prompt_input(const char *prompt, input_handler handler, void *data)
6208 {
6209 enum input_status status = INPUT_OK;
6210 static char buf[SIZEOF_STR];
6211 size_t pos = 0;
6213 buf[pos] = 0;
6215 while (status == INPUT_OK || status == INPUT_SKIP) {
6216 int key;
6218 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6219 wclrtoeol(status_win);
6221 key = get_input(pos + 1);
6222 switch (key) {
6223 case KEY_RETURN:
6224 case KEY_ENTER:
6225 case '\n':
6226 status = pos ? INPUT_STOP : INPUT_CANCEL;
6227 break;
6229 case KEY_BACKSPACE:
6230 if (pos > 0)
6231 buf[--pos] = 0;
6232 else
6233 status = INPUT_CANCEL;
6234 break;
6236 case KEY_ESC:
6237 status = INPUT_CANCEL;
6238 break;
6240 default:
6241 if (pos >= sizeof(buf)) {
6242 report("Input string too long");
6243 return NULL;
6244 }
6246 status = handler(data, buf, key);
6247 if (status == INPUT_OK)
6248 buf[pos++] = (char) key;
6249 }
6250 }
6252 /* Clear the status window */
6253 status_empty = FALSE;
6254 report("");
6256 if (status == INPUT_CANCEL)
6257 return NULL;
6259 buf[pos++] = 0;
6261 return buf;
6262 }
6264 static enum input_status
6265 prompt_yesno_handler(void *data, char *buf, int c)
6266 {
6267 if (c == 'y' || c == 'Y')
6268 return INPUT_STOP;
6269 if (c == 'n' || c == 'N')
6270 return INPUT_CANCEL;
6271 return INPUT_SKIP;
6272 }
6274 static bool
6275 prompt_yesno(const char *prompt)
6276 {
6277 char prompt2[SIZEOF_STR];
6279 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6280 return FALSE;
6282 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6283 }
6285 static enum input_status
6286 read_prompt_handler(void *data, char *buf, int c)
6287 {
6288 return isprint(c) ? INPUT_OK : INPUT_SKIP;
6289 }
6291 static char *
6292 read_prompt(const char *prompt)
6293 {
6294 return prompt_input(prompt, read_prompt_handler, NULL);
6295 }
6297 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6298 {
6299 enum input_status status = INPUT_OK;
6300 int size = 0;
6302 while (items[size].text)
6303 size++;
6305 while (status == INPUT_OK) {
6306 const struct menu_item *item = &items[*selected];
6307 int key;
6308 int i;
6310 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6311 prompt, *selected + 1, size);
6312 if (item->hotkey)
6313 wprintw(status_win, "[%c] ", (char) item->hotkey);
6314 wprintw(status_win, "%s", item->text);
6315 wclrtoeol(status_win);
6317 key = get_input(COLS - 1);
6318 switch (key) {
6319 case KEY_RETURN:
6320 case KEY_ENTER:
6321 case '\n':
6322 status = INPUT_STOP;
6323 break;
6325 case KEY_LEFT:
6326 case KEY_UP:
6327 *selected = *selected - 1;
6328 if (*selected < 0)
6329 *selected = size - 1;
6330 break;
6332 case KEY_RIGHT:
6333 case KEY_DOWN:
6334 *selected = (*selected + 1) % size;
6335 break;
6337 case KEY_ESC:
6338 status = INPUT_CANCEL;
6339 break;
6341 default:
6342 for (i = 0; items[i].text; i++)
6343 if (items[i].hotkey == key) {
6344 *selected = i;
6345 status = INPUT_STOP;
6346 break;
6347 }
6348 }
6349 }
6351 /* Clear the status window */
6352 status_empty = FALSE;
6353 report("");
6355 return status != INPUT_CANCEL;
6356 }
6358 /*
6359 * Repository properties
6360 */
6362 static struct ref **refs = NULL;
6363 static size_t refs_size = 0;
6364 static struct ref *refs_head = NULL;
6366 static struct ref_list **ref_lists = NULL;
6367 static size_t ref_lists_size = 0;
6369 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
6370 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
6371 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
6373 static int
6374 compare_refs(const void *ref1_, const void *ref2_)
6375 {
6376 const struct ref *ref1 = *(const struct ref **)ref1_;
6377 const struct ref *ref2 = *(const struct ref **)ref2_;
6379 if (ref1->tag != ref2->tag)
6380 return ref2->tag - ref1->tag;
6381 if (ref1->ltag != ref2->ltag)
6382 return ref2->ltag - ref2->ltag;
6383 if (ref1->head != ref2->head)
6384 return ref2->head - ref1->head;
6385 if (ref1->tracked != ref2->tracked)
6386 return ref2->tracked - ref1->tracked;
6387 if (ref1->remote != ref2->remote)
6388 return ref2->remote - ref1->remote;
6389 return strcmp(ref1->name, ref2->name);
6390 }
6392 static void
6393 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
6394 {
6395 size_t i;
6397 for (i = 0; i < refs_size; i++)
6398 if (!visitor(data, refs[i]))
6399 break;
6400 }
6402 static struct ref *
6403 get_ref_head()
6404 {
6405 return refs_head;
6406 }
6408 static struct ref_list *
6409 get_ref_list(const char *id)
6410 {
6411 struct ref_list *list;
6412 size_t i;
6414 for (i = 0; i < ref_lists_size; i++)
6415 if (!strcmp(id, ref_lists[i]->id))
6416 return ref_lists[i];
6418 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
6419 return NULL;
6420 list = calloc(1, sizeof(*list));
6421 if (!list)
6422 return NULL;
6424 for (i = 0; i < refs_size; i++) {
6425 if (!strcmp(id, refs[i]->id) &&
6426 realloc_refs_list(&list->refs, list->size, 1))
6427 list->refs[list->size++] = refs[i];
6428 }
6430 if (!list->refs) {
6431 free(list);
6432 return NULL;
6433 }
6435 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
6436 ref_lists[ref_lists_size++] = list;
6437 return list;
6438 }
6440 static int
6441 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
6442 {
6443 struct ref *ref = NULL;
6444 bool tag = FALSE;
6445 bool ltag = FALSE;
6446 bool remote = FALSE;
6447 bool tracked = FALSE;
6448 bool head = FALSE;
6449 int from = 0, to = refs_size - 1;
6451 if (!prefixcmp(name, "refs/tags/")) {
6452 if (!suffixcmp(name, namelen, "^{}")) {
6453 namelen -= 3;
6454 name[namelen] = 0;
6455 } else {
6456 ltag = TRUE;
6457 }
6459 tag = TRUE;
6460 namelen -= STRING_SIZE("refs/tags/");
6461 name += STRING_SIZE("refs/tags/");
6463 } else if (!prefixcmp(name, "refs/remotes/")) {
6464 remote = TRUE;
6465 namelen -= STRING_SIZE("refs/remotes/");
6466 name += STRING_SIZE("refs/remotes/");
6467 tracked = !strcmp(opt_remote, name);
6469 } else if (!prefixcmp(name, "refs/heads/")) {
6470 namelen -= STRING_SIZE("refs/heads/");
6471 name += STRING_SIZE("refs/heads/");
6472 if (!strncmp(opt_head, name, namelen))
6473 return OK;
6475 } else if (!strcmp(name, "HEAD")) {
6476 head = TRUE;
6477 if (*opt_head) {
6478 namelen = strlen(opt_head);
6479 name = opt_head;
6480 }
6481 }
6483 /* If we are reloading or it's an annotated tag, replace the
6484 * previous SHA1 with the resolved commit id; relies on the fact
6485 * git-ls-remote lists the commit id of an annotated tag right
6486 * before the commit id it points to. */
6487 while (from <= to) {
6488 size_t pos = (to + from) / 2;
6489 int cmp = strcmp(name, refs[pos]->name);
6491 if (!cmp) {
6492 ref = refs[pos];
6493 break;
6494 }
6496 if (cmp < 0)
6497 to = pos - 1;
6498 else
6499 from = pos + 1;
6500 }
6502 if (!ref) {
6503 if (!realloc_refs(&refs, refs_size, 1))
6504 return ERR;
6505 ref = calloc(1, sizeof(*ref) + namelen);
6506 if (!ref)
6507 return ERR;
6508 memmove(refs + from + 1, refs + from,
6509 (refs_size - from) * sizeof(*refs));
6510 refs[from] = ref;
6511 strncpy(ref->name, name, namelen);
6512 refs_size++;
6513 }
6515 ref->head = head;
6516 ref->tag = tag;
6517 ref->ltag = ltag;
6518 ref->remote = remote;
6519 ref->tracked = tracked;
6520 string_copy_rev(ref->id, id);
6522 if (head)
6523 refs_head = ref;
6524 return OK;
6525 }
6527 static int
6528 load_refs(void)
6529 {
6530 const char *head_argv[] = {
6531 "git", "symbolic-ref", "HEAD", NULL
6532 };
6533 static const char *ls_remote_argv[SIZEOF_ARG] = {
6534 "git", "ls-remote", opt_git_dir, NULL
6535 };
6536 static bool init = FALSE;
6537 size_t i;
6539 if (!init) {
6540 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
6541 die("TIG_LS_REMOTE contains too many arguments");
6542 init = TRUE;
6543 }
6545 if (!*opt_git_dir)
6546 return OK;
6548 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
6549 !prefixcmp(opt_head, "refs/heads/")) {
6550 char *offset = opt_head + STRING_SIZE("refs/heads/");
6552 memmove(opt_head, offset, strlen(offset) + 1);
6553 }
6555 refs_head = NULL;
6556 for (i = 0; i < refs_size; i++)
6557 refs[i]->id[0] = 0;
6559 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
6560 return ERR;
6562 /* Update the ref lists to reflect changes. */
6563 for (i = 0; i < ref_lists_size; i++) {
6564 struct ref_list *list = ref_lists[i];
6565 size_t old, new;
6567 for (old = new = 0; old < list->size; old++)
6568 if (!strcmp(list->id, list->refs[old]->id))
6569 list->refs[new++] = list->refs[old];
6570 list->size = new;
6571 }
6573 return OK;
6574 }
6576 static void
6577 set_remote_branch(const char *name, const char *value, size_t valuelen)
6578 {
6579 if (!strcmp(name, ".remote")) {
6580 string_ncopy(opt_remote, value, valuelen);
6582 } else if (*opt_remote && !strcmp(name, ".merge")) {
6583 size_t from = strlen(opt_remote);
6585 if (!prefixcmp(value, "refs/heads/"))
6586 value += STRING_SIZE("refs/heads/");
6588 if (!string_format_from(opt_remote, &from, "/%s", value))
6589 opt_remote[0] = 0;
6590 }
6591 }
6593 static void
6594 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
6595 {
6596 const char *argv[SIZEOF_ARG] = { name, "=" };
6597 int argc = 1 + (cmd == option_set_command);
6598 enum option_code error;
6600 if (!argv_from_string(argv, &argc, value))
6601 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
6602 else
6603 error = cmd(argc, argv);
6605 if (error != OPT_OK)
6606 warn("Option 'tig.%s': %s", name, option_errors[error]);
6607 }
6609 static bool
6610 set_environment_variable(const char *name, const char *value)
6611 {
6612 size_t len = strlen(name) + 1 + strlen(value) + 1;
6613 char *env = malloc(len);
6615 if (env &&
6616 string_nformat(env, len, NULL, "%s=%s", name, value) &&
6617 putenv(env) == 0)
6618 return TRUE;
6619 free(env);
6620 return FALSE;
6621 }
6623 static void
6624 set_work_tree(const char *value)
6625 {
6626 char cwd[SIZEOF_STR];
6628 if (!getcwd(cwd, sizeof(cwd)))
6629 die("Failed to get cwd path: %s", strerror(errno));
6630 if (chdir(opt_git_dir) < 0)
6631 die("Failed to chdir(%s): %s", strerror(errno));
6632 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
6633 die("Failed to get git path: %s", strerror(errno));
6634 if (chdir(cwd) < 0)
6635 die("Failed to chdir(%s): %s", cwd, strerror(errno));
6636 if (chdir(value) < 0)
6637 die("Failed to chdir(%s): %s", value, strerror(errno));
6638 if (!getcwd(cwd, sizeof(cwd)))
6639 die("Failed to get cwd path: %s", strerror(errno));
6640 if (!set_environment_variable("GIT_WORK_TREE", cwd))
6641 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
6642 if (!set_environment_variable("GIT_DIR", opt_git_dir))
6643 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
6644 opt_is_inside_work_tree = TRUE;
6645 }
6647 static int
6648 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6649 {
6650 if (!strcmp(name, "i18n.commitencoding"))
6651 string_ncopy(opt_encoding, value, valuelen);
6653 else if (!strcmp(name, "core.editor"))
6654 string_ncopy(opt_editor, value, valuelen);
6656 else if (!strcmp(name, "core.worktree"))
6657 set_work_tree(value);
6659 else if (!prefixcmp(name, "tig.color."))
6660 set_repo_config_option(name + 10, value, option_color_command);
6662 else if (!prefixcmp(name, "tig.bind."))
6663 set_repo_config_option(name + 9, value, option_bind_command);
6665 else if (!prefixcmp(name, "tig."))
6666 set_repo_config_option(name + 4, value, option_set_command);
6668 else if (*opt_head && !prefixcmp(name, "branch.") &&
6669 !strncmp(name + 7, opt_head, strlen(opt_head)))
6670 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
6672 return OK;
6673 }
6675 static int
6676 load_git_config(void)
6677 {
6678 const char *config_list_argv[] = { "git", "config", "--list", NULL };
6680 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
6681 }
6683 static int
6684 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6685 {
6686 if (!opt_git_dir[0]) {
6687 string_ncopy(opt_git_dir, name, namelen);
6689 } else if (opt_is_inside_work_tree == -1) {
6690 /* This can be 3 different values depending on the
6691 * version of git being used. If git-rev-parse does not
6692 * understand --is-inside-work-tree it will simply echo
6693 * the option else either "true" or "false" is printed.
6694 * Default to true for the unknown case. */
6695 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
6697 } else if (*name == '.') {
6698 string_ncopy(opt_cdup, name, namelen);
6700 } else {
6701 string_ncopy(opt_prefix, name, namelen);
6702 }
6704 return OK;
6705 }
6707 static int
6708 load_repo_info(void)
6709 {
6710 const char *rev_parse_argv[] = {
6711 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
6712 "--show-cdup", "--show-prefix", NULL
6713 };
6715 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
6716 }
6719 /*
6720 * Main
6721 */
6723 static const char usage[] =
6724 "tig " TIG_VERSION " (" __DATE__ ")\n"
6725 "\n"
6726 "Usage: tig [options] [revs] [--] [paths]\n"
6727 " or: tig show [options] [revs] [--] [paths]\n"
6728 " or: tig blame [options] [rev] [--] path\n"
6729 " or: tig status\n"
6730 " or: tig < [git command output]\n"
6731 "\n"
6732 "Options:\n"
6733 " -v, --version Show version and exit\n"
6734 " -h, --help Show help message and exit";
6736 static void __NORETURN
6737 quit(int sig)
6738 {
6739 /* XXX: Restore tty modes and let the OS cleanup the rest! */
6740 if (cursed)
6741 endwin();
6742 exit(0);
6743 }
6745 static void __NORETURN
6746 die(const char *err, ...)
6747 {
6748 va_list args;
6750 endwin();
6752 va_start(args, err);
6753 fputs("tig: ", stderr);
6754 vfprintf(stderr, err, args);
6755 fputs("\n", stderr);
6756 va_end(args);
6758 exit(1);
6759 }
6761 static void
6762 warn(const char *msg, ...)
6763 {
6764 va_list args;
6766 va_start(args, msg);
6767 fputs("tig warning: ", stderr);
6768 vfprintf(stderr, msg, args);
6769 fputs("\n", stderr);
6770 va_end(args);
6771 }
6773 static int
6774 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6775 {
6776 const char ***filter_args = data;
6778 return argv_append(filter_args, name) ? OK : ERR;
6779 }
6781 static void
6782 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
6783 {
6784 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
6785 const char **all_argv = NULL;
6787 if (!argv_append_array(&all_argv, rev_parse_argv) ||
6788 !argv_append_array(&all_argv, argv) ||
6789 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
6790 die("Failed to split arguments");
6791 argv_free(all_argv);
6792 free(all_argv);
6793 }
6795 static void
6796 filter_options(const char *argv[])
6797 {
6798 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
6799 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
6800 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
6801 }
6803 static enum request
6804 parse_options(int argc, const char *argv[])
6805 {
6806 enum request request = REQ_VIEW_MAIN;
6807 const char *subcommand;
6808 bool seen_dashdash = FALSE;
6809 const char **filter_argv = NULL;
6810 int i;
6812 if (!isatty(STDIN_FILENO))
6813 return REQ_VIEW_PAGER;
6815 if (argc <= 1)
6816 return REQ_VIEW_MAIN;
6818 subcommand = argv[1];
6819 if (!strcmp(subcommand, "status")) {
6820 if (argc > 2)
6821 warn("ignoring arguments after `%s'", subcommand);
6822 return REQ_VIEW_STATUS;
6824 } else if (!strcmp(subcommand, "blame")) {
6825 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv + 2);
6826 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv + 2);
6827 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv + 2);
6829 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
6830 die("invalid number of options to blame\n\n%s", usage);
6832 if (opt_rev_argv) {
6833 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
6834 }
6836 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
6837 return REQ_VIEW_BLAME;
6839 } else if (!strcmp(subcommand, "show")) {
6840 request = REQ_VIEW_DIFF;
6842 } else {
6843 subcommand = NULL;
6844 }
6846 for (i = 1 + !!subcommand; i < argc; i++) {
6847 const char *opt = argv[i];
6849 if (seen_dashdash) {
6850 argv_append(&opt_file_argv, opt);
6851 continue;
6853 } else if (!strcmp(opt, "--")) {
6854 seen_dashdash = TRUE;
6855 continue;
6857 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
6858 printf("tig version %s\n", TIG_VERSION);
6859 quit(0);
6861 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
6862 printf("%s\n", usage);
6863 quit(0);
6865 } else if (!strcmp(opt, "--all")) {
6866 argv_append(&opt_rev_argv, opt);
6867 continue;
6868 }
6870 if (!argv_append(&filter_argv, opt))
6871 die("command too long");
6872 }
6874 if (filter_argv)
6875 filter_options(filter_argv);
6877 return request;
6878 }
6880 int
6881 main(int argc, const char *argv[])
6882 {
6883 const char *codeset = "UTF-8";
6884 enum request request = parse_options(argc, argv);
6885 struct view *view;
6887 signal(SIGINT, quit);
6888 signal(SIGPIPE, SIG_IGN);
6890 if (setlocale(LC_ALL, "")) {
6891 codeset = nl_langinfo(CODESET);
6892 }
6894 if (load_repo_info() == ERR)
6895 die("Failed to load repo info.");
6897 if (load_options() == ERR)
6898 die("Failed to load user config.");
6900 if (load_git_config() == ERR)
6901 die("Failed to load repo config.");
6903 /* Require a git repository unless when running in pager mode. */
6904 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
6905 die("Not a git repository");
6907 if (*opt_encoding && strcmp(codeset, "UTF-8")) {
6908 opt_iconv_in = iconv_open("UTF-8", opt_encoding);
6909 if (opt_iconv_in == ICONV_NONE)
6910 die("Failed to initialize character set conversion");
6911 }
6913 if (codeset && strcmp(codeset, "UTF-8")) {
6914 opt_iconv_out = iconv_open(codeset, "UTF-8");
6915 if (opt_iconv_out == ICONV_NONE)
6916 die("Failed to initialize character set conversion");
6917 }
6919 if (load_refs() == ERR)
6920 die("Failed to load refs.");
6922 init_display();
6924 while (view_driver(display[current_view], request)) {
6925 int key = get_input(0);
6927 view = display[current_view];
6928 request = get_keybinding(view->keymap, key);
6930 /* Some low-level request handling. This keeps access to
6931 * status_win restricted. */
6932 switch (request) {
6933 case REQ_NONE:
6934 report("Unknown key, press %s for help",
6935 get_key(view->keymap, REQ_VIEW_HELP));
6936 break;
6937 case REQ_PROMPT:
6938 {
6939 char *cmd = read_prompt(":");
6941 if (cmd && isdigit(*cmd)) {
6942 int lineno = view->lineno + 1;
6944 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OK) {
6945 select_view_line(view, lineno - 1);
6946 report("");
6947 } else {
6948 report("Unable to parse '%s' as a line number", cmd);
6949 }
6951 } else if (cmd) {
6952 struct view *next = VIEW(REQ_VIEW_PAGER);
6953 const char *argv[SIZEOF_ARG] = { "git" };
6954 int argc = 1;
6956 /* When running random commands, initially show the
6957 * command in the title. However, it maybe later be
6958 * overwritten if a commit line is selected. */
6959 string_ncopy(next->ref, cmd, strlen(cmd));
6961 if (!argv_from_string(argv, &argc, cmd)) {
6962 report("Too many arguments");
6963 } else {
6964 open_argv(view, next, argv, NULL, OPEN_DEFAULT);
6965 }
6966 }
6968 request = REQ_NONE;
6969 break;
6970 }
6971 case REQ_SEARCH:
6972 case REQ_SEARCH_BACK:
6973 {
6974 const char *prompt = request == REQ_SEARCH ? "/" : "?";
6975 char *search = read_prompt(prompt);
6977 if (search)
6978 string_ncopy(opt_search, search, strlen(search));
6979 else if (*opt_search)
6980 request = request == REQ_SEARCH ?
6981 REQ_FIND_NEXT :
6982 REQ_FIND_PREV;
6983 else
6984 request = REQ_NONE;
6985 break;
6986 }
6987 default:
6988 break;
6989 }
6990 }
6992 quit(0);
6994 return 0;
6995 }