1 /* Copyright (c) 2006-2010 Jonas Fonseca <fonseca@diku.dk>
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU General Public License as
5 * published by the Free Software Foundation; either version 2 of
6 * the License, or (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
19 #define TIG_VERSION "unknown-version"
34 #include <sys/types.h>
37 #include <sys/select.h>
49 /* ncurses(3): Must be defined to have extended wide-character functions. */
50 #define _XOPEN_SOURCE_EXTENDED
52 #ifdef HAVE_NCURSESW_NCURSES_H
53 #include <ncursesw/ncurses.h>
55 #ifdef HAVE_NCURSES_NCURSES_H
56 #include <ncurses/ncurses.h>
63 #define __NORETURN __attribute__((__noreturn__))
68 static void __NORETURN
die(const char *err
, ...);
69 static void warn(const char *msg
, ...);
70 static void report(const char *msg
, ...);
71 static void set_nonblocking_input(bool loading
);
72 static size_t utf8_length(const char **start
, size_t skip
, int *width
, size_t max_width
, int *trimmed
, bool reserve
, int tab_size
);
73 static inline unsigned char utf8_char_length(const char *string
, const char *end
);
75 #define ABS(x) ((x) >= 0 ? (x) : -(x))
76 #define MIN(x, y) ((x) < (y) ? (x) : (y))
77 #define MAX(x, y) ((x) > (y) ? (x) : (y))
79 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
80 #define STRING_SIZE(x) (sizeof(x) - 1)
82 #define SIZEOF_STR 1024 /* Default string size. */
83 #define SIZEOF_REF 256 /* Size of symbolic or SHA1 ID. */
84 #define SIZEOF_REV 41 /* Holds a SHA-1 and an ending NUL. */
85 #define SIZEOF_ARG 32 /* Default argument array size. */
89 #define REVGRAPH_INIT 'I'
90 #define REVGRAPH_MERGE 'M'
91 #define REVGRAPH_BRANCH '+'
92 #define REVGRAPH_COMMIT '*'
93 #define REVGRAPH_BOUND '^'
95 #define SIZEOF_REVGRAPH 19 /* Size of revision ancestry graphics. */
97 /* This color name can be used to refer to the default term colors. */
98 #define COLOR_DEFAULT (-1)
100 #define ICONV_NONE ((iconv_t) -1)
102 #define ICONV_CONST /* nothing */
105 /* The format and size of the date column in the main view. */
106 #define DATE_FORMAT "%Y-%m-%d %H:%M"
107 #define DATE_COLS STRING_SIZE("2006-04-29 14:21 ")
108 #define DATE_SHORT_COLS STRING_SIZE("2006-04-29 ")
111 #define AUTHOR_COLS 19
113 #define MIN_VIEW_HEIGHT 4
115 #define NULL_ID "0000000000000000000000000000000000000000"
117 #define S_ISGITLINK(mode) (((mode) & S_IFMT) == 0160000)
119 /* Some ASCII-shorthands fitted into the ncurses namespace. */
121 #define KEY_RETURN '\r'
126 char id
[SIZEOF_REV
]; /* Commit SHA1 ID */
127 unsigned int head
:1; /* Is it the current HEAD? */
128 unsigned int tag
:1; /* Is it a tag? */
129 unsigned int ltag
:1; /* If so, is the tag local? */
130 unsigned int remote
:1; /* Is it a remote ref? */
131 unsigned int tracked
:1; /* Is it the remote for the current HEAD? */
132 char name
[1]; /* Ref name; tag or head names are shortened. */
136 char id
[SIZEOF_REV
]; /* Commit SHA1 ID */
137 size_t size
; /* Number of refs. */
138 struct ref
**refs
; /* References for this ID. */
141 static struct ref_list
*get_ref_list(const char *id
);
142 static void foreach_ref(bool (*visitor
)(void *data
, const struct ref
*ref
), void *data
);
143 static int load_refs(void);
146 FORMAT_ALL
, /* Perform replacement in all arguments. */
147 FORMAT_DASH
, /* Perform replacement up until "--". */
148 FORMAT_NONE
/* No replacement should be performed. */
151 static bool format_argv(const char *dst
[], const char *src
[], enum format_flags flags
);
160 typedef enum input_status (*input_handler
)(void *data
, char *buf
, int c
);
162 static char *prompt_input(const char *prompt
, input_handler handler
, void *data
);
163 static bool prompt_yesno(const char *prompt
);
171 static bool prompt_menu(const char *prompt
, const struct menu_item
*items
, int *selected
);
174 * Allocation helpers ... Entering macro hell to never be seen again.
177 #define DEFINE_ALLOCATOR(name, type, chunk_size) \
179 name(type **mem, size_t size, size_t increase) \
181 size_t num_chunks = (size + chunk_size - 1) / chunk_size; \
182 size_t num_chunks_new = (size + increase + chunk_size - 1) / chunk_size;\
185 if (mem == NULL || num_chunks != num_chunks_new) { \
186 tmp = realloc(tmp, num_chunks_new * chunk_size * sizeof(type)); \
199 string_ncopy_do(char *dst
, size_t dstlen
, const char *src
, size_t srclen
)
201 if (srclen
> dstlen
- 1)
204 strncpy(dst
, src
, srclen
);
208 /* Shorthands for safely copying into a fixed buffer. */
210 #define string_copy(dst, src) \
211 string_ncopy_do(dst, sizeof(dst), src, sizeof(src))
213 #define string_ncopy(dst, src, srclen) \
214 string_ncopy_do(dst, sizeof(dst), src, srclen)
216 #define string_copy_rev(dst, src) \
217 string_ncopy_do(dst, SIZEOF_REV, src, SIZEOF_REV - 1)
219 #define string_add(dst, from, src) \
220 string_ncopy_do(dst + (from), sizeof(dst) - (from), src, sizeof(src))
223 string_expand(char *dst
, size_t dstlen
, const char *src
, int tabsize
)
227 for (size
= pos
= 0; size
< dstlen
- 1 && src
[pos
]; pos
++) {
228 if (src
[pos
] == '\t') {
229 size_t expanded
= tabsize
- (size
% tabsize
);
231 if (expanded
+ size
>= dstlen
- 1)
232 expanded
= dstlen
- size
- 1;
233 memcpy(dst
+ size
, " ", expanded
);
236 dst
[size
++] = src
[pos
];
244 chomp_string(char *name
)
248 while (isspace(*name
))
251 namelen
= strlen(name
) - 1;
252 while (namelen
> 0 && isspace(name
[namelen
]))
259 string_nformat(char *buf
, size_t bufsize
, size_t *bufpos
, const char *fmt
, ...)
262 size_t pos
= bufpos
? *bufpos
: 0;
265 pos
+= vsnprintf(buf
+ pos
, bufsize
- pos
, fmt
, args
);
271 return pos
>= bufsize
? FALSE
: TRUE
;
274 #define string_format(buf, fmt, args...) \
275 string_nformat(buf, sizeof(buf), NULL, fmt, args)
277 #define string_format_from(buf, from, fmt, args...) \
278 string_nformat(buf, sizeof(buf), from, fmt, args)
281 string_enum_compare(const char *str1
, const char *str2
, int len
)
285 #define string_enum_sep(x) ((x) == '-' || (x) == '_' || (x) == '.')
287 /* Diff-Header == DIFF_HEADER */
288 for (i
= 0; i
< len
; i
++) {
289 if (toupper(str1
[i
]) == toupper(str2
[i
]))
292 if (string_enum_sep(str1
[i
]) &&
293 string_enum_sep(str2
[i
]))
296 return str1
[i
] - str2
[i
];
302 #define enum_equals(entry, str, len) \
303 ((entry).namelen == (len) && !string_enum_compare((entry).name, str, len))
311 #define ENUM_MAP(name, value) { name, STRING_SIZE(name), value }
314 enum_map_name(const char *name
, size_t namelen
)
316 static char buf
[SIZEOF_STR
];
319 for (bufpos
= 0; bufpos
<= namelen
; bufpos
++) {
320 buf
[bufpos
] = tolower(name
[bufpos
]);
321 if (buf
[bufpos
] == '_')
329 #define enum_name(entry) enum_map_name((entry).name, (entry).namelen)
332 map_enum_do(const struct enum_map
*map
, size_t map_size
, int *value
, const char *name
)
334 size_t namelen
= strlen(name
);
337 for (i
= 0; i
< map_size
; i
++)
338 if (enum_equals(map
[i
], name
, namelen
)) {
339 *value
= map
[i
].value
;
346 #define map_enum(attr, map, name) \
347 map_enum_do(map, ARRAY_SIZE(map), attr, name)
349 #define prefixcmp(str1, str2) \
350 strncmp(str1, str2, STRING_SIZE(str2))
353 suffixcmp(const char *str
, int slen
, const char *suffix
)
355 size_t len
= slen
>= 0 ? slen
: strlen(str
);
356 size_t suffixlen
= strlen(suffix
);
358 return suffixlen
< len
? strcmp(str
+ len
- suffixlen
, suffix
) : -1;
369 #define DATE_(name) DATE_##name
374 static const struct enum_map date_map
[] = {
375 #define DATE_(name) ENUM_MAP(#name, DATE_##name)
385 static inline int timecmp(const struct time
*t1
, const struct time
*t2
)
387 return t1
->sec
- t2
->sec
;
391 string_date(const struct time
*time
, enum date date
)
393 static char buf
[DATE_COLS
+ 1];
394 static const struct enum_map reldate
[] = {
395 { "second", 1, 60 * 2 },
396 { "minute", 60, 60 * 60 * 2 },
397 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
398 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
399 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
400 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 30 * 12 },
404 if (date
== DATE_RELATIVE
) {
406 time_t date
= time
->sec
+ time
->tz
;
410 gettimeofday(&now
, NULL
);
411 seconds
= now
.tv_sec
< date
? date
- now
.tv_sec
: now
.tv_sec
- date
;
412 for (i
= 0; i
< ARRAY_SIZE(reldate
); i
++) {
413 if (seconds
>= reldate
[i
].value
)
416 seconds
/= reldate
[i
].namelen
;
417 if (!string_format(buf
, "%ld %s%s %s",
418 seconds
, reldate
[i
].name
,
419 seconds
> 1 ? "s" : "",
420 now
.tv_sec
>= date
? "ago" : "ahead"))
426 gmtime_r(&time
->sec
, &tm
);
427 return strftime(buf
, sizeof(buf
), DATE_FORMAT
, &tm
) ? buf
: NULL
;
431 #define AUTHOR_VALUES \
437 #define AUTHOR_(name) AUTHOR_##name
440 AUTHOR_DEFAULT
= AUTHOR_FULL
443 static const struct enum_map author_map
[] = {
444 #define AUTHOR_(name) ENUM_MAP(#name, AUTHOR_##name)
450 get_author_initials(const char *author
)
452 static char initials
[AUTHOR_COLS
* 6 + 1];
454 const char *end
= strchr(author
, '\0');
456 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
458 memset(initials
, 0, sizeof(initials
));
459 while (author
< end
) {
463 while (is_initial_sep(*author
))
466 bytes
= utf8_char_length(author
, end
);
467 if (bytes
< sizeof(initials
) - 1 - pos
) {
469 initials
[pos
++] = *author
++;
473 for (i
= pos
; author
< end
&& !is_initial_sep(*author
); author
++) {
474 if (i
< sizeof(initials
) - 1)
475 initials
[i
++] = *author
;
486 argv_from_string(const char *argv
[SIZEOF_ARG
], int *argc
, char *cmd
)
490 while (*cmd
&& *argc
< SIZEOF_ARG
&& (valuelen
= strcspn(cmd
, " \t"))) {
491 bool advance
= cmd
[valuelen
] != 0;
494 argv
[(*argc
)++] = chomp_string(cmd
);
495 cmd
= chomp_string(cmd
+ valuelen
+ advance
);
498 if (*argc
< SIZEOF_ARG
)
500 return *argc
< SIZEOF_ARG
;
504 argv_from_env(const char **argv
, const char *name
)
506 char *env
= argv
? getenv(name
) : NULL
;
511 if (env
&& !argv_from_string(argv
, &argc
, env
))
512 die("Too many arguments in the `%s` environment variable", name
);
517 * Executing external commands.
521 IO_FD
, /* File descriptor based IO. */
522 IO_BG
, /* Execute command in the background. */
523 IO_FG
, /* Execute command with same std{in,out,err}. */
524 IO_RD
, /* Read only fork+exec IO. */
525 IO_WR
, /* Write only fork+exec IO. */
526 IO_AP
, /* Append fork+exec output to file. */
530 enum io_type type
; /* The requested type of pipe. */
531 const char *dir
; /* Directory from which to execute. */
532 pid_t pid
; /* Pipe for reading or writing. */
533 int pipe
; /* Pipe end for reading or writing. */
534 int error
; /* Error status. */
535 const char *argv
[SIZEOF_ARG
]; /* Shell command arguments. */
536 char *buf
; /* Read buffer. */
537 size_t bufalloc
; /* Allocated buffer size. */
538 size_t bufsize
; /* Buffer content size. */
539 char *bufpos
; /* Current buffer position. */
540 unsigned int eof
:1; /* Has end of file been reached. */
544 reset_io(struct io
*io
)
548 io
->buf
= io
->bufpos
= NULL
;
549 io
->bufalloc
= io
->bufsize
= 0;
555 init_io(struct io
*io
, const char *dir
, enum io_type type
)
563 init_io_rd(struct io
*io
, const char *argv
[], const char *dir
,
564 enum format_flags flags
)
566 init_io(io
, dir
, IO_RD
);
567 return format_argv(io
->argv
, argv
, flags
);
571 io_open(struct io
*io
, const char *fmt
, ...)
573 char name
[SIZEOF_STR
] = "";
577 init_io(io
, NULL
, IO_FD
);
580 fits
= vsnprintf(name
, sizeof(name
), fmt
, args
) < sizeof(name
);
584 io
->error
= ENAMETOOLONG
;
587 io
->pipe
= *name
? open(name
, O_RDONLY
) : STDIN_FILENO
;
590 return io
->pipe
!= -1;
594 kill_io(struct io
*io
)
596 return io
->pid
== 0 || kill(io
->pid
, SIGKILL
) != -1;
600 done_io(struct io
*io
)
611 pid_t waiting
= waitpid(pid
, &status
, 0);
616 report("waitpid failed (%s)", strerror(errno
));
620 return waiting
== pid
&&
621 !WIFSIGNALED(status
) &&
623 !WEXITSTATUS(status
);
630 start_io(struct io
*io
)
632 int pipefds
[2] = { -1, -1 };
634 if (io
->type
== IO_FD
)
637 if ((io
->type
== IO_RD
|| io
->type
== IO_WR
) &&
640 else if (io
->type
== IO_AP
)
641 pipefds
[1] = io
->pipe
;
643 if ((io
->pid
= fork())) {
644 if (pipefds
[!(io
->type
== IO_WR
)] != -1)
645 close(pipefds
[!(io
->type
== IO_WR
)]);
647 io
->pipe
= pipefds
[!!(io
->type
== IO_WR
)];
652 if (io
->type
!= IO_FG
) {
653 int devnull
= open("/dev/null", O_RDWR
);
654 int readfd
= io
->type
== IO_WR
? pipefds
[0] : devnull
;
655 int writefd
= (io
->type
== IO_RD
|| io
->type
== IO_AP
)
656 ? pipefds
[1] : devnull
;
658 dup2(readfd
, STDIN_FILENO
);
659 dup2(writefd
, STDOUT_FILENO
);
660 dup2(devnull
, STDERR_FILENO
);
663 if (pipefds
[0] != -1)
665 if (pipefds
[1] != -1)
669 if (io
->dir
&& *io
->dir
&& chdir(io
->dir
) == -1)
670 die("Failed to change directory: %s", strerror(errno
));
672 execvp(io
->argv
[0], (char *const*) io
->argv
);
673 die("Failed to execute program: %s", strerror(errno
));
676 if (pipefds
[!!(io
->type
== IO_WR
)] != -1)
677 close(pipefds
[!!(io
->type
== IO_WR
)]);
682 run_io(struct io
*io
, const char **argv
, const char *dir
, enum io_type type
)
684 init_io(io
, dir
, type
);
685 if (!format_argv(io
->argv
, argv
, FORMAT_NONE
))
691 run_io_do(struct io
*io
)
693 return start_io(io
) && done_io(io
);
697 run_io_bg(const char **argv
)
701 init_io(&io
, NULL
, IO_BG
);
702 if (!format_argv(io
.argv
, argv
, FORMAT_NONE
))
704 return run_io_do(&io
);
708 run_io_fg(const char **argv
, const char *dir
)
712 init_io(&io
, dir
, IO_FG
);
713 if (!format_argv(io
.argv
, argv
, FORMAT_NONE
))
715 return run_io_do(&io
);
719 run_io_append(const char **argv
, enum format_flags flags
, int fd
)
723 init_io(&io
, NULL
, IO_AP
);
725 if (format_argv(io
.argv
, argv
, flags
))
726 return run_io_do(&io
);
732 run_io_rd(struct io
*io
, const char **argv
, const char *dir
, enum format_flags flags
)
734 return init_io_rd(io
, argv
, dir
, flags
) && start_io(io
);
738 io_eof(struct io
*io
)
744 io_error(struct io
*io
)
750 io_strerror(struct io
*io
)
752 return strerror(io
->error
);
756 io_can_read(struct io
*io
)
758 struct timeval tv
= { 0, 500 };
762 FD_SET(io
->pipe
, &fds
);
764 return select(io
->pipe
+ 1, &fds
, NULL
, NULL
, &tv
) > 0;
768 io_read(struct io
*io
, void *buf
, size_t bufsize
)
771 ssize_t readsize
= read(io
->pipe
, buf
, bufsize
);
773 if (readsize
< 0 && (errno
== EAGAIN
|| errno
== EINTR
))
775 else if (readsize
== -1)
777 else if (readsize
== 0)
783 DEFINE_ALLOCATOR(realloc_io_buf
, char, BUFSIZ
)
786 io_get(struct io
*io
, int c
, bool can_read
)
792 if (io
->bufsize
> 0) {
793 eol
= memchr(io
->bufpos
, c
, io
->bufsize
);
795 char *line
= io
->bufpos
;
798 io
->bufpos
= eol
+ 1;
799 io
->bufsize
-= io
->bufpos
- line
;
806 io
->bufpos
[io
->bufsize
] = 0;
816 if (io
->bufsize
> 0 && io
->bufpos
> io
->buf
)
817 memmove(io
->buf
, io
->bufpos
, io
->bufsize
);
819 if (io
->bufalloc
== io
->bufsize
) {
820 if (!realloc_io_buf(&io
->buf
, io
->bufalloc
, BUFSIZ
))
822 io
->bufalloc
+= BUFSIZ
;
825 io
->bufpos
= io
->buf
;
826 readsize
= io_read(io
, io
->buf
+ io
->bufsize
, io
->bufalloc
- io
->bufsize
);
829 io
->bufsize
+= readsize
;
834 io_write(struct io
*io
, const void *buf
, size_t bufsize
)
838 while (!io_error(io
) && written
< bufsize
) {
841 size
= write(io
->pipe
, buf
+ written
, bufsize
- written
);
842 if (size
< 0 && (errno
== EAGAIN
|| errno
== EINTR
))
850 return written
== bufsize
;
854 io_read_buf(struct io
*io
, char buf
[], size_t bufsize
)
856 char *result
= io_get(io
, '\n', TRUE
);
859 result
= chomp_string(result
);
860 string_ncopy_do(buf
, bufsize
, result
, strlen(result
));
863 return done_io(io
) && result
;
867 run_io_buf(const char **argv
, char buf
[], size_t bufsize
)
871 return run_io_rd(&io
, argv
, NULL
, FORMAT_NONE
)
872 && io_read_buf(&io
, buf
, bufsize
);
876 io_load(struct io
*io
, const char *separators
,
877 int (*read_property
)(char *, size_t, char *, size_t))
885 while (state
== OK
&& (name
= io_get(io
, '\n', TRUE
))) {
890 name
= chomp_string(name
);
891 namelen
= strcspn(name
, separators
);
895 value
= chomp_string(name
+ namelen
+ 1);
896 valuelen
= strlen(value
);
903 state
= read_property(name
, namelen
, value
, valuelen
);
906 if (state
!= ERR
&& io_error(io
))
914 run_io_load(const char **argv
, const char *separators
,
915 int (*read_property
)(char *, size_t, char *, size_t))
919 return init_io_rd(&io
, argv
, NULL
, FORMAT_NONE
)
920 ? io_load(&io
, separators
, read_property
) : ERR
;
929 /* XXX: Keep the view request first and in sync with views[]. */ \
930 REQ_GROUP("View switching") \
931 REQ_(VIEW_MAIN, "Show main view"), \
932 REQ_(VIEW_DIFF, "Show diff view"), \
933 REQ_(VIEW_LOG, "Show log view"), \
934 REQ_(VIEW_TREE, "Show tree view"), \
935 REQ_(VIEW_BLOB, "Show blob view"), \
936 REQ_(VIEW_BLAME, "Show blame view"), \
937 REQ_(VIEW_BRANCH, "Show branch view"), \
938 REQ_(VIEW_HELP, "Show help page"), \
939 REQ_(VIEW_PAGER, "Show pager view"), \
940 REQ_(VIEW_STATUS, "Show status view"), \
941 REQ_(VIEW_STAGE, "Show stage view"), \
943 REQ_GROUP("View manipulation") \
944 REQ_(ENTER, "Enter current line and scroll"), \
945 REQ_(NEXT, "Move to next"), \
946 REQ_(PREVIOUS, "Move to previous"), \
947 REQ_(PARENT, "Move to parent"), \
948 REQ_(VIEW_NEXT, "Move focus to next view"), \
949 REQ_(REFRESH, "Reload and refresh"), \
950 REQ_(MAXIMIZE, "Maximize the current view"), \
951 REQ_(VIEW_CLOSE, "Close the current view"), \
952 REQ_(QUIT, "Close all views and quit"), \
954 REQ_GROUP("View specific requests") \
955 REQ_(STATUS_UPDATE, "Update file status"), \
956 REQ_(STATUS_REVERT, "Revert file changes"), \
957 REQ_(STATUS_MERGE, "Merge file using external tool"), \
958 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
960 REQ_GROUP("Cursor navigation") \
961 REQ_(MOVE_UP, "Move cursor one line up"), \
962 REQ_(MOVE_DOWN, "Move cursor one line down"), \
963 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
964 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
965 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
966 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
968 REQ_GROUP("Scrolling") \
969 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
970 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
971 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
972 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
973 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
974 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
976 REQ_GROUP("Searching") \
977 REQ_(SEARCH, "Search the view"), \
978 REQ_(SEARCH_BACK, "Search backwards in the view"), \
979 REQ_(FIND_NEXT, "Find next search match"), \
980 REQ_(FIND_PREV, "Find previous search match"), \
982 REQ_GROUP("Option manipulation") \
983 REQ_(OPTIONS, "Open option menu"), \
984 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
985 REQ_(TOGGLE_DATE, "Toggle date display"), \
986 REQ_(TOGGLE_DATE_SHORT, "Toggle short (date-only) dates"), \
987 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
988 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
989 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
990 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
991 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
994 REQ_(PROMPT, "Bring up the prompt"), \
995 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
996 REQ_(SHOW_VERSION, "Show version information"), \
997 REQ_(STOP_LOADING, "Stop all loading views"), \
998 REQ_(EDIT, "Open in editor"), \
999 REQ_(NONE, "Do nothing")
1002 /* User action requests. */
1004 #define REQ_GROUP(help)
1005 #define REQ_(req, help) REQ_##req
1007 /* Offset all requests to avoid conflicts with ncurses getch values. */
1008 REQ_OFFSET
= KEY_MAX
+ 1,
1015 struct request_info
{
1016 enum request request
;
1022 static const struct request_info req_info
[] = {
1023 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
1024 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
1031 get_request(const char *name
)
1033 int namelen
= strlen(name
);
1036 for (i
= 0; i
< ARRAY_SIZE(req_info
); i
++)
1037 if (enum_equals(req_info
[i
], name
, namelen
))
1038 return req_info
[i
].request
;
1048 /* Option and state variables. */
1049 static enum date opt_date
= DATE_DEFAULT
;
1050 static enum author opt_author
= AUTHOR_DEFAULT
;
1051 static bool opt_line_number
= FALSE
;
1052 static bool opt_line_graphics
= TRUE
;
1053 static bool opt_rev_graph
= FALSE
;
1054 static bool opt_show_refs
= TRUE
;
1055 static int opt_num_interval
= 5;
1056 static double opt_hscroll
= 0.50;
1057 static double opt_scale_split_view
= 2.0 / 3.0;
1058 static int opt_tab_size
= 8;
1059 static int opt_author_cols
= AUTHOR_COLS
;
1060 static char opt_path
[SIZEOF_STR
] = "";
1061 static char opt_file
[SIZEOF_STR
] = "";
1062 static char opt_ref
[SIZEOF_REF
] = "";
1063 static char opt_head
[SIZEOF_REF
] = "";
1064 static char opt_head_rev
[SIZEOF_REV
] = "";
1065 static char opt_remote
[SIZEOF_REF
] = "";
1066 static char opt_encoding
[20] = "UTF-8";
1067 static iconv_t opt_iconv_in
= ICONV_NONE
;
1068 static iconv_t opt_iconv_out
= ICONV_NONE
;
1069 static char opt_search
[SIZEOF_STR
] = "";
1070 static char opt_cdup
[SIZEOF_STR
] = "";
1071 static char opt_prefix
[SIZEOF_STR
] = "";
1072 static char opt_git_dir
[SIZEOF_STR
] = "";
1073 static signed char opt_is_inside_work_tree
= -1; /* set to TRUE or FALSE */
1074 static char opt_editor
[SIZEOF_STR
] = "";
1075 static FILE *opt_tty
= NULL
;
1077 #define is_initial_commit() (!*opt_head_rev)
1078 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || !strcmp(opt_head_rev, (rev)))
1079 #define mkdate(time) string_date(time, opt_date)
1083 * Line-oriented content detection.
1087 LINE(DIFF_HEADER, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1088 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1089 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
1090 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
1091 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
1092 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1093 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1094 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1095 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1096 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1097 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1098 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1099 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1100 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
1101 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
1102 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1103 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
1104 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1105 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1106 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1107 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
1108 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
1109 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
1110 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
1111 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
1112 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1113 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1114 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1115 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
1116 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
1117 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
1118 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1119 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
1120 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
1121 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
1122 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
1123 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
1124 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
1125 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
1126 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1127 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1128 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
1129 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
1130 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
1131 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1132 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
1133 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
1134 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
1135 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1136 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
1137 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
1138 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1139 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1140 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1141 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
1142 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
1143 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0)
1146 #define LINE(type, line, fg, bg, attr) \
1154 const char *name
; /* Option name. */
1155 int namelen
; /* Size of option name. */
1156 const char *line
; /* The start of line to match. */
1157 int linelen
; /* Size of string to match. */
1158 int fg
, bg
, attr
; /* Color and text attributes for the lines. */
1161 static struct line_info line_info
[] = {
1162 #define LINE(type, line, fg, bg, attr) \
1163 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
1168 static enum line_type
1169 get_line_type(const char *line
)
1171 int linelen
= strlen(line
);
1172 enum line_type type
;
1174 for (type
= 0; type
< ARRAY_SIZE(line_info
); type
++)
1175 /* Case insensitive search matches Signed-off-by lines better. */
1176 if (linelen
>= line_info
[type
].linelen
&&
1177 !strncasecmp(line_info
[type
].line
, line
, line_info
[type
].linelen
))
1180 return LINE_DEFAULT
;
1184 get_line_attr(enum line_type type
)
1186 assert(type
< ARRAY_SIZE(line_info
));
1187 return COLOR_PAIR(type
) | line_info
[type
].attr
;
1190 static struct line_info
*
1191 get_line_info(const char *name
)
1193 size_t namelen
= strlen(name
);
1194 enum line_type type
;
1196 for (type
= 0; type
< ARRAY_SIZE(line_info
); type
++)
1197 if (enum_equals(line_info
[type
], name
, namelen
))
1198 return &line_info
[type
];
1206 int default_bg
= line_info
[LINE_DEFAULT
].bg
;
1207 int default_fg
= line_info
[LINE_DEFAULT
].fg
;
1208 enum line_type type
;
1212 if (assume_default_colors(default_fg
, default_bg
) == ERR
) {
1213 default_bg
= COLOR_BLACK
;
1214 default_fg
= COLOR_WHITE
;
1217 for (type
= 0; type
< ARRAY_SIZE(line_info
); type
++) {
1218 struct line_info
*info
= &line_info
[type
];
1219 int bg
= info
->bg
== COLOR_DEFAULT
? default_bg
: info
->bg
;
1220 int fg
= info
->fg
== COLOR_DEFAULT
? default_fg
: info
->fg
;
1222 init_pair(type
, fg
, bg
);
1227 enum line_type type
;
1230 unsigned int selected
:1;
1231 unsigned int dirty
:1;
1232 unsigned int cleareol
:1;
1233 unsigned int other
:16;
1235 void *data
; /* User data */
1245 enum request request
;
1248 static const struct keybinding default_keybindings
[] = {
1249 /* View switching */
1250 { 'm', REQ_VIEW_MAIN
},
1251 { 'd', REQ_VIEW_DIFF
},
1252 { 'l', REQ_VIEW_LOG
},
1253 { 't', REQ_VIEW_TREE
},
1254 { 'f', REQ_VIEW_BLOB
},
1255 { 'B', REQ_VIEW_BLAME
},
1256 { 'H', REQ_VIEW_BRANCH
},
1257 { 'p', REQ_VIEW_PAGER
},
1258 { 'h', REQ_VIEW_HELP
},
1259 { 'S', REQ_VIEW_STATUS
},
1260 { 'c', REQ_VIEW_STAGE
},
1262 /* View manipulation */
1263 { 'q', REQ_VIEW_CLOSE
},
1264 { KEY_TAB
, REQ_VIEW_NEXT
},
1265 { KEY_RETURN
, REQ_ENTER
},
1266 { KEY_UP
, REQ_PREVIOUS
},
1267 { KEY_DOWN
, REQ_NEXT
},
1268 { 'R', REQ_REFRESH
},
1269 { KEY_F(5), REQ_REFRESH
},
1270 { 'O', REQ_MAXIMIZE
},
1272 /* Cursor navigation */
1273 { 'k', REQ_MOVE_UP
},
1274 { 'j', REQ_MOVE_DOWN
},
1275 { KEY_HOME
, REQ_MOVE_FIRST_LINE
},
1276 { KEY_END
, REQ_MOVE_LAST_LINE
},
1277 { KEY_NPAGE
, REQ_MOVE_PAGE_DOWN
},
1278 { ' ', REQ_MOVE_PAGE_DOWN
},
1279 { KEY_PPAGE
, REQ_MOVE_PAGE_UP
},
1280 { 'b', REQ_MOVE_PAGE_UP
},
1281 { '-', REQ_MOVE_PAGE_UP
},
1284 { KEY_LEFT
, REQ_SCROLL_LEFT
},
1285 { KEY_RIGHT
, REQ_SCROLL_RIGHT
},
1286 { KEY_IC
, REQ_SCROLL_LINE_UP
},
1287 { KEY_DC
, REQ_SCROLL_LINE_DOWN
},
1288 { 'w', REQ_SCROLL_PAGE_UP
},
1289 { 's', REQ_SCROLL_PAGE_DOWN
},
1292 { '/', REQ_SEARCH
},
1293 { '?', REQ_SEARCH_BACK
},
1294 { 'n', REQ_FIND_NEXT
},
1295 { 'N', REQ_FIND_PREV
},
1299 { 'z', REQ_STOP_LOADING
},
1300 { 'v', REQ_SHOW_VERSION
},
1301 { 'r', REQ_SCREEN_REDRAW
},
1302 { 'o', REQ_OPTIONS
},
1303 { '.', REQ_TOGGLE_LINENO
},
1304 { 'D', REQ_TOGGLE_DATE
},
1305 { 'A', REQ_TOGGLE_AUTHOR
},
1306 { 'g', REQ_TOGGLE_REV_GRAPH
},
1307 { 'F', REQ_TOGGLE_REFS
},
1308 { 'I', REQ_TOGGLE_SORT_ORDER
},
1309 { 'i', REQ_TOGGLE_SORT_FIELD
},
1310 { ':', REQ_PROMPT
},
1311 { 'u', REQ_STATUS_UPDATE
},
1312 { '!', REQ_STATUS_REVERT
},
1313 { 'M', REQ_STATUS_MERGE
},
1314 { '@', REQ_STAGE_NEXT
},
1315 { ',', REQ_PARENT
},
1319 #define KEYMAP_INFO \
1334 #define KEYMAP_(name) KEYMAP_##name
1339 static const struct enum_map keymap_table
[] = {
1340 #define KEYMAP_(name) ENUM_MAP(#name, KEYMAP_##name)
1345 #define set_keymap(map, name) map_enum(map, keymap_table, name)
1347 struct keybinding_table
{
1348 struct keybinding
*data
;
1352 static struct keybinding_table keybindings
[ARRAY_SIZE(keymap_table
)];
1355 add_keybinding(enum keymap keymap
, enum request request
, int key
)
1357 struct keybinding_table
*table
= &keybindings
[keymap
];
1359 table
->data
= realloc(table
->data
, (table
->size
+ 1) * sizeof(*table
->data
));
1361 die("Failed to allocate keybinding");
1362 table
->data
[table
->size
].alias
= key
;
1363 table
->data
[table
->size
++].request
= request
;
1366 /* Looks for a key binding first in the given map, then in the generic map, and
1367 * lastly in the default keybindings. */
1369 get_keybinding(enum keymap keymap
, int key
)
1373 for (i
= 0; i
< keybindings
[keymap
].size
; i
++)
1374 if (keybindings
[keymap
].data
[i
].alias
== key
)
1375 return keybindings
[keymap
].data
[i
].request
;
1377 for (i
= 0; i
< keybindings
[KEYMAP_GENERIC
].size
; i
++)
1378 if (keybindings
[KEYMAP_GENERIC
].data
[i
].alias
== key
)
1379 return keybindings
[KEYMAP_GENERIC
].data
[i
].request
;
1381 for (i
= 0; i
< ARRAY_SIZE(default_keybindings
); i
++)
1382 if (default_keybindings
[i
].alias
== key
)
1383 return default_keybindings
[i
].request
;
1385 return (enum request
) key
;
1394 static const struct key key_table
[] = {
1395 { "Enter", KEY_RETURN
},
1397 { "Backspace", KEY_BACKSPACE
},
1399 { "Escape", KEY_ESC
},
1400 { "Left", KEY_LEFT
},
1401 { "Right", KEY_RIGHT
},
1403 { "Down", KEY_DOWN
},
1404 { "Insert", KEY_IC
},
1405 { "Delete", KEY_DC
},
1407 { "Home", KEY_HOME
},
1409 { "PageUp", KEY_PPAGE
},
1410 { "PageDown", KEY_NPAGE
},
1420 { "F10", KEY_F(10) },
1421 { "F11", KEY_F(11) },
1422 { "F12", KEY_F(12) },
1426 get_key_value(const char *name
)
1430 for (i
= 0; i
< ARRAY_SIZE(key_table
); i
++)
1431 if (!strcasecmp(key_table
[i
].name
, name
))
1432 return key_table
[i
].value
;
1434 if (strlen(name
) == 1 && isprint(*name
))
1441 get_key_name(int key_value
)
1443 static char key_char
[] = "'X'";
1444 const char *seq
= NULL
;
1447 for (key
= 0; key
< ARRAY_SIZE(key_table
); key
++)
1448 if (key_table
[key
].value
== key_value
)
1449 seq
= key_table
[key
].name
;
1453 isprint(key_value
)) {
1454 key_char
[1] = (char) key_value
;
1458 return seq
? seq
: "(no key)";
1462 append_key(char *buf
, size_t *pos
, const struct keybinding
*keybinding
)
1464 const char *sep
= *pos
> 0 ? ", " : "";
1465 const char *keyname
= get_key_name(keybinding
->alias
);
1467 return string_nformat(buf
, BUFSIZ
, pos
, "%s%s", sep
, keyname
);
1471 append_keymap_request_keys(char *buf
, size_t *pos
, enum request request
,
1472 enum keymap keymap
, bool all
)
1476 for (i
= 0; i
< keybindings
[keymap
].size
; i
++) {
1477 if (keybindings
[keymap
].data
[i
].request
== request
) {
1478 if (!append_key(buf
, pos
, &keybindings
[keymap
].data
[i
]))
1488 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
1491 get_keys(enum keymap keymap
, enum request request
, bool all
)
1493 static char buf
[BUFSIZ
];
1499 if (!append_keymap_request_keys(buf
, &pos
, request
, keymap
, all
))
1500 return "Too many keybindings!";
1501 if (pos
> 0 && !all
)
1504 if (keymap
!= KEYMAP_GENERIC
) {
1505 /* Only the generic keymap includes the default keybindings when
1506 * listing all keys. */
1510 if (!append_keymap_request_keys(buf
, &pos
, request
, KEYMAP_GENERIC
, all
))
1511 return "Too many keybindings!";
1516 for (i
= 0; i
< ARRAY_SIZE(default_keybindings
); i
++) {
1517 if (default_keybindings
[i
].request
== request
) {
1518 if (!append_key(buf
, &pos
, &default_keybindings
[i
]))
1519 return "Too many keybindings!";
1528 struct run_request
{
1531 const char *argv
[SIZEOF_ARG
];
1534 static struct run_request
*run_request
;
1535 static size_t run_requests
;
1537 DEFINE_ALLOCATOR(realloc_run_requests
, struct run_request
, 8)
1540 add_run_request(enum keymap keymap
, int key
, int argc
, const char **argv
)
1542 struct run_request
*req
;
1544 if (argc
>= ARRAY_SIZE(req
->argv
) - 1)
1547 if (!realloc_run_requests(&run_request
, run_requests
, 1))
1550 req
= &run_request
[run_requests
];
1551 req
->keymap
= keymap
;
1553 req
->argv
[0] = NULL
;
1555 if (!format_argv(req
->argv
, argv
, FORMAT_NONE
))
1558 return REQ_NONE
+ ++run_requests
;
1561 static struct run_request
*
1562 get_run_request(enum request request
)
1564 if (request
<= REQ_NONE
)
1566 return &run_request
[request
- REQ_NONE
- 1];
1570 add_builtin_run_requests(void)
1572 const char *cherry_pick
[] = { "git", "cherry-pick", "%(commit)", NULL
};
1573 const char *commit
[] = { "git", "commit", NULL
};
1574 const char *gc
[] = { "git", "gc", NULL
};
1581 { KEYMAP_MAIN
, 'C', ARRAY_SIZE(cherry_pick
) - 1, cherry_pick
},
1582 { KEYMAP_STATUS
, 'C', ARRAY_SIZE(commit
) - 1, commit
},
1583 { KEYMAP_GENERIC
, 'G', ARRAY_SIZE(gc
) - 1, gc
},
1587 for (i
= 0; i
< ARRAY_SIZE(reqs
); i
++) {
1590 req
= add_run_request(reqs
[i
].keymap
, reqs
[i
].key
, reqs
[i
].argc
, reqs
[i
].argv
);
1591 if (req
!= REQ_NONE
)
1592 add_keybinding(reqs
[i
].keymap
, req
, reqs
[i
].key
);
1597 * User config file handling.
1600 static int config_lineno
;
1601 static bool config_errors
;
1602 static const char *config_msg
;
1604 static const struct enum_map color_map
[] = {
1605 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1617 static const struct enum_map attr_map
[] = {
1618 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1625 ATTR_MAP(UNDERLINE
),
1628 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1630 static int parse_step(double *opt
, const char *arg
)
1633 if (!strchr(arg
, '%'))
1636 /* "Shift down" so 100% and 1 does not conflict. */
1637 *opt
= (*opt
- 1) / 100;
1640 config_msg
= "Step value larger than 100%";
1645 config_msg
= "Invalid step value";
1652 parse_int(int *opt
, const char *arg
, int min
, int max
)
1654 int value
= atoi(arg
);
1656 if (min
<= value
&& value
<= max
) {
1661 config_msg
= "Integer value out of bound";
1666 set_color(int *color
, const char *name
)
1668 if (map_enum(color
, color_map
, name
))
1670 if (!prefixcmp(name
, "color"))
1671 return parse_int(color
, name
+ 5, 0, 255) == OK
;
1675 /* Wants: object fgcolor bgcolor [attribute] */
1677 option_color_command(int argc
, const char *argv
[])
1679 struct line_info
*info
;
1682 config_msg
= "Wrong number of arguments given to color command";
1686 info
= get_line_info(argv
[0]);
1688 static const struct enum_map obsolete
[] = {
1689 ENUM_MAP("main-delim", LINE_DELIMITER
),
1690 ENUM_MAP("main-date", LINE_DATE
),
1691 ENUM_MAP("main-author", LINE_AUTHOR
),
1695 if (!map_enum(&index
, obsolete
, argv
[0])) {
1696 config_msg
= "Unknown color name";
1699 info
= &line_info
[index
];
1702 if (!set_color(&info
->fg
, argv
[1]) ||
1703 !set_color(&info
->bg
, argv
[2])) {
1704 config_msg
= "Unknown color";
1709 while (argc
-- > 3) {
1712 if (!set_attribute(&attr
, argv
[argc
])) {
1713 config_msg
= "Unknown attribute";
1722 static int parse_bool(bool *opt
, const char *arg
)
1724 *opt
= (!strcmp(arg
, "1") || !strcmp(arg
, "true") || !strcmp(arg
, "yes"))
1729 static int parse_enum_do(unsigned int *opt
, const char *arg
,
1730 const struct enum_map
*map
, size_t map_size
)
1734 assert(map_size
> 1);
1736 if (map_enum_do(map
, map_size
, (int *) opt
, arg
))
1739 if (parse_bool(&is_true
, arg
) != OK
)
1742 *opt
= is_true
? map
[1].value
: map
[0].value
;
1746 #define parse_enum(opt, arg, map) \
1747 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1750 parse_string(char *opt
, const char *arg
, size_t optsize
)
1752 int arglen
= strlen(arg
);
1757 if (arglen
== 1 || arg
[arglen
- 1] != arg
[0]) {
1758 config_msg
= "Unmatched quotation";
1761 arg
+= 1; arglen
-= 2;
1763 string_ncopy_do(opt
, optsize
, arg
, arglen
);
1768 /* Wants: name = value */
1770 option_set_command(int argc
, const char *argv
[])
1773 config_msg
= "Wrong number of arguments given to set command";
1777 if (strcmp(argv
[1], "=")) {
1778 config_msg
= "No value assigned";
1782 if (!strcmp(argv
[0], "show-author"))
1783 return parse_enum(&opt_author
, argv
[2], author_map
);
1785 if (!strcmp(argv
[0], "show-date"))
1786 return parse_enum(&opt_date
, argv
[2], date_map
);
1788 if (!strcmp(argv
[0], "show-rev-graph"))
1789 return parse_bool(&opt_rev_graph
, argv
[2]);
1791 if (!strcmp(argv
[0], "show-refs"))
1792 return parse_bool(&opt_show_refs
, argv
[2]);
1794 if (!strcmp(argv
[0], "show-line-numbers"))
1795 return parse_bool(&opt_line_number
, argv
[2]);
1797 if (!strcmp(argv
[0], "line-graphics"))
1798 return parse_bool(&opt_line_graphics
, argv
[2]);
1800 if (!strcmp(argv
[0], "line-number-interval"))
1801 return parse_int(&opt_num_interval
, argv
[2], 1, 1024);
1803 if (!strcmp(argv
[0], "author-width"))
1804 return parse_int(&opt_author_cols
, argv
[2], 0, 1024);
1806 if (!strcmp(argv
[0], "horizontal-scroll"))
1807 return parse_step(&opt_hscroll
, argv
[2]);
1809 if (!strcmp(argv
[0], "split-view-height"))
1810 return parse_step(&opt_scale_split_view
, argv
[2]);
1812 if (!strcmp(argv
[0], "tab-size"))
1813 return parse_int(&opt_tab_size
, argv
[2], 1, 1024);
1815 if (!strcmp(argv
[0], "commit-encoding"))
1816 return parse_string(opt_encoding
, argv
[2], sizeof(opt_encoding
));
1818 config_msg
= "Unknown variable name";
1822 /* Wants: mode request key */
1824 option_bind_command(int argc
, const char *argv
[])
1826 enum request request
;
1831 config_msg
= "Wrong number of arguments given to bind command";
1835 if (set_keymap(&keymap
, argv
[0]) == ERR
) {
1836 config_msg
= "Unknown key map";
1840 key
= get_key_value(argv
[1]);
1842 config_msg
= "Unknown key";
1846 request
= get_request(argv
[2]);
1847 if (request
== REQ_NONE
) {
1848 static const struct enum_map obsolete
[] = {
1849 ENUM_MAP("cherry-pick", REQ_NONE
),
1850 ENUM_MAP("screen-resize", REQ_NONE
),
1851 ENUM_MAP("tree-parent", REQ_PARENT
),
1855 if (map_enum(&alias
, obsolete
, argv
[2])) {
1856 if (alias
!= REQ_NONE
)
1857 add_keybinding(keymap
, alias
, key
);
1858 config_msg
= "Obsolete request name";
1862 if (request
== REQ_NONE
&& *argv
[2]++ == '!')
1863 request
= add_run_request(keymap
, key
, argc
- 2, argv
+ 2);
1864 if (request
== REQ_NONE
) {
1865 config_msg
= "Unknown request name";
1869 add_keybinding(keymap
, request
, key
);
1875 set_option(const char *opt
, char *value
)
1877 const char *argv
[SIZEOF_ARG
];
1880 if (!argv_from_string(argv
, &argc
, value
)) {
1881 config_msg
= "Too many option arguments";
1885 if (!strcmp(opt
, "color"))
1886 return option_color_command(argc
, argv
);
1888 if (!strcmp(opt
, "set"))
1889 return option_set_command(argc
, argv
);
1891 if (!strcmp(opt
, "bind"))
1892 return option_bind_command(argc
, argv
);
1894 config_msg
= "Unknown option command";
1899 read_option(char *opt
, size_t optlen
, char *value
, size_t valuelen
)
1904 config_msg
= "Internal error";
1906 /* Check for comment markers, since read_properties() will
1907 * only ensure opt and value are split at first " \t". */
1908 optlen
= strcspn(opt
, "#");
1912 if (opt
[optlen
] != 0) {
1913 config_msg
= "No option value";
1917 /* Look for comment endings in the value. */
1918 size_t len
= strcspn(value
, "#");
1920 if (len
< valuelen
) {
1922 value
[valuelen
] = 0;
1925 status
= set_option(opt
, value
);
1928 if (status
== ERR
) {
1929 warn("Error on line %d, near '%.*s': %s",
1930 config_lineno
, (int) optlen
, opt
, config_msg
);
1931 config_errors
= TRUE
;
1934 /* Always keep going if errors are encountered. */
1939 load_option_file(const char *path
)
1943 /* It's OK that the file doesn't exist. */
1944 if (!io_open(&io
, "%s", path
))
1948 config_errors
= FALSE
;
1950 if (io_load(&io
, " \t", read_option
) == ERR
||
1951 config_errors
== TRUE
)
1952 warn("Errors while loading %s.", path
);
1958 const char *home
= getenv("HOME");
1959 const char *tigrc_user
= getenv("TIGRC_USER");
1960 const char *tigrc_system
= getenv("TIGRC_SYSTEM");
1961 char buf
[SIZEOF_STR
];
1963 add_builtin_run_requests();
1966 tigrc_system
= SYSCONFDIR
"/tigrc";
1967 load_option_file(tigrc_system
);
1970 if (!home
|| !string_format(buf
, "%s/.tigrc", home
))
1974 load_option_file(tigrc_user
);
1987 /* The display array of active views and the index of the current view. */
1988 static struct view
*display
[2];
1989 static unsigned int current_view
;
1991 #define foreach_displayed_view(view, i) \
1992 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1994 #define displayed_views() (display[1] != NULL ? 2 : 1)
1996 /* Current head and commit ID */
1997 static char ref_blob
[SIZEOF_REF
] = "";
1998 static char ref_commit
[SIZEOF_REF
] = "HEAD";
1999 static char ref_head
[SIZEOF_REF
] = "HEAD";
2002 const char *name
; /* View name */
2003 const char *cmd_env
; /* Command line set via environment */
2004 const char *id
; /* Points to either of ref_{head,commit,blob} */
2006 struct view_ops
*ops
; /* View operations */
2008 enum keymap keymap
; /* What keymap does this view have */
2009 bool git_dir
; /* Whether the view requires a git directory. */
2011 char ref
[SIZEOF_REF
]; /* Hovered commit reference */
2012 char vid
[SIZEOF_REF
]; /* View ID. Set to id member when updating. */
2014 int height
, width
; /* The width and height of the main window */
2015 WINDOW
*win
; /* The main window */
2016 WINDOW
*title
; /* The title window living below the main window */
2019 unsigned long offset
; /* Offset of the window top */
2020 unsigned long yoffset
; /* Offset from the window side. */
2021 unsigned long lineno
; /* Current line number */
2022 unsigned long p_offset
; /* Previous offset of the window top */
2023 unsigned long p_yoffset
;/* Previous offset from the window side */
2024 unsigned long p_lineno
; /* Previous current line number */
2025 bool p_restore
; /* Should the previous position be restored. */
2028 char grep
[SIZEOF_STR
]; /* Search string */
2029 regex_t
*regex
; /* Pre-compiled regexp */
2031 /* If non-NULL, points to the view that opened this view. If this view
2032 * is closed tig will switch back to the parent view. */
2033 struct view
*parent
;
2036 size_t lines
; /* Total number of lines */
2037 struct line
*line
; /* Line index */
2038 unsigned int digits
; /* Number of digits in the lines member. */
2041 struct line
*curline
; /* Line currently being drawn. */
2042 enum line_type curtype
; /* Attribute currently used for drawing. */
2043 unsigned long col
; /* Column when drawing. */
2044 bool has_scrolled
; /* View was scrolled. */
2054 /* What type of content being displayed. Used in the title bar. */
2056 /* Default command arguments. */
2058 /* Open and reads in all view content. */
2059 bool (*open
)(struct view
*view
);
2060 /* Read one line; updates view->line. */
2061 bool (*read
)(struct view
*view
, char *data
);
2062 /* Draw one line; @lineno must be < view->height. */
2063 bool (*draw
)(struct view
*view
, struct line
*line
, unsigned int lineno
);
2064 /* Depending on view handle a special requests. */
2065 enum request (*request
)(struct view
*view
, enum request request
, struct line
*line
);
2066 /* Search for regexp in a line. */
2067 bool (*grep
)(struct view
*view
, struct line
*line
);
2069 void (*select
)(struct view
*view
, struct line
*line
);
2070 /* Prepare view for loading */
2071 bool (*prepare
)(struct view
*view
);
2074 static struct view_ops blame_ops
;
2075 static struct view_ops blob_ops
;
2076 static struct view_ops diff_ops
;
2077 static struct view_ops help_ops
;
2078 static struct view_ops log_ops
;
2079 static struct view_ops main_ops
;
2080 static struct view_ops pager_ops
;
2081 static struct view_ops stage_ops
;
2082 static struct view_ops status_ops
;
2083 static struct view_ops tree_ops
;
2084 static struct view_ops branch_ops
;
2086 #define VIEW_STR(name, env, ref, ops, map, git) \
2087 { name, #env, ref, ops, map, git }
2089 #define VIEW_(id, name, ops, git, ref) \
2090 VIEW_STR(name, TIG_##id##_CMD, ref, ops, KEYMAP_##id, git)
2093 static struct view views
[] = {
2094 VIEW_(MAIN
, "main", &main_ops
, TRUE
, ref_head
),
2095 VIEW_(DIFF
, "diff", &diff_ops
, TRUE
, ref_commit
),
2096 VIEW_(LOG
, "log", &log_ops
, TRUE
, ref_head
),
2097 VIEW_(TREE
, "tree", &tree_ops
, TRUE
, ref_commit
),
2098 VIEW_(BLOB
, "blob", &blob_ops
, TRUE
, ref_blob
),
2099 VIEW_(BLAME
, "blame", &blame_ops
, TRUE
, ref_commit
),
2100 VIEW_(BRANCH
, "branch", &branch_ops
, TRUE
, ref_head
),
2101 VIEW_(HELP
, "help", &help_ops
, FALSE
, ""),
2102 VIEW_(PAGER
, "pager", &pager_ops
, FALSE
, "stdin"),
2103 VIEW_(STATUS
, "status", &status_ops
, TRUE
, ""),
2104 VIEW_(STAGE
, "stage", &stage_ops
, TRUE
, ""),
2107 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
2108 #define VIEW_REQ(view) ((view) - views + REQ_OFFSET + 1)
2110 #define foreach_view(view, i) \
2111 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2113 #define view_is_displayed(view) \
2114 (view == display[0] || view == display[1])
2118 set_view_attr(struct view
*view
, enum line_type type
)
2120 if (!view
->curline
->selected
&& view
->curtype
!= type
) {
2121 (void) wattrset(view
->win
, get_line_attr(type
));
2122 wchgat(view
->win
, -1, 0, type
, NULL
);
2123 view
->curtype
= type
;
2128 draw_chars(struct view
*view
, enum line_type type
, const char *string
,
2129 int max_len
, bool use_tilde
)
2131 static char out_buffer
[BUFSIZ
* 2];
2134 int trimmed
= FALSE
;
2135 size_t skip
= view
->yoffset
> view
->col
? view
->yoffset
- view
->col
: 0;
2140 len
= utf8_length(&string
, skip
, &col
, max_len
, &trimmed
, use_tilde
, opt_tab_size
);
2142 set_view_attr(view
, type
);
2144 if (opt_iconv_out
!= ICONV_NONE
) {
2145 ICONV_CONST
char *inbuf
= (ICONV_CONST
char *) string
;
2146 size_t inlen
= len
+ 1;
2148 char *outbuf
= out_buffer
;
2149 size_t outlen
= sizeof(out_buffer
);
2153 ret
= iconv(opt_iconv_out
, &inbuf
, &inlen
, &outbuf
, &outlen
);
2154 if (ret
!= (size_t) -1) {
2155 string
= out_buffer
;
2156 len
= sizeof(out_buffer
) - outlen
;
2160 waddnstr(view
->win
, string
, len
);
2162 if (trimmed
&& use_tilde
) {
2163 set_view_attr(view
, LINE_DELIMITER
);
2164 waddch(view
->win
, '~');
2172 draw_space(struct view
*view
, enum line_type type
, int max
, int spaces
)
2174 static char space
[] = " ";
2177 spaces
= MIN(max
, spaces
);
2179 while (spaces
> 0) {
2180 int len
= MIN(spaces
, sizeof(space
) - 1);
2182 col
+= draw_chars(view
, type
, space
, len
, FALSE
);
2190 draw_text(struct view
*view
, enum line_type type
, const char *string
, bool trim
)
2192 view
->col
+= draw_chars(view
, type
, string
, view
->width
+ view
->yoffset
- view
->col
, trim
);
2193 return view
->width
+ view
->yoffset
<= view
->col
;
2197 draw_graphic(struct view
*view
, enum line_type type
, chtype graphic
[], size_t size
)
2199 size_t skip
= view
->yoffset
> view
->col
? view
->yoffset
- view
->col
: 0;
2200 int max
= view
->width
+ view
->yoffset
- view
->col
;
2206 set_view_attr(view
, type
);
2207 /* Using waddch() instead of waddnstr() ensures that
2208 * they'll be rendered correctly for the cursor line. */
2209 for (i
= skip
; i
< size
; i
++)
2210 waddch(view
->win
, graphic
[i
]);
2213 if (size
< max
&& skip
<= size
)
2214 waddch(view
->win
, ' ');
2217 return view
->width
+ view
->yoffset
<= view
->col
;
2221 draw_field(struct view
*view
, enum line_type type
, const char *text
, int len
, bool trim
)
2223 int max
= MIN(view
->width
+ view
->yoffset
- view
->col
, len
);
2227 col
= draw_chars(view
, type
, text
, max
- 1, trim
);
2229 col
= draw_space(view
, type
, max
- 1, max
- 1);
2232 view
->col
+= draw_space(view
, LINE_DEFAULT
, max
- col
, max
- col
);
2233 return view
->width
+ view
->yoffset
<= view
->col
;
2237 draw_date(struct view
*view
, struct time
*time
)
2239 const char *date
= time
&& time
->sec
? mkdate(time
) : "";
2240 int cols
= opt_date
== DATE_SHORT
? DATE_SHORT_COLS
: DATE_COLS
;
2242 return draw_field(view
, LINE_DATE
, date
, cols
, FALSE
);
2246 draw_author(struct view
*view
, const char *author
)
2248 bool trim
= opt_author_cols
== 0 || opt_author_cols
> 5;
2249 bool abbreviate
= opt_author
== AUTHOR_ABBREVIATED
|| !trim
;
2251 if (abbreviate
&& author
)
2252 author
= get_author_initials(author
);
2254 return draw_field(view
, LINE_AUTHOR
, author
, opt_author_cols
, trim
);
2258 draw_mode(struct view
*view
, mode_t mode
)
2264 else if (S_ISLNK(mode
))
2266 else if (S_ISGITLINK(mode
))
2268 else if (S_ISREG(mode
) && mode
& S_IXUSR
)
2270 else if (S_ISREG(mode
))
2275 return draw_field(view
, LINE_MODE
, str
, STRING_SIZE("-rw-r--r-- "), FALSE
);
2279 draw_lineno(struct view
*view
, unsigned int lineno
)
2282 int digits3
= view
->digits
< 3 ? 3 : view
->digits
;
2283 int max
= MIN(view
->width
+ view
->yoffset
- view
->col
, digits3
);
2285 chtype separator
= opt_line_graphics
? ACS_VLINE
: '|';
2287 lineno
+= view
->offset
+ 1;
2288 if (lineno
== 1 || (lineno
% opt_num_interval
) == 0) {
2289 static char fmt
[] = "%1ld";
2291 fmt
[1] = '0' + (view
->digits
<= 9 ? digits3
: 1);
2292 if (string_format(number
, fmt
, lineno
))
2296 view
->col
+= draw_chars(view
, LINE_LINE_NUMBER
, text
, max
, TRUE
);
2298 view
->col
+= draw_space(view
, LINE_LINE_NUMBER
, max
, digits3
);
2299 return draw_graphic(view
, LINE_DEFAULT
, &separator
, 1);
2303 draw_view_line(struct view
*view
, unsigned int lineno
)
2306 bool selected
= (view
->offset
+ lineno
== view
->lineno
);
2308 assert(view_is_displayed(view
));
2310 if (view
->offset
+ lineno
>= view
->lines
)
2313 line
= &view
->line
[view
->offset
+ lineno
];
2315 wmove(view
->win
, lineno
, 0);
2317 wclrtoeol(view
->win
);
2319 view
->curline
= line
;
2320 view
->curtype
= LINE_NONE
;
2321 line
->selected
= FALSE
;
2322 line
->dirty
= line
->cleareol
= 0;
2325 set_view_attr(view
, LINE_CURSOR
);
2326 line
->selected
= TRUE
;
2327 view
->ops
->select(view
, line
);
2330 return view
->ops
->draw(view
, line
, lineno
);
2334 redraw_view_dirty(struct view
*view
)
2339 for (lineno
= 0; lineno
< view
->height
; lineno
++) {
2340 if (view
->offset
+ lineno
>= view
->lines
)
2342 if (!view
->line
[view
->offset
+ lineno
].dirty
)
2345 if (!draw_view_line(view
, lineno
))
2351 wnoutrefresh(view
->win
);
2355 redraw_view_from(struct view
*view
, int lineno
)
2357 assert(0 <= lineno
&& lineno
< view
->height
);
2359 for (; lineno
< view
->height
; lineno
++) {
2360 if (!draw_view_line(view
, lineno
))
2364 wnoutrefresh(view
->win
);
2368 redraw_view(struct view
*view
)
2371 redraw_view_from(view
, 0);
2376 update_view_title(struct view
*view
)
2378 char buf
[SIZEOF_STR
];
2379 char state
[SIZEOF_STR
];
2380 size_t bufpos
= 0, statelen
= 0;
2382 assert(view_is_displayed(view
));
2384 if (view
!= VIEW(REQ_VIEW_STATUS
) && view
->lines
) {
2385 unsigned int view_lines
= view
->offset
+ view
->height
;
2386 unsigned int lines
= view
->lines
2387 ? MIN(view_lines
, view
->lines
) * 100 / view
->lines
2390 string_format_from(state
, &statelen
, " - %s %d of %d (%d%%)",
2399 time_t secs
= time(NULL
) - view
->start_time
;
2401 /* Three git seconds are a long time ... */
2403 string_format_from(state
, &statelen
, " loading %lds", secs
);
2406 string_format_from(buf
, &bufpos
, "[%s]", view
->name
);
2407 if (*view
->ref
&& bufpos
< view
->width
) {
2408 size_t refsize
= strlen(view
->ref
);
2409 size_t minsize
= bufpos
+ 1 + /* abbrev= */ 7 + 1 + statelen
;
2411 if (minsize
< view
->width
)
2412 refsize
= view
->width
- minsize
+ 7;
2413 string_format_from(buf
, &bufpos
, " %.*s", (int) refsize
, view
->ref
);
2416 if (statelen
&& bufpos
< view
->width
) {
2417 string_format_from(buf
, &bufpos
, "%s", state
);
2420 if (view
== display
[current_view
])
2421 wbkgdset(view
->title
, get_line_attr(LINE_TITLE_FOCUS
));
2423 wbkgdset(view
->title
, get_line_attr(LINE_TITLE_BLUR
));
2425 mvwaddnstr(view
->title
, 0, 0, buf
, bufpos
);
2426 wclrtoeol(view
->title
);
2427 wnoutrefresh(view
->title
);
2431 apply_step(double step
, int value
)
2435 value
*= step
+ 0.01;
2436 return value
? value
: 1;
2440 resize_display(void)
2443 struct view
*base
= display
[0];
2444 struct view
*view
= display
[1] ? display
[1] : display
[0];
2446 /* Setup window dimensions */
2448 getmaxyx(stdscr
, base
->height
, base
->width
);
2450 /* Make room for the status window. */
2454 /* Horizontal split. */
2455 view
->width
= base
->width
;
2456 view
->height
= apply_step(opt_scale_split_view
, base
->height
);
2457 view
->height
= MAX(view
->height
, MIN_VIEW_HEIGHT
);
2458 view
->height
= MIN(view
->height
, base
->height
- MIN_VIEW_HEIGHT
);
2459 base
->height
-= view
->height
;
2461 /* Make room for the title bar. */
2465 /* Make room for the title bar. */
2470 foreach_displayed_view (view
, i
) {
2472 view
->win
= newwin(view
->height
, 0, offset
, 0);
2474 die("Failed to create %s view", view
->name
);
2476 scrollok(view
->win
, FALSE
);
2478 view
->title
= newwin(1, 0, offset
+ view
->height
, 0);
2480 die("Failed to create title window");
2483 wresize(view
->win
, view
->height
, view
->width
);
2484 mvwin(view
->win
, offset
, 0);
2485 mvwin(view
->title
, offset
+ view
->height
, 0);
2488 offset
+= view
->height
+ 1;
2493 redraw_display(bool clear
)
2498 foreach_displayed_view (view
, i
) {
2502 update_view_title(view
);
2507 toggle_enum_option_do(unsigned int *opt
, const char *help
,
2508 const struct enum_map
*map
, size_t size
)
2510 *opt
= (*opt
+ 1) % size
;
2511 redraw_display(FALSE
);
2512 report("Displaying %s %s", enum_name(map
[*opt
]), help
);
2515 #define toggle_enum_option(opt, help, map) \
2516 toggle_enum_option_do(opt, help, map, ARRAY_SIZE(map))
2518 #define toggle_date() toggle_enum_option(&opt_date, "dates", date_map)
2519 #define toggle_author() toggle_enum_option(&opt_author, "author names", author_map)
2522 toggle_view_option(bool *option
, const char *help
)
2525 redraw_display(FALSE
);
2526 report("%sabling %s", *option
? "En" : "Dis", help
);
2530 open_option_menu(void)
2532 const struct menu_item menu
[] = {
2533 { '.', "line numbers", &opt_line_number
},
2534 { 'D', "date display", &opt_date
},
2535 { 'A', "author display", &opt_author
},
2536 { 'g', "revision graph display", &opt_rev_graph
},
2537 { 'F', "reference display", &opt_show_refs
},
2542 if (prompt_menu("Toggle option", menu
, &selected
)) {
2543 if (menu
[selected
].data
== &opt_date
)
2545 else if (menu
[selected
].data
== &opt_author
)
2548 toggle_view_option(menu
[selected
].data
, menu
[selected
].text
);
2553 maximize_view(struct view
*view
)
2555 memset(display
, 0, sizeof(display
));
2557 display
[current_view
] = view
;
2559 redraw_display(FALSE
);
2569 goto_view_line(struct view
*view
, unsigned long offset
, unsigned long lineno
)
2571 if (lineno
>= view
->lines
)
2572 lineno
= view
->lines
> 0 ? view
->lines
- 1 : 0;
2574 if (offset
> lineno
|| offset
+ view
->height
<= lineno
) {
2575 unsigned long half
= view
->height
/ 2;
2578 offset
= lineno
- half
;
2583 if (offset
!= view
->offset
|| lineno
!= view
->lineno
) {
2584 view
->offset
= offset
;
2585 view
->lineno
= lineno
;
2592 /* Scrolling backend */
2594 do_scroll_view(struct view
*view
, int lines
)
2596 bool redraw_current_line
= FALSE
;
2598 /* The rendering expects the new offset. */
2599 view
->offset
+= lines
;
2601 assert(0 <= view
->offset
&& view
->offset
< view
->lines
);
2604 /* Move current line into the view. */
2605 if (view
->lineno
< view
->offset
) {
2606 view
->lineno
= view
->offset
;
2607 redraw_current_line
= TRUE
;
2608 } else if (view
->lineno
>= view
->offset
+ view
->height
) {
2609 view
->lineno
= view
->offset
+ view
->height
- 1;
2610 redraw_current_line
= TRUE
;
2613 assert(view
->offset
<= view
->lineno
&& view
->lineno
< view
->lines
);
2615 /* Redraw the whole screen if scrolling is pointless. */
2616 if (view
->height
< ABS(lines
)) {
2620 int line
= lines
> 0 ? view
->height
- lines
: 0;
2621 int end
= line
+ ABS(lines
);
2623 scrollok(view
->win
, TRUE
);
2624 wscrl(view
->win
, lines
);
2625 scrollok(view
->win
, FALSE
);
2627 while (line
< end
&& draw_view_line(view
, line
))
2630 if (redraw_current_line
)
2631 draw_view_line(view
, view
->lineno
- view
->offset
);
2632 wnoutrefresh(view
->win
);
2635 view
->has_scrolled
= TRUE
;
2639 /* Scroll frontend */
2641 scroll_view(struct view
*view
, enum request request
)
2645 assert(view_is_displayed(view
));
2648 case REQ_SCROLL_LEFT
:
2649 if (view
->yoffset
== 0) {
2650 report("Cannot scroll beyond the first column");
2653 if (view
->yoffset
<= apply_step(opt_hscroll
, view
->width
))
2656 view
->yoffset
-= apply_step(opt_hscroll
, view
->width
);
2657 redraw_view_from(view
, 0);
2660 case REQ_SCROLL_RIGHT
:
2661 view
->yoffset
+= apply_step(opt_hscroll
, view
->width
);
2665 case REQ_SCROLL_PAGE_DOWN
:
2666 lines
= view
->height
;
2667 case REQ_SCROLL_LINE_DOWN
:
2668 if (view
->offset
+ lines
> view
->lines
)
2669 lines
= view
->lines
- view
->offset
;
2671 if (lines
== 0 || view
->offset
+ view
->height
>= view
->lines
) {
2672 report("Cannot scroll beyond the last line");
2677 case REQ_SCROLL_PAGE_UP
:
2678 lines
= view
->height
;
2679 case REQ_SCROLL_LINE_UP
:
2680 if (lines
> view
->offset
)
2681 lines
= view
->offset
;
2684 report("Cannot scroll beyond the first line");
2692 die("request %d not handled in switch", request
);
2695 do_scroll_view(view
, lines
);
2700 move_view(struct view
*view
, enum request request
)
2702 int scroll_steps
= 0;
2706 case REQ_MOVE_FIRST_LINE
:
2707 steps
= -view
->lineno
;
2710 case REQ_MOVE_LAST_LINE
:
2711 steps
= view
->lines
- view
->lineno
- 1;
2714 case REQ_MOVE_PAGE_UP
:
2715 steps
= view
->height
> view
->lineno
2716 ? -view
->lineno
: -view
->height
;
2719 case REQ_MOVE_PAGE_DOWN
:
2720 steps
= view
->lineno
+ view
->height
>= view
->lines
2721 ? view
->lines
- view
->lineno
- 1 : view
->height
;
2733 die("request %d not handled in switch", request
);
2736 if (steps
<= 0 && view
->lineno
== 0) {
2737 report("Cannot move beyond the first line");
2740 } else if (steps
>= 0 && view
->lineno
+ 1 >= view
->lines
) {
2741 report("Cannot move beyond the last line");
2745 /* Move the current line */
2746 view
->lineno
+= steps
;
2747 assert(0 <= view
->lineno
&& view
->lineno
< view
->lines
);
2749 /* Check whether the view needs to be scrolled */
2750 if (view
->lineno
< view
->offset
||
2751 view
->lineno
>= view
->offset
+ view
->height
) {
2752 scroll_steps
= steps
;
2753 if (steps
< 0 && -steps
> view
->offset
) {
2754 scroll_steps
= -view
->offset
;
2756 } else if (steps
> 0) {
2757 if (view
->lineno
== view
->lines
- 1 &&
2758 view
->lines
> view
->height
) {
2759 scroll_steps
= view
->lines
- view
->offset
- 1;
2760 if (scroll_steps
>= view
->height
)
2761 scroll_steps
-= view
->height
- 1;
2766 if (!view_is_displayed(view
)) {
2767 view
->offset
+= scroll_steps
;
2768 assert(0 <= view
->offset
&& view
->offset
< view
->lines
);
2769 view
->ops
->select(view
, &view
->line
[view
->lineno
]);
2773 /* Repaint the old "current" line if we be scrolling */
2774 if (ABS(steps
) < view
->height
)
2775 draw_view_line(view
, view
->lineno
- steps
- view
->offset
);
2778 do_scroll_view(view
, scroll_steps
);
2782 /* Draw the current line */
2783 draw_view_line(view
, view
->lineno
- view
->offset
);
2785 wnoutrefresh(view
->win
);
2794 static void search_view(struct view
*view
, enum request request
);
2797 grep_text(struct view
*view
, const char *text
[])
2802 for (i
= 0; text
[i
]; i
++)
2804 regexec(view
->regex
, text
[i
], 1, &pmatch
, 0) != REG_NOMATCH
)
2810 select_view_line(struct view
*view
, unsigned long lineno
)
2812 unsigned long old_lineno
= view
->lineno
;
2813 unsigned long old_offset
= view
->offset
;
2815 if (goto_view_line(view
, view
->offset
, lineno
)) {
2816 if (view_is_displayed(view
)) {
2817 if (old_offset
!= view
->offset
) {
2820 draw_view_line(view
, old_lineno
- view
->offset
);
2821 draw_view_line(view
, view
->lineno
- view
->offset
);
2822 wnoutrefresh(view
->win
);
2825 view
->ops
->select(view
, &view
->line
[view
->lineno
]);
2831 find_next(struct view
*view
, enum request request
)
2833 unsigned long lineno
= view
->lineno
;
2838 report("No previous search");
2840 search_view(view
, request
);
2850 case REQ_SEARCH_BACK
:
2859 if (request
== REQ_FIND_NEXT
|| request
== REQ_FIND_PREV
)
2860 lineno
+= direction
;
2862 /* Note, lineno is unsigned long so will wrap around in which case it
2863 * will become bigger than view->lines. */
2864 for (; lineno
< view
->lines
; lineno
+= direction
) {
2865 if (view
->ops
->grep(view
, &view
->line
[lineno
])) {
2866 select_view_line(view
, lineno
);
2867 report("Line %ld matches '%s'", lineno
+ 1, view
->grep
);
2872 report("No match found for '%s'", view
->grep
);
2876 search_view(struct view
*view
, enum request request
)
2881 regfree(view
->regex
);
2884 view
->regex
= calloc(1, sizeof(*view
->regex
));
2889 regex_err
= regcomp(view
->regex
, opt_search
, REG_EXTENDED
);
2890 if (regex_err
!= 0) {
2891 char buf
[SIZEOF_STR
] = "unknown error";
2893 regerror(regex_err
, view
->regex
, buf
, sizeof(buf
));
2894 report("Search failed: %s", buf
);
2898 string_copy(view
->grep
, opt_search
);
2900 find_next(view
, request
);
2904 * Incremental updating
2908 reset_view(struct view
*view
)
2912 for (i
= 0; i
< view
->lines
; i
++)
2913 free(view
->line
[i
].data
);
2916 view
->p_offset
= view
->offset
;
2917 view
->p_yoffset
= view
->yoffset
;
2918 view
->p_lineno
= view
->lineno
;
2926 view
->update_secs
= 0;
2930 free_argv(const char *argv
[])
2934 for (argc
= 0; argv
[argc
]; argc
++)
2935 free((void *) argv
[argc
]);
2939 format_arg(const char *name
)
2945 const char *value_if_empty
;
2947 #define FORMAT_VAR(name, value, value_if_empty) \
2948 { name, STRING_SIZE(name), value, value_if_empty }
2949 FORMAT_VAR("%(directory)", opt_path
, ""),
2950 FORMAT_VAR("%(file)", opt_file
, ""),
2951 FORMAT_VAR("%(ref)", opt_ref
, "HEAD"),
2952 FORMAT_VAR("%(head)", ref_head
, ""),
2953 FORMAT_VAR("%(commit)", ref_commit
, ""),
2954 FORMAT_VAR("%(blob)", ref_blob
, ""),
2958 for (i
= 0; i
< ARRAY_SIZE(vars
); i
++)
2959 if (!strncmp(name
, vars
[i
].name
, vars
[i
].namelen
))
2960 return *vars
[i
].value
? vars
[i
].value
: vars
[i
].value_if_empty
;
2965 format_argv(const char *dst_argv
[], const char *src_argv
[], enum format_flags flags
)
2967 char buf
[SIZEOF_STR
];
2969 bool noreplace
= flags
== FORMAT_NONE
;
2971 free_argv(dst_argv
);
2973 for (argc
= 0; src_argv
[argc
]; argc
++) {
2974 const char *arg
= src_argv
[argc
];
2978 char *next
= strstr(arg
, "%(");
2979 int len
= next
- arg
;
2982 if (!next
|| noreplace
) {
2983 if (flags
== FORMAT_DASH
&& !strcmp(arg
, "--"))
2989 value
= format_arg(next
);
2992 report("Unknown replacement: `%s`", next
);
2997 if (!string_format_from(buf
, &bufpos
, "%.*s%s", len
, arg
, value
))
3000 arg
= next
&& !noreplace
? strchr(next
, ')') + 1 : NULL
;
3003 dst_argv
[argc
] = strdup(buf
);
3004 if (!dst_argv
[argc
])
3008 dst_argv
[argc
] = NULL
;
3010 return src_argv
[argc
] == NULL
;
3014 restore_view_position(struct view
*view
)
3016 if (!view
->p_restore
|| (view
->pipe
&& view
->lines
<= view
->p_lineno
))
3019 /* Changing the view position cancels the restoring. */
3020 /* FIXME: Changing back to the first line is not detected. */
3021 if (view
->offset
!= 0 || view
->lineno
!= 0) {
3022 view
->p_restore
= FALSE
;
3026 if (goto_view_line(view
, view
->p_offset
, view
->p_lineno
) &&
3027 view_is_displayed(view
))
3030 view
->yoffset
= view
->p_yoffset
;
3031 view
->p_restore
= FALSE
;
3037 end_update(struct view
*view
, bool force
)
3041 while (!view
->ops
->read(view
, NULL
))
3044 set_nonblocking_input(FALSE
);
3046 kill_io(view
->pipe
);
3047 done_io(view
->pipe
);
3052 setup_update(struct view
*view
, const char *vid
)
3054 set_nonblocking_input(TRUE
);
3056 string_copy_rev(view
->vid
, vid
);
3057 view
->pipe
= &view
->io
;
3058 view
->start_time
= time(NULL
);
3062 prepare_update(struct view
*view
, const char *argv
[], const char *dir
,
3063 enum format_flags flags
)
3066 end_update(view
, TRUE
);
3067 return init_io_rd(&view
->io
, argv
, dir
, flags
);
3071 prepare_update_file(struct view
*view
, const char *name
)
3074 end_update(view
, TRUE
);
3075 return io_open(&view
->io
, "%s/%s", opt_cdup
[0] ? opt_cdup
: ".", name
);
3079 begin_update(struct view
*view
, bool refresh
)
3082 end_update(view
, TRUE
);
3085 if (view
->ops
->prepare
) {
3086 if (!view
->ops
->prepare(view
))
3088 } else if (!init_io_rd(&view
->io
, view
->ops
->argv
, NULL
, FORMAT_ALL
)) {
3092 /* Put the current ref_* value to the view title ref
3093 * member. This is needed by the blob view. Most other
3094 * views sets it automatically after loading because the
3095 * first line is a commit line. */
3096 string_copy_rev(view
->ref
, view
->id
);
3099 if (!start_io(&view
->io
))
3102 setup_update(view
, view
->id
);
3108 update_view(struct view
*view
)
3110 char out_buffer
[BUFSIZ
* 2];
3112 /* Clear the view and redraw everything since the tree sorting
3113 * might have rearranged things. */
3114 bool redraw
= view
->lines
== 0;
3115 bool can_read
= TRUE
;
3120 if (!io_can_read(view
->pipe
)) {
3121 if (view
->lines
== 0 && view_is_displayed(view
)) {
3122 time_t secs
= time(NULL
) - view
->start_time
;
3124 if (secs
> 1 && secs
> view
->update_secs
) {
3125 if (view
->update_secs
== 0)
3127 update_view_title(view
);
3128 view
->update_secs
= secs
;
3134 for (; (line
= io_get(view
->pipe
, '\n', can_read
)); can_read
= FALSE
) {
3135 if (opt_iconv_in
!= ICONV_NONE
) {
3136 ICONV_CONST
char *inbuf
= line
;
3137 size_t inlen
= strlen(line
) + 1;
3139 char *outbuf
= out_buffer
;
3140 size_t outlen
= sizeof(out_buffer
);
3144 ret
= iconv(opt_iconv_in
, &inbuf
, &inlen
, &outbuf
, &outlen
);
3145 if (ret
!= (size_t) -1)
3149 if (!view
->ops
->read(view
, line
)) {
3150 report("Allocation failure");
3151 end_update(view
, TRUE
);
3157 unsigned long lines
= view
->lines
;
3160 for (digits
= 0; lines
; digits
++)
3163 /* Keep the displayed view in sync with line number scaling. */
3164 if (digits
!= view
->digits
) {
3165 view
->digits
= digits
;
3166 if (opt_line_number
|| view
== VIEW(REQ_VIEW_BLAME
))
3171 if (io_error(view
->pipe
)) {
3172 report("Failed to read: %s", io_strerror(view
->pipe
));
3173 end_update(view
, TRUE
);
3175 } else if (io_eof(view
->pipe
)) {
3177 end_update(view
, FALSE
);
3180 if (restore_view_position(view
))
3183 if (!view_is_displayed(view
))
3187 redraw_view_from(view
, 0);
3189 redraw_view_dirty(view
);
3191 /* Update the title _after_ the redraw so that if the redraw picks up a
3192 * commit reference in view->ref it'll be available here. */
3193 update_view_title(view
);
3197 DEFINE_ALLOCATOR(realloc_lines
, struct line
, 256)
3199 static struct line
*
3200 add_line_data(struct view
*view
, void *data
, enum line_type type
)
3204 if (!realloc_lines(&view
->line
, view
->lines
, 1))
3207 line
= &view
->line
[view
->lines
++];
3208 memset(line
, 0, sizeof(*line
));
3216 static struct line
*
3217 add_line_text(struct view
*view
, const char *text
, enum line_type type
)
3219 char *data
= text
? strdup(text
) : NULL
;
3221 return data
? add_line_data(view
, data
, type
) : NULL
;
3224 static struct line
*
3225 add_line_format(struct view
*view
, enum line_type type
, const char *fmt
, ...)
3227 char buf
[SIZEOF_STR
];
3230 va_start(args
, fmt
);
3231 if (vsnprintf(buf
, sizeof(buf
), fmt
, args
) >= sizeof(buf
))
3235 return buf
[0] ? add_line_text(view
, buf
, type
) : NULL
;
3243 OPEN_DEFAULT
= 0, /* Use default view switching. */
3244 OPEN_SPLIT
= 1, /* Split current view. */
3245 OPEN_RELOAD
= 4, /* Reload view even if it is the current. */
3246 OPEN_REFRESH
= 16, /* Refresh view using previous command. */
3247 OPEN_PREPARED
= 32, /* Open already prepared command. */
3251 open_view(struct view
*prev
, enum request request
, enum open_flags flags
)
3253 bool split
= !!(flags
& OPEN_SPLIT
);
3254 bool reload
= !!(flags
& (OPEN_RELOAD
| OPEN_REFRESH
| OPEN_PREPARED
));
3255 bool nomaximize
= !!(flags
& OPEN_REFRESH
);
3256 struct view
*view
= VIEW(request
);
3257 int nviews
= displayed_views();
3258 struct view
*base_view
= display
[0];
3260 if (view
== prev
&& nviews
== 1 && !reload
) {
3261 report("Already in %s view", view
->name
);
3265 if (view
->git_dir
&& !opt_git_dir
[0]) {
3266 report("The %s view is disabled in pager view", view
->name
);
3273 } else if (!nomaximize
) {
3274 /* Maximize the current view. */
3275 memset(display
, 0, sizeof(display
));
3277 display
[current_view
] = view
;
3280 /* No parent signals that this is the first loaded view. */
3281 if (prev
&& view
!= prev
) {
3282 view
->parent
= prev
;
3285 /* Resize the view when switching between split- and full-screen,
3286 * or when switching between two different full-screen views. */
3287 if (nviews
!= displayed_views() ||
3288 (nviews
== 1 && base_view
!= display
[0]))
3291 if (view
->ops
->open
) {
3293 end_update(view
, TRUE
);
3294 if (!view
->ops
->open(view
)) {
3295 report("Failed to load %s view", view
->name
);
3298 restore_view_position(view
);
3300 } else if ((reload
|| strcmp(view
->vid
, view
->id
)) &&
3301 !begin_update(view
, flags
& (OPEN_REFRESH
| OPEN_PREPARED
))) {
3302 report("Failed to load %s view", view
->name
);
3306 if (split
&& prev
->lineno
- prev
->offset
>= prev
->height
) {
3307 /* Take the title line into account. */
3308 int lines
= prev
->lineno
- prev
->offset
- prev
->height
+ 1;
3310 /* Scroll the view that was split if the current line is
3311 * outside the new limited view. */
3312 do_scroll_view(prev
, lines
);
3315 if (prev
&& view
!= prev
&& split
&& view_is_displayed(prev
)) {
3316 /* "Blur" the previous view. */
3317 update_view_title(prev
);
3320 if (view
->pipe
&& view
->lines
== 0) {
3321 /* Clear the old view and let the incremental updating refill
3324 view
->p_restore
= flags
& (OPEN_RELOAD
| OPEN_REFRESH
);
3326 } else if (view_is_displayed(view
)) {
3333 open_external_viewer(const char *argv
[], const char *dir
)
3335 def_prog_mode(); /* save current tty modes */
3336 endwin(); /* restore original tty modes */
3337 run_io_fg(argv
, dir
);
3338 fprintf(stderr
, "Press Enter to continue");
3341 redraw_display(TRUE
);
3345 open_mergetool(const char *file
)
3347 const char *mergetool_argv
[] = { "git", "mergetool", file
, NULL
};
3349 open_external_viewer(mergetool_argv
, opt_cdup
);
3353 open_editor(const char *file
)
3355 const char *editor_argv
[] = { "vi", file
, NULL
};
3358 editor
= getenv("GIT_EDITOR");
3359 if (!editor
&& *opt_editor
)
3360 editor
= opt_editor
;
3362 editor
= getenv("VISUAL");
3364 editor
= getenv("EDITOR");
3368 editor_argv
[0] = editor
;
3369 open_external_viewer(editor_argv
, opt_cdup
);
3373 open_run_request(enum request request
)
3375 struct run_request
*req
= get_run_request(request
);
3376 const char *argv
[ARRAY_SIZE(req
->argv
)] = { NULL
};
3379 report("Unknown run request");
3383 if (format_argv(argv
, req
->argv
, FORMAT_ALL
))
3384 open_external_viewer(argv
, NULL
);
3389 * User request switch noodle
3393 view_driver(struct view
*view
, enum request request
)
3397 if (request
== REQ_NONE
)
3400 if (request
> REQ_NONE
) {
3401 open_run_request(request
);
3402 /* FIXME: When all views can refresh always do this. */
3403 if (view
== VIEW(REQ_VIEW_STATUS
) ||
3404 view
== VIEW(REQ_VIEW_MAIN
) ||
3405 view
== VIEW(REQ_VIEW_LOG
) ||
3406 view
== VIEW(REQ_VIEW_BRANCH
) ||
3407 view
== VIEW(REQ_VIEW_STAGE
))
3408 request
= REQ_REFRESH
;
3413 if (view
&& view
->lines
) {
3414 request
= view
->ops
->request(view
, request
, &view
->line
[view
->lineno
]);
3415 if (request
== REQ_NONE
)
3422 case REQ_MOVE_PAGE_UP
:
3423 case REQ_MOVE_PAGE_DOWN
:
3424 case REQ_MOVE_FIRST_LINE
:
3425 case REQ_MOVE_LAST_LINE
:
3426 move_view(view
, request
);
3429 case REQ_SCROLL_LEFT
:
3430 case REQ_SCROLL_RIGHT
:
3431 case REQ_SCROLL_LINE_DOWN
:
3432 case REQ_SCROLL_LINE_UP
:
3433 case REQ_SCROLL_PAGE_DOWN
:
3434 case REQ_SCROLL_PAGE_UP
:
3435 scroll_view(view
, request
);
3438 case REQ_VIEW_BLAME
:
3440 report("No file chosen, press %s to open tree view",
3441 get_key(view
->keymap
, REQ_VIEW_TREE
));
3444 open_view(view
, request
, OPEN_DEFAULT
);
3449 report("No file chosen, press %s to open tree view",
3450 get_key(view
->keymap
, REQ_VIEW_TREE
));
3453 open_view(view
, request
, OPEN_DEFAULT
);
3456 case REQ_VIEW_PAGER
:
3457 if (!VIEW(REQ_VIEW_PAGER
)->pipe
&& !VIEW(REQ_VIEW_PAGER
)->lines
) {
3458 report("No pager content, press %s to run command from prompt",
3459 get_key(view
->keymap
, REQ_PROMPT
));
3462 open_view(view
, request
, OPEN_DEFAULT
);
3465 case REQ_VIEW_STAGE
:
3466 if (!VIEW(REQ_VIEW_STAGE
)->lines
) {
3467 report("No stage content, press %s to open the status view and choose file",
3468 get_key(view
->keymap
, REQ_VIEW_STATUS
));
3471 open_view(view
, request
, OPEN_DEFAULT
);
3474 case REQ_VIEW_STATUS
:
3475 if (opt_is_inside_work_tree
== FALSE
) {
3476 report("The status view requires a working tree");
3479 open_view(view
, request
, OPEN_DEFAULT
);
3487 case REQ_VIEW_BRANCH
:
3488 open_view(view
, request
, OPEN_DEFAULT
);
3493 request
= request
== REQ_NEXT
? REQ_MOVE_DOWN
: REQ_MOVE_UP
;
3495 if ((view
== VIEW(REQ_VIEW_DIFF
) &&
3496 view
->parent
== VIEW(REQ_VIEW_MAIN
)) ||
3497 (view
== VIEW(REQ_VIEW_DIFF
) &&
3498 view
->parent
== VIEW(REQ_VIEW_BLAME
)) ||
3499 (view
== VIEW(REQ_VIEW_STAGE
) &&
3500 view
->parent
== VIEW(REQ_VIEW_STATUS
)) ||
3501 (view
== VIEW(REQ_VIEW_BLOB
) &&
3502 view
->parent
== VIEW(REQ_VIEW_TREE
)) ||
3503 (view
== VIEW(REQ_VIEW_MAIN
) &&
3504 view
->parent
== VIEW(REQ_VIEW_BRANCH
))) {
3507 view
= view
->parent
;
3508 line
= view
->lineno
;
3509 move_view(view
, request
);
3510 if (view_is_displayed(view
))
3511 update_view_title(view
);
3512 if (line
!= view
->lineno
)
3513 view
->ops
->request(view
, REQ_ENTER
,
3514 &view
->line
[view
->lineno
]);
3517 move_view(view
, request
);
3523 int nviews
= displayed_views();
3524 int next_view
= (current_view
+ 1) % nviews
;
3526 if (next_view
== current_view
) {
3527 report("Only one view is displayed");
3531 current_view
= next_view
;
3532 /* Blur out the title of the previous view. */
3533 update_view_title(view
);
3538 report("Refreshing is not yet supported for the %s view", view
->name
);
3542 if (displayed_views() == 2)
3543 maximize_view(view
);
3550 case REQ_TOGGLE_LINENO
:
3551 toggle_view_option(&opt_line_number
, "line numbers");
3554 case REQ_TOGGLE_DATE
:
3558 case REQ_TOGGLE_AUTHOR
:
3562 case REQ_TOGGLE_REV_GRAPH
:
3563 toggle_view_option(&opt_rev_graph
, "revision graph display");
3566 case REQ_TOGGLE_REFS
:
3567 toggle_view_option(&opt_show_refs
, "reference display");
3570 case REQ_TOGGLE_SORT_FIELD
:
3571 case REQ_TOGGLE_SORT_ORDER
:
3572 report("Sorting is not yet supported for the %s view", view
->name
);
3576 case REQ_SEARCH_BACK
:
3577 search_view(view
, request
);
3582 find_next(view
, request
);
3585 case REQ_STOP_LOADING
:
3586 for (i
= 0; i
< ARRAY_SIZE(views
); i
++) {
3589 report("Stopped loading the %s view", view
->name
),
3590 end_update(view
, TRUE
);
3594 case REQ_SHOW_VERSION
:
3595 report("tig-%s (built %s)", TIG_VERSION
, __DATE__
);
3598 case REQ_SCREEN_REDRAW
:
3599 redraw_display(TRUE
);
3603 report("Nothing to edit");
3607 report("Nothing to enter");
3610 case REQ_VIEW_CLOSE
:
3611 /* XXX: Mark closed views by letting view->parent point to the
3612 * view itself. Parents to closed view should never be
3615 view
->parent
->parent
!= view
->parent
) {
3616 maximize_view(view
->parent
);
3617 view
->parent
= view
;
3625 report("Unknown key, press %s for help",
3626 get_key(view
->keymap
, REQ_VIEW_HELP
));
3635 * View backend utilities
3645 const enum sort_field
*fields
;
3646 size_t size
, current
;
3650 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3651 #define get_sort_field(state) ((state).fields[(state).current])
3652 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3655 sort_view(struct view
*view
, enum request request
, struct sort_state
*state
,
3656 int (*compare
)(const void *, const void *))
3659 case REQ_TOGGLE_SORT_FIELD
:
3660 state
->current
= (state
->current
+ 1) % state
->size
;
3663 case REQ_TOGGLE_SORT_ORDER
:
3664 state
->reverse
= !state
->reverse
;
3667 die("Not a sort request");
3670 qsort(view
->line
, view
->lines
, sizeof(*view
->line
), compare
);
3674 DEFINE_ALLOCATOR(realloc_authors
, const char *, 256)
3676 /* Small author cache to reduce memory consumption. It uses binary
3677 * search to lookup or find place to position new entries. No entries
3678 * are ever freed. */
3680 get_author(const char *name
)
3682 static const char **authors
;
3683 static size_t authors_size
;
3684 int from
= 0, to
= authors_size
- 1;
3686 while (from
<= to
) {
3687 size_t pos
= (to
+ from
) / 2;
3688 int cmp
= strcmp(name
, authors
[pos
]);
3691 return authors
[pos
];
3699 if (!realloc_authors(&authors
, authors_size
, 1))
3701 name
= strdup(name
);
3705 memmove(authors
+ from
+ 1, authors
+ from
, (authors_size
- from
) * sizeof(*authors
));
3706 authors
[from
] = name
;
3713 parse_timesec(struct time
*time
, const char *sec
)
3715 time
->sec
= (time_t) atol(sec
);
3719 parse_timezone(struct time
*time
, const char *zone
)
3723 tz
= ('0' - zone
[1]) * 60 * 60 * 10;
3724 tz
+= ('0' - zone
[2]) * 60 * 60;
3725 tz
+= ('0' - zone
[3]) * 60;
3726 tz
+= ('0' - zone
[4]);
3735 /* Parse author lines where the name may be empty:
3736 * author <email@address.tld> 1138474660 +0100
3739 parse_author_line(char *ident
, const char **author
, struct time
*time
)
3741 char *nameend
= strchr(ident
, '<');
3742 char *emailend
= strchr(ident
, '>');
3744 if (nameend
&& emailend
)
3745 *nameend
= *emailend
= 0;
3746 ident
= chomp_string(ident
);
3749 ident
= chomp_string(nameend
+ 1);
3754 *author
= get_author(ident
);
3756 /* Parse epoch and timezone */
3757 if (emailend
&& emailend
[1] == ' ') {
3758 char *secs
= emailend
+ 2;
3759 char *zone
= strchr(secs
, ' ');
3761 parse_timesec(time
, secs
);
3763 if (zone
&& strlen(zone
) == STRING_SIZE(" +0700"))
3764 parse_timezone(time
, zone
+ 1);
3769 open_commit_parent_menu(char buf
[SIZEOF_STR
], int *parents
)
3771 char rev
[SIZEOF_REV
];
3772 const char *revlist_argv
[] = {
3773 "git", "log", "--no-color", "-1", "--pretty=format:%s", rev
, NULL
3775 struct menu_item
*items
;
3776 char text
[SIZEOF_STR
];
3780 items
= calloc(*parents
+ 1, sizeof(*items
));
3784 for (i
= 0; i
< *parents
; i
++) {
3785 string_copy_rev(rev
, &buf
[SIZEOF_REV
* i
]);
3786 if (!run_io_buf(revlist_argv
, text
, sizeof(text
)) ||
3787 !(items
[i
].text
= strdup(text
))) {
3795 ok
= prompt_menu("Select parent", items
, parents
);
3797 for (i
= 0; items
[i
].text
; i
++)
3798 free((char *) items
[i
].text
);
3804 select_commit_parent(const char *id
, char rev
[SIZEOF_REV
], const char *path
)
3806 char buf
[SIZEOF_STR
* 4];
3807 const char *revlist_argv
[] = {
3808 "git", "log", "--no-color", "-1",
3809 "--pretty=format:%P", id
, "--", path
, NULL
3813 if (!run_io_buf(revlist_argv
, buf
, sizeof(buf
)) ||
3814 (parents
= strlen(buf
) / 40) < 0) {
3815 report("Failed to get parent information");
3818 } else if (parents
== 0) {
3820 report("Path '%s' does not exist in the parent", path
);
3822 report("The selected commit has no parents");
3826 if (parents
> 1 && !open_commit_parent_menu(buf
, &parents
))
3829 string_copy_rev(rev
, &buf
[41 * parents
]);
3838 pager_draw(struct view
*view
, struct line
*line
, unsigned int lineno
)
3840 char text
[SIZEOF_STR
];
3842 if (opt_line_number
&& draw_lineno(view
, lineno
))
3845 string_expand(text
, sizeof(text
), line
->data
, opt_tab_size
);
3846 draw_text(view
, line
->type
, text
, TRUE
);
3851 add_describe_ref(char *buf
, size_t *bufpos
, const char *commit_id
, const char *sep
)
3853 const char *describe_argv
[] = { "git", "describe", commit_id
, NULL
};
3854 char ref
[SIZEOF_STR
];
3856 if (!run_io_buf(describe_argv
, ref
, sizeof(ref
)) || !*ref
)
3859 /* This is the only fatal call, since it can "corrupt" the buffer. */
3860 if (!string_nformat(buf
, SIZEOF_STR
, bufpos
, "%s%s", sep
, ref
))
3867 add_pager_refs(struct view
*view
, struct line
*line
)
3869 char buf
[SIZEOF_STR
];
3870 char *commit_id
= (char *)line
->data
+ STRING_SIZE("commit ");
3871 struct ref_list
*list
;
3872 size_t bufpos
= 0, i
;
3873 const char *sep
= "Refs: ";
3874 bool is_tag
= FALSE
;
3876 assert(line
->type
== LINE_COMMIT
);
3878 list
= get_ref_list(commit_id
);
3880 if (view
== VIEW(REQ_VIEW_DIFF
))
3881 goto try_add_describe_ref
;
3885 for (i
= 0; i
< list
->size
; i
++) {
3886 struct ref
*ref
= list
->refs
[i
];
3887 const char *fmt
= ref
->tag
? "%s[%s]" :
3888 ref
->remote
? "%s<%s>" : "%s%s";
3890 if (!string_format_from(buf
, &bufpos
, fmt
, sep
, ref
->name
))
3897 if (!is_tag
&& view
== VIEW(REQ_VIEW_DIFF
)) {
3898 try_add_describe_ref
:
3899 /* Add <tag>-g<commit_id> "fake" reference. */
3900 if (!add_describe_ref(buf
, &bufpos
, commit_id
, sep
))
3907 add_line_text(view
, buf
, LINE_PP_REFS
);
3911 pager_read(struct view
*view
, char *data
)
3918 line
= add_line_text(view
, data
, get_line_type(data
));
3922 if (line
->type
== LINE_COMMIT
&&
3923 (view
== VIEW(REQ_VIEW_DIFF
) ||
3924 view
== VIEW(REQ_VIEW_LOG
)))
3925 add_pager_refs(view
, line
);
3931 pager_request(struct view
*view
, enum request request
, struct line
*line
)
3935 if (request
!= REQ_ENTER
)
3938 if (line
->type
== LINE_COMMIT
&&
3939 (view
== VIEW(REQ_VIEW_LOG
) ||
3940 view
== VIEW(REQ_VIEW_PAGER
))) {
3941 open_view(view
, REQ_VIEW_DIFF
, OPEN_SPLIT
);
3945 /* Always scroll the view even if it was split. That way
3946 * you can use Enter to scroll through the log view and
3947 * split open each commit diff. */
3948 scroll_view(view
, REQ_SCROLL_LINE_DOWN
);
3950 /* FIXME: A minor workaround. Scrolling the view will call report("")
3951 * but if we are scrolling a non-current view this won't properly
3952 * update the view title. */
3954 update_view_title(view
);
3960 pager_grep(struct view
*view
, struct line
*line
)
3962 const char *text
[] = { line
->data
, NULL
};
3964 return grep_text(view
, text
);
3968 pager_select(struct view
*view
, struct line
*line
)
3970 if (line
->type
== LINE_COMMIT
) {
3971 char *text
= (char *)line
->data
+ STRING_SIZE("commit ");
3973 if (view
!= VIEW(REQ_VIEW_PAGER
))
3974 string_copy_rev(view
->ref
, text
);
3975 string_copy_rev(ref_commit
, text
);
3979 static struct view_ops pager_ops
= {
3990 static const char *log_argv
[SIZEOF_ARG
] = {
3991 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
3995 log_request(struct view
*view
, enum request request
, struct line
*line
)
4000 open_view(view
, REQ_VIEW_LOG
, OPEN_REFRESH
);
4003 return pager_request(view
, request
, line
);
4007 static struct view_ops log_ops
= {
4018 static const char *diff_argv
[SIZEOF_ARG
] = {
4019 "git", "show", "--pretty=fuller", "--no-color", "--root",
4020 "--patch-with-stat", "--find-copies-harder", "-C", "%(commit)", NULL
4023 static struct view_ops diff_ops
= {
4038 static bool help_keymap_hidden
[ARRAY_SIZE(keymap_table
)];
4041 help_open_keymap_title(struct view
*view
, enum keymap keymap
)
4045 line
= add_line_format(view
, LINE_HELP_KEYMAP
, "[%c] %s bindings",
4046 help_keymap_hidden
[keymap
] ? '+' : '-',
4047 enum_name(keymap_table
[keymap
]));
4049 line
->other
= keymap
;
4051 return help_keymap_hidden
[keymap
];
4055 help_open_keymap(struct view
*view
, enum keymap keymap
)
4057 const char *group
= NULL
;
4058 char buf
[SIZEOF_STR
];
4060 bool add_title
= TRUE
;
4063 for (i
= 0; i
< ARRAY_SIZE(req_info
); i
++) {
4064 const char *key
= NULL
;
4066 if (req_info
[i
].request
== REQ_NONE
)
4069 if (!req_info
[i
].request
) {
4070 group
= req_info
[i
].help
;
4074 key
= get_keys(keymap
, req_info
[i
].request
, TRUE
);
4078 if (add_title
&& help_open_keymap_title(view
, keymap
))
4083 add_line_text(view
, group
, LINE_HELP_GROUP
);
4087 add_line_format(view
, LINE_DEFAULT
, " %-25s %-20s %s", key
,
4088 enum_name(req_info
[i
]), req_info
[i
].help
);
4091 group
= "External commands:";
4093 for (i
= 0; i
< run_requests
; i
++) {
4094 struct run_request
*req
= get_run_request(REQ_NONE
+ i
+ 1);
4098 if (!req
|| req
->keymap
!= keymap
)
4101 key
= get_key_name(req
->key
);
4103 key
= "(no key defined)";
4105 if (add_title
&& help_open_keymap_title(view
, keymap
))
4108 add_line_text(view
, group
, LINE_HELP_GROUP
);
4112 for (bufpos
= 0, argc
= 0; req
->argv
[argc
]; argc
++)
4113 if (!string_format_from(buf
, &bufpos
, "%s%s",
4114 argc
? " " : "", req
->argv
[argc
]))
4117 add_line_format(view
, LINE_DEFAULT
, " %-25s `%s`", key
, buf
);
4122 help_open(struct view
*view
)
4127 add_line_text(view
, "Quick reference for tig keybindings:", LINE_DEFAULT
);
4128 add_line_text(view
, "", LINE_DEFAULT
);
4130 for (keymap
= 0; keymap
< ARRAY_SIZE(keymap_table
); keymap
++)
4131 help_open_keymap(view
, keymap
);
4137 help_request(struct view
*view
, enum request request
, struct line
*line
)
4141 if (line
->type
== LINE_HELP_KEYMAP
) {
4142 help_keymap_hidden
[line
->other
] =
4143 !help_keymap_hidden
[line
->other
];
4144 view
->p_restore
= TRUE
;
4145 open_view(view
, REQ_VIEW_HELP
, OPEN_REFRESH
);
4150 return pager_request(view
, request
, line
);
4154 static struct view_ops help_ops
= {
4170 struct tree_stack_entry
{
4171 struct tree_stack_entry
*prev
; /* Entry below this in the stack */
4172 unsigned long lineno
; /* Line number to restore */
4173 char *name
; /* Position of name in opt_path */
4176 /* The top of the path stack. */
4177 static struct tree_stack_entry
*tree_stack
= NULL
;
4178 unsigned long tree_lineno
= 0;
4181 pop_tree_stack_entry(void)
4183 struct tree_stack_entry
*entry
= tree_stack
;
4185 tree_lineno
= entry
->lineno
;
4187 tree_stack
= entry
->prev
;
4192 push_tree_stack_entry(const char *name
, unsigned long lineno
)
4194 struct tree_stack_entry
*entry
= calloc(1, sizeof(*entry
));
4195 size_t pathlen
= strlen(opt_path
);
4200 entry
->prev
= tree_stack
;
4201 entry
->name
= opt_path
+ pathlen
;
4204 if (!string_format_from(opt_path
, &pathlen
, "%s/", name
)) {
4205 pop_tree_stack_entry();
4209 /* Move the current line to the first tree entry. */
4211 entry
->lineno
= lineno
;
4214 /* Parse output from git-ls-tree(1):
4216 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4219 #define SIZEOF_TREE_ATTR \
4220 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4222 #define SIZEOF_TREE_MODE \
4223 STRING_SIZE("100644 ")
4225 #define TREE_ID_OFFSET \
4226 STRING_SIZE("100644 blob ")
4229 char id
[SIZEOF_REV
];
4231 struct time time
; /* Date from the author ident. */
4232 const char *author
; /* Author of the commit. */
4237 tree_path(const struct line
*line
)
4239 return ((struct tree_entry
*) line
->data
)->name
;
4243 tree_compare_entry(const struct line
*line1
, const struct line
*line2
)
4245 if (line1
->type
!= line2
->type
)
4246 return line1
->type
== LINE_TREE_DIR
? -1 : 1;
4247 return strcmp(tree_path(line1
), tree_path(line2
));
4250 static const enum sort_field tree_sort_fields
[] = {
4251 ORDERBY_NAME
, ORDERBY_DATE
, ORDERBY_AUTHOR
4253 static struct sort_state tree_sort_state
= SORT_STATE(tree_sort_fields
);
4256 tree_compare(const void *l1
, const void *l2
)
4258 const struct line
*line1
= (const struct line
*) l1
;
4259 const struct line
*line2
= (const struct line
*) l2
;
4260 const struct tree_entry
*entry1
= ((const struct line
*) l1
)->data
;
4261 const struct tree_entry
*entry2
= ((const struct line
*) l2
)->data
;
4263 if (line1
->type
== LINE_TREE_HEAD
)
4265 if (line2
->type
== LINE_TREE_HEAD
)
4268 switch (get_sort_field(tree_sort_state
)) {
4270 return sort_order(tree_sort_state
, timecmp(&entry1
->time
, &entry2
->time
));
4272 case ORDERBY_AUTHOR
:
4273 return sort_order(tree_sort_state
, strcmp(entry1
->author
, entry2
->author
));
4277 return sort_order(tree_sort_state
, tree_compare_entry(line1
, line2
));
4282 static struct line
*
4283 tree_entry(struct view
*view
, enum line_type type
, const char *path
,
4284 const char *mode
, const char *id
)
4286 struct tree_entry
*entry
= calloc(1, sizeof(*entry
) + strlen(path
));
4287 struct line
*line
= entry
? add_line_data(view
, entry
, type
) : NULL
;
4289 if (!entry
|| !line
) {
4294 strncpy(entry
->name
, path
, strlen(path
));
4296 entry
->mode
= strtoul(mode
, NULL
, 8);
4298 string_copy_rev(entry
->id
, id
);
4304 tree_read_date(struct view
*view
, char *text
, bool *read_date
)
4306 static const char *author_name
;
4307 static struct time author_time
;
4309 if (!text
&& *read_date
) {
4314 char *path
= *opt_path
? opt_path
: ".";
4315 /* Find next entry to process */
4316 const char *log_file
[] = {
4317 "git", "log", "--no-color", "--pretty=raw",
4318 "--cc", "--raw", view
->id
, "--", path
, NULL
4323 tree_entry(view
, LINE_TREE_HEAD
, opt_path
, NULL
, NULL
);
4324 report("Tree is empty");
4328 if (!run_io_rd(&io
, log_file
, opt_cdup
, FORMAT_NONE
)) {
4329 report("Failed to load tree data");
4333 done_io(view
->pipe
);
4338 } else if (*text
== 'a' && get_line_type(text
) == LINE_AUTHOR
) {
4339 parse_author_line(text
+ STRING_SIZE("author "),
4340 &author_name
, &author_time
);
4342 } else if (*text
== ':') {
4344 size_t annotated
= 1;
4347 pos
= strchr(text
, '\t');
4351 if (*opt_path
&& !strncmp(text
, opt_path
, strlen(opt_path
)))
4352 text
+= strlen(opt_path
);
4353 pos
= strchr(text
, '/');
4357 for (i
= 1; i
< view
->lines
; i
++) {
4358 struct line
*line
= &view
->line
[i
];
4359 struct tree_entry
*entry
= line
->data
;
4361 annotated
+= !!entry
->author
;
4362 if (entry
->author
|| strcmp(entry
->name
, text
))
4365 entry
->author
= author_name
;
4366 entry
->time
= author_time
;
4371 if (annotated
== view
->lines
)
4372 kill_io(view
->pipe
);
4378 tree_read(struct view
*view
, char *text
)
4380 static bool read_date
= FALSE
;
4381 struct tree_entry
*data
;
4382 struct line
*entry
, *line
;
4383 enum line_type type
;
4384 size_t textlen
= text
? strlen(text
) : 0;
4385 char *path
= text
+ SIZEOF_TREE_ATTR
;
4387 if (read_date
|| !text
)
4388 return tree_read_date(view
, text
, &read_date
);
4390 if (textlen
<= SIZEOF_TREE_ATTR
)
4392 if (view
->lines
== 0 &&
4393 !tree_entry(view
, LINE_TREE_HEAD
, opt_path
, NULL
, NULL
))
4396 /* Strip the path part ... */
4398 size_t pathlen
= textlen
- SIZEOF_TREE_ATTR
;
4399 size_t striplen
= strlen(opt_path
);
4401 if (pathlen
> striplen
)
4402 memmove(path
, path
+ striplen
,
4403 pathlen
- striplen
+ 1);
4405 /* Insert "link" to parent directory. */
4406 if (view
->lines
== 1 &&
4407 !tree_entry(view
, LINE_TREE_DIR
, "..", "040000", view
->ref
))
4411 type
= text
[SIZEOF_TREE_MODE
] == 't' ? LINE_TREE_DIR
: LINE_TREE_FILE
;
4412 entry
= tree_entry(view
, type
, path
, text
, text
+ TREE_ID_OFFSET
);
4417 /* Skip "Directory ..." and ".." line. */
4418 for (line
= &view
->line
[1 + !!*opt_path
]; line
< entry
; line
++) {
4419 if (tree_compare_entry(line
, entry
) <= 0)
4422 memmove(line
+ 1, line
, (entry
- line
) * sizeof(*entry
));
4426 for (; line
<= entry
; line
++)
4427 line
->dirty
= line
->cleareol
= 1;
4431 if (tree_lineno
> view
->lineno
) {
4432 view
->lineno
= tree_lineno
;
4440 tree_draw(struct view
*view
, struct line
*line
, unsigned int lineno
)
4442 struct tree_entry
*entry
= line
->data
;
4444 if (line
->type
== LINE_TREE_HEAD
) {
4445 if (draw_text(view
, line
->type
, "Directory path /", TRUE
))
4448 if (draw_mode(view
, entry
->mode
))
4451 if (opt_author
&& draw_author(view
, entry
->author
))
4454 if (opt_date
&& draw_date(view
, &entry
->time
))
4457 if (draw_text(view
, line
->type
, entry
->name
, TRUE
))
4465 char file
[SIZEOF_STR
] = "/tmp/tigblob.XXXXXX";
4466 int fd
= mkstemp(file
);
4469 report("Failed to create temporary file");
4470 else if (!run_io_append(blob_ops
.argv
, FORMAT_ALL
, fd
))
4471 report("Failed to save blob data to file");
4479 tree_request(struct view
*view
, enum request request
, struct line
*line
)
4481 enum open_flags flags
;
4484 case REQ_VIEW_BLAME
:
4485 if (line
->type
!= LINE_TREE_FILE
) {
4486 report("Blame only supported for files");
4490 string_copy(opt_ref
, view
->vid
);
4494 if (line
->type
!= LINE_TREE_FILE
) {
4495 report("Edit only supported for files");
4496 } else if (!is_head_commit(view
->vid
)) {
4499 open_editor(opt_file
);
4503 case REQ_TOGGLE_SORT_FIELD
:
4504 case REQ_TOGGLE_SORT_ORDER
:
4505 sort_view(view
, request
, &tree_sort_state
, tree_compare
);
4510 /* quit view if at top of tree */
4511 return REQ_VIEW_CLOSE
;
4514 line
= &view
->line
[1];
4524 /* Cleanup the stack if the tree view is at a different tree. */
4525 while (!*opt_path
&& tree_stack
)
4526 pop_tree_stack_entry();
4528 switch (line
->type
) {
4530 /* Depending on whether it is a subdirectory or parent link
4531 * mangle the path buffer. */
4532 if (line
== &view
->line
[1] && *opt_path
) {
4533 pop_tree_stack_entry();
4536 const char *basename
= tree_path(line
);
4538 push_tree_stack_entry(basename
, view
->lineno
);
4541 /* Trees and subtrees share the same ID, so they are not not
4542 * unique like blobs. */
4543 flags
= OPEN_RELOAD
;
4544 request
= REQ_VIEW_TREE
;
4547 case LINE_TREE_FILE
:
4548 flags
= display
[0] == view
? OPEN_SPLIT
: OPEN_DEFAULT
;
4549 request
= REQ_VIEW_BLOB
;
4556 open_view(view
, request
, flags
);
4557 if (request
== REQ_VIEW_TREE
)
4558 view
->lineno
= tree_lineno
;
4564 tree_grep(struct view
*view
, struct line
*line
)
4566 struct tree_entry
*entry
= line
->data
;
4567 const char *text
[] = {
4569 opt_author
? entry
->author
: "",
4570 opt_date
? mkdate(&entry
->time
) : "",
4574 return grep_text(view
, text
);
4578 tree_select(struct view
*view
, struct line
*line
)
4580 struct tree_entry
*entry
= line
->data
;
4582 if (line
->type
== LINE_TREE_FILE
) {
4583 string_copy_rev(ref_blob
, entry
->id
);
4584 string_format(opt_file
, "%s%s", opt_path
, tree_path(line
));
4586 } else if (line
->type
!= LINE_TREE_DIR
) {
4590 string_copy_rev(view
->ref
, entry
->id
);
4594 tree_prepare(struct view
*view
)
4596 if (view
->lines
== 0 && opt_prefix
[0]) {
4597 char *pos
= opt_prefix
;
4599 while (pos
&& *pos
) {
4600 char *end
= strchr(pos
, '/');
4604 push_tree_stack_entry(pos
, 0);
4612 } else if (strcmp(view
->vid
, view
->id
)) {
4616 return init_io_rd(&view
->io
, view
->ops
->argv
, opt_cdup
, FORMAT_ALL
);
4619 static const char *tree_argv
[SIZEOF_ARG
] = {
4620 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4623 static struct view_ops tree_ops
= {
4636 blob_read(struct view
*view
, char *line
)
4640 return add_line_text(view
, line
, LINE_DEFAULT
) != NULL
;
4644 blob_request(struct view
*view
, enum request request
, struct line
*line
)
4651 return pager_request(view
, request
, line
);
4655 static const char *blob_argv
[SIZEOF_ARG
] = {
4656 "git", "cat-file", "blob", "%(blob)", NULL
4659 static struct view_ops blob_ops
= {
4673 * Loading the blame view is a two phase job:
4675 * 1. File content is read either using opt_file from the
4676 * filesystem or using git-cat-file.
4677 * 2. Then blame information is incrementally added by
4678 * reading output from git-blame.
4681 static const char *blame_head_argv
[] = {
4682 "git", "blame", "--incremental", "--", "%(file)", NULL
4685 static const char *blame_ref_argv
[] = {
4686 "git", "blame", "--incremental", "%(ref)", "--", "%(file)", NULL
4689 static const char *blame_cat_file_argv
[] = {
4690 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4693 struct blame_commit
{
4694 char id
[SIZEOF_REV
]; /* SHA1 ID. */
4695 char title
[128]; /* First line of the commit message. */
4696 const char *author
; /* Author of the commit. */
4697 struct time time
; /* Date from the author ident. */
4698 char filename
[128]; /* Name of file. */
4699 bool has_previous
; /* Was a "previous" line detected. */
4703 struct blame_commit
*commit
;
4704 unsigned long lineno
;
4709 blame_open(struct view
*view
)
4711 char path
[SIZEOF_STR
];
4713 if (!view
->parent
&& *opt_prefix
) {
4714 string_copy(path
, opt_file
);
4715 if (!string_format(opt_file
, "%s%s", opt_prefix
, path
))
4719 if (*opt_ref
|| !io_open(&view
->io
, "%s%s", opt_cdup
, opt_file
)) {
4720 if (!run_io_rd(&view
->io
, blame_cat_file_argv
, opt_cdup
, FORMAT_ALL
))
4724 setup_update(view
, opt_file
);
4725 string_format(view
->ref
, "%s ...", opt_file
);
4730 static struct blame_commit
*
4731 get_blame_commit(struct view
*view
, const char *id
)
4735 for (i
= 0; i
< view
->lines
; i
++) {
4736 struct blame
*blame
= view
->line
[i
].data
;
4741 if (!strncmp(blame
->commit
->id
, id
, SIZEOF_REV
- 1))
4742 return blame
->commit
;
4746 struct blame_commit
*commit
= calloc(1, sizeof(*commit
));
4749 string_ncopy(commit
->id
, id
, SIZEOF_REV
);
4755 parse_number(const char **posref
, size_t *number
, size_t min
, size_t max
)
4757 const char *pos
= *posref
;
4760 pos
= strchr(pos
+ 1, ' ');
4761 if (!pos
|| !isdigit(pos
[1]))
4763 *number
= atoi(pos
+ 1);
4764 if (*number
< min
|| *number
> max
)
4771 static struct blame_commit
*
4772 parse_blame_commit(struct view
*view
, const char *text
, int *blamed
)
4774 struct blame_commit
*commit
;
4775 struct blame
*blame
;
4776 const char *pos
= text
+ SIZEOF_REV
- 2;
4777 size_t orig_lineno
= 0;
4781 if (strlen(text
) <= SIZEOF_REV
|| pos
[1] != ' ')
4784 if (!parse_number(&pos
, &orig_lineno
, 1, 9999999) ||
4785 !parse_number(&pos
, &lineno
, 1, view
->lines
) ||
4786 !parse_number(&pos
, &group
, 1, view
->lines
- lineno
+ 1))
4789 commit
= get_blame_commit(view
, text
);
4795 struct line
*line
= &view
->line
[lineno
+ group
- 1];
4798 blame
->commit
= commit
;
4799 blame
->lineno
= orig_lineno
+ group
- 1;
4807 blame_read_file(struct view
*view
, const char *line
, bool *read_file
)
4810 const char **argv
= *opt_ref
? blame_ref_argv
: blame_head_argv
;
4813 if (view
->lines
== 0 && !view
->parent
)
4814 die("No blame exist for %s", view
->vid
);
4816 if (view
->lines
== 0 || !run_io_rd(&io
, argv
, opt_cdup
, FORMAT_ALL
)) {
4817 report("Failed to load blame data");
4821 done_io(view
->pipe
);
4827 size_t linelen
= strlen(line
);
4828 struct blame
*blame
= malloc(sizeof(*blame
) + linelen
);
4833 blame
->commit
= NULL
;
4834 strncpy(blame
->text
, line
, linelen
);
4835 blame
->text
[linelen
] = 0;
4836 return add_line_data(view
, blame
, LINE_BLAME_ID
) != NULL
;
4841 match_blame_header(const char *name
, char **line
)
4843 size_t namelen
= strlen(name
);
4844 bool matched
= !strncmp(name
, *line
, namelen
);
4853 blame_read(struct view
*view
, char *line
)
4855 static struct blame_commit
*commit
= NULL
;
4856 static int blamed
= 0;
4857 static bool read_file
= TRUE
;
4860 return blame_read_file(view
, line
, &read_file
);
4867 string_format(view
->ref
, "%s", view
->vid
);
4868 if (view_is_displayed(view
)) {
4869 update_view_title(view
);
4870 redraw_view_from(view
, 0);
4876 commit
= parse_blame_commit(view
, line
, &blamed
);
4877 string_format(view
->ref
, "%s %2d%%", view
->vid
,
4878 view
->lines
? blamed
* 100 / view
->lines
: 0);
4880 } else if (match_blame_header("author ", &line
)) {
4881 commit
->author
= get_author(line
);
4883 } else if (match_blame_header("author-time ", &line
)) {
4884 parse_timesec(&commit
->time
, line
);
4886 } else if (match_blame_header("author-tz ", &line
)) {
4887 parse_timezone(&commit
->time
, line
);
4889 } else if (match_blame_header("summary ", &line
)) {
4890 string_ncopy(commit
->title
, line
, strlen(line
));
4892 } else if (match_blame_header("previous ", &line
)) {
4893 commit
->has_previous
= TRUE
;
4895 } else if (match_blame_header("filename ", &line
)) {
4896 string_ncopy(commit
->filename
, line
, strlen(line
));
4904 blame_draw(struct view
*view
, struct line
*line
, unsigned int lineno
)
4906 struct blame
*blame
= line
->data
;
4907 struct time
*time
= NULL
;
4908 const char *id
= NULL
, *author
= NULL
;
4909 char text
[SIZEOF_STR
];
4911 if (blame
->commit
&& *blame
->commit
->filename
) {
4912 id
= blame
->commit
->id
;
4913 author
= blame
->commit
->author
;
4914 time
= &blame
->commit
->time
;
4917 if (opt_date
&& draw_date(view
, time
))
4920 if (opt_author
&& draw_author(view
, author
))
4923 if (draw_field(view
, LINE_BLAME_ID
, id
, ID_COLS
, FALSE
))
4926 if (draw_lineno(view
, lineno
))
4929 string_expand(text
, sizeof(text
), blame
->text
, opt_tab_size
);
4930 draw_text(view
, LINE_DEFAULT
, text
, TRUE
);
4935 check_blame_commit(struct blame
*blame
, bool check_null_id
)
4938 report("Commit data not loaded yet");
4939 else if (check_null_id
&& !strcmp(blame
->commit
->id
, NULL_ID
))
4940 report("No commit exist for the selected line");
4947 setup_blame_parent_line(struct view
*view
, struct blame
*blame
)
4949 const char *diff_tree_argv
[] = {
4950 "git", "diff-tree", "-U0", blame
->commit
->id
,
4951 "--", blame
->commit
->filename
, NULL
4954 int parent_lineno
= -1;
4955 int blamed_lineno
= -1;
4958 if (!run_io(&io
, diff_tree_argv
, NULL
, IO_RD
))
4961 while ((line
= io_get(&io
, '\n', TRUE
))) {
4963 char *pos
= strchr(line
, '+');
4965 parent_lineno
= atoi(line
+ 4);
4967 blamed_lineno
= atoi(pos
+ 1);
4969 } else if (*line
== '+' && parent_lineno
!= -1) {
4970 if (blame
->lineno
== blamed_lineno
- 1 &&
4971 !strcmp(blame
->text
, line
+ 1)) {
4972 view
->lineno
= parent_lineno
? parent_lineno
- 1 : 0;
4983 blame_request(struct view
*view
, enum request request
, struct line
*line
)
4985 enum open_flags flags
= display
[0] == view
? OPEN_SPLIT
: OPEN_DEFAULT
;
4986 struct blame
*blame
= line
->data
;
4989 case REQ_VIEW_BLAME
:
4990 if (check_blame_commit(blame
, TRUE
)) {
4991 string_copy(opt_ref
, blame
->commit
->id
);
4992 string_copy(opt_file
, blame
->commit
->filename
);
4994 view
->lineno
= blame
->lineno
;
4995 open_view(view
, REQ_VIEW_BLAME
, OPEN_REFRESH
);
5000 if (check_blame_commit(blame
, TRUE
) &&
5001 select_commit_parent(blame
->commit
->id
, opt_ref
,
5002 blame
->commit
->filename
)) {
5003 string_copy(opt_file
, blame
->commit
->filename
);
5004 setup_blame_parent_line(view
, blame
);
5005 open_view(view
, REQ_VIEW_BLAME
, OPEN_REFRESH
);
5010 if (!check_blame_commit(blame
, FALSE
))
5013 if (view_is_displayed(VIEW(REQ_VIEW_DIFF
)) &&
5014 !strcmp(blame
->commit
->id
, VIEW(REQ_VIEW_DIFF
)->ref
))
5017 if (!strcmp(blame
->commit
->id
, NULL_ID
)) {
5018 struct view
*diff
= VIEW(REQ_VIEW_DIFF
);
5019 const char *diff_index_argv
[] = {
5020 "git", "diff-index", "--root", "--patch-with-stat",
5021 "-C", "-M", "HEAD", "--", view
->vid
, NULL
5024 if (!blame
->commit
->has_previous
) {
5025 diff_index_argv
[1] = "diff";
5026 diff_index_argv
[2] = "--no-color";
5027 diff_index_argv
[6] = "--";
5028 diff_index_argv
[7] = "/dev/null";
5031 if (!prepare_update(diff
, diff_index_argv
, NULL
, FORMAT_DASH
)) {
5032 report("Failed to allocate diff command");
5035 flags
|= OPEN_PREPARED
;
5038 open_view(view
, REQ_VIEW_DIFF
, flags
);
5039 if (VIEW(REQ_VIEW_DIFF
)->pipe
&& !strcmp(blame
->commit
->id
, NULL_ID
))
5040 string_copy_rev(VIEW(REQ_VIEW_DIFF
)->ref
, NULL_ID
);
5051 blame_grep(struct view
*view
, struct line
*line
)
5053 struct blame
*blame
= line
->data
;
5054 struct blame_commit
*commit
= blame
->commit
;
5055 const char *text
[] = {
5057 commit
? commit
->title
: "",
5058 commit
? commit
->id
: "",
5059 commit
&& opt_author
? commit
->author
: "",
5060 commit
&& opt_date
? mkdate(&commit
->time
) : "",
5064 return grep_text(view
, text
);
5068 blame_select(struct view
*view
, struct line
*line
)
5070 struct blame
*blame
= line
->data
;
5071 struct blame_commit
*commit
= blame
->commit
;
5076 if (!strcmp(commit
->id
, NULL_ID
))
5077 string_ncopy(ref_commit
, "HEAD", 4);
5079 string_copy_rev(ref_commit
, commit
->id
);
5082 static struct view_ops blame_ops
= {
5098 const char *author
; /* Author of the last commit. */
5099 struct time time
; /* Date of the last activity. */
5100 const struct ref
*ref
; /* Name and commit ID information. */
5103 static const struct ref branch_all
;
5105 static const enum sort_field branch_sort_fields
[] = {
5106 ORDERBY_NAME
, ORDERBY_DATE
, ORDERBY_AUTHOR
5108 static struct sort_state branch_sort_state
= SORT_STATE(branch_sort_fields
);
5111 branch_compare(const void *l1
, const void *l2
)
5113 const struct branch
*branch1
= ((const struct line
*) l1
)->data
;
5114 const struct branch
*branch2
= ((const struct line
*) l2
)->data
;
5116 switch (get_sort_field(branch_sort_state
)) {
5118 return sort_order(branch_sort_state
, timecmp(&branch1
->time
, &branch2
->time
));
5120 case ORDERBY_AUTHOR
:
5121 return sort_order(branch_sort_state
, strcmp(branch1
->author
, branch2
->author
));
5125 return sort_order(branch_sort_state
, strcmp(branch1
->ref
->name
, branch2
->ref
->name
));
5130 branch_draw(struct view
*view
, struct line
*line
, unsigned int lineno
)
5132 struct branch
*branch
= line
->data
;
5133 enum line_type type
= branch
->ref
->head
? LINE_MAIN_HEAD
: LINE_DEFAULT
;
5135 if (opt_date
&& draw_date(view
, &branch
->time
))
5138 if (opt_author
&& draw_author(view
, branch
->author
))
5141 draw_text(view
, type
, branch
->ref
== &branch_all
? "All branches" : branch
->ref
->name
, TRUE
);
5146 branch_request(struct view
*view
, enum request request
, struct line
*line
)
5148 struct branch
*branch
= line
->data
;
5153 open_view(view
, REQ_VIEW_BRANCH
, OPEN_REFRESH
);
5156 case REQ_TOGGLE_SORT_FIELD
:
5157 case REQ_TOGGLE_SORT_ORDER
:
5158 sort_view(view
, request
, &branch_sort_state
, branch_compare
);
5162 if (branch
->ref
== &branch_all
) {
5163 const char *all_branches_argv
[] = {
5164 "git", "log", "--no-color", "--pretty=raw", "--parents",
5165 "--topo-order", "--all", NULL
5167 struct view
*main_view
= VIEW(REQ_VIEW_MAIN
);
5169 if (!prepare_update(main_view
, all_branches_argv
, NULL
, FORMAT_NONE
)) {
5170 report("Failed to load view of all branches");
5173 open_view(view
, REQ_VIEW_MAIN
, OPEN_PREPARED
| OPEN_SPLIT
);
5175 open_view(view
, REQ_VIEW_MAIN
, OPEN_SPLIT
);
5185 branch_read(struct view
*view
, char *line
)
5187 static char id
[SIZEOF_REV
];
5188 struct branch
*reference
;
5194 switch (get_line_type(line
)) {
5196 string_copy_rev(id
, line
+ STRING_SIZE("commit "));
5200 for (i
= 0, reference
= NULL
; i
< view
->lines
; i
++) {
5201 struct branch
*branch
= view
->line
[i
].data
;
5203 if (strcmp(branch
->ref
->id
, id
))
5206 view
->line
[i
].dirty
= TRUE
;
5208 branch
->author
= reference
->author
;
5209 branch
->time
= reference
->time
;
5213 parse_author_line(line
+ STRING_SIZE("author "),
5214 &branch
->author
, &branch
->time
);
5226 branch_open_visitor(void *data
, const struct ref
*ref
)
5228 struct view
*view
= data
;
5229 struct branch
*branch
;
5231 if (ref
->tag
|| ref
->ltag
|| ref
->remote
)
5234 branch
= calloc(1, sizeof(*branch
));
5239 return !!add_line_data(view
, branch
, LINE_DEFAULT
);
5243 branch_open(struct view
*view
)
5245 const char *branch_log
[] = {
5246 "git", "log", "--no-color", "--pretty=raw",
5247 "--simplify-by-decoration", "--all", NULL
5250 if (!run_io_rd(&view
->io
, branch_log
, NULL
, FORMAT_NONE
)) {
5251 report("Failed to load branch data");
5255 setup_update(view
, view
->id
);
5256 branch_open_visitor(view
, &branch_all
);
5257 foreach_ref(branch_open_visitor
, view
);
5258 view
->p_restore
= TRUE
;
5264 branch_grep(struct view
*view
, struct line
*line
)
5266 struct branch
*branch
= line
->data
;
5267 const char *text
[] = {
5273 return grep_text(view
, text
);
5277 branch_select(struct view
*view
, struct line
*line
)
5279 struct branch
*branch
= line
->data
;
5281 string_copy_rev(view
->ref
, branch
->ref
->id
);
5282 string_copy_rev(ref_commit
, branch
->ref
->id
);
5283 string_copy_rev(ref_head
, branch
->ref
->id
);
5286 static struct view_ops branch_ops
= {
5305 char rev
[SIZEOF_REV
];
5306 char name
[SIZEOF_STR
];
5310 char rev
[SIZEOF_REV
];
5311 char name
[SIZEOF_STR
];
5315 static char status_onbranch
[SIZEOF_STR
];
5316 static struct status stage_status
;
5317 static enum line_type stage_line_type
;
5318 static size_t stage_chunks
;
5319 static int *stage_chunk
;
5321 DEFINE_ALLOCATOR(realloc_ints
, int, 32)
5323 /* This should work even for the "On branch" line. */
5325 status_has_none(struct view
*view
, struct line
*line
)
5327 return line
< view
->line
+ view
->lines
&& !line
[1].data
;
5330 /* Get fields from the diff line:
5331 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5334 status_get_diff(struct status
*file
, const char *buf
, size_t bufsize
)
5336 const char *old_mode
= buf
+ 1;
5337 const char *new_mode
= buf
+ 8;
5338 const char *old_rev
= buf
+ 15;
5339 const char *new_rev
= buf
+ 56;
5340 const char *status
= buf
+ 97;
5343 old_mode
[-1] != ':' ||
5344 new_mode
[-1] != ' ' ||
5345 old_rev
[-1] != ' ' ||
5346 new_rev
[-1] != ' ' ||
5350 file
->status
= *status
;
5352 string_copy_rev(file
->old
.rev
, old_rev
);
5353 string_copy_rev(file
->new.rev
, new_rev
);
5355 file
->old
.mode
= strtoul(old_mode
, NULL
, 8);
5356 file
->new.mode
= strtoul(new_mode
, NULL
, 8);
5358 file
->old
.name
[0] = file
->new.name
[0] = 0;
5364 status_run(struct view
*view
, const char *argv
[], char status
, enum line_type type
)
5366 struct status
*unmerged
= NULL
;
5370 if (!run_io(&io
, argv
, opt_cdup
, IO_RD
))
5373 add_line_data(view
, NULL
, type
);
5375 while ((buf
= io_get(&io
, 0, TRUE
))) {
5376 struct status
*file
= unmerged
;
5379 file
= calloc(1, sizeof(*file
));
5380 if (!file
|| !add_line_data(view
, file
, type
))
5384 /* Parse diff info part. */
5386 file
->status
= status
;
5388 string_copy(file
->old
.rev
, NULL_ID
);
5390 } else if (!file
->status
|| file
== unmerged
) {
5391 if (!status_get_diff(file
, buf
, strlen(buf
)))
5394 buf
= io_get(&io
, 0, TRUE
);
5398 /* Collapse all modified entries that follow an
5399 * associated unmerged entry. */
5400 if (unmerged
== file
) {
5401 unmerged
->status
= 'U';
5403 } else if (file
->status
== 'U') {
5408 /* Grab the old name for rename/copy. */
5409 if (!*file
->old
.name
&&
5410 (file
->status
== 'R' || file
->status
== 'C')) {
5411 string_ncopy(file
->old
.name
, buf
, strlen(buf
));
5413 buf
= io_get(&io
, 0, TRUE
);
5418 /* git-ls-files just delivers a NUL separated list of
5419 * file names similar to the second half of the
5420 * git-diff-* output. */
5421 string_ncopy(file
->new.name
, buf
, strlen(buf
));
5422 if (!*file
->old
.name
)
5423 string_copy(file
->old
.name
, file
->new.name
);
5427 if (io_error(&io
)) {
5433 if (!view
->line
[view
->lines
- 1].data
)
5434 add_line_data(view
, NULL
, LINE_STAT_NONE
);
5440 /* Don't show unmerged entries in the staged section. */
5441 static const char *status_diff_index_argv
[] = {
5442 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
5443 "--cached", "-M", "HEAD", NULL
5446 static const char *status_diff_files_argv
[] = {
5447 "git", "diff-files", "-z", NULL
5450 static const char *status_list_other_argv
[] = {
5451 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix
, NULL
5454 static const char *status_list_no_head_argv
[] = {
5455 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5458 static const char *update_index_argv
[] = {
5459 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5462 /* Restore the previous line number to stay in the context or select a
5463 * line with something that can be updated. */
5465 status_restore(struct view
*view
)
5467 if (view
->p_lineno
>= view
->lines
)
5468 view
->p_lineno
= view
->lines
- 1;
5469 while (view
->p_lineno
< view
->lines
&& !view
->line
[view
->p_lineno
].data
)
5471 while (view
->p_lineno
> 0 && !view
->line
[view
->p_lineno
].data
)
5474 /* If the above fails, always skip the "On branch" line. */
5475 if (view
->p_lineno
< view
->lines
)
5476 view
->lineno
= view
->p_lineno
;
5480 if (view
->lineno
< view
->offset
)
5481 view
->offset
= view
->lineno
;
5482 else if (view
->offset
+ view
->height
<= view
->lineno
)
5483 view
->offset
= view
->lineno
- view
->height
+ 1;
5485 view
->p_restore
= FALSE
;
5489 status_update_onbranch(void)
5491 static const char *paths
[][2] = {
5492 { "rebase-apply/rebasing", "Rebasing" },
5493 { "rebase-apply/applying", "Applying mailbox" },
5494 { "rebase-apply/", "Rebasing mailbox" },
5495 { "rebase-merge/interactive", "Interactive rebase" },
5496 { "rebase-merge/", "Rebase merge" },
5497 { "MERGE_HEAD", "Merging" },
5498 { "BISECT_LOG", "Bisecting" },
5499 { "HEAD", "On branch" },
5501 char buf
[SIZEOF_STR
];
5505 if (is_initial_commit()) {
5506 string_copy(status_onbranch
, "Initial commit");
5510 for (i
= 0; i
< ARRAY_SIZE(paths
); i
++) {
5511 char *head
= opt_head
;
5513 if (!string_format(buf
, "%s/%s", opt_git_dir
, paths
[i
][0]) ||
5514 lstat(buf
, &stat
) < 0)
5520 if (io_open(&io
, "%s/rebase-merge/head-name", opt_git_dir
) &&
5521 io_read_buf(&io
, buf
, sizeof(buf
))) {
5523 if (!prefixcmp(head
, "refs/heads/"))
5524 head
+= STRING_SIZE("refs/heads/");
5528 if (!string_format(status_onbranch
, "%s %s", paths
[i
][1], head
))
5529 string_copy(status_onbranch
, opt_head
);
5533 string_copy(status_onbranch
, "Not currently on any branch");
5536 /* First parse staged info using git-diff-index(1), then parse unstaged
5537 * info using git-diff-files(1), and finally untracked files using
5538 * git-ls-files(1). */
5540 status_open(struct view
*view
)
5544 add_line_data(view
, NULL
, LINE_STAT_HEAD
);
5545 status_update_onbranch();
5547 run_io_bg(update_index_argv
);
5549 if (is_initial_commit()) {
5550 if (!status_run(view
, status_list_no_head_argv
, 'A', LINE_STAT_STAGED
))
5552 } else if (!status_run(view
, status_diff_index_argv
, 0, LINE_STAT_STAGED
)) {
5556 if (!status_run(view
, status_diff_files_argv
, 0, LINE_STAT_UNSTAGED
) ||
5557 !status_run(view
, status_list_other_argv
, '?', LINE_STAT_UNTRACKED
))
5560 /* Restore the exact position or use the specialized restore
5562 if (!view
->p_restore
)
5563 status_restore(view
);
5568 status_draw(struct view
*view
, struct line
*line
, unsigned int lineno
)
5570 struct status
*status
= line
->data
;
5571 enum line_type type
;
5575 switch (line
->type
) {
5576 case LINE_STAT_STAGED
:
5577 type
= LINE_STAT_SECTION
;
5578 text
= "Changes to be committed:";
5581 case LINE_STAT_UNSTAGED
:
5582 type
= LINE_STAT_SECTION
;
5583 text
= "Changed but not updated:";
5586 case LINE_STAT_UNTRACKED
:
5587 type
= LINE_STAT_SECTION
;
5588 text
= "Untracked files:";
5591 case LINE_STAT_NONE
:
5592 type
= LINE_DEFAULT
;
5593 text
= " (no files)";
5596 case LINE_STAT_HEAD
:
5597 type
= LINE_STAT_HEAD
;
5598 text
= status_onbranch
;
5605 static char buf
[] = { '?', ' ', ' ', ' ', 0 };
5607 buf
[0] = status
->status
;
5608 if (draw_text(view
, line
->type
, buf
, TRUE
))
5610 type
= LINE_DEFAULT
;
5611 text
= status
->new.name
;
5614 draw_text(view
, type
, text
, TRUE
);
5619 status_load_error(struct view
*view
, struct view
*stage
, const char *path
)
5621 if (displayed_views() == 2 || display
[current_view
] != view
)
5622 maximize_view(view
);
5623 report("Failed to load '%s': %s", path
, io_strerror(&stage
->io
));
5628 status_enter(struct view
*view
, struct line
*line
)
5630 struct status
*status
= line
->data
;
5631 const char *oldpath
= status
? status
->old
.name
: NULL
;
5632 /* Diffs for unmerged entries are empty when passing the new
5633 * path, so leave it empty. */
5634 const char *newpath
= status
&& status
->status
!= 'U' ? status
->new.name
: NULL
;
5636 enum open_flags split
;
5637 struct view
*stage
= VIEW(REQ_VIEW_STAGE
);
5639 if (line
->type
== LINE_STAT_NONE
||
5640 (!status
&& line
[1].type
== LINE_STAT_NONE
)) {
5641 report("No file to diff");
5645 switch (line
->type
) {
5646 case LINE_STAT_STAGED
:
5647 if (is_initial_commit()) {
5648 const char *no_head_diff_argv
[] = {
5649 "git", "diff", "--no-color", "--patch-with-stat",
5650 "--", "/dev/null", newpath
, NULL
5653 if (!prepare_update(stage
, no_head_diff_argv
, opt_cdup
, FORMAT_DASH
))
5654 return status_load_error(view
, stage
, newpath
);
5656 const char *index_show_argv
[] = {
5657 "git", "diff-index", "--root", "--patch-with-stat",
5658 "-C", "-M", "--cached", "HEAD", "--",
5659 oldpath
, newpath
, NULL
5662 if (!prepare_update(stage
, index_show_argv
, opt_cdup
, FORMAT_DASH
))
5663 return status_load_error(view
, stage
, newpath
);
5667 info
= "Staged changes to %s";
5669 info
= "Staged changes";
5672 case LINE_STAT_UNSTAGED
:
5674 const char *files_show_argv
[] = {
5675 "git", "diff-files", "--root", "--patch-with-stat",
5676 "-C", "-M", "--", oldpath
, newpath
, NULL
5679 if (!prepare_update(stage
, files_show_argv
, opt_cdup
, FORMAT_DASH
))
5680 return status_load_error(view
, stage
, newpath
);
5682 info
= "Unstaged changes to %s";
5684 info
= "Unstaged changes";
5687 case LINE_STAT_UNTRACKED
:
5689 report("No file to show");
5693 if (!suffixcmp(status
->new.name
, -1, "/")) {
5694 report("Cannot display a directory");
5698 if (!prepare_update_file(stage
, newpath
))
5699 return status_load_error(view
, stage
, newpath
);
5700 info
= "Untracked file %s";
5703 case LINE_STAT_HEAD
:
5707 die("line type %d not handled in switch", line
->type
);
5710 split
= view_is_displayed(view
) ? OPEN_SPLIT
: 0;
5711 open_view(view
, REQ_VIEW_STAGE
, OPEN_PREPARED
| split
);
5712 if (view_is_displayed(VIEW(REQ_VIEW_STAGE
))) {
5714 stage_status
= *status
;
5716 memset(&stage_status
, 0, sizeof(stage_status
));
5719 stage_line_type
= line
->type
;
5721 string_format(VIEW(REQ_VIEW_STAGE
)->ref
, info
, stage_status
.new.name
);
5728 status_exists(struct status
*status
, enum line_type type
)
5730 struct view
*view
= VIEW(REQ_VIEW_STATUS
);
5731 unsigned long lineno
;
5733 for (lineno
= 0; lineno
< view
->lines
; lineno
++) {
5734 struct line
*line
= &view
->line
[lineno
];
5735 struct status
*pos
= line
->data
;
5737 if (line
->type
!= type
)
5739 if (!pos
&& (!status
|| !status
->status
) && line
[1].data
) {
5740 select_view_line(view
, lineno
);
5743 if (pos
&& !strcmp(status
->new.name
, pos
->new.name
)) {
5744 select_view_line(view
, lineno
);
5754 status_update_prepare(struct io
*io
, enum line_type type
)
5756 const char *staged_argv
[] = {
5757 "git", "update-index", "-z", "--index-info", NULL
5759 const char *others_argv
[] = {
5760 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5764 case LINE_STAT_STAGED
:
5765 return run_io(io
, staged_argv
, opt_cdup
, IO_WR
);
5767 case LINE_STAT_UNSTAGED
:
5768 case LINE_STAT_UNTRACKED
:
5769 return run_io(io
, others_argv
, opt_cdup
, IO_WR
);
5772 die("line type %d not handled in switch", type
);
5778 status_update_write(struct io
*io
, struct status
*status
, enum line_type type
)
5780 char buf
[SIZEOF_STR
];
5784 case LINE_STAT_STAGED
:
5785 if (!string_format_from(buf
, &bufsize
, "%06o %s\t%s%c",
5788 status
->old
.name
, 0))
5792 case LINE_STAT_UNSTAGED
:
5793 case LINE_STAT_UNTRACKED
:
5794 if (!string_format_from(buf
, &bufsize
, "%s%c", status
->new.name
, 0))
5799 die("line type %d not handled in switch", type
);
5802 return io_write(io
, buf
, bufsize
);
5806 status_update_file(struct status
*status
, enum line_type type
)
5811 if (!status_update_prepare(&io
, type
))
5814 result
= status_update_write(&io
, status
, type
);
5815 return done_io(&io
) && result
;
5819 status_update_files(struct view
*view
, struct line
*line
)
5821 char buf
[sizeof(view
->ref
)];
5824 struct line
*pos
= view
->line
+ view
->lines
;
5827 int cursor_y
= -1, cursor_x
= -1;
5829 if (!status_update_prepare(&io
, line
->type
))
5832 for (pos
= line
; pos
< view
->line
+ view
->lines
&& pos
->data
; pos
++)
5835 string_copy(buf
, view
->ref
);
5836 getsyx(cursor_y
, cursor_x
);
5837 for (file
= 0, done
= 5; result
&& file
< files
; line
++, file
++) {
5838 int almost_done
= file
* 100 / files
;
5840 if (almost_done
> done
) {
5842 string_format(view
->ref
, "updating file %u of %u (%d%% done)",
5844 update_view_title(view
);
5845 setsyx(cursor_y
, cursor_x
);
5848 result
= status_update_write(&io
, line
->data
, line
->type
);
5850 string_copy(view
->ref
, buf
);
5852 return done_io(&io
) && result
;
5856 status_update(struct view
*view
)
5858 struct line
*line
= &view
->line
[view
->lineno
];
5860 assert(view
->lines
);
5863 /* This should work even for the "On branch" line. */
5864 if (line
< view
->line
+ view
->lines
&& !line
[1].data
) {
5865 report("Nothing to update");
5869 if (!status_update_files(view
, line
+ 1)) {
5870 report("Failed to update file status");
5874 } else if (!status_update_file(line
->data
, line
->type
)) {
5875 report("Failed to update file status");
5883 status_revert(struct status
*status
, enum line_type type
, bool has_none
)
5885 if (!status
|| type
!= LINE_STAT_UNSTAGED
) {
5886 if (type
== LINE_STAT_STAGED
) {
5887 report("Cannot revert changes to staged files");
5888 } else if (type
== LINE_STAT_UNTRACKED
) {
5889 report("Cannot revert changes to untracked files");
5890 } else if (has_none
) {
5891 report("Nothing to revert");
5893 report("Cannot revert changes to multiple files");
5896 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
5897 char mode
[10] = "100644";
5898 const char *reset_argv
[] = {
5899 "git", "update-index", "--cacheinfo", mode
,
5900 status
->old
.rev
, status
->old
.name
, NULL
5902 const char *checkout_argv
[] = {
5903 "git", "checkout", "--", status
->old
.name
, NULL
5906 if (status
->status
== 'U') {
5907 string_format(mode
, "%5o", status
->old
.mode
);
5909 if (status
->old
.mode
== 0 && status
->new.mode
== 0) {
5910 reset_argv
[2] = "--force-remove";
5911 reset_argv
[3] = status
->old
.name
;
5912 reset_argv
[4] = NULL
;
5915 if (!run_io_fg(reset_argv
, opt_cdup
))
5917 if (status
->old
.mode
== 0 && status
->new.mode
== 0)
5921 return run_io_fg(checkout_argv
, opt_cdup
);
5928 status_request(struct view
*view
, enum request request
, struct line
*line
)
5930 struct status
*status
= line
->data
;
5933 case REQ_STATUS_UPDATE
:
5934 if (!status_update(view
))
5938 case REQ_STATUS_REVERT
:
5939 if (!status_revert(status
, line
->type
, status_has_none(view
, line
)))
5943 case REQ_STATUS_MERGE
:
5944 if (!status
|| status
->status
!= 'U') {
5945 report("Merging only possible for files with unmerged status ('U').");
5948 open_mergetool(status
->new.name
);
5954 if (status
->status
== 'D') {
5955 report("File has been deleted.");
5959 open_editor(status
->new.name
);
5962 case REQ_VIEW_BLAME
:
5968 /* After returning the status view has been split to
5969 * show the stage view. No further reloading is
5971 return status_enter(view
, line
);
5974 /* Simply reload the view. */
5981 open_view(view
, REQ_VIEW_STATUS
, OPEN_RELOAD
);
5987 status_select(struct view
*view
, struct line
*line
)
5989 struct status
*status
= line
->data
;
5990 char file
[SIZEOF_STR
] = "all files";
5994 if (status
&& !string_format(file
, "'%s'", status
->new.name
))
5997 if (!status
&& line
[1].type
== LINE_STAT_NONE
)
6000 switch (line
->type
) {
6001 case LINE_STAT_STAGED
:
6002 text
= "Press %s to unstage %s for commit";
6005 case LINE_STAT_UNSTAGED
:
6006 text
= "Press %s to stage %s for commit";
6009 case LINE_STAT_UNTRACKED
:
6010 text
= "Press %s to stage %s for addition";
6013 case LINE_STAT_HEAD
:
6014 case LINE_STAT_NONE
:
6015 text
= "Nothing to update";
6019 die("line type %d not handled in switch", line
->type
);
6022 if (status
&& status
->status
== 'U') {
6023 text
= "Press %s to resolve conflict in %s";
6024 key
= get_key(KEYMAP_STATUS
, REQ_STATUS_MERGE
);
6027 key
= get_key(KEYMAP_STATUS
, REQ_STATUS_UPDATE
);
6030 string_format(view
->ref
, text
, key
, file
);
6032 string_copy(opt_file
, status
->new.name
);
6036 status_grep(struct view
*view
, struct line
*line
)
6038 struct status
*status
= line
->data
;
6041 const char buf
[2] = { status
->status
, 0 };
6042 const char *text
[] = { status
->new.name
, buf
, NULL
};
6044 return grep_text(view
, text
);
6050 static struct view_ops status_ops
= {
6063 stage_diff_write(struct io
*io
, struct line
*line
, struct line
*end
)
6065 while (line
< end
) {
6066 if (!io_write(io
, line
->data
, strlen(line
->data
)) ||
6067 !io_write(io
, "\n", 1))
6070 if (line
->type
== LINE_DIFF_CHUNK
||
6071 line
->type
== LINE_DIFF_HEADER
)
6078 static struct line
*
6079 stage_diff_find(struct view
*view
, struct line
*line
, enum line_type type
)
6081 for (; view
->line
< line
; line
--)
6082 if (line
->type
== type
)
6089 stage_apply_chunk(struct view
*view
, struct line
*chunk
, bool revert
)
6091 const char *apply_argv
[SIZEOF_ARG
] = {
6092 "git", "apply", "--whitespace=nowarn", NULL
6094 struct line
*diff_hdr
;
6098 diff_hdr
= stage_diff_find(view
, chunk
, LINE_DIFF_HEADER
);
6103 apply_argv
[argc
++] = "--cached";
6104 if (revert
|| stage_line_type
== LINE_STAT_STAGED
)
6105 apply_argv
[argc
++] = "-R";
6106 apply_argv
[argc
++] = "-";
6107 apply_argv
[argc
++] = NULL
;
6108 if (!run_io(&io
, apply_argv
, opt_cdup
, IO_WR
))
6111 if (!stage_diff_write(&io
, diff_hdr
, chunk
) ||
6112 !stage_diff_write(&io
, chunk
, view
->line
+ view
->lines
))
6116 run_io_bg(update_index_argv
);
6118 return chunk
? TRUE
: FALSE
;
6122 stage_update(struct view
*view
, struct line
*line
)
6124 struct line
*chunk
= NULL
;
6126 if (!is_initial_commit() && stage_line_type
!= LINE_STAT_UNTRACKED
)
6127 chunk
= stage_diff_find(view
, line
, LINE_DIFF_CHUNK
);
6130 if (!stage_apply_chunk(view
, chunk
, FALSE
)) {
6131 report("Failed to apply chunk");
6135 } else if (!stage_status
.status
) {
6136 view
= VIEW(REQ_VIEW_STATUS
);
6138 for (line
= view
->line
; line
< view
->line
+ view
->lines
; line
++)
6139 if (line
->type
== stage_line_type
)
6142 if (!status_update_files(view
, line
+ 1)) {
6143 report("Failed to update files");
6147 } else if (!status_update_file(&stage_status
, stage_line_type
)) {
6148 report("Failed to update file");
6156 stage_revert(struct view
*view
, struct line
*line
)
6158 struct line
*chunk
= NULL
;
6160 if (!is_initial_commit() && stage_line_type
== LINE_STAT_UNSTAGED
)
6161 chunk
= stage_diff_find(view
, line
, LINE_DIFF_CHUNK
);
6164 if (!prompt_yesno("Are you sure you want to revert changes?"))
6167 if (!stage_apply_chunk(view
, chunk
, TRUE
)) {
6168 report("Failed to revert chunk");
6174 return status_revert(stage_status
.status
? &stage_status
: NULL
,
6175 stage_line_type
, FALSE
);
6181 stage_next(struct view
*view
, struct line
*line
)
6185 if (!stage_chunks
) {
6186 for (line
= view
->line
; line
< view
->line
+ view
->lines
; line
++) {
6187 if (line
->type
!= LINE_DIFF_CHUNK
)
6190 if (!realloc_ints(&stage_chunk
, stage_chunks
, 1)) {
6191 report("Allocation failure");
6195 stage_chunk
[stage_chunks
++] = line
- view
->line
;
6199 for (i
= 0; i
< stage_chunks
; i
++) {
6200 if (stage_chunk
[i
] > view
->lineno
) {
6201 do_scroll_view(view
, stage_chunk
[i
] - view
->lineno
);
6202 report("Chunk %d of %d", i
+ 1, stage_chunks
);
6207 report("No next chunk found");
6211 stage_request(struct view
*view
, enum request request
, struct line
*line
)
6214 case REQ_STATUS_UPDATE
:
6215 if (!stage_update(view
, line
))
6219 case REQ_STATUS_REVERT
:
6220 if (!stage_revert(view
, line
))
6224 case REQ_STAGE_NEXT
:
6225 if (stage_line_type
== LINE_STAT_UNTRACKED
) {
6226 report("File is untracked; press %s to add",
6227 get_key(KEYMAP_STAGE
, REQ_STATUS_UPDATE
));
6230 stage_next(view
, line
);
6234 if (!stage_status
.new.name
[0])
6236 if (stage_status
.status
== 'D') {
6237 report("File has been deleted.");
6241 open_editor(stage_status
.new.name
);
6245 /* Reload everything ... */
6248 case REQ_VIEW_BLAME
:
6249 if (stage_status
.new.name
[0]) {
6250 string_copy(opt_file
, stage_status
.new.name
);
6256 return pager_request(view
, request
, line
);
6262 VIEW(REQ_VIEW_STATUS
)->p_restore
= TRUE
;
6263 open_view(view
, REQ_VIEW_STATUS
, OPEN_REFRESH
);
6265 /* Check whether the staged entry still exists, and close the
6266 * stage view if it doesn't. */
6267 if (!status_exists(&stage_status
, stage_line_type
)) {
6268 status_restore(VIEW(REQ_VIEW_STATUS
));
6269 return REQ_VIEW_CLOSE
;
6272 if (stage_line_type
== LINE_STAT_UNTRACKED
) {
6273 if (!suffixcmp(stage_status
.new.name
, -1, "/")) {
6274 report("Cannot display a directory");
6278 if (!prepare_update_file(view
, stage_status
.new.name
)) {
6279 report("Failed to open file: %s", strerror(errno
));
6283 open_view(view
, REQ_VIEW_STAGE
, OPEN_REFRESH
);
6288 static struct view_ops stage_ops
= {
6305 char id
[SIZEOF_REV
]; /* SHA1 ID. */
6306 char title
[128]; /* First line of the commit message. */
6307 const char *author
; /* Author of the commit. */
6308 struct time time
; /* Date from the author ident. */
6309 struct ref_list
*refs
; /* Repository references. */
6310 chtype graph
[SIZEOF_REVGRAPH
]; /* Ancestry chain graphics. */
6311 size_t graph_size
; /* The width of the graph array. */
6312 bool has_parents
; /* Rewritten --parents seen. */
6315 /* Size of rev graph with no "padding" columns */
6316 #define SIZEOF_REVITEMS (SIZEOF_REVGRAPH - (SIZEOF_REVGRAPH / 2))
6319 struct rev_graph
*prev
, *next
, *parents
;
6320 char rev
[SIZEOF_REVITEMS
][SIZEOF_REV
];
6322 struct commit
*commit
;
6324 unsigned int boundary
:1;
6327 /* Parents of the commit being visualized. */
6328 static struct rev_graph graph_parents
[4];
6330 /* The current stack of revisions on the graph. */
6331 static struct rev_graph graph_stacks
[4] = {
6332 { &graph_stacks
[3], &graph_stacks
[1], &graph_parents
[0] },
6333 { &graph_stacks
[0], &graph_stacks
[2], &graph_parents
[1] },
6334 { &graph_stacks
[1], &graph_stacks
[3], &graph_parents
[2] },
6335 { &graph_stacks
[2], &graph_stacks
[0], &graph_parents
[3] },
6339 graph_parent_is_merge(struct rev_graph
*graph
)
6341 return graph
->parents
->size
> 1;
6345 append_to_rev_graph(struct rev_graph
*graph
, chtype symbol
)
6347 struct commit
*commit
= graph
->commit
;
6349 if (commit
->graph_size
< ARRAY_SIZE(commit
->graph
) - 1)
6350 commit
->graph
[commit
->graph_size
++] = symbol
;
6354 clear_rev_graph(struct rev_graph
*graph
)
6356 graph
->boundary
= 0;
6357 graph
->size
= graph
->pos
= 0;
6358 graph
->commit
= NULL
;
6359 memset(graph
->parents
, 0, sizeof(*graph
->parents
));
6363 done_rev_graph(struct rev_graph
*graph
)
6365 if (graph_parent_is_merge(graph
) &&
6366 graph
->pos
< graph
->size
- 1 &&
6367 graph
->next
->size
== graph
->size
+ graph
->parents
->size
- 1) {
6368 size_t i
= graph
->pos
+ graph
->parents
->size
- 1;
6370 graph
->commit
->graph_size
= i
* 2;
6371 while (i
< graph
->next
->size
- 1) {
6372 append_to_rev_graph(graph
, ' ');
6373 append_to_rev_graph(graph
, '\\');
6378 clear_rev_graph(graph
);
6382 push_rev_graph(struct rev_graph
*graph
, const char *parent
)
6386 /* "Collapse" duplicate parents lines.
6388 * FIXME: This needs to also update update the drawn graph but
6389 * for now it just serves as a method for pruning graph lines. */
6390 for (i
= 0; i
< graph
->size
; i
++)
6391 if (!strncmp(graph
->rev
[i
], parent
, SIZEOF_REV
))
6394 if (graph
->size
< SIZEOF_REVITEMS
) {
6395 string_copy_rev(graph
->rev
[graph
->size
++], parent
);
6400 get_rev_graph_symbol(struct rev_graph
*graph
)
6404 if (graph
->boundary
)
6405 symbol
= REVGRAPH_BOUND
;
6406 else if (graph
->parents
->size
== 0)
6407 symbol
= REVGRAPH_INIT
;
6408 else if (graph_parent_is_merge(graph
))
6409 symbol
= REVGRAPH_MERGE
;
6410 else if (graph
->pos
>= graph
->size
)
6411 symbol
= REVGRAPH_BRANCH
;
6413 symbol
= REVGRAPH_COMMIT
;
6419 draw_rev_graph(struct rev_graph
*graph
)
6422 chtype separator
, line
;
6424 enum { DEFAULT
, RSHARP
, RDIAG
, LDIAG
};
6425 static struct rev_filler fillers
[] = {
6431 chtype symbol
= get_rev_graph_symbol(graph
);
6432 struct rev_filler
*filler
;
6435 fillers
[DEFAULT
].line
= opt_line_graphics
? ACS_VLINE
: '|';
6436 filler
= &fillers
[DEFAULT
];
6438 for (i
= 0; i
< graph
->pos
; i
++) {
6439 append_to_rev_graph(graph
, filler
->line
);
6440 if (graph_parent_is_merge(graph
->prev
) &&
6441 graph
->prev
->pos
== i
)
6442 filler
= &fillers
[RSHARP
];
6444 append_to_rev_graph(graph
, filler
->separator
);
6447 /* Place the symbol for this revision. */
6448 append_to_rev_graph(graph
, symbol
);
6450 if (graph
->prev
->size
> graph
->size
)
6451 filler
= &fillers
[RDIAG
];
6453 filler
= &fillers
[DEFAULT
];
6457 for (; i
< graph
->size
; i
++) {
6458 append_to_rev_graph(graph
, filler
->separator
);
6459 append_to_rev_graph(graph
, filler
->line
);
6460 if (graph_parent_is_merge(graph
->prev
) &&
6461 i
< graph
->prev
->pos
+ graph
->parents
->size
)
6462 filler
= &fillers
[RSHARP
];
6463 if (graph
->prev
->size
> graph
->size
)
6464 filler
= &fillers
[LDIAG
];
6467 if (graph
->prev
->size
> graph
->size
) {
6468 append_to_rev_graph(graph
, filler
->separator
);
6469 if (filler
->line
!= ' ')
6470 append_to_rev_graph(graph
, filler
->line
);
6474 /* Prepare the next rev graph */
6476 prepare_rev_graph(struct rev_graph
*graph
)
6480 /* First, traverse all lines of revisions up to the active one. */
6481 for (graph
->pos
= 0; graph
->pos
< graph
->size
; graph
->pos
++) {
6482 if (!strcmp(graph
->rev
[graph
->pos
], graph
->commit
->id
))
6485 push_rev_graph(graph
->next
, graph
->rev
[graph
->pos
]);
6488 /* Interleave the new revision parent(s). */
6489 for (i
= 0; !graph
->boundary
&& i
< graph
->parents
->size
; i
++)
6490 push_rev_graph(graph
->next
, graph
->parents
->rev
[i
]);
6492 /* Lastly, put any remaining revisions. */
6493 for (i
= graph
->pos
+ 1; i
< graph
->size
; i
++)
6494 push_rev_graph(graph
->next
, graph
->rev
[i
]);
6498 update_rev_graph(struct view
*view
, struct rev_graph
*graph
)
6500 /* If this is the finalizing update ... */
6502 prepare_rev_graph(graph
);
6504 /* Graph visualization needs a one rev look-ahead,
6505 * so the first update doesn't visualize anything. */
6506 if (!graph
->prev
->commit
)
6509 if (view
->lines
> 2)
6510 view
->line
[view
->lines
- 3].dirty
= 1;
6511 if (view
->lines
> 1)
6512 view
->line
[view
->lines
- 2].dirty
= 1;
6513 draw_rev_graph(graph
->prev
);
6514 done_rev_graph(graph
->prev
->prev
);
6522 static const char *main_argv
[SIZEOF_ARG
] = {
6523 "git", "log", "--no-color", "--pretty=raw", "--parents",
6524 "--topo-order", "%(head)", NULL
6528 main_draw(struct view
*view
, struct line
*line
, unsigned int lineno
)
6530 struct commit
*commit
= line
->data
;
6532 if (!commit
->author
)
6535 if (opt_date
&& draw_date(view
, &commit
->time
))
6538 if (opt_author
&& draw_author(view
, commit
->author
))
6541 if (opt_rev_graph
&& commit
->graph_size
&&
6542 draw_graphic(view
, LINE_MAIN_REVGRAPH
, commit
->graph
, commit
->graph_size
))
6545 if (opt_show_refs
&& commit
->refs
) {
6548 for (i
= 0; i
< commit
->refs
->size
; i
++) {
6549 struct ref
*ref
= commit
->refs
->refs
[i
];
6550 enum line_type type
;
6553 type
= LINE_MAIN_HEAD
;
6555 type
= LINE_MAIN_LOCAL_TAG
;
6557 type
= LINE_MAIN_TAG
;
6558 else if (ref
->tracked
)
6559 type
= LINE_MAIN_TRACKED
;
6560 else if (ref
->remote
)
6561 type
= LINE_MAIN_REMOTE
;
6563 type
= LINE_MAIN_REF
;
6565 if (draw_text(view
, type
, "[", TRUE
) ||
6566 draw_text(view
, type
, ref
->name
, TRUE
) ||
6567 draw_text(view
, type
, "]", TRUE
))
6570 if (draw_text(view
, LINE_DEFAULT
, " ", TRUE
))
6575 draw_text(view
, LINE_DEFAULT
, commit
->title
, TRUE
);
6579 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6581 main_read(struct view
*view
, char *line
)
6583 static struct rev_graph
*graph
= graph_stacks
;
6584 enum line_type type
;
6585 struct commit
*commit
;
6590 if (!view
->lines
&& !view
->parent
)
6591 die("No revisions match the given arguments.");
6592 if (view
->lines
> 0) {
6593 commit
= view
->line
[view
->lines
- 1].data
;
6594 view
->line
[view
->lines
- 1].dirty
= 1;
6595 if (!commit
->author
) {
6598 graph
->commit
= NULL
;
6601 update_rev_graph(view
, graph
);
6603 for (i
= 0; i
< ARRAY_SIZE(graph_stacks
); i
++)
6604 clear_rev_graph(&graph_stacks
[i
]);
6608 type
= get_line_type(line
);
6609 if (type
== LINE_COMMIT
) {
6610 commit
= calloc(1, sizeof(struct commit
));
6614 line
+= STRING_SIZE("commit ");
6616 graph
->boundary
= 1;
6620 string_copy_rev(commit
->id
, line
);
6621 commit
->refs
= get_ref_list(commit
->id
);
6622 graph
->commit
= commit
;
6623 add_line_data(view
, commit
, LINE_MAIN_COMMIT
);
6625 while ((line
= strchr(line
, ' '))) {
6627 push_rev_graph(graph
->parents
, line
);
6628 commit
->has_parents
= TRUE
;
6635 commit
= view
->line
[view
->lines
- 1].data
;
6639 if (commit
->has_parents
)
6641 push_rev_graph(graph
->parents
, line
+ STRING_SIZE("parent "));
6645 parse_author_line(line
+ STRING_SIZE("author "),
6646 &commit
->author
, &commit
->time
);
6647 update_rev_graph(view
, graph
);
6648 graph
= graph
->next
;
6652 /* Fill in the commit title if it has not already been set. */
6653 if (commit
->title
[0])
6656 /* Require titles to start with a non-space character at the
6657 * offset used by git log. */
6658 if (strncmp(line
, " ", 4))
6661 /* Well, if the title starts with a whitespace character,
6662 * try to be forgiving. Otherwise we end up with no title. */
6663 while (isspace(*line
))
6667 /* FIXME: More graceful handling of titles; append "..." to
6668 * shortened titles, etc. */
6670 string_expand(commit
->title
, sizeof(commit
->title
), line
, 1);
6671 view
->line
[view
->lines
- 1].dirty
= 1;
6678 main_request(struct view
*view
, enum request request
, struct line
*line
)
6680 enum open_flags flags
= display
[0] == view
? OPEN_SPLIT
: OPEN_DEFAULT
;
6684 open_view(view
, REQ_VIEW_DIFF
, flags
);
6688 open_view(view
, REQ_VIEW_MAIN
, OPEN_REFRESH
);
6698 grep_refs(struct ref_list
*list
, regex_t
*regex
)
6703 if (!opt_show_refs
|| !list
)
6706 for (i
= 0; i
< list
->size
; i
++) {
6707 if (regexec(regex
, list
->refs
[i
]->name
, 1, &pmatch
, 0) != REG_NOMATCH
)
6715 main_grep(struct view
*view
, struct line
*line
)
6717 struct commit
*commit
= line
->data
;
6718 const char *text
[] = {
6720 opt_author
? commit
->author
: "",
6721 opt_date
? mkdate(&commit
->time
) : "",
6725 return grep_text(view
, text
) || grep_refs(commit
->refs
, view
->regex
);
6729 main_select(struct view
*view
, struct line
*line
)
6731 struct commit
*commit
= line
->data
;
6733 string_copy_rev(view
->ref
, commit
->id
);
6734 string_copy_rev(ref_commit
, view
->ref
);
6737 static struct view_ops main_ops
= {
6750 * Unicode / UTF-8 handling
6752 * NOTE: Much of the following code for dealing with Unicode is derived from
6753 * ELinks' UTF-8 code developed by Scrool <scroolik@gmail.com>. Origin file is
6754 * src/intl/charset.c from the UTF-8 branch commit elinks-0.11.0-g31f2c28.
6758 unicode_width(unsigned long c
, int tab_size
)
6761 (c
<= 0x115f /* Hangul Jamo */
6764 || (c
>= 0x2e80 && c
<= 0xa4cf && c
!= 0x303f)
6766 || (c
>= 0xac00 && c
<= 0xd7a3) /* Hangul Syllables */
6767 || (c
>= 0xf900 && c
<= 0xfaff) /* CJK Compatibility Ideographs */
6768 || (c
>= 0xfe30 && c
<= 0xfe6f) /* CJK Compatibility Forms */
6769 || (c
>= 0xff00 && c
<= 0xff60) /* Fullwidth Forms */
6770 || (c
>= 0xffe0 && c
<= 0xffe6)
6771 || (c
>= 0x20000 && c
<= 0x2fffd)
6772 || (c
>= 0x30000 && c
<= 0x3fffd)))
6781 /* Number of bytes used for encoding a UTF-8 character indexed by first byte.
6782 * Illegal bytes are set one. */
6783 static const unsigned char utf8_bytes
[256] = {
6784 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
6785 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
6786 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
6787 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
6788 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
6789 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
6790 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,
6791 3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4, 5,5,5,5,6,6,1,1,
6794 static inline unsigned char
6795 utf8_char_length(const char *string
, const char *end
)
6797 int c
= *(unsigned char *) string
;
6799 return utf8_bytes
[c
];
6802 /* Decode UTF-8 multi-byte representation into a Unicode character. */
6803 static inline unsigned long
6804 utf8_to_unicode(const char *string
, size_t length
)
6806 unsigned long unicode
;
6810 unicode
= string
[0];
6813 unicode
= (string
[0] & 0x1f) << 6;
6814 unicode
+= (string
[1] & 0x3f);
6817 unicode
= (string
[0] & 0x0f) << 12;
6818 unicode
+= ((string
[1] & 0x3f) << 6);
6819 unicode
+= (string
[2] & 0x3f);
6822 unicode
= (string
[0] & 0x0f) << 18;
6823 unicode
+= ((string
[1] & 0x3f) << 12);
6824 unicode
+= ((string
[2] & 0x3f) << 6);
6825 unicode
+= (string
[3] & 0x3f);
6828 unicode
= (string
[0] & 0x0f) << 24;
6829 unicode
+= ((string
[1] & 0x3f) << 18);
6830 unicode
+= ((string
[2] & 0x3f) << 12);
6831 unicode
+= ((string
[3] & 0x3f) << 6);
6832 unicode
+= (string
[4] & 0x3f);
6835 unicode
= (string
[0] & 0x01) << 30;
6836 unicode
+= ((string
[1] & 0x3f) << 24);
6837 unicode
+= ((string
[2] & 0x3f) << 18);
6838 unicode
+= ((string
[3] & 0x3f) << 12);
6839 unicode
+= ((string
[4] & 0x3f) << 6);
6840 unicode
+= (string
[5] & 0x3f);
6843 die("Invalid Unicode length");
6846 /* Invalid characters could return the special 0xfffd value but NUL
6847 * should be just as good. */
6848 return unicode
> 0xffff ? 0 : unicode
;
6851 /* Calculates how much of string can be shown within the given maximum width
6852 * and sets trimmed parameter to non-zero value if all of string could not be
6853 * shown. If the reserve flag is TRUE, it will reserve at least one
6854 * trailing character, which can be useful when drawing a delimiter.
6856 * Returns the number of bytes to output from string to satisfy max_width. */
6858 utf8_length(const char **start
, size_t skip
, int *width
, size_t max_width
, int *trimmed
, bool reserve
, int tab_size
)
6860 const char *string
= *start
;
6861 const char *end
= strchr(string
, '\0');
6862 unsigned char last_bytes
= 0;
6863 size_t last_ucwidth
= 0;
6868 while (string
< end
) {
6869 unsigned char bytes
= utf8_char_length(string
, end
);
6871 unsigned long unicode
;
6873 if (string
+ bytes
> end
)
6876 /* Change representation to figure out whether
6877 * it is a single- or double-width character. */
6879 unicode
= utf8_to_unicode(string
, bytes
);
6880 /* FIXME: Graceful handling of invalid Unicode character. */
6884 ucwidth
= unicode_width(unicode
, tab_size
);
6886 skip
-= ucwidth
<= skip
? ucwidth
: skip
;
6890 if (*width
> max_width
) {
6893 if (reserve
&& *width
== max_width
) {
6894 string
-= last_bytes
;
6895 *width
-= last_ucwidth
;
6901 last_bytes
= ucwidth
? bytes
: 0;
6902 last_ucwidth
= ucwidth
;
6905 return string
- *start
;
6913 /* Whether or not the curses interface has been initialized. */
6914 static bool cursed
= FALSE
;
6916 /* Terminal hacks and workarounds. */
6917 static bool use_scroll_redrawwin
;
6918 static bool use_scroll_status_wclear
;
6920 /* The status window is used for polling keystrokes. */
6921 static WINDOW
*status_win
;
6923 /* Reading from the prompt? */
6924 static bool input_mode
= FALSE
;
6926 static bool status_empty
= FALSE
;
6928 /* Update status and title window. */
6930 report(const char *msg
, ...)
6932 struct view
*view
= display
[current_view
];
6938 char buf
[SIZEOF_STR
];
6941 va_start(args
, msg
);
6942 if (vsnprintf(buf
, sizeof(buf
), msg
, args
) >= sizeof(buf
)) {
6943 buf
[sizeof(buf
) - 1] = 0;
6944 buf
[sizeof(buf
) - 2] = '.';
6945 buf
[sizeof(buf
) - 3] = '.';
6946 buf
[sizeof(buf
) - 4] = '.';
6952 if (!status_empty
|| *msg
) {
6955 va_start(args
, msg
);
6957 wmove(status_win
, 0, 0);
6958 if (view
->has_scrolled
&& use_scroll_status_wclear
)
6961 vwprintw(status_win
, msg
, args
);
6962 status_empty
= FALSE
;
6964 status_empty
= TRUE
;
6966 wclrtoeol(status_win
);
6967 wnoutrefresh(status_win
);
6972 update_view_title(view
);
6975 /* Controls when nodelay should be in effect when polling user input. */
6977 set_nonblocking_input(bool loading
)
6979 static unsigned int loading_views
;
6981 if ((loading
== FALSE
&& loading_views
-- == 1) ||
6982 (loading
== TRUE
&& loading_views
++ == 0))
6983 nodelay(status_win
, loading
);
6992 /* Initialize the curses library */
6993 if (isatty(STDIN_FILENO
)) {
6994 cursed
= !!initscr();
6997 /* Leave stdin and stdout alone when acting as a pager. */
6998 opt_tty
= fopen("/dev/tty", "r+");
7000 die("Failed to open /dev/tty");
7001 cursed
= !!newterm(NULL
, opt_tty
, opt_tty
);
7005 die("Failed to initialize curses");
7007 nonl(); /* Disable conversion and detect newlines from input. */
7008 cbreak(); /* Take input chars one at a time, no wait for \n */
7009 noecho(); /* Don't echo input */
7010 leaveok(stdscr
, FALSE
);
7015 getmaxyx(stdscr
, y
, x
);
7016 status_win
= newwin(1, 0, y
- 1, 0);
7018 die("Failed to create status window");
7020 /* Enable keyboard mapping */
7021 keypad(status_win
, TRUE
);
7022 wbkgdset(status_win
, get_line_attr(LINE_STATUS
));
7024 TABSIZE
= opt_tab_size
;
7026 term
= getenv("XTERM_VERSION") ? NULL
: getenv("COLORTERM");
7027 if (term
&& !strcmp(term
, "gnome-terminal")) {
7028 /* In the gnome-terminal-emulator, the message from
7029 * scrolling up one line when impossible followed by
7030 * scrolling down one line causes corruption of the
7031 * status line. This is fixed by calling wclear. */
7032 use_scroll_status_wclear
= TRUE
;
7033 use_scroll_redrawwin
= FALSE
;
7035 } else if (term
&& !strcmp(term
, "xrvt-xpm")) {
7036 /* No problems with full optimizations in xrvt-(unicode)
7038 use_scroll_status_wclear
= use_scroll_redrawwin
= FALSE
;
7041 /* When scrolling in (u)xterm the last line in the
7042 * scrolling direction will update slowly. */
7043 use_scroll_redrawwin
= TRUE
;
7044 use_scroll_status_wclear
= FALSE
;
7049 get_input(int prompt_position
)
7052 int i
, key
, cursor_y
, cursor_x
;
7054 if (prompt_position
)
7058 foreach_view (view
, i
) {
7060 if (view_is_displayed(view
) && view
->has_scrolled
&&
7061 use_scroll_redrawwin
)
7062 redrawwin(view
->win
);
7063 view
->has_scrolled
= FALSE
;
7066 /* Update the cursor position. */
7067 if (prompt_position
) {
7068 getbegyx(status_win
, cursor_y
, cursor_x
);
7069 cursor_x
= prompt_position
;
7071 view
= display
[current_view
];
7072 getbegyx(view
->win
, cursor_y
, cursor_x
);
7073 cursor_x
= view
->width
- 1;
7074 cursor_y
+= view
->lineno
- view
->offset
;
7076 setsyx(cursor_y
, cursor_x
);
7078 /* Refresh, accept single keystroke of input */
7080 key
= wgetch(status_win
);
7082 /* wgetch() with nodelay() enabled returns ERR when
7083 * there's no input. */
7086 } else if (key
== KEY_RESIZE
) {
7089 getmaxyx(stdscr
, height
, width
);
7091 wresize(status_win
, 1, width
);
7092 mvwin(status_win
, height
- 1, 0);
7093 wnoutrefresh(status_win
);
7095 redraw_display(TRUE
);
7105 prompt_input(const char *prompt
, input_handler handler
, void *data
)
7107 enum input_status status
= INPUT_OK
;
7108 static char buf
[SIZEOF_STR
];
7113 while (status
== INPUT_OK
|| status
== INPUT_SKIP
) {
7116 mvwprintw(status_win
, 0, 0, "%s%.*s", prompt
, pos
, buf
);
7117 wclrtoeol(status_win
);
7119 key
= get_input(pos
+ 1);
7124 status
= pos
? INPUT_STOP
: INPUT_CANCEL
;
7131 status
= INPUT_CANCEL
;
7135 status
= INPUT_CANCEL
;
7139 if (pos
>= sizeof(buf
)) {
7140 report("Input string too long");
7144 status
= handler(data
, buf
, key
);
7145 if (status
== INPUT_OK
)
7146 buf
[pos
++] = (char) key
;
7150 /* Clear the status window */
7151 status_empty
= FALSE
;
7154 if (status
== INPUT_CANCEL
)
7162 static enum input_status
7163 prompt_yesno_handler(void *data
, char *buf
, int c
)
7165 if (c
== 'y' || c
== 'Y')
7167 if (c
== 'n' || c
== 'N')
7168 return INPUT_CANCEL
;
7173 prompt_yesno(const char *prompt
)
7175 char prompt2
[SIZEOF_STR
];
7177 if (!string_format(prompt2
, "%s [Yy/Nn]", prompt
))
7180 return !!prompt_input(prompt2
, prompt_yesno_handler
, NULL
);
7183 static enum input_status
7184 read_prompt_handler(void *data
, char *buf
, int c
)
7186 return isprint(c
) ? INPUT_OK
: INPUT_SKIP
;
7190 read_prompt(const char *prompt
)
7192 return prompt_input(prompt
, read_prompt_handler
, NULL
);
7195 static bool prompt_menu(const char *prompt
, const struct menu_item
*items
, int *selected
)
7197 enum input_status status
= INPUT_OK
;
7200 while (items
[size
].text
)
7203 while (status
== INPUT_OK
) {
7204 const struct menu_item
*item
= &items
[*selected
];
7208 mvwprintw(status_win
, 0, 0, "%s (%d of %d) ",
7209 prompt
, *selected
+ 1, size
);
7211 wprintw(status_win
, "[%c] ", (char) item
->hotkey
);
7212 wprintw(status_win
, "%s", item
->text
);
7213 wclrtoeol(status_win
);
7215 key
= get_input(COLS
- 1);
7220 status
= INPUT_STOP
;
7225 *selected
= *selected
- 1;
7227 *selected
= size
- 1;
7232 *selected
= (*selected
+ 1) % size
;
7236 status
= INPUT_CANCEL
;
7240 for (i
= 0; items
[i
].text
; i
++)
7241 if (items
[i
].hotkey
== key
) {
7243 status
= INPUT_STOP
;
7249 /* Clear the status window */
7250 status_empty
= FALSE
;
7253 return status
!= INPUT_CANCEL
;
7257 * Repository properties
7260 static struct ref
**refs
= NULL
;
7261 static size_t refs_size
= 0;
7263 static struct ref_list
**ref_lists
= NULL
;
7264 static size_t ref_lists_size
= 0;
7266 DEFINE_ALLOCATOR(realloc_refs
, struct ref
*, 256)
7267 DEFINE_ALLOCATOR(realloc_refs_list
, struct ref
*, 8)
7268 DEFINE_ALLOCATOR(realloc_ref_lists
, struct ref_list
*, 8)
7271 compare_refs(const void *ref1_
, const void *ref2_
)
7273 const struct ref
*ref1
= *(const struct ref
**)ref1_
;
7274 const struct ref
*ref2
= *(const struct ref
**)ref2_
;
7276 if (ref1
->tag
!= ref2
->tag
)
7277 return ref2
->tag
- ref1
->tag
;
7278 if (ref1
->ltag
!= ref2
->ltag
)
7279 return ref2
->ltag
- ref2
->ltag
;
7280 if (ref1
->head
!= ref2
->head
)
7281 return ref2
->head
- ref1
->head
;
7282 if (ref1
->tracked
!= ref2
->tracked
)
7283 return ref2
->tracked
- ref1
->tracked
;
7284 if (ref1
->remote
!= ref2
->remote
)
7285 return ref2
->remote
- ref1
->remote
;
7286 return strcmp(ref1
->name
, ref2
->name
);
7290 foreach_ref(bool (*visitor
)(void *data
, const struct ref
*ref
), void *data
)
7294 for (i
= 0; i
< refs_size
; i
++)
7295 if (!visitor(data
, refs
[i
]))
7299 static struct ref_list
*
7300 get_ref_list(const char *id
)
7302 struct ref_list
*list
;
7305 for (i
= 0; i
< ref_lists_size
; i
++)
7306 if (!strcmp(id
, ref_lists
[i
]->id
))
7307 return ref_lists
[i
];
7309 if (!realloc_ref_lists(&ref_lists
, ref_lists_size
, 1))
7311 list
= calloc(1, sizeof(*list
));
7315 for (i
= 0; i
< refs_size
; i
++) {
7316 if (!strcmp(id
, refs
[i
]->id
) &&
7317 realloc_refs_list(&list
->refs
, list
->size
, 1))
7318 list
->refs
[list
->size
++] = refs
[i
];
7326 qsort(list
->refs
, list
->size
, sizeof(*list
->refs
), compare_refs
);
7327 ref_lists
[ref_lists_size
++] = list
;
7332 read_ref(char *id
, size_t idlen
, char *name
, size_t namelen
)
7334 struct ref
*ref
= NULL
;
7337 bool remote
= FALSE
;
7338 bool tracked
= FALSE
;
7340 int from
= 0, to
= refs_size
- 1;
7342 if (!prefixcmp(name
, "refs/tags/")) {
7343 if (!suffixcmp(name
, namelen
, "^{}")) {
7351 namelen
-= STRING_SIZE("refs/tags/");
7352 name
+= STRING_SIZE("refs/tags/");
7354 } else if (!prefixcmp(name
, "refs/remotes/")) {
7356 namelen
-= STRING_SIZE("refs/remotes/");
7357 name
+= STRING_SIZE("refs/remotes/");
7358 tracked
= !strcmp(opt_remote
, name
);
7360 } else if (!prefixcmp(name
, "refs/heads/")) {
7361 namelen
-= STRING_SIZE("refs/heads/");
7362 name
+= STRING_SIZE("refs/heads/");
7363 head
= !strncmp(opt_head
, name
, namelen
);
7365 } else if (!strcmp(name
, "HEAD")) {
7366 string_ncopy(opt_head_rev
, id
, idlen
);
7370 /* If we are reloading or it's an annotated tag, replace the
7371 * previous SHA1 with the resolved commit id; relies on the fact
7372 * git-ls-remote lists the commit id of an annotated tag right
7373 * before the commit id it points to. */
7374 while (from
<= to
) {
7375 size_t pos
= (to
+ from
) / 2;
7376 int cmp
= strcmp(name
, refs
[pos
]->name
);
7390 if (!realloc_refs(&refs
, refs_size
, 1))
7392 ref
= calloc(1, sizeof(*ref
) + namelen
);
7395 memmove(refs
+ from
+ 1, refs
+ from
,
7396 (refs_size
- from
) * sizeof(*refs
));
7398 strncpy(ref
->name
, name
, namelen
);
7405 ref
->remote
= remote
;
7406 ref
->tracked
= tracked
;
7407 string_copy_rev(ref
->id
, id
);
7415 const char *head_argv
[] = {
7416 "git", "symbolic-ref", "HEAD", NULL
7418 static const char *ls_remote_argv
[SIZEOF_ARG
] = {
7419 "git", "ls-remote", opt_git_dir
, NULL
7421 static bool init
= FALSE
;
7425 argv_from_env(ls_remote_argv
, "TIG_LS_REMOTE");
7432 if (run_io_buf(head_argv
, opt_head
, sizeof(opt_head
)) &&
7433 !prefixcmp(opt_head
, "refs/heads/")) {
7434 char *offset
= opt_head
+ STRING_SIZE("refs/heads/");
7436 memmove(opt_head
, offset
, strlen(offset
) + 1);
7439 for (i
= 0; i
< refs_size
; i
++)
7442 if (run_io_load(ls_remote_argv
, "\t", read_ref
) == ERR
)
7445 /* Update the ref lists to reflect changes. */
7446 for (i
= 0; i
< ref_lists_size
; i
++) {
7447 struct ref_list
*list
= ref_lists
[i
];
7450 for (old
= new = 0; old
< list
->size
; old
++)
7451 if (!strcmp(list
->id
, list
->refs
[old
]->id
))
7452 list
->refs
[new++] = list
->refs
[old
];
7460 set_remote_branch(const char *name
, const char *value
, size_t valuelen
)
7462 if (!strcmp(name
, ".remote")) {
7463 string_ncopy(opt_remote
, value
, valuelen
);
7465 } else if (*opt_remote
&& !strcmp(name
, ".merge")) {
7466 size_t from
= strlen(opt_remote
);
7468 if (!prefixcmp(value
, "refs/heads/"))
7469 value
+= STRING_SIZE("refs/heads/");
7471 if (!string_format_from(opt_remote
, &from
, "/%s", value
))
7477 set_repo_config_option(char *name
, char *value
, int (*cmd
)(int, const char **))
7479 const char *argv
[SIZEOF_ARG
] = { name
, "=" };
7480 int argc
= 1 + (cmd
== option_set_command
);
7483 if (!argv_from_string(argv
, &argc
, value
))
7484 config_msg
= "Too many option arguments";
7486 error
= cmd(argc
, argv
);
7489 warn("Option 'tig.%s': %s", name
, config_msg
);
7493 set_environment_variable(const char *name
, const char *value
)
7495 size_t len
= strlen(name
) + 1 + strlen(value
) + 1;
7496 char *env
= malloc(len
);
7499 string_nformat(env
, len
, NULL
, "%s=%s", name
, value
) &&
7507 set_work_tree(const char *value
)
7509 char cwd
[SIZEOF_STR
];
7511 if (!getcwd(cwd
, sizeof(cwd
)))
7512 die("Failed to get cwd path: %s", strerror(errno
));
7513 if (chdir(opt_git_dir
) < 0)
7514 die("Failed to chdir(%s): %s", strerror(errno
));
7515 if (!getcwd(opt_git_dir
, sizeof(opt_git_dir
)))
7516 die("Failed to get git path: %s", strerror(errno
));
7518 die("Failed to chdir(%s): %s", cwd
, strerror(errno
));
7519 if (chdir(value
) < 0)
7520 die("Failed to chdir(%s): %s", value
, strerror(errno
));
7521 if (!getcwd(cwd
, sizeof(cwd
)))
7522 die("Failed to get cwd path: %s", strerror(errno
));
7523 if (!set_environment_variable("GIT_WORK_TREE", cwd
))
7524 die("Failed to set GIT_WORK_TREE to '%s'", cwd
);
7525 if (!set_environment_variable("GIT_DIR", opt_git_dir
))
7526 die("Failed to set GIT_DIR to '%s'", opt_git_dir
);
7527 opt_is_inside_work_tree
= TRUE
;
7531 read_repo_config_option(char *name
, size_t namelen
, char *value
, size_t valuelen
)
7533 if (!strcmp(name
, "i18n.commitencoding"))
7534 string_ncopy(opt_encoding
, value
, valuelen
);
7536 else if (!strcmp(name
, "core.editor"))
7537 string_ncopy(opt_editor
, value
, valuelen
);
7539 else if (!strcmp(name
, "core.worktree"))
7540 set_work_tree(value
);
7542 else if (!prefixcmp(name
, "tig.color."))
7543 set_repo_config_option(name
+ 10, value
, option_color_command
);
7545 else if (!prefixcmp(name
, "tig.bind."))
7546 set_repo_config_option(name
+ 9, value
, option_bind_command
);
7548 else if (!prefixcmp(name
, "tig."))
7549 set_repo_config_option(name
+ 4, value
, option_set_command
);
7551 else if (*opt_head
&& !prefixcmp(name
, "branch.") &&
7552 !strncmp(name
+ 7, opt_head
, strlen(opt_head
)))
7553 set_remote_branch(name
+ 7 + strlen(opt_head
), value
, valuelen
);
7559 load_git_config(void)
7561 const char *config_list_argv
[] = { "git", "config", "--list", NULL
};
7563 return run_io_load(config_list_argv
, "=", read_repo_config_option
);
7567 read_repo_info(char *name
, size_t namelen
, char *value
, size_t valuelen
)
7569 if (!opt_git_dir
[0]) {
7570 string_ncopy(opt_git_dir
, name
, namelen
);
7572 } else if (opt_is_inside_work_tree
== -1) {
7573 /* This can be 3 different values depending on the
7574 * version of git being used. If git-rev-parse does not
7575 * understand --is-inside-work-tree it will simply echo
7576 * the option else either "true" or "false" is printed.
7577 * Default to true for the unknown case. */
7578 opt_is_inside_work_tree
= strcmp(name
, "false") ? TRUE
: FALSE
;
7580 } else if (*name
== '.') {
7581 string_ncopy(opt_cdup
, name
, namelen
);
7584 string_ncopy(opt_prefix
, name
, namelen
);
7591 load_repo_info(void)
7593 const char *rev_parse_argv
[] = {
7594 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7595 "--show-cdup", "--show-prefix", NULL
7598 return run_io_load(rev_parse_argv
, "=", read_repo_info
);
7606 static const char usage
[] =
7607 "tig " TIG_VERSION
" (" __DATE__
")\n"
7609 "Usage: tig [options] [revs] [--] [paths]\n"
7610 " or: tig show [options] [revs] [--] [paths]\n"
7611 " or: tig blame [rev] path\n"
7613 " or: tig < [git command output]\n"
7616 " -v, --version Show version and exit\n"
7617 " -h, --help Show help message and exit";
7619 static void __NORETURN
7622 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7628 static void __NORETURN
7629 die(const char *err
, ...)
7635 va_start(args
, err
);
7636 fputs("tig: ", stderr
);
7637 vfprintf(stderr
, err
, args
);
7638 fputs("\n", stderr
);
7645 warn(const char *msg
, ...)
7649 va_start(args
, msg
);
7650 fputs("tig warning: ", stderr
);
7651 vfprintf(stderr
, msg
, args
);
7652 fputs("\n", stderr
);
7657 parse_options(int argc
, const char *argv
[])
7659 enum request request
= REQ_VIEW_MAIN
;
7660 const char *subcommand
;
7661 bool seen_dashdash
= FALSE
;
7662 /* XXX: This is vulnerable to the user overriding options
7663 * required for the main view parser. */
7664 const char *custom_argv
[SIZEOF_ARG
] = {
7665 "git", "log", "--no-color", "--pretty=raw", "--parents",
7666 "--topo-order", NULL
7670 if (!isatty(STDIN_FILENO
)) {
7671 io_open(&VIEW(REQ_VIEW_PAGER
)->io
, "");
7672 return REQ_VIEW_PAGER
;
7678 subcommand
= argv
[1];
7679 if (!strcmp(subcommand
, "status")) {
7681 warn("ignoring arguments after `%s'", subcommand
);
7682 return REQ_VIEW_STATUS
;
7684 } else if (!strcmp(subcommand
, "blame")) {
7685 if (argc
<= 2 || argc
> 4)
7686 die("invalid number of options to blame\n\n%s", usage
);
7690 string_ncopy(opt_ref
, argv
[i
], strlen(argv
[i
]));
7694 string_ncopy(opt_file
, argv
[i
], strlen(argv
[i
]));
7695 return REQ_VIEW_BLAME
;
7697 } else if (!strcmp(subcommand
, "show")) {
7698 request
= REQ_VIEW_DIFF
;
7705 custom_argv
[1] = subcommand
;
7709 for (i
= 1 + !!subcommand
; i
< argc
; i
++) {
7710 const char *opt
= argv
[i
];
7712 if (seen_dashdash
|| !strcmp(opt
, "--")) {
7713 seen_dashdash
= TRUE
;
7715 } else if (!strcmp(opt
, "-v") || !strcmp(opt
, "--version")) {
7716 printf("tig version %s\n", TIG_VERSION
);
7719 } else if (!strcmp(opt
, "-h") || !strcmp(opt
, "--help")) {
7720 printf("%s\n", usage
);
7724 custom_argv
[j
++] = opt
;
7725 if (j
>= ARRAY_SIZE(custom_argv
))
7726 die("command too long");
7729 if (!prepare_update(VIEW(request
), custom_argv
, NULL
, FORMAT_NONE
))
7730 die("Failed to format arguments");
7736 main(int argc
, const char *argv
[])
7738 const char *codeset
= "UTF-8";
7739 enum request request
= parse_options(argc
, argv
);
7743 signal(SIGINT
, quit
);
7744 signal(SIGPIPE
, SIG_IGN
);
7746 if (setlocale(LC_ALL
, "")) {
7747 codeset
= nl_langinfo(CODESET
);
7750 if (load_repo_info() == ERR
)
7751 die("Failed to load repo info.");
7753 if (load_options() == ERR
)
7754 die("Failed to load user config.");
7756 if (load_git_config() == ERR
)
7757 die("Failed to load repo config.");
7759 /* Require a git repository unless when running in pager mode. */
7760 if (!opt_git_dir
[0] && request
!= REQ_VIEW_PAGER
)
7761 die("Not a git repository");
7763 if (*opt_encoding
&& strcmp(codeset
, "UTF-8")) {
7764 opt_iconv_in
= iconv_open("UTF-8", opt_encoding
);
7765 if (opt_iconv_in
== ICONV_NONE
)
7766 die("Failed to initialize character set conversion");
7769 if (codeset
&& strcmp(codeset
, "UTF-8")) {
7770 opt_iconv_out
= iconv_open(codeset
, "UTF-8");
7771 if (opt_iconv_out
== ICONV_NONE
)
7772 die("Failed to initialize character set conversion");
7775 if (load_refs() == ERR
)
7776 die("Failed to load refs.");
7778 foreach_view (view
, i
)
7779 argv_from_env(view
->ops
->argv
, view
->cmd_env
);
7783 if (request
!= REQ_NONE
)
7784 open_view(NULL
, request
, OPEN_PREPARED
);
7785 request
= request
== REQ_NONE
? REQ_VIEW_MAIN
: REQ_NONE
;
7787 while (view_driver(display
[current_view
], request
)) {
7788 int key
= get_input(0);
7790 view
= display
[current_view
];
7791 request
= get_keybinding(view
->keymap
, key
);
7793 /* Some low-level request handling. This keeps access to
7794 * status_win restricted. */
7798 char *cmd
= read_prompt(":");
7800 if (cmd
&& isdigit(*cmd
)) {
7801 int lineno
= view
->lineno
+ 1;
7803 if (parse_int(&lineno
, cmd
, 1, view
->lines
+ 1) == OK
) {
7804 select_view_line(view
, lineno
- 1);
7807 report("Unable to parse '%s' as a line number", cmd
);
7811 struct view
*next
= VIEW(REQ_VIEW_PAGER
);
7812 const char *argv
[SIZEOF_ARG
] = { "git" };
7815 /* When running random commands, initially show the
7816 * command in the title. However, it maybe later be
7817 * overwritten if a commit line is selected. */
7818 string_ncopy(next
->ref
, cmd
, strlen(cmd
));
7820 if (!argv_from_string(argv
, &argc
, cmd
)) {
7821 report("Too many arguments");
7822 } else if (!prepare_update(next
, argv
, NULL
, FORMAT_DASH
)) {
7823 report("Failed to format command");
7825 open_view(view
, REQ_VIEW_PAGER
, OPEN_PREPARED
);
7833 case REQ_SEARCH_BACK
:
7835 const char *prompt
= request
== REQ_SEARCH
? "/" : "?";
7836 char *search
= read_prompt(prompt
);
7839 string_ncopy(opt_search
, search
, strlen(search
));
7840 else if (*opt_search
)
7841 request
= request
== REQ_SEARCH
?