9250cd7013e7c26b8187ce09c2ead6233bc61f87
1 /* Copyright (c) 2006-2010 Jonas Fonseca <fonseca@diku.dk>
2 *
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU General Public License as
5 * published by the Free Software Foundation; either version 2 of
6 * the License, or (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 */
14 #include "tig.h"
15 #include "io.h"
16 #include "graph.h"
18 static void __NORETURN die(const char *err, ...);
19 static void warn(const char *msg, ...);
20 static void report(const char *msg, ...);
23 struct ref {
24 char id[SIZEOF_REV]; /* Commit SHA1 ID */
25 unsigned int head:1; /* Is it the current HEAD? */
26 unsigned int tag:1; /* Is it a tag? */
27 unsigned int ltag:1; /* If so, is the tag local? */
28 unsigned int remote:1; /* Is it a remote ref? */
29 unsigned int tracked:1; /* Is it the remote for the current HEAD? */
30 char name[1]; /* Ref name; tag or head names are shortened. */
31 };
33 struct ref_list {
34 char id[SIZEOF_REV]; /* Commit SHA1 ID */
35 size_t size; /* Number of refs. */
36 struct ref **refs; /* References for this ID. */
37 };
39 static struct ref *get_ref_head();
40 static struct ref_list *get_ref_list(const char *id);
41 static void foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data);
42 static int load_refs(void);
44 enum input_status {
45 INPUT_OK,
46 INPUT_SKIP,
47 INPUT_STOP,
48 INPUT_CANCEL
49 };
51 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
53 static char *prompt_input(const char *prompt, input_handler handler, void *data);
54 static bool prompt_yesno(const char *prompt);
56 struct menu_item {
57 int hotkey;
58 const char *text;
59 void *data;
60 };
62 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
64 enum graphic {
65 GRAPHIC_ASCII = 0,
66 GRAPHIC_DEFAULT,
67 GRAPHIC_UTF8
68 };
70 static const struct enum_map graphic_map[] = {
71 #define GRAPHIC_(name) ENUM_MAP(#name, GRAPHIC_##name)
72 GRAPHIC_(ASCII),
73 GRAPHIC_(DEFAULT),
74 GRAPHIC_(UTF8)
75 #undef GRAPHIC_
76 };
78 #define DATE_INFO \
79 DATE_(NO), \
80 DATE_(DEFAULT), \
81 DATE_(LOCAL), \
82 DATE_(RELATIVE), \
83 DATE_(SHORT)
85 enum date {
86 #define DATE_(name) DATE_##name
87 DATE_INFO
88 #undef DATE_
89 };
91 static const struct enum_map date_map[] = {
92 #define DATE_(name) ENUM_MAP(#name, DATE_##name)
93 DATE_INFO
94 #undef DATE_
95 };
97 struct time {
98 time_t sec;
99 int tz;
100 };
102 static inline int timecmp(const struct time *t1, const struct time *t2)
103 {
104 return t1->sec - t2->sec;
105 }
107 static const char *
108 mkdate(const struct time *time, enum date date)
109 {
110 static char buf[DATE_COLS + 1];
111 static const struct enum_map reldate[] = {
112 { "second", 1, 60 * 2 },
113 { "minute", 60, 60 * 60 * 2 },
114 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
115 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
116 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
117 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 30 * 12 },
118 };
119 struct tm tm;
121 if (!date || !time || !time->sec)
122 return "";
124 if (date == DATE_RELATIVE) {
125 struct timeval now;
126 time_t date = time->sec + time->tz;
127 time_t seconds;
128 int i;
130 gettimeofday(&now, NULL);
131 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
132 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
133 if (seconds >= reldate[i].value)
134 continue;
136 seconds /= reldate[i].namelen;
137 if (!string_format(buf, "%ld %s%s %s",
138 seconds, reldate[i].name,
139 seconds > 1 ? "s" : "",
140 now.tv_sec >= date ? "ago" : "ahead"))
141 break;
142 return buf;
143 }
144 }
146 if (date == DATE_LOCAL) {
147 time_t date = time->sec + time->tz;
148 localtime_r(&date, &tm);
149 }
150 else {
151 gmtime_r(&time->sec, &tm);
152 }
153 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
154 }
157 #define AUTHOR_VALUES \
158 AUTHOR_(NO), \
159 AUTHOR_(FULL), \
160 AUTHOR_(ABBREVIATED)
162 enum author {
163 #define AUTHOR_(name) AUTHOR_##name
164 AUTHOR_VALUES,
165 #undef AUTHOR_
166 AUTHOR_DEFAULT = AUTHOR_FULL
167 };
169 static const struct enum_map author_map[] = {
170 #define AUTHOR_(name) ENUM_MAP(#name, AUTHOR_##name)
171 AUTHOR_VALUES
172 #undef AUTHOR_
173 };
175 static const char *
176 get_author_initials(const char *author)
177 {
178 static char initials[AUTHOR_COLS * 6 + 1];
179 size_t pos = 0;
180 const char *end = strchr(author, '\0');
182 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
184 memset(initials, 0, sizeof(initials));
185 while (author < end) {
186 unsigned char bytes;
187 size_t i;
189 while (is_initial_sep(*author))
190 author++;
192 bytes = utf8_char_length(author, end);
193 if (bytes < sizeof(initials) - 1 - pos) {
194 while (bytes--) {
195 initials[pos++] = *author++;
196 }
197 }
199 for (i = pos; author < end && !is_initial_sep(*author); author++) {
200 if (i < sizeof(initials) - 1)
201 initials[i++] = *author;
202 }
204 initials[i++] = 0;
205 }
207 return initials;
208 }
211 /*
212 * User requests
213 */
215 #define REQ_INFO \
216 /* XXX: Keep the view request first and in sync with views[]. */ \
217 REQ_GROUP("View switching") \
218 REQ_(VIEW_MAIN, "Show main view"), \
219 REQ_(VIEW_DIFF, "Show diff view"), \
220 REQ_(VIEW_LOG, "Show log view"), \
221 REQ_(VIEW_TREE, "Show tree view"), \
222 REQ_(VIEW_BLOB, "Show blob view"), \
223 REQ_(VIEW_BLAME, "Show blame view"), \
224 REQ_(VIEW_BRANCH, "Show branch view"), \
225 REQ_(VIEW_HELP, "Show help page"), \
226 REQ_(VIEW_PAGER, "Show pager view"), \
227 REQ_(VIEW_STATUS, "Show status view"), \
228 REQ_(VIEW_STAGE, "Show stage view"), \
229 \
230 REQ_GROUP("View manipulation") \
231 REQ_(ENTER, "Enter current line and scroll"), \
232 REQ_(NEXT, "Move to next"), \
233 REQ_(PREVIOUS, "Move to previous"), \
234 REQ_(PARENT, "Move to parent"), \
235 REQ_(VIEW_NEXT, "Move focus to next view"), \
236 REQ_(REFRESH, "Reload and refresh"), \
237 REQ_(MAXIMIZE, "Maximize the current view"), \
238 REQ_(VIEW_CLOSE, "Close the current view"), \
239 REQ_(QUIT, "Close all views and quit"), \
240 \
241 REQ_GROUP("View specific requests") \
242 REQ_(STATUS_UPDATE, "Update file status"), \
243 REQ_(STATUS_REVERT, "Revert file changes"), \
244 REQ_(STATUS_MERGE, "Merge file using external tool"), \
245 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
246 \
247 REQ_GROUP("Cursor navigation") \
248 REQ_(MOVE_UP, "Move cursor one line up"), \
249 REQ_(MOVE_DOWN, "Move cursor one line down"), \
250 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
251 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
252 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
253 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
254 \
255 REQ_GROUP("Scrolling") \
256 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
257 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
258 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
259 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
260 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
261 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
262 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
263 \
264 REQ_GROUP("Searching") \
265 REQ_(SEARCH, "Search the view"), \
266 REQ_(SEARCH_BACK, "Search backwards in the view"), \
267 REQ_(FIND_NEXT, "Find next search match"), \
268 REQ_(FIND_PREV, "Find previous search match"), \
269 \
270 REQ_GROUP("Option manipulation") \
271 REQ_(OPTIONS, "Open option menu"), \
272 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
273 REQ_(TOGGLE_DATE, "Toggle date display"), \
274 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
275 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
276 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
277 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
278 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
279 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
280 \
281 REQ_GROUP("Misc") \
282 REQ_(PROMPT, "Bring up the prompt"), \
283 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
284 REQ_(SHOW_VERSION, "Show version information"), \
285 REQ_(STOP_LOADING, "Stop all loading views"), \
286 REQ_(EDIT, "Open in editor"), \
287 REQ_(NONE, "Do nothing")
290 /* User action requests. */
291 enum request {
292 #define REQ_GROUP(help)
293 #define REQ_(req, help) REQ_##req
295 /* Offset all requests to avoid conflicts with ncurses getch values. */
296 REQ_UNKNOWN = KEY_MAX + 1,
297 REQ_OFFSET,
298 REQ_INFO
300 #undef REQ_GROUP
301 #undef REQ_
302 };
304 struct request_info {
305 enum request request;
306 const char *name;
307 int namelen;
308 const char *help;
309 };
311 static const struct request_info req_info[] = {
312 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
313 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
314 REQ_INFO
315 #undef REQ_GROUP
316 #undef REQ_
317 };
319 static enum request
320 get_request(const char *name)
321 {
322 int namelen = strlen(name);
323 int i;
325 for (i = 0; i < ARRAY_SIZE(req_info); i++)
326 if (enum_equals(req_info[i], name, namelen))
327 return req_info[i].request;
329 return REQ_UNKNOWN;
330 }
333 /*
334 * Options
335 */
337 /* Option and state variables. */
338 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
339 static enum date opt_date = DATE_DEFAULT;
340 static enum author opt_author = AUTHOR_DEFAULT;
341 static bool opt_rev_graph = TRUE;
342 static bool opt_line_number = FALSE;
343 static bool opt_show_refs = TRUE;
344 static bool opt_untracked_dirs_content = TRUE;
345 static int opt_num_interval = 5;
346 static double opt_hscroll = 0.50;
347 static double opt_scale_split_view = 2.0 / 3.0;
348 static int opt_tab_size = 8;
349 static int opt_author_cols = AUTHOR_COLS;
350 static char opt_path[SIZEOF_STR] = "";
351 static char opt_file[SIZEOF_STR] = "";
352 static char opt_ref[SIZEOF_REF] = "";
353 static char opt_head[SIZEOF_REF] = "";
354 static char opt_remote[SIZEOF_REF] = "";
355 static char opt_encoding[20] = "UTF-8";
356 static iconv_t opt_iconv_in = ICONV_NONE;
357 static iconv_t opt_iconv_out = ICONV_NONE;
358 static char opt_search[SIZEOF_STR] = "";
359 static char opt_cdup[SIZEOF_STR] = "";
360 static char opt_prefix[SIZEOF_STR] = "";
361 static char opt_git_dir[SIZEOF_STR] = "";
362 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
363 static char opt_editor[SIZEOF_STR] = "";
364 static FILE *opt_tty = NULL;
365 static const char **opt_diff_argv = NULL;
366 static const char **opt_rev_argv = NULL;
367 static const char **opt_file_argv = NULL;
369 #define is_initial_commit() (!get_ref_head())
370 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
373 /*
374 * Line-oriented content detection.
375 */
377 #define LINE_INFO \
378 LINE(DIFF_HEADER, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
379 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
380 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
381 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
382 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
383 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
384 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
385 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
386 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
387 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
388 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
389 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
390 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
391 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
392 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
393 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
394 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
395 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
396 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
397 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
398 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
399 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
400 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
401 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
402 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
403 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
404 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
405 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
406 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
407 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
408 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
409 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
410 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
411 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
412 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
413 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
414 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
415 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
416 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
417 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
418 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
419 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
420 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
421 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
422 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
423 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
424 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
425 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
426 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
427 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
428 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
429 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
430 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
431 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
432 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
433 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
434 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
435 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
436 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
437 LINE(GRAPH_LINE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
438 LINE(GRAPH_LINE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
439 LINE(GRAPH_LINE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
440 LINE(GRAPH_LINE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
441 LINE(GRAPH_LINE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
442 LINE(GRAPH_LINE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
443 LINE(GRAPH_LINE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
444 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
446 enum line_type {
447 #define LINE(type, line, fg, bg, attr) \
448 LINE_##type
449 LINE_INFO,
450 LINE_NONE
451 #undef LINE
452 };
454 struct line_info {
455 const char *name; /* Option name. */
456 int namelen; /* Size of option name. */
457 const char *line; /* The start of line to match. */
458 int linelen; /* Size of string to match. */
459 int fg, bg, attr; /* Color and text attributes for the lines. */
460 };
462 static struct line_info line_info[] = {
463 #define LINE(type, line, fg, bg, attr) \
464 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
465 LINE_INFO
466 #undef LINE
467 };
469 static enum line_type
470 get_line_type(const char *line)
471 {
472 int linelen = strlen(line);
473 enum line_type type;
475 for (type = 0; type < ARRAY_SIZE(line_info); type++)
476 /* Case insensitive search matches Signed-off-by lines better. */
477 if (linelen >= line_info[type].linelen &&
478 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
479 return type;
481 return LINE_DEFAULT;
482 }
484 static inline int
485 get_line_attr(enum line_type type)
486 {
487 assert(type < ARRAY_SIZE(line_info));
488 return COLOR_PAIR(type) | line_info[type].attr;
489 }
491 static struct line_info *
492 get_line_info(const char *name)
493 {
494 size_t namelen = strlen(name);
495 enum line_type type;
497 for (type = 0; type < ARRAY_SIZE(line_info); type++)
498 if (enum_equals(line_info[type], name, namelen))
499 return &line_info[type];
501 return NULL;
502 }
504 static void
505 init_colors(void)
506 {
507 int default_bg = line_info[LINE_DEFAULT].bg;
508 int default_fg = line_info[LINE_DEFAULT].fg;
509 enum line_type type;
511 start_color();
513 if (assume_default_colors(default_fg, default_bg) == ERR) {
514 default_bg = COLOR_BLACK;
515 default_fg = COLOR_WHITE;
516 }
518 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
519 struct line_info *info = &line_info[type];
520 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
521 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
523 init_pair(type, fg, bg);
524 }
525 }
527 struct line {
528 enum line_type type;
530 /* State flags */
531 unsigned int selected:1;
532 unsigned int dirty:1;
533 unsigned int cleareol:1;
534 unsigned int other:16;
536 void *data; /* User data */
537 };
540 /*
541 * Keys
542 */
544 struct keybinding {
545 int alias;
546 enum request request;
547 };
549 static struct keybinding default_keybindings[] = {
550 /* View switching */
551 { 'm', REQ_VIEW_MAIN },
552 { 'd', REQ_VIEW_DIFF },
553 { 'l', REQ_VIEW_LOG },
554 { 't', REQ_VIEW_TREE },
555 { 'f', REQ_VIEW_BLOB },
556 { 'B', REQ_VIEW_BLAME },
557 { 'H', REQ_VIEW_BRANCH },
558 { 'p', REQ_VIEW_PAGER },
559 { 'h', REQ_VIEW_HELP },
560 { 'S', REQ_VIEW_STATUS },
561 { 'c', REQ_VIEW_STAGE },
563 /* View manipulation */
564 { 'q', REQ_VIEW_CLOSE },
565 { KEY_TAB, REQ_VIEW_NEXT },
566 { KEY_RETURN, REQ_ENTER },
567 { KEY_UP, REQ_PREVIOUS },
568 { KEY_CTL('P'), REQ_PREVIOUS },
569 { KEY_DOWN, REQ_NEXT },
570 { KEY_CTL('N'), REQ_NEXT },
571 { 'R', REQ_REFRESH },
572 { KEY_F(5), REQ_REFRESH },
573 { 'O', REQ_MAXIMIZE },
575 /* Cursor navigation */
576 { 'k', REQ_MOVE_UP },
577 { 'j', REQ_MOVE_DOWN },
578 { KEY_HOME, REQ_MOVE_FIRST_LINE },
579 { KEY_END, REQ_MOVE_LAST_LINE },
580 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
581 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
582 { ' ', REQ_MOVE_PAGE_DOWN },
583 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
584 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
585 { 'b', REQ_MOVE_PAGE_UP },
586 { '-', REQ_MOVE_PAGE_UP },
588 /* Scrolling */
589 { '|', REQ_SCROLL_FIRST_COL },
590 { KEY_LEFT, REQ_SCROLL_LEFT },
591 { KEY_RIGHT, REQ_SCROLL_RIGHT },
592 { KEY_IC, REQ_SCROLL_LINE_UP },
593 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
594 { KEY_DC, REQ_SCROLL_LINE_DOWN },
595 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
596 { 'w', REQ_SCROLL_PAGE_UP },
597 { 's', REQ_SCROLL_PAGE_DOWN },
599 /* Searching */
600 { '/', REQ_SEARCH },
601 { '?', REQ_SEARCH_BACK },
602 { 'n', REQ_FIND_NEXT },
603 { 'N', REQ_FIND_PREV },
605 /* Misc */
606 { 'Q', REQ_QUIT },
607 { 'z', REQ_STOP_LOADING },
608 { 'v', REQ_SHOW_VERSION },
609 { 'r', REQ_SCREEN_REDRAW },
610 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
611 { 'o', REQ_OPTIONS },
612 { '.', REQ_TOGGLE_LINENO },
613 { 'D', REQ_TOGGLE_DATE },
614 { 'A', REQ_TOGGLE_AUTHOR },
615 { 'g', REQ_TOGGLE_REV_GRAPH },
616 { '~', REQ_TOGGLE_GRAPHIC },
617 { 'F', REQ_TOGGLE_REFS },
618 { 'I', REQ_TOGGLE_SORT_ORDER },
619 { 'i', REQ_TOGGLE_SORT_FIELD },
620 { ':', REQ_PROMPT },
621 { 'u', REQ_STATUS_UPDATE },
622 { '!', REQ_STATUS_REVERT },
623 { 'M', REQ_STATUS_MERGE },
624 { '@', REQ_STAGE_NEXT },
625 { ',', REQ_PARENT },
626 { 'e', REQ_EDIT },
627 };
629 #define KEYMAP_INFO \
630 KEYMAP_(GENERIC), \
631 KEYMAP_(MAIN), \
632 KEYMAP_(DIFF), \
633 KEYMAP_(LOG), \
634 KEYMAP_(TREE), \
635 KEYMAP_(BLOB), \
636 KEYMAP_(BLAME), \
637 KEYMAP_(BRANCH), \
638 KEYMAP_(PAGER), \
639 KEYMAP_(HELP), \
640 KEYMAP_(STATUS), \
641 KEYMAP_(STAGE)
643 enum keymap {
644 #define KEYMAP_(name) KEYMAP_##name
645 KEYMAP_INFO
646 #undef KEYMAP_
647 };
649 static const struct enum_map keymap_table[] = {
650 #define KEYMAP_(name) ENUM_MAP(#name, KEYMAP_##name)
651 KEYMAP_INFO
652 #undef KEYMAP_
653 };
655 #define set_keymap(map, name) map_enum(map, keymap_table, name)
657 struct keybinding_table {
658 struct keybinding *data;
659 size_t size;
660 };
662 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_table)];
664 static void
665 add_keybinding(enum keymap keymap, enum request request, int key)
666 {
667 struct keybinding_table *table = &keybindings[keymap];
668 size_t i;
670 for (i = 0; i < keybindings[keymap].size; i++) {
671 if (keybindings[keymap].data[i].alias == key) {
672 keybindings[keymap].data[i].request = request;
673 return;
674 }
675 }
677 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
678 if (!table->data)
679 die("Failed to allocate keybinding");
680 table->data[table->size].alias = key;
681 table->data[table->size++].request = request;
683 if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
684 int i;
686 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
687 if (default_keybindings[i].alias == key)
688 default_keybindings[i].request = REQ_NONE;
689 }
690 }
692 /* Looks for a key binding first in the given map, then in the generic map, and
693 * lastly in the default keybindings. */
694 static enum request
695 get_keybinding(enum keymap keymap, int key)
696 {
697 size_t i;
699 for (i = 0; i < keybindings[keymap].size; i++)
700 if (keybindings[keymap].data[i].alias == key)
701 return keybindings[keymap].data[i].request;
703 for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
704 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
705 return keybindings[KEYMAP_GENERIC].data[i].request;
707 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
708 if (default_keybindings[i].alias == key)
709 return default_keybindings[i].request;
711 return (enum request) key;
712 }
715 struct key {
716 const char *name;
717 int value;
718 };
720 static const struct key key_table[] = {
721 { "Enter", KEY_RETURN },
722 { "Space", ' ' },
723 { "Backspace", KEY_BACKSPACE },
724 { "Tab", KEY_TAB },
725 { "Escape", KEY_ESC },
726 { "Left", KEY_LEFT },
727 { "Right", KEY_RIGHT },
728 { "Up", KEY_UP },
729 { "Down", KEY_DOWN },
730 { "Insert", KEY_IC },
731 { "Delete", KEY_DC },
732 { "Hash", '#' },
733 { "Home", KEY_HOME },
734 { "End", KEY_END },
735 { "PageUp", KEY_PPAGE },
736 { "PageDown", KEY_NPAGE },
737 { "F1", KEY_F(1) },
738 { "F2", KEY_F(2) },
739 { "F3", KEY_F(3) },
740 { "F4", KEY_F(4) },
741 { "F5", KEY_F(5) },
742 { "F6", KEY_F(6) },
743 { "F7", KEY_F(7) },
744 { "F8", KEY_F(8) },
745 { "F9", KEY_F(9) },
746 { "F10", KEY_F(10) },
747 { "F11", KEY_F(11) },
748 { "F12", KEY_F(12) },
749 };
751 static int
752 get_key_value(const char *name)
753 {
754 int i;
756 for (i = 0; i < ARRAY_SIZE(key_table); i++)
757 if (!strcasecmp(key_table[i].name, name))
758 return key_table[i].value;
760 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
761 return (int)name[1] & 0x1f;
762 if (strlen(name) == 1 && isprint(*name))
763 return (int) *name;
764 return ERR;
765 }
767 static const char *
768 get_key_name(int key_value)
769 {
770 static char key_char[] = "'X'\0";
771 const char *seq = NULL;
772 int key;
774 for (key = 0; key < ARRAY_SIZE(key_table); key++)
775 if (key_table[key].value == key_value)
776 seq = key_table[key].name;
778 if (seq == NULL && key_value < 0x7f) {
779 char *s = key_char + 1;
781 if (key_value >= 0x20) {
782 *s++ = key_value;
783 } else {
784 *s++ = '^';
785 *s++ = 0x40 | (key_value & 0x1f);
786 }
787 *s++ = '\'';
788 *s++ = '\0';
789 seq = key_char;
790 }
792 return seq ? seq : "(no key)";
793 }
795 static bool
796 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
797 {
798 const char *sep = *pos > 0 ? ", " : "";
799 const char *keyname = get_key_name(keybinding->alias);
801 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
802 }
804 static bool
805 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
806 enum keymap keymap, bool all)
807 {
808 int i;
810 for (i = 0; i < keybindings[keymap].size; i++) {
811 if (keybindings[keymap].data[i].request == request) {
812 if (!append_key(buf, pos, &keybindings[keymap].data[i]))
813 return FALSE;
814 if (!all)
815 break;
816 }
817 }
819 return TRUE;
820 }
822 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
824 static const char *
825 get_keys(enum keymap keymap, enum request request, bool all)
826 {
827 static char buf[BUFSIZ];
828 size_t pos = 0;
829 int i;
831 buf[pos] = 0;
833 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
834 return "Too many keybindings!";
835 if (pos > 0 && !all)
836 return buf;
838 if (keymap != KEYMAP_GENERIC) {
839 /* Only the generic keymap includes the default keybindings when
840 * listing all keys. */
841 if (all)
842 return buf;
844 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
845 return "Too many keybindings!";
846 if (pos)
847 return buf;
848 }
850 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
851 if (default_keybindings[i].request == request) {
852 if (!append_key(buf, &pos, &default_keybindings[i]))
853 return "Too many keybindings!";
854 if (!all)
855 return buf;
856 }
857 }
859 return buf;
860 }
862 struct run_request {
863 enum keymap keymap;
864 int key;
865 const char **argv;
866 };
868 static struct run_request *run_request;
869 static size_t run_requests;
871 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
873 static enum request
874 add_run_request(enum keymap keymap, int key, const char **argv)
875 {
876 struct run_request *req;
878 if (!realloc_run_requests(&run_request, run_requests, 1))
879 return REQ_NONE;
881 req = &run_request[run_requests];
882 req->keymap = keymap;
883 req->key = key;
884 req->argv = NULL;
886 if (!argv_copy(&req->argv, argv))
887 return REQ_NONE;
889 return REQ_NONE + ++run_requests;
890 }
892 static struct run_request *
893 get_run_request(enum request request)
894 {
895 if (request <= REQ_NONE)
896 return NULL;
897 return &run_request[request - REQ_NONE - 1];
898 }
900 static void
901 add_builtin_run_requests(void)
902 {
903 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
904 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
905 const char *commit[] = { "git", "commit", NULL };
906 const char *gc[] = { "git", "gc", NULL };
907 struct run_request reqs[] = {
908 { KEYMAP_MAIN, 'C', cherry_pick },
909 { KEYMAP_STATUS, 'C', commit },
910 { KEYMAP_BRANCH, 'C', checkout },
911 { KEYMAP_GENERIC, 'G', gc },
912 };
913 int i;
915 for (i = 0; i < ARRAY_SIZE(reqs); i++) {
916 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
918 if (req != reqs[i].key)
919 continue;
920 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
921 if (req != REQ_NONE)
922 add_keybinding(reqs[i].keymap, req, reqs[i].key);
923 }
924 }
926 /*
927 * User config file handling.
928 */
930 #define OPT_ERR_INFO \
931 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
932 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
933 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
934 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
935 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
936 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
937 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
938 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
939 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
940 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
941 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
942 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
943 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
944 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
945 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
946 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
948 enum option_code {
949 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
950 OPT_ERR_INFO
951 #undef OPT_ERR_
952 OPT_OK
953 };
955 static const char *option_errors[] = {
956 #define OPT_ERR_(name, msg) msg
957 OPT_ERR_INFO
958 #undef OPT_ERR_
959 };
961 static const struct enum_map color_map[] = {
962 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
963 COLOR_MAP(DEFAULT),
964 COLOR_MAP(BLACK),
965 COLOR_MAP(BLUE),
966 COLOR_MAP(CYAN),
967 COLOR_MAP(GREEN),
968 COLOR_MAP(MAGENTA),
969 COLOR_MAP(RED),
970 COLOR_MAP(WHITE),
971 COLOR_MAP(YELLOW),
972 };
974 static const struct enum_map attr_map[] = {
975 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
976 ATTR_MAP(NORMAL),
977 ATTR_MAP(BLINK),
978 ATTR_MAP(BOLD),
979 ATTR_MAP(DIM),
980 ATTR_MAP(REVERSE),
981 ATTR_MAP(STANDOUT),
982 ATTR_MAP(UNDERLINE),
983 };
985 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
987 static enum option_code
988 parse_step(double *opt, const char *arg)
989 {
990 *opt = atoi(arg);
991 if (!strchr(arg, '%'))
992 return OPT_OK;
994 /* "Shift down" so 100% and 1 does not conflict. */
995 *opt = (*opt - 1) / 100;
996 if (*opt >= 1.0) {
997 *opt = 0.99;
998 return OPT_ERR_INVALID_STEP_VALUE;
999 }
1000 if (*opt < 0.0) {
1001 *opt = 1;
1002 return OPT_ERR_INVALID_STEP_VALUE;
1003 }
1004 return OPT_OK;
1005 }
1007 static enum option_code
1008 parse_int(int *opt, const char *arg, int min, int max)
1009 {
1010 int value = atoi(arg);
1012 if (min <= value && value <= max) {
1013 *opt = value;
1014 return OPT_OK;
1015 }
1017 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1018 }
1020 static bool
1021 set_color(int *color, const char *name)
1022 {
1023 if (map_enum(color, color_map, name))
1024 return TRUE;
1025 if (!prefixcmp(name, "color"))
1026 return parse_int(color, name + 5, 0, 255) == OK;
1027 return FALSE;
1028 }
1030 /* Wants: object fgcolor bgcolor [attribute] */
1031 static enum option_code
1032 option_color_command(int argc, const char *argv[])
1033 {
1034 struct line_info *info;
1036 if (argc < 3)
1037 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1039 info = get_line_info(argv[0]);
1040 if (!info) {
1041 static const struct enum_map obsolete[] = {
1042 ENUM_MAP("main-delim", LINE_DELIMITER),
1043 ENUM_MAP("main-date", LINE_DATE),
1044 ENUM_MAP("main-author", LINE_AUTHOR),
1045 };
1046 int index;
1048 if (!map_enum(&index, obsolete, argv[0]))
1049 return OPT_ERR_UNKNOWN_COLOR_NAME;
1050 info = &line_info[index];
1051 }
1053 if (!set_color(&info->fg, argv[1]) ||
1054 !set_color(&info->bg, argv[2]))
1055 return OPT_ERR_UNKNOWN_COLOR;
1057 info->attr = 0;
1058 while (argc-- > 3) {
1059 int attr;
1061 if (!set_attribute(&attr, argv[argc]))
1062 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1063 info->attr |= attr;
1064 }
1066 return OPT_OK;
1067 }
1069 static enum option_code
1070 parse_bool(bool *opt, const char *arg)
1071 {
1072 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1073 ? TRUE : FALSE;
1074 return OPT_OK;
1075 }
1077 static enum option_code
1078 parse_enum_do(unsigned int *opt, const char *arg,
1079 const struct enum_map *map, size_t map_size)
1080 {
1081 bool is_true;
1083 assert(map_size > 1);
1085 if (map_enum_do(map, map_size, (int *) opt, arg))
1086 return OPT_OK;
1088 parse_bool(&is_true, arg);
1089 *opt = is_true ? map[1].value : map[0].value;
1090 return OPT_OK;
1091 }
1093 #define parse_enum(opt, arg, map) \
1094 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1096 static enum option_code
1097 parse_string(char *opt, const char *arg, size_t optsize)
1098 {
1099 int arglen = strlen(arg);
1101 switch (arg[0]) {
1102 case '\"':
1103 case '\'':
1104 if (arglen == 1 || arg[arglen - 1] != arg[0])
1105 return OPT_ERR_UNMATCHED_QUOTATION;
1106 arg += 1; arglen -= 2;
1107 default:
1108 string_ncopy_do(opt, optsize, arg, arglen);
1109 return OPT_OK;
1110 }
1111 }
1113 /* Wants: name = value */
1114 static enum option_code
1115 option_set_command(int argc, const char *argv[])
1116 {
1117 if (argc != 3)
1118 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1120 if (strcmp(argv[1], "="))
1121 return OPT_ERR_NO_VALUE_ASSIGNED;
1123 if (!strcmp(argv[0], "show-author"))
1124 return parse_enum(&opt_author, argv[2], author_map);
1126 if (!strcmp(argv[0], "show-date"))
1127 return parse_enum(&opt_date, argv[2], date_map);
1129 if (!strcmp(argv[0], "show-rev-graph"))
1130 return parse_bool(&opt_rev_graph, argv[2]);
1132 if (!strcmp(argv[0], "show-refs"))
1133 return parse_bool(&opt_show_refs, argv[2]);
1135 if (!strcmp(argv[0], "show-line-numbers"))
1136 return parse_bool(&opt_line_number, argv[2]);
1138 if (!strcmp(argv[0], "line-graphics"))
1139 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1141 if (!strcmp(argv[0], "line-number-interval"))
1142 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1144 if (!strcmp(argv[0], "author-width"))
1145 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1147 if (!strcmp(argv[0], "horizontal-scroll"))
1148 return parse_step(&opt_hscroll, argv[2]);
1150 if (!strcmp(argv[0], "split-view-height"))
1151 return parse_step(&opt_scale_split_view, argv[2]);
1153 if (!strcmp(argv[0], "tab-size"))
1154 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1156 if (!strcmp(argv[0], "commit-encoding"))
1157 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1159 if (!strcmp(argv[0], "status-untracked-dirs"))
1160 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1162 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1163 }
1165 /* Wants: mode request key */
1166 static enum option_code
1167 option_bind_command(int argc, const char *argv[])
1168 {
1169 enum request request;
1170 int keymap = -1;
1171 int key;
1173 if (argc < 3)
1174 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1176 if (!set_keymap(&keymap, argv[0]))
1177 return OPT_ERR_UNKNOWN_KEY_MAP;
1179 key = get_key_value(argv[1]);
1180 if (key == ERR)
1181 return OPT_ERR_UNKNOWN_KEY;
1183 request = get_request(argv[2]);
1184 if (request == REQ_UNKNOWN) {
1185 static const struct enum_map obsolete[] = {
1186 ENUM_MAP("cherry-pick", REQ_NONE),
1187 ENUM_MAP("screen-resize", REQ_NONE),
1188 ENUM_MAP("tree-parent", REQ_PARENT),
1189 };
1190 int alias;
1192 if (map_enum(&alias, obsolete, argv[2])) {
1193 if (alias != REQ_NONE)
1194 add_keybinding(keymap, alias, key);
1195 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1196 }
1197 }
1198 if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1199 request = add_run_request(keymap, key, argv + 2);
1200 if (request == REQ_UNKNOWN)
1201 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1203 add_keybinding(keymap, request, key);
1205 return OPT_OK;
1206 }
1208 static enum option_code
1209 set_option(const char *opt, char *value)
1210 {
1211 const char *argv[SIZEOF_ARG];
1212 int argc = 0;
1214 if (!argv_from_string(argv, &argc, value))
1215 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1217 if (!strcmp(opt, "color"))
1218 return option_color_command(argc, argv);
1220 if (!strcmp(opt, "set"))
1221 return option_set_command(argc, argv);
1223 if (!strcmp(opt, "bind"))
1224 return option_bind_command(argc, argv);
1226 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1227 }
1229 struct config_state {
1230 int lineno;
1231 bool errors;
1232 };
1234 static int
1235 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1236 {
1237 struct config_state *config = data;
1238 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1240 config->lineno++;
1242 /* Check for comment markers, since read_properties() will
1243 * only ensure opt and value are split at first " \t". */
1244 optlen = strcspn(opt, "#");
1245 if (optlen == 0)
1246 return OK;
1248 if (opt[optlen] == 0) {
1249 /* Look for comment endings in the value. */
1250 size_t len = strcspn(value, "#");
1252 if (len < valuelen) {
1253 valuelen = len;
1254 value[valuelen] = 0;
1255 }
1257 status = set_option(opt, value);
1258 }
1260 if (status != OPT_OK) {
1261 warn("Error on line %d, near '%.*s': %s",
1262 config->lineno, (int) optlen, opt, option_errors[status]);
1263 config->errors = TRUE;
1264 }
1266 /* Always keep going if errors are encountered. */
1267 return OK;
1268 }
1270 static void
1271 load_option_file(const char *path)
1272 {
1273 struct config_state config = { 0, FALSE };
1274 struct io io;
1276 /* It's OK that the file doesn't exist. */
1277 if (!io_open(&io, "%s", path))
1278 return;
1280 if (io_load(&io, " \t", read_option, &config) == ERR ||
1281 config.errors == TRUE)
1282 warn("Errors while loading %s.", path);
1283 }
1285 static int
1286 load_options(void)
1287 {
1288 const char *home = getenv("HOME");
1289 const char *tigrc_user = getenv("TIGRC_USER");
1290 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1291 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1292 char buf[SIZEOF_STR];
1294 if (!tigrc_system)
1295 tigrc_system = SYSCONFDIR "/tigrc";
1296 load_option_file(tigrc_system);
1298 if (!tigrc_user) {
1299 if (!home || !string_format(buf, "%s/.tigrc", home))
1300 return ERR;
1301 tigrc_user = buf;
1302 }
1303 load_option_file(tigrc_user);
1305 /* Add _after_ loading config files to avoid adding run requests
1306 * that conflict with keybindings. */
1307 add_builtin_run_requests();
1309 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1310 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1311 int argc = 0;
1313 if (!string_format(buf, "%s", tig_diff_opts) ||
1314 !argv_from_string(diff_opts, &argc, buf))
1315 die("TIG_DIFF_OPTS contains too many arguments");
1316 else if (!argv_copy(&opt_diff_argv, diff_opts))
1317 die("Failed to format TIG_DIFF_OPTS arguments");
1318 }
1320 return OK;
1321 }
1324 /*
1325 * The viewer
1326 */
1328 struct view;
1329 struct view_ops;
1331 /* The display array of active views and the index of the current view. */
1332 static struct view *display[2];
1333 static WINDOW *display_win[2];
1334 static WINDOW *display_title[2];
1335 static unsigned int current_view;
1337 #define foreach_displayed_view(view, i) \
1338 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1340 #define displayed_views() (display[1] != NULL ? 2 : 1)
1342 /* Current head and commit ID */
1343 static char ref_blob[SIZEOF_REF] = "";
1344 static char ref_commit[SIZEOF_REF] = "HEAD";
1345 static char ref_head[SIZEOF_REF] = "HEAD";
1346 static char ref_branch[SIZEOF_REF] = "";
1348 enum view_type {
1349 VIEW_MAIN,
1350 VIEW_DIFF,
1351 VIEW_LOG,
1352 VIEW_TREE,
1353 VIEW_BLOB,
1354 VIEW_BLAME,
1355 VIEW_BRANCH,
1356 VIEW_HELP,
1357 VIEW_PAGER,
1358 VIEW_STATUS,
1359 VIEW_STAGE,
1360 };
1362 struct view {
1363 enum view_type type; /* View type */
1364 const char *name; /* View name */
1365 const char *cmd_env; /* Command line set via environment */
1366 const char *id; /* Points to either of ref_{head,commit,blob} */
1368 struct view_ops *ops; /* View operations */
1370 enum keymap keymap; /* What keymap does this view have */
1371 bool git_dir; /* Whether the view requires a git directory. */
1373 char ref[SIZEOF_REF]; /* Hovered commit reference */
1374 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1376 int height, width; /* The width and height of the main window */
1377 WINDOW *win; /* The main window */
1379 /* Navigation */
1380 unsigned long offset; /* Offset of the window top */
1381 unsigned long yoffset; /* Offset from the window side. */
1382 unsigned long lineno; /* Current line number */
1383 unsigned long p_offset; /* Previous offset of the window top */
1384 unsigned long p_yoffset;/* Previous offset from the window side */
1385 unsigned long p_lineno; /* Previous current line number */
1386 bool p_restore; /* Should the previous position be restored. */
1388 /* Searching */
1389 char grep[SIZEOF_STR]; /* Search string */
1390 regex_t *regex; /* Pre-compiled regexp */
1392 /* If non-NULL, points to the view that opened this view. If this view
1393 * is closed tig will switch back to the parent view. */
1394 struct view *parent;
1395 struct view *prev;
1397 /* Buffering */
1398 size_t lines; /* Total number of lines */
1399 struct line *line; /* Line index */
1400 unsigned int digits; /* Number of digits in the lines member. */
1402 /* Drawing */
1403 struct line *curline; /* Line currently being drawn. */
1404 enum line_type curtype; /* Attribute currently used for drawing. */
1405 unsigned long col; /* Column when drawing. */
1406 bool has_scrolled; /* View was scrolled. */
1408 /* Loading */
1409 const char **argv; /* Shell command arguments. */
1410 const char *dir; /* Directory from which to execute. */
1411 struct io io;
1412 struct io *pipe;
1413 time_t start_time;
1414 time_t update_secs;
1415 };
1417 struct view_ops {
1418 /* What type of content being displayed. Used in the title bar. */
1419 const char *type;
1420 /* Default command arguments. */
1421 const char **argv;
1422 /* Open and reads in all view content. */
1423 bool (*open)(struct view *view);
1424 /* Read one line; updates view->line. */
1425 bool (*read)(struct view *view, char *data);
1426 /* Draw one line; @lineno must be < view->height. */
1427 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1428 /* Depending on view handle a special requests. */
1429 enum request (*request)(struct view *view, enum request request, struct line *line);
1430 /* Search for regexp in a line. */
1431 bool (*grep)(struct view *view, struct line *line);
1432 /* Select line */
1433 void (*select)(struct view *view, struct line *line);
1434 /* Prepare view for loading */
1435 bool (*prepare)(struct view *view);
1436 };
1438 static struct view_ops blame_ops;
1439 static struct view_ops blob_ops;
1440 static struct view_ops diff_ops;
1441 static struct view_ops help_ops;
1442 static struct view_ops log_ops;
1443 static struct view_ops main_ops;
1444 static struct view_ops pager_ops;
1445 static struct view_ops stage_ops;
1446 static struct view_ops status_ops;
1447 static struct view_ops tree_ops;
1448 static struct view_ops branch_ops;
1450 #define VIEW_STR(type, name, env, ref, ops, map, git) \
1451 { type, name, #env, ref, ops, map, git }
1453 #define VIEW_(id, name, ops, git, ref) \
1454 VIEW_STR(VIEW_##id, name, TIG_##id##_CMD, ref, ops, KEYMAP_##id, git)
1456 static struct view views[] = {
1457 VIEW_(MAIN, "main", &main_ops, TRUE, ref_head),
1458 VIEW_(DIFF, "diff", &diff_ops, TRUE, ref_commit),
1459 VIEW_(LOG, "log", &log_ops, TRUE, ref_head),
1460 VIEW_(TREE, "tree", &tree_ops, TRUE, ref_commit),
1461 VIEW_(BLOB, "blob", &blob_ops, TRUE, ref_blob),
1462 VIEW_(BLAME, "blame", &blame_ops, TRUE, ref_commit),
1463 VIEW_(BRANCH, "branch", &branch_ops, TRUE, ref_head),
1464 VIEW_(HELP, "help", &help_ops, FALSE, ""),
1465 VIEW_(PAGER, "pager", &pager_ops, FALSE, ""),
1466 VIEW_(STATUS, "status", &status_ops, TRUE, ""),
1467 VIEW_(STAGE, "stage", &stage_ops, TRUE, ""),
1468 };
1470 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1472 #define foreach_view(view, i) \
1473 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1475 #define view_is_displayed(view) \
1476 (view == display[0] || view == display[1])
1478 static enum request
1479 view_request(struct view *view, enum request request)
1480 {
1481 if (!view || !view->lines)
1482 return request;
1483 return view->ops->request(view, request, &view->line[view->lineno]);
1484 }
1487 /*
1488 * View drawing.
1489 */
1491 static inline void
1492 set_view_attr(struct view *view, enum line_type type)
1493 {
1494 if (!view->curline->selected && view->curtype != type) {
1495 (void) wattrset(view->win, get_line_attr(type));
1496 wchgat(view->win, -1, 0, type, NULL);
1497 view->curtype = type;
1498 }
1499 }
1501 static int
1502 draw_chars(struct view *view, enum line_type type, const char *string,
1503 int max_len, bool use_tilde)
1504 {
1505 static char out_buffer[BUFSIZ * 2];
1506 int len = 0;
1507 int col = 0;
1508 int trimmed = FALSE;
1509 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1511 if (max_len <= 0)
1512 return 0;
1514 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1516 set_view_attr(view, type);
1517 if (len > 0) {
1518 if (opt_iconv_out != ICONV_NONE) {
1519 ICONV_CONST char *inbuf = (ICONV_CONST char *) string;
1520 size_t inlen = len + 1;
1522 char *outbuf = out_buffer;
1523 size_t outlen = sizeof(out_buffer);
1525 size_t ret;
1527 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1528 if (ret != (size_t) -1) {
1529 string = out_buffer;
1530 len = sizeof(out_buffer) - outlen;
1531 }
1532 }
1534 waddnstr(view->win, string, len);
1536 if (trimmed && use_tilde) {
1537 set_view_attr(view, LINE_DELIMITER);
1538 waddch(view->win, '~');
1539 col++;
1540 }
1541 }
1543 return col;
1544 }
1546 static int
1547 draw_space(struct view *view, enum line_type type, int max, int spaces)
1548 {
1549 static char space[] = " ";
1550 int col = 0;
1552 spaces = MIN(max, spaces);
1554 while (spaces > 0) {
1555 int len = MIN(spaces, sizeof(space) - 1);
1557 col += draw_chars(view, type, space, len, FALSE);
1558 spaces -= len;
1559 }
1561 return col;
1562 }
1564 static bool
1565 draw_text(struct view *view, enum line_type type, const char *string)
1566 {
1567 char text[SIZEOF_STR];
1569 do {
1570 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1572 view->col += draw_chars(view, type, text, view->width + view->yoffset - view->col, TRUE);
1573 string += pos;
1574 } while (*string && view->width + view->yoffset > view->col);
1576 return view->width + view->yoffset <= view->col;
1577 }
1579 static bool
1580 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1581 {
1582 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1583 int max = view->width + view->yoffset - view->col;
1584 int i;
1586 if (max < size)
1587 size = max;
1589 set_view_attr(view, type);
1590 /* Using waddch() instead of waddnstr() ensures that
1591 * they'll be rendered correctly for the cursor line. */
1592 for (i = skip; i < size; i++)
1593 waddch(view->win, graphic[i]);
1595 view->col += size;
1596 if (separator) {
1597 if (size < max && skip <= size)
1598 waddch(view->win, ' ');
1599 view->col++;
1600 }
1602 return view->width + view->yoffset <= view->col;
1603 }
1605 static bool
1606 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1607 {
1608 int max = MIN(view->width + view->yoffset - view->col, len);
1609 int col;
1611 if (text)
1612 col = draw_chars(view, type, text, max - 1, trim);
1613 else
1614 col = draw_space(view, type, max - 1, max - 1);
1616 view->col += col;
1617 view->col += draw_space(view, LINE_DEFAULT, max - col, max - col);
1618 return view->width + view->yoffset <= view->col;
1619 }
1621 static bool
1622 draw_date(struct view *view, struct time *time)
1623 {
1624 const char *date = mkdate(time, opt_date);
1625 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1627 return draw_field(view, LINE_DATE, date, cols, FALSE);
1628 }
1630 static bool
1631 draw_author(struct view *view, const char *author)
1632 {
1633 bool trim = opt_author_cols == 0 || opt_author_cols > 5;
1634 bool abbreviate = opt_author == AUTHOR_ABBREVIATED || !trim;
1636 if (abbreviate && author)
1637 author = get_author_initials(author);
1639 return draw_field(view, LINE_AUTHOR, author, opt_author_cols, trim);
1640 }
1642 static bool
1643 draw_mode(struct view *view, mode_t mode)
1644 {
1645 const char *str;
1647 if (S_ISDIR(mode))
1648 str = "drwxr-xr-x";
1649 else if (S_ISLNK(mode))
1650 str = "lrwxrwxrwx";
1651 else if (S_ISGITLINK(mode))
1652 str = "m---------";
1653 else if (S_ISREG(mode) && mode & S_IXUSR)
1654 str = "-rwxr-xr-x";
1655 else if (S_ISREG(mode))
1656 str = "-rw-r--r--";
1657 else
1658 str = "----------";
1660 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1661 }
1663 static bool
1664 draw_lineno(struct view *view, unsigned int lineno)
1665 {
1666 char number[10];
1667 int digits3 = view->digits < 3 ? 3 : view->digits;
1668 int max = MIN(view->width + view->yoffset - view->col, digits3);
1669 char *text = NULL;
1670 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1672 lineno += view->offset + 1;
1673 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1674 static char fmt[] = "%1ld";
1676 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1677 if (string_format(number, fmt, lineno))
1678 text = number;
1679 }
1680 if (text)
1681 view->col += draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1682 else
1683 view->col += draw_space(view, LINE_LINE_NUMBER, max, digits3);
1684 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1685 }
1687 static bool
1688 draw_view_line(struct view *view, unsigned int lineno)
1689 {
1690 struct line *line;
1691 bool selected = (view->offset + lineno == view->lineno);
1693 assert(view_is_displayed(view));
1695 if (view->offset + lineno >= view->lines)
1696 return FALSE;
1698 line = &view->line[view->offset + lineno];
1700 wmove(view->win, lineno, 0);
1701 if (line->cleareol)
1702 wclrtoeol(view->win);
1703 view->col = 0;
1704 view->curline = line;
1705 view->curtype = LINE_NONE;
1706 line->selected = FALSE;
1707 line->dirty = line->cleareol = 0;
1709 if (selected) {
1710 set_view_attr(view, LINE_CURSOR);
1711 line->selected = TRUE;
1712 view->ops->select(view, line);
1713 }
1715 return view->ops->draw(view, line, lineno);
1716 }
1718 static void
1719 redraw_view_dirty(struct view *view)
1720 {
1721 bool dirty = FALSE;
1722 int lineno;
1724 for (lineno = 0; lineno < view->height; lineno++) {
1725 if (view->offset + lineno >= view->lines)
1726 break;
1727 if (!view->line[view->offset + lineno].dirty)
1728 continue;
1729 dirty = TRUE;
1730 if (!draw_view_line(view, lineno))
1731 break;
1732 }
1734 if (!dirty)
1735 return;
1736 wnoutrefresh(view->win);
1737 }
1739 static void
1740 redraw_view_from(struct view *view, int lineno)
1741 {
1742 assert(0 <= lineno && lineno < view->height);
1744 for (; lineno < view->height; lineno++) {
1745 if (!draw_view_line(view, lineno))
1746 break;
1747 }
1749 wnoutrefresh(view->win);
1750 }
1752 static void
1753 redraw_view(struct view *view)
1754 {
1755 werase(view->win);
1756 redraw_view_from(view, 0);
1757 }
1760 static void
1761 update_view_title(struct view *view)
1762 {
1763 char buf[SIZEOF_STR];
1764 char state[SIZEOF_STR];
1765 size_t bufpos = 0, statelen = 0;
1766 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1768 assert(view_is_displayed(view));
1770 if (view->type != VIEW_STATUS && view->lines) {
1771 unsigned int view_lines = view->offset + view->height;
1772 unsigned int lines = view->lines
1773 ? MIN(view_lines, view->lines) * 100 / view->lines
1774 : 0;
1776 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
1777 view->ops->type,
1778 view->lineno + 1,
1779 view->lines,
1780 lines);
1782 }
1784 if (view->pipe) {
1785 time_t secs = time(NULL) - view->start_time;
1787 /* Three git seconds are a long time ... */
1788 if (secs > 2)
1789 string_format_from(state, &statelen, " loading %lds", secs);
1790 }
1792 string_format_from(buf, &bufpos, "[%s]", view->name);
1793 if (*view->ref && bufpos < view->width) {
1794 size_t refsize = strlen(view->ref);
1795 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
1797 if (minsize < view->width)
1798 refsize = view->width - minsize + 7;
1799 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
1800 }
1802 if (statelen && bufpos < view->width) {
1803 string_format_from(buf, &bufpos, "%s", state);
1804 }
1806 if (view == display[current_view])
1807 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
1808 else
1809 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
1811 mvwaddnstr(window, 0, 0, buf, bufpos);
1812 wclrtoeol(window);
1813 wnoutrefresh(window);
1814 }
1816 static int
1817 apply_step(double step, int value)
1818 {
1819 if (step >= 1)
1820 return (int) step;
1821 value *= step + 0.01;
1822 return value ? value : 1;
1823 }
1825 static void
1826 resize_display(void)
1827 {
1828 int offset, i;
1829 struct view *base = display[0];
1830 struct view *view = display[1] ? display[1] : display[0];
1832 /* Setup window dimensions */
1834 getmaxyx(stdscr, base->height, base->width);
1836 /* Make room for the status window. */
1837 base->height -= 1;
1839 if (view != base) {
1840 /* Horizontal split. */
1841 view->width = base->width;
1842 view->height = apply_step(opt_scale_split_view, base->height);
1843 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
1844 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
1845 base->height -= view->height;
1847 /* Make room for the title bar. */
1848 view->height -= 1;
1849 }
1851 /* Make room for the title bar. */
1852 base->height -= 1;
1854 offset = 0;
1856 foreach_displayed_view (view, i) {
1857 if (!display_win[i]) {
1858 display_win[i] = newwin(view->height, view->width, offset, 0);
1859 if (!display_win[i])
1860 die("Failed to create %s view", view->name);
1862 scrollok(display_win[i], FALSE);
1864 display_title[i] = newwin(1, view->width, offset + view->height, 0);
1865 if (!display_title[i])
1866 die("Failed to create title window");
1868 } else {
1869 wresize(display_win[i], view->height, view->width);
1870 mvwin(display_win[i], offset, 0);
1871 mvwin(display_title[i], offset + view->height, 0);
1872 }
1874 view->win = display_win[i];
1876 offset += view->height + 1;
1877 }
1878 }
1880 static void
1881 redraw_display(bool clear)
1882 {
1883 struct view *view;
1884 int i;
1886 foreach_displayed_view (view, i) {
1887 if (clear)
1888 wclear(view->win);
1889 redraw_view(view);
1890 update_view_title(view);
1891 }
1892 }
1895 /*
1896 * Option management
1897 */
1899 #define TOGGLE_MENU \
1900 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
1901 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
1902 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
1903 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
1904 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
1905 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL)
1907 static void
1908 toggle_option(enum request request)
1909 {
1910 const struct {
1911 enum request request;
1912 const struct enum_map *map;
1913 size_t map_size;
1914 } data[] = {
1915 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
1916 TOGGLE_MENU
1917 #undef TOGGLE_
1918 };
1919 const struct menu_item menu[] = {
1920 #define TOGGLE_(id, key, help, value, map) { key, help, value },
1921 TOGGLE_MENU
1922 #undef TOGGLE_
1923 { 0 }
1924 };
1925 int i = 0;
1927 if (request == REQ_OPTIONS) {
1928 if (!prompt_menu("Toggle option", menu, &i))
1929 return;
1930 } else {
1931 while (i < ARRAY_SIZE(data) && data[i].request != request)
1932 i++;
1933 if (i >= ARRAY_SIZE(data))
1934 die("Invalid request (%d)", request);
1935 }
1937 if (data[i].map != NULL) {
1938 unsigned int *opt = menu[i].data;
1940 *opt = (*opt + 1) % data[i].map_size;
1941 redraw_display(FALSE);
1942 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
1944 } else {
1945 bool *option = menu[i].data;
1947 *option = !*option;
1948 redraw_display(FALSE);
1949 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
1950 }
1951 }
1953 static void
1954 maximize_view(struct view *view)
1955 {
1956 memset(display, 0, sizeof(display));
1957 current_view = 0;
1958 display[current_view] = view;
1959 resize_display();
1960 redraw_display(FALSE);
1961 report("");
1962 }
1965 /*
1966 * Navigation
1967 */
1969 static bool
1970 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
1971 {
1972 if (lineno >= view->lines)
1973 lineno = view->lines > 0 ? view->lines - 1 : 0;
1975 if (offset > lineno || offset + view->height <= lineno) {
1976 unsigned long half = view->height / 2;
1978 if (lineno > half)
1979 offset = lineno - half;
1980 else
1981 offset = 0;
1982 }
1984 if (offset != view->offset || lineno != view->lineno) {
1985 view->offset = offset;
1986 view->lineno = lineno;
1987 return TRUE;
1988 }
1990 return FALSE;
1991 }
1993 /* Scrolling backend */
1994 static void
1995 do_scroll_view(struct view *view, int lines)
1996 {
1997 bool redraw_current_line = FALSE;
1999 /* The rendering expects the new offset. */
2000 view->offset += lines;
2002 assert(0 <= view->offset && view->offset < view->lines);
2003 assert(lines);
2005 /* Move current line into the view. */
2006 if (view->lineno < view->offset) {
2007 view->lineno = view->offset;
2008 redraw_current_line = TRUE;
2009 } else if (view->lineno >= view->offset + view->height) {
2010 view->lineno = view->offset + view->height - 1;
2011 redraw_current_line = TRUE;
2012 }
2014 assert(view->offset <= view->lineno && view->lineno < view->lines);
2016 /* Redraw the whole screen if scrolling is pointless. */
2017 if (view->height < ABS(lines)) {
2018 redraw_view(view);
2020 } else {
2021 int line = lines > 0 ? view->height - lines : 0;
2022 int end = line + ABS(lines);
2024 scrollok(view->win, TRUE);
2025 wscrl(view->win, lines);
2026 scrollok(view->win, FALSE);
2028 while (line < end && draw_view_line(view, line))
2029 line++;
2031 if (redraw_current_line)
2032 draw_view_line(view, view->lineno - view->offset);
2033 wnoutrefresh(view->win);
2034 }
2036 view->has_scrolled = TRUE;
2037 report("");
2038 }
2040 /* Scroll frontend */
2041 static void
2042 scroll_view(struct view *view, enum request request)
2043 {
2044 int lines = 1;
2046 assert(view_is_displayed(view));
2048 switch (request) {
2049 case REQ_SCROLL_FIRST_COL:
2050 view->yoffset = 0;
2051 redraw_view_from(view, 0);
2052 report("");
2053 return;
2054 case REQ_SCROLL_LEFT:
2055 if (view->yoffset == 0) {
2056 report("Cannot scroll beyond the first column");
2057 return;
2058 }
2059 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2060 view->yoffset = 0;
2061 else
2062 view->yoffset -= apply_step(opt_hscroll, view->width);
2063 redraw_view_from(view, 0);
2064 report("");
2065 return;
2066 case REQ_SCROLL_RIGHT:
2067 view->yoffset += apply_step(opt_hscroll, view->width);
2068 redraw_view(view);
2069 report("");
2070 return;
2071 case REQ_SCROLL_PAGE_DOWN:
2072 lines = view->height;
2073 case REQ_SCROLL_LINE_DOWN:
2074 if (view->offset + lines > view->lines)
2075 lines = view->lines - view->offset;
2077 if (lines == 0 || view->offset + view->height >= view->lines) {
2078 report("Cannot scroll beyond the last line");
2079 return;
2080 }
2081 break;
2083 case REQ_SCROLL_PAGE_UP:
2084 lines = view->height;
2085 case REQ_SCROLL_LINE_UP:
2086 if (lines > view->offset)
2087 lines = view->offset;
2089 if (lines == 0) {
2090 report("Cannot scroll beyond the first line");
2091 return;
2092 }
2094 lines = -lines;
2095 break;
2097 default:
2098 die("request %d not handled in switch", request);
2099 }
2101 do_scroll_view(view, lines);
2102 }
2104 /* Cursor moving */
2105 static void
2106 move_view(struct view *view, enum request request)
2107 {
2108 int scroll_steps = 0;
2109 int steps;
2111 switch (request) {
2112 case REQ_MOVE_FIRST_LINE:
2113 steps = -view->lineno;
2114 break;
2116 case REQ_MOVE_LAST_LINE:
2117 steps = view->lines - view->lineno - 1;
2118 break;
2120 case REQ_MOVE_PAGE_UP:
2121 steps = view->height > view->lineno
2122 ? -view->lineno : -view->height;
2123 break;
2125 case REQ_MOVE_PAGE_DOWN:
2126 steps = view->lineno + view->height >= view->lines
2127 ? view->lines - view->lineno - 1 : view->height;
2128 break;
2130 case REQ_MOVE_UP:
2131 steps = -1;
2132 break;
2134 case REQ_MOVE_DOWN:
2135 steps = 1;
2136 break;
2138 default:
2139 die("request %d not handled in switch", request);
2140 }
2142 if (steps <= 0 && view->lineno == 0) {
2143 report("Cannot move beyond the first line");
2144 return;
2146 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2147 report("Cannot move beyond the last line");
2148 return;
2149 }
2151 /* Move the current line */
2152 view->lineno += steps;
2153 assert(0 <= view->lineno && view->lineno < view->lines);
2155 /* Check whether the view needs to be scrolled */
2156 if (view->lineno < view->offset ||
2157 view->lineno >= view->offset + view->height) {
2158 scroll_steps = steps;
2159 if (steps < 0 && -steps > view->offset) {
2160 scroll_steps = -view->offset;
2162 } else if (steps > 0) {
2163 if (view->lineno == view->lines - 1 &&
2164 view->lines > view->height) {
2165 scroll_steps = view->lines - view->offset - 1;
2166 if (scroll_steps >= view->height)
2167 scroll_steps -= view->height - 1;
2168 }
2169 }
2170 }
2172 if (!view_is_displayed(view)) {
2173 view->offset += scroll_steps;
2174 assert(0 <= view->offset && view->offset < view->lines);
2175 view->ops->select(view, &view->line[view->lineno]);
2176 return;
2177 }
2179 /* Repaint the old "current" line if we be scrolling */
2180 if (ABS(steps) < view->height)
2181 draw_view_line(view, view->lineno - steps - view->offset);
2183 if (scroll_steps) {
2184 do_scroll_view(view, scroll_steps);
2185 return;
2186 }
2188 /* Draw the current line */
2189 draw_view_line(view, view->lineno - view->offset);
2191 wnoutrefresh(view->win);
2192 report("");
2193 }
2196 /*
2197 * Searching
2198 */
2200 static void search_view(struct view *view, enum request request);
2202 static bool
2203 grep_text(struct view *view, const char *text[])
2204 {
2205 regmatch_t pmatch;
2206 size_t i;
2208 for (i = 0; text[i]; i++)
2209 if (*text[i] &&
2210 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2211 return TRUE;
2212 return FALSE;
2213 }
2215 static void
2216 select_view_line(struct view *view, unsigned long lineno)
2217 {
2218 unsigned long old_lineno = view->lineno;
2219 unsigned long old_offset = view->offset;
2221 if (goto_view_line(view, view->offset, lineno)) {
2222 if (view_is_displayed(view)) {
2223 if (old_offset != view->offset) {
2224 redraw_view(view);
2225 } else {
2226 draw_view_line(view, old_lineno - view->offset);
2227 draw_view_line(view, view->lineno - view->offset);
2228 wnoutrefresh(view->win);
2229 }
2230 } else {
2231 view->ops->select(view, &view->line[view->lineno]);
2232 }
2233 }
2234 }
2236 static void
2237 find_next(struct view *view, enum request request)
2238 {
2239 unsigned long lineno = view->lineno;
2240 int direction;
2242 if (!*view->grep) {
2243 if (!*opt_search)
2244 report("No previous search");
2245 else
2246 search_view(view, request);
2247 return;
2248 }
2250 switch (request) {
2251 case REQ_SEARCH:
2252 case REQ_FIND_NEXT:
2253 direction = 1;
2254 break;
2256 case REQ_SEARCH_BACK:
2257 case REQ_FIND_PREV:
2258 direction = -1;
2259 break;
2261 default:
2262 return;
2263 }
2265 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2266 lineno += direction;
2268 /* Note, lineno is unsigned long so will wrap around in which case it
2269 * will become bigger than view->lines. */
2270 for (; lineno < view->lines; lineno += direction) {
2271 if (view->ops->grep(view, &view->line[lineno])) {
2272 select_view_line(view, lineno);
2273 report("Line %ld matches '%s'", lineno + 1, view->grep);
2274 return;
2275 }
2276 }
2278 report("No match found for '%s'", view->grep);
2279 }
2281 static void
2282 search_view(struct view *view, enum request request)
2283 {
2284 int regex_err;
2286 if (view->regex) {
2287 regfree(view->regex);
2288 *view->grep = 0;
2289 } else {
2290 view->regex = calloc(1, sizeof(*view->regex));
2291 if (!view->regex)
2292 return;
2293 }
2295 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2296 if (regex_err != 0) {
2297 char buf[SIZEOF_STR] = "unknown error";
2299 regerror(regex_err, view->regex, buf, sizeof(buf));
2300 report("Search failed: %s", buf);
2301 return;
2302 }
2304 string_copy(view->grep, opt_search);
2306 find_next(view, request);
2307 }
2309 /*
2310 * Incremental updating
2311 */
2313 static void
2314 reset_view(struct view *view)
2315 {
2316 int i;
2318 for (i = 0; i < view->lines; i++)
2319 free(view->line[i].data);
2320 free(view->line);
2322 view->p_offset = view->offset;
2323 view->p_yoffset = view->yoffset;
2324 view->p_lineno = view->lineno;
2326 view->line = NULL;
2327 view->offset = 0;
2328 view->yoffset = 0;
2329 view->lines = 0;
2330 view->lineno = 0;
2331 view->vid[0] = 0;
2332 view->update_secs = 0;
2333 }
2335 static const char *
2336 format_arg(const char *name)
2337 {
2338 static struct {
2339 const char *name;
2340 size_t namelen;
2341 const char *value;
2342 const char *value_if_empty;
2343 } vars[] = {
2344 #define FORMAT_VAR(name, value, value_if_empty) \
2345 { name, STRING_SIZE(name), value, value_if_empty }
2346 FORMAT_VAR("%(directory)", opt_path, "."),
2347 FORMAT_VAR("%(file)", opt_file, ""),
2348 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2349 FORMAT_VAR("%(head)", ref_head, ""),
2350 FORMAT_VAR("%(commit)", ref_commit, ""),
2351 FORMAT_VAR("%(blob)", ref_blob, ""),
2352 FORMAT_VAR("%(branch)", ref_branch, ""),
2353 };
2354 int i;
2356 for (i = 0; i < ARRAY_SIZE(vars); i++)
2357 if (!strncmp(name, vars[i].name, vars[i].namelen))
2358 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2360 report("Unknown replacement: `%s`", name);
2361 return NULL;
2362 }
2364 static bool
2365 format_argv(const char ***dst_argv, const char *src_argv[], bool replace, bool first)
2366 {
2367 char buf[SIZEOF_STR];
2368 int argc;
2370 argv_free(*dst_argv);
2372 for (argc = 0; src_argv[argc]; argc++) {
2373 const char *arg = src_argv[argc];
2374 size_t bufpos = 0;
2376 if (!strcmp(arg, "%(fileargs)")) {
2377 if (!argv_append_array(dst_argv, opt_file_argv))
2378 break;
2379 continue;
2381 } else if (!strcmp(arg, "%(diffargs)")) {
2382 if (!argv_append_array(dst_argv, opt_diff_argv))
2383 break;
2384 continue;
2386 } else if (!strcmp(arg, "%(revargs)") ||
2387 (first && !strcmp(arg, "%(commit)"))) {
2388 if (!argv_append_array(dst_argv, opt_rev_argv))
2389 break;
2390 continue;
2391 }
2393 while (arg) {
2394 char *next = strstr(arg, "%(");
2395 int len = next - arg;
2396 const char *value;
2398 if (!next || !replace) {
2399 len = strlen(arg);
2400 value = "";
2402 } else {
2403 value = format_arg(next);
2405 if (!value) {
2406 return FALSE;
2407 }
2408 }
2410 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2411 return FALSE;
2413 arg = next && replace ? strchr(next, ')') + 1 : NULL;
2414 }
2416 if (!argv_append(dst_argv, buf))
2417 break;
2418 }
2420 return src_argv[argc] == NULL;
2421 }
2423 static bool
2424 restore_view_position(struct view *view)
2425 {
2426 if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2427 return FALSE;
2429 /* Changing the view position cancels the restoring. */
2430 /* FIXME: Changing back to the first line is not detected. */
2431 if (view->offset != 0 || view->lineno != 0) {
2432 view->p_restore = FALSE;
2433 return FALSE;
2434 }
2436 if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2437 view_is_displayed(view))
2438 werase(view->win);
2440 view->yoffset = view->p_yoffset;
2441 view->p_restore = FALSE;
2443 return TRUE;
2444 }
2446 static void
2447 end_update(struct view *view, bool force)
2448 {
2449 if (!view->pipe)
2450 return;
2451 while (!view->ops->read(view, NULL))
2452 if (!force)
2453 return;
2454 if (force)
2455 io_kill(view->pipe);
2456 io_done(view->pipe);
2457 view->pipe = NULL;
2458 }
2460 static void
2461 setup_update(struct view *view, const char *vid)
2462 {
2463 reset_view(view);
2464 string_copy_rev(view->vid, vid);
2465 view->pipe = &view->io;
2466 view->start_time = time(NULL);
2467 }
2469 static bool
2470 prepare_io(struct view *view, const char *dir, const char *argv[], bool replace)
2471 {
2472 view->dir = dir;
2473 return format_argv(&view->argv, argv, replace, !view->prev);
2474 }
2476 static bool
2477 prepare_update(struct view *view, const char *argv[], const char *dir)
2478 {
2479 if (view->pipe)
2480 end_update(view, TRUE);
2481 return prepare_io(view, dir, argv, FALSE);
2482 }
2484 static bool
2485 start_update(struct view *view, const char **argv, const char *dir)
2486 {
2487 if (view->pipe)
2488 io_done(view->pipe);
2489 return prepare_io(view, dir, argv, FALSE) &&
2490 io_run(&view->io, IO_RD, dir, view->argv);
2491 }
2493 static bool
2494 prepare_update_file(struct view *view, const char *name)
2495 {
2496 if (view->pipe)
2497 end_update(view, TRUE);
2498 argv_free(view->argv);
2499 return io_open(&view->io, "%s/%s", opt_cdup[0] ? opt_cdup : ".", name);
2500 }
2502 static bool
2503 begin_update(struct view *view, bool refresh)
2504 {
2505 if (view->pipe)
2506 end_update(view, TRUE);
2508 if (!refresh) {
2509 if (view->ops->prepare) {
2510 if (!view->ops->prepare(view))
2511 return FALSE;
2512 } else if (!prepare_io(view, NULL, view->ops->argv, TRUE)) {
2513 return FALSE;
2514 }
2516 /* Put the current ref_* value to the view title ref
2517 * member. This is needed by the blob view. Most other
2518 * views sets it automatically after loading because the
2519 * first line is a commit line. */
2520 string_copy_rev(view->ref, view->id);
2521 }
2523 if (view->argv && view->argv[0] &&
2524 !io_run(&view->io, IO_RD, view->dir, view->argv))
2525 return FALSE;
2527 setup_update(view, view->id);
2529 return TRUE;
2530 }
2532 static bool
2533 update_view(struct view *view)
2534 {
2535 char out_buffer[BUFSIZ * 2];
2536 char *line;
2537 /* Clear the view and redraw everything since the tree sorting
2538 * might have rearranged things. */
2539 bool redraw = view->lines == 0;
2540 bool can_read = TRUE;
2542 if (!view->pipe)
2543 return TRUE;
2545 if (!io_can_read(view->pipe, FALSE)) {
2546 if (view->lines == 0 && view_is_displayed(view)) {
2547 time_t secs = time(NULL) - view->start_time;
2549 if (secs > 1 && secs > view->update_secs) {
2550 if (view->update_secs == 0)
2551 redraw_view(view);
2552 update_view_title(view);
2553 view->update_secs = secs;
2554 }
2555 }
2556 return TRUE;
2557 }
2559 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2560 if (opt_iconv_in != ICONV_NONE) {
2561 ICONV_CONST char *inbuf = line;
2562 size_t inlen = strlen(line) + 1;
2564 char *outbuf = out_buffer;
2565 size_t outlen = sizeof(out_buffer);
2567 size_t ret;
2569 ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2570 if (ret != (size_t) -1)
2571 line = out_buffer;
2572 }
2574 if (!view->ops->read(view, line)) {
2575 report("Allocation failure");
2576 end_update(view, TRUE);
2577 return FALSE;
2578 }
2579 }
2581 {
2582 unsigned long lines = view->lines;
2583 int digits;
2585 for (digits = 0; lines; digits++)
2586 lines /= 10;
2588 /* Keep the displayed view in sync with line number scaling. */
2589 if (digits != view->digits) {
2590 view->digits = digits;
2591 if (opt_line_number || view->type == VIEW_BLAME)
2592 redraw = TRUE;
2593 }
2594 }
2596 if (io_error(view->pipe)) {
2597 report("Failed to read: %s", io_strerror(view->pipe));
2598 end_update(view, TRUE);
2600 } else if (io_eof(view->pipe)) {
2601 if (view_is_displayed(view))
2602 report("");
2603 end_update(view, FALSE);
2604 }
2606 if (restore_view_position(view))
2607 redraw = TRUE;
2609 if (!view_is_displayed(view))
2610 return TRUE;
2612 if (redraw)
2613 redraw_view_from(view, 0);
2614 else
2615 redraw_view_dirty(view);
2617 /* Update the title _after_ the redraw so that if the redraw picks up a
2618 * commit reference in view->ref it'll be available here. */
2619 update_view_title(view);
2620 return TRUE;
2621 }
2623 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2625 static struct line *
2626 add_line_data(struct view *view, void *data, enum line_type type)
2627 {
2628 struct line *line;
2630 if (!realloc_lines(&view->line, view->lines, 1))
2631 return NULL;
2633 line = &view->line[view->lines++];
2634 memset(line, 0, sizeof(*line));
2635 line->type = type;
2636 line->data = data;
2637 line->dirty = 1;
2639 return line;
2640 }
2642 static struct line *
2643 add_line_text(struct view *view, const char *text, enum line_type type)
2644 {
2645 char *data = text ? strdup(text) : NULL;
2647 return data ? add_line_data(view, data, type) : NULL;
2648 }
2650 static struct line *
2651 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2652 {
2653 char buf[SIZEOF_STR];
2654 va_list args;
2656 va_start(args, fmt);
2657 if (vsnprintf(buf, sizeof(buf), fmt, args) >= sizeof(buf))
2658 buf[0] = 0;
2659 va_end(args);
2661 return buf[0] ? add_line_text(view, buf, type) : NULL;
2662 }
2664 /*
2665 * View opening
2666 */
2668 enum open_flags {
2669 OPEN_DEFAULT = 0, /* Use default view switching. */
2670 OPEN_SPLIT = 1, /* Split current view. */
2671 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
2672 OPEN_REFRESH = 16, /* Refresh view using previous command. */
2673 OPEN_PREPARED = 32, /* Open already prepared command. */
2674 };
2676 static void
2677 open_view(struct view *prev, enum request request, enum open_flags flags)
2678 {
2679 bool split = !!(flags & OPEN_SPLIT);
2680 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED));
2681 bool nomaximize = !!(flags & OPEN_REFRESH);
2682 struct view *view = VIEW(request);
2683 int nviews = displayed_views();
2684 struct view *base_view = display[0];
2686 if (view == prev && nviews == 1 && !reload) {
2687 report("Already in %s view", view->name);
2688 return;
2689 }
2691 if (view->git_dir && !opt_git_dir[0]) {
2692 report("The %s view is disabled in pager view", view->name);
2693 return;
2694 }
2696 if (split) {
2697 display[1] = view;
2698 current_view = 1;
2699 view->parent = prev;
2700 } else if (!nomaximize) {
2701 /* Maximize the current view. */
2702 memset(display, 0, sizeof(display));
2703 current_view = 0;
2704 display[current_view] = view;
2705 }
2707 /* No prev signals that this is the first loaded view. */
2708 if (prev && view != prev) {
2709 view->prev = prev;
2710 }
2712 /* Resize the view when switching between split- and full-screen,
2713 * or when switching between two different full-screen views. */
2714 if (nviews != displayed_views() ||
2715 (nviews == 1 && base_view != display[0]))
2716 resize_display();
2718 if (view->ops->open) {
2719 if (view->pipe)
2720 end_update(view, TRUE);
2721 if (!view->ops->open(view)) {
2722 report("Failed to load %s view", view->name);
2723 return;
2724 }
2725 restore_view_position(view);
2727 } else if ((reload || strcmp(view->vid, view->id)) &&
2728 !begin_update(view, flags & (OPEN_REFRESH | OPEN_PREPARED))) {
2729 report("Failed to load %s view", view->name);
2730 return;
2731 }
2733 if (split && prev->lineno - prev->offset >= prev->height) {
2734 /* Take the title line into account. */
2735 int lines = prev->lineno - prev->offset - prev->height + 1;
2737 /* Scroll the view that was split if the current line is
2738 * outside the new limited view. */
2739 do_scroll_view(prev, lines);
2740 }
2742 if (prev && view != prev && split && view_is_displayed(prev)) {
2743 /* "Blur" the previous view. */
2744 update_view_title(prev);
2745 }
2747 if (view->pipe && view->lines == 0) {
2748 /* Clear the old view and let the incremental updating refill
2749 * the screen. */
2750 werase(view->win);
2751 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2752 report("");
2753 } else if (view_is_displayed(view)) {
2754 redraw_view(view);
2755 report("");
2756 }
2757 }
2759 static void
2760 open_external_viewer(const char *argv[], const char *dir)
2761 {
2762 def_prog_mode(); /* save current tty modes */
2763 endwin(); /* restore original tty modes */
2764 io_run_fg(argv, dir);
2765 fprintf(stderr, "Press Enter to continue");
2766 getc(opt_tty);
2767 reset_prog_mode();
2768 redraw_display(TRUE);
2769 }
2771 static void
2772 open_mergetool(const char *file)
2773 {
2774 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2776 open_external_viewer(mergetool_argv, opt_cdup);
2777 }
2779 static void
2780 open_editor(const char *file)
2781 {
2782 const char *editor_argv[] = { "vi", file, NULL };
2783 const char *editor;
2785 editor = getenv("GIT_EDITOR");
2786 if (!editor && *opt_editor)
2787 editor = opt_editor;
2788 if (!editor)
2789 editor = getenv("VISUAL");
2790 if (!editor)
2791 editor = getenv("EDITOR");
2792 if (!editor)
2793 editor = "vi";
2795 editor_argv[0] = editor;
2796 open_external_viewer(editor_argv, opt_cdup);
2797 }
2799 static void
2800 open_run_request(enum request request)
2801 {
2802 struct run_request *req = get_run_request(request);
2803 const char **argv = NULL;
2805 if (!req) {
2806 report("Unknown run request");
2807 return;
2808 }
2810 if (format_argv(&argv, req->argv, TRUE, FALSE))
2811 open_external_viewer(argv, NULL);
2812 if (argv)
2813 argv_free(argv);
2814 free(argv);
2815 }
2817 /*
2818 * User request switch noodle
2819 */
2821 static int
2822 view_driver(struct view *view, enum request request)
2823 {
2824 int i;
2826 if (request == REQ_NONE)
2827 return TRUE;
2829 if (request > REQ_NONE) {
2830 open_run_request(request);
2831 view_request(view, REQ_REFRESH);
2832 return TRUE;
2833 }
2835 request = view_request(view, request);
2836 if (request == REQ_NONE)
2837 return TRUE;
2839 switch (request) {
2840 case REQ_MOVE_UP:
2841 case REQ_MOVE_DOWN:
2842 case REQ_MOVE_PAGE_UP:
2843 case REQ_MOVE_PAGE_DOWN:
2844 case REQ_MOVE_FIRST_LINE:
2845 case REQ_MOVE_LAST_LINE:
2846 move_view(view, request);
2847 break;
2849 case REQ_SCROLL_FIRST_COL:
2850 case REQ_SCROLL_LEFT:
2851 case REQ_SCROLL_RIGHT:
2852 case REQ_SCROLL_LINE_DOWN:
2853 case REQ_SCROLL_LINE_UP:
2854 case REQ_SCROLL_PAGE_DOWN:
2855 case REQ_SCROLL_PAGE_UP:
2856 scroll_view(view, request);
2857 break;
2859 case REQ_VIEW_BLAME:
2860 if (!opt_file[0]) {
2861 report("No file chosen, press %s to open tree view",
2862 get_key(view->keymap, REQ_VIEW_TREE));
2863 break;
2864 }
2865 open_view(view, request, OPEN_DEFAULT);
2866 break;
2868 case REQ_VIEW_BLOB:
2869 if (!ref_blob[0]) {
2870 report("No file chosen, press %s to open tree view",
2871 get_key(view->keymap, REQ_VIEW_TREE));
2872 break;
2873 }
2874 open_view(view, request, OPEN_DEFAULT);
2875 break;
2877 case REQ_VIEW_PAGER:
2878 if (view == NULL) {
2879 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
2880 die("Failed to open stdin");
2881 open_view(view, request, OPEN_PREPARED);
2882 break;
2883 }
2885 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
2886 report("No pager content, press %s to run command from prompt",
2887 get_key(view->keymap, REQ_PROMPT));
2888 break;
2889 }
2890 open_view(view, request, OPEN_DEFAULT);
2891 break;
2893 case REQ_VIEW_STAGE:
2894 if (!VIEW(REQ_VIEW_STAGE)->lines) {
2895 report("No stage content, press %s to open the status view and choose file",
2896 get_key(view->keymap, REQ_VIEW_STATUS));
2897 break;
2898 }
2899 open_view(view, request, OPEN_DEFAULT);
2900 break;
2902 case REQ_VIEW_STATUS:
2903 if (opt_is_inside_work_tree == FALSE) {
2904 report("The status view requires a working tree");
2905 break;
2906 }
2907 open_view(view, request, OPEN_DEFAULT);
2908 break;
2910 case REQ_VIEW_MAIN:
2911 case REQ_VIEW_DIFF:
2912 case REQ_VIEW_LOG:
2913 case REQ_VIEW_TREE:
2914 case REQ_VIEW_HELP:
2915 case REQ_VIEW_BRANCH:
2916 open_view(view, request, OPEN_DEFAULT);
2917 break;
2919 case REQ_NEXT:
2920 case REQ_PREVIOUS:
2921 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
2923 if (view->parent) {
2924 int line;
2926 view = view->parent;
2927 line = view->lineno;
2928 move_view(view, request);
2929 if (view_is_displayed(view))
2930 update_view_title(view);
2931 if (line != view->lineno)
2932 view_request(view, REQ_ENTER);
2933 } else {
2934 move_view(view, request);
2935 }
2936 break;
2938 case REQ_VIEW_NEXT:
2939 {
2940 int nviews = displayed_views();
2941 int next_view = (current_view + 1) % nviews;
2943 if (next_view == current_view) {
2944 report("Only one view is displayed");
2945 break;
2946 }
2948 current_view = next_view;
2949 /* Blur out the title of the previous view. */
2950 update_view_title(view);
2951 report("");
2952 break;
2953 }
2954 case REQ_REFRESH:
2955 report("Refreshing is not yet supported for the %s view", view->name);
2956 break;
2958 case REQ_MAXIMIZE:
2959 if (displayed_views() == 2)
2960 maximize_view(view);
2961 break;
2963 case REQ_OPTIONS:
2964 case REQ_TOGGLE_LINENO:
2965 case REQ_TOGGLE_DATE:
2966 case REQ_TOGGLE_AUTHOR:
2967 case REQ_TOGGLE_GRAPHIC:
2968 case REQ_TOGGLE_REV_GRAPH:
2969 case REQ_TOGGLE_REFS:
2970 toggle_option(request);
2971 break;
2973 case REQ_TOGGLE_SORT_FIELD:
2974 case REQ_TOGGLE_SORT_ORDER:
2975 report("Sorting is not yet supported for the %s view", view->name);
2976 break;
2978 case REQ_SEARCH:
2979 case REQ_SEARCH_BACK:
2980 search_view(view, request);
2981 break;
2983 case REQ_FIND_NEXT:
2984 case REQ_FIND_PREV:
2985 find_next(view, request);
2986 break;
2988 case REQ_STOP_LOADING:
2989 foreach_view(view, i) {
2990 if (view->pipe)
2991 report("Stopped loading the %s view", view->name),
2992 end_update(view, TRUE);
2993 }
2994 break;
2996 case REQ_SHOW_VERSION:
2997 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
2998 return TRUE;
3000 case REQ_SCREEN_REDRAW:
3001 redraw_display(TRUE);
3002 break;
3004 case REQ_EDIT:
3005 report("Nothing to edit");
3006 break;
3008 case REQ_ENTER:
3009 report("Nothing to enter");
3010 break;
3012 case REQ_VIEW_CLOSE:
3013 /* XXX: Mark closed views by letting view->prev point to the
3014 * view itself. Parents to closed view should never be
3015 * followed. */
3016 if (view->prev && view->prev != view) {
3017 maximize_view(view->prev);
3018 view->prev = view;
3019 break;
3020 }
3021 /* Fall-through */
3022 case REQ_QUIT:
3023 return FALSE;
3025 default:
3026 report("Unknown key, press %s for help",
3027 get_key(view->keymap, REQ_VIEW_HELP));
3028 return TRUE;
3029 }
3031 return TRUE;
3032 }
3035 /*
3036 * View backend utilities
3037 */
3039 enum sort_field {
3040 ORDERBY_NAME,
3041 ORDERBY_DATE,
3042 ORDERBY_AUTHOR,
3043 };
3045 struct sort_state {
3046 const enum sort_field *fields;
3047 size_t size, current;
3048 bool reverse;
3049 };
3051 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3052 #define get_sort_field(state) ((state).fields[(state).current])
3053 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3055 static void
3056 sort_view(struct view *view, enum request request, struct sort_state *state,
3057 int (*compare)(const void *, const void *))
3058 {
3059 switch (request) {
3060 case REQ_TOGGLE_SORT_FIELD:
3061 state->current = (state->current + 1) % state->size;
3062 break;
3064 case REQ_TOGGLE_SORT_ORDER:
3065 state->reverse = !state->reverse;
3066 break;
3067 default:
3068 die("Not a sort request");
3069 }
3071 qsort(view->line, view->lines, sizeof(*view->line), compare);
3072 redraw_view(view);
3073 }
3075 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3077 /* Small author cache to reduce memory consumption. It uses binary
3078 * search to lookup or find place to position new entries. No entries
3079 * are ever freed. */
3080 static const char *
3081 get_author(const char *name)
3082 {
3083 static const char **authors;
3084 static size_t authors_size;
3085 int from = 0, to = authors_size - 1;
3087 while (from <= to) {
3088 size_t pos = (to + from) / 2;
3089 int cmp = strcmp(name, authors[pos]);
3091 if (!cmp)
3092 return authors[pos];
3094 if (cmp < 0)
3095 to = pos - 1;
3096 else
3097 from = pos + 1;
3098 }
3100 if (!realloc_authors(&authors, authors_size, 1))
3101 return NULL;
3102 name = strdup(name);
3103 if (!name)
3104 return NULL;
3106 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3107 authors[from] = name;
3108 authors_size++;
3110 return name;
3111 }
3113 static void
3114 parse_timesec(struct time *time, const char *sec)
3115 {
3116 time->sec = (time_t) atol(sec);
3117 }
3119 static void
3120 parse_timezone(struct time *time, const char *zone)
3121 {
3122 long tz;
3124 tz = ('0' - zone[1]) * 60 * 60 * 10;
3125 tz += ('0' - zone[2]) * 60 * 60;
3126 tz += ('0' - zone[3]) * 60 * 10;
3127 tz += ('0' - zone[4]) * 60;
3129 if (zone[0] == '-')
3130 tz = -tz;
3132 time->tz = tz;
3133 time->sec -= tz;
3134 }
3136 /* Parse author lines where the name may be empty:
3137 * author <email@address.tld> 1138474660 +0100
3138 */
3139 static void
3140 parse_author_line(char *ident, const char **author, struct time *time)
3141 {
3142 char *nameend = strchr(ident, '<');
3143 char *emailend = strchr(ident, '>');
3145 if (nameend && emailend)
3146 *nameend = *emailend = 0;
3147 ident = chomp_string(ident);
3148 if (!*ident) {
3149 if (nameend)
3150 ident = chomp_string(nameend + 1);
3151 if (!*ident)
3152 ident = "Unknown";
3153 }
3155 *author = get_author(ident);
3157 /* Parse epoch and timezone */
3158 if (emailend && emailend[1] == ' ') {
3159 char *secs = emailend + 2;
3160 char *zone = strchr(secs, ' ');
3162 parse_timesec(time, secs);
3164 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3165 parse_timezone(time, zone + 1);
3166 }
3167 }
3169 /*
3170 * Pager backend
3171 */
3173 static bool
3174 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3175 {
3176 if (opt_line_number && draw_lineno(view, lineno))
3177 return TRUE;
3179 draw_text(view, line->type, line->data);
3180 return TRUE;
3181 }
3183 static bool
3184 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3185 {
3186 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3187 char ref[SIZEOF_STR];
3189 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3190 return TRUE;
3192 /* This is the only fatal call, since it can "corrupt" the buffer. */
3193 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3194 return FALSE;
3196 return TRUE;
3197 }
3199 static void
3200 add_pager_refs(struct view *view, struct line *line)
3201 {
3202 char buf[SIZEOF_STR];
3203 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3204 struct ref_list *list;
3205 size_t bufpos = 0, i;
3206 const char *sep = "Refs: ";
3207 bool is_tag = FALSE;
3209 assert(line->type == LINE_COMMIT);
3211 list = get_ref_list(commit_id);
3212 if (!list) {
3213 if (view->type == VIEW_DIFF)
3214 goto try_add_describe_ref;
3215 return;
3216 }
3218 for (i = 0; i < list->size; i++) {
3219 struct ref *ref = list->refs[i];
3220 const char *fmt = ref->tag ? "%s[%s]" :
3221 ref->remote ? "%s<%s>" : "%s%s";
3223 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3224 return;
3225 sep = ", ";
3226 if (ref->tag)
3227 is_tag = TRUE;
3228 }
3230 if (!is_tag && view->type == VIEW_DIFF) {
3231 try_add_describe_ref:
3232 /* Add <tag>-g<commit_id> "fake" reference. */
3233 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3234 return;
3235 }
3237 if (bufpos == 0)
3238 return;
3240 add_line_text(view, buf, LINE_PP_REFS);
3241 }
3243 static bool
3244 pager_read(struct view *view, char *data)
3245 {
3246 struct line *line;
3248 if (!data)
3249 return TRUE;
3251 line = add_line_text(view, data, get_line_type(data));
3252 if (!line)
3253 return FALSE;
3255 if (line->type == LINE_COMMIT &&
3256 (view->type == VIEW_DIFF ||
3257 view->type == VIEW_LOG))
3258 add_pager_refs(view, line);
3260 return TRUE;
3261 }
3263 static enum request
3264 pager_request(struct view *view, enum request request, struct line *line)
3265 {
3266 int split = 0;
3268 if (request != REQ_ENTER)
3269 return request;
3271 if (line->type == LINE_COMMIT &&
3272 (view->type == VIEW_LOG ||
3273 view->type == VIEW_PAGER)) {
3274 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3275 split = 1;
3276 }
3278 /* Always scroll the view even if it was split. That way
3279 * you can use Enter to scroll through the log view and
3280 * split open each commit diff. */
3281 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3283 /* FIXME: A minor workaround. Scrolling the view will call report("")
3284 * but if we are scrolling a non-current view this won't properly
3285 * update the view title. */
3286 if (split)
3287 update_view_title(view);
3289 return REQ_NONE;
3290 }
3292 static bool
3293 pager_grep(struct view *view, struct line *line)
3294 {
3295 const char *text[] = { line->data, NULL };
3297 return grep_text(view, text);
3298 }
3300 static void
3301 pager_select(struct view *view, struct line *line)
3302 {
3303 if (line->type == LINE_COMMIT) {
3304 char *text = (char *)line->data + STRING_SIZE("commit ");
3306 if (view->type != VIEW_PAGER)
3307 string_copy_rev(view->ref, text);
3308 string_copy_rev(ref_commit, text);
3309 }
3310 }
3312 static struct view_ops pager_ops = {
3313 "line",
3314 NULL,
3315 NULL,
3316 pager_read,
3317 pager_draw,
3318 pager_request,
3319 pager_grep,
3320 pager_select,
3321 };
3323 static const char *log_argv[SIZEOF_ARG] = {
3324 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3325 };
3327 static enum request
3328 log_request(struct view *view, enum request request, struct line *line)
3329 {
3330 switch (request) {
3331 case REQ_REFRESH:
3332 load_refs();
3333 open_view(view, REQ_VIEW_LOG, OPEN_REFRESH);
3334 return REQ_NONE;
3335 default:
3336 return pager_request(view, request, line);
3337 }
3338 }
3340 static struct view_ops log_ops = {
3341 "line",
3342 log_argv,
3343 NULL,
3344 pager_read,
3345 pager_draw,
3346 log_request,
3347 pager_grep,
3348 pager_select,
3349 };
3351 static const char *diff_argv[SIZEOF_ARG] = {
3352 "git", "show", "--pretty=fuller", "--no-color", "--root",
3353 "--patch-with-stat", "--find-copies-harder", "-C",
3354 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3355 };
3357 static bool
3358 diff_read(struct view *view, char *data)
3359 {
3360 if (!data) {
3361 /* Fall back to retry if no diff will be shown. */
3362 if (view->lines == 0 && opt_file_argv) {
3363 int pos = argv_size(view->argv)
3364 - argv_size(opt_file_argv) - 1;
3366 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3367 for (; view->argv[pos]; pos++) {
3368 free((void *) view->argv[pos]);
3369 view->argv[pos] = NULL;
3370 }
3372 if (view->pipe)
3373 io_done(view->pipe);
3374 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3375 return FALSE;
3376 }
3377 }
3378 return TRUE;
3379 }
3381 return pager_read(view, data);
3382 }
3384 static struct view_ops diff_ops = {
3385 "line",
3386 diff_argv,
3387 NULL,
3388 diff_read,
3389 pager_draw,
3390 pager_request,
3391 pager_grep,
3392 pager_select,
3393 };
3395 /*
3396 * Help backend
3397 */
3399 static bool help_keymap_hidden[ARRAY_SIZE(keymap_table)];
3401 static bool
3402 help_open_keymap_title(struct view *view, enum keymap keymap)
3403 {
3404 struct line *line;
3406 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
3407 help_keymap_hidden[keymap] ? '+' : '-',
3408 enum_name(keymap_table[keymap]));
3409 if (line)
3410 line->other = keymap;
3412 return help_keymap_hidden[keymap];
3413 }
3415 static void
3416 help_open_keymap(struct view *view, enum keymap keymap)
3417 {
3418 const char *group = NULL;
3419 char buf[SIZEOF_STR];
3420 size_t bufpos;
3421 bool add_title = TRUE;
3422 int i;
3424 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
3425 const char *key = NULL;
3427 if (req_info[i].request == REQ_NONE)
3428 continue;
3430 if (!req_info[i].request) {
3431 group = req_info[i].help;
3432 continue;
3433 }
3435 key = get_keys(keymap, req_info[i].request, TRUE);
3436 if (!key || !*key)
3437 continue;
3439 if (add_title && help_open_keymap_title(view, keymap))
3440 return;
3441 add_title = FALSE;
3443 if (group) {
3444 add_line_text(view, group, LINE_HELP_GROUP);
3445 group = NULL;
3446 }
3448 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
3449 enum_name(req_info[i]), req_info[i].help);
3450 }
3452 group = "External commands:";
3454 for (i = 0; i < run_requests; i++) {
3455 struct run_request *req = get_run_request(REQ_NONE + i + 1);
3456 const char *key;
3457 int argc;
3459 if (!req || req->keymap != keymap)
3460 continue;
3462 key = get_key_name(req->key);
3463 if (!*key)
3464 key = "(no key defined)";
3466 if (add_title && help_open_keymap_title(view, keymap))
3467 return;
3468 if (group) {
3469 add_line_text(view, group, LINE_HELP_GROUP);
3470 group = NULL;
3471 }
3473 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
3474 if (!string_format_from(buf, &bufpos, "%s%s",
3475 argc ? " " : "", req->argv[argc]))
3476 return;
3478 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
3479 }
3480 }
3482 static bool
3483 help_open(struct view *view)
3484 {
3485 enum keymap keymap;
3487 reset_view(view);
3488 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
3489 add_line_text(view, "", LINE_DEFAULT);
3491 for (keymap = 0; keymap < ARRAY_SIZE(keymap_table); keymap++)
3492 help_open_keymap(view, keymap);
3494 return TRUE;
3495 }
3497 static enum request
3498 help_request(struct view *view, enum request request, struct line *line)
3499 {
3500 switch (request) {
3501 case REQ_ENTER:
3502 if (line->type == LINE_HELP_KEYMAP) {
3503 help_keymap_hidden[line->other] =
3504 !help_keymap_hidden[line->other];
3505 view->p_restore = TRUE;
3506 open_view(view, REQ_VIEW_HELP, OPEN_REFRESH);
3507 }
3509 return REQ_NONE;
3510 default:
3511 return pager_request(view, request, line);
3512 }
3513 }
3515 static struct view_ops help_ops = {
3516 "line",
3517 NULL,
3518 help_open,
3519 NULL,
3520 pager_draw,
3521 help_request,
3522 pager_grep,
3523 pager_select,
3524 };
3527 /*
3528 * Tree backend
3529 */
3531 struct tree_stack_entry {
3532 struct tree_stack_entry *prev; /* Entry below this in the stack */
3533 unsigned long lineno; /* Line number to restore */
3534 char *name; /* Position of name in opt_path */
3535 };
3537 /* The top of the path stack. */
3538 static struct tree_stack_entry *tree_stack = NULL;
3539 unsigned long tree_lineno = 0;
3541 static void
3542 pop_tree_stack_entry(void)
3543 {
3544 struct tree_stack_entry *entry = tree_stack;
3546 tree_lineno = entry->lineno;
3547 entry->name[0] = 0;
3548 tree_stack = entry->prev;
3549 free(entry);
3550 }
3552 static void
3553 push_tree_stack_entry(const char *name, unsigned long lineno)
3554 {
3555 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
3556 size_t pathlen = strlen(opt_path);
3558 if (!entry)
3559 return;
3561 entry->prev = tree_stack;
3562 entry->name = opt_path + pathlen;
3563 tree_stack = entry;
3565 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
3566 pop_tree_stack_entry();
3567 return;
3568 }
3570 /* Move the current line to the first tree entry. */
3571 tree_lineno = 1;
3572 entry->lineno = lineno;
3573 }
3575 /* Parse output from git-ls-tree(1):
3576 *
3577 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
3578 */
3580 #define SIZEOF_TREE_ATTR \
3581 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
3583 #define SIZEOF_TREE_MODE \
3584 STRING_SIZE("100644 ")
3586 #define TREE_ID_OFFSET \
3587 STRING_SIZE("100644 blob ")
3589 struct tree_entry {
3590 char id[SIZEOF_REV];
3591 mode_t mode;
3592 struct time time; /* Date from the author ident. */
3593 const char *author; /* Author of the commit. */
3594 char name[1];
3595 };
3597 static const char *
3598 tree_path(const struct line *line)
3599 {
3600 return ((struct tree_entry *) line->data)->name;
3601 }
3603 static int
3604 tree_compare_entry(const struct line *line1, const struct line *line2)
3605 {
3606 if (line1->type != line2->type)
3607 return line1->type == LINE_TREE_DIR ? -1 : 1;
3608 return strcmp(tree_path(line1), tree_path(line2));
3609 }
3611 static const enum sort_field tree_sort_fields[] = {
3612 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
3613 };
3614 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
3616 static int
3617 tree_compare(const void *l1, const void *l2)
3618 {
3619 const struct line *line1 = (const struct line *) l1;
3620 const struct line *line2 = (const struct line *) l2;
3621 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
3622 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
3624 if (line1->type == LINE_TREE_HEAD)
3625 return -1;
3626 if (line2->type == LINE_TREE_HEAD)
3627 return 1;
3629 switch (get_sort_field(tree_sort_state)) {
3630 case ORDERBY_DATE:
3631 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
3633 case ORDERBY_AUTHOR:
3634 return sort_order(tree_sort_state, strcmp(entry1->author, entry2->author));
3636 case ORDERBY_NAME:
3637 default:
3638 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
3639 }
3640 }
3643 static struct line *
3644 tree_entry(struct view *view, enum line_type type, const char *path,
3645 const char *mode, const char *id)
3646 {
3647 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
3648 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
3650 if (!entry || !line) {
3651 free(entry);
3652 return NULL;
3653 }
3655 strncpy(entry->name, path, strlen(path));
3656 if (mode)
3657 entry->mode = strtoul(mode, NULL, 8);
3658 if (id)
3659 string_copy_rev(entry->id, id);
3661 return line;
3662 }
3664 static bool
3665 tree_read_date(struct view *view, char *text, bool *read_date)
3666 {
3667 static const char *author_name;
3668 static struct time author_time;
3670 if (!text && *read_date) {
3671 *read_date = FALSE;
3672 return TRUE;
3674 } else if (!text) {
3675 char *path = *opt_path ? opt_path : ".";
3676 /* Find next entry to process */
3677 const char *log_file[] = {
3678 "git", "log", "--no-color", "--pretty=raw",
3679 "--cc", "--raw", view->id, "--", path, NULL
3680 };
3682 if (!view->lines) {
3683 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
3684 report("Tree is empty");
3685 return TRUE;
3686 }
3688 if (!start_update(view, log_file, opt_cdup)) {
3689 report("Failed to load tree data");
3690 return TRUE;
3691 }
3693 *read_date = TRUE;
3694 return FALSE;
3696 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
3697 parse_author_line(text + STRING_SIZE("author "),
3698 &author_name, &author_time);
3700 } else if (*text == ':') {
3701 char *pos;
3702 size_t annotated = 1;
3703 size_t i;
3705 pos = strchr(text, '\t');
3706 if (!pos)
3707 return TRUE;
3708 text = pos + 1;
3709 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
3710 text += strlen(opt_path);
3711 pos = strchr(text, '/');
3712 if (pos)
3713 *pos = 0;
3715 for (i = 1; i < view->lines; i++) {
3716 struct line *line = &view->line[i];
3717 struct tree_entry *entry = line->data;
3719 annotated += !!entry->author;
3720 if (entry->author || strcmp(entry->name, text))
3721 continue;
3723 entry->author = author_name;
3724 entry->time = author_time;
3725 line->dirty = 1;
3726 break;
3727 }
3729 if (annotated == view->lines)
3730 io_kill(view->pipe);
3731 }
3732 return TRUE;
3733 }
3735 static bool
3736 tree_read(struct view *view, char *text)
3737 {
3738 static bool read_date = FALSE;
3739 struct tree_entry *data;
3740 struct line *entry, *line;
3741 enum line_type type;
3742 size_t textlen = text ? strlen(text) : 0;
3743 char *path = text + SIZEOF_TREE_ATTR;
3745 if (read_date || !text)
3746 return tree_read_date(view, text, &read_date);
3748 if (textlen <= SIZEOF_TREE_ATTR)
3749 return FALSE;
3750 if (view->lines == 0 &&
3751 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
3752 return FALSE;
3754 /* Strip the path part ... */
3755 if (*opt_path) {
3756 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
3757 size_t striplen = strlen(opt_path);
3759 if (pathlen > striplen)
3760 memmove(path, path + striplen,
3761 pathlen - striplen + 1);
3763 /* Insert "link" to parent directory. */
3764 if (view->lines == 1 &&
3765 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
3766 return FALSE;
3767 }
3769 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
3770 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
3771 if (!entry)
3772 return FALSE;
3773 data = entry->data;
3775 /* Skip "Directory ..." and ".." line. */
3776 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
3777 if (tree_compare_entry(line, entry) <= 0)
3778 continue;
3780 memmove(line + 1, line, (entry - line) * sizeof(*entry));
3782 line->data = data;
3783 line->type = type;
3784 for (; line <= entry; line++)
3785 line->dirty = line->cleareol = 1;
3786 return TRUE;
3787 }
3789 if (tree_lineno > view->lineno) {
3790 view->lineno = tree_lineno;
3791 tree_lineno = 0;
3792 }
3794 return TRUE;
3795 }
3797 static bool
3798 tree_draw(struct view *view, struct line *line, unsigned int lineno)
3799 {
3800 struct tree_entry *entry = line->data;
3802 if (line->type == LINE_TREE_HEAD) {
3803 if (draw_text(view, line->type, "Directory path /"))
3804 return TRUE;
3805 } else {
3806 if (draw_mode(view, entry->mode))
3807 return TRUE;
3809 if (opt_author && draw_author(view, entry->author))
3810 return TRUE;
3812 if (opt_date && draw_date(view, &entry->time))
3813 return TRUE;
3814 }
3816 draw_text(view, line->type, entry->name);
3817 return TRUE;
3818 }
3820 static void
3821 open_blob_editor(const char *id)
3822 {
3823 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
3824 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
3825 int fd = mkstemp(file);
3827 if (fd == -1)
3828 report("Failed to create temporary file");
3829 else if (!io_run_append(blob_argv, fd))
3830 report("Failed to save blob data to file");
3831 else
3832 open_editor(file);
3833 if (fd != -1)
3834 unlink(file);
3835 }
3837 static enum request
3838 tree_request(struct view *view, enum request request, struct line *line)
3839 {
3840 enum open_flags flags;
3841 struct tree_entry *entry = line->data;
3843 switch (request) {
3844 case REQ_VIEW_BLAME:
3845 if (line->type != LINE_TREE_FILE) {
3846 report("Blame only supported for files");
3847 return REQ_NONE;
3848 }
3850 string_copy(opt_ref, view->vid);
3851 return request;
3853 case REQ_EDIT:
3854 if (line->type != LINE_TREE_FILE) {
3855 report("Edit only supported for files");
3856 } else if (!is_head_commit(view->vid)) {
3857 open_blob_editor(entry->id);
3858 } else {
3859 open_editor(opt_file);
3860 }
3861 return REQ_NONE;
3863 case REQ_TOGGLE_SORT_FIELD:
3864 case REQ_TOGGLE_SORT_ORDER:
3865 sort_view(view, request, &tree_sort_state, tree_compare);
3866 return REQ_NONE;
3868 case REQ_PARENT:
3869 if (!*opt_path) {
3870 /* quit view if at top of tree */
3871 return REQ_VIEW_CLOSE;
3872 }
3873 /* fake 'cd ..' */
3874 line = &view->line[1];
3875 break;
3877 case REQ_ENTER:
3878 break;
3880 default:
3881 return request;
3882 }
3884 /* Cleanup the stack if the tree view is at a different tree. */
3885 while (!*opt_path && tree_stack)
3886 pop_tree_stack_entry();
3888 switch (line->type) {
3889 case LINE_TREE_DIR:
3890 /* Depending on whether it is a subdirectory or parent link
3891 * mangle the path buffer. */
3892 if (line == &view->line[1] && *opt_path) {
3893 pop_tree_stack_entry();
3895 } else {
3896 const char *basename = tree_path(line);
3898 push_tree_stack_entry(basename, view->lineno);
3899 }
3901 /* Trees and subtrees share the same ID, so they are not not
3902 * unique like blobs. */
3903 flags = OPEN_RELOAD;
3904 request = REQ_VIEW_TREE;
3905 break;
3907 case LINE_TREE_FILE:
3908 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
3909 request = REQ_VIEW_BLOB;
3910 break;
3912 default:
3913 return REQ_NONE;
3914 }
3916 open_view(view, request, flags);
3917 if (request == REQ_VIEW_TREE)
3918 view->lineno = tree_lineno;
3920 return REQ_NONE;
3921 }
3923 static bool
3924 tree_grep(struct view *view, struct line *line)
3925 {
3926 struct tree_entry *entry = line->data;
3927 const char *text[] = {
3928 entry->name,
3929 opt_author ? entry->author : "",
3930 mkdate(&entry->time, opt_date),
3931 NULL
3932 };
3934 return grep_text(view, text);
3935 }
3937 static void
3938 tree_select(struct view *view, struct line *line)
3939 {
3940 struct tree_entry *entry = line->data;
3942 if (line->type == LINE_TREE_FILE) {
3943 string_copy_rev(ref_blob, entry->id);
3944 string_format(opt_file, "%s%s", opt_path, tree_path(line));
3946 } else if (line->type != LINE_TREE_DIR) {
3947 return;
3948 }
3950 string_copy_rev(view->ref, entry->id);
3951 }
3953 static bool
3954 tree_prepare(struct view *view)
3955 {
3956 if (view->lines == 0 && opt_prefix[0]) {
3957 char *pos = opt_prefix;
3959 while (pos && *pos) {
3960 char *end = strchr(pos, '/');
3962 if (end)
3963 *end = 0;
3964 push_tree_stack_entry(pos, 0);
3965 pos = end;
3966 if (end) {
3967 *end = '/';
3968 pos++;
3969 }
3970 }
3972 } else if (strcmp(view->vid, view->id)) {
3973 opt_path[0] = 0;
3974 }
3976 return prepare_io(view, opt_cdup, view->ops->argv, TRUE);
3977 }
3979 static const char *tree_argv[SIZEOF_ARG] = {
3980 "git", "ls-tree", "%(commit)", "%(directory)", NULL
3981 };
3983 static struct view_ops tree_ops = {
3984 "file",
3985 tree_argv,
3986 NULL,
3987 tree_read,
3988 tree_draw,
3989 tree_request,
3990 tree_grep,
3991 tree_select,
3992 tree_prepare,
3993 };
3995 static bool
3996 blob_read(struct view *view, char *line)
3997 {
3998 if (!line)
3999 return TRUE;
4000 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4001 }
4003 static enum request
4004 blob_request(struct view *view, enum request request, struct line *line)
4005 {
4006 switch (request) {
4007 case REQ_EDIT:
4008 open_blob_editor(view->vid);
4009 return REQ_NONE;
4010 default:
4011 return pager_request(view, request, line);
4012 }
4013 }
4015 static const char *blob_argv[SIZEOF_ARG] = {
4016 "git", "cat-file", "blob", "%(blob)", NULL
4017 };
4019 static struct view_ops blob_ops = {
4020 "line",
4021 blob_argv,
4022 NULL,
4023 blob_read,
4024 pager_draw,
4025 blob_request,
4026 pager_grep,
4027 pager_select,
4028 };
4030 /*
4031 * Blame backend
4032 *
4033 * Loading the blame view is a two phase job:
4034 *
4035 * 1. File content is read either using opt_file from the
4036 * filesystem or using git-cat-file.
4037 * 2. Then blame information is incrementally added by
4038 * reading output from git-blame.
4039 */
4041 struct blame_commit {
4042 char id[SIZEOF_REV]; /* SHA1 ID. */
4043 char title[128]; /* First line of the commit message. */
4044 const char *author; /* Author of the commit. */
4045 struct time time; /* Date from the author ident. */
4046 char filename[128]; /* Name of file. */
4047 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
4048 char parent_filename[128]; /* Parent/previous name of file. */
4049 };
4051 struct blame {
4052 struct blame_commit *commit;
4053 unsigned long lineno;
4054 char text[1];
4055 };
4057 static bool
4058 blame_open(struct view *view)
4059 {
4060 char path[SIZEOF_STR];
4061 size_t i;
4063 if (!view->prev && *opt_prefix) {
4064 string_copy(path, opt_file);
4065 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4066 return FALSE;
4067 }
4069 if (*opt_ref || !io_open(&view->io, "%s%s", opt_cdup, opt_file)) {
4070 const char *blame_cat_file_argv[] = {
4071 "git", "cat-file", "blob", path, NULL
4072 };
4074 if (!string_format(path, "%s:%s", opt_ref, opt_file) ||
4075 !start_update(view, blame_cat_file_argv, opt_cdup))
4076 return FALSE;
4077 }
4079 /* First pass: remove multiple references to the same commit. */
4080 for (i = 0; i < view->lines; i++) {
4081 struct blame *blame = view->line[i].data;
4083 if (blame->commit && blame->commit->id[0])
4084 blame->commit->id[0] = 0;
4085 else
4086 blame->commit = NULL;
4087 }
4089 /* Second pass: free existing references. */
4090 for (i = 0; i < view->lines; i++) {
4091 struct blame *blame = view->line[i].data;
4093 if (blame->commit)
4094 free(blame->commit);
4095 }
4097 setup_update(view, opt_file);
4098 string_format(view->ref, "%s ...", opt_file);
4100 return TRUE;
4101 }
4103 static struct blame_commit *
4104 get_blame_commit(struct view *view, const char *id)
4105 {
4106 size_t i;
4108 for (i = 0; i < view->lines; i++) {
4109 struct blame *blame = view->line[i].data;
4111 if (!blame->commit)
4112 continue;
4114 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4115 return blame->commit;
4116 }
4118 {
4119 struct blame_commit *commit = calloc(1, sizeof(*commit));
4121 if (commit)
4122 string_ncopy(commit->id, id, SIZEOF_REV);
4123 return commit;
4124 }
4125 }
4127 static bool
4128 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4129 {
4130 const char *pos = *posref;
4132 *posref = NULL;
4133 pos = strchr(pos + 1, ' ');
4134 if (!pos || !isdigit(pos[1]))
4135 return FALSE;
4136 *number = atoi(pos + 1);
4137 if (*number < min || *number > max)
4138 return FALSE;
4140 *posref = pos;
4141 return TRUE;
4142 }
4144 static struct blame_commit *
4145 parse_blame_commit(struct view *view, const char *text, int *blamed)
4146 {
4147 struct blame_commit *commit;
4148 struct blame *blame;
4149 const char *pos = text + SIZEOF_REV - 2;
4150 size_t orig_lineno = 0;
4151 size_t lineno;
4152 size_t group;
4154 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4155 return NULL;
4157 if (!parse_number(&pos, &orig_lineno, 1, 9999999) ||
4158 !parse_number(&pos, &lineno, 1, view->lines) ||
4159 !parse_number(&pos, &group, 1, view->lines - lineno + 1))
4160 return NULL;
4162 commit = get_blame_commit(view, text);
4163 if (!commit)
4164 return NULL;
4166 *blamed += group;
4167 while (group--) {
4168 struct line *line = &view->line[lineno + group - 1];
4170 blame = line->data;
4171 blame->commit = commit;
4172 blame->lineno = orig_lineno + group - 1;
4173 line->dirty = 1;
4174 }
4176 return commit;
4177 }
4179 static bool
4180 blame_read_file(struct view *view, const char *line, bool *read_file)
4181 {
4182 if (!line) {
4183 const char *blame_argv[] = {
4184 "git", "blame", "--incremental",
4185 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4186 };
4188 if (view->lines == 0 && !view->prev)
4189 die("No blame exist for %s", view->vid);
4191 if (view->lines == 0 || !start_update(view, blame_argv, opt_cdup)) {
4192 report("Failed to load blame data");
4193 return TRUE;
4194 }
4196 *read_file = FALSE;
4197 return FALSE;
4199 } else {
4200 size_t linelen = strlen(line);
4201 struct blame *blame = malloc(sizeof(*blame) + linelen);
4203 if (!blame)
4204 return FALSE;
4206 blame->commit = NULL;
4207 strncpy(blame->text, line, linelen);
4208 blame->text[linelen] = 0;
4209 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4210 }
4211 }
4213 static bool
4214 match_blame_header(const char *name, char **line)
4215 {
4216 size_t namelen = strlen(name);
4217 bool matched = !strncmp(name, *line, namelen);
4219 if (matched)
4220 *line += namelen;
4222 return matched;
4223 }
4225 static bool
4226 blame_read(struct view *view, char *line)
4227 {
4228 static struct blame_commit *commit = NULL;
4229 static int blamed = 0;
4230 static bool read_file = TRUE;
4232 if (read_file)
4233 return blame_read_file(view, line, &read_file);
4235 if (!line) {
4236 /* Reset all! */
4237 commit = NULL;
4238 blamed = 0;
4239 read_file = TRUE;
4240 string_format(view->ref, "%s", view->vid);
4241 if (view_is_displayed(view)) {
4242 update_view_title(view);
4243 redraw_view_from(view, 0);
4244 }
4245 return TRUE;
4246 }
4248 if (!commit) {
4249 commit = parse_blame_commit(view, line, &blamed);
4250 string_format(view->ref, "%s %2d%%", view->vid,
4251 view->lines ? blamed * 100 / view->lines : 0);
4253 } else if (match_blame_header("author ", &line)) {
4254 commit->author = get_author(line);
4256 } else if (match_blame_header("author-time ", &line)) {
4257 parse_timesec(&commit->time, line);
4259 } else if (match_blame_header("author-tz ", &line)) {
4260 parse_timezone(&commit->time, line);
4262 } else if (match_blame_header("summary ", &line)) {
4263 string_ncopy(commit->title, line, strlen(line));
4265 } else if (match_blame_header("previous ", &line)) {
4266 if (strlen(line) <= SIZEOF_REV)
4267 return FALSE;
4268 string_copy_rev(commit->parent_id, line);
4269 line += SIZEOF_REV;
4270 string_ncopy(commit->parent_filename, line, strlen(line));
4272 } else if (match_blame_header("filename ", &line)) {
4273 string_ncopy(commit->filename, line, strlen(line));
4274 commit = NULL;
4275 }
4277 return TRUE;
4278 }
4280 static bool
4281 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4282 {
4283 struct blame *blame = line->data;
4284 struct time *time = NULL;
4285 const char *id = NULL, *author = NULL;
4287 if (blame->commit && *blame->commit->filename) {
4288 id = blame->commit->id;
4289 author = blame->commit->author;
4290 time = &blame->commit->time;
4291 }
4293 if (opt_date && draw_date(view, time))
4294 return TRUE;
4296 if (opt_author && draw_author(view, author))
4297 return TRUE;
4299 if (draw_field(view, LINE_BLAME_ID, id, ID_COLS, FALSE))
4300 return TRUE;
4302 if (draw_lineno(view, lineno))
4303 return TRUE;
4305 draw_text(view, LINE_DEFAULT, blame->text);
4306 return TRUE;
4307 }
4309 static bool
4310 check_blame_commit(struct blame *blame, bool check_null_id)
4311 {
4312 if (!blame->commit)
4313 report("Commit data not loaded yet");
4314 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4315 report("No commit exist for the selected line");
4316 else
4317 return TRUE;
4318 return FALSE;
4319 }
4321 static void
4322 setup_blame_parent_line(struct view *view, struct blame *blame)
4323 {
4324 char from[SIZEOF_REF + SIZEOF_STR];
4325 char to[SIZEOF_REF + SIZEOF_STR];
4326 const char *diff_tree_argv[] = {
4327 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4328 "-U0", from, to, "--", NULL
4329 };
4330 struct io io;
4331 int parent_lineno = -1;
4332 int blamed_lineno = -1;
4333 char *line;
4335 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4336 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4337 !io_run(&io, IO_RD, NULL, diff_tree_argv))
4338 return;
4340 while ((line = io_get(&io, '\n', TRUE))) {
4341 if (*line == '@') {
4342 char *pos = strchr(line, '+');
4344 parent_lineno = atoi(line + 4);
4345 if (pos)
4346 blamed_lineno = atoi(pos + 1);
4348 } else if (*line == '+' && parent_lineno != -1) {
4349 if (blame->lineno == blamed_lineno - 1 &&
4350 !strcmp(blame->text, line + 1)) {
4351 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4352 break;
4353 }
4354 blamed_lineno++;
4355 }
4356 }
4358 io_done(&io);
4359 }
4361 static enum request
4362 blame_request(struct view *view, enum request request, struct line *line)
4363 {
4364 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4365 struct blame *blame = line->data;
4367 switch (request) {
4368 case REQ_VIEW_BLAME:
4369 if (check_blame_commit(blame, TRUE)) {
4370 string_copy(opt_ref, blame->commit->id);
4371 string_copy(opt_file, blame->commit->filename);
4372 if (blame->lineno)
4373 view->lineno = blame->lineno;
4374 open_view(view, REQ_VIEW_BLAME, OPEN_REFRESH);
4375 }
4376 break;
4378 case REQ_PARENT:
4379 if (!check_blame_commit(blame, TRUE))
4380 break;
4381 if (!*blame->commit->parent_id) {
4382 report("The selected commit has no parents");
4383 } else {
4384 string_copy_rev(opt_ref, blame->commit->parent_id);
4385 string_copy(opt_file, blame->commit->parent_filename);
4386 setup_blame_parent_line(view, blame);
4387 open_view(view, REQ_VIEW_BLAME, OPEN_REFRESH);
4388 }
4389 break;
4391 case REQ_ENTER:
4392 if (!check_blame_commit(blame, FALSE))
4393 break;
4395 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
4396 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
4397 break;
4399 if (!strcmp(blame->commit->id, NULL_ID)) {
4400 struct view *diff = VIEW(REQ_VIEW_DIFF);
4401 const char *diff_index_argv[] = {
4402 "git", "diff-index", "--root", "--patch-with-stat",
4403 "-C", "-M", "HEAD", "--", view->vid, NULL
4404 };
4406 if (!*blame->commit->parent_id) {
4407 diff_index_argv[1] = "diff";
4408 diff_index_argv[2] = "--no-color";
4409 diff_index_argv[6] = "--";
4410 diff_index_argv[7] = "/dev/null";
4411 }
4413 if (!prepare_update(diff, diff_index_argv, NULL)) {
4414 report("Failed to allocate diff command");
4415 break;
4416 }
4417 flags |= OPEN_PREPARED;
4418 }
4420 open_view(view, REQ_VIEW_DIFF, flags);
4421 if (VIEW(REQ_VIEW_DIFF)->pipe && !strcmp(blame->commit->id, NULL_ID))
4422 string_copy_rev(VIEW(REQ_VIEW_DIFF)->ref, NULL_ID);
4423 break;
4425 default:
4426 return request;
4427 }
4429 return REQ_NONE;
4430 }
4432 static bool
4433 blame_grep(struct view *view, struct line *line)
4434 {
4435 struct blame *blame = line->data;
4436 struct blame_commit *commit = blame->commit;
4437 const char *text[] = {
4438 blame->text,
4439 commit ? commit->title : "",
4440 commit ? commit->id : "",
4441 commit && opt_author ? commit->author : "",
4442 commit ? mkdate(&commit->time, opt_date) : "",
4443 NULL
4444 };
4446 return grep_text(view, text);
4447 }
4449 static void
4450 blame_select(struct view *view, struct line *line)
4451 {
4452 struct blame *blame = line->data;
4453 struct blame_commit *commit = blame->commit;
4455 if (!commit)
4456 return;
4458 if (!strcmp(commit->id, NULL_ID))
4459 string_ncopy(ref_commit, "HEAD", 4);
4460 else
4461 string_copy_rev(ref_commit, commit->id);
4462 }
4464 static struct view_ops blame_ops = {
4465 "line",
4466 NULL,
4467 blame_open,
4468 blame_read,
4469 blame_draw,
4470 blame_request,
4471 blame_grep,
4472 blame_select,
4473 };
4475 /*
4476 * Branch backend
4477 */
4479 struct branch {
4480 const char *author; /* Author of the last commit. */
4481 struct time time; /* Date of the last activity. */
4482 const struct ref *ref; /* Name and commit ID information. */
4483 };
4485 static const struct ref branch_all;
4487 static const enum sort_field branch_sort_fields[] = {
4488 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4489 };
4490 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
4492 static int
4493 branch_compare(const void *l1, const void *l2)
4494 {
4495 const struct branch *branch1 = ((const struct line *) l1)->data;
4496 const struct branch *branch2 = ((const struct line *) l2)->data;
4498 switch (get_sort_field(branch_sort_state)) {
4499 case ORDERBY_DATE:
4500 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
4502 case ORDERBY_AUTHOR:
4503 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
4505 case ORDERBY_NAME:
4506 default:
4507 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
4508 }
4509 }
4511 static bool
4512 branch_draw(struct view *view, struct line *line, unsigned int lineno)
4513 {
4514 struct branch *branch = line->data;
4515 enum line_type type = branch->ref->head ? LINE_MAIN_HEAD : LINE_DEFAULT;
4517 if (opt_date && draw_date(view, &branch->time))
4518 return TRUE;
4520 if (opt_author && draw_author(view, branch->author))
4521 return TRUE;
4523 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
4524 return TRUE;
4525 }
4527 static enum request
4528 branch_request(struct view *view, enum request request, struct line *line)
4529 {
4530 struct branch *branch = line->data;
4532 switch (request) {
4533 case REQ_REFRESH:
4534 load_refs();
4535 open_view(view, REQ_VIEW_BRANCH, OPEN_REFRESH);
4536 return REQ_NONE;
4538 case REQ_TOGGLE_SORT_FIELD:
4539 case REQ_TOGGLE_SORT_ORDER:
4540 sort_view(view, request, &branch_sort_state, branch_compare);
4541 return REQ_NONE;
4543 case REQ_ENTER:
4544 {
4545 const struct ref *ref = branch->ref;
4546 const char *all_branches_argv[] = {
4547 "git", "log", "--no-color", "--pretty=raw", "--parents",
4548 "--topo-order",
4549 ref == &branch_all ? "--all" : ref->name, NULL
4550 };
4551 struct view *main_view = VIEW(REQ_VIEW_MAIN);
4553 if (!prepare_update(main_view, all_branches_argv, NULL))
4554 report("Failed to load view of all branches");
4555 else
4556 open_view(view, REQ_VIEW_MAIN, OPEN_PREPARED | OPEN_SPLIT);
4557 return REQ_NONE;
4558 }
4559 default:
4560 return request;
4561 }
4562 }
4564 static bool
4565 branch_read(struct view *view, char *line)
4566 {
4567 static char id[SIZEOF_REV];
4568 struct branch *reference;
4569 size_t i;
4571 if (!line)
4572 return TRUE;
4574 switch (get_line_type(line)) {
4575 case LINE_COMMIT:
4576 string_copy_rev(id, line + STRING_SIZE("commit "));
4577 return TRUE;
4579 case LINE_AUTHOR:
4580 for (i = 0, reference = NULL; i < view->lines; i++) {
4581 struct branch *branch = view->line[i].data;
4583 if (strcmp(branch->ref->id, id))
4584 continue;
4586 view->line[i].dirty = TRUE;
4587 if (reference) {
4588 branch->author = reference->author;
4589 branch->time = reference->time;
4590 continue;
4591 }
4593 parse_author_line(line + STRING_SIZE("author "),
4594 &branch->author, &branch->time);
4595 reference = branch;
4596 }
4597 return TRUE;
4599 default:
4600 return TRUE;
4601 }
4603 }
4605 static bool
4606 branch_open_visitor(void *data, const struct ref *ref)
4607 {
4608 struct view *view = data;
4609 struct branch *branch;
4611 if (ref->tag || ref->ltag || ref->remote)
4612 return TRUE;
4614 branch = calloc(1, sizeof(*branch));
4615 if (!branch)
4616 return FALSE;
4618 branch->ref = ref;
4619 return !!add_line_data(view, branch, LINE_DEFAULT);
4620 }
4622 static bool
4623 branch_open(struct view *view)
4624 {
4625 const char *branch_log[] = {
4626 "git", "log", "--no-color", "--pretty=raw",
4627 "--simplify-by-decoration", "--all", NULL
4628 };
4630 if (!start_update(view, branch_log, NULL)) {
4631 report("Failed to load branch data");
4632 return TRUE;
4633 }
4635 setup_update(view, view->id);
4636 branch_open_visitor(view, &branch_all);
4637 foreach_ref(branch_open_visitor, view);
4638 view->p_restore = TRUE;
4640 return TRUE;
4641 }
4643 static bool
4644 branch_grep(struct view *view, struct line *line)
4645 {
4646 struct branch *branch = line->data;
4647 const char *text[] = {
4648 branch->ref->name,
4649 branch->author,
4650 NULL
4651 };
4653 return grep_text(view, text);
4654 }
4656 static void
4657 branch_select(struct view *view, struct line *line)
4658 {
4659 struct branch *branch = line->data;
4661 string_copy_rev(view->ref, branch->ref->id);
4662 string_copy_rev(ref_commit, branch->ref->id);
4663 string_copy_rev(ref_head, branch->ref->id);
4664 string_copy_rev(ref_branch, branch->ref->name);
4665 }
4667 static struct view_ops branch_ops = {
4668 "branch",
4669 NULL,
4670 branch_open,
4671 branch_read,
4672 branch_draw,
4673 branch_request,
4674 branch_grep,
4675 branch_select,
4676 };
4678 /*
4679 * Status backend
4680 */
4682 struct status {
4683 char status;
4684 struct {
4685 mode_t mode;
4686 char rev[SIZEOF_REV];
4687 char name[SIZEOF_STR];
4688 } old;
4689 struct {
4690 mode_t mode;
4691 char rev[SIZEOF_REV];
4692 char name[SIZEOF_STR];
4693 } new;
4694 };
4696 static char status_onbranch[SIZEOF_STR];
4697 static struct status stage_status;
4698 static enum line_type stage_line_type;
4699 static size_t stage_chunks;
4700 static int *stage_chunk;
4702 DEFINE_ALLOCATOR(realloc_ints, int, 32)
4704 /* This should work even for the "On branch" line. */
4705 static inline bool
4706 status_has_none(struct view *view, struct line *line)
4707 {
4708 return line < view->line + view->lines && !line[1].data;
4709 }
4711 /* Get fields from the diff line:
4712 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
4713 */
4714 static inline bool
4715 status_get_diff(struct status *file, const char *buf, size_t bufsize)
4716 {
4717 const char *old_mode = buf + 1;
4718 const char *new_mode = buf + 8;
4719 const char *old_rev = buf + 15;
4720 const char *new_rev = buf + 56;
4721 const char *status = buf + 97;
4723 if (bufsize < 98 ||
4724 old_mode[-1] != ':' ||
4725 new_mode[-1] != ' ' ||
4726 old_rev[-1] != ' ' ||
4727 new_rev[-1] != ' ' ||
4728 status[-1] != ' ')
4729 return FALSE;
4731 file->status = *status;
4733 string_copy_rev(file->old.rev, old_rev);
4734 string_copy_rev(file->new.rev, new_rev);
4736 file->old.mode = strtoul(old_mode, NULL, 8);
4737 file->new.mode = strtoul(new_mode, NULL, 8);
4739 file->old.name[0] = file->new.name[0] = 0;
4741 return TRUE;
4742 }
4744 static bool
4745 status_run(struct view *view, const char *argv[], char status, enum line_type type)
4746 {
4747 struct status *unmerged = NULL;
4748 char *buf;
4749 struct io io;
4751 if (!io_run(&io, IO_RD, opt_cdup, argv))
4752 return FALSE;
4754 add_line_data(view, NULL, type);
4756 while ((buf = io_get(&io, 0, TRUE))) {
4757 struct status *file = unmerged;
4759 if (!file) {
4760 file = calloc(1, sizeof(*file));
4761 if (!file || !add_line_data(view, file, type))
4762 goto error_out;
4763 }
4765 /* Parse diff info part. */
4766 if (status) {
4767 file->status = status;
4768 if (status == 'A')
4769 string_copy(file->old.rev, NULL_ID);
4771 } else if (!file->status || file == unmerged) {
4772 if (!status_get_diff(file, buf, strlen(buf)))
4773 goto error_out;
4775 buf = io_get(&io, 0, TRUE);
4776 if (!buf)
4777 break;
4779 /* Collapse all modified entries that follow an
4780 * associated unmerged entry. */
4781 if (unmerged == file) {
4782 unmerged->status = 'U';
4783 unmerged = NULL;
4784 } else if (file->status == 'U') {
4785 unmerged = file;
4786 }
4787 }
4789 /* Grab the old name for rename/copy. */
4790 if (!*file->old.name &&
4791 (file->status == 'R' || file->status == 'C')) {
4792 string_ncopy(file->old.name, buf, strlen(buf));
4794 buf = io_get(&io, 0, TRUE);
4795 if (!buf)
4796 break;
4797 }
4799 /* git-ls-files just delivers a NUL separated list of
4800 * file names similar to the second half of the
4801 * git-diff-* output. */
4802 string_ncopy(file->new.name, buf, strlen(buf));
4803 if (!*file->old.name)
4804 string_copy(file->old.name, file->new.name);
4805 file = NULL;
4806 }
4808 if (io_error(&io)) {
4809 error_out:
4810 io_done(&io);
4811 return FALSE;
4812 }
4814 if (!view->line[view->lines - 1].data)
4815 add_line_data(view, NULL, LINE_STAT_NONE);
4817 io_done(&io);
4818 return TRUE;
4819 }
4821 /* Don't show unmerged entries in the staged section. */
4822 static const char *status_diff_index_argv[] = {
4823 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
4824 "--cached", "-M", "HEAD", NULL
4825 };
4827 static const char *status_diff_files_argv[] = {
4828 "git", "diff-files", "-z", NULL
4829 };
4831 static const char *status_list_other_argv[] = {
4832 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
4833 };
4835 static const char *status_list_no_head_argv[] = {
4836 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
4837 };
4839 static const char *update_index_argv[] = {
4840 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
4841 };
4843 /* Restore the previous line number to stay in the context or select a
4844 * line with something that can be updated. */
4845 static void
4846 status_restore(struct view *view)
4847 {
4848 if (view->p_lineno >= view->lines)
4849 view->p_lineno = view->lines - 1;
4850 while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
4851 view->p_lineno++;
4852 while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
4853 view->p_lineno--;
4855 /* If the above fails, always skip the "On branch" line. */
4856 if (view->p_lineno < view->lines)
4857 view->lineno = view->p_lineno;
4858 else
4859 view->lineno = 1;
4861 if (view->lineno < view->offset)
4862 view->offset = view->lineno;
4863 else if (view->offset + view->height <= view->lineno)
4864 view->offset = view->lineno - view->height + 1;
4866 view->p_restore = FALSE;
4867 }
4869 static void
4870 status_update_onbranch(void)
4871 {
4872 static const char *paths[][2] = {
4873 { "rebase-apply/rebasing", "Rebasing" },
4874 { "rebase-apply/applying", "Applying mailbox" },
4875 { "rebase-apply/", "Rebasing mailbox" },
4876 { "rebase-merge/interactive", "Interactive rebase" },
4877 { "rebase-merge/", "Rebase merge" },
4878 { "MERGE_HEAD", "Merging" },
4879 { "BISECT_LOG", "Bisecting" },
4880 { "HEAD", "On branch" },
4881 };
4882 char buf[SIZEOF_STR];
4883 struct stat stat;
4884 int i;
4886 if (is_initial_commit()) {
4887 string_copy(status_onbranch, "Initial commit");
4888 return;
4889 }
4891 for (i = 0; i < ARRAY_SIZE(paths); i++) {
4892 char *head = opt_head;
4894 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
4895 lstat(buf, &stat) < 0)
4896 continue;
4898 if (!*opt_head) {
4899 struct io io;
4901 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
4902 io_read_buf(&io, buf, sizeof(buf))) {
4903 head = buf;
4904 if (!prefixcmp(head, "refs/heads/"))
4905 head += STRING_SIZE("refs/heads/");
4906 }
4907 }
4909 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
4910 string_copy(status_onbranch, opt_head);
4911 return;
4912 }
4914 string_copy(status_onbranch, "Not currently on any branch");
4915 }
4917 /* First parse staged info using git-diff-index(1), then parse unstaged
4918 * info using git-diff-files(1), and finally untracked files using
4919 * git-ls-files(1). */
4920 static bool
4921 status_open(struct view *view)
4922 {
4923 reset_view(view);
4925 add_line_data(view, NULL, LINE_STAT_HEAD);
4926 status_update_onbranch();
4928 io_run_bg(update_index_argv);
4930 if (is_initial_commit()) {
4931 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
4932 return FALSE;
4933 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
4934 return FALSE;
4935 }
4937 if (!opt_untracked_dirs_content)
4938 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
4940 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
4941 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
4942 return FALSE;
4944 /* Restore the exact position or use the specialized restore
4945 * mode? */
4946 if (!view->p_restore)
4947 status_restore(view);
4948 return TRUE;
4949 }
4951 static bool
4952 status_draw(struct view *view, struct line *line, unsigned int lineno)
4953 {
4954 struct status *status = line->data;
4955 enum line_type type;
4956 const char *text;
4958 if (!status) {
4959 switch (line->type) {
4960 case LINE_STAT_STAGED:
4961 type = LINE_STAT_SECTION;
4962 text = "Changes to be committed:";
4963 break;
4965 case LINE_STAT_UNSTAGED:
4966 type = LINE_STAT_SECTION;
4967 text = "Changed but not updated:";
4968 break;
4970 case LINE_STAT_UNTRACKED:
4971 type = LINE_STAT_SECTION;
4972 text = "Untracked files:";
4973 break;
4975 case LINE_STAT_NONE:
4976 type = LINE_DEFAULT;
4977 text = " (no files)";
4978 break;
4980 case LINE_STAT_HEAD:
4981 type = LINE_STAT_HEAD;
4982 text = status_onbranch;
4983 break;
4985 default:
4986 return FALSE;
4987 }
4988 } else {
4989 static char buf[] = { '?', ' ', ' ', ' ', 0 };
4991 buf[0] = status->status;
4992 if (draw_text(view, line->type, buf))
4993 return TRUE;
4994 type = LINE_DEFAULT;
4995 text = status->new.name;
4996 }
4998 draw_text(view, type, text);
4999 return TRUE;
5000 }
5002 static enum request
5003 status_load_error(struct view *view, struct view *stage, const char *path)
5004 {
5005 if (displayed_views() == 2 || display[current_view] != view)
5006 maximize_view(view);
5007 report("Failed to load '%s': %s", path, io_strerror(&stage->io));
5008 return REQ_NONE;
5009 }
5011 static enum request
5012 status_enter(struct view *view, struct line *line)
5013 {
5014 struct status *status = line->data;
5015 const char *oldpath = status ? status->old.name : NULL;
5016 /* Diffs for unmerged entries are empty when passing the new
5017 * path, so leave it empty. */
5018 const char *newpath = status && status->status != 'U' ? status->new.name : NULL;
5019 const char *info;
5020 enum open_flags split;
5021 struct view *stage = VIEW(REQ_VIEW_STAGE);
5023 if (line->type == LINE_STAT_NONE ||
5024 (!status && line[1].type == LINE_STAT_NONE)) {
5025 report("No file to diff");
5026 return REQ_NONE;
5027 }
5029 switch (line->type) {
5030 case LINE_STAT_STAGED:
5031 if (is_initial_commit()) {
5032 const char *no_head_diff_argv[] = {
5033 "git", "diff", "--no-color", "--patch-with-stat",
5034 "--", "/dev/null", newpath, NULL
5035 };
5037 if (!prepare_update(stage, no_head_diff_argv, opt_cdup))
5038 return status_load_error(view, stage, newpath);
5039 } else {
5040 const char *index_show_argv[] = {
5041 "git", "diff-index", "--root", "--patch-with-stat",
5042 "-C", "-M", "--cached", "HEAD", "--",
5043 oldpath, newpath, NULL
5044 };
5046 if (!prepare_update(stage, index_show_argv, opt_cdup))
5047 return status_load_error(view, stage, newpath);
5048 }
5050 if (status)
5051 info = "Staged changes to %s";
5052 else
5053 info = "Staged changes";
5054 break;
5056 case LINE_STAT_UNSTAGED:
5057 {
5058 const char *files_show_argv[] = {
5059 "git", "diff-files", "--root", "--patch-with-stat",
5060 "-C", "-M", "--", oldpath, newpath, NULL
5061 };
5063 if (!prepare_update(stage, files_show_argv, opt_cdup))
5064 return status_load_error(view, stage, newpath);
5065 if (status)
5066 info = "Unstaged changes to %s";
5067 else
5068 info = "Unstaged changes";
5069 break;
5070 }
5071 case LINE_STAT_UNTRACKED:
5072 if (!newpath) {
5073 report("No file to show");
5074 return REQ_NONE;
5075 }
5077 if (!suffixcmp(status->new.name, -1, "/")) {
5078 report("Cannot display a directory");
5079 return REQ_NONE;
5080 }
5082 if (!prepare_update_file(stage, newpath))
5083 return status_load_error(view, stage, newpath);
5084 info = "Untracked file %s";
5085 break;
5087 case LINE_STAT_HEAD:
5088 return REQ_NONE;
5090 default:
5091 die("line type %d not handled in switch", line->type);
5092 }
5094 split = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5095 open_view(view, REQ_VIEW_STAGE, OPEN_PREPARED | split);
5096 if (view_is_displayed(VIEW(REQ_VIEW_STAGE))) {
5097 if (status) {
5098 stage_status = *status;
5099 } else {
5100 memset(&stage_status, 0, sizeof(stage_status));
5101 }
5103 stage_line_type = line->type;
5104 stage_chunks = 0;
5105 string_format(VIEW(REQ_VIEW_STAGE)->ref, info, stage_status.new.name);
5106 }
5108 return REQ_NONE;
5109 }
5111 static bool
5112 status_exists(struct status *status, enum line_type type)
5113 {
5114 struct view *view = VIEW(REQ_VIEW_STATUS);
5115 unsigned long lineno;
5117 for (lineno = 0; lineno < view->lines; lineno++) {
5118 struct line *line = &view->line[lineno];
5119 struct status *pos = line->data;
5121 if (line->type != type)
5122 continue;
5123 if (!pos && (!status || !status->status) && line[1].data) {
5124 select_view_line(view, lineno);
5125 return TRUE;
5126 }
5127 if (pos && !strcmp(status->new.name, pos->new.name)) {
5128 select_view_line(view, lineno);
5129 return TRUE;
5130 }
5131 }
5133 return FALSE;
5134 }
5137 static bool
5138 status_update_prepare(struct io *io, enum line_type type)
5139 {
5140 const char *staged_argv[] = {
5141 "git", "update-index", "-z", "--index-info", NULL
5142 };
5143 const char *others_argv[] = {
5144 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5145 };
5147 switch (type) {
5148 case LINE_STAT_STAGED:
5149 return io_run(io, IO_WR, opt_cdup, staged_argv);
5151 case LINE_STAT_UNSTAGED:
5152 case LINE_STAT_UNTRACKED:
5153 return io_run(io, IO_WR, opt_cdup, others_argv);
5155 default:
5156 die("line type %d not handled in switch", type);
5157 return FALSE;
5158 }
5159 }
5161 static bool
5162 status_update_write(struct io *io, struct status *status, enum line_type type)
5163 {
5164 char buf[SIZEOF_STR];
5165 size_t bufsize = 0;
5167 switch (type) {
5168 case LINE_STAT_STAGED:
5169 if (!string_format_from(buf, &bufsize, "%06o %s\t%s%c",
5170 status->old.mode,
5171 status->old.rev,
5172 status->old.name, 0))
5173 return FALSE;
5174 break;
5176 case LINE_STAT_UNSTAGED:
5177 case LINE_STAT_UNTRACKED:
5178 if (!string_format_from(buf, &bufsize, "%s%c", status->new.name, 0))
5179 return FALSE;
5180 break;
5182 default:
5183 die("line type %d not handled in switch", type);
5184 }
5186 return io_write(io, buf, bufsize);
5187 }
5189 static bool
5190 status_update_file(struct status *status, enum line_type type)
5191 {
5192 struct io io;
5193 bool result;
5195 if (!status_update_prepare(&io, type))
5196 return FALSE;
5198 result = status_update_write(&io, status, type);
5199 return io_done(&io) && result;
5200 }
5202 static bool
5203 status_update_files(struct view *view, struct line *line)
5204 {
5205 char buf[sizeof(view->ref)];
5206 struct io io;
5207 bool result = TRUE;
5208 struct line *pos = view->line + view->lines;
5209 int files = 0;
5210 int file, done;
5211 int cursor_y = -1, cursor_x = -1;
5213 if (!status_update_prepare(&io, line->type))
5214 return FALSE;
5216 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5217 files++;
5219 string_copy(buf, view->ref);
5220 getsyx(cursor_y, cursor_x);
5221 for (file = 0, done = 5; result && file < files; line++, file++) {
5222 int almost_done = file * 100 / files;
5224 if (almost_done > done) {
5225 done = almost_done;
5226 string_format(view->ref, "updating file %u of %u (%d%% done)",
5227 file, files, done);
5228 update_view_title(view);
5229 setsyx(cursor_y, cursor_x);
5230 doupdate();
5231 }
5232 result = status_update_write(&io, line->data, line->type);
5233 }
5234 string_copy(view->ref, buf);
5236 return io_done(&io) && result;
5237 }
5239 static bool
5240 status_update(struct view *view)
5241 {
5242 struct line *line = &view->line[view->lineno];
5244 assert(view->lines);
5246 if (!line->data) {
5247 /* This should work even for the "On branch" line. */
5248 if (line < view->line + view->lines && !line[1].data) {
5249 report("Nothing to update");
5250 return FALSE;
5251 }
5253 if (!status_update_files(view, line + 1)) {
5254 report("Failed to update file status");
5255 return FALSE;
5256 }
5258 } else if (!status_update_file(line->data, line->type)) {
5259 report("Failed to update file status");
5260 return FALSE;
5261 }
5263 return TRUE;
5264 }
5266 static bool
5267 status_revert(struct status *status, enum line_type type, bool has_none)
5268 {
5269 if (!status || type != LINE_STAT_UNSTAGED) {
5270 if (type == LINE_STAT_STAGED) {
5271 report("Cannot revert changes to staged files");
5272 } else if (type == LINE_STAT_UNTRACKED) {
5273 report("Cannot revert changes to untracked files");
5274 } else if (has_none) {
5275 report("Nothing to revert");
5276 } else {
5277 report("Cannot revert changes to multiple files");
5278 }
5280 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5281 char mode[10] = "100644";
5282 const char *reset_argv[] = {
5283 "git", "update-index", "--cacheinfo", mode,
5284 status->old.rev, status->old.name, NULL
5285 };
5286 const char *checkout_argv[] = {
5287 "git", "checkout", "--", status->old.name, NULL
5288 };
5290 if (status->status == 'U') {
5291 string_format(mode, "%5o", status->old.mode);
5293 if (status->old.mode == 0 && status->new.mode == 0) {
5294 reset_argv[2] = "--force-remove";
5295 reset_argv[3] = status->old.name;
5296 reset_argv[4] = NULL;
5297 }
5299 if (!io_run_fg(reset_argv, opt_cdup))
5300 return FALSE;
5301 if (status->old.mode == 0 && status->new.mode == 0)
5302 return TRUE;
5303 }
5305 return io_run_fg(checkout_argv, opt_cdup);
5306 }
5308 return FALSE;
5309 }
5311 static enum request
5312 status_request(struct view *view, enum request request, struct line *line)
5313 {
5314 struct status *status = line->data;
5316 switch (request) {
5317 case REQ_STATUS_UPDATE:
5318 if (!status_update(view))
5319 return REQ_NONE;
5320 break;
5322 case REQ_STATUS_REVERT:
5323 if (!status_revert(status, line->type, status_has_none(view, line)))
5324 return REQ_NONE;
5325 break;
5327 case REQ_STATUS_MERGE:
5328 if (!status || status->status != 'U') {
5329 report("Merging only possible for files with unmerged status ('U').");
5330 return REQ_NONE;
5331 }
5332 open_mergetool(status->new.name);
5333 break;
5335 case REQ_EDIT:
5336 if (!status)
5337 return request;
5338 if (status->status == 'D') {
5339 report("File has been deleted.");
5340 return REQ_NONE;
5341 }
5343 open_editor(status->new.name);
5344 break;
5346 case REQ_VIEW_BLAME:
5347 if (status)
5348 opt_ref[0] = 0;
5349 return request;
5351 case REQ_ENTER:
5352 /* After returning the status view has been split to
5353 * show the stage view. No further reloading is
5354 * necessary. */
5355 return status_enter(view, line);
5357 case REQ_REFRESH:
5358 /* Simply reload the view. */
5359 break;
5361 default:
5362 return request;
5363 }
5365 open_view(view, REQ_VIEW_STATUS, OPEN_RELOAD);
5367 return REQ_NONE;
5368 }
5370 static void
5371 status_select(struct view *view, struct line *line)
5372 {
5373 struct status *status = line->data;
5374 char file[SIZEOF_STR] = "all files";
5375 const char *text;
5376 const char *key;
5378 if (status && !string_format(file, "'%s'", status->new.name))
5379 return;
5381 if (!status && line[1].type == LINE_STAT_NONE)
5382 line++;
5384 switch (line->type) {
5385 case LINE_STAT_STAGED:
5386 text = "Press %s to unstage %s for commit";
5387 break;
5389 case LINE_STAT_UNSTAGED:
5390 text = "Press %s to stage %s for commit";
5391 break;
5393 case LINE_STAT_UNTRACKED:
5394 text = "Press %s to stage %s for addition";
5395 break;
5397 case LINE_STAT_HEAD:
5398 case LINE_STAT_NONE:
5399 text = "Nothing to update";
5400 break;
5402 default:
5403 die("line type %d not handled in switch", line->type);
5404 }
5406 if (status && status->status == 'U') {
5407 text = "Press %s to resolve conflict in %s";
5408 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5410 } else {
5411 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5412 }
5414 string_format(view->ref, text, key, file);
5415 if (status)
5416 string_copy(opt_file, status->new.name);
5417 }
5419 static bool
5420 status_grep(struct view *view, struct line *line)
5421 {
5422 struct status *status = line->data;
5424 if (status) {
5425 const char buf[2] = { status->status, 0 };
5426 const char *text[] = { status->new.name, buf, NULL };
5428 return grep_text(view, text);
5429 }
5431 return FALSE;
5432 }
5434 static struct view_ops status_ops = {
5435 "file",
5436 NULL,
5437 status_open,
5438 NULL,
5439 status_draw,
5440 status_request,
5441 status_grep,
5442 status_select,
5443 };
5446 static bool
5447 stage_diff_write(struct io *io, struct line *line, struct line *end)
5448 {
5449 while (line < end) {
5450 if (!io_write(io, line->data, strlen(line->data)) ||
5451 !io_write(io, "\n", 1))
5452 return FALSE;
5453 line++;
5454 if (line->type == LINE_DIFF_CHUNK ||
5455 line->type == LINE_DIFF_HEADER)
5456 break;
5457 }
5459 return TRUE;
5460 }
5462 static struct line *
5463 stage_diff_find(struct view *view, struct line *line, enum line_type type)
5464 {
5465 for (; view->line < line; line--)
5466 if (line->type == type)
5467 return line;
5469 return NULL;
5470 }
5472 static bool
5473 stage_apply_chunk(struct view *view, struct line *chunk, bool revert)
5474 {
5475 const char *apply_argv[SIZEOF_ARG] = {
5476 "git", "apply", "--whitespace=nowarn", NULL
5477 };
5478 struct line *diff_hdr;
5479 struct io io;
5480 int argc = 3;
5482 diff_hdr = stage_diff_find(view, chunk, LINE_DIFF_HEADER);
5483 if (!diff_hdr)
5484 return FALSE;
5486 if (!revert)
5487 apply_argv[argc++] = "--cached";
5488 if (revert || stage_line_type == LINE_STAT_STAGED)
5489 apply_argv[argc++] = "-R";
5490 apply_argv[argc++] = "-";
5491 apply_argv[argc++] = NULL;
5492 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
5493 return FALSE;
5495 if (!stage_diff_write(&io, diff_hdr, chunk) ||
5496 !stage_diff_write(&io, chunk, view->line + view->lines))
5497 chunk = NULL;
5499 io_done(&io);
5500 io_run_bg(update_index_argv);
5502 return chunk ? TRUE : FALSE;
5503 }
5505 static bool
5506 stage_update(struct view *view, struct line *line)
5507 {
5508 struct line *chunk = NULL;
5510 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
5511 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5513 if (chunk) {
5514 if (!stage_apply_chunk(view, chunk, FALSE)) {
5515 report("Failed to apply chunk");
5516 return FALSE;
5517 }
5519 } else if (!stage_status.status) {
5520 view = VIEW(REQ_VIEW_STATUS);
5522 for (line = view->line; line < view->line + view->lines; line++)
5523 if (line->type == stage_line_type)
5524 break;
5526 if (!status_update_files(view, line + 1)) {
5527 report("Failed to update files");
5528 return FALSE;
5529 }
5531 } else if (!status_update_file(&stage_status, stage_line_type)) {
5532 report("Failed to update file");
5533 return FALSE;
5534 }
5536 return TRUE;
5537 }
5539 static bool
5540 stage_revert(struct view *view, struct line *line)
5541 {
5542 struct line *chunk = NULL;
5544 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
5545 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5547 if (chunk) {
5548 if (!prompt_yesno("Are you sure you want to revert changes?"))
5549 return FALSE;
5551 if (!stage_apply_chunk(view, chunk, TRUE)) {
5552 report("Failed to revert chunk");
5553 return FALSE;
5554 }
5555 return TRUE;
5557 } else {
5558 return status_revert(stage_status.status ? &stage_status : NULL,
5559 stage_line_type, FALSE);
5560 }
5561 }
5564 static void
5565 stage_next(struct view *view, struct line *line)
5566 {
5567 int i;
5569 if (!stage_chunks) {
5570 for (line = view->line; line < view->line + view->lines; line++) {
5571 if (line->type != LINE_DIFF_CHUNK)
5572 continue;
5574 if (!realloc_ints(&stage_chunk, stage_chunks, 1)) {
5575 report("Allocation failure");
5576 return;
5577 }
5579 stage_chunk[stage_chunks++] = line - view->line;
5580 }
5581 }
5583 for (i = 0; i < stage_chunks; i++) {
5584 if (stage_chunk[i] > view->lineno) {
5585 do_scroll_view(view, stage_chunk[i] - view->lineno);
5586 report("Chunk %d of %d", i + 1, stage_chunks);
5587 return;
5588 }
5589 }
5591 report("No next chunk found");
5592 }
5594 static enum request
5595 stage_request(struct view *view, enum request request, struct line *line)
5596 {
5597 switch (request) {
5598 case REQ_STATUS_UPDATE:
5599 if (!stage_update(view, line))
5600 return REQ_NONE;
5601 break;
5603 case REQ_STATUS_REVERT:
5604 if (!stage_revert(view, line))
5605 return REQ_NONE;
5606 break;
5608 case REQ_STAGE_NEXT:
5609 if (stage_line_type == LINE_STAT_UNTRACKED) {
5610 report("File is untracked; press %s to add",
5611 get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
5612 return REQ_NONE;
5613 }
5614 stage_next(view, line);
5615 return REQ_NONE;
5617 case REQ_EDIT:
5618 if (!stage_status.new.name[0])
5619 return request;
5620 if (stage_status.status == 'D') {
5621 report("File has been deleted.");
5622 return REQ_NONE;
5623 }
5625 open_editor(stage_status.new.name);
5626 break;
5628 case REQ_REFRESH:
5629 /* Reload everything ... */
5630 break;
5632 case REQ_VIEW_BLAME:
5633 if (stage_status.new.name[0]) {
5634 string_copy(opt_file, stage_status.new.name);
5635 opt_ref[0] = 0;
5636 }
5637 return request;
5639 case REQ_ENTER:
5640 return pager_request(view, request, line);
5642 default:
5643 return request;
5644 }
5646 VIEW(REQ_VIEW_STATUS)->p_restore = TRUE;
5647 open_view(view, REQ_VIEW_STATUS, OPEN_REFRESH);
5649 /* Check whether the staged entry still exists, and close the
5650 * stage view if it doesn't. */
5651 if (!status_exists(&stage_status, stage_line_type)) {
5652 status_restore(VIEW(REQ_VIEW_STATUS));
5653 return REQ_VIEW_CLOSE;
5654 }
5656 if (stage_line_type == LINE_STAT_UNTRACKED) {
5657 if (!suffixcmp(stage_status.new.name, -1, "/")) {
5658 report("Cannot display a directory");
5659 return REQ_NONE;
5660 }
5662 if (!prepare_update_file(view, stage_status.new.name)) {
5663 report("Failed to open file: %s", strerror(errno));
5664 return REQ_NONE;
5665 }
5666 }
5667 open_view(view, REQ_VIEW_STAGE, OPEN_REFRESH);
5669 return REQ_NONE;
5670 }
5672 static struct view_ops stage_ops = {
5673 "line",
5674 NULL,
5675 NULL,
5676 pager_read,
5677 pager_draw,
5678 stage_request,
5679 pager_grep,
5680 pager_select,
5681 };
5684 /*
5685 * Revision graph
5686 */
5688 static const enum line_type graph_colors[] = {
5689 LINE_GRAPH_LINE_0,
5690 LINE_GRAPH_LINE_1,
5691 LINE_GRAPH_LINE_2,
5692 LINE_GRAPH_LINE_3,
5693 LINE_GRAPH_LINE_4,
5694 LINE_GRAPH_LINE_5,
5695 LINE_GRAPH_LINE_6,
5696 };
5698 static enum line_type get_graph_color(struct graph_symbol *symbol)
5699 {
5700 if (symbol->commit)
5701 return LINE_GRAPH_COMMIT;
5702 assert(symbol->color < ARRAY_SIZE(graph_colors));
5703 return graph_colors[symbol->color];
5704 }
5706 static bool
5707 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5708 {
5709 const char *chars = graph_symbol_to_utf8(symbol);
5711 return draw_text(view, color, chars + !!first);
5712 }
5714 static bool
5715 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5716 {
5717 const char *chars = graph_symbol_to_ascii(symbol);
5719 return draw_text(view, color, chars + !!first);
5720 }
5722 static bool
5723 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5724 {
5725 const chtype *chars = graph_symbol_to_chtype(symbol);
5727 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
5728 }
5730 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
5732 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
5733 {
5734 static const draw_graph_fn fns[] = {
5735 draw_graph_ascii,
5736 draw_graph_chtype,
5737 draw_graph_utf8
5738 };
5739 draw_graph_fn fn = fns[opt_line_graphics];
5740 int i;
5742 for (i = 0; i < canvas->size; i++) {
5743 struct graph_symbol *symbol = &canvas->symbols[i];
5744 enum line_type color = get_graph_color(symbol);
5746 if (fn(view, symbol, color, i == 0))
5747 return TRUE;
5748 }
5750 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
5751 }
5753 /*
5754 * Main view backend
5755 */
5757 struct commit {
5758 char id[SIZEOF_REV]; /* SHA1 ID. */
5759 char title[128]; /* First line of the commit message. */
5760 const char *author; /* Author of the commit. */
5761 struct time time; /* Date from the author ident. */
5762 struct ref_list *refs; /* Repository references. */
5763 struct graph_canvas graph; /* Ancestry chain graphics. */
5764 };
5766 static const char *main_argv[SIZEOF_ARG] = {
5767 "git", "log", "--no-color", "--pretty=raw", "--parents",
5768 "--topo-order", "%(diffargs)", "%(revargs)",
5769 "--", "%(fileargs)", NULL
5770 };
5772 static bool
5773 main_draw(struct view *view, struct line *line, unsigned int lineno)
5774 {
5775 struct commit *commit = line->data;
5777 if (!commit->author)
5778 return FALSE;
5780 if (opt_date && draw_date(view, &commit->time))
5781 return TRUE;
5783 if (opt_author && draw_author(view, commit->author))
5784 return TRUE;
5786 if (opt_rev_graph && draw_graph(view, &commit->graph))
5787 return TRUE;
5789 if (opt_show_refs && commit->refs) {
5790 size_t i;
5792 for (i = 0; i < commit->refs->size; i++) {
5793 struct ref *ref = commit->refs->refs[i];
5794 enum line_type type;
5796 if (ref->head)
5797 type = LINE_MAIN_HEAD;
5798 else if (ref->ltag)
5799 type = LINE_MAIN_LOCAL_TAG;
5800 else if (ref->tag)
5801 type = LINE_MAIN_TAG;
5802 else if (ref->tracked)
5803 type = LINE_MAIN_TRACKED;
5804 else if (ref->remote)
5805 type = LINE_MAIN_REMOTE;
5806 else
5807 type = LINE_MAIN_REF;
5809 if (draw_text(view, type, "[") ||
5810 draw_text(view, type, ref->name) ||
5811 draw_text(view, type, "]"))
5812 return TRUE;
5814 if (draw_text(view, LINE_DEFAULT, " "))
5815 return TRUE;
5816 }
5817 }
5819 draw_text(view, LINE_DEFAULT, commit->title);
5820 return TRUE;
5821 }
5823 /* Reads git log --pretty=raw output and parses it into the commit struct. */
5824 static bool
5825 main_read(struct view *view, char *line)
5826 {
5827 static struct graph graph;
5828 enum line_type type;
5829 struct commit *commit;
5831 if (!line) {
5832 if (!view->lines && !view->prev)
5833 die("No revisions match the given arguments.");
5834 if (view->lines > 0) {
5835 commit = view->line[view->lines - 1].data;
5836 view->line[view->lines - 1].dirty = 1;
5837 if (!commit->author) {
5838 view->lines--;
5839 free(commit);
5840 }
5841 }
5843 done_graph(&graph);
5844 return TRUE;
5845 }
5847 type = get_line_type(line);
5848 if (type == LINE_COMMIT) {
5849 bool is_boundary;
5851 commit = calloc(1, sizeof(struct commit));
5852 if (!commit)
5853 return FALSE;
5855 line += STRING_SIZE("commit ");
5856 is_boundary = *line == '-';
5857 if (is_boundary)
5858 line++;
5860 string_copy_rev(commit->id, line);
5861 commit->refs = get_ref_list(commit->id);
5862 add_line_data(view, commit, LINE_MAIN_COMMIT);
5863 graph_add_commit(&graph, &commit->graph, commit->id, line, is_boundary);
5864 return TRUE;
5865 }
5867 if (!view->lines)
5868 return TRUE;
5869 commit = view->line[view->lines - 1].data;
5871 switch (type) {
5872 case LINE_PARENT:
5873 if (!graph.has_parents)
5874 graph_add_parent(&graph, line + STRING_SIZE("parent "));
5875 break;
5877 case LINE_AUTHOR:
5878 parse_author_line(line + STRING_SIZE("author "),
5879 &commit->author, &commit->time);
5880 graph_render_parents(&graph);
5881 break;
5883 default:
5884 /* Fill in the commit title if it has not already been set. */
5885 if (commit->title[0])
5886 break;
5888 /* Require titles to start with a non-space character at the
5889 * offset used by git log. */
5890 if (strncmp(line, " ", 4))
5891 break;
5892 line += 4;
5893 /* Well, if the title starts with a whitespace character,
5894 * try to be forgiving. Otherwise we end up with no title. */
5895 while (isspace(*line))
5896 line++;
5897 if (*line == '\0')
5898 break;
5899 /* FIXME: More graceful handling of titles; append "..." to
5900 * shortened titles, etc. */
5902 string_expand(commit->title, sizeof(commit->title), line, 1);
5903 view->line[view->lines - 1].dirty = 1;
5904 }
5906 return TRUE;
5907 }
5909 static enum request
5910 main_request(struct view *view, enum request request, struct line *line)
5911 {
5912 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5914 switch (request) {
5915 case REQ_ENTER:
5916 if (view_is_displayed(view) && display[0] != view)
5917 maximize_view(view);
5918 open_view(view, REQ_VIEW_DIFF, flags);
5919 break;
5920 case REQ_REFRESH:
5921 load_refs();
5922 open_view(view, REQ_VIEW_MAIN, OPEN_REFRESH);
5923 break;
5924 default:
5925 return request;
5926 }
5928 return REQ_NONE;
5929 }
5931 static bool
5932 grep_refs(struct ref_list *list, regex_t *regex)
5933 {
5934 regmatch_t pmatch;
5935 size_t i;
5937 if (!opt_show_refs || !list)
5938 return FALSE;
5940 for (i = 0; i < list->size; i++) {
5941 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
5942 return TRUE;
5943 }
5945 return FALSE;
5946 }
5948 static bool
5949 main_grep(struct view *view, struct line *line)
5950 {
5951 struct commit *commit = line->data;
5952 const char *text[] = {
5953 commit->title,
5954 opt_author ? commit->author : "",
5955 mkdate(&commit->time, opt_date),
5956 NULL
5957 };
5959 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
5960 }
5962 static void
5963 main_select(struct view *view, struct line *line)
5964 {
5965 struct commit *commit = line->data;
5967 string_copy_rev(view->ref, commit->id);
5968 string_copy_rev(ref_commit, view->ref);
5969 }
5971 static struct view_ops main_ops = {
5972 "commit",
5973 main_argv,
5974 NULL,
5975 main_read,
5976 main_draw,
5977 main_request,
5978 main_grep,
5979 main_select,
5980 };
5983 /*
5984 * Status management
5985 */
5987 /* Whether or not the curses interface has been initialized. */
5988 static bool cursed = FALSE;
5990 /* Terminal hacks and workarounds. */
5991 static bool use_scroll_redrawwin;
5992 static bool use_scroll_status_wclear;
5994 /* The status window is used for polling keystrokes. */
5995 static WINDOW *status_win;
5997 /* Reading from the prompt? */
5998 static bool input_mode = FALSE;
6000 static bool status_empty = FALSE;
6002 /* Update status and title window. */
6003 static void
6004 report(const char *msg, ...)
6005 {
6006 struct view *view = display[current_view];
6008 if (input_mode)
6009 return;
6011 if (!view) {
6012 char buf[SIZEOF_STR];
6013 va_list args;
6015 va_start(args, msg);
6016 if (vsnprintf(buf, sizeof(buf), msg, args) >= sizeof(buf)) {
6017 buf[sizeof(buf) - 1] = 0;
6018 buf[sizeof(buf) - 2] = '.';
6019 buf[sizeof(buf) - 3] = '.';
6020 buf[sizeof(buf) - 4] = '.';
6021 }
6022 va_end(args);
6023 die("%s", buf);
6024 }
6026 if (!status_empty || *msg) {
6027 va_list args;
6029 va_start(args, msg);
6031 wmove(status_win, 0, 0);
6032 if (view->has_scrolled && use_scroll_status_wclear)
6033 wclear(status_win);
6034 if (*msg) {
6035 vwprintw(status_win, msg, args);
6036 status_empty = FALSE;
6037 } else {
6038 status_empty = TRUE;
6039 }
6040 wclrtoeol(status_win);
6041 wnoutrefresh(status_win);
6043 va_end(args);
6044 }
6046 update_view_title(view);
6047 }
6049 static void
6050 init_display(void)
6051 {
6052 const char *term;
6053 int x, y;
6055 /* Initialize the curses library */
6056 if (isatty(STDIN_FILENO)) {
6057 cursed = !!initscr();
6058 opt_tty = stdin;
6059 } else {
6060 /* Leave stdin and stdout alone when acting as a pager. */
6061 opt_tty = fopen("/dev/tty", "r+");
6062 if (!opt_tty)
6063 die("Failed to open /dev/tty");
6064 cursed = !!newterm(NULL, opt_tty, opt_tty);
6065 }
6067 if (!cursed)
6068 die("Failed to initialize curses");
6070 nonl(); /* Disable conversion and detect newlines from input. */
6071 cbreak(); /* Take input chars one at a time, no wait for \n */
6072 noecho(); /* Don't echo input */
6073 leaveok(stdscr, FALSE);
6075 if (has_colors())
6076 init_colors();
6078 getmaxyx(stdscr, y, x);
6079 status_win = newwin(1, x, y - 1, 0);
6080 if (!status_win)
6081 die("Failed to create status window");
6083 /* Enable keyboard mapping */
6084 keypad(status_win, TRUE);
6085 wbkgdset(status_win, get_line_attr(LINE_STATUS));
6087 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6088 set_tabsize(opt_tab_size);
6089 #else
6090 TABSIZE = opt_tab_size;
6091 #endif
6093 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6094 if (term && !strcmp(term, "gnome-terminal")) {
6095 /* In the gnome-terminal-emulator, the message from
6096 * scrolling up one line when impossible followed by
6097 * scrolling down one line causes corruption of the
6098 * status line. This is fixed by calling wclear. */
6099 use_scroll_status_wclear = TRUE;
6100 use_scroll_redrawwin = FALSE;
6102 } else if (term && !strcmp(term, "xrvt-xpm")) {
6103 /* No problems with full optimizations in xrvt-(unicode)
6104 * and aterm. */
6105 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6107 } else {
6108 /* When scrolling in (u)xterm the last line in the
6109 * scrolling direction will update slowly. */
6110 use_scroll_redrawwin = TRUE;
6111 use_scroll_status_wclear = FALSE;
6112 }
6113 }
6115 static int
6116 get_input(int prompt_position)
6117 {
6118 struct view *view;
6119 int i, key, cursor_y, cursor_x;
6121 if (prompt_position)
6122 input_mode = TRUE;
6124 while (TRUE) {
6125 bool loading = FALSE;
6127 foreach_view (view, i) {
6128 update_view(view);
6129 if (view_is_displayed(view) && view->has_scrolled &&
6130 use_scroll_redrawwin)
6131 redrawwin(view->win);
6132 view->has_scrolled = FALSE;
6133 if (view->pipe)
6134 loading = TRUE;
6135 }
6137 /* Update the cursor position. */
6138 if (prompt_position) {
6139 getbegyx(status_win, cursor_y, cursor_x);
6140 cursor_x = prompt_position;
6141 } else {
6142 view = display[current_view];
6143 getbegyx(view->win, cursor_y, cursor_x);
6144 cursor_x = view->width - 1;
6145 cursor_y += view->lineno - view->offset;
6146 }
6147 setsyx(cursor_y, cursor_x);
6149 /* Refresh, accept single keystroke of input */
6150 doupdate();
6151 nodelay(status_win, loading);
6152 key = wgetch(status_win);
6154 /* wgetch() with nodelay() enabled returns ERR when
6155 * there's no input. */
6156 if (key == ERR) {
6158 } else if (key == KEY_RESIZE) {
6159 int height, width;
6161 getmaxyx(stdscr, height, width);
6163 wresize(status_win, 1, width);
6164 mvwin(status_win, height - 1, 0);
6165 wnoutrefresh(status_win);
6166 resize_display();
6167 redraw_display(TRUE);
6169 } else {
6170 input_mode = FALSE;
6171 return key;
6172 }
6173 }
6174 }
6176 static char *
6177 prompt_input(const char *prompt, input_handler handler, void *data)
6178 {
6179 enum input_status status = INPUT_OK;
6180 static char buf[SIZEOF_STR];
6181 size_t pos = 0;
6183 buf[pos] = 0;
6185 while (status == INPUT_OK || status == INPUT_SKIP) {
6186 int key;
6188 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6189 wclrtoeol(status_win);
6191 key = get_input(pos + 1);
6192 switch (key) {
6193 case KEY_RETURN:
6194 case KEY_ENTER:
6195 case '\n':
6196 status = pos ? INPUT_STOP : INPUT_CANCEL;
6197 break;
6199 case KEY_BACKSPACE:
6200 if (pos > 0)
6201 buf[--pos] = 0;
6202 else
6203 status = INPUT_CANCEL;
6204 break;
6206 case KEY_ESC:
6207 status = INPUT_CANCEL;
6208 break;
6210 default:
6211 if (pos >= sizeof(buf)) {
6212 report("Input string too long");
6213 return NULL;
6214 }
6216 status = handler(data, buf, key);
6217 if (status == INPUT_OK)
6218 buf[pos++] = (char) key;
6219 }
6220 }
6222 /* Clear the status window */
6223 status_empty = FALSE;
6224 report("");
6226 if (status == INPUT_CANCEL)
6227 return NULL;
6229 buf[pos++] = 0;
6231 return buf;
6232 }
6234 static enum input_status
6235 prompt_yesno_handler(void *data, char *buf, int c)
6236 {
6237 if (c == 'y' || c == 'Y')
6238 return INPUT_STOP;
6239 if (c == 'n' || c == 'N')
6240 return INPUT_CANCEL;
6241 return INPUT_SKIP;
6242 }
6244 static bool
6245 prompt_yesno(const char *prompt)
6246 {
6247 char prompt2[SIZEOF_STR];
6249 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6250 return FALSE;
6252 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6253 }
6255 static enum input_status
6256 read_prompt_handler(void *data, char *buf, int c)
6257 {
6258 return isprint(c) ? INPUT_OK : INPUT_SKIP;
6259 }
6261 static char *
6262 read_prompt(const char *prompt)
6263 {
6264 return prompt_input(prompt, read_prompt_handler, NULL);
6265 }
6267 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6268 {
6269 enum input_status status = INPUT_OK;
6270 int size = 0;
6272 while (items[size].text)
6273 size++;
6275 while (status == INPUT_OK) {
6276 const struct menu_item *item = &items[*selected];
6277 int key;
6278 int i;
6280 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6281 prompt, *selected + 1, size);
6282 if (item->hotkey)
6283 wprintw(status_win, "[%c] ", (char) item->hotkey);
6284 wprintw(status_win, "%s", item->text);
6285 wclrtoeol(status_win);
6287 key = get_input(COLS - 1);
6288 switch (key) {
6289 case KEY_RETURN:
6290 case KEY_ENTER:
6291 case '\n':
6292 status = INPUT_STOP;
6293 break;
6295 case KEY_LEFT:
6296 case KEY_UP:
6297 *selected = *selected - 1;
6298 if (*selected < 0)
6299 *selected = size - 1;
6300 break;
6302 case KEY_RIGHT:
6303 case KEY_DOWN:
6304 *selected = (*selected + 1) % size;
6305 break;
6307 case KEY_ESC:
6308 status = INPUT_CANCEL;
6309 break;
6311 default:
6312 for (i = 0; items[i].text; i++)
6313 if (items[i].hotkey == key) {
6314 *selected = i;
6315 status = INPUT_STOP;
6316 break;
6317 }
6318 }
6319 }
6321 /* Clear the status window */
6322 status_empty = FALSE;
6323 report("");
6325 return status != INPUT_CANCEL;
6326 }
6328 /*
6329 * Repository properties
6330 */
6332 static struct ref **refs = NULL;
6333 static size_t refs_size = 0;
6334 static struct ref *refs_head = NULL;
6336 static struct ref_list **ref_lists = NULL;
6337 static size_t ref_lists_size = 0;
6339 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
6340 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
6341 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
6343 static int
6344 compare_refs(const void *ref1_, const void *ref2_)
6345 {
6346 const struct ref *ref1 = *(const struct ref **)ref1_;
6347 const struct ref *ref2 = *(const struct ref **)ref2_;
6349 if (ref1->tag != ref2->tag)
6350 return ref2->tag - ref1->tag;
6351 if (ref1->ltag != ref2->ltag)
6352 return ref2->ltag - ref2->ltag;
6353 if (ref1->head != ref2->head)
6354 return ref2->head - ref1->head;
6355 if (ref1->tracked != ref2->tracked)
6356 return ref2->tracked - ref1->tracked;
6357 if (ref1->remote != ref2->remote)
6358 return ref2->remote - ref1->remote;
6359 return strcmp(ref1->name, ref2->name);
6360 }
6362 static void
6363 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
6364 {
6365 size_t i;
6367 for (i = 0; i < refs_size; i++)
6368 if (!visitor(data, refs[i]))
6369 break;
6370 }
6372 static struct ref *
6373 get_ref_head()
6374 {
6375 return refs_head;
6376 }
6378 static struct ref_list *
6379 get_ref_list(const char *id)
6380 {
6381 struct ref_list *list;
6382 size_t i;
6384 for (i = 0; i < ref_lists_size; i++)
6385 if (!strcmp(id, ref_lists[i]->id))
6386 return ref_lists[i];
6388 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
6389 return NULL;
6390 list = calloc(1, sizeof(*list));
6391 if (!list)
6392 return NULL;
6394 for (i = 0; i < refs_size; i++) {
6395 if (!strcmp(id, refs[i]->id) &&
6396 realloc_refs_list(&list->refs, list->size, 1))
6397 list->refs[list->size++] = refs[i];
6398 }
6400 if (!list->refs) {
6401 free(list);
6402 return NULL;
6403 }
6405 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
6406 ref_lists[ref_lists_size++] = list;
6407 return list;
6408 }
6410 static int
6411 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
6412 {
6413 struct ref *ref = NULL;
6414 bool tag = FALSE;
6415 bool ltag = FALSE;
6416 bool remote = FALSE;
6417 bool tracked = FALSE;
6418 bool head = FALSE;
6419 int from = 0, to = refs_size - 1;
6421 if (!prefixcmp(name, "refs/tags/")) {
6422 if (!suffixcmp(name, namelen, "^{}")) {
6423 namelen -= 3;
6424 name[namelen] = 0;
6425 } else {
6426 ltag = TRUE;
6427 }
6429 tag = TRUE;
6430 namelen -= STRING_SIZE("refs/tags/");
6431 name += STRING_SIZE("refs/tags/");
6433 } else if (!prefixcmp(name, "refs/remotes/")) {
6434 remote = TRUE;
6435 namelen -= STRING_SIZE("refs/remotes/");
6436 name += STRING_SIZE("refs/remotes/");
6437 tracked = !strcmp(opt_remote, name);
6439 } else if (!prefixcmp(name, "refs/heads/")) {
6440 namelen -= STRING_SIZE("refs/heads/");
6441 name += STRING_SIZE("refs/heads/");
6442 if (!strncmp(opt_head, name, namelen))
6443 return OK;
6445 } else if (!strcmp(name, "HEAD")) {
6446 head = TRUE;
6447 if (*opt_head) {
6448 namelen = strlen(opt_head);
6449 name = opt_head;
6450 }
6451 }
6453 /* If we are reloading or it's an annotated tag, replace the
6454 * previous SHA1 with the resolved commit id; relies on the fact
6455 * git-ls-remote lists the commit id of an annotated tag right
6456 * before the commit id it points to. */
6457 while (from <= to) {
6458 size_t pos = (to + from) / 2;
6459 int cmp = strcmp(name, refs[pos]->name);
6461 if (!cmp) {
6462 ref = refs[pos];
6463 break;
6464 }
6466 if (cmp < 0)
6467 to = pos - 1;
6468 else
6469 from = pos + 1;
6470 }
6472 if (!ref) {
6473 if (!realloc_refs(&refs, refs_size, 1))
6474 return ERR;
6475 ref = calloc(1, sizeof(*ref) + namelen);
6476 if (!ref)
6477 return ERR;
6478 memmove(refs + from + 1, refs + from,
6479 (refs_size - from) * sizeof(*refs));
6480 refs[from] = ref;
6481 strncpy(ref->name, name, namelen);
6482 refs_size++;
6483 }
6485 ref->head = head;
6486 ref->tag = tag;
6487 ref->ltag = ltag;
6488 ref->remote = remote;
6489 ref->tracked = tracked;
6490 string_copy_rev(ref->id, id);
6492 if (head)
6493 refs_head = ref;
6494 return OK;
6495 }
6497 static int
6498 load_refs(void)
6499 {
6500 const char *head_argv[] = {
6501 "git", "symbolic-ref", "HEAD", NULL
6502 };
6503 static const char *ls_remote_argv[SIZEOF_ARG] = {
6504 "git", "ls-remote", opt_git_dir, NULL
6505 };
6506 static bool init = FALSE;
6507 size_t i;
6509 if (!init) {
6510 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
6511 die("TIG_LS_REMOTE contains too many arguments");
6512 init = TRUE;
6513 }
6515 if (!*opt_git_dir)
6516 return OK;
6518 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
6519 !prefixcmp(opt_head, "refs/heads/")) {
6520 char *offset = opt_head + STRING_SIZE("refs/heads/");
6522 memmove(opt_head, offset, strlen(offset) + 1);
6523 }
6525 refs_head = NULL;
6526 for (i = 0; i < refs_size; i++)
6527 refs[i]->id[0] = 0;
6529 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
6530 return ERR;
6532 /* Update the ref lists to reflect changes. */
6533 for (i = 0; i < ref_lists_size; i++) {
6534 struct ref_list *list = ref_lists[i];
6535 size_t old, new;
6537 for (old = new = 0; old < list->size; old++)
6538 if (!strcmp(list->id, list->refs[old]->id))
6539 list->refs[new++] = list->refs[old];
6540 list->size = new;
6541 }
6543 return OK;
6544 }
6546 static void
6547 set_remote_branch(const char *name, const char *value, size_t valuelen)
6548 {
6549 if (!strcmp(name, ".remote")) {
6550 string_ncopy(opt_remote, value, valuelen);
6552 } else if (*opt_remote && !strcmp(name, ".merge")) {
6553 size_t from = strlen(opt_remote);
6555 if (!prefixcmp(value, "refs/heads/"))
6556 value += STRING_SIZE("refs/heads/");
6558 if (!string_format_from(opt_remote, &from, "/%s", value))
6559 opt_remote[0] = 0;
6560 }
6561 }
6563 static void
6564 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
6565 {
6566 const char *argv[SIZEOF_ARG] = { name, "=" };
6567 int argc = 1 + (cmd == option_set_command);
6568 enum option_code error;
6570 if (!argv_from_string(argv, &argc, value))
6571 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
6572 else
6573 error = cmd(argc, argv);
6575 if (error != OPT_OK)
6576 warn("Option 'tig.%s': %s", name, option_errors[error]);
6577 }
6579 static bool
6580 set_environment_variable(const char *name, const char *value)
6581 {
6582 size_t len = strlen(name) + 1 + strlen(value) + 1;
6583 char *env = malloc(len);
6585 if (env &&
6586 string_nformat(env, len, NULL, "%s=%s", name, value) &&
6587 putenv(env) == 0)
6588 return TRUE;
6589 free(env);
6590 return FALSE;
6591 }
6593 static void
6594 set_work_tree(const char *value)
6595 {
6596 char cwd[SIZEOF_STR];
6598 if (!getcwd(cwd, sizeof(cwd)))
6599 die("Failed to get cwd path: %s", strerror(errno));
6600 if (chdir(opt_git_dir) < 0)
6601 die("Failed to chdir(%s): %s", strerror(errno));
6602 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
6603 die("Failed to get git path: %s", strerror(errno));
6604 if (chdir(cwd) < 0)
6605 die("Failed to chdir(%s): %s", cwd, strerror(errno));
6606 if (chdir(value) < 0)
6607 die("Failed to chdir(%s): %s", value, strerror(errno));
6608 if (!getcwd(cwd, sizeof(cwd)))
6609 die("Failed to get cwd path: %s", strerror(errno));
6610 if (!set_environment_variable("GIT_WORK_TREE", cwd))
6611 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
6612 if (!set_environment_variable("GIT_DIR", opt_git_dir))
6613 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
6614 opt_is_inside_work_tree = TRUE;
6615 }
6617 static int
6618 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6619 {
6620 if (!strcmp(name, "i18n.commitencoding"))
6621 string_ncopy(opt_encoding, value, valuelen);
6623 else if (!strcmp(name, "core.editor"))
6624 string_ncopy(opt_editor, value, valuelen);
6626 else if (!strcmp(name, "core.worktree"))
6627 set_work_tree(value);
6629 else if (!prefixcmp(name, "tig.color."))
6630 set_repo_config_option(name + 10, value, option_color_command);
6632 else if (!prefixcmp(name, "tig.bind."))
6633 set_repo_config_option(name + 9, value, option_bind_command);
6635 else if (!prefixcmp(name, "tig."))
6636 set_repo_config_option(name + 4, value, option_set_command);
6638 else if (*opt_head && !prefixcmp(name, "branch.") &&
6639 !strncmp(name + 7, opt_head, strlen(opt_head)))
6640 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
6642 return OK;
6643 }
6645 static int
6646 load_git_config(void)
6647 {
6648 const char *config_list_argv[] = { "git", "config", "--list", NULL };
6650 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
6651 }
6653 static int
6654 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6655 {
6656 if (!opt_git_dir[0]) {
6657 string_ncopy(opt_git_dir, name, namelen);
6659 } else if (opt_is_inside_work_tree == -1) {
6660 /* This can be 3 different values depending on the
6661 * version of git being used. If git-rev-parse does not
6662 * understand --is-inside-work-tree it will simply echo
6663 * the option else either "true" or "false" is printed.
6664 * Default to true for the unknown case. */
6665 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
6667 } else if (*name == '.') {
6668 string_ncopy(opt_cdup, name, namelen);
6670 } else {
6671 string_ncopy(opt_prefix, name, namelen);
6672 }
6674 return OK;
6675 }
6677 static int
6678 load_repo_info(void)
6679 {
6680 const char *rev_parse_argv[] = {
6681 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
6682 "--show-cdup", "--show-prefix", NULL
6683 };
6685 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
6686 }
6689 /*
6690 * Main
6691 */
6693 static const char usage[] =
6694 "tig " TIG_VERSION " (" __DATE__ ")\n"
6695 "\n"
6696 "Usage: tig [options] [revs] [--] [paths]\n"
6697 " or: tig show [options] [revs] [--] [paths]\n"
6698 " or: tig blame [rev] path\n"
6699 " or: tig status\n"
6700 " or: tig < [git command output]\n"
6701 "\n"
6702 "Options:\n"
6703 " -v, --version Show version and exit\n"
6704 " -h, --help Show help message and exit";
6706 static void __NORETURN
6707 quit(int sig)
6708 {
6709 /* XXX: Restore tty modes and let the OS cleanup the rest! */
6710 if (cursed)
6711 endwin();
6712 exit(0);
6713 }
6715 static void __NORETURN
6716 die(const char *err, ...)
6717 {
6718 va_list args;
6720 endwin();
6722 va_start(args, err);
6723 fputs("tig: ", stderr);
6724 vfprintf(stderr, err, args);
6725 fputs("\n", stderr);
6726 va_end(args);
6728 exit(1);
6729 }
6731 static void
6732 warn(const char *msg, ...)
6733 {
6734 va_list args;
6736 va_start(args, msg);
6737 fputs("tig warning: ", stderr);
6738 vfprintf(stderr, msg, args);
6739 fputs("\n", stderr);
6740 va_end(args);
6741 }
6743 static int
6744 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6745 {
6746 const char ***filter_args = data;
6748 return argv_append(filter_args, name) ? OK : ERR;
6749 }
6751 static void
6752 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
6753 {
6754 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
6755 const char **all_argv = NULL;
6757 if (!argv_append_array(&all_argv, rev_parse_argv) ||
6758 !argv_append_array(&all_argv, argv) ||
6759 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
6760 die("Failed to split arguments");
6761 argv_free(all_argv);
6762 free(all_argv);
6763 }
6765 static void
6766 filter_options(const char *argv[])
6767 {
6768 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
6769 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
6770 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
6771 }
6773 static enum request
6774 parse_options(int argc, const char *argv[])
6775 {
6776 enum request request = REQ_VIEW_MAIN;
6777 const char *subcommand;
6778 bool seen_dashdash = FALSE;
6779 const char **filter_argv = NULL;
6780 int i;
6782 if (!isatty(STDIN_FILENO))
6783 return REQ_VIEW_PAGER;
6785 if (argc <= 1)
6786 return REQ_VIEW_MAIN;
6788 subcommand = argv[1];
6789 if (!strcmp(subcommand, "status")) {
6790 if (argc > 2)
6791 warn("ignoring arguments after `%s'", subcommand);
6792 return REQ_VIEW_STATUS;
6794 } else if (!strcmp(subcommand, "blame")) {
6795 if (argc <= 2 || argc > 4)
6796 die("invalid number of options to blame\n\n%s", usage);
6798 i = 2;
6799 if (argc == 4) {
6800 string_ncopy(opt_ref, argv[i], strlen(argv[i]));
6801 i++;
6802 }
6804 string_ncopy(opt_file, argv[i], strlen(argv[i]));
6805 return REQ_VIEW_BLAME;
6807 } else if (!strcmp(subcommand, "show")) {
6808 request = REQ_VIEW_DIFF;
6810 } else {
6811 subcommand = NULL;
6812 }
6814 for (i = 1 + !!subcommand; i < argc; i++) {
6815 const char *opt = argv[i];
6817 if (seen_dashdash) {
6818 argv_append(&opt_file_argv, opt);
6819 continue;
6821 } else if (!strcmp(opt, "--")) {
6822 seen_dashdash = TRUE;
6823 continue;
6825 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
6826 printf("tig version %s\n", TIG_VERSION);
6827 quit(0);
6829 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
6830 printf("%s\n", usage);
6831 quit(0);
6833 } else if (!strcmp(opt, "--all")) {
6834 argv_append(&opt_rev_argv, opt);
6835 continue;
6836 }
6838 if (!argv_append(&filter_argv, opt))
6839 die("command too long");
6840 }
6842 if (filter_argv)
6843 filter_options(filter_argv);
6845 return request;
6846 }
6848 int
6849 main(int argc, const char *argv[])
6850 {
6851 const char *codeset = "UTF-8";
6852 enum request request = parse_options(argc, argv);
6853 struct view *view;
6854 size_t i;
6856 signal(SIGINT, quit);
6857 signal(SIGPIPE, SIG_IGN);
6859 if (setlocale(LC_ALL, "")) {
6860 codeset = nl_langinfo(CODESET);
6861 }
6863 if (load_repo_info() == ERR)
6864 die("Failed to load repo info.");
6866 if (load_options() == ERR)
6867 die("Failed to load user config.");
6869 if (load_git_config() == ERR)
6870 die("Failed to load repo config.");
6872 /* Require a git repository unless when running in pager mode. */
6873 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
6874 die("Not a git repository");
6876 if (*opt_encoding && strcmp(codeset, "UTF-8")) {
6877 opt_iconv_in = iconv_open("UTF-8", opt_encoding);
6878 if (opt_iconv_in == ICONV_NONE)
6879 die("Failed to initialize character set conversion");
6880 }
6882 if (codeset && strcmp(codeset, "UTF-8")) {
6883 opt_iconv_out = iconv_open(codeset, "UTF-8");
6884 if (opt_iconv_out == ICONV_NONE)
6885 die("Failed to initialize character set conversion");
6886 }
6888 if (load_refs() == ERR)
6889 die("Failed to load refs.");
6891 foreach_view (view, i) {
6892 if (getenv(view->cmd_env))
6893 warn("Use of the %s environment variable is deprecated,"
6894 " use options or TIG_DIFF_ARGS instead",
6895 view->cmd_env);
6896 if (!argv_from_env(view->ops->argv, view->cmd_env))
6897 die("Too many arguments in the `%s` environment variable",
6898 view->cmd_env);
6899 }
6901 init_display();
6903 while (view_driver(display[current_view], request)) {
6904 int key = get_input(0);
6906 view = display[current_view];
6907 request = get_keybinding(view->keymap, key);
6909 /* Some low-level request handling. This keeps access to
6910 * status_win restricted. */
6911 switch (request) {
6912 case REQ_NONE:
6913 report("Unknown key, press %s for help",
6914 get_key(view->keymap, REQ_VIEW_HELP));
6915 break;
6916 case REQ_PROMPT:
6917 {
6918 char *cmd = read_prompt(":");
6920 if (cmd && isdigit(*cmd)) {
6921 int lineno = view->lineno + 1;
6923 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OK) {
6924 select_view_line(view, lineno - 1);
6925 report("");
6926 } else {
6927 report("Unable to parse '%s' as a line number", cmd);
6928 }
6930 } else if (cmd) {
6931 struct view *next = VIEW(REQ_VIEW_PAGER);
6932 const char *argv[SIZEOF_ARG] = { "git" };
6933 int argc = 1;
6935 /* When running random commands, initially show the
6936 * command in the title. However, it maybe later be
6937 * overwritten if a commit line is selected. */
6938 string_ncopy(next->ref, cmd, strlen(cmd));
6940 if (!argv_from_string(argv, &argc, cmd)) {
6941 report("Too many arguments");
6942 } else if (!prepare_update(next, argv, NULL)) {
6943 report("Failed to format command");
6944 } else {
6945 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
6946 }
6947 }
6949 request = REQ_NONE;
6950 break;
6951 }
6952 case REQ_SEARCH:
6953 case REQ_SEARCH_BACK:
6954 {
6955 const char *prompt = request == REQ_SEARCH ? "/" : "?";
6956 char *search = read_prompt(prompt);
6958 if (search)
6959 string_ncopy(opt_search, search, strlen(search));
6960 else if (*opt_search)
6961 request = request == REQ_SEARCH ?
6962 REQ_FIND_NEXT :
6963 REQ_FIND_PREV;
6964 else
6965 request = REQ_NONE;
6966 break;
6967 }
6968 default:
6969 break;
6970 }
6971 }
6973 quit(0);
6975 return 0;
6976 }