f56547455c50dcf170dbdb0f8424915a9db2c40e
1 /* Copyright (c) 2006-2010 Jonas Fonseca <fonseca@diku.dk>
2 *
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU General Public License as
5 * published by the Free Software Foundation; either version 2 of
6 * the License, or (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 */
14 #include "tig.h"
15 #include "io.h"
16 #include "graph.h"
18 static void __NORETURN die(const char *err, ...);
19 static void warn(const char *msg, ...);
20 static void report(const char *msg, ...);
23 struct ref {
24 char id[SIZEOF_REV]; /* Commit SHA1 ID */
25 unsigned int head:1; /* Is it the current HEAD? */
26 unsigned int tag:1; /* Is it a tag? */
27 unsigned int ltag:1; /* If so, is the tag local? */
28 unsigned int remote:1; /* Is it a remote ref? */
29 unsigned int tracked:1; /* Is it the remote for the current HEAD? */
30 char name[1]; /* Ref name; tag or head names are shortened. */
31 };
33 struct ref_list {
34 char id[SIZEOF_REV]; /* Commit SHA1 ID */
35 size_t size; /* Number of refs. */
36 struct ref **refs; /* References for this ID. */
37 };
39 static struct ref *get_ref_head();
40 static struct ref_list *get_ref_list(const char *id);
41 static void foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data);
42 static int load_refs(void);
44 enum input_status {
45 INPUT_OK,
46 INPUT_SKIP,
47 INPUT_STOP,
48 INPUT_CANCEL
49 };
51 typedef enum input_status (*input_handler)(void *data, char *buf, int c);
53 static char *prompt_input(const char *prompt, input_handler handler, void *data);
54 static bool prompt_yesno(const char *prompt);
56 struct menu_item {
57 int hotkey;
58 const char *text;
59 void *data;
60 };
62 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected);
64 enum graphic {
65 GRAPHIC_ASCII = 0,
66 GRAPHIC_DEFAULT,
67 GRAPHIC_UTF8
68 };
70 static const struct enum_map graphic_map[] = {
71 #define GRAPHIC_(name) ENUM_MAP(#name, GRAPHIC_##name)
72 GRAPHIC_(ASCII),
73 GRAPHIC_(DEFAULT),
74 GRAPHIC_(UTF8)
75 #undef GRAPHIC_
76 };
78 #define DATE_INFO \
79 DATE_(NO), \
80 DATE_(DEFAULT), \
81 DATE_(LOCAL), \
82 DATE_(RELATIVE), \
83 DATE_(SHORT)
85 enum date {
86 #define DATE_(name) DATE_##name
87 DATE_INFO
88 #undef DATE_
89 };
91 static const struct enum_map date_map[] = {
92 #define DATE_(name) ENUM_MAP(#name, DATE_##name)
93 DATE_INFO
94 #undef DATE_
95 };
97 struct time {
98 time_t sec;
99 int tz;
100 };
102 static inline int timecmp(const struct time *t1, const struct time *t2)
103 {
104 return t1->sec - t2->sec;
105 }
107 static const char *
108 mkdate(const struct time *time, enum date date)
109 {
110 static char buf[DATE_COLS + 1];
111 static const struct enum_map reldate[] = {
112 { "second", 1, 60 * 2 },
113 { "minute", 60, 60 * 60 * 2 },
114 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
115 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
116 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
117 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 30 * 12 },
118 };
119 struct tm tm;
121 if (!date || !time || !time->sec)
122 return "";
124 if (date == DATE_RELATIVE) {
125 struct timeval now;
126 time_t date = time->sec + time->tz;
127 time_t seconds;
128 int i;
130 gettimeofday(&now, NULL);
131 seconds = now.tv_sec < date ? date - now.tv_sec : now.tv_sec - date;
132 for (i = 0; i < ARRAY_SIZE(reldate); i++) {
133 if (seconds >= reldate[i].value)
134 continue;
136 seconds /= reldate[i].namelen;
137 if (!string_format(buf, "%ld %s%s %s",
138 seconds, reldate[i].name,
139 seconds > 1 ? "s" : "",
140 now.tv_sec >= date ? "ago" : "ahead"))
141 break;
142 return buf;
143 }
144 }
146 if (date == DATE_LOCAL) {
147 time_t date = time->sec + time->tz;
148 localtime_r(&date, &tm);
149 }
150 else {
151 gmtime_r(&time->sec, &tm);
152 }
153 return strftime(buf, sizeof(buf), DATE_FORMAT, &tm) ? buf : NULL;
154 }
157 #define AUTHOR_VALUES \
158 AUTHOR_(NO), \
159 AUTHOR_(FULL), \
160 AUTHOR_(ABBREVIATED)
162 enum author {
163 #define AUTHOR_(name) AUTHOR_##name
164 AUTHOR_VALUES,
165 #undef AUTHOR_
166 AUTHOR_DEFAULT = AUTHOR_FULL
167 };
169 static const struct enum_map author_map[] = {
170 #define AUTHOR_(name) ENUM_MAP(#name, AUTHOR_##name)
171 AUTHOR_VALUES
172 #undef AUTHOR_
173 };
175 static const char *
176 get_author_initials(const char *author)
177 {
178 static char initials[AUTHOR_COLS * 6 + 1];
179 size_t pos = 0;
180 const char *end = strchr(author, '\0');
182 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
184 memset(initials, 0, sizeof(initials));
185 while (author < end) {
186 unsigned char bytes;
187 size_t i;
189 while (is_initial_sep(*author))
190 author++;
192 bytes = utf8_char_length(author, end);
193 if (bytes < sizeof(initials) - 1 - pos) {
194 while (bytes--) {
195 initials[pos++] = *author++;
196 }
197 }
199 for (i = pos; author < end && !is_initial_sep(*author); author++) {
200 if (i < sizeof(initials) - 1)
201 initials[i++] = *author;
202 }
204 initials[i++] = 0;
205 }
207 return initials;
208 }
211 /*
212 * User requests
213 */
215 #define REQ_INFO \
216 /* XXX: Keep the view request first and in sync with views[]. */ \
217 REQ_GROUP("View switching") \
218 REQ_(VIEW_MAIN, "Show main view"), \
219 REQ_(VIEW_DIFF, "Show diff view"), \
220 REQ_(VIEW_LOG, "Show log view"), \
221 REQ_(VIEW_TREE, "Show tree view"), \
222 REQ_(VIEW_BLOB, "Show blob view"), \
223 REQ_(VIEW_BLAME, "Show blame view"), \
224 REQ_(VIEW_BRANCH, "Show branch view"), \
225 REQ_(VIEW_HELP, "Show help page"), \
226 REQ_(VIEW_PAGER, "Show pager view"), \
227 REQ_(VIEW_STATUS, "Show status view"), \
228 REQ_(VIEW_STAGE, "Show stage view"), \
229 \
230 REQ_GROUP("View manipulation") \
231 REQ_(ENTER, "Enter current line and scroll"), \
232 REQ_(NEXT, "Move to next"), \
233 REQ_(PREVIOUS, "Move to previous"), \
234 REQ_(PARENT, "Move to parent"), \
235 REQ_(VIEW_NEXT, "Move focus to next view"), \
236 REQ_(REFRESH, "Reload and refresh"), \
237 REQ_(MAXIMIZE, "Maximize the current view"), \
238 REQ_(VIEW_CLOSE, "Close the current view"), \
239 REQ_(QUIT, "Close all views and quit"), \
240 \
241 REQ_GROUP("View specific requests") \
242 REQ_(STATUS_UPDATE, "Update file status"), \
243 REQ_(STATUS_REVERT, "Revert file changes"), \
244 REQ_(STATUS_MERGE, "Merge file using external tool"), \
245 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
246 \
247 REQ_GROUP("Cursor navigation") \
248 REQ_(MOVE_UP, "Move cursor one line up"), \
249 REQ_(MOVE_DOWN, "Move cursor one line down"), \
250 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
251 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
252 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
253 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
254 \
255 REQ_GROUP("Scrolling") \
256 REQ_(SCROLL_FIRST_COL, "Scroll to the first line columns"), \
257 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
258 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
259 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
260 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
261 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
262 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
263 \
264 REQ_GROUP("Searching") \
265 REQ_(SEARCH, "Search the view"), \
266 REQ_(SEARCH_BACK, "Search backwards in the view"), \
267 REQ_(FIND_NEXT, "Find next search match"), \
268 REQ_(FIND_PREV, "Find previous search match"), \
269 \
270 REQ_GROUP("Option manipulation") \
271 REQ_(OPTIONS, "Open option menu"), \
272 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
273 REQ_(TOGGLE_DATE, "Toggle date display"), \
274 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
275 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
276 REQ_(TOGGLE_GRAPHIC, "Toggle (line) graphics mode"), \
277 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
278 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
279 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
280 \
281 REQ_GROUP("Misc") \
282 REQ_(PROMPT, "Bring up the prompt"), \
283 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
284 REQ_(SHOW_VERSION, "Show version information"), \
285 REQ_(STOP_LOADING, "Stop all loading views"), \
286 REQ_(EDIT, "Open in editor"), \
287 REQ_(NONE, "Do nothing")
290 /* User action requests. */
291 enum request {
292 #define REQ_GROUP(help)
293 #define REQ_(req, help) REQ_##req
295 /* Offset all requests to avoid conflicts with ncurses getch values. */
296 REQ_UNKNOWN = KEY_MAX + 1,
297 REQ_OFFSET,
298 REQ_INFO
300 #undef REQ_GROUP
301 #undef REQ_
302 };
304 struct request_info {
305 enum request request;
306 const char *name;
307 int namelen;
308 const char *help;
309 };
311 static const struct request_info req_info[] = {
312 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
313 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
314 REQ_INFO
315 #undef REQ_GROUP
316 #undef REQ_
317 };
319 static enum request
320 get_request(const char *name)
321 {
322 int namelen = strlen(name);
323 int i;
325 for (i = 0; i < ARRAY_SIZE(req_info); i++)
326 if (enum_equals(req_info[i], name, namelen))
327 return req_info[i].request;
329 return REQ_UNKNOWN;
330 }
333 /*
334 * Options
335 */
337 /* Option and state variables. */
338 static enum graphic opt_line_graphics = GRAPHIC_DEFAULT;
339 static enum date opt_date = DATE_DEFAULT;
340 static enum author opt_author = AUTHOR_DEFAULT;
341 static bool opt_rev_graph = TRUE;
342 static bool opt_line_number = FALSE;
343 static bool opt_show_refs = TRUE;
344 static bool opt_untracked_dirs_content = TRUE;
345 static int opt_num_interval = 5;
346 static double opt_hscroll = 0.50;
347 static double opt_scale_split_view = 2.0 / 3.0;
348 static int opt_tab_size = 8;
349 static int opt_author_cols = AUTHOR_COLS;
350 static char opt_path[SIZEOF_STR] = "";
351 static char opt_file[SIZEOF_STR] = "";
352 static char opt_ref[SIZEOF_REF] = "";
353 static char opt_head[SIZEOF_REF] = "";
354 static char opt_remote[SIZEOF_REF] = "";
355 static char opt_encoding[20] = "UTF-8";
356 static iconv_t opt_iconv_in = ICONV_NONE;
357 static iconv_t opt_iconv_out = ICONV_NONE;
358 static char opt_search[SIZEOF_STR] = "";
359 static char opt_cdup[SIZEOF_STR] = "";
360 static char opt_prefix[SIZEOF_STR] = "";
361 static char opt_git_dir[SIZEOF_STR] = "";
362 static signed char opt_is_inside_work_tree = -1; /* set to TRUE or FALSE */
363 static char opt_editor[SIZEOF_STR] = "";
364 static FILE *opt_tty = NULL;
365 static const char **opt_diff_argv = NULL;
366 static const char **opt_rev_argv = NULL;
367 static const char **opt_file_argv = NULL;
368 static const char **opt_blame_argv = NULL;
370 #define is_initial_commit() (!get_ref_head())
371 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
374 /*
375 * Line-oriented content detection.
376 */
378 #define LINE_INFO \
379 LINE(DIFF_HEADER, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
380 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
381 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
382 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
383 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
384 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
385 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
386 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
387 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
388 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
389 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
390 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
391 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
392 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
393 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
394 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
395 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
396 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
397 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
398 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
399 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
400 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
401 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
402 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
403 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
404 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
405 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
406 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
407 LINE(TESTED, " Tested-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
408 LINE(REVIEWED, " Reviewed-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
409 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
410 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
411 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
412 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
413 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
414 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
415 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
416 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
417 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
418 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
419 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
420 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
421 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
422 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
423 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
424 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
425 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
426 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
427 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
428 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
429 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
430 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
431 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
432 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
433 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
434 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
435 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
436 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
437 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
438 LINE(GRAPH_LINE_0, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
439 LINE(GRAPH_LINE_1, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
440 LINE(GRAPH_LINE_2, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
441 LINE(GRAPH_LINE_3, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
442 LINE(GRAPH_LINE_4, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
443 LINE(GRAPH_LINE_5, "", COLOR_WHITE, COLOR_DEFAULT, 0), \
444 LINE(GRAPH_LINE_6, "", COLOR_RED, COLOR_DEFAULT, 0), \
445 LINE(GRAPH_COMMIT, "", COLOR_BLUE, COLOR_DEFAULT, 0)
447 enum line_type {
448 #define LINE(type, line, fg, bg, attr) \
449 LINE_##type
450 LINE_INFO,
451 LINE_NONE
452 #undef LINE
453 };
455 struct line_info {
456 const char *name; /* Option name. */
457 int namelen; /* Size of option name. */
458 const char *line; /* The start of line to match. */
459 int linelen; /* Size of string to match. */
460 int fg, bg, attr; /* Color and text attributes for the lines. */
461 };
463 static struct line_info line_info[] = {
464 #define LINE(type, line, fg, bg, attr) \
465 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
466 LINE_INFO
467 #undef LINE
468 };
470 static enum line_type
471 get_line_type(const char *line)
472 {
473 int linelen = strlen(line);
474 enum line_type type;
476 for (type = 0; type < ARRAY_SIZE(line_info); type++)
477 /* Case insensitive search matches Signed-off-by lines better. */
478 if (linelen >= line_info[type].linelen &&
479 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
480 return type;
482 return LINE_DEFAULT;
483 }
485 static inline int
486 get_line_attr(enum line_type type)
487 {
488 assert(type < ARRAY_SIZE(line_info));
489 return COLOR_PAIR(type) | line_info[type].attr;
490 }
492 static struct line_info *
493 get_line_info(const char *name)
494 {
495 size_t namelen = strlen(name);
496 enum line_type type;
498 for (type = 0; type < ARRAY_SIZE(line_info); type++)
499 if (enum_equals(line_info[type], name, namelen))
500 return &line_info[type];
502 return NULL;
503 }
505 static void
506 init_colors(void)
507 {
508 int default_bg = line_info[LINE_DEFAULT].bg;
509 int default_fg = line_info[LINE_DEFAULT].fg;
510 enum line_type type;
512 start_color();
514 if (assume_default_colors(default_fg, default_bg) == ERR) {
515 default_bg = COLOR_BLACK;
516 default_fg = COLOR_WHITE;
517 }
519 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
520 struct line_info *info = &line_info[type];
521 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
522 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
524 init_pair(type, fg, bg);
525 }
526 }
528 struct line {
529 enum line_type type;
531 /* State flags */
532 unsigned int selected:1;
533 unsigned int dirty:1;
534 unsigned int cleareol:1;
535 unsigned int other:16;
537 void *data; /* User data */
538 };
541 /*
542 * Keys
543 */
545 struct keybinding {
546 int alias;
547 enum request request;
548 };
550 static struct keybinding default_keybindings[] = {
551 /* View switching */
552 { 'm', REQ_VIEW_MAIN },
553 { 'd', REQ_VIEW_DIFF },
554 { 'l', REQ_VIEW_LOG },
555 { 't', REQ_VIEW_TREE },
556 { 'f', REQ_VIEW_BLOB },
557 { 'B', REQ_VIEW_BLAME },
558 { 'H', REQ_VIEW_BRANCH },
559 { 'p', REQ_VIEW_PAGER },
560 { 'h', REQ_VIEW_HELP },
561 { 'S', REQ_VIEW_STATUS },
562 { 'c', REQ_VIEW_STAGE },
564 /* View manipulation */
565 { 'q', REQ_VIEW_CLOSE },
566 { KEY_TAB, REQ_VIEW_NEXT },
567 { KEY_RETURN, REQ_ENTER },
568 { KEY_UP, REQ_PREVIOUS },
569 { KEY_CTL('P'), REQ_PREVIOUS },
570 { KEY_DOWN, REQ_NEXT },
571 { KEY_CTL('N'), REQ_NEXT },
572 { 'R', REQ_REFRESH },
573 { KEY_F(5), REQ_REFRESH },
574 { 'O', REQ_MAXIMIZE },
576 /* Cursor navigation */
577 { 'k', REQ_MOVE_UP },
578 { 'j', REQ_MOVE_DOWN },
579 { KEY_HOME, REQ_MOVE_FIRST_LINE },
580 { KEY_END, REQ_MOVE_LAST_LINE },
581 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
582 { KEY_CTL('D'), REQ_MOVE_PAGE_DOWN },
583 { ' ', REQ_MOVE_PAGE_DOWN },
584 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
585 { KEY_CTL('U'), REQ_MOVE_PAGE_UP },
586 { 'b', REQ_MOVE_PAGE_UP },
587 { '-', REQ_MOVE_PAGE_UP },
589 /* Scrolling */
590 { '|', REQ_SCROLL_FIRST_COL },
591 { KEY_LEFT, REQ_SCROLL_LEFT },
592 { KEY_RIGHT, REQ_SCROLL_RIGHT },
593 { KEY_IC, REQ_SCROLL_LINE_UP },
594 { KEY_CTL('Y'), REQ_SCROLL_LINE_UP },
595 { KEY_DC, REQ_SCROLL_LINE_DOWN },
596 { KEY_CTL('E'), REQ_SCROLL_LINE_DOWN },
597 { 'w', REQ_SCROLL_PAGE_UP },
598 { 's', REQ_SCROLL_PAGE_DOWN },
600 /* Searching */
601 { '/', REQ_SEARCH },
602 { '?', REQ_SEARCH_BACK },
603 { 'n', REQ_FIND_NEXT },
604 { 'N', REQ_FIND_PREV },
606 /* Misc */
607 { 'Q', REQ_QUIT },
608 { 'z', REQ_STOP_LOADING },
609 { 'v', REQ_SHOW_VERSION },
610 { 'r', REQ_SCREEN_REDRAW },
611 { KEY_CTL('L'), REQ_SCREEN_REDRAW },
612 { 'o', REQ_OPTIONS },
613 { '.', REQ_TOGGLE_LINENO },
614 { 'D', REQ_TOGGLE_DATE },
615 { 'A', REQ_TOGGLE_AUTHOR },
616 { 'g', REQ_TOGGLE_REV_GRAPH },
617 { '~', REQ_TOGGLE_GRAPHIC },
618 { 'F', REQ_TOGGLE_REFS },
619 { 'I', REQ_TOGGLE_SORT_ORDER },
620 { 'i', REQ_TOGGLE_SORT_FIELD },
621 { ':', REQ_PROMPT },
622 { 'u', REQ_STATUS_UPDATE },
623 { '!', REQ_STATUS_REVERT },
624 { 'M', REQ_STATUS_MERGE },
625 { '@', REQ_STAGE_NEXT },
626 { ',', REQ_PARENT },
627 { 'e', REQ_EDIT },
628 };
630 #define KEYMAP_INFO \
631 KEYMAP_(GENERIC), \
632 KEYMAP_(MAIN), \
633 KEYMAP_(DIFF), \
634 KEYMAP_(LOG), \
635 KEYMAP_(TREE), \
636 KEYMAP_(BLOB), \
637 KEYMAP_(BLAME), \
638 KEYMAP_(BRANCH), \
639 KEYMAP_(PAGER), \
640 KEYMAP_(HELP), \
641 KEYMAP_(STATUS), \
642 KEYMAP_(STAGE)
644 enum keymap {
645 #define KEYMAP_(name) KEYMAP_##name
646 KEYMAP_INFO
647 #undef KEYMAP_
648 };
650 static const struct enum_map keymap_table[] = {
651 #define KEYMAP_(name) ENUM_MAP(#name, KEYMAP_##name)
652 KEYMAP_INFO
653 #undef KEYMAP_
654 };
656 #define set_keymap(map, name) map_enum(map, keymap_table, name)
658 struct keybinding_table {
659 struct keybinding *data;
660 size_t size;
661 };
663 static struct keybinding_table keybindings[ARRAY_SIZE(keymap_table)];
665 static void
666 add_keybinding(enum keymap keymap, enum request request, int key)
667 {
668 struct keybinding_table *table = &keybindings[keymap];
669 size_t i;
671 for (i = 0; i < keybindings[keymap].size; i++) {
672 if (keybindings[keymap].data[i].alias == key) {
673 keybindings[keymap].data[i].request = request;
674 return;
675 }
676 }
678 table->data = realloc(table->data, (table->size + 1) * sizeof(*table->data));
679 if (!table->data)
680 die("Failed to allocate keybinding");
681 table->data[table->size].alias = key;
682 table->data[table->size++].request = request;
684 if (request == REQ_NONE && keymap == KEYMAP_GENERIC) {
685 int i;
687 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
688 if (default_keybindings[i].alias == key)
689 default_keybindings[i].request = REQ_NONE;
690 }
691 }
693 /* Looks for a key binding first in the given map, then in the generic map, and
694 * lastly in the default keybindings. */
695 static enum request
696 get_keybinding(enum keymap keymap, int key)
697 {
698 size_t i;
700 for (i = 0; i < keybindings[keymap].size; i++)
701 if (keybindings[keymap].data[i].alias == key)
702 return keybindings[keymap].data[i].request;
704 for (i = 0; i < keybindings[KEYMAP_GENERIC].size; i++)
705 if (keybindings[KEYMAP_GENERIC].data[i].alias == key)
706 return keybindings[KEYMAP_GENERIC].data[i].request;
708 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
709 if (default_keybindings[i].alias == key)
710 return default_keybindings[i].request;
712 return (enum request) key;
713 }
716 struct key {
717 const char *name;
718 int value;
719 };
721 static const struct key key_table[] = {
722 { "Enter", KEY_RETURN },
723 { "Space", ' ' },
724 { "Backspace", KEY_BACKSPACE },
725 { "Tab", KEY_TAB },
726 { "Escape", KEY_ESC },
727 { "Left", KEY_LEFT },
728 { "Right", KEY_RIGHT },
729 { "Up", KEY_UP },
730 { "Down", KEY_DOWN },
731 { "Insert", KEY_IC },
732 { "Delete", KEY_DC },
733 { "Hash", '#' },
734 { "Home", KEY_HOME },
735 { "End", KEY_END },
736 { "PageUp", KEY_PPAGE },
737 { "PageDown", KEY_NPAGE },
738 { "F1", KEY_F(1) },
739 { "F2", KEY_F(2) },
740 { "F3", KEY_F(3) },
741 { "F4", KEY_F(4) },
742 { "F5", KEY_F(5) },
743 { "F6", KEY_F(6) },
744 { "F7", KEY_F(7) },
745 { "F8", KEY_F(8) },
746 { "F9", KEY_F(9) },
747 { "F10", KEY_F(10) },
748 { "F11", KEY_F(11) },
749 { "F12", KEY_F(12) },
750 };
752 static int
753 get_key_value(const char *name)
754 {
755 int i;
757 for (i = 0; i < ARRAY_SIZE(key_table); i++)
758 if (!strcasecmp(key_table[i].name, name))
759 return key_table[i].value;
761 if (strlen(name) == 2 && name[0] == '^' && isprint(*name))
762 return (int)name[1] & 0x1f;
763 if (strlen(name) == 1 && isprint(*name))
764 return (int) *name;
765 return ERR;
766 }
768 static const char *
769 get_key_name(int key_value)
770 {
771 static char key_char[] = "'X'\0";
772 const char *seq = NULL;
773 int key;
775 for (key = 0; key < ARRAY_SIZE(key_table); key++)
776 if (key_table[key].value == key_value)
777 seq = key_table[key].name;
779 if (seq == NULL && key_value < 0x7f) {
780 char *s = key_char + 1;
782 if (key_value >= 0x20) {
783 *s++ = key_value;
784 } else {
785 *s++ = '^';
786 *s++ = 0x40 | (key_value & 0x1f);
787 }
788 *s++ = '\'';
789 *s++ = '\0';
790 seq = key_char;
791 }
793 return seq ? seq : "(no key)";
794 }
796 static bool
797 append_key(char *buf, size_t *pos, const struct keybinding *keybinding)
798 {
799 const char *sep = *pos > 0 ? ", " : "";
800 const char *keyname = get_key_name(keybinding->alias);
802 return string_nformat(buf, BUFSIZ, pos, "%s%s", sep, keyname);
803 }
805 static bool
806 append_keymap_request_keys(char *buf, size_t *pos, enum request request,
807 enum keymap keymap, bool all)
808 {
809 int i;
811 for (i = 0; i < keybindings[keymap].size; i++) {
812 if (keybindings[keymap].data[i].request == request) {
813 if (!append_key(buf, pos, &keybindings[keymap].data[i]))
814 return FALSE;
815 if (!all)
816 break;
817 }
818 }
820 return TRUE;
821 }
823 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
825 static const char *
826 get_keys(enum keymap keymap, enum request request, bool all)
827 {
828 static char buf[BUFSIZ];
829 size_t pos = 0;
830 int i;
832 buf[pos] = 0;
834 if (!append_keymap_request_keys(buf, &pos, request, keymap, all))
835 return "Too many keybindings!";
836 if (pos > 0 && !all)
837 return buf;
839 if (keymap != KEYMAP_GENERIC) {
840 /* Only the generic keymap includes the default keybindings when
841 * listing all keys. */
842 if (all)
843 return buf;
845 if (!append_keymap_request_keys(buf, &pos, request, KEYMAP_GENERIC, all))
846 return "Too many keybindings!";
847 if (pos)
848 return buf;
849 }
851 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
852 if (default_keybindings[i].request == request) {
853 if (!append_key(buf, &pos, &default_keybindings[i]))
854 return "Too many keybindings!";
855 if (!all)
856 return buf;
857 }
858 }
860 return buf;
861 }
863 struct run_request {
864 enum keymap keymap;
865 int key;
866 const char **argv;
867 };
869 static struct run_request *run_request;
870 static size_t run_requests;
872 DEFINE_ALLOCATOR(realloc_run_requests, struct run_request, 8)
874 static enum request
875 add_run_request(enum keymap keymap, int key, const char **argv)
876 {
877 struct run_request *req;
879 if (!realloc_run_requests(&run_request, run_requests, 1))
880 return REQ_NONE;
882 req = &run_request[run_requests];
883 req->keymap = keymap;
884 req->key = key;
885 req->argv = NULL;
887 if (!argv_copy(&req->argv, argv))
888 return REQ_NONE;
890 return REQ_NONE + ++run_requests;
891 }
893 static struct run_request *
894 get_run_request(enum request request)
895 {
896 if (request <= REQ_NONE)
897 return NULL;
898 return &run_request[request - REQ_NONE - 1];
899 }
901 static void
902 add_builtin_run_requests(void)
903 {
904 const char *cherry_pick[] = { "git", "cherry-pick", "%(commit)", NULL };
905 const char *checkout[] = { "git", "checkout", "%(branch)", NULL };
906 const char *commit[] = { "git", "commit", NULL };
907 const char *gc[] = { "git", "gc", NULL };
908 struct run_request reqs[] = {
909 { KEYMAP_MAIN, 'C', cherry_pick },
910 { KEYMAP_STATUS, 'C', commit },
911 { KEYMAP_BRANCH, 'C', checkout },
912 { KEYMAP_GENERIC, 'G', gc },
913 };
914 int i;
916 for (i = 0; i < ARRAY_SIZE(reqs); i++) {
917 enum request req = get_keybinding(reqs[i].keymap, reqs[i].key);
919 if (req != reqs[i].key)
920 continue;
921 req = add_run_request(reqs[i].keymap, reqs[i].key, reqs[i].argv);
922 if (req != REQ_NONE)
923 add_keybinding(reqs[i].keymap, req, reqs[i].key);
924 }
925 }
927 /*
928 * User config file handling.
929 */
931 #define OPT_ERR_INFO \
932 OPT_ERR_(INTEGER_VALUE_OUT_OF_BOUND, "Integer value out of bound"), \
933 OPT_ERR_(INVALID_STEP_VALUE, "Invalid step value"), \
934 OPT_ERR_(NO_OPTION_VALUE, "No option value"), \
935 OPT_ERR_(NO_VALUE_ASSIGNED, "No value assigned"), \
936 OPT_ERR_(OBSOLETE_REQUEST_NAME, "Obsolete request name"), \
937 OPT_ERR_(OUT_OF_MEMORY, "Out of memory"), \
938 OPT_ERR_(TOO_MANY_OPTION_ARGUMENTS, "Too many option arguments"), \
939 OPT_ERR_(UNKNOWN_ATTRIBUTE, "Unknown attribute"), \
940 OPT_ERR_(UNKNOWN_COLOR, "Unknown color"), \
941 OPT_ERR_(UNKNOWN_COLOR_NAME, "Unknown color name"), \
942 OPT_ERR_(UNKNOWN_KEY, "Unknown key"), \
943 OPT_ERR_(UNKNOWN_KEY_MAP, "Unknown key map"), \
944 OPT_ERR_(UNKNOWN_OPTION_COMMAND, "Unknown option command"), \
945 OPT_ERR_(UNKNOWN_REQUEST_NAME, "Unknown request name"), \
946 OPT_ERR_(UNKNOWN_VARIABLE_NAME, "Unknown variable name"), \
947 OPT_ERR_(UNMATCHED_QUOTATION, "Unmatched quotation"), \
948 OPT_ERR_(WRONG_NUMBER_OF_ARGUMENTS, "Wrong number of arguments"),
950 enum option_code {
951 #define OPT_ERR_(name, msg) OPT_ERR_ ## name
952 OPT_ERR_INFO
953 #undef OPT_ERR_
954 OPT_OK
955 };
957 static const char *option_errors[] = {
958 #define OPT_ERR_(name, msg) msg
959 OPT_ERR_INFO
960 #undef OPT_ERR_
961 };
963 static const struct enum_map color_map[] = {
964 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
965 COLOR_MAP(DEFAULT),
966 COLOR_MAP(BLACK),
967 COLOR_MAP(BLUE),
968 COLOR_MAP(CYAN),
969 COLOR_MAP(GREEN),
970 COLOR_MAP(MAGENTA),
971 COLOR_MAP(RED),
972 COLOR_MAP(WHITE),
973 COLOR_MAP(YELLOW),
974 };
976 static const struct enum_map attr_map[] = {
977 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
978 ATTR_MAP(NORMAL),
979 ATTR_MAP(BLINK),
980 ATTR_MAP(BOLD),
981 ATTR_MAP(DIM),
982 ATTR_MAP(REVERSE),
983 ATTR_MAP(STANDOUT),
984 ATTR_MAP(UNDERLINE),
985 };
987 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
989 static enum option_code
990 parse_step(double *opt, const char *arg)
991 {
992 *opt = atoi(arg);
993 if (!strchr(arg, '%'))
994 return OPT_OK;
996 /* "Shift down" so 100% and 1 does not conflict. */
997 *opt = (*opt - 1) / 100;
998 if (*opt >= 1.0) {
999 *opt = 0.99;
1000 return OPT_ERR_INVALID_STEP_VALUE;
1001 }
1002 if (*opt < 0.0) {
1003 *opt = 1;
1004 return OPT_ERR_INVALID_STEP_VALUE;
1005 }
1006 return OPT_OK;
1007 }
1009 static enum option_code
1010 parse_int(int *opt, const char *arg, int min, int max)
1011 {
1012 int value = atoi(arg);
1014 if (min <= value && value <= max) {
1015 *opt = value;
1016 return OPT_OK;
1017 }
1019 return OPT_ERR_INTEGER_VALUE_OUT_OF_BOUND;
1020 }
1022 static bool
1023 set_color(int *color, const char *name)
1024 {
1025 if (map_enum(color, color_map, name))
1026 return TRUE;
1027 if (!prefixcmp(name, "color"))
1028 return parse_int(color, name + 5, 0, 255) == OK;
1029 return FALSE;
1030 }
1032 /* Wants: object fgcolor bgcolor [attribute] */
1033 static enum option_code
1034 option_color_command(int argc, const char *argv[])
1035 {
1036 struct line_info *info;
1038 if (argc < 3)
1039 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1041 info = get_line_info(argv[0]);
1042 if (!info) {
1043 static const struct enum_map obsolete[] = {
1044 ENUM_MAP("main-delim", LINE_DELIMITER),
1045 ENUM_MAP("main-date", LINE_DATE),
1046 ENUM_MAP("main-author", LINE_AUTHOR),
1047 };
1048 int index;
1050 if (!map_enum(&index, obsolete, argv[0]))
1051 return OPT_ERR_UNKNOWN_COLOR_NAME;
1052 info = &line_info[index];
1053 }
1055 if (!set_color(&info->fg, argv[1]) ||
1056 !set_color(&info->bg, argv[2]))
1057 return OPT_ERR_UNKNOWN_COLOR;
1059 info->attr = 0;
1060 while (argc-- > 3) {
1061 int attr;
1063 if (!set_attribute(&attr, argv[argc]))
1064 return OPT_ERR_UNKNOWN_ATTRIBUTE;
1065 info->attr |= attr;
1066 }
1068 return OPT_OK;
1069 }
1071 static enum option_code
1072 parse_bool(bool *opt, const char *arg)
1073 {
1074 *opt = (!strcmp(arg, "1") || !strcmp(arg, "true") || !strcmp(arg, "yes"))
1075 ? TRUE : FALSE;
1076 return OPT_OK;
1077 }
1079 static enum option_code
1080 parse_enum_do(unsigned int *opt, const char *arg,
1081 const struct enum_map *map, size_t map_size)
1082 {
1083 bool is_true;
1085 assert(map_size > 1);
1087 if (map_enum_do(map, map_size, (int *) opt, arg))
1088 return OPT_OK;
1090 parse_bool(&is_true, arg);
1091 *opt = is_true ? map[1].value : map[0].value;
1092 return OPT_OK;
1093 }
1095 #define parse_enum(opt, arg, map) \
1096 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1098 static enum option_code
1099 parse_string(char *opt, const char *arg, size_t optsize)
1100 {
1101 int arglen = strlen(arg);
1103 switch (arg[0]) {
1104 case '\"':
1105 case '\'':
1106 if (arglen == 1 || arg[arglen - 1] != arg[0])
1107 return OPT_ERR_UNMATCHED_QUOTATION;
1108 arg += 1; arglen -= 2;
1109 default:
1110 string_ncopy_do(opt, optsize, arg, arglen);
1111 return OPT_OK;
1112 }
1113 }
1115 static enum option_code
1116 parse_args(const char ***args, const char *argv[])
1117 {
1118 if (*args == NULL && !argv_copy(args, argv))
1119 return OPT_ERR_OUT_OF_MEMORY;
1120 return OPT_OK;
1121 }
1123 /* Wants: name = value */
1124 static enum option_code
1125 option_set_command(int argc, const char *argv[])
1126 {
1127 if (argc < 3)
1128 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1130 if (strcmp(argv[1], "="))
1131 return OPT_ERR_NO_VALUE_ASSIGNED;
1133 if (!strcmp(argv[0], "blame-options"))
1134 return parse_args(&opt_blame_argv, argv + 2);
1136 if (argc != 3)
1137 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1139 if (!strcmp(argv[0], "show-author"))
1140 return parse_enum(&opt_author, argv[2], author_map);
1142 if (!strcmp(argv[0], "show-date"))
1143 return parse_enum(&opt_date, argv[2], date_map);
1145 if (!strcmp(argv[0], "show-rev-graph"))
1146 return parse_bool(&opt_rev_graph, argv[2]);
1148 if (!strcmp(argv[0], "show-refs"))
1149 return parse_bool(&opt_show_refs, argv[2]);
1151 if (!strcmp(argv[0], "show-line-numbers"))
1152 return parse_bool(&opt_line_number, argv[2]);
1154 if (!strcmp(argv[0], "line-graphics"))
1155 return parse_enum(&opt_line_graphics, argv[2], graphic_map);
1157 if (!strcmp(argv[0], "line-number-interval"))
1158 return parse_int(&opt_num_interval, argv[2], 1, 1024);
1160 if (!strcmp(argv[0], "author-width"))
1161 return parse_int(&opt_author_cols, argv[2], 0, 1024);
1163 if (!strcmp(argv[0], "horizontal-scroll"))
1164 return parse_step(&opt_hscroll, argv[2]);
1166 if (!strcmp(argv[0], "split-view-height"))
1167 return parse_step(&opt_scale_split_view, argv[2]);
1169 if (!strcmp(argv[0], "tab-size"))
1170 return parse_int(&opt_tab_size, argv[2], 1, 1024);
1172 if (!strcmp(argv[0], "commit-encoding"))
1173 return parse_string(opt_encoding, argv[2], sizeof(opt_encoding));
1175 if (!strcmp(argv[0], "status-untracked-dirs"))
1176 return parse_bool(&opt_untracked_dirs_content, argv[2]);
1178 return OPT_ERR_UNKNOWN_VARIABLE_NAME;
1179 }
1181 /* Wants: mode request key */
1182 static enum option_code
1183 option_bind_command(int argc, const char *argv[])
1184 {
1185 enum request request;
1186 int keymap = -1;
1187 int key;
1189 if (argc < 3)
1190 return OPT_ERR_WRONG_NUMBER_OF_ARGUMENTS;
1192 if (!set_keymap(&keymap, argv[0]))
1193 return OPT_ERR_UNKNOWN_KEY_MAP;
1195 key = get_key_value(argv[1]);
1196 if (key == ERR)
1197 return OPT_ERR_UNKNOWN_KEY;
1199 request = get_request(argv[2]);
1200 if (request == REQ_UNKNOWN) {
1201 static const struct enum_map obsolete[] = {
1202 ENUM_MAP("cherry-pick", REQ_NONE),
1203 ENUM_MAP("screen-resize", REQ_NONE),
1204 ENUM_MAP("tree-parent", REQ_PARENT),
1205 };
1206 int alias;
1208 if (map_enum(&alias, obsolete, argv[2])) {
1209 if (alias != REQ_NONE)
1210 add_keybinding(keymap, alias, key);
1211 return OPT_ERR_OBSOLETE_REQUEST_NAME;
1212 }
1213 }
1214 if (request == REQ_UNKNOWN && *argv[2]++ == '!')
1215 request = add_run_request(keymap, key, argv + 2);
1216 if (request == REQ_UNKNOWN)
1217 return OPT_ERR_UNKNOWN_REQUEST_NAME;
1219 add_keybinding(keymap, request, key);
1221 return OPT_OK;
1222 }
1224 static enum option_code
1225 set_option(const char *opt, char *value)
1226 {
1227 const char *argv[SIZEOF_ARG];
1228 int argc = 0;
1230 if (!argv_from_string(argv, &argc, value))
1231 return OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
1233 if (!strcmp(opt, "color"))
1234 return option_color_command(argc, argv);
1236 if (!strcmp(opt, "set"))
1237 return option_set_command(argc, argv);
1239 if (!strcmp(opt, "bind"))
1240 return option_bind_command(argc, argv);
1242 return OPT_ERR_UNKNOWN_OPTION_COMMAND;
1243 }
1245 struct config_state {
1246 int lineno;
1247 bool errors;
1248 };
1250 static int
1251 read_option(char *opt, size_t optlen, char *value, size_t valuelen, void *data)
1252 {
1253 struct config_state *config = data;
1254 enum option_code status = OPT_ERR_NO_OPTION_VALUE;
1256 config->lineno++;
1258 /* Check for comment markers, since read_properties() will
1259 * only ensure opt and value are split at first " \t". */
1260 optlen = strcspn(opt, "#");
1261 if (optlen == 0)
1262 return OK;
1264 if (opt[optlen] == 0) {
1265 /* Look for comment endings in the value. */
1266 size_t len = strcspn(value, "#");
1268 if (len < valuelen) {
1269 valuelen = len;
1270 value[valuelen] = 0;
1271 }
1273 status = set_option(opt, value);
1274 }
1276 if (status != OPT_OK) {
1277 warn("Error on line %d, near '%.*s': %s",
1278 config->lineno, (int) optlen, opt, option_errors[status]);
1279 config->errors = TRUE;
1280 }
1282 /* Always keep going if errors are encountered. */
1283 return OK;
1284 }
1286 static void
1287 load_option_file(const char *path)
1288 {
1289 struct config_state config = { 0, FALSE };
1290 struct io io;
1292 /* It's OK that the file doesn't exist. */
1293 if (!io_open(&io, "%s", path))
1294 return;
1296 if (io_load(&io, " \t", read_option, &config) == ERR ||
1297 config.errors == TRUE)
1298 warn("Errors while loading %s.", path);
1299 }
1301 static int
1302 load_options(void)
1303 {
1304 const char *home = getenv("HOME");
1305 const char *tigrc_user = getenv("TIGRC_USER");
1306 const char *tigrc_system = getenv("TIGRC_SYSTEM");
1307 const char *tig_diff_opts = getenv("TIG_DIFF_OPTS");
1308 char buf[SIZEOF_STR];
1310 if (!tigrc_system)
1311 tigrc_system = SYSCONFDIR "/tigrc";
1312 load_option_file(tigrc_system);
1314 if (!tigrc_user) {
1315 if (!home || !string_format(buf, "%s/.tigrc", home))
1316 return ERR;
1317 tigrc_user = buf;
1318 }
1319 load_option_file(tigrc_user);
1321 /* Add _after_ loading config files to avoid adding run requests
1322 * that conflict with keybindings. */
1323 add_builtin_run_requests();
1325 if (!opt_diff_argv && tig_diff_opts && *tig_diff_opts) {
1326 static const char *diff_opts[SIZEOF_ARG] = { NULL };
1327 int argc = 0;
1329 if (!string_format(buf, "%s", tig_diff_opts) ||
1330 !argv_from_string(diff_opts, &argc, buf))
1331 die("TIG_DIFF_OPTS contains too many arguments");
1332 else if (!argv_copy(&opt_diff_argv, diff_opts))
1333 die("Failed to format TIG_DIFF_OPTS arguments");
1334 }
1336 return OK;
1337 }
1340 /*
1341 * The viewer
1342 */
1344 struct view;
1345 struct view_ops;
1347 /* The display array of active views and the index of the current view. */
1348 static struct view *display[2];
1349 static WINDOW *display_win[2];
1350 static WINDOW *display_title[2];
1351 static unsigned int current_view;
1353 #define foreach_displayed_view(view, i) \
1354 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1356 #define displayed_views() (display[1] != NULL ? 2 : 1)
1358 /* Current head and commit ID */
1359 static char ref_blob[SIZEOF_REF] = "";
1360 static char ref_commit[SIZEOF_REF] = "HEAD";
1361 static char ref_head[SIZEOF_REF] = "HEAD";
1362 static char ref_branch[SIZEOF_REF] = "";
1364 enum view_type {
1365 VIEW_MAIN,
1366 VIEW_DIFF,
1367 VIEW_LOG,
1368 VIEW_TREE,
1369 VIEW_BLOB,
1370 VIEW_BLAME,
1371 VIEW_BRANCH,
1372 VIEW_HELP,
1373 VIEW_PAGER,
1374 VIEW_STATUS,
1375 VIEW_STAGE,
1376 };
1378 struct view {
1379 enum view_type type; /* View type */
1380 const char *name; /* View name */
1381 const char *cmd_env; /* Command line set via environment */
1382 const char *id; /* Points to either of ref_{head,commit,blob} */
1384 struct view_ops *ops; /* View operations */
1386 enum keymap keymap; /* What keymap does this view have */
1387 bool git_dir; /* Whether the view requires a git directory. */
1389 char ref[SIZEOF_REF]; /* Hovered commit reference */
1390 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1392 int height, width; /* The width and height of the main window */
1393 WINDOW *win; /* The main window */
1395 /* Navigation */
1396 unsigned long offset; /* Offset of the window top */
1397 unsigned long yoffset; /* Offset from the window side. */
1398 unsigned long lineno; /* Current line number */
1399 unsigned long p_offset; /* Previous offset of the window top */
1400 unsigned long p_yoffset;/* Previous offset from the window side */
1401 unsigned long p_lineno; /* Previous current line number */
1402 bool p_restore; /* Should the previous position be restored. */
1404 /* Searching */
1405 char grep[SIZEOF_STR]; /* Search string */
1406 regex_t *regex; /* Pre-compiled regexp */
1408 /* If non-NULL, points to the view that opened this view. If this view
1409 * is closed tig will switch back to the parent view. */
1410 struct view *parent;
1411 struct view *prev;
1413 /* Buffering */
1414 size_t lines; /* Total number of lines */
1415 struct line *line; /* Line index */
1416 unsigned int digits; /* Number of digits in the lines member. */
1418 /* Drawing */
1419 struct line *curline; /* Line currently being drawn. */
1420 enum line_type curtype; /* Attribute currently used for drawing. */
1421 unsigned long col; /* Column when drawing. */
1422 bool has_scrolled; /* View was scrolled. */
1424 /* Loading */
1425 const char **argv; /* Shell command arguments. */
1426 const char *dir; /* Directory from which to execute. */
1427 struct io io;
1428 struct io *pipe;
1429 time_t start_time;
1430 time_t update_secs;
1431 };
1433 struct view_ops {
1434 /* What type of content being displayed. Used in the title bar. */
1435 const char *type;
1436 /* Default command arguments. */
1437 const char **argv;
1438 /* Open and reads in all view content. */
1439 bool (*open)(struct view *view);
1440 /* Read one line; updates view->line. */
1441 bool (*read)(struct view *view, char *data);
1442 /* Draw one line; @lineno must be < view->height. */
1443 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1444 /* Depending on view handle a special requests. */
1445 enum request (*request)(struct view *view, enum request request, struct line *line);
1446 /* Search for regexp in a line. */
1447 bool (*grep)(struct view *view, struct line *line);
1448 /* Select line */
1449 void (*select)(struct view *view, struct line *line);
1450 /* Prepare view for loading */
1451 bool (*prepare)(struct view *view);
1452 };
1454 static struct view_ops blame_ops;
1455 static struct view_ops blob_ops;
1456 static struct view_ops diff_ops;
1457 static struct view_ops help_ops;
1458 static struct view_ops log_ops;
1459 static struct view_ops main_ops;
1460 static struct view_ops pager_ops;
1461 static struct view_ops stage_ops;
1462 static struct view_ops status_ops;
1463 static struct view_ops tree_ops;
1464 static struct view_ops branch_ops;
1466 #define VIEW_STR(type, name, env, ref, ops, map, git) \
1467 { type, name, #env, ref, ops, map, git }
1469 #define VIEW_(id, name, ops, git, ref) \
1470 VIEW_STR(VIEW_##id, name, TIG_##id##_CMD, ref, ops, KEYMAP_##id, git)
1472 static struct view views[] = {
1473 VIEW_(MAIN, "main", &main_ops, TRUE, ref_head),
1474 VIEW_(DIFF, "diff", &diff_ops, TRUE, ref_commit),
1475 VIEW_(LOG, "log", &log_ops, TRUE, ref_head),
1476 VIEW_(TREE, "tree", &tree_ops, TRUE, ref_commit),
1477 VIEW_(BLOB, "blob", &blob_ops, TRUE, ref_blob),
1478 VIEW_(BLAME, "blame", &blame_ops, TRUE, ref_commit),
1479 VIEW_(BRANCH, "branch", &branch_ops, TRUE, ref_head),
1480 VIEW_(HELP, "help", &help_ops, FALSE, ""),
1481 VIEW_(PAGER, "pager", &pager_ops, FALSE, ""),
1482 VIEW_(STATUS, "status", &status_ops, TRUE, ""),
1483 VIEW_(STAGE, "stage", &stage_ops, TRUE, ""),
1484 };
1486 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1488 #define foreach_view(view, i) \
1489 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1491 #define view_is_displayed(view) \
1492 (view == display[0] || view == display[1])
1494 static enum request
1495 view_request(struct view *view, enum request request)
1496 {
1497 if (!view || !view->lines)
1498 return request;
1499 return view->ops->request(view, request, &view->line[view->lineno]);
1500 }
1503 /*
1504 * View drawing.
1505 */
1507 static inline void
1508 set_view_attr(struct view *view, enum line_type type)
1509 {
1510 if (!view->curline->selected && view->curtype != type) {
1511 (void) wattrset(view->win, get_line_attr(type));
1512 wchgat(view->win, -1, 0, type, NULL);
1513 view->curtype = type;
1514 }
1515 }
1517 static int
1518 draw_chars(struct view *view, enum line_type type, const char *string,
1519 int max_len, bool use_tilde)
1520 {
1521 static char out_buffer[BUFSIZ * 2];
1522 int len = 0;
1523 int col = 0;
1524 int trimmed = FALSE;
1525 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1527 if (max_len <= 0)
1528 return 0;
1530 len = utf8_length(&string, skip, &col, max_len, &trimmed, use_tilde, opt_tab_size);
1532 set_view_attr(view, type);
1533 if (len > 0) {
1534 if (opt_iconv_out != ICONV_NONE) {
1535 ICONV_CONST char *inbuf = (ICONV_CONST char *) string;
1536 size_t inlen = len + 1;
1538 char *outbuf = out_buffer;
1539 size_t outlen = sizeof(out_buffer);
1541 size_t ret;
1543 ret = iconv(opt_iconv_out, &inbuf, &inlen, &outbuf, &outlen);
1544 if (ret != (size_t) -1) {
1545 string = out_buffer;
1546 len = sizeof(out_buffer) - outlen;
1547 }
1548 }
1550 waddnstr(view->win, string, len);
1552 if (trimmed && use_tilde) {
1553 set_view_attr(view, LINE_DELIMITER);
1554 waddch(view->win, '~');
1555 col++;
1556 }
1557 }
1559 return col;
1560 }
1562 static int
1563 draw_space(struct view *view, enum line_type type, int max, int spaces)
1564 {
1565 static char space[] = " ";
1566 int col = 0;
1568 spaces = MIN(max, spaces);
1570 while (spaces > 0) {
1571 int len = MIN(spaces, sizeof(space) - 1);
1573 col += draw_chars(view, type, space, len, FALSE);
1574 spaces -= len;
1575 }
1577 return col;
1578 }
1580 static bool
1581 draw_text(struct view *view, enum line_type type, const char *string)
1582 {
1583 char text[SIZEOF_STR];
1585 do {
1586 size_t pos = string_expand(text, sizeof(text), string, opt_tab_size);
1588 view->col += draw_chars(view, type, text, view->width + view->yoffset - view->col, TRUE);
1589 string += pos;
1590 } while (*string && view->width + view->yoffset > view->col);
1592 return view->width + view->yoffset <= view->col;
1593 }
1595 static bool
1596 draw_graphic(struct view *view, enum line_type type, const chtype graphic[], size_t size, bool separator)
1597 {
1598 size_t skip = view->yoffset > view->col ? view->yoffset - view->col : 0;
1599 int max = view->width + view->yoffset - view->col;
1600 int i;
1602 if (max < size)
1603 size = max;
1605 set_view_attr(view, type);
1606 /* Using waddch() instead of waddnstr() ensures that
1607 * they'll be rendered correctly for the cursor line. */
1608 for (i = skip; i < size; i++)
1609 waddch(view->win, graphic[i]);
1611 view->col += size;
1612 if (separator) {
1613 if (size < max && skip <= size)
1614 waddch(view->win, ' ');
1615 view->col++;
1616 }
1618 return view->width + view->yoffset <= view->col;
1619 }
1621 static bool
1622 draw_field(struct view *view, enum line_type type, const char *text, int len, bool trim)
1623 {
1624 int max = MIN(view->width + view->yoffset - view->col, len);
1625 int col;
1627 if (text)
1628 col = draw_chars(view, type, text, max - 1, trim);
1629 else
1630 col = draw_space(view, type, max - 1, max - 1);
1632 view->col += col;
1633 view->col += draw_space(view, LINE_DEFAULT, max - col, max - col);
1634 return view->width + view->yoffset <= view->col;
1635 }
1637 static bool
1638 draw_date(struct view *view, struct time *time)
1639 {
1640 const char *date = mkdate(time, opt_date);
1641 int cols = opt_date == DATE_SHORT ? DATE_SHORT_COLS : DATE_COLS;
1643 return draw_field(view, LINE_DATE, date, cols, FALSE);
1644 }
1646 static bool
1647 draw_author(struct view *view, const char *author)
1648 {
1649 bool trim = opt_author_cols == 0 || opt_author_cols > 5;
1650 bool abbreviate = opt_author == AUTHOR_ABBREVIATED || !trim;
1652 if (abbreviate && author)
1653 author = get_author_initials(author);
1655 return draw_field(view, LINE_AUTHOR, author, opt_author_cols, trim);
1656 }
1658 static bool
1659 draw_mode(struct view *view, mode_t mode)
1660 {
1661 const char *str;
1663 if (S_ISDIR(mode))
1664 str = "drwxr-xr-x";
1665 else if (S_ISLNK(mode))
1666 str = "lrwxrwxrwx";
1667 else if (S_ISGITLINK(mode))
1668 str = "m---------";
1669 else if (S_ISREG(mode) && mode & S_IXUSR)
1670 str = "-rwxr-xr-x";
1671 else if (S_ISREG(mode))
1672 str = "-rw-r--r--";
1673 else
1674 str = "----------";
1676 return draw_field(view, LINE_MODE, str, STRING_SIZE("-rw-r--r-- "), FALSE);
1677 }
1679 static bool
1680 draw_lineno(struct view *view, unsigned int lineno)
1681 {
1682 char number[10];
1683 int digits3 = view->digits < 3 ? 3 : view->digits;
1684 int max = MIN(view->width + view->yoffset - view->col, digits3);
1685 char *text = NULL;
1686 chtype separator = opt_line_graphics ? ACS_VLINE : '|';
1688 lineno += view->offset + 1;
1689 if (lineno == 1 || (lineno % opt_num_interval) == 0) {
1690 static char fmt[] = "%1ld";
1692 fmt[1] = '0' + (view->digits <= 9 ? digits3 : 1);
1693 if (string_format(number, fmt, lineno))
1694 text = number;
1695 }
1696 if (text)
1697 view->col += draw_chars(view, LINE_LINE_NUMBER, text, max, TRUE);
1698 else
1699 view->col += draw_space(view, LINE_LINE_NUMBER, max, digits3);
1700 return draw_graphic(view, LINE_DEFAULT, &separator, 1, TRUE);
1701 }
1703 static bool
1704 draw_view_line(struct view *view, unsigned int lineno)
1705 {
1706 struct line *line;
1707 bool selected = (view->offset + lineno == view->lineno);
1709 assert(view_is_displayed(view));
1711 if (view->offset + lineno >= view->lines)
1712 return FALSE;
1714 line = &view->line[view->offset + lineno];
1716 wmove(view->win, lineno, 0);
1717 if (line->cleareol)
1718 wclrtoeol(view->win);
1719 view->col = 0;
1720 view->curline = line;
1721 view->curtype = LINE_NONE;
1722 line->selected = FALSE;
1723 line->dirty = line->cleareol = 0;
1725 if (selected) {
1726 set_view_attr(view, LINE_CURSOR);
1727 line->selected = TRUE;
1728 view->ops->select(view, line);
1729 }
1731 return view->ops->draw(view, line, lineno);
1732 }
1734 static void
1735 redraw_view_dirty(struct view *view)
1736 {
1737 bool dirty = FALSE;
1738 int lineno;
1740 for (lineno = 0; lineno < view->height; lineno++) {
1741 if (view->offset + lineno >= view->lines)
1742 break;
1743 if (!view->line[view->offset + lineno].dirty)
1744 continue;
1745 dirty = TRUE;
1746 if (!draw_view_line(view, lineno))
1747 break;
1748 }
1750 if (!dirty)
1751 return;
1752 wnoutrefresh(view->win);
1753 }
1755 static void
1756 redraw_view_from(struct view *view, int lineno)
1757 {
1758 assert(0 <= lineno && lineno < view->height);
1760 for (; lineno < view->height; lineno++) {
1761 if (!draw_view_line(view, lineno))
1762 break;
1763 }
1765 wnoutrefresh(view->win);
1766 }
1768 static void
1769 redraw_view(struct view *view)
1770 {
1771 werase(view->win);
1772 redraw_view_from(view, 0);
1773 }
1776 static void
1777 update_view_title(struct view *view)
1778 {
1779 char buf[SIZEOF_STR];
1780 char state[SIZEOF_STR];
1781 size_t bufpos = 0, statelen = 0;
1782 WINDOW *window = display[0] == view ? display_title[0] : display_title[1];
1784 assert(view_is_displayed(view));
1786 if (view->type != VIEW_STATUS && view->lines) {
1787 unsigned int view_lines = view->offset + view->height;
1788 unsigned int lines = view->lines
1789 ? MIN(view_lines, view->lines) * 100 / view->lines
1790 : 0;
1792 string_format_from(state, &statelen, " - %s %d of %d (%d%%)",
1793 view->ops->type,
1794 view->lineno + 1,
1795 view->lines,
1796 lines);
1798 }
1800 if (view->pipe) {
1801 time_t secs = time(NULL) - view->start_time;
1803 /* Three git seconds are a long time ... */
1804 if (secs > 2)
1805 string_format_from(state, &statelen, " loading %lds", secs);
1806 }
1808 string_format_from(buf, &bufpos, "[%s]", view->name);
1809 if (*view->ref && bufpos < view->width) {
1810 size_t refsize = strlen(view->ref);
1811 size_t minsize = bufpos + 1 + /* abbrev= */ 7 + 1 + statelen;
1813 if (minsize < view->width)
1814 refsize = view->width - minsize + 7;
1815 string_format_from(buf, &bufpos, " %.*s", (int) refsize, view->ref);
1816 }
1818 if (statelen && bufpos < view->width) {
1819 string_format_from(buf, &bufpos, "%s", state);
1820 }
1822 if (view == display[current_view])
1823 wbkgdset(window, get_line_attr(LINE_TITLE_FOCUS));
1824 else
1825 wbkgdset(window, get_line_attr(LINE_TITLE_BLUR));
1827 mvwaddnstr(window, 0, 0, buf, bufpos);
1828 wclrtoeol(window);
1829 wnoutrefresh(window);
1830 }
1832 static int
1833 apply_step(double step, int value)
1834 {
1835 if (step >= 1)
1836 return (int) step;
1837 value *= step + 0.01;
1838 return value ? value : 1;
1839 }
1841 static void
1842 resize_display(void)
1843 {
1844 int offset, i;
1845 struct view *base = display[0];
1846 struct view *view = display[1] ? display[1] : display[0];
1848 /* Setup window dimensions */
1850 getmaxyx(stdscr, base->height, base->width);
1852 /* Make room for the status window. */
1853 base->height -= 1;
1855 if (view != base) {
1856 /* Horizontal split. */
1857 view->width = base->width;
1858 view->height = apply_step(opt_scale_split_view, base->height);
1859 view->height = MAX(view->height, MIN_VIEW_HEIGHT);
1860 view->height = MIN(view->height, base->height - MIN_VIEW_HEIGHT);
1861 base->height -= view->height;
1863 /* Make room for the title bar. */
1864 view->height -= 1;
1865 }
1867 /* Make room for the title bar. */
1868 base->height -= 1;
1870 offset = 0;
1872 foreach_displayed_view (view, i) {
1873 if (!display_win[i]) {
1874 display_win[i] = newwin(view->height, view->width, offset, 0);
1875 if (!display_win[i])
1876 die("Failed to create %s view", view->name);
1878 scrollok(display_win[i], FALSE);
1880 display_title[i] = newwin(1, view->width, offset + view->height, 0);
1881 if (!display_title[i])
1882 die("Failed to create title window");
1884 } else {
1885 wresize(display_win[i], view->height, view->width);
1886 mvwin(display_win[i], offset, 0);
1887 mvwin(display_title[i], offset + view->height, 0);
1888 }
1890 view->win = display_win[i];
1892 offset += view->height + 1;
1893 }
1894 }
1896 static void
1897 redraw_display(bool clear)
1898 {
1899 struct view *view;
1900 int i;
1902 foreach_displayed_view (view, i) {
1903 if (clear)
1904 wclear(view->win);
1905 redraw_view(view);
1906 update_view_title(view);
1907 }
1908 }
1911 /*
1912 * Option management
1913 */
1915 #define TOGGLE_MENU \
1916 TOGGLE_(LINENO, '.', "line numbers", &opt_line_number, NULL) \
1917 TOGGLE_(DATE, 'D', "dates", &opt_date, date_map) \
1918 TOGGLE_(AUTHOR, 'A', "author names", &opt_author, author_map) \
1919 TOGGLE_(GRAPHIC, '~', "graphics", &opt_line_graphics, graphic_map) \
1920 TOGGLE_(REV_GRAPH, 'g', "revision graph", &opt_rev_graph, NULL) \
1921 TOGGLE_(REFS, 'F', "reference display", &opt_show_refs, NULL)
1923 static void
1924 toggle_option(enum request request)
1925 {
1926 const struct {
1927 enum request request;
1928 const struct enum_map *map;
1929 size_t map_size;
1930 } data[] = {
1931 #define TOGGLE_(id, key, help, value, map) { REQ_TOGGLE_ ## id, map, ARRAY_SIZE(map) },
1932 TOGGLE_MENU
1933 #undef TOGGLE_
1934 };
1935 const struct menu_item menu[] = {
1936 #define TOGGLE_(id, key, help, value, map) { key, help, value },
1937 TOGGLE_MENU
1938 #undef TOGGLE_
1939 { 0 }
1940 };
1941 int i = 0;
1943 if (request == REQ_OPTIONS) {
1944 if (!prompt_menu("Toggle option", menu, &i))
1945 return;
1946 } else {
1947 while (i < ARRAY_SIZE(data) && data[i].request != request)
1948 i++;
1949 if (i >= ARRAY_SIZE(data))
1950 die("Invalid request (%d)", request);
1951 }
1953 if (data[i].map != NULL) {
1954 unsigned int *opt = menu[i].data;
1956 *opt = (*opt + 1) % data[i].map_size;
1957 redraw_display(FALSE);
1958 report("Displaying %s %s", enum_name(data[i].map[*opt]), menu[i].text);
1960 } else {
1961 bool *option = menu[i].data;
1963 *option = !*option;
1964 redraw_display(FALSE);
1965 report("%sabling %s", *option ? "En" : "Dis", menu[i].text);
1966 }
1967 }
1969 static void
1970 maximize_view(struct view *view)
1971 {
1972 memset(display, 0, sizeof(display));
1973 current_view = 0;
1974 display[current_view] = view;
1975 resize_display();
1976 redraw_display(FALSE);
1977 report("");
1978 }
1981 /*
1982 * Navigation
1983 */
1985 static bool
1986 goto_view_line(struct view *view, unsigned long offset, unsigned long lineno)
1987 {
1988 if (lineno >= view->lines)
1989 lineno = view->lines > 0 ? view->lines - 1 : 0;
1991 if (offset > lineno || offset + view->height <= lineno) {
1992 unsigned long half = view->height / 2;
1994 if (lineno > half)
1995 offset = lineno - half;
1996 else
1997 offset = 0;
1998 }
2000 if (offset != view->offset || lineno != view->lineno) {
2001 view->offset = offset;
2002 view->lineno = lineno;
2003 return TRUE;
2004 }
2006 return FALSE;
2007 }
2009 /* Scrolling backend */
2010 static void
2011 do_scroll_view(struct view *view, int lines)
2012 {
2013 bool redraw_current_line = FALSE;
2015 /* The rendering expects the new offset. */
2016 view->offset += lines;
2018 assert(0 <= view->offset && view->offset < view->lines);
2019 assert(lines);
2021 /* Move current line into the view. */
2022 if (view->lineno < view->offset) {
2023 view->lineno = view->offset;
2024 redraw_current_line = TRUE;
2025 } else if (view->lineno >= view->offset + view->height) {
2026 view->lineno = view->offset + view->height - 1;
2027 redraw_current_line = TRUE;
2028 }
2030 assert(view->offset <= view->lineno && view->lineno < view->lines);
2032 /* Redraw the whole screen if scrolling is pointless. */
2033 if (view->height < ABS(lines)) {
2034 redraw_view(view);
2036 } else {
2037 int line = lines > 0 ? view->height - lines : 0;
2038 int end = line + ABS(lines);
2040 scrollok(view->win, TRUE);
2041 wscrl(view->win, lines);
2042 scrollok(view->win, FALSE);
2044 while (line < end && draw_view_line(view, line))
2045 line++;
2047 if (redraw_current_line)
2048 draw_view_line(view, view->lineno - view->offset);
2049 wnoutrefresh(view->win);
2050 }
2052 view->has_scrolled = TRUE;
2053 report("");
2054 }
2056 /* Scroll frontend */
2057 static void
2058 scroll_view(struct view *view, enum request request)
2059 {
2060 int lines = 1;
2062 assert(view_is_displayed(view));
2064 switch (request) {
2065 case REQ_SCROLL_FIRST_COL:
2066 view->yoffset = 0;
2067 redraw_view_from(view, 0);
2068 report("");
2069 return;
2070 case REQ_SCROLL_LEFT:
2071 if (view->yoffset == 0) {
2072 report("Cannot scroll beyond the first column");
2073 return;
2074 }
2075 if (view->yoffset <= apply_step(opt_hscroll, view->width))
2076 view->yoffset = 0;
2077 else
2078 view->yoffset -= apply_step(opt_hscroll, view->width);
2079 redraw_view_from(view, 0);
2080 report("");
2081 return;
2082 case REQ_SCROLL_RIGHT:
2083 view->yoffset += apply_step(opt_hscroll, view->width);
2084 redraw_view(view);
2085 report("");
2086 return;
2087 case REQ_SCROLL_PAGE_DOWN:
2088 lines = view->height;
2089 case REQ_SCROLL_LINE_DOWN:
2090 if (view->offset + lines > view->lines)
2091 lines = view->lines - view->offset;
2093 if (lines == 0 || view->offset + view->height >= view->lines) {
2094 report("Cannot scroll beyond the last line");
2095 return;
2096 }
2097 break;
2099 case REQ_SCROLL_PAGE_UP:
2100 lines = view->height;
2101 case REQ_SCROLL_LINE_UP:
2102 if (lines > view->offset)
2103 lines = view->offset;
2105 if (lines == 0) {
2106 report("Cannot scroll beyond the first line");
2107 return;
2108 }
2110 lines = -lines;
2111 break;
2113 default:
2114 die("request %d not handled in switch", request);
2115 }
2117 do_scroll_view(view, lines);
2118 }
2120 /* Cursor moving */
2121 static void
2122 move_view(struct view *view, enum request request)
2123 {
2124 int scroll_steps = 0;
2125 int steps;
2127 switch (request) {
2128 case REQ_MOVE_FIRST_LINE:
2129 steps = -view->lineno;
2130 break;
2132 case REQ_MOVE_LAST_LINE:
2133 steps = view->lines - view->lineno - 1;
2134 break;
2136 case REQ_MOVE_PAGE_UP:
2137 steps = view->height > view->lineno
2138 ? -view->lineno : -view->height;
2139 break;
2141 case REQ_MOVE_PAGE_DOWN:
2142 steps = view->lineno + view->height >= view->lines
2143 ? view->lines - view->lineno - 1 : view->height;
2144 break;
2146 case REQ_MOVE_UP:
2147 steps = -1;
2148 break;
2150 case REQ_MOVE_DOWN:
2151 steps = 1;
2152 break;
2154 default:
2155 die("request %d not handled in switch", request);
2156 }
2158 if (steps <= 0 && view->lineno == 0) {
2159 report("Cannot move beyond the first line");
2160 return;
2162 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
2163 report("Cannot move beyond the last line");
2164 return;
2165 }
2167 /* Move the current line */
2168 view->lineno += steps;
2169 assert(0 <= view->lineno && view->lineno < view->lines);
2171 /* Check whether the view needs to be scrolled */
2172 if (view->lineno < view->offset ||
2173 view->lineno >= view->offset + view->height) {
2174 scroll_steps = steps;
2175 if (steps < 0 && -steps > view->offset) {
2176 scroll_steps = -view->offset;
2178 } else if (steps > 0) {
2179 if (view->lineno == view->lines - 1 &&
2180 view->lines > view->height) {
2181 scroll_steps = view->lines - view->offset - 1;
2182 if (scroll_steps >= view->height)
2183 scroll_steps -= view->height - 1;
2184 }
2185 }
2186 }
2188 if (!view_is_displayed(view)) {
2189 view->offset += scroll_steps;
2190 assert(0 <= view->offset && view->offset < view->lines);
2191 view->ops->select(view, &view->line[view->lineno]);
2192 return;
2193 }
2195 /* Repaint the old "current" line if we be scrolling */
2196 if (ABS(steps) < view->height)
2197 draw_view_line(view, view->lineno - steps - view->offset);
2199 if (scroll_steps) {
2200 do_scroll_view(view, scroll_steps);
2201 return;
2202 }
2204 /* Draw the current line */
2205 draw_view_line(view, view->lineno - view->offset);
2207 wnoutrefresh(view->win);
2208 report("");
2209 }
2212 /*
2213 * Searching
2214 */
2216 static void search_view(struct view *view, enum request request);
2218 static bool
2219 grep_text(struct view *view, const char *text[])
2220 {
2221 regmatch_t pmatch;
2222 size_t i;
2224 for (i = 0; text[i]; i++)
2225 if (*text[i] &&
2226 regexec(view->regex, text[i], 1, &pmatch, 0) != REG_NOMATCH)
2227 return TRUE;
2228 return FALSE;
2229 }
2231 static void
2232 select_view_line(struct view *view, unsigned long lineno)
2233 {
2234 unsigned long old_lineno = view->lineno;
2235 unsigned long old_offset = view->offset;
2237 if (goto_view_line(view, view->offset, lineno)) {
2238 if (view_is_displayed(view)) {
2239 if (old_offset != view->offset) {
2240 redraw_view(view);
2241 } else {
2242 draw_view_line(view, old_lineno - view->offset);
2243 draw_view_line(view, view->lineno - view->offset);
2244 wnoutrefresh(view->win);
2245 }
2246 } else {
2247 view->ops->select(view, &view->line[view->lineno]);
2248 }
2249 }
2250 }
2252 static void
2253 find_next(struct view *view, enum request request)
2254 {
2255 unsigned long lineno = view->lineno;
2256 int direction;
2258 if (!*view->grep) {
2259 if (!*opt_search)
2260 report("No previous search");
2261 else
2262 search_view(view, request);
2263 return;
2264 }
2266 switch (request) {
2267 case REQ_SEARCH:
2268 case REQ_FIND_NEXT:
2269 direction = 1;
2270 break;
2272 case REQ_SEARCH_BACK:
2273 case REQ_FIND_PREV:
2274 direction = -1;
2275 break;
2277 default:
2278 return;
2279 }
2281 if (request == REQ_FIND_NEXT || request == REQ_FIND_PREV)
2282 lineno += direction;
2284 /* Note, lineno is unsigned long so will wrap around in which case it
2285 * will become bigger than view->lines. */
2286 for (; lineno < view->lines; lineno += direction) {
2287 if (view->ops->grep(view, &view->line[lineno])) {
2288 select_view_line(view, lineno);
2289 report("Line %ld matches '%s'", lineno + 1, view->grep);
2290 return;
2291 }
2292 }
2294 report("No match found for '%s'", view->grep);
2295 }
2297 static void
2298 search_view(struct view *view, enum request request)
2299 {
2300 int regex_err;
2302 if (view->regex) {
2303 regfree(view->regex);
2304 *view->grep = 0;
2305 } else {
2306 view->regex = calloc(1, sizeof(*view->regex));
2307 if (!view->regex)
2308 return;
2309 }
2311 regex_err = regcomp(view->regex, opt_search, REG_EXTENDED);
2312 if (regex_err != 0) {
2313 char buf[SIZEOF_STR] = "unknown error";
2315 regerror(regex_err, view->regex, buf, sizeof(buf));
2316 report("Search failed: %s", buf);
2317 return;
2318 }
2320 string_copy(view->grep, opt_search);
2322 find_next(view, request);
2323 }
2325 /*
2326 * Incremental updating
2327 */
2329 static void
2330 reset_view(struct view *view)
2331 {
2332 int i;
2334 for (i = 0; i < view->lines; i++)
2335 free(view->line[i].data);
2336 free(view->line);
2338 view->p_offset = view->offset;
2339 view->p_yoffset = view->yoffset;
2340 view->p_lineno = view->lineno;
2342 view->line = NULL;
2343 view->offset = 0;
2344 view->yoffset = 0;
2345 view->lines = 0;
2346 view->lineno = 0;
2347 view->vid[0] = 0;
2348 view->update_secs = 0;
2349 }
2351 static const char *
2352 format_arg(const char *name)
2353 {
2354 static struct {
2355 const char *name;
2356 size_t namelen;
2357 const char *value;
2358 const char *value_if_empty;
2359 } vars[] = {
2360 #define FORMAT_VAR(name, value, value_if_empty) \
2361 { name, STRING_SIZE(name), value, value_if_empty }
2362 FORMAT_VAR("%(directory)", opt_path, "."),
2363 FORMAT_VAR("%(file)", opt_file, ""),
2364 FORMAT_VAR("%(ref)", opt_ref, "HEAD"),
2365 FORMAT_VAR("%(head)", ref_head, ""),
2366 FORMAT_VAR("%(commit)", ref_commit, ""),
2367 FORMAT_VAR("%(blob)", ref_blob, ""),
2368 FORMAT_VAR("%(branch)", ref_branch, ""),
2369 };
2370 int i;
2372 for (i = 0; i < ARRAY_SIZE(vars); i++)
2373 if (!strncmp(name, vars[i].name, vars[i].namelen))
2374 return *vars[i].value ? vars[i].value : vars[i].value_if_empty;
2376 report("Unknown replacement: `%s`", name);
2377 return NULL;
2378 }
2380 static bool
2381 format_argv(const char ***dst_argv, const char *src_argv[], bool replace, bool first)
2382 {
2383 char buf[SIZEOF_STR];
2384 int argc;
2386 argv_free(*dst_argv);
2388 for (argc = 0; src_argv[argc]; argc++) {
2389 const char *arg = src_argv[argc];
2390 size_t bufpos = 0;
2392 if (!strcmp(arg, "%(fileargs)")) {
2393 if (!argv_append_array(dst_argv, opt_file_argv))
2394 break;
2395 continue;
2397 } else if (!strcmp(arg, "%(diffargs)")) {
2398 if (!argv_append_array(dst_argv, opt_diff_argv))
2399 break;
2400 continue;
2402 } else if (!strcmp(arg, "%(blameargs)")) {
2403 if (!argv_append_array(dst_argv, opt_blame_argv))
2404 break;
2405 continue;
2407 } else if (!strcmp(arg, "%(revargs)") ||
2408 (first && !strcmp(arg, "%(commit)"))) {
2409 if (!argv_append_array(dst_argv, opt_rev_argv))
2410 break;
2411 continue;
2412 }
2414 while (arg) {
2415 char *next = strstr(arg, "%(");
2416 int len = next - arg;
2417 const char *value;
2419 if (!next || !replace) {
2420 len = strlen(arg);
2421 value = "";
2423 } else {
2424 value = format_arg(next);
2426 if (!value) {
2427 return FALSE;
2428 }
2429 }
2431 if (!string_format_from(buf, &bufpos, "%.*s%s", len, arg, value))
2432 return FALSE;
2434 arg = next && replace ? strchr(next, ')') + 1 : NULL;
2435 }
2437 if (!argv_append(dst_argv, buf))
2438 break;
2439 }
2441 return src_argv[argc] == NULL;
2442 }
2444 static bool
2445 restore_view_position(struct view *view)
2446 {
2447 if (!view->p_restore || (view->pipe && view->lines <= view->p_lineno))
2448 return FALSE;
2450 /* Changing the view position cancels the restoring. */
2451 /* FIXME: Changing back to the first line is not detected. */
2452 if (view->offset != 0 || view->lineno != 0) {
2453 view->p_restore = FALSE;
2454 return FALSE;
2455 }
2457 if (goto_view_line(view, view->p_offset, view->p_lineno) &&
2458 view_is_displayed(view))
2459 werase(view->win);
2461 view->yoffset = view->p_yoffset;
2462 view->p_restore = FALSE;
2464 return TRUE;
2465 }
2467 static void
2468 end_update(struct view *view, bool force)
2469 {
2470 if (!view->pipe)
2471 return;
2472 while (!view->ops->read(view, NULL))
2473 if (!force)
2474 return;
2475 if (force)
2476 io_kill(view->pipe);
2477 io_done(view->pipe);
2478 view->pipe = NULL;
2479 }
2481 static void
2482 setup_update(struct view *view, const char *vid)
2483 {
2484 reset_view(view);
2485 string_copy_rev(view->vid, vid);
2486 view->pipe = &view->io;
2487 view->start_time = time(NULL);
2488 }
2490 static bool
2491 prepare_io(struct view *view, const char *dir, const char *argv[], bool replace)
2492 {
2493 view->dir = dir;
2494 return format_argv(&view->argv, argv, replace, !view->prev);
2495 }
2497 static bool
2498 prepare_update(struct view *view, const char *argv[], const char *dir)
2499 {
2500 if (view->pipe)
2501 end_update(view, TRUE);
2502 return prepare_io(view, dir, argv, FALSE);
2503 }
2505 static bool
2506 start_update(struct view *view, const char **argv, const char *dir)
2507 {
2508 if (view->pipe)
2509 io_done(view->pipe);
2510 return prepare_io(view, dir, argv, FALSE) &&
2511 io_run(&view->io, IO_RD, dir, view->argv);
2512 }
2514 static bool
2515 prepare_update_file(struct view *view, const char *name)
2516 {
2517 if (view->pipe)
2518 end_update(view, TRUE);
2519 argv_free(view->argv);
2520 return io_open(&view->io, "%s/%s", opt_cdup[0] ? opt_cdup : ".", name);
2521 }
2523 static bool
2524 begin_update(struct view *view, bool refresh)
2525 {
2526 if (view->pipe)
2527 end_update(view, TRUE);
2529 if (!refresh) {
2530 if (view->ops->prepare) {
2531 if (!view->ops->prepare(view))
2532 return FALSE;
2533 } else if (!prepare_io(view, NULL, view->ops->argv, TRUE)) {
2534 return FALSE;
2535 }
2537 /* Put the current ref_* value to the view title ref
2538 * member. This is needed by the blob view. Most other
2539 * views sets it automatically after loading because the
2540 * first line is a commit line. */
2541 string_copy_rev(view->ref, view->id);
2542 }
2544 if (view->argv && view->argv[0] &&
2545 !io_run(&view->io, IO_RD, view->dir, view->argv))
2546 return FALSE;
2548 setup_update(view, view->id);
2550 return TRUE;
2551 }
2553 static bool
2554 update_view(struct view *view)
2555 {
2556 char out_buffer[BUFSIZ * 2];
2557 char *line;
2558 /* Clear the view and redraw everything since the tree sorting
2559 * might have rearranged things. */
2560 bool redraw = view->lines == 0;
2561 bool can_read = TRUE;
2563 if (!view->pipe)
2564 return TRUE;
2566 if (!io_can_read(view->pipe, FALSE)) {
2567 if (view->lines == 0 && view_is_displayed(view)) {
2568 time_t secs = time(NULL) - view->start_time;
2570 if (secs > 1 && secs > view->update_secs) {
2571 if (view->update_secs == 0)
2572 redraw_view(view);
2573 update_view_title(view);
2574 view->update_secs = secs;
2575 }
2576 }
2577 return TRUE;
2578 }
2580 for (; (line = io_get(view->pipe, '\n', can_read)); can_read = FALSE) {
2581 if (opt_iconv_in != ICONV_NONE) {
2582 ICONV_CONST char *inbuf = line;
2583 size_t inlen = strlen(line) + 1;
2585 char *outbuf = out_buffer;
2586 size_t outlen = sizeof(out_buffer);
2588 size_t ret;
2590 ret = iconv(opt_iconv_in, &inbuf, &inlen, &outbuf, &outlen);
2591 if (ret != (size_t) -1)
2592 line = out_buffer;
2593 }
2595 if (!view->ops->read(view, line)) {
2596 report("Allocation failure");
2597 end_update(view, TRUE);
2598 return FALSE;
2599 }
2600 }
2602 {
2603 unsigned long lines = view->lines;
2604 int digits;
2606 for (digits = 0; lines; digits++)
2607 lines /= 10;
2609 /* Keep the displayed view in sync with line number scaling. */
2610 if (digits != view->digits) {
2611 view->digits = digits;
2612 if (opt_line_number || view->type == VIEW_BLAME)
2613 redraw = TRUE;
2614 }
2615 }
2617 if (io_error(view->pipe)) {
2618 report("Failed to read: %s", io_strerror(view->pipe));
2619 end_update(view, TRUE);
2621 } else if (io_eof(view->pipe)) {
2622 if (view_is_displayed(view))
2623 report("");
2624 end_update(view, FALSE);
2625 }
2627 if (restore_view_position(view))
2628 redraw = TRUE;
2630 if (!view_is_displayed(view))
2631 return TRUE;
2633 if (redraw)
2634 redraw_view_from(view, 0);
2635 else
2636 redraw_view_dirty(view);
2638 /* Update the title _after_ the redraw so that if the redraw picks up a
2639 * commit reference in view->ref it'll be available here. */
2640 update_view_title(view);
2641 return TRUE;
2642 }
2644 DEFINE_ALLOCATOR(realloc_lines, struct line, 256)
2646 static struct line *
2647 add_line_data(struct view *view, void *data, enum line_type type)
2648 {
2649 struct line *line;
2651 if (!realloc_lines(&view->line, view->lines, 1))
2652 return NULL;
2654 line = &view->line[view->lines++];
2655 memset(line, 0, sizeof(*line));
2656 line->type = type;
2657 line->data = data;
2658 line->dirty = 1;
2660 return line;
2661 }
2663 static struct line *
2664 add_line_text(struct view *view, const char *text, enum line_type type)
2665 {
2666 char *data = text ? strdup(text) : NULL;
2668 return data ? add_line_data(view, data, type) : NULL;
2669 }
2671 static struct line *
2672 add_line_format(struct view *view, enum line_type type, const char *fmt, ...)
2673 {
2674 char buf[SIZEOF_STR];
2675 va_list args;
2677 va_start(args, fmt);
2678 if (vsnprintf(buf, sizeof(buf), fmt, args) >= sizeof(buf))
2679 buf[0] = 0;
2680 va_end(args);
2682 return buf[0] ? add_line_text(view, buf, type) : NULL;
2683 }
2685 /*
2686 * View opening
2687 */
2689 enum open_flags {
2690 OPEN_DEFAULT = 0, /* Use default view switching. */
2691 OPEN_SPLIT = 1, /* Split current view. */
2692 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
2693 OPEN_REFRESH = 16, /* Refresh view using previous command. */
2694 OPEN_PREPARED = 32, /* Open already prepared command. */
2695 };
2697 static void
2698 open_view(struct view *prev, enum request request, enum open_flags flags)
2699 {
2700 bool split = !!(flags & OPEN_SPLIT);
2701 bool reload = !!(flags & (OPEN_RELOAD | OPEN_REFRESH | OPEN_PREPARED));
2702 bool nomaximize = !!(flags & OPEN_REFRESH);
2703 struct view *view = VIEW(request);
2704 int nviews = displayed_views();
2705 struct view *base_view = display[0];
2707 if (view == prev && nviews == 1 && !reload) {
2708 report("Already in %s view", view->name);
2709 return;
2710 }
2712 if (view->git_dir && !opt_git_dir[0]) {
2713 report("The %s view is disabled in pager view", view->name);
2714 return;
2715 }
2717 if (split) {
2718 display[1] = view;
2719 current_view = 1;
2720 view->parent = prev;
2721 } else if (!nomaximize) {
2722 /* Maximize the current view. */
2723 memset(display, 0, sizeof(display));
2724 current_view = 0;
2725 display[current_view] = view;
2726 }
2728 /* No prev signals that this is the first loaded view. */
2729 if (prev && view != prev) {
2730 view->prev = prev;
2731 }
2733 /* Resize the view when switching between split- and full-screen,
2734 * or when switching between two different full-screen views. */
2735 if (nviews != displayed_views() ||
2736 (nviews == 1 && base_view != display[0]))
2737 resize_display();
2739 if (view->ops->open) {
2740 if (view->pipe)
2741 end_update(view, TRUE);
2742 if (!view->ops->open(view)) {
2743 report("Failed to load %s view", view->name);
2744 return;
2745 }
2746 restore_view_position(view);
2748 } else if ((reload || strcmp(view->vid, view->id)) &&
2749 !begin_update(view, flags & (OPEN_REFRESH | OPEN_PREPARED))) {
2750 report("Failed to load %s view", view->name);
2751 return;
2752 }
2754 if (split && prev->lineno - prev->offset >= prev->height) {
2755 /* Take the title line into account. */
2756 int lines = prev->lineno - prev->offset - prev->height + 1;
2758 /* Scroll the view that was split if the current line is
2759 * outside the new limited view. */
2760 do_scroll_view(prev, lines);
2761 }
2763 if (prev && view != prev && split && view_is_displayed(prev)) {
2764 /* "Blur" the previous view. */
2765 update_view_title(prev);
2766 }
2768 if (view->pipe && view->lines == 0) {
2769 /* Clear the old view and let the incremental updating refill
2770 * the screen. */
2771 werase(view->win);
2772 view->p_restore = flags & (OPEN_RELOAD | OPEN_REFRESH);
2773 report("");
2774 } else if (view_is_displayed(view)) {
2775 redraw_view(view);
2776 report("");
2777 }
2778 }
2780 static void
2781 open_external_viewer(const char *argv[], const char *dir)
2782 {
2783 def_prog_mode(); /* save current tty modes */
2784 endwin(); /* restore original tty modes */
2785 io_run_fg(argv, dir);
2786 fprintf(stderr, "Press Enter to continue");
2787 getc(opt_tty);
2788 reset_prog_mode();
2789 redraw_display(TRUE);
2790 }
2792 static void
2793 open_mergetool(const char *file)
2794 {
2795 const char *mergetool_argv[] = { "git", "mergetool", file, NULL };
2797 open_external_viewer(mergetool_argv, opt_cdup);
2798 }
2800 static void
2801 open_editor(const char *file)
2802 {
2803 const char *editor_argv[] = { "vi", file, NULL };
2804 const char *editor;
2806 editor = getenv("GIT_EDITOR");
2807 if (!editor && *opt_editor)
2808 editor = opt_editor;
2809 if (!editor)
2810 editor = getenv("VISUAL");
2811 if (!editor)
2812 editor = getenv("EDITOR");
2813 if (!editor)
2814 editor = "vi";
2816 editor_argv[0] = editor;
2817 open_external_viewer(editor_argv, opt_cdup);
2818 }
2820 static void
2821 open_run_request(enum request request)
2822 {
2823 struct run_request *req = get_run_request(request);
2824 const char **argv = NULL;
2826 if (!req) {
2827 report("Unknown run request");
2828 return;
2829 }
2831 if (format_argv(&argv, req->argv, TRUE, FALSE))
2832 open_external_viewer(argv, NULL);
2833 if (argv)
2834 argv_free(argv);
2835 free(argv);
2836 }
2838 /*
2839 * User request switch noodle
2840 */
2842 static int
2843 view_driver(struct view *view, enum request request)
2844 {
2845 int i;
2847 if (request == REQ_NONE)
2848 return TRUE;
2850 if (request > REQ_NONE) {
2851 open_run_request(request);
2852 view_request(view, REQ_REFRESH);
2853 return TRUE;
2854 }
2856 request = view_request(view, request);
2857 if (request == REQ_NONE)
2858 return TRUE;
2860 switch (request) {
2861 case REQ_MOVE_UP:
2862 case REQ_MOVE_DOWN:
2863 case REQ_MOVE_PAGE_UP:
2864 case REQ_MOVE_PAGE_DOWN:
2865 case REQ_MOVE_FIRST_LINE:
2866 case REQ_MOVE_LAST_LINE:
2867 move_view(view, request);
2868 break;
2870 case REQ_SCROLL_FIRST_COL:
2871 case REQ_SCROLL_LEFT:
2872 case REQ_SCROLL_RIGHT:
2873 case REQ_SCROLL_LINE_DOWN:
2874 case REQ_SCROLL_LINE_UP:
2875 case REQ_SCROLL_PAGE_DOWN:
2876 case REQ_SCROLL_PAGE_UP:
2877 scroll_view(view, request);
2878 break;
2880 case REQ_VIEW_BLAME:
2881 if (!opt_file[0]) {
2882 report("No file chosen, press %s to open tree view",
2883 get_key(view->keymap, REQ_VIEW_TREE));
2884 break;
2885 }
2886 open_view(view, request, OPEN_DEFAULT);
2887 break;
2889 case REQ_VIEW_BLOB:
2890 if (!ref_blob[0]) {
2891 report("No file chosen, press %s to open tree view",
2892 get_key(view->keymap, REQ_VIEW_TREE));
2893 break;
2894 }
2895 open_view(view, request, OPEN_DEFAULT);
2896 break;
2898 case REQ_VIEW_PAGER:
2899 if (view == NULL) {
2900 if (!io_open(&VIEW(REQ_VIEW_PAGER)->io, ""))
2901 die("Failed to open stdin");
2902 open_view(view, request, OPEN_PREPARED);
2903 break;
2904 }
2906 if (!VIEW(REQ_VIEW_PAGER)->pipe && !VIEW(REQ_VIEW_PAGER)->lines) {
2907 report("No pager content, press %s to run command from prompt",
2908 get_key(view->keymap, REQ_PROMPT));
2909 break;
2910 }
2911 open_view(view, request, OPEN_DEFAULT);
2912 break;
2914 case REQ_VIEW_STAGE:
2915 if (!VIEW(REQ_VIEW_STAGE)->lines) {
2916 report("No stage content, press %s to open the status view and choose file",
2917 get_key(view->keymap, REQ_VIEW_STATUS));
2918 break;
2919 }
2920 open_view(view, request, OPEN_DEFAULT);
2921 break;
2923 case REQ_VIEW_STATUS:
2924 if (opt_is_inside_work_tree == FALSE) {
2925 report("The status view requires a working tree");
2926 break;
2927 }
2928 open_view(view, request, OPEN_DEFAULT);
2929 break;
2931 case REQ_VIEW_MAIN:
2932 case REQ_VIEW_DIFF:
2933 case REQ_VIEW_LOG:
2934 case REQ_VIEW_TREE:
2935 case REQ_VIEW_HELP:
2936 case REQ_VIEW_BRANCH:
2937 open_view(view, request, OPEN_DEFAULT);
2938 break;
2940 case REQ_NEXT:
2941 case REQ_PREVIOUS:
2942 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
2944 if (view->parent) {
2945 int line;
2947 view = view->parent;
2948 line = view->lineno;
2949 move_view(view, request);
2950 if (view_is_displayed(view))
2951 update_view_title(view);
2952 if (line != view->lineno)
2953 view_request(view, REQ_ENTER);
2954 } else {
2955 move_view(view, request);
2956 }
2957 break;
2959 case REQ_VIEW_NEXT:
2960 {
2961 int nviews = displayed_views();
2962 int next_view = (current_view + 1) % nviews;
2964 if (next_view == current_view) {
2965 report("Only one view is displayed");
2966 break;
2967 }
2969 current_view = next_view;
2970 /* Blur out the title of the previous view. */
2971 update_view_title(view);
2972 report("");
2973 break;
2974 }
2975 case REQ_REFRESH:
2976 report("Refreshing is not yet supported for the %s view", view->name);
2977 break;
2979 case REQ_MAXIMIZE:
2980 if (displayed_views() == 2)
2981 maximize_view(view);
2982 break;
2984 case REQ_OPTIONS:
2985 case REQ_TOGGLE_LINENO:
2986 case REQ_TOGGLE_DATE:
2987 case REQ_TOGGLE_AUTHOR:
2988 case REQ_TOGGLE_GRAPHIC:
2989 case REQ_TOGGLE_REV_GRAPH:
2990 case REQ_TOGGLE_REFS:
2991 toggle_option(request);
2992 break;
2994 case REQ_TOGGLE_SORT_FIELD:
2995 case REQ_TOGGLE_SORT_ORDER:
2996 report("Sorting is not yet supported for the %s view", view->name);
2997 break;
2999 case REQ_SEARCH:
3000 case REQ_SEARCH_BACK:
3001 search_view(view, request);
3002 break;
3004 case REQ_FIND_NEXT:
3005 case REQ_FIND_PREV:
3006 find_next(view, request);
3007 break;
3009 case REQ_STOP_LOADING:
3010 foreach_view(view, i) {
3011 if (view->pipe)
3012 report("Stopped loading the %s view", view->name),
3013 end_update(view, TRUE);
3014 }
3015 break;
3017 case REQ_SHOW_VERSION:
3018 report("tig-%s (built %s)", TIG_VERSION, __DATE__);
3019 return TRUE;
3021 case REQ_SCREEN_REDRAW:
3022 redraw_display(TRUE);
3023 break;
3025 case REQ_EDIT:
3026 report("Nothing to edit");
3027 break;
3029 case REQ_ENTER:
3030 report("Nothing to enter");
3031 break;
3033 case REQ_VIEW_CLOSE:
3034 /* XXX: Mark closed views by letting view->prev point to the
3035 * view itself. Parents to closed view should never be
3036 * followed. */
3037 if (view->prev && view->prev != view) {
3038 maximize_view(view->prev);
3039 view->prev = view;
3040 break;
3041 }
3042 /* Fall-through */
3043 case REQ_QUIT:
3044 return FALSE;
3046 default:
3047 report("Unknown key, press %s for help",
3048 get_key(view->keymap, REQ_VIEW_HELP));
3049 return TRUE;
3050 }
3052 return TRUE;
3053 }
3056 /*
3057 * View backend utilities
3058 */
3060 enum sort_field {
3061 ORDERBY_NAME,
3062 ORDERBY_DATE,
3063 ORDERBY_AUTHOR,
3064 };
3066 struct sort_state {
3067 const enum sort_field *fields;
3068 size_t size, current;
3069 bool reverse;
3070 };
3072 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3073 #define get_sort_field(state) ((state).fields[(state).current])
3074 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3076 static void
3077 sort_view(struct view *view, enum request request, struct sort_state *state,
3078 int (*compare)(const void *, const void *))
3079 {
3080 switch (request) {
3081 case REQ_TOGGLE_SORT_FIELD:
3082 state->current = (state->current + 1) % state->size;
3083 break;
3085 case REQ_TOGGLE_SORT_ORDER:
3086 state->reverse = !state->reverse;
3087 break;
3088 default:
3089 die("Not a sort request");
3090 }
3092 qsort(view->line, view->lines, sizeof(*view->line), compare);
3093 redraw_view(view);
3094 }
3096 DEFINE_ALLOCATOR(realloc_authors, const char *, 256)
3098 /* Small author cache to reduce memory consumption. It uses binary
3099 * search to lookup or find place to position new entries. No entries
3100 * are ever freed. */
3101 static const char *
3102 get_author(const char *name)
3103 {
3104 static const char **authors;
3105 static size_t authors_size;
3106 int from = 0, to = authors_size - 1;
3108 while (from <= to) {
3109 size_t pos = (to + from) / 2;
3110 int cmp = strcmp(name, authors[pos]);
3112 if (!cmp)
3113 return authors[pos];
3115 if (cmp < 0)
3116 to = pos - 1;
3117 else
3118 from = pos + 1;
3119 }
3121 if (!realloc_authors(&authors, authors_size, 1))
3122 return NULL;
3123 name = strdup(name);
3124 if (!name)
3125 return NULL;
3127 memmove(authors + from + 1, authors + from, (authors_size - from) * sizeof(*authors));
3128 authors[from] = name;
3129 authors_size++;
3131 return name;
3132 }
3134 static void
3135 parse_timesec(struct time *time, const char *sec)
3136 {
3137 time->sec = (time_t) atol(sec);
3138 }
3140 static void
3141 parse_timezone(struct time *time, const char *zone)
3142 {
3143 long tz;
3145 tz = ('0' - zone[1]) * 60 * 60 * 10;
3146 tz += ('0' - zone[2]) * 60 * 60;
3147 tz += ('0' - zone[3]) * 60 * 10;
3148 tz += ('0' - zone[4]) * 60;
3150 if (zone[0] == '-')
3151 tz = -tz;
3153 time->tz = tz;
3154 time->sec -= tz;
3155 }
3157 /* Parse author lines where the name may be empty:
3158 * author <email@address.tld> 1138474660 +0100
3159 */
3160 static void
3161 parse_author_line(char *ident, const char **author, struct time *time)
3162 {
3163 char *nameend = strchr(ident, '<');
3164 char *emailend = strchr(ident, '>');
3166 if (nameend && emailend)
3167 *nameend = *emailend = 0;
3168 ident = chomp_string(ident);
3169 if (!*ident) {
3170 if (nameend)
3171 ident = chomp_string(nameend + 1);
3172 if (!*ident)
3173 ident = "Unknown";
3174 }
3176 *author = get_author(ident);
3178 /* Parse epoch and timezone */
3179 if (emailend && emailend[1] == ' ') {
3180 char *secs = emailend + 2;
3181 char *zone = strchr(secs, ' ');
3183 parse_timesec(time, secs);
3185 if (zone && strlen(zone) == STRING_SIZE(" +0700"))
3186 parse_timezone(time, zone + 1);
3187 }
3188 }
3190 /*
3191 * Pager backend
3192 */
3194 static bool
3195 pager_draw(struct view *view, struct line *line, unsigned int lineno)
3196 {
3197 if (opt_line_number && draw_lineno(view, lineno))
3198 return TRUE;
3200 draw_text(view, line->type, line->data);
3201 return TRUE;
3202 }
3204 static bool
3205 add_describe_ref(char *buf, size_t *bufpos, const char *commit_id, const char *sep)
3206 {
3207 const char *describe_argv[] = { "git", "describe", commit_id, NULL };
3208 char ref[SIZEOF_STR];
3210 if (!io_run_buf(describe_argv, ref, sizeof(ref)) || !*ref)
3211 return TRUE;
3213 /* This is the only fatal call, since it can "corrupt" the buffer. */
3214 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
3215 return FALSE;
3217 return TRUE;
3218 }
3220 static void
3221 add_pager_refs(struct view *view, struct line *line)
3222 {
3223 char buf[SIZEOF_STR];
3224 char *commit_id = (char *)line->data + STRING_SIZE("commit ");
3225 struct ref_list *list;
3226 size_t bufpos = 0, i;
3227 const char *sep = "Refs: ";
3228 bool is_tag = FALSE;
3230 assert(line->type == LINE_COMMIT);
3232 list = get_ref_list(commit_id);
3233 if (!list) {
3234 if (view->type == VIEW_DIFF)
3235 goto try_add_describe_ref;
3236 return;
3237 }
3239 for (i = 0; i < list->size; i++) {
3240 struct ref *ref = list->refs[i];
3241 const char *fmt = ref->tag ? "%s[%s]" :
3242 ref->remote ? "%s<%s>" : "%s%s";
3244 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
3245 return;
3246 sep = ", ";
3247 if (ref->tag)
3248 is_tag = TRUE;
3249 }
3251 if (!is_tag && view->type == VIEW_DIFF) {
3252 try_add_describe_ref:
3253 /* Add <tag>-g<commit_id> "fake" reference. */
3254 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
3255 return;
3256 }
3258 if (bufpos == 0)
3259 return;
3261 add_line_text(view, buf, LINE_PP_REFS);
3262 }
3264 static bool
3265 pager_read(struct view *view, char *data)
3266 {
3267 struct line *line;
3269 if (!data)
3270 return TRUE;
3272 line = add_line_text(view, data, get_line_type(data));
3273 if (!line)
3274 return FALSE;
3276 if (line->type == LINE_COMMIT &&
3277 (view->type == VIEW_DIFF ||
3278 view->type == VIEW_LOG))
3279 add_pager_refs(view, line);
3281 return TRUE;
3282 }
3284 static enum request
3285 pager_request(struct view *view, enum request request, struct line *line)
3286 {
3287 int split = 0;
3289 if (request != REQ_ENTER)
3290 return request;
3292 if (line->type == LINE_COMMIT &&
3293 (view->type == VIEW_LOG ||
3294 view->type == VIEW_PAGER)) {
3295 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
3296 split = 1;
3297 }
3299 /* Always scroll the view even if it was split. That way
3300 * you can use Enter to scroll through the log view and
3301 * split open each commit diff. */
3302 scroll_view(view, REQ_SCROLL_LINE_DOWN);
3304 /* FIXME: A minor workaround. Scrolling the view will call report("")
3305 * but if we are scrolling a non-current view this won't properly
3306 * update the view title. */
3307 if (split)
3308 update_view_title(view);
3310 return REQ_NONE;
3311 }
3313 static bool
3314 pager_grep(struct view *view, struct line *line)
3315 {
3316 const char *text[] = { line->data, NULL };
3318 return grep_text(view, text);
3319 }
3321 static void
3322 pager_select(struct view *view, struct line *line)
3323 {
3324 if (line->type == LINE_COMMIT) {
3325 char *text = (char *)line->data + STRING_SIZE("commit ");
3327 if (view->type != VIEW_PAGER)
3328 string_copy_rev(view->ref, text);
3329 string_copy_rev(ref_commit, text);
3330 }
3331 }
3333 static struct view_ops pager_ops = {
3334 "line",
3335 NULL,
3336 NULL,
3337 pager_read,
3338 pager_draw,
3339 pager_request,
3340 pager_grep,
3341 pager_select,
3342 };
3344 static const char *log_argv[SIZEOF_ARG] = {
3345 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3346 };
3348 static enum request
3349 log_request(struct view *view, enum request request, struct line *line)
3350 {
3351 switch (request) {
3352 case REQ_REFRESH:
3353 load_refs();
3354 open_view(view, REQ_VIEW_LOG, OPEN_REFRESH);
3355 return REQ_NONE;
3356 default:
3357 return pager_request(view, request, line);
3358 }
3359 }
3361 static struct view_ops log_ops = {
3362 "line",
3363 log_argv,
3364 NULL,
3365 pager_read,
3366 pager_draw,
3367 log_request,
3368 pager_grep,
3369 pager_select,
3370 };
3372 static const char *diff_argv[SIZEOF_ARG] = {
3373 "git", "show", "--pretty=fuller", "--no-color", "--root",
3374 "--patch-with-stat", "--find-copies-harder", "-C",
3375 "%(diffargs)", "%(commit)", "--", "%(fileargs)", NULL
3376 };
3378 static bool
3379 diff_read(struct view *view, char *data)
3380 {
3381 if (!data) {
3382 /* Fall back to retry if no diff will be shown. */
3383 if (view->lines == 0 && opt_file_argv) {
3384 int pos = argv_size(view->argv)
3385 - argv_size(opt_file_argv) - 1;
3387 if (pos > 0 && !strcmp(view->argv[pos], "--")) {
3388 for (; view->argv[pos]; pos++) {
3389 free((void *) view->argv[pos]);
3390 view->argv[pos] = NULL;
3391 }
3393 if (view->pipe)
3394 io_done(view->pipe);
3395 if (io_run(&view->io, IO_RD, view->dir, view->argv))
3396 return FALSE;
3397 }
3398 }
3399 return TRUE;
3400 }
3402 return pager_read(view, data);
3403 }
3405 static struct view_ops diff_ops = {
3406 "line",
3407 diff_argv,
3408 NULL,
3409 diff_read,
3410 pager_draw,
3411 pager_request,
3412 pager_grep,
3413 pager_select,
3414 };
3416 /*
3417 * Help backend
3418 */
3420 static bool help_keymap_hidden[ARRAY_SIZE(keymap_table)];
3422 static bool
3423 help_open_keymap_title(struct view *view, enum keymap keymap)
3424 {
3425 struct line *line;
3427 line = add_line_format(view, LINE_HELP_KEYMAP, "[%c] %s bindings",
3428 help_keymap_hidden[keymap] ? '+' : '-',
3429 enum_name(keymap_table[keymap]));
3430 if (line)
3431 line->other = keymap;
3433 return help_keymap_hidden[keymap];
3434 }
3436 static void
3437 help_open_keymap(struct view *view, enum keymap keymap)
3438 {
3439 const char *group = NULL;
3440 char buf[SIZEOF_STR];
3441 size_t bufpos;
3442 bool add_title = TRUE;
3443 int i;
3445 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
3446 const char *key = NULL;
3448 if (req_info[i].request == REQ_NONE)
3449 continue;
3451 if (!req_info[i].request) {
3452 group = req_info[i].help;
3453 continue;
3454 }
3456 key = get_keys(keymap, req_info[i].request, TRUE);
3457 if (!key || !*key)
3458 continue;
3460 if (add_title && help_open_keymap_title(view, keymap))
3461 return;
3462 add_title = FALSE;
3464 if (group) {
3465 add_line_text(view, group, LINE_HELP_GROUP);
3466 group = NULL;
3467 }
3469 add_line_format(view, LINE_DEFAULT, " %-25s %-20s %s", key,
3470 enum_name(req_info[i]), req_info[i].help);
3471 }
3473 group = "External commands:";
3475 for (i = 0; i < run_requests; i++) {
3476 struct run_request *req = get_run_request(REQ_NONE + i + 1);
3477 const char *key;
3478 int argc;
3480 if (!req || req->keymap != keymap)
3481 continue;
3483 key = get_key_name(req->key);
3484 if (!*key)
3485 key = "(no key defined)";
3487 if (add_title && help_open_keymap_title(view, keymap))
3488 return;
3489 if (group) {
3490 add_line_text(view, group, LINE_HELP_GROUP);
3491 group = NULL;
3492 }
3494 for (bufpos = 0, argc = 0; req->argv[argc]; argc++)
3495 if (!string_format_from(buf, &bufpos, "%s%s",
3496 argc ? " " : "", req->argv[argc]))
3497 return;
3499 add_line_format(view, LINE_DEFAULT, " %-25s `%s`", key, buf);
3500 }
3501 }
3503 static bool
3504 help_open(struct view *view)
3505 {
3506 enum keymap keymap;
3508 reset_view(view);
3509 add_line_text(view, "Quick reference for tig keybindings:", LINE_DEFAULT);
3510 add_line_text(view, "", LINE_DEFAULT);
3512 for (keymap = 0; keymap < ARRAY_SIZE(keymap_table); keymap++)
3513 help_open_keymap(view, keymap);
3515 return TRUE;
3516 }
3518 static enum request
3519 help_request(struct view *view, enum request request, struct line *line)
3520 {
3521 switch (request) {
3522 case REQ_ENTER:
3523 if (line->type == LINE_HELP_KEYMAP) {
3524 help_keymap_hidden[line->other] =
3525 !help_keymap_hidden[line->other];
3526 view->p_restore = TRUE;
3527 open_view(view, REQ_VIEW_HELP, OPEN_REFRESH);
3528 }
3530 return REQ_NONE;
3531 default:
3532 return pager_request(view, request, line);
3533 }
3534 }
3536 static struct view_ops help_ops = {
3537 "line",
3538 NULL,
3539 help_open,
3540 NULL,
3541 pager_draw,
3542 help_request,
3543 pager_grep,
3544 pager_select,
3545 };
3548 /*
3549 * Tree backend
3550 */
3552 struct tree_stack_entry {
3553 struct tree_stack_entry *prev; /* Entry below this in the stack */
3554 unsigned long lineno; /* Line number to restore */
3555 char *name; /* Position of name in opt_path */
3556 };
3558 /* The top of the path stack. */
3559 static struct tree_stack_entry *tree_stack = NULL;
3560 unsigned long tree_lineno = 0;
3562 static void
3563 pop_tree_stack_entry(void)
3564 {
3565 struct tree_stack_entry *entry = tree_stack;
3567 tree_lineno = entry->lineno;
3568 entry->name[0] = 0;
3569 tree_stack = entry->prev;
3570 free(entry);
3571 }
3573 static void
3574 push_tree_stack_entry(const char *name, unsigned long lineno)
3575 {
3576 struct tree_stack_entry *entry = calloc(1, sizeof(*entry));
3577 size_t pathlen = strlen(opt_path);
3579 if (!entry)
3580 return;
3582 entry->prev = tree_stack;
3583 entry->name = opt_path + pathlen;
3584 tree_stack = entry;
3586 if (!string_format_from(opt_path, &pathlen, "%s/", name)) {
3587 pop_tree_stack_entry();
3588 return;
3589 }
3591 /* Move the current line to the first tree entry. */
3592 tree_lineno = 1;
3593 entry->lineno = lineno;
3594 }
3596 /* Parse output from git-ls-tree(1):
3597 *
3598 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
3599 */
3601 #define SIZEOF_TREE_ATTR \
3602 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
3604 #define SIZEOF_TREE_MODE \
3605 STRING_SIZE("100644 ")
3607 #define TREE_ID_OFFSET \
3608 STRING_SIZE("100644 blob ")
3610 struct tree_entry {
3611 char id[SIZEOF_REV];
3612 mode_t mode;
3613 struct time time; /* Date from the author ident. */
3614 const char *author; /* Author of the commit. */
3615 char name[1];
3616 };
3618 static const char *
3619 tree_path(const struct line *line)
3620 {
3621 return ((struct tree_entry *) line->data)->name;
3622 }
3624 static int
3625 tree_compare_entry(const struct line *line1, const struct line *line2)
3626 {
3627 if (line1->type != line2->type)
3628 return line1->type == LINE_TREE_DIR ? -1 : 1;
3629 return strcmp(tree_path(line1), tree_path(line2));
3630 }
3632 static const enum sort_field tree_sort_fields[] = {
3633 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
3634 };
3635 static struct sort_state tree_sort_state = SORT_STATE(tree_sort_fields);
3637 static int
3638 tree_compare(const void *l1, const void *l2)
3639 {
3640 const struct line *line1 = (const struct line *) l1;
3641 const struct line *line2 = (const struct line *) l2;
3642 const struct tree_entry *entry1 = ((const struct line *) l1)->data;
3643 const struct tree_entry *entry2 = ((const struct line *) l2)->data;
3645 if (line1->type == LINE_TREE_HEAD)
3646 return -1;
3647 if (line2->type == LINE_TREE_HEAD)
3648 return 1;
3650 switch (get_sort_field(tree_sort_state)) {
3651 case ORDERBY_DATE:
3652 return sort_order(tree_sort_state, timecmp(&entry1->time, &entry2->time));
3654 case ORDERBY_AUTHOR:
3655 return sort_order(tree_sort_state, strcmp(entry1->author, entry2->author));
3657 case ORDERBY_NAME:
3658 default:
3659 return sort_order(tree_sort_state, tree_compare_entry(line1, line2));
3660 }
3661 }
3664 static struct line *
3665 tree_entry(struct view *view, enum line_type type, const char *path,
3666 const char *mode, const char *id)
3667 {
3668 struct tree_entry *entry = calloc(1, sizeof(*entry) + strlen(path));
3669 struct line *line = entry ? add_line_data(view, entry, type) : NULL;
3671 if (!entry || !line) {
3672 free(entry);
3673 return NULL;
3674 }
3676 strncpy(entry->name, path, strlen(path));
3677 if (mode)
3678 entry->mode = strtoul(mode, NULL, 8);
3679 if (id)
3680 string_copy_rev(entry->id, id);
3682 return line;
3683 }
3685 static bool
3686 tree_read_date(struct view *view, char *text, bool *read_date)
3687 {
3688 static const char *author_name;
3689 static struct time author_time;
3691 if (!text && *read_date) {
3692 *read_date = FALSE;
3693 return TRUE;
3695 } else if (!text) {
3696 char *path = *opt_path ? opt_path : ".";
3697 /* Find next entry to process */
3698 const char *log_file[] = {
3699 "git", "log", "--no-color", "--pretty=raw",
3700 "--cc", "--raw", view->id, "--", path, NULL
3701 };
3703 if (!view->lines) {
3704 tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL);
3705 report("Tree is empty");
3706 return TRUE;
3707 }
3709 if (!start_update(view, log_file, opt_cdup)) {
3710 report("Failed to load tree data");
3711 return TRUE;
3712 }
3714 *read_date = TRUE;
3715 return FALSE;
3717 } else if (*text == 'a' && get_line_type(text) == LINE_AUTHOR) {
3718 parse_author_line(text + STRING_SIZE("author "),
3719 &author_name, &author_time);
3721 } else if (*text == ':') {
3722 char *pos;
3723 size_t annotated = 1;
3724 size_t i;
3726 pos = strchr(text, '\t');
3727 if (!pos)
3728 return TRUE;
3729 text = pos + 1;
3730 if (*opt_path && !strncmp(text, opt_path, strlen(opt_path)))
3731 text += strlen(opt_path);
3732 pos = strchr(text, '/');
3733 if (pos)
3734 *pos = 0;
3736 for (i = 1; i < view->lines; i++) {
3737 struct line *line = &view->line[i];
3738 struct tree_entry *entry = line->data;
3740 annotated += !!entry->author;
3741 if (entry->author || strcmp(entry->name, text))
3742 continue;
3744 entry->author = author_name;
3745 entry->time = author_time;
3746 line->dirty = 1;
3747 break;
3748 }
3750 if (annotated == view->lines)
3751 io_kill(view->pipe);
3752 }
3753 return TRUE;
3754 }
3756 static bool
3757 tree_read(struct view *view, char *text)
3758 {
3759 static bool read_date = FALSE;
3760 struct tree_entry *data;
3761 struct line *entry, *line;
3762 enum line_type type;
3763 size_t textlen = text ? strlen(text) : 0;
3764 char *path = text + SIZEOF_TREE_ATTR;
3766 if (read_date || !text)
3767 return tree_read_date(view, text, &read_date);
3769 if (textlen <= SIZEOF_TREE_ATTR)
3770 return FALSE;
3771 if (view->lines == 0 &&
3772 !tree_entry(view, LINE_TREE_HEAD, opt_path, NULL, NULL))
3773 return FALSE;
3775 /* Strip the path part ... */
3776 if (*opt_path) {
3777 size_t pathlen = textlen - SIZEOF_TREE_ATTR;
3778 size_t striplen = strlen(opt_path);
3780 if (pathlen > striplen)
3781 memmove(path, path + striplen,
3782 pathlen - striplen + 1);
3784 /* Insert "link" to parent directory. */
3785 if (view->lines == 1 &&
3786 !tree_entry(view, LINE_TREE_DIR, "..", "040000", view->ref))
3787 return FALSE;
3788 }
3790 type = text[SIZEOF_TREE_MODE] == 't' ? LINE_TREE_DIR : LINE_TREE_FILE;
3791 entry = tree_entry(view, type, path, text, text + TREE_ID_OFFSET);
3792 if (!entry)
3793 return FALSE;
3794 data = entry->data;
3796 /* Skip "Directory ..." and ".." line. */
3797 for (line = &view->line[1 + !!*opt_path]; line < entry; line++) {
3798 if (tree_compare_entry(line, entry) <= 0)
3799 continue;
3801 memmove(line + 1, line, (entry - line) * sizeof(*entry));
3803 line->data = data;
3804 line->type = type;
3805 for (; line <= entry; line++)
3806 line->dirty = line->cleareol = 1;
3807 return TRUE;
3808 }
3810 if (tree_lineno > view->lineno) {
3811 view->lineno = tree_lineno;
3812 tree_lineno = 0;
3813 }
3815 return TRUE;
3816 }
3818 static bool
3819 tree_draw(struct view *view, struct line *line, unsigned int lineno)
3820 {
3821 struct tree_entry *entry = line->data;
3823 if (line->type == LINE_TREE_HEAD) {
3824 if (draw_text(view, line->type, "Directory path /"))
3825 return TRUE;
3826 } else {
3827 if (draw_mode(view, entry->mode))
3828 return TRUE;
3830 if (opt_author && draw_author(view, entry->author))
3831 return TRUE;
3833 if (opt_date && draw_date(view, &entry->time))
3834 return TRUE;
3835 }
3837 draw_text(view, line->type, entry->name);
3838 return TRUE;
3839 }
3841 static void
3842 open_blob_editor(const char *id)
3843 {
3844 const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL };
3845 char file[SIZEOF_STR] = "/tmp/tigblob.XXXXXX";
3846 int fd = mkstemp(file);
3848 if (fd == -1)
3849 report("Failed to create temporary file");
3850 else if (!io_run_append(blob_argv, fd))
3851 report("Failed to save blob data to file");
3852 else
3853 open_editor(file);
3854 if (fd != -1)
3855 unlink(file);
3856 }
3858 static enum request
3859 tree_request(struct view *view, enum request request, struct line *line)
3860 {
3861 enum open_flags flags;
3862 struct tree_entry *entry = line->data;
3864 switch (request) {
3865 case REQ_VIEW_BLAME:
3866 if (line->type != LINE_TREE_FILE) {
3867 report("Blame only supported for files");
3868 return REQ_NONE;
3869 }
3871 string_copy(opt_ref, view->vid);
3872 return request;
3874 case REQ_EDIT:
3875 if (line->type != LINE_TREE_FILE) {
3876 report("Edit only supported for files");
3877 } else if (!is_head_commit(view->vid)) {
3878 open_blob_editor(entry->id);
3879 } else {
3880 open_editor(opt_file);
3881 }
3882 return REQ_NONE;
3884 case REQ_TOGGLE_SORT_FIELD:
3885 case REQ_TOGGLE_SORT_ORDER:
3886 sort_view(view, request, &tree_sort_state, tree_compare);
3887 return REQ_NONE;
3889 case REQ_PARENT:
3890 if (!*opt_path) {
3891 /* quit view if at top of tree */
3892 return REQ_VIEW_CLOSE;
3893 }
3894 /* fake 'cd ..' */
3895 line = &view->line[1];
3896 break;
3898 case REQ_ENTER:
3899 break;
3901 default:
3902 return request;
3903 }
3905 /* Cleanup the stack if the tree view is at a different tree. */
3906 while (!*opt_path && tree_stack)
3907 pop_tree_stack_entry();
3909 switch (line->type) {
3910 case LINE_TREE_DIR:
3911 /* Depending on whether it is a subdirectory or parent link
3912 * mangle the path buffer. */
3913 if (line == &view->line[1] && *opt_path) {
3914 pop_tree_stack_entry();
3916 } else {
3917 const char *basename = tree_path(line);
3919 push_tree_stack_entry(basename, view->lineno);
3920 }
3922 /* Trees and subtrees share the same ID, so they are not not
3923 * unique like blobs. */
3924 flags = OPEN_RELOAD;
3925 request = REQ_VIEW_TREE;
3926 break;
3928 case LINE_TREE_FILE:
3929 flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
3930 request = REQ_VIEW_BLOB;
3931 break;
3933 default:
3934 return REQ_NONE;
3935 }
3937 open_view(view, request, flags);
3938 if (request == REQ_VIEW_TREE)
3939 view->lineno = tree_lineno;
3941 return REQ_NONE;
3942 }
3944 static bool
3945 tree_grep(struct view *view, struct line *line)
3946 {
3947 struct tree_entry *entry = line->data;
3948 const char *text[] = {
3949 entry->name,
3950 opt_author ? entry->author : "",
3951 mkdate(&entry->time, opt_date),
3952 NULL
3953 };
3955 return grep_text(view, text);
3956 }
3958 static void
3959 tree_select(struct view *view, struct line *line)
3960 {
3961 struct tree_entry *entry = line->data;
3963 if (line->type == LINE_TREE_FILE) {
3964 string_copy_rev(ref_blob, entry->id);
3965 string_format(opt_file, "%s%s", opt_path, tree_path(line));
3967 } else if (line->type != LINE_TREE_DIR) {
3968 return;
3969 }
3971 string_copy_rev(view->ref, entry->id);
3972 }
3974 static bool
3975 tree_prepare(struct view *view)
3976 {
3977 if (view->lines == 0 && opt_prefix[0]) {
3978 char *pos = opt_prefix;
3980 while (pos && *pos) {
3981 char *end = strchr(pos, '/');
3983 if (end)
3984 *end = 0;
3985 push_tree_stack_entry(pos, 0);
3986 pos = end;
3987 if (end) {
3988 *end = '/';
3989 pos++;
3990 }
3991 }
3993 } else if (strcmp(view->vid, view->id)) {
3994 opt_path[0] = 0;
3995 }
3997 return prepare_io(view, opt_cdup, view->ops->argv, TRUE);
3998 }
4000 static const char *tree_argv[SIZEOF_ARG] = {
4001 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4002 };
4004 static struct view_ops tree_ops = {
4005 "file",
4006 tree_argv,
4007 NULL,
4008 tree_read,
4009 tree_draw,
4010 tree_request,
4011 tree_grep,
4012 tree_select,
4013 tree_prepare,
4014 };
4016 static bool
4017 blob_read(struct view *view, char *line)
4018 {
4019 if (!line)
4020 return TRUE;
4021 return add_line_text(view, line, LINE_DEFAULT) != NULL;
4022 }
4024 static enum request
4025 blob_request(struct view *view, enum request request, struct line *line)
4026 {
4027 switch (request) {
4028 case REQ_EDIT:
4029 open_blob_editor(view->vid);
4030 return REQ_NONE;
4031 default:
4032 return pager_request(view, request, line);
4033 }
4034 }
4036 static const char *blob_argv[SIZEOF_ARG] = {
4037 "git", "cat-file", "blob", "%(blob)", NULL
4038 };
4040 static struct view_ops blob_ops = {
4041 "line",
4042 blob_argv,
4043 NULL,
4044 blob_read,
4045 pager_draw,
4046 blob_request,
4047 pager_grep,
4048 pager_select,
4049 };
4051 /*
4052 * Blame backend
4053 *
4054 * Loading the blame view is a two phase job:
4055 *
4056 * 1. File content is read either using opt_file from the
4057 * filesystem or using git-cat-file.
4058 * 2. Then blame information is incrementally added by
4059 * reading output from git-blame.
4060 */
4062 struct blame_commit {
4063 char id[SIZEOF_REV]; /* SHA1 ID. */
4064 char title[128]; /* First line of the commit message. */
4065 const char *author; /* Author of the commit. */
4066 struct time time; /* Date from the author ident. */
4067 char filename[128]; /* Name of file. */
4068 char parent_id[SIZEOF_REV]; /* Parent/previous SHA1 ID. */
4069 char parent_filename[128]; /* Parent/previous name of file. */
4070 };
4072 struct blame {
4073 struct blame_commit *commit;
4074 unsigned long lineno;
4075 char text[1];
4076 };
4078 static bool
4079 blame_open(struct view *view)
4080 {
4081 char path[SIZEOF_STR];
4082 size_t i;
4084 if (!view->prev && *opt_prefix) {
4085 string_copy(path, opt_file);
4086 if (!string_format(opt_file, "%s%s", opt_prefix, path))
4087 return FALSE;
4088 }
4090 if (*opt_ref || !io_open(&view->io, "%s%s", opt_cdup, opt_file)) {
4091 const char *blame_cat_file_argv[] = {
4092 "git", "cat-file", "blob", path, NULL
4093 };
4095 if (!string_format(path, "%s:%s", opt_ref, opt_file) ||
4096 !start_update(view, blame_cat_file_argv, opt_cdup))
4097 return FALSE;
4098 }
4100 /* First pass: remove multiple references to the same commit. */
4101 for (i = 0; i < view->lines; i++) {
4102 struct blame *blame = view->line[i].data;
4104 if (blame->commit && blame->commit->id[0])
4105 blame->commit->id[0] = 0;
4106 else
4107 blame->commit = NULL;
4108 }
4110 /* Second pass: free existing references. */
4111 for (i = 0; i < view->lines; i++) {
4112 struct blame *blame = view->line[i].data;
4114 if (blame->commit)
4115 free(blame->commit);
4116 }
4118 setup_update(view, opt_file);
4119 string_format(view->ref, "%s ...", opt_file);
4121 return TRUE;
4122 }
4124 static struct blame_commit *
4125 get_blame_commit(struct view *view, const char *id)
4126 {
4127 size_t i;
4129 for (i = 0; i < view->lines; i++) {
4130 struct blame *blame = view->line[i].data;
4132 if (!blame->commit)
4133 continue;
4135 if (!strncmp(blame->commit->id, id, SIZEOF_REV - 1))
4136 return blame->commit;
4137 }
4139 {
4140 struct blame_commit *commit = calloc(1, sizeof(*commit));
4142 if (commit)
4143 string_ncopy(commit->id, id, SIZEOF_REV);
4144 return commit;
4145 }
4146 }
4148 static bool
4149 parse_number(const char **posref, size_t *number, size_t min, size_t max)
4150 {
4151 const char *pos = *posref;
4153 *posref = NULL;
4154 pos = strchr(pos + 1, ' ');
4155 if (!pos || !isdigit(pos[1]))
4156 return FALSE;
4157 *number = atoi(pos + 1);
4158 if (*number < min || *number > max)
4159 return FALSE;
4161 *posref = pos;
4162 return TRUE;
4163 }
4165 static struct blame_commit *
4166 parse_blame_commit(struct view *view, const char *text, int *blamed)
4167 {
4168 struct blame_commit *commit;
4169 struct blame *blame;
4170 const char *pos = text + SIZEOF_REV - 2;
4171 size_t orig_lineno = 0;
4172 size_t lineno;
4173 size_t group;
4175 if (strlen(text) <= SIZEOF_REV || pos[1] != ' ')
4176 return NULL;
4178 if (!parse_number(&pos, &orig_lineno, 1, 9999999) ||
4179 !parse_number(&pos, &lineno, 1, view->lines) ||
4180 !parse_number(&pos, &group, 1, view->lines - lineno + 1))
4181 return NULL;
4183 commit = get_blame_commit(view, text);
4184 if (!commit)
4185 return NULL;
4187 *blamed += group;
4188 while (group--) {
4189 struct line *line = &view->line[lineno + group - 1];
4191 blame = line->data;
4192 blame->commit = commit;
4193 blame->lineno = orig_lineno + group - 1;
4194 line->dirty = 1;
4195 }
4197 return commit;
4198 }
4200 static bool
4201 blame_read_file(struct view *view, const char *line, bool *read_file)
4202 {
4203 if (!line) {
4204 const char *blame_argv[] = {
4205 "git", "blame", "%(blameargs)", "--incremental",
4206 *opt_ref ? opt_ref : "--incremental", "--", opt_file, NULL
4207 };
4209 if (view->lines == 0 && !view->prev)
4210 die("No blame exist for %s", view->vid);
4212 if (view->lines == 0 || !start_update(view, blame_argv, opt_cdup)) {
4213 report("Failed to load blame data");
4214 return TRUE;
4215 }
4217 *read_file = FALSE;
4218 return FALSE;
4220 } else {
4221 size_t linelen = strlen(line);
4222 struct blame *blame = malloc(sizeof(*blame) + linelen);
4224 if (!blame)
4225 return FALSE;
4227 blame->commit = NULL;
4228 strncpy(blame->text, line, linelen);
4229 blame->text[linelen] = 0;
4230 return add_line_data(view, blame, LINE_BLAME_ID) != NULL;
4231 }
4232 }
4234 static bool
4235 match_blame_header(const char *name, char **line)
4236 {
4237 size_t namelen = strlen(name);
4238 bool matched = !strncmp(name, *line, namelen);
4240 if (matched)
4241 *line += namelen;
4243 return matched;
4244 }
4246 static bool
4247 blame_read(struct view *view, char *line)
4248 {
4249 static struct blame_commit *commit = NULL;
4250 static int blamed = 0;
4251 static bool read_file = TRUE;
4253 if (read_file)
4254 return blame_read_file(view, line, &read_file);
4256 if (!line) {
4257 /* Reset all! */
4258 commit = NULL;
4259 blamed = 0;
4260 read_file = TRUE;
4261 string_format(view->ref, "%s", view->vid);
4262 if (view_is_displayed(view)) {
4263 update_view_title(view);
4264 redraw_view_from(view, 0);
4265 }
4266 return TRUE;
4267 }
4269 if (!commit) {
4270 commit = parse_blame_commit(view, line, &blamed);
4271 string_format(view->ref, "%s %2d%%", view->vid,
4272 view->lines ? blamed * 100 / view->lines : 0);
4274 } else if (match_blame_header("author ", &line)) {
4275 commit->author = get_author(line);
4277 } else if (match_blame_header("author-time ", &line)) {
4278 parse_timesec(&commit->time, line);
4280 } else if (match_blame_header("author-tz ", &line)) {
4281 parse_timezone(&commit->time, line);
4283 } else if (match_blame_header("summary ", &line)) {
4284 string_ncopy(commit->title, line, strlen(line));
4286 } else if (match_blame_header("previous ", &line)) {
4287 if (strlen(line) <= SIZEOF_REV)
4288 return FALSE;
4289 string_copy_rev(commit->parent_id, line);
4290 line += SIZEOF_REV;
4291 string_ncopy(commit->parent_filename, line, strlen(line));
4293 } else if (match_blame_header("filename ", &line)) {
4294 string_ncopy(commit->filename, line, strlen(line));
4295 commit = NULL;
4296 }
4298 return TRUE;
4299 }
4301 static bool
4302 blame_draw(struct view *view, struct line *line, unsigned int lineno)
4303 {
4304 struct blame *blame = line->data;
4305 struct time *time = NULL;
4306 const char *id = NULL, *author = NULL;
4308 if (blame->commit && *blame->commit->filename) {
4309 id = blame->commit->id;
4310 author = blame->commit->author;
4311 time = &blame->commit->time;
4312 }
4314 if (opt_date && draw_date(view, time))
4315 return TRUE;
4317 if (opt_author && draw_author(view, author))
4318 return TRUE;
4320 if (draw_field(view, LINE_BLAME_ID, id, ID_COLS, FALSE))
4321 return TRUE;
4323 if (draw_lineno(view, lineno))
4324 return TRUE;
4326 draw_text(view, LINE_DEFAULT, blame->text);
4327 return TRUE;
4328 }
4330 static bool
4331 check_blame_commit(struct blame *blame, bool check_null_id)
4332 {
4333 if (!blame->commit)
4334 report("Commit data not loaded yet");
4335 else if (check_null_id && !strcmp(blame->commit->id, NULL_ID))
4336 report("No commit exist for the selected line");
4337 else
4338 return TRUE;
4339 return FALSE;
4340 }
4342 static void
4343 setup_blame_parent_line(struct view *view, struct blame *blame)
4344 {
4345 char from[SIZEOF_REF + SIZEOF_STR];
4346 char to[SIZEOF_REF + SIZEOF_STR];
4347 const char *diff_tree_argv[] = {
4348 "git", "diff", "--no-textconv", "--no-extdiff", "--no-color",
4349 "-U0", from, to, "--", NULL
4350 };
4351 struct io io;
4352 int parent_lineno = -1;
4353 int blamed_lineno = -1;
4354 char *line;
4356 if (!string_format(from, "%s:%s", opt_ref, opt_file) ||
4357 !string_format(to, "%s:%s", blame->commit->id, blame->commit->filename) ||
4358 !io_run(&io, IO_RD, NULL, diff_tree_argv))
4359 return;
4361 while ((line = io_get(&io, '\n', TRUE))) {
4362 if (*line == '@') {
4363 char *pos = strchr(line, '+');
4365 parent_lineno = atoi(line + 4);
4366 if (pos)
4367 blamed_lineno = atoi(pos + 1);
4369 } else if (*line == '+' && parent_lineno != -1) {
4370 if (blame->lineno == blamed_lineno - 1 &&
4371 !strcmp(blame->text, line + 1)) {
4372 view->lineno = parent_lineno ? parent_lineno - 1 : 0;
4373 break;
4374 }
4375 blamed_lineno++;
4376 }
4377 }
4379 io_done(&io);
4380 }
4382 static enum request
4383 blame_request(struct view *view, enum request request, struct line *line)
4384 {
4385 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
4386 struct blame *blame = line->data;
4388 switch (request) {
4389 case REQ_VIEW_BLAME:
4390 if (check_blame_commit(blame, TRUE)) {
4391 string_copy(opt_ref, blame->commit->id);
4392 string_copy(opt_file, blame->commit->filename);
4393 if (blame->lineno)
4394 view->lineno = blame->lineno;
4395 open_view(view, REQ_VIEW_BLAME, OPEN_REFRESH);
4396 }
4397 break;
4399 case REQ_PARENT:
4400 if (!check_blame_commit(blame, TRUE))
4401 break;
4402 if (!*blame->commit->parent_id) {
4403 report("The selected commit has no parents");
4404 } else {
4405 string_copy_rev(opt_ref, blame->commit->parent_id);
4406 string_copy(opt_file, blame->commit->parent_filename);
4407 setup_blame_parent_line(view, blame);
4408 open_view(view, REQ_VIEW_BLAME, OPEN_REFRESH);
4409 }
4410 break;
4412 case REQ_ENTER:
4413 if (!check_blame_commit(blame, FALSE))
4414 break;
4416 if (view_is_displayed(VIEW(REQ_VIEW_DIFF)) &&
4417 !strcmp(blame->commit->id, VIEW(REQ_VIEW_DIFF)->ref))
4418 break;
4420 if (!strcmp(blame->commit->id, NULL_ID)) {
4421 struct view *diff = VIEW(REQ_VIEW_DIFF);
4422 const char *diff_index_argv[] = {
4423 "git", "diff-index", "--root", "--patch-with-stat",
4424 "-C", "-M", "HEAD", "--", view->vid, NULL
4425 };
4427 if (!*blame->commit->parent_id) {
4428 diff_index_argv[1] = "diff";
4429 diff_index_argv[2] = "--no-color";
4430 diff_index_argv[6] = "--";
4431 diff_index_argv[7] = "/dev/null";
4432 }
4434 if (!prepare_update(diff, diff_index_argv, NULL)) {
4435 report("Failed to allocate diff command");
4436 break;
4437 }
4438 flags |= OPEN_PREPARED;
4439 }
4441 open_view(view, REQ_VIEW_DIFF, flags);
4442 if (VIEW(REQ_VIEW_DIFF)->pipe && !strcmp(blame->commit->id, NULL_ID))
4443 string_copy_rev(VIEW(REQ_VIEW_DIFF)->ref, NULL_ID);
4444 break;
4446 default:
4447 return request;
4448 }
4450 return REQ_NONE;
4451 }
4453 static bool
4454 blame_grep(struct view *view, struct line *line)
4455 {
4456 struct blame *blame = line->data;
4457 struct blame_commit *commit = blame->commit;
4458 const char *text[] = {
4459 blame->text,
4460 commit ? commit->title : "",
4461 commit ? commit->id : "",
4462 commit && opt_author ? commit->author : "",
4463 commit ? mkdate(&commit->time, opt_date) : "",
4464 NULL
4465 };
4467 return grep_text(view, text);
4468 }
4470 static void
4471 blame_select(struct view *view, struct line *line)
4472 {
4473 struct blame *blame = line->data;
4474 struct blame_commit *commit = blame->commit;
4476 if (!commit)
4477 return;
4479 if (!strcmp(commit->id, NULL_ID))
4480 string_ncopy(ref_commit, "HEAD", 4);
4481 else
4482 string_copy_rev(ref_commit, commit->id);
4483 }
4485 static struct view_ops blame_ops = {
4486 "line",
4487 NULL,
4488 blame_open,
4489 blame_read,
4490 blame_draw,
4491 blame_request,
4492 blame_grep,
4493 blame_select,
4494 };
4496 /*
4497 * Branch backend
4498 */
4500 struct branch {
4501 const char *author; /* Author of the last commit. */
4502 struct time time; /* Date of the last activity. */
4503 const struct ref *ref; /* Name and commit ID information. */
4504 };
4506 static const struct ref branch_all;
4508 static const enum sort_field branch_sort_fields[] = {
4509 ORDERBY_NAME, ORDERBY_DATE, ORDERBY_AUTHOR
4510 };
4511 static struct sort_state branch_sort_state = SORT_STATE(branch_sort_fields);
4513 static int
4514 branch_compare(const void *l1, const void *l2)
4515 {
4516 const struct branch *branch1 = ((const struct line *) l1)->data;
4517 const struct branch *branch2 = ((const struct line *) l2)->data;
4519 switch (get_sort_field(branch_sort_state)) {
4520 case ORDERBY_DATE:
4521 return sort_order(branch_sort_state, timecmp(&branch1->time, &branch2->time));
4523 case ORDERBY_AUTHOR:
4524 return sort_order(branch_sort_state, strcmp(branch1->author, branch2->author));
4526 case ORDERBY_NAME:
4527 default:
4528 return sort_order(branch_sort_state, strcmp(branch1->ref->name, branch2->ref->name));
4529 }
4530 }
4532 static bool
4533 branch_draw(struct view *view, struct line *line, unsigned int lineno)
4534 {
4535 struct branch *branch = line->data;
4536 enum line_type type = branch->ref->head ? LINE_MAIN_HEAD : LINE_DEFAULT;
4538 if (opt_date && draw_date(view, &branch->time))
4539 return TRUE;
4541 if (opt_author && draw_author(view, branch->author))
4542 return TRUE;
4544 draw_text(view, type, branch->ref == &branch_all ? "All branches" : branch->ref->name);
4545 return TRUE;
4546 }
4548 static enum request
4549 branch_request(struct view *view, enum request request, struct line *line)
4550 {
4551 struct branch *branch = line->data;
4553 switch (request) {
4554 case REQ_REFRESH:
4555 load_refs();
4556 open_view(view, REQ_VIEW_BRANCH, OPEN_REFRESH);
4557 return REQ_NONE;
4559 case REQ_TOGGLE_SORT_FIELD:
4560 case REQ_TOGGLE_SORT_ORDER:
4561 sort_view(view, request, &branch_sort_state, branch_compare);
4562 return REQ_NONE;
4564 case REQ_ENTER:
4565 {
4566 const struct ref *ref = branch->ref;
4567 const char *all_branches_argv[] = {
4568 "git", "log", "--no-color", "--pretty=raw", "--parents",
4569 "--topo-order",
4570 ref == &branch_all ? "--all" : ref->name, NULL
4571 };
4572 struct view *main_view = VIEW(REQ_VIEW_MAIN);
4574 if (!prepare_update(main_view, all_branches_argv, NULL))
4575 report("Failed to load view of all branches");
4576 else
4577 open_view(view, REQ_VIEW_MAIN, OPEN_PREPARED | OPEN_SPLIT);
4578 return REQ_NONE;
4579 }
4580 default:
4581 return request;
4582 }
4583 }
4585 static bool
4586 branch_read(struct view *view, char *line)
4587 {
4588 static char id[SIZEOF_REV];
4589 struct branch *reference;
4590 size_t i;
4592 if (!line)
4593 return TRUE;
4595 switch (get_line_type(line)) {
4596 case LINE_COMMIT:
4597 string_copy_rev(id, line + STRING_SIZE("commit "));
4598 return TRUE;
4600 case LINE_AUTHOR:
4601 for (i = 0, reference = NULL; i < view->lines; i++) {
4602 struct branch *branch = view->line[i].data;
4604 if (strcmp(branch->ref->id, id))
4605 continue;
4607 view->line[i].dirty = TRUE;
4608 if (reference) {
4609 branch->author = reference->author;
4610 branch->time = reference->time;
4611 continue;
4612 }
4614 parse_author_line(line + STRING_SIZE("author "),
4615 &branch->author, &branch->time);
4616 reference = branch;
4617 }
4618 return TRUE;
4620 default:
4621 return TRUE;
4622 }
4624 }
4626 static bool
4627 branch_open_visitor(void *data, const struct ref *ref)
4628 {
4629 struct view *view = data;
4630 struct branch *branch;
4632 if (ref->tag || ref->ltag || ref->remote)
4633 return TRUE;
4635 branch = calloc(1, sizeof(*branch));
4636 if (!branch)
4637 return FALSE;
4639 branch->ref = ref;
4640 return !!add_line_data(view, branch, LINE_DEFAULT);
4641 }
4643 static bool
4644 branch_open(struct view *view)
4645 {
4646 const char *branch_log[] = {
4647 "git", "log", "--no-color", "--pretty=raw",
4648 "--simplify-by-decoration", "--all", NULL
4649 };
4651 if (!start_update(view, branch_log, NULL)) {
4652 report("Failed to load branch data");
4653 return TRUE;
4654 }
4656 setup_update(view, view->id);
4657 branch_open_visitor(view, &branch_all);
4658 foreach_ref(branch_open_visitor, view);
4659 view->p_restore = TRUE;
4661 return TRUE;
4662 }
4664 static bool
4665 branch_grep(struct view *view, struct line *line)
4666 {
4667 struct branch *branch = line->data;
4668 const char *text[] = {
4669 branch->ref->name,
4670 branch->author,
4671 NULL
4672 };
4674 return grep_text(view, text);
4675 }
4677 static void
4678 branch_select(struct view *view, struct line *line)
4679 {
4680 struct branch *branch = line->data;
4682 string_copy_rev(view->ref, branch->ref->id);
4683 string_copy_rev(ref_commit, branch->ref->id);
4684 string_copy_rev(ref_head, branch->ref->id);
4685 string_copy_rev(ref_branch, branch->ref->name);
4686 }
4688 static struct view_ops branch_ops = {
4689 "branch",
4690 NULL,
4691 branch_open,
4692 branch_read,
4693 branch_draw,
4694 branch_request,
4695 branch_grep,
4696 branch_select,
4697 };
4699 /*
4700 * Status backend
4701 */
4703 struct status {
4704 char status;
4705 struct {
4706 mode_t mode;
4707 char rev[SIZEOF_REV];
4708 char name[SIZEOF_STR];
4709 } old;
4710 struct {
4711 mode_t mode;
4712 char rev[SIZEOF_REV];
4713 char name[SIZEOF_STR];
4714 } new;
4715 };
4717 static char status_onbranch[SIZEOF_STR];
4718 static struct status stage_status;
4719 static enum line_type stage_line_type;
4720 static size_t stage_chunks;
4721 static int *stage_chunk;
4723 DEFINE_ALLOCATOR(realloc_ints, int, 32)
4725 /* This should work even for the "On branch" line. */
4726 static inline bool
4727 status_has_none(struct view *view, struct line *line)
4728 {
4729 return line < view->line + view->lines && !line[1].data;
4730 }
4732 /* Get fields from the diff line:
4733 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
4734 */
4735 static inline bool
4736 status_get_diff(struct status *file, const char *buf, size_t bufsize)
4737 {
4738 const char *old_mode = buf + 1;
4739 const char *new_mode = buf + 8;
4740 const char *old_rev = buf + 15;
4741 const char *new_rev = buf + 56;
4742 const char *status = buf + 97;
4744 if (bufsize < 98 ||
4745 old_mode[-1] != ':' ||
4746 new_mode[-1] != ' ' ||
4747 old_rev[-1] != ' ' ||
4748 new_rev[-1] != ' ' ||
4749 status[-1] != ' ')
4750 return FALSE;
4752 file->status = *status;
4754 string_copy_rev(file->old.rev, old_rev);
4755 string_copy_rev(file->new.rev, new_rev);
4757 file->old.mode = strtoul(old_mode, NULL, 8);
4758 file->new.mode = strtoul(new_mode, NULL, 8);
4760 file->old.name[0] = file->new.name[0] = 0;
4762 return TRUE;
4763 }
4765 static bool
4766 status_run(struct view *view, const char *argv[], char status, enum line_type type)
4767 {
4768 struct status *unmerged = NULL;
4769 char *buf;
4770 struct io io;
4772 if (!io_run(&io, IO_RD, opt_cdup, argv))
4773 return FALSE;
4775 add_line_data(view, NULL, type);
4777 while ((buf = io_get(&io, 0, TRUE))) {
4778 struct status *file = unmerged;
4780 if (!file) {
4781 file = calloc(1, sizeof(*file));
4782 if (!file || !add_line_data(view, file, type))
4783 goto error_out;
4784 }
4786 /* Parse diff info part. */
4787 if (status) {
4788 file->status = status;
4789 if (status == 'A')
4790 string_copy(file->old.rev, NULL_ID);
4792 } else if (!file->status || file == unmerged) {
4793 if (!status_get_diff(file, buf, strlen(buf)))
4794 goto error_out;
4796 buf = io_get(&io, 0, TRUE);
4797 if (!buf)
4798 break;
4800 /* Collapse all modified entries that follow an
4801 * associated unmerged entry. */
4802 if (unmerged == file) {
4803 unmerged->status = 'U';
4804 unmerged = NULL;
4805 } else if (file->status == 'U') {
4806 unmerged = file;
4807 }
4808 }
4810 /* Grab the old name for rename/copy. */
4811 if (!*file->old.name &&
4812 (file->status == 'R' || file->status == 'C')) {
4813 string_ncopy(file->old.name, buf, strlen(buf));
4815 buf = io_get(&io, 0, TRUE);
4816 if (!buf)
4817 break;
4818 }
4820 /* git-ls-files just delivers a NUL separated list of
4821 * file names similar to the second half of the
4822 * git-diff-* output. */
4823 string_ncopy(file->new.name, buf, strlen(buf));
4824 if (!*file->old.name)
4825 string_copy(file->old.name, file->new.name);
4826 file = NULL;
4827 }
4829 if (io_error(&io)) {
4830 error_out:
4831 io_done(&io);
4832 return FALSE;
4833 }
4835 if (!view->line[view->lines - 1].data)
4836 add_line_data(view, NULL, LINE_STAT_NONE);
4838 io_done(&io);
4839 return TRUE;
4840 }
4842 /* Don't show unmerged entries in the staged section. */
4843 static const char *status_diff_index_argv[] = {
4844 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
4845 "--cached", "-M", "HEAD", NULL
4846 };
4848 static const char *status_diff_files_argv[] = {
4849 "git", "diff-files", "-z", NULL
4850 };
4852 static const char *status_list_other_argv[] = {
4853 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix, NULL, NULL,
4854 };
4856 static const char *status_list_no_head_argv[] = {
4857 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
4858 };
4860 static const char *update_index_argv[] = {
4861 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
4862 };
4864 /* Restore the previous line number to stay in the context or select a
4865 * line with something that can be updated. */
4866 static void
4867 status_restore(struct view *view)
4868 {
4869 if (view->p_lineno >= view->lines)
4870 view->p_lineno = view->lines - 1;
4871 while (view->p_lineno < view->lines && !view->line[view->p_lineno].data)
4872 view->p_lineno++;
4873 while (view->p_lineno > 0 && !view->line[view->p_lineno].data)
4874 view->p_lineno--;
4876 /* If the above fails, always skip the "On branch" line. */
4877 if (view->p_lineno < view->lines)
4878 view->lineno = view->p_lineno;
4879 else
4880 view->lineno = 1;
4882 if (view->lineno < view->offset)
4883 view->offset = view->lineno;
4884 else if (view->offset + view->height <= view->lineno)
4885 view->offset = view->lineno - view->height + 1;
4887 view->p_restore = FALSE;
4888 }
4890 static void
4891 status_update_onbranch(void)
4892 {
4893 static const char *paths[][2] = {
4894 { "rebase-apply/rebasing", "Rebasing" },
4895 { "rebase-apply/applying", "Applying mailbox" },
4896 { "rebase-apply/", "Rebasing mailbox" },
4897 { "rebase-merge/interactive", "Interactive rebase" },
4898 { "rebase-merge/", "Rebase merge" },
4899 { "MERGE_HEAD", "Merging" },
4900 { "BISECT_LOG", "Bisecting" },
4901 { "HEAD", "On branch" },
4902 };
4903 char buf[SIZEOF_STR];
4904 struct stat stat;
4905 int i;
4907 if (is_initial_commit()) {
4908 string_copy(status_onbranch, "Initial commit");
4909 return;
4910 }
4912 for (i = 0; i < ARRAY_SIZE(paths); i++) {
4913 char *head = opt_head;
4915 if (!string_format(buf, "%s/%s", opt_git_dir, paths[i][0]) ||
4916 lstat(buf, &stat) < 0)
4917 continue;
4919 if (!*opt_head) {
4920 struct io io;
4922 if (io_open(&io, "%s/rebase-merge/head-name", opt_git_dir) &&
4923 io_read_buf(&io, buf, sizeof(buf))) {
4924 head = buf;
4925 if (!prefixcmp(head, "refs/heads/"))
4926 head += STRING_SIZE("refs/heads/");
4927 }
4928 }
4930 if (!string_format(status_onbranch, "%s %s", paths[i][1], head))
4931 string_copy(status_onbranch, opt_head);
4932 return;
4933 }
4935 string_copy(status_onbranch, "Not currently on any branch");
4936 }
4938 /* First parse staged info using git-diff-index(1), then parse unstaged
4939 * info using git-diff-files(1), and finally untracked files using
4940 * git-ls-files(1). */
4941 static bool
4942 status_open(struct view *view)
4943 {
4944 reset_view(view);
4946 add_line_data(view, NULL, LINE_STAT_HEAD);
4947 status_update_onbranch();
4949 io_run_bg(update_index_argv);
4951 if (is_initial_commit()) {
4952 if (!status_run(view, status_list_no_head_argv, 'A', LINE_STAT_STAGED))
4953 return FALSE;
4954 } else if (!status_run(view, status_diff_index_argv, 0, LINE_STAT_STAGED)) {
4955 return FALSE;
4956 }
4958 if (!opt_untracked_dirs_content)
4959 status_list_other_argv[ARRAY_SIZE(status_list_other_argv) - 2] = "--directory";
4961 if (!status_run(view, status_diff_files_argv, 0, LINE_STAT_UNSTAGED) ||
4962 !status_run(view, status_list_other_argv, '?', LINE_STAT_UNTRACKED))
4963 return FALSE;
4965 /* Restore the exact position or use the specialized restore
4966 * mode? */
4967 if (!view->p_restore)
4968 status_restore(view);
4969 return TRUE;
4970 }
4972 static bool
4973 status_draw(struct view *view, struct line *line, unsigned int lineno)
4974 {
4975 struct status *status = line->data;
4976 enum line_type type;
4977 const char *text;
4979 if (!status) {
4980 switch (line->type) {
4981 case LINE_STAT_STAGED:
4982 type = LINE_STAT_SECTION;
4983 text = "Changes to be committed:";
4984 break;
4986 case LINE_STAT_UNSTAGED:
4987 type = LINE_STAT_SECTION;
4988 text = "Changed but not updated:";
4989 break;
4991 case LINE_STAT_UNTRACKED:
4992 type = LINE_STAT_SECTION;
4993 text = "Untracked files:";
4994 break;
4996 case LINE_STAT_NONE:
4997 type = LINE_DEFAULT;
4998 text = " (no files)";
4999 break;
5001 case LINE_STAT_HEAD:
5002 type = LINE_STAT_HEAD;
5003 text = status_onbranch;
5004 break;
5006 default:
5007 return FALSE;
5008 }
5009 } else {
5010 static char buf[] = { '?', ' ', ' ', ' ', 0 };
5012 buf[0] = status->status;
5013 if (draw_text(view, line->type, buf))
5014 return TRUE;
5015 type = LINE_DEFAULT;
5016 text = status->new.name;
5017 }
5019 draw_text(view, type, text);
5020 return TRUE;
5021 }
5023 static enum request
5024 status_load_error(struct view *view, struct view *stage, const char *path)
5025 {
5026 if (displayed_views() == 2 || display[current_view] != view)
5027 maximize_view(view);
5028 report("Failed to load '%s': %s", path, io_strerror(&stage->io));
5029 return REQ_NONE;
5030 }
5032 static enum request
5033 status_enter(struct view *view, struct line *line)
5034 {
5035 struct status *status = line->data;
5036 const char *oldpath = status ? status->old.name : NULL;
5037 /* Diffs for unmerged entries are empty when passing the new
5038 * path, so leave it empty. */
5039 const char *newpath = status && status->status != 'U' ? status->new.name : NULL;
5040 const char *info;
5041 enum open_flags split;
5042 struct view *stage = VIEW(REQ_VIEW_STAGE);
5044 if (line->type == LINE_STAT_NONE ||
5045 (!status && line[1].type == LINE_STAT_NONE)) {
5046 report("No file to diff");
5047 return REQ_NONE;
5048 }
5050 switch (line->type) {
5051 case LINE_STAT_STAGED:
5052 if (is_initial_commit()) {
5053 const char *no_head_diff_argv[] = {
5054 "git", "diff", "--no-color", "--patch-with-stat",
5055 "--", "/dev/null", newpath, NULL
5056 };
5058 if (!prepare_update(stage, no_head_diff_argv, opt_cdup))
5059 return status_load_error(view, stage, newpath);
5060 } else {
5061 const char *index_show_argv[] = {
5062 "git", "diff-index", "--root", "--patch-with-stat",
5063 "-C", "-M", "--cached", "HEAD", "--",
5064 oldpath, newpath, NULL
5065 };
5067 if (!prepare_update(stage, index_show_argv, opt_cdup))
5068 return status_load_error(view, stage, newpath);
5069 }
5071 if (status)
5072 info = "Staged changes to %s";
5073 else
5074 info = "Staged changes";
5075 break;
5077 case LINE_STAT_UNSTAGED:
5078 {
5079 const char *files_show_argv[] = {
5080 "git", "diff-files", "--root", "--patch-with-stat",
5081 "-C", "-M", "--", oldpath, newpath, NULL
5082 };
5084 if (!prepare_update(stage, files_show_argv, opt_cdup))
5085 return status_load_error(view, stage, newpath);
5086 if (status)
5087 info = "Unstaged changes to %s";
5088 else
5089 info = "Unstaged changes";
5090 break;
5091 }
5092 case LINE_STAT_UNTRACKED:
5093 if (!newpath) {
5094 report("No file to show");
5095 return REQ_NONE;
5096 }
5098 if (!suffixcmp(status->new.name, -1, "/")) {
5099 report("Cannot display a directory");
5100 return REQ_NONE;
5101 }
5103 if (!prepare_update_file(stage, newpath))
5104 return status_load_error(view, stage, newpath);
5105 info = "Untracked file %s";
5106 break;
5108 case LINE_STAT_HEAD:
5109 return REQ_NONE;
5111 default:
5112 die("line type %d not handled in switch", line->type);
5113 }
5115 split = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5116 open_view(view, REQ_VIEW_STAGE, OPEN_PREPARED | split);
5117 if (view_is_displayed(VIEW(REQ_VIEW_STAGE))) {
5118 if (status) {
5119 stage_status = *status;
5120 } else {
5121 memset(&stage_status, 0, sizeof(stage_status));
5122 }
5124 stage_line_type = line->type;
5125 stage_chunks = 0;
5126 string_format(VIEW(REQ_VIEW_STAGE)->ref, info, stage_status.new.name);
5127 }
5129 return REQ_NONE;
5130 }
5132 static bool
5133 status_exists(struct status *status, enum line_type type)
5134 {
5135 struct view *view = VIEW(REQ_VIEW_STATUS);
5136 unsigned long lineno;
5138 for (lineno = 0; lineno < view->lines; lineno++) {
5139 struct line *line = &view->line[lineno];
5140 struct status *pos = line->data;
5142 if (line->type != type)
5143 continue;
5144 if (!pos && (!status || !status->status) && line[1].data) {
5145 select_view_line(view, lineno);
5146 return TRUE;
5147 }
5148 if (pos && !strcmp(status->new.name, pos->new.name)) {
5149 select_view_line(view, lineno);
5150 return TRUE;
5151 }
5152 }
5154 return FALSE;
5155 }
5158 static bool
5159 status_update_prepare(struct io *io, enum line_type type)
5160 {
5161 const char *staged_argv[] = {
5162 "git", "update-index", "-z", "--index-info", NULL
5163 };
5164 const char *others_argv[] = {
5165 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5166 };
5168 switch (type) {
5169 case LINE_STAT_STAGED:
5170 return io_run(io, IO_WR, opt_cdup, staged_argv);
5172 case LINE_STAT_UNSTAGED:
5173 case LINE_STAT_UNTRACKED:
5174 return io_run(io, IO_WR, opt_cdup, others_argv);
5176 default:
5177 die("line type %d not handled in switch", type);
5178 return FALSE;
5179 }
5180 }
5182 static bool
5183 status_update_write(struct io *io, struct status *status, enum line_type type)
5184 {
5185 char buf[SIZEOF_STR];
5186 size_t bufsize = 0;
5188 switch (type) {
5189 case LINE_STAT_STAGED:
5190 if (!string_format_from(buf, &bufsize, "%06o %s\t%s%c",
5191 status->old.mode,
5192 status->old.rev,
5193 status->old.name, 0))
5194 return FALSE;
5195 break;
5197 case LINE_STAT_UNSTAGED:
5198 case LINE_STAT_UNTRACKED:
5199 if (!string_format_from(buf, &bufsize, "%s%c", status->new.name, 0))
5200 return FALSE;
5201 break;
5203 default:
5204 die("line type %d not handled in switch", type);
5205 }
5207 return io_write(io, buf, bufsize);
5208 }
5210 static bool
5211 status_update_file(struct status *status, enum line_type type)
5212 {
5213 struct io io;
5214 bool result;
5216 if (!status_update_prepare(&io, type))
5217 return FALSE;
5219 result = status_update_write(&io, status, type);
5220 return io_done(&io) && result;
5221 }
5223 static bool
5224 status_update_files(struct view *view, struct line *line)
5225 {
5226 char buf[sizeof(view->ref)];
5227 struct io io;
5228 bool result = TRUE;
5229 struct line *pos = view->line + view->lines;
5230 int files = 0;
5231 int file, done;
5232 int cursor_y = -1, cursor_x = -1;
5234 if (!status_update_prepare(&io, line->type))
5235 return FALSE;
5237 for (pos = line; pos < view->line + view->lines && pos->data; pos++)
5238 files++;
5240 string_copy(buf, view->ref);
5241 getsyx(cursor_y, cursor_x);
5242 for (file = 0, done = 5; result && file < files; line++, file++) {
5243 int almost_done = file * 100 / files;
5245 if (almost_done > done) {
5246 done = almost_done;
5247 string_format(view->ref, "updating file %u of %u (%d%% done)",
5248 file, files, done);
5249 update_view_title(view);
5250 setsyx(cursor_y, cursor_x);
5251 doupdate();
5252 }
5253 result = status_update_write(&io, line->data, line->type);
5254 }
5255 string_copy(view->ref, buf);
5257 return io_done(&io) && result;
5258 }
5260 static bool
5261 status_update(struct view *view)
5262 {
5263 struct line *line = &view->line[view->lineno];
5265 assert(view->lines);
5267 if (!line->data) {
5268 /* This should work even for the "On branch" line. */
5269 if (line < view->line + view->lines && !line[1].data) {
5270 report("Nothing to update");
5271 return FALSE;
5272 }
5274 if (!status_update_files(view, line + 1)) {
5275 report("Failed to update file status");
5276 return FALSE;
5277 }
5279 } else if (!status_update_file(line->data, line->type)) {
5280 report("Failed to update file status");
5281 return FALSE;
5282 }
5284 return TRUE;
5285 }
5287 static bool
5288 status_revert(struct status *status, enum line_type type, bool has_none)
5289 {
5290 if (!status || type != LINE_STAT_UNSTAGED) {
5291 if (type == LINE_STAT_STAGED) {
5292 report("Cannot revert changes to staged files");
5293 } else if (type == LINE_STAT_UNTRACKED) {
5294 report("Cannot revert changes to untracked files");
5295 } else if (has_none) {
5296 report("Nothing to revert");
5297 } else {
5298 report("Cannot revert changes to multiple files");
5299 }
5301 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5302 char mode[10] = "100644";
5303 const char *reset_argv[] = {
5304 "git", "update-index", "--cacheinfo", mode,
5305 status->old.rev, status->old.name, NULL
5306 };
5307 const char *checkout_argv[] = {
5308 "git", "checkout", "--", status->old.name, NULL
5309 };
5311 if (status->status == 'U') {
5312 string_format(mode, "%5o", status->old.mode);
5314 if (status->old.mode == 0 && status->new.mode == 0) {
5315 reset_argv[2] = "--force-remove";
5316 reset_argv[3] = status->old.name;
5317 reset_argv[4] = NULL;
5318 }
5320 if (!io_run_fg(reset_argv, opt_cdup))
5321 return FALSE;
5322 if (status->old.mode == 0 && status->new.mode == 0)
5323 return TRUE;
5324 }
5326 return io_run_fg(checkout_argv, opt_cdup);
5327 }
5329 return FALSE;
5330 }
5332 static enum request
5333 status_request(struct view *view, enum request request, struct line *line)
5334 {
5335 struct status *status = line->data;
5337 switch (request) {
5338 case REQ_STATUS_UPDATE:
5339 if (!status_update(view))
5340 return REQ_NONE;
5341 break;
5343 case REQ_STATUS_REVERT:
5344 if (!status_revert(status, line->type, status_has_none(view, line)))
5345 return REQ_NONE;
5346 break;
5348 case REQ_STATUS_MERGE:
5349 if (!status || status->status != 'U') {
5350 report("Merging only possible for files with unmerged status ('U').");
5351 return REQ_NONE;
5352 }
5353 open_mergetool(status->new.name);
5354 break;
5356 case REQ_EDIT:
5357 if (!status)
5358 return request;
5359 if (status->status == 'D') {
5360 report("File has been deleted.");
5361 return REQ_NONE;
5362 }
5364 open_editor(status->new.name);
5365 break;
5367 case REQ_VIEW_BLAME:
5368 if (status)
5369 opt_ref[0] = 0;
5370 return request;
5372 case REQ_ENTER:
5373 /* After returning the status view has been split to
5374 * show the stage view. No further reloading is
5375 * necessary. */
5376 return status_enter(view, line);
5378 case REQ_REFRESH:
5379 /* Simply reload the view. */
5380 break;
5382 default:
5383 return request;
5384 }
5386 open_view(view, REQ_VIEW_STATUS, OPEN_RELOAD);
5388 return REQ_NONE;
5389 }
5391 static void
5392 status_select(struct view *view, struct line *line)
5393 {
5394 struct status *status = line->data;
5395 char file[SIZEOF_STR] = "all files";
5396 const char *text;
5397 const char *key;
5399 if (status && !string_format(file, "'%s'", status->new.name))
5400 return;
5402 if (!status && line[1].type == LINE_STAT_NONE)
5403 line++;
5405 switch (line->type) {
5406 case LINE_STAT_STAGED:
5407 text = "Press %s to unstage %s for commit";
5408 break;
5410 case LINE_STAT_UNSTAGED:
5411 text = "Press %s to stage %s for commit";
5412 break;
5414 case LINE_STAT_UNTRACKED:
5415 text = "Press %s to stage %s for addition";
5416 break;
5418 case LINE_STAT_HEAD:
5419 case LINE_STAT_NONE:
5420 text = "Nothing to update";
5421 break;
5423 default:
5424 die("line type %d not handled in switch", line->type);
5425 }
5427 if (status && status->status == 'U') {
5428 text = "Press %s to resolve conflict in %s";
5429 key = get_key(KEYMAP_STATUS, REQ_STATUS_MERGE);
5431 } else {
5432 key = get_key(KEYMAP_STATUS, REQ_STATUS_UPDATE);
5433 }
5435 string_format(view->ref, text, key, file);
5436 if (status)
5437 string_copy(opt_file, status->new.name);
5438 }
5440 static bool
5441 status_grep(struct view *view, struct line *line)
5442 {
5443 struct status *status = line->data;
5445 if (status) {
5446 const char buf[2] = { status->status, 0 };
5447 const char *text[] = { status->new.name, buf, NULL };
5449 return grep_text(view, text);
5450 }
5452 return FALSE;
5453 }
5455 static struct view_ops status_ops = {
5456 "file",
5457 NULL,
5458 status_open,
5459 NULL,
5460 status_draw,
5461 status_request,
5462 status_grep,
5463 status_select,
5464 };
5467 static bool
5468 stage_diff_write(struct io *io, struct line *line, struct line *end)
5469 {
5470 while (line < end) {
5471 if (!io_write(io, line->data, strlen(line->data)) ||
5472 !io_write(io, "\n", 1))
5473 return FALSE;
5474 line++;
5475 if (line->type == LINE_DIFF_CHUNK ||
5476 line->type == LINE_DIFF_HEADER)
5477 break;
5478 }
5480 return TRUE;
5481 }
5483 static struct line *
5484 stage_diff_find(struct view *view, struct line *line, enum line_type type)
5485 {
5486 for (; view->line < line; line--)
5487 if (line->type == type)
5488 return line;
5490 return NULL;
5491 }
5493 static bool
5494 stage_apply_chunk(struct view *view, struct line *chunk, bool revert)
5495 {
5496 const char *apply_argv[SIZEOF_ARG] = {
5497 "git", "apply", "--whitespace=nowarn", NULL
5498 };
5499 struct line *diff_hdr;
5500 struct io io;
5501 int argc = 3;
5503 diff_hdr = stage_diff_find(view, chunk, LINE_DIFF_HEADER);
5504 if (!diff_hdr)
5505 return FALSE;
5507 if (!revert)
5508 apply_argv[argc++] = "--cached";
5509 if (revert || stage_line_type == LINE_STAT_STAGED)
5510 apply_argv[argc++] = "-R";
5511 apply_argv[argc++] = "-";
5512 apply_argv[argc++] = NULL;
5513 if (!io_run(&io, IO_WR, opt_cdup, apply_argv))
5514 return FALSE;
5516 if (!stage_diff_write(&io, diff_hdr, chunk) ||
5517 !stage_diff_write(&io, chunk, view->line + view->lines))
5518 chunk = NULL;
5520 io_done(&io);
5521 io_run_bg(update_index_argv);
5523 return chunk ? TRUE : FALSE;
5524 }
5526 static bool
5527 stage_update(struct view *view, struct line *line)
5528 {
5529 struct line *chunk = NULL;
5531 if (!is_initial_commit() && stage_line_type != LINE_STAT_UNTRACKED)
5532 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5534 if (chunk) {
5535 if (!stage_apply_chunk(view, chunk, FALSE)) {
5536 report("Failed to apply chunk");
5537 return FALSE;
5538 }
5540 } else if (!stage_status.status) {
5541 view = VIEW(REQ_VIEW_STATUS);
5543 for (line = view->line; line < view->line + view->lines; line++)
5544 if (line->type == stage_line_type)
5545 break;
5547 if (!status_update_files(view, line + 1)) {
5548 report("Failed to update files");
5549 return FALSE;
5550 }
5552 } else if (!status_update_file(&stage_status, stage_line_type)) {
5553 report("Failed to update file");
5554 return FALSE;
5555 }
5557 return TRUE;
5558 }
5560 static bool
5561 stage_revert(struct view *view, struct line *line)
5562 {
5563 struct line *chunk = NULL;
5565 if (!is_initial_commit() && stage_line_type == LINE_STAT_UNSTAGED)
5566 chunk = stage_diff_find(view, line, LINE_DIFF_CHUNK);
5568 if (chunk) {
5569 if (!prompt_yesno("Are you sure you want to revert changes?"))
5570 return FALSE;
5572 if (!stage_apply_chunk(view, chunk, TRUE)) {
5573 report("Failed to revert chunk");
5574 return FALSE;
5575 }
5576 return TRUE;
5578 } else {
5579 return status_revert(stage_status.status ? &stage_status : NULL,
5580 stage_line_type, FALSE);
5581 }
5582 }
5585 static void
5586 stage_next(struct view *view, struct line *line)
5587 {
5588 int i;
5590 if (!stage_chunks) {
5591 for (line = view->line; line < view->line + view->lines; line++) {
5592 if (line->type != LINE_DIFF_CHUNK)
5593 continue;
5595 if (!realloc_ints(&stage_chunk, stage_chunks, 1)) {
5596 report("Allocation failure");
5597 return;
5598 }
5600 stage_chunk[stage_chunks++] = line - view->line;
5601 }
5602 }
5604 for (i = 0; i < stage_chunks; i++) {
5605 if (stage_chunk[i] > view->lineno) {
5606 do_scroll_view(view, stage_chunk[i] - view->lineno);
5607 report("Chunk %d of %d", i + 1, stage_chunks);
5608 return;
5609 }
5610 }
5612 report("No next chunk found");
5613 }
5615 static enum request
5616 stage_request(struct view *view, enum request request, struct line *line)
5617 {
5618 switch (request) {
5619 case REQ_STATUS_UPDATE:
5620 if (!stage_update(view, line))
5621 return REQ_NONE;
5622 break;
5624 case REQ_STATUS_REVERT:
5625 if (!stage_revert(view, line))
5626 return REQ_NONE;
5627 break;
5629 case REQ_STAGE_NEXT:
5630 if (stage_line_type == LINE_STAT_UNTRACKED) {
5631 report("File is untracked; press %s to add",
5632 get_key(KEYMAP_STAGE, REQ_STATUS_UPDATE));
5633 return REQ_NONE;
5634 }
5635 stage_next(view, line);
5636 return REQ_NONE;
5638 case REQ_EDIT:
5639 if (!stage_status.new.name[0])
5640 return request;
5641 if (stage_status.status == 'D') {
5642 report("File has been deleted.");
5643 return REQ_NONE;
5644 }
5646 open_editor(stage_status.new.name);
5647 break;
5649 case REQ_REFRESH:
5650 /* Reload everything ... */
5651 break;
5653 case REQ_VIEW_BLAME:
5654 if (stage_status.new.name[0]) {
5655 string_copy(opt_file, stage_status.new.name);
5656 opt_ref[0] = 0;
5657 }
5658 return request;
5660 case REQ_ENTER:
5661 return pager_request(view, request, line);
5663 default:
5664 return request;
5665 }
5667 VIEW(REQ_VIEW_STATUS)->p_restore = TRUE;
5668 open_view(view, REQ_VIEW_STATUS, OPEN_REFRESH);
5670 /* Check whether the staged entry still exists, and close the
5671 * stage view if it doesn't. */
5672 if (!status_exists(&stage_status, stage_line_type)) {
5673 status_restore(VIEW(REQ_VIEW_STATUS));
5674 return REQ_VIEW_CLOSE;
5675 }
5677 if (stage_line_type == LINE_STAT_UNTRACKED) {
5678 if (!suffixcmp(stage_status.new.name, -1, "/")) {
5679 report("Cannot display a directory");
5680 return REQ_NONE;
5681 }
5683 if (!prepare_update_file(view, stage_status.new.name)) {
5684 report("Failed to open file: %s", strerror(errno));
5685 return REQ_NONE;
5686 }
5687 }
5688 open_view(view, REQ_VIEW_STAGE, OPEN_REFRESH);
5690 return REQ_NONE;
5691 }
5693 static struct view_ops stage_ops = {
5694 "line",
5695 NULL,
5696 NULL,
5697 pager_read,
5698 pager_draw,
5699 stage_request,
5700 pager_grep,
5701 pager_select,
5702 };
5705 /*
5706 * Revision graph
5707 */
5709 static const enum line_type graph_colors[] = {
5710 LINE_GRAPH_LINE_0,
5711 LINE_GRAPH_LINE_1,
5712 LINE_GRAPH_LINE_2,
5713 LINE_GRAPH_LINE_3,
5714 LINE_GRAPH_LINE_4,
5715 LINE_GRAPH_LINE_5,
5716 LINE_GRAPH_LINE_6,
5717 };
5719 static enum line_type get_graph_color(struct graph_symbol *symbol)
5720 {
5721 if (symbol->commit)
5722 return LINE_GRAPH_COMMIT;
5723 assert(symbol->color < ARRAY_SIZE(graph_colors));
5724 return graph_colors[symbol->color];
5725 }
5727 static bool
5728 draw_graph_utf8(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5729 {
5730 const char *chars = graph_symbol_to_utf8(symbol);
5732 return draw_text(view, color, chars + !!first);
5733 }
5735 static bool
5736 draw_graph_ascii(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5737 {
5738 const char *chars = graph_symbol_to_ascii(symbol);
5740 return draw_text(view, color, chars + !!first);
5741 }
5743 static bool
5744 draw_graph_chtype(struct view *view, struct graph_symbol *symbol, enum line_type color, bool first)
5745 {
5746 const chtype *chars = graph_symbol_to_chtype(symbol);
5748 return draw_graphic(view, color, chars + !!first, 2 - !!first, FALSE);
5749 }
5751 typedef bool (*draw_graph_fn)(struct view *, struct graph_symbol *, enum line_type, bool);
5753 static bool draw_graph(struct view *view, struct graph_canvas *canvas)
5754 {
5755 static const draw_graph_fn fns[] = {
5756 draw_graph_ascii,
5757 draw_graph_chtype,
5758 draw_graph_utf8
5759 };
5760 draw_graph_fn fn = fns[opt_line_graphics];
5761 int i;
5763 for (i = 0; i < canvas->size; i++) {
5764 struct graph_symbol *symbol = &canvas->symbols[i];
5765 enum line_type color = get_graph_color(symbol);
5767 if (fn(view, symbol, color, i == 0))
5768 return TRUE;
5769 }
5771 return draw_text(view, LINE_MAIN_REVGRAPH, " ");
5772 }
5774 /*
5775 * Main view backend
5776 */
5778 struct commit {
5779 char id[SIZEOF_REV]; /* SHA1 ID. */
5780 char title[128]; /* First line of the commit message. */
5781 const char *author; /* Author of the commit. */
5782 struct time time; /* Date from the author ident. */
5783 struct ref_list *refs; /* Repository references. */
5784 struct graph_canvas graph; /* Ancestry chain graphics. */
5785 };
5787 static const char *main_argv[SIZEOF_ARG] = {
5788 "git", "log", "--no-color", "--pretty=raw", "--parents",
5789 "--topo-order", "%(diffargs)", "%(revargs)",
5790 "--", "%(fileargs)", NULL
5791 };
5793 static bool
5794 main_draw(struct view *view, struct line *line, unsigned int lineno)
5795 {
5796 struct commit *commit = line->data;
5798 if (!commit->author)
5799 return FALSE;
5801 if (opt_date && draw_date(view, &commit->time))
5802 return TRUE;
5804 if (opt_author && draw_author(view, commit->author))
5805 return TRUE;
5807 if (opt_rev_graph && draw_graph(view, &commit->graph))
5808 return TRUE;
5810 if (opt_show_refs && commit->refs) {
5811 size_t i;
5813 for (i = 0; i < commit->refs->size; i++) {
5814 struct ref *ref = commit->refs->refs[i];
5815 enum line_type type;
5817 if (ref->head)
5818 type = LINE_MAIN_HEAD;
5819 else if (ref->ltag)
5820 type = LINE_MAIN_LOCAL_TAG;
5821 else if (ref->tag)
5822 type = LINE_MAIN_TAG;
5823 else if (ref->tracked)
5824 type = LINE_MAIN_TRACKED;
5825 else if (ref->remote)
5826 type = LINE_MAIN_REMOTE;
5827 else
5828 type = LINE_MAIN_REF;
5830 if (draw_text(view, type, "[") ||
5831 draw_text(view, type, ref->name) ||
5832 draw_text(view, type, "]"))
5833 return TRUE;
5835 if (draw_text(view, LINE_DEFAULT, " "))
5836 return TRUE;
5837 }
5838 }
5840 draw_text(view, LINE_DEFAULT, commit->title);
5841 return TRUE;
5842 }
5844 /* Reads git log --pretty=raw output and parses it into the commit struct. */
5845 static bool
5846 main_read(struct view *view, char *line)
5847 {
5848 static struct graph graph;
5849 enum line_type type;
5850 struct commit *commit;
5852 if (!line) {
5853 if (!view->lines && !view->prev)
5854 die("No revisions match the given arguments.");
5855 if (view->lines > 0) {
5856 commit = view->line[view->lines - 1].data;
5857 view->line[view->lines - 1].dirty = 1;
5858 if (!commit->author) {
5859 view->lines--;
5860 free(commit);
5861 }
5862 }
5864 done_graph(&graph);
5865 return TRUE;
5866 }
5868 type = get_line_type(line);
5869 if (type == LINE_COMMIT) {
5870 bool is_boundary;
5872 commit = calloc(1, sizeof(struct commit));
5873 if (!commit)
5874 return FALSE;
5876 line += STRING_SIZE("commit ");
5877 is_boundary = *line == '-';
5878 if (is_boundary)
5879 line++;
5881 string_copy_rev(commit->id, line);
5882 commit->refs = get_ref_list(commit->id);
5883 add_line_data(view, commit, LINE_MAIN_COMMIT);
5884 graph_add_commit(&graph, &commit->graph, commit->id, line, is_boundary);
5885 return TRUE;
5886 }
5888 if (!view->lines)
5889 return TRUE;
5890 commit = view->line[view->lines - 1].data;
5892 switch (type) {
5893 case LINE_PARENT:
5894 if (!graph.has_parents)
5895 graph_add_parent(&graph, line + STRING_SIZE("parent "));
5896 break;
5898 case LINE_AUTHOR:
5899 parse_author_line(line + STRING_SIZE("author "),
5900 &commit->author, &commit->time);
5901 graph_render_parents(&graph);
5902 break;
5904 default:
5905 /* Fill in the commit title if it has not already been set. */
5906 if (commit->title[0])
5907 break;
5909 /* Require titles to start with a non-space character at the
5910 * offset used by git log. */
5911 if (strncmp(line, " ", 4))
5912 break;
5913 line += 4;
5914 /* Well, if the title starts with a whitespace character,
5915 * try to be forgiving. Otherwise we end up with no title. */
5916 while (isspace(*line))
5917 line++;
5918 if (*line == '\0')
5919 break;
5920 /* FIXME: More graceful handling of titles; append "..." to
5921 * shortened titles, etc. */
5923 string_expand(commit->title, sizeof(commit->title), line, 1);
5924 view->line[view->lines - 1].dirty = 1;
5925 }
5927 return TRUE;
5928 }
5930 static enum request
5931 main_request(struct view *view, enum request request, struct line *line)
5932 {
5933 enum open_flags flags = view_is_displayed(view) ? OPEN_SPLIT : OPEN_DEFAULT;
5935 switch (request) {
5936 case REQ_ENTER:
5937 if (view_is_displayed(view) && display[0] != view)
5938 maximize_view(view);
5939 open_view(view, REQ_VIEW_DIFF, flags);
5940 break;
5941 case REQ_REFRESH:
5942 load_refs();
5943 open_view(view, REQ_VIEW_MAIN, OPEN_REFRESH);
5944 break;
5945 default:
5946 return request;
5947 }
5949 return REQ_NONE;
5950 }
5952 static bool
5953 grep_refs(struct ref_list *list, regex_t *regex)
5954 {
5955 regmatch_t pmatch;
5956 size_t i;
5958 if (!opt_show_refs || !list)
5959 return FALSE;
5961 for (i = 0; i < list->size; i++) {
5962 if (regexec(regex, list->refs[i]->name, 1, &pmatch, 0) != REG_NOMATCH)
5963 return TRUE;
5964 }
5966 return FALSE;
5967 }
5969 static bool
5970 main_grep(struct view *view, struct line *line)
5971 {
5972 struct commit *commit = line->data;
5973 const char *text[] = {
5974 commit->title,
5975 opt_author ? commit->author : "",
5976 mkdate(&commit->time, opt_date),
5977 NULL
5978 };
5980 return grep_text(view, text) || grep_refs(commit->refs, view->regex);
5981 }
5983 static void
5984 main_select(struct view *view, struct line *line)
5985 {
5986 struct commit *commit = line->data;
5988 string_copy_rev(view->ref, commit->id);
5989 string_copy_rev(ref_commit, view->ref);
5990 }
5992 static struct view_ops main_ops = {
5993 "commit",
5994 main_argv,
5995 NULL,
5996 main_read,
5997 main_draw,
5998 main_request,
5999 main_grep,
6000 main_select,
6001 };
6004 /*
6005 * Status management
6006 */
6008 /* Whether or not the curses interface has been initialized. */
6009 static bool cursed = FALSE;
6011 /* Terminal hacks and workarounds. */
6012 static bool use_scroll_redrawwin;
6013 static bool use_scroll_status_wclear;
6015 /* The status window is used for polling keystrokes. */
6016 static WINDOW *status_win;
6018 /* Reading from the prompt? */
6019 static bool input_mode = FALSE;
6021 static bool status_empty = FALSE;
6023 /* Update status and title window. */
6024 static void
6025 report(const char *msg, ...)
6026 {
6027 struct view *view = display[current_view];
6029 if (input_mode)
6030 return;
6032 if (!view) {
6033 char buf[SIZEOF_STR];
6034 va_list args;
6036 va_start(args, msg);
6037 if (vsnprintf(buf, sizeof(buf), msg, args) >= sizeof(buf)) {
6038 buf[sizeof(buf) - 1] = 0;
6039 buf[sizeof(buf) - 2] = '.';
6040 buf[sizeof(buf) - 3] = '.';
6041 buf[sizeof(buf) - 4] = '.';
6042 }
6043 va_end(args);
6044 die("%s", buf);
6045 }
6047 if (!status_empty || *msg) {
6048 va_list args;
6050 va_start(args, msg);
6052 wmove(status_win, 0, 0);
6053 if (view->has_scrolled && use_scroll_status_wclear)
6054 wclear(status_win);
6055 if (*msg) {
6056 vwprintw(status_win, msg, args);
6057 status_empty = FALSE;
6058 } else {
6059 status_empty = TRUE;
6060 }
6061 wclrtoeol(status_win);
6062 wnoutrefresh(status_win);
6064 va_end(args);
6065 }
6067 update_view_title(view);
6068 }
6070 static void
6071 init_display(void)
6072 {
6073 const char *term;
6074 int x, y;
6076 /* Initialize the curses library */
6077 if (isatty(STDIN_FILENO)) {
6078 cursed = !!initscr();
6079 opt_tty = stdin;
6080 } else {
6081 /* Leave stdin and stdout alone when acting as a pager. */
6082 opt_tty = fopen("/dev/tty", "r+");
6083 if (!opt_tty)
6084 die("Failed to open /dev/tty");
6085 cursed = !!newterm(NULL, opt_tty, opt_tty);
6086 }
6088 if (!cursed)
6089 die("Failed to initialize curses");
6091 nonl(); /* Disable conversion and detect newlines from input. */
6092 cbreak(); /* Take input chars one at a time, no wait for \n */
6093 noecho(); /* Don't echo input */
6094 leaveok(stdscr, FALSE);
6096 if (has_colors())
6097 init_colors();
6099 getmaxyx(stdscr, y, x);
6100 status_win = newwin(1, x, y - 1, 0);
6101 if (!status_win)
6102 die("Failed to create status window");
6104 /* Enable keyboard mapping */
6105 keypad(status_win, TRUE);
6106 wbkgdset(status_win, get_line_attr(LINE_STATUS));
6108 #if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
6109 set_tabsize(opt_tab_size);
6110 #else
6111 TABSIZE = opt_tab_size;
6112 #endif
6114 term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
6115 if (term && !strcmp(term, "gnome-terminal")) {
6116 /* In the gnome-terminal-emulator, the message from
6117 * scrolling up one line when impossible followed by
6118 * scrolling down one line causes corruption of the
6119 * status line. This is fixed by calling wclear. */
6120 use_scroll_status_wclear = TRUE;
6121 use_scroll_redrawwin = FALSE;
6123 } else if (term && !strcmp(term, "xrvt-xpm")) {
6124 /* No problems with full optimizations in xrvt-(unicode)
6125 * and aterm. */
6126 use_scroll_status_wclear = use_scroll_redrawwin = FALSE;
6128 } else {
6129 /* When scrolling in (u)xterm the last line in the
6130 * scrolling direction will update slowly. */
6131 use_scroll_redrawwin = TRUE;
6132 use_scroll_status_wclear = FALSE;
6133 }
6134 }
6136 static int
6137 get_input(int prompt_position)
6138 {
6139 struct view *view;
6140 int i, key, cursor_y, cursor_x;
6142 if (prompt_position)
6143 input_mode = TRUE;
6145 while (TRUE) {
6146 bool loading = FALSE;
6148 foreach_view (view, i) {
6149 update_view(view);
6150 if (view_is_displayed(view) && view->has_scrolled &&
6151 use_scroll_redrawwin)
6152 redrawwin(view->win);
6153 view->has_scrolled = FALSE;
6154 if (view->pipe)
6155 loading = TRUE;
6156 }
6158 /* Update the cursor position. */
6159 if (prompt_position) {
6160 getbegyx(status_win, cursor_y, cursor_x);
6161 cursor_x = prompt_position;
6162 } else {
6163 view = display[current_view];
6164 getbegyx(view->win, cursor_y, cursor_x);
6165 cursor_x = view->width - 1;
6166 cursor_y += view->lineno - view->offset;
6167 }
6168 setsyx(cursor_y, cursor_x);
6170 /* Refresh, accept single keystroke of input */
6171 doupdate();
6172 nodelay(status_win, loading);
6173 key = wgetch(status_win);
6175 /* wgetch() with nodelay() enabled returns ERR when
6176 * there's no input. */
6177 if (key == ERR) {
6179 } else if (key == KEY_RESIZE) {
6180 int height, width;
6182 getmaxyx(stdscr, height, width);
6184 wresize(status_win, 1, width);
6185 mvwin(status_win, height - 1, 0);
6186 wnoutrefresh(status_win);
6187 resize_display();
6188 redraw_display(TRUE);
6190 } else {
6191 input_mode = FALSE;
6192 return key;
6193 }
6194 }
6195 }
6197 static char *
6198 prompt_input(const char *prompt, input_handler handler, void *data)
6199 {
6200 enum input_status status = INPUT_OK;
6201 static char buf[SIZEOF_STR];
6202 size_t pos = 0;
6204 buf[pos] = 0;
6206 while (status == INPUT_OK || status == INPUT_SKIP) {
6207 int key;
6209 mvwprintw(status_win, 0, 0, "%s%.*s", prompt, pos, buf);
6210 wclrtoeol(status_win);
6212 key = get_input(pos + 1);
6213 switch (key) {
6214 case KEY_RETURN:
6215 case KEY_ENTER:
6216 case '\n':
6217 status = pos ? INPUT_STOP : INPUT_CANCEL;
6218 break;
6220 case KEY_BACKSPACE:
6221 if (pos > 0)
6222 buf[--pos] = 0;
6223 else
6224 status = INPUT_CANCEL;
6225 break;
6227 case KEY_ESC:
6228 status = INPUT_CANCEL;
6229 break;
6231 default:
6232 if (pos >= sizeof(buf)) {
6233 report("Input string too long");
6234 return NULL;
6235 }
6237 status = handler(data, buf, key);
6238 if (status == INPUT_OK)
6239 buf[pos++] = (char) key;
6240 }
6241 }
6243 /* Clear the status window */
6244 status_empty = FALSE;
6245 report("");
6247 if (status == INPUT_CANCEL)
6248 return NULL;
6250 buf[pos++] = 0;
6252 return buf;
6253 }
6255 static enum input_status
6256 prompt_yesno_handler(void *data, char *buf, int c)
6257 {
6258 if (c == 'y' || c == 'Y')
6259 return INPUT_STOP;
6260 if (c == 'n' || c == 'N')
6261 return INPUT_CANCEL;
6262 return INPUT_SKIP;
6263 }
6265 static bool
6266 prompt_yesno(const char *prompt)
6267 {
6268 char prompt2[SIZEOF_STR];
6270 if (!string_format(prompt2, "%s [Yy/Nn]", prompt))
6271 return FALSE;
6273 return !!prompt_input(prompt2, prompt_yesno_handler, NULL);
6274 }
6276 static enum input_status
6277 read_prompt_handler(void *data, char *buf, int c)
6278 {
6279 return isprint(c) ? INPUT_OK : INPUT_SKIP;
6280 }
6282 static char *
6283 read_prompt(const char *prompt)
6284 {
6285 return prompt_input(prompt, read_prompt_handler, NULL);
6286 }
6288 static bool prompt_menu(const char *prompt, const struct menu_item *items, int *selected)
6289 {
6290 enum input_status status = INPUT_OK;
6291 int size = 0;
6293 while (items[size].text)
6294 size++;
6296 while (status == INPUT_OK) {
6297 const struct menu_item *item = &items[*selected];
6298 int key;
6299 int i;
6301 mvwprintw(status_win, 0, 0, "%s (%d of %d) ",
6302 prompt, *selected + 1, size);
6303 if (item->hotkey)
6304 wprintw(status_win, "[%c] ", (char) item->hotkey);
6305 wprintw(status_win, "%s", item->text);
6306 wclrtoeol(status_win);
6308 key = get_input(COLS - 1);
6309 switch (key) {
6310 case KEY_RETURN:
6311 case KEY_ENTER:
6312 case '\n':
6313 status = INPUT_STOP;
6314 break;
6316 case KEY_LEFT:
6317 case KEY_UP:
6318 *selected = *selected - 1;
6319 if (*selected < 0)
6320 *selected = size - 1;
6321 break;
6323 case KEY_RIGHT:
6324 case KEY_DOWN:
6325 *selected = (*selected + 1) % size;
6326 break;
6328 case KEY_ESC:
6329 status = INPUT_CANCEL;
6330 break;
6332 default:
6333 for (i = 0; items[i].text; i++)
6334 if (items[i].hotkey == key) {
6335 *selected = i;
6336 status = INPUT_STOP;
6337 break;
6338 }
6339 }
6340 }
6342 /* Clear the status window */
6343 status_empty = FALSE;
6344 report("");
6346 return status != INPUT_CANCEL;
6347 }
6349 /*
6350 * Repository properties
6351 */
6353 static struct ref **refs = NULL;
6354 static size_t refs_size = 0;
6355 static struct ref *refs_head = NULL;
6357 static struct ref_list **ref_lists = NULL;
6358 static size_t ref_lists_size = 0;
6360 DEFINE_ALLOCATOR(realloc_refs, struct ref *, 256)
6361 DEFINE_ALLOCATOR(realloc_refs_list, struct ref *, 8)
6362 DEFINE_ALLOCATOR(realloc_ref_lists, struct ref_list *, 8)
6364 static int
6365 compare_refs(const void *ref1_, const void *ref2_)
6366 {
6367 const struct ref *ref1 = *(const struct ref **)ref1_;
6368 const struct ref *ref2 = *(const struct ref **)ref2_;
6370 if (ref1->tag != ref2->tag)
6371 return ref2->tag - ref1->tag;
6372 if (ref1->ltag != ref2->ltag)
6373 return ref2->ltag - ref2->ltag;
6374 if (ref1->head != ref2->head)
6375 return ref2->head - ref1->head;
6376 if (ref1->tracked != ref2->tracked)
6377 return ref2->tracked - ref1->tracked;
6378 if (ref1->remote != ref2->remote)
6379 return ref2->remote - ref1->remote;
6380 return strcmp(ref1->name, ref2->name);
6381 }
6383 static void
6384 foreach_ref(bool (*visitor)(void *data, const struct ref *ref), void *data)
6385 {
6386 size_t i;
6388 for (i = 0; i < refs_size; i++)
6389 if (!visitor(data, refs[i]))
6390 break;
6391 }
6393 static struct ref *
6394 get_ref_head()
6395 {
6396 return refs_head;
6397 }
6399 static struct ref_list *
6400 get_ref_list(const char *id)
6401 {
6402 struct ref_list *list;
6403 size_t i;
6405 for (i = 0; i < ref_lists_size; i++)
6406 if (!strcmp(id, ref_lists[i]->id))
6407 return ref_lists[i];
6409 if (!realloc_ref_lists(&ref_lists, ref_lists_size, 1))
6410 return NULL;
6411 list = calloc(1, sizeof(*list));
6412 if (!list)
6413 return NULL;
6415 for (i = 0; i < refs_size; i++) {
6416 if (!strcmp(id, refs[i]->id) &&
6417 realloc_refs_list(&list->refs, list->size, 1))
6418 list->refs[list->size++] = refs[i];
6419 }
6421 if (!list->refs) {
6422 free(list);
6423 return NULL;
6424 }
6426 qsort(list->refs, list->size, sizeof(*list->refs), compare_refs);
6427 ref_lists[ref_lists_size++] = list;
6428 return list;
6429 }
6431 static int
6432 read_ref(char *id, size_t idlen, char *name, size_t namelen, void *data)
6433 {
6434 struct ref *ref = NULL;
6435 bool tag = FALSE;
6436 bool ltag = FALSE;
6437 bool remote = FALSE;
6438 bool tracked = FALSE;
6439 bool head = FALSE;
6440 int from = 0, to = refs_size - 1;
6442 if (!prefixcmp(name, "refs/tags/")) {
6443 if (!suffixcmp(name, namelen, "^{}")) {
6444 namelen -= 3;
6445 name[namelen] = 0;
6446 } else {
6447 ltag = TRUE;
6448 }
6450 tag = TRUE;
6451 namelen -= STRING_SIZE("refs/tags/");
6452 name += STRING_SIZE("refs/tags/");
6454 } else if (!prefixcmp(name, "refs/remotes/")) {
6455 remote = TRUE;
6456 namelen -= STRING_SIZE("refs/remotes/");
6457 name += STRING_SIZE("refs/remotes/");
6458 tracked = !strcmp(opt_remote, name);
6460 } else if (!prefixcmp(name, "refs/heads/")) {
6461 namelen -= STRING_SIZE("refs/heads/");
6462 name += STRING_SIZE("refs/heads/");
6463 if (!strncmp(opt_head, name, namelen))
6464 return OK;
6466 } else if (!strcmp(name, "HEAD")) {
6467 head = TRUE;
6468 if (*opt_head) {
6469 namelen = strlen(opt_head);
6470 name = opt_head;
6471 }
6472 }
6474 /* If we are reloading or it's an annotated tag, replace the
6475 * previous SHA1 with the resolved commit id; relies on the fact
6476 * git-ls-remote lists the commit id of an annotated tag right
6477 * before the commit id it points to. */
6478 while (from <= to) {
6479 size_t pos = (to + from) / 2;
6480 int cmp = strcmp(name, refs[pos]->name);
6482 if (!cmp) {
6483 ref = refs[pos];
6484 break;
6485 }
6487 if (cmp < 0)
6488 to = pos - 1;
6489 else
6490 from = pos + 1;
6491 }
6493 if (!ref) {
6494 if (!realloc_refs(&refs, refs_size, 1))
6495 return ERR;
6496 ref = calloc(1, sizeof(*ref) + namelen);
6497 if (!ref)
6498 return ERR;
6499 memmove(refs + from + 1, refs + from,
6500 (refs_size - from) * sizeof(*refs));
6501 refs[from] = ref;
6502 strncpy(ref->name, name, namelen);
6503 refs_size++;
6504 }
6506 ref->head = head;
6507 ref->tag = tag;
6508 ref->ltag = ltag;
6509 ref->remote = remote;
6510 ref->tracked = tracked;
6511 string_copy_rev(ref->id, id);
6513 if (head)
6514 refs_head = ref;
6515 return OK;
6516 }
6518 static int
6519 load_refs(void)
6520 {
6521 const char *head_argv[] = {
6522 "git", "symbolic-ref", "HEAD", NULL
6523 };
6524 static const char *ls_remote_argv[SIZEOF_ARG] = {
6525 "git", "ls-remote", opt_git_dir, NULL
6526 };
6527 static bool init = FALSE;
6528 size_t i;
6530 if (!init) {
6531 if (!argv_from_env(ls_remote_argv, "TIG_LS_REMOTE"))
6532 die("TIG_LS_REMOTE contains too many arguments");
6533 init = TRUE;
6534 }
6536 if (!*opt_git_dir)
6537 return OK;
6539 if (io_run_buf(head_argv, opt_head, sizeof(opt_head)) &&
6540 !prefixcmp(opt_head, "refs/heads/")) {
6541 char *offset = opt_head + STRING_SIZE("refs/heads/");
6543 memmove(opt_head, offset, strlen(offset) + 1);
6544 }
6546 refs_head = NULL;
6547 for (i = 0; i < refs_size; i++)
6548 refs[i]->id[0] = 0;
6550 if (io_run_load(ls_remote_argv, "\t", read_ref, NULL) == ERR)
6551 return ERR;
6553 /* Update the ref lists to reflect changes. */
6554 for (i = 0; i < ref_lists_size; i++) {
6555 struct ref_list *list = ref_lists[i];
6556 size_t old, new;
6558 for (old = new = 0; old < list->size; old++)
6559 if (!strcmp(list->id, list->refs[old]->id))
6560 list->refs[new++] = list->refs[old];
6561 list->size = new;
6562 }
6564 return OK;
6565 }
6567 static void
6568 set_remote_branch(const char *name, const char *value, size_t valuelen)
6569 {
6570 if (!strcmp(name, ".remote")) {
6571 string_ncopy(opt_remote, value, valuelen);
6573 } else if (*opt_remote && !strcmp(name, ".merge")) {
6574 size_t from = strlen(opt_remote);
6576 if (!prefixcmp(value, "refs/heads/"))
6577 value += STRING_SIZE("refs/heads/");
6579 if (!string_format_from(opt_remote, &from, "/%s", value))
6580 opt_remote[0] = 0;
6581 }
6582 }
6584 static void
6585 set_repo_config_option(char *name, char *value, enum option_code (*cmd)(int, const char **))
6586 {
6587 const char *argv[SIZEOF_ARG] = { name, "=" };
6588 int argc = 1 + (cmd == option_set_command);
6589 enum option_code error;
6591 if (!argv_from_string(argv, &argc, value))
6592 error = OPT_ERR_TOO_MANY_OPTION_ARGUMENTS;
6593 else
6594 error = cmd(argc, argv);
6596 if (error != OPT_OK)
6597 warn("Option 'tig.%s': %s", name, option_errors[error]);
6598 }
6600 static bool
6601 set_environment_variable(const char *name, const char *value)
6602 {
6603 size_t len = strlen(name) + 1 + strlen(value) + 1;
6604 char *env = malloc(len);
6606 if (env &&
6607 string_nformat(env, len, NULL, "%s=%s", name, value) &&
6608 putenv(env) == 0)
6609 return TRUE;
6610 free(env);
6611 return FALSE;
6612 }
6614 static void
6615 set_work_tree(const char *value)
6616 {
6617 char cwd[SIZEOF_STR];
6619 if (!getcwd(cwd, sizeof(cwd)))
6620 die("Failed to get cwd path: %s", strerror(errno));
6621 if (chdir(opt_git_dir) < 0)
6622 die("Failed to chdir(%s): %s", strerror(errno));
6623 if (!getcwd(opt_git_dir, sizeof(opt_git_dir)))
6624 die("Failed to get git path: %s", strerror(errno));
6625 if (chdir(cwd) < 0)
6626 die("Failed to chdir(%s): %s", cwd, strerror(errno));
6627 if (chdir(value) < 0)
6628 die("Failed to chdir(%s): %s", value, strerror(errno));
6629 if (!getcwd(cwd, sizeof(cwd)))
6630 die("Failed to get cwd path: %s", strerror(errno));
6631 if (!set_environment_variable("GIT_WORK_TREE", cwd))
6632 die("Failed to set GIT_WORK_TREE to '%s'", cwd);
6633 if (!set_environment_variable("GIT_DIR", opt_git_dir))
6634 die("Failed to set GIT_DIR to '%s'", opt_git_dir);
6635 opt_is_inside_work_tree = TRUE;
6636 }
6638 static int
6639 read_repo_config_option(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6640 {
6641 if (!strcmp(name, "i18n.commitencoding"))
6642 string_ncopy(opt_encoding, value, valuelen);
6644 else if (!strcmp(name, "core.editor"))
6645 string_ncopy(opt_editor, value, valuelen);
6647 else if (!strcmp(name, "core.worktree"))
6648 set_work_tree(value);
6650 else if (!prefixcmp(name, "tig.color."))
6651 set_repo_config_option(name + 10, value, option_color_command);
6653 else if (!prefixcmp(name, "tig.bind."))
6654 set_repo_config_option(name + 9, value, option_bind_command);
6656 else if (!prefixcmp(name, "tig."))
6657 set_repo_config_option(name + 4, value, option_set_command);
6659 else if (*opt_head && !prefixcmp(name, "branch.") &&
6660 !strncmp(name + 7, opt_head, strlen(opt_head)))
6661 set_remote_branch(name + 7 + strlen(opt_head), value, valuelen);
6663 return OK;
6664 }
6666 static int
6667 load_git_config(void)
6668 {
6669 const char *config_list_argv[] = { "git", "config", "--list", NULL };
6671 return io_run_load(config_list_argv, "=", read_repo_config_option, NULL);
6672 }
6674 static int
6675 read_repo_info(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6676 {
6677 if (!opt_git_dir[0]) {
6678 string_ncopy(opt_git_dir, name, namelen);
6680 } else if (opt_is_inside_work_tree == -1) {
6681 /* This can be 3 different values depending on the
6682 * version of git being used. If git-rev-parse does not
6683 * understand --is-inside-work-tree it will simply echo
6684 * the option else either "true" or "false" is printed.
6685 * Default to true for the unknown case. */
6686 opt_is_inside_work_tree = strcmp(name, "false") ? TRUE : FALSE;
6688 } else if (*name == '.') {
6689 string_ncopy(opt_cdup, name, namelen);
6691 } else {
6692 string_ncopy(opt_prefix, name, namelen);
6693 }
6695 return OK;
6696 }
6698 static int
6699 load_repo_info(void)
6700 {
6701 const char *rev_parse_argv[] = {
6702 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
6703 "--show-cdup", "--show-prefix", NULL
6704 };
6706 return io_run_load(rev_parse_argv, "=", read_repo_info, NULL);
6707 }
6710 /*
6711 * Main
6712 */
6714 static const char usage[] =
6715 "tig " TIG_VERSION " (" __DATE__ ")\n"
6716 "\n"
6717 "Usage: tig [options] [revs] [--] [paths]\n"
6718 " or: tig show [options] [revs] [--] [paths]\n"
6719 " or: tig blame [options] [rev] [--] path\n"
6720 " or: tig status\n"
6721 " or: tig < [git command output]\n"
6722 "\n"
6723 "Options:\n"
6724 " -v, --version Show version and exit\n"
6725 " -h, --help Show help message and exit";
6727 static void __NORETURN
6728 quit(int sig)
6729 {
6730 /* XXX: Restore tty modes and let the OS cleanup the rest! */
6731 if (cursed)
6732 endwin();
6733 exit(0);
6734 }
6736 static void __NORETURN
6737 die(const char *err, ...)
6738 {
6739 va_list args;
6741 endwin();
6743 va_start(args, err);
6744 fputs("tig: ", stderr);
6745 vfprintf(stderr, err, args);
6746 fputs("\n", stderr);
6747 va_end(args);
6749 exit(1);
6750 }
6752 static void
6753 warn(const char *msg, ...)
6754 {
6755 va_list args;
6757 va_start(args, msg);
6758 fputs("tig warning: ", stderr);
6759 vfprintf(stderr, msg, args);
6760 fputs("\n", stderr);
6761 va_end(args);
6762 }
6764 static int
6765 read_filter_args(char *name, size_t namelen, char *value, size_t valuelen, void *data)
6766 {
6767 const char ***filter_args = data;
6769 return argv_append(filter_args, name) ? OK : ERR;
6770 }
6772 static void
6773 filter_rev_parse(const char ***args, const char *arg1, const char *arg2, const char *argv[])
6774 {
6775 const char *rev_parse_argv[SIZEOF_ARG] = { "git", "rev-parse", arg1, arg2 };
6776 const char **all_argv = NULL;
6778 if (!argv_append_array(&all_argv, rev_parse_argv) ||
6779 !argv_append_array(&all_argv, argv) ||
6780 !io_run_load(all_argv, "\n", read_filter_args, args) == ERR)
6781 die("Failed to split arguments");
6782 argv_free(all_argv);
6783 free(all_argv);
6784 }
6786 static void
6787 filter_options(const char *argv[])
6788 {
6789 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv);
6790 filter_rev_parse(&opt_diff_argv, "--no-revs", "--flags", argv);
6791 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv);
6792 }
6794 static enum request
6795 parse_options(int argc, const char *argv[])
6796 {
6797 enum request request = REQ_VIEW_MAIN;
6798 const char *subcommand;
6799 bool seen_dashdash = FALSE;
6800 const char **filter_argv = NULL;
6801 int i;
6803 if (!isatty(STDIN_FILENO))
6804 return REQ_VIEW_PAGER;
6806 if (argc <= 1)
6807 return REQ_VIEW_MAIN;
6809 subcommand = argv[1];
6810 if (!strcmp(subcommand, "status")) {
6811 if (argc > 2)
6812 warn("ignoring arguments after `%s'", subcommand);
6813 return REQ_VIEW_STATUS;
6815 } else if (!strcmp(subcommand, "blame")) {
6816 filter_rev_parse(&opt_file_argv, "--no-revs", "--no-flags", argv + 2);
6817 filter_rev_parse(&opt_blame_argv, "--no-revs", "--flags", argv + 2);
6818 filter_rev_parse(&opt_rev_argv, "--symbolic", "--revs-only", argv + 2);
6820 if (!opt_file_argv || opt_file_argv[1] || (opt_rev_argv && opt_rev_argv[1]))
6821 die("invalid number of options to blame\n\n%s", usage);
6823 if (opt_rev_argv) {
6824 string_ncopy(opt_ref, opt_rev_argv[0], strlen(opt_rev_argv[0]));
6825 }
6827 string_ncopy(opt_file, opt_file_argv[0], strlen(opt_file_argv[0]));
6828 return REQ_VIEW_BLAME;
6830 } else if (!strcmp(subcommand, "show")) {
6831 request = REQ_VIEW_DIFF;
6833 } else {
6834 subcommand = NULL;
6835 }
6837 for (i = 1 + !!subcommand; i < argc; i++) {
6838 const char *opt = argv[i];
6840 if (seen_dashdash) {
6841 argv_append(&opt_file_argv, opt);
6842 continue;
6844 } else if (!strcmp(opt, "--")) {
6845 seen_dashdash = TRUE;
6846 continue;
6848 } else if (!strcmp(opt, "-v") || !strcmp(opt, "--version")) {
6849 printf("tig version %s\n", TIG_VERSION);
6850 quit(0);
6852 } else if (!strcmp(opt, "-h") || !strcmp(opt, "--help")) {
6853 printf("%s\n", usage);
6854 quit(0);
6856 } else if (!strcmp(opt, "--all")) {
6857 argv_append(&opt_rev_argv, opt);
6858 continue;
6859 }
6861 if (!argv_append(&filter_argv, opt))
6862 die("command too long");
6863 }
6865 if (filter_argv)
6866 filter_options(filter_argv);
6868 return request;
6869 }
6871 int
6872 main(int argc, const char *argv[])
6873 {
6874 const char *codeset = "UTF-8";
6875 enum request request = parse_options(argc, argv);
6876 struct view *view;
6877 size_t i;
6879 signal(SIGINT, quit);
6880 signal(SIGPIPE, SIG_IGN);
6882 if (setlocale(LC_ALL, "")) {
6883 codeset = nl_langinfo(CODESET);
6884 }
6886 if (load_repo_info() == ERR)
6887 die("Failed to load repo info.");
6889 if (load_options() == ERR)
6890 die("Failed to load user config.");
6892 if (load_git_config() == ERR)
6893 die("Failed to load repo config.");
6895 /* Require a git repository unless when running in pager mode. */
6896 if (!opt_git_dir[0] && request != REQ_VIEW_PAGER)
6897 die("Not a git repository");
6899 if (*opt_encoding && strcmp(codeset, "UTF-8")) {
6900 opt_iconv_in = iconv_open("UTF-8", opt_encoding);
6901 if (opt_iconv_in == ICONV_NONE)
6902 die("Failed to initialize character set conversion");
6903 }
6905 if (codeset && strcmp(codeset, "UTF-8")) {
6906 opt_iconv_out = iconv_open(codeset, "UTF-8");
6907 if (opt_iconv_out == ICONV_NONE)
6908 die("Failed to initialize character set conversion");
6909 }
6911 if (load_refs() == ERR)
6912 die("Failed to load refs.");
6914 foreach_view (view, i) {
6915 if (getenv(view->cmd_env))
6916 warn("Use of the %s environment variable is deprecated,"
6917 " use options or TIG_DIFF_ARGS instead",
6918 view->cmd_env);
6919 if (!argv_from_env(view->ops->argv, view->cmd_env))
6920 die("Too many arguments in the `%s` environment variable",
6921 view->cmd_env);
6922 }
6924 init_display();
6926 while (view_driver(display[current_view], request)) {
6927 int key = get_input(0);
6929 view = display[current_view];
6930 request = get_keybinding(view->keymap, key);
6932 /* Some low-level request handling. This keeps access to
6933 * status_win restricted. */
6934 switch (request) {
6935 case REQ_NONE:
6936 report("Unknown key, press %s for help",
6937 get_key(view->keymap, REQ_VIEW_HELP));
6938 break;
6939 case REQ_PROMPT:
6940 {
6941 char *cmd = read_prompt(":");
6943 if (cmd && isdigit(*cmd)) {
6944 int lineno = view->lineno + 1;
6946 if (parse_int(&lineno, cmd, 1, view->lines + 1) == OK) {
6947 select_view_line(view, lineno - 1);
6948 report("");
6949 } else {
6950 report("Unable to parse '%s' as a line number", cmd);
6951 }
6953 } else if (cmd) {
6954 struct view *next = VIEW(REQ_VIEW_PAGER);
6955 const char *argv[SIZEOF_ARG] = { "git" };
6956 int argc = 1;
6958 /* When running random commands, initially show the
6959 * command in the title. However, it maybe later be
6960 * overwritten if a commit line is selected. */
6961 string_ncopy(next->ref, cmd, strlen(cmd));
6963 if (!argv_from_string(argv, &argc, cmd)) {
6964 report("Too many arguments");
6965 } else if (!prepare_update(next, argv, NULL)) {
6966 report("Failed to format command");
6967 } else {
6968 open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED);
6969 }
6970 }
6972 request = REQ_NONE;
6973 break;
6974 }
6975 case REQ_SEARCH:
6976 case REQ_SEARCH_BACK:
6977 {
6978 const char *prompt = request == REQ_SEARCH ? "/" : "?";
6979 char *search = read_prompt(prompt);
6981 if (search)
6982 string_ncopy(opt_search, search, strlen(search));
6983 else if (*opt_search)
6984 request = request == REQ_SEARCH ?
6985 REQ_FIND_NEXT :
6986 REQ_FIND_PREV;
6987 else
6988 request = REQ_NONE;
6989 break;
6990 }
6991 default:
6992 break;
6993 }
6994 }
6996 quit(0);
6998 return 0;
6999 }