Merge branch 'yb/utf-16le-bom-spellfix'
[git] / pretty.c
1 #include "cache.h"
2 #include "config.h"
3 #include "commit.h"
4 #include "utf8.h"
5 #include "diff.h"
6 #include "revision.h"
7 #include "string-list.h"
8 #include "mailmap.h"
9 #include "log-tree.h"
10 #include "notes.h"
11 #include "color.h"
12 #include "reflog-walk.h"
13 #include "gpg-interface.h"
14 #include "trailer.h"
15
16 static char *user_format;
17 static struct cmt_fmt_map {
18         const char *name;
19         enum cmit_fmt format;
20         int is_tformat;
21         int expand_tabs_in_log;
22         int is_alias;
23         const char *user_format;
24 } *commit_formats;
25 static size_t builtin_formats_len;
26 static size_t commit_formats_len;
27 static size_t commit_formats_alloc;
28 static struct cmt_fmt_map *find_commit_format(const char *sought);
29
30 int commit_format_is_empty(enum cmit_fmt fmt)
31 {
32         return fmt == CMIT_FMT_USERFORMAT && !*user_format;
33 }
34
35 static void save_user_format(struct rev_info *rev, const char *cp, int is_tformat)
36 {
37         free(user_format);
38         user_format = xstrdup(cp);
39         if (is_tformat)
40                 rev->use_terminator = 1;
41         rev->commit_format = CMIT_FMT_USERFORMAT;
42 }
43
44 static int git_pretty_formats_config(const char *var, const char *value, void *cb)
45 {
46         struct cmt_fmt_map *commit_format = NULL;
47         const char *name;
48         const char *fmt;
49         int i;
50
51         if (!skip_prefix(var, "pretty.", &name))
52                 return 0;
53
54         for (i = 0; i < builtin_formats_len; i++) {
55                 if (!strcmp(commit_formats[i].name, name))
56                         return 0;
57         }
58
59         for (i = builtin_formats_len; i < commit_formats_len; i++) {
60                 if (!strcmp(commit_formats[i].name, name)) {
61                         commit_format = &commit_formats[i];
62                         break;
63                 }
64         }
65
66         if (!commit_format) {
67                 ALLOC_GROW(commit_formats, commit_formats_len+1,
68                            commit_formats_alloc);
69                 commit_format = &commit_formats[commit_formats_len];
70                 memset(commit_format, 0, sizeof(*commit_format));
71                 commit_formats_len++;
72         }
73
74         commit_format->name = xstrdup(name);
75         commit_format->format = CMIT_FMT_USERFORMAT;
76         if (git_config_string(&fmt, var, value))
77                 return -1;
78
79         if (skip_prefix(fmt, "format:", &fmt))
80                 commit_format->is_tformat = 0;
81         else if (skip_prefix(fmt, "tformat:", &fmt) || strchr(fmt, '%'))
82                 commit_format->is_tformat = 1;
83         else
84                 commit_format->is_alias = 1;
85         commit_format->user_format = fmt;
86
87         return 0;
88 }
89
90 static void setup_commit_formats(void)
91 {
92         struct cmt_fmt_map builtin_formats[] = {
93                 { "raw",        CMIT_FMT_RAW,           0,      0 },
94                 { "medium",     CMIT_FMT_MEDIUM,        0,      8 },
95                 { "short",      CMIT_FMT_SHORT,         0,      0 },
96                 { "email",      CMIT_FMT_EMAIL,         0,      0 },
97                 { "mboxrd",     CMIT_FMT_MBOXRD,        0,      0 },
98                 { "fuller",     CMIT_FMT_FULLER,        0,      8 },
99                 { "full",       CMIT_FMT_FULL,          0,      8 },
100                 { "oneline",    CMIT_FMT_ONELINE,       1,      0 }
101                 /*
102                  * Please update $__git_log_pretty_formats in
103                  * git-completion.bash when you add new formats.
104                  */
105         };
106         commit_formats_len = ARRAY_SIZE(builtin_formats);
107         builtin_formats_len = commit_formats_len;
108         ALLOC_GROW(commit_formats, commit_formats_len, commit_formats_alloc);
109         memcpy(commit_formats, builtin_formats,
110                sizeof(*builtin_formats)*ARRAY_SIZE(builtin_formats));
111
112         git_config(git_pretty_formats_config, NULL);
113 }
114
115 static struct cmt_fmt_map *find_commit_format_recursive(const char *sought,
116                                                         const char *original,
117                                                         int num_redirections)
118 {
119         struct cmt_fmt_map *found = NULL;
120         size_t found_match_len = 0;
121         int i;
122
123         if (num_redirections >= commit_formats_len)
124                 die("invalid --pretty format: "
125                     "'%s' references an alias which points to itself",
126                     original);
127
128         for (i = 0; i < commit_formats_len; i++) {
129                 size_t match_len;
130
131                 if (!starts_with(commit_formats[i].name, sought))
132                         continue;
133
134                 match_len = strlen(commit_formats[i].name);
135                 if (found == NULL || found_match_len > match_len) {
136                         found = &commit_formats[i];
137                         found_match_len = match_len;
138                 }
139         }
140
141         if (found && found->is_alias) {
142                 found = find_commit_format_recursive(found->user_format,
143                                                      original,
144                                                      num_redirections+1);
145         }
146
147         return found;
148 }
149
150 static struct cmt_fmt_map *find_commit_format(const char *sought)
151 {
152         if (!commit_formats)
153                 setup_commit_formats();
154
155         return find_commit_format_recursive(sought, sought, 0);
156 }
157
158 void get_commit_format(const char *arg, struct rev_info *rev)
159 {
160         struct cmt_fmt_map *commit_format;
161
162         rev->use_terminator = 0;
163         if (!arg) {
164                 rev->commit_format = CMIT_FMT_DEFAULT;
165                 return;
166         }
167         if (skip_prefix(arg, "format:", &arg)) {
168                 save_user_format(rev, arg, 0);
169                 return;
170         }
171
172         if (!*arg || skip_prefix(arg, "tformat:", &arg) || strchr(arg, '%')) {
173                 save_user_format(rev, arg, 1);
174                 return;
175         }
176
177         commit_format = find_commit_format(arg);
178         if (!commit_format)
179                 die("invalid --pretty format: %s", arg);
180
181         rev->commit_format = commit_format->format;
182         rev->use_terminator = commit_format->is_tformat;
183         rev->expand_tabs_in_log_default = commit_format->expand_tabs_in_log;
184         if (commit_format->format == CMIT_FMT_USERFORMAT) {
185                 save_user_format(rev, commit_format->user_format,
186                                  commit_format->is_tformat);
187         }
188 }
189
190 /*
191  * Generic support for pretty-printing the header
192  */
193 static int get_one_line(const char *msg)
194 {
195         int ret = 0;
196
197         for (;;) {
198                 char c = *msg++;
199                 if (!c)
200                         break;
201                 ret++;
202                 if (c == '\n')
203                         break;
204         }
205         return ret;
206 }
207
208 /* High bit set, or ISO-2022-INT */
209 static int non_ascii(int ch)
210 {
211         return !isascii(ch) || ch == '\033';
212 }
213
214 int has_non_ascii(const char *s)
215 {
216         int ch;
217         if (!s)
218                 return 0;
219         while ((ch = *s++) != '\0') {
220                 if (non_ascii(ch))
221                         return 1;
222         }
223         return 0;
224 }
225
226 static int is_rfc822_special(char ch)
227 {
228         switch (ch) {
229         case '(':
230         case ')':
231         case '<':
232         case '>':
233         case '[':
234         case ']':
235         case ':':
236         case ';':
237         case '@':
238         case ',':
239         case '.':
240         case '"':
241         case '\\':
242                 return 1;
243         default:
244                 return 0;
245         }
246 }
247
248 static int needs_rfc822_quoting(const char *s, int len)
249 {
250         int i;
251         for (i = 0; i < len; i++)
252                 if (is_rfc822_special(s[i]))
253                         return 1;
254         return 0;
255 }
256
257 static int last_line_length(struct strbuf *sb)
258 {
259         int i;
260
261         /* How many bytes are already used on the last line? */
262         for (i = sb->len - 1; i >= 0; i--)
263                 if (sb->buf[i] == '\n')
264                         break;
265         return sb->len - (i + 1);
266 }
267
268 static void add_rfc822_quoted(struct strbuf *out, const char *s, int len)
269 {
270         int i;
271
272         /* just a guess, we may have to also backslash-quote */
273         strbuf_grow(out, len + 2);
274
275         strbuf_addch(out, '"');
276         for (i = 0; i < len; i++) {
277                 switch (s[i]) {
278                 case '"':
279                 case '\\':
280                         strbuf_addch(out, '\\');
281                         /* fall through */
282                 default:
283                         strbuf_addch(out, s[i]);
284                 }
285         }
286         strbuf_addch(out, '"');
287 }
288
289 enum rfc2047_type {
290         RFC2047_SUBJECT,
291         RFC2047_ADDRESS
292 };
293
294 static int is_rfc2047_special(char ch, enum rfc2047_type type)
295 {
296         /*
297          * rfc2047, section 4.2:
298          *
299          *    8-bit values which correspond to printable ASCII characters other
300          *    than "=", "?", and "_" (underscore), MAY be represented as those
301          *    characters.  (But see section 5 for restrictions.)  In
302          *    particular, SPACE and TAB MUST NOT be represented as themselves
303          *    within encoded words.
304          */
305
306         /*
307          * rule out non-ASCII characters and non-printable characters (the
308          * non-ASCII check should be redundant as isprint() is not localized
309          * and only knows about ASCII, but be defensive about that)
310          */
311         if (non_ascii(ch) || !isprint(ch))
312                 return 1;
313
314         /*
315          * rule out special printable characters (' ' should be the only
316          * whitespace character considered printable, but be defensive and use
317          * isspace())
318          */
319         if (isspace(ch) || ch == '=' || ch == '?' || ch == '_')
320                 return 1;
321
322         /*
323          * rfc2047, section 5.3:
324          *
325          *    As a replacement for a 'word' entity within a 'phrase', for example,
326          *    one that precedes an address in a From, To, or Cc header.  The ABNF
327          *    definition for 'phrase' from RFC 822 thus becomes:
328          *
329          *    phrase = 1*( encoded-word / word )
330          *
331          *    In this case the set of characters that may be used in a "Q"-encoded
332          *    'encoded-word' is restricted to: <upper and lower case ASCII
333          *    letters, decimal digits, "!", "*", "+", "-", "/", "=", and "_"
334          *    (underscore, ASCII 95.)>.  An 'encoded-word' that appears within a
335          *    'phrase' MUST be separated from any adjacent 'word', 'text' or
336          *    'special' by 'linear-white-space'.
337          */
338
339         if (type != RFC2047_ADDRESS)
340                 return 0;
341
342         /* '=' and '_' are special cases and have been checked above */
343         return !(isalnum(ch) || ch == '!' || ch == '*' || ch == '+' || ch == '-' || ch == '/');
344 }
345
346 static int needs_rfc2047_encoding(const char *line, int len,
347                                   enum rfc2047_type type)
348 {
349         int i;
350
351         for (i = 0; i < len; i++) {
352                 int ch = line[i];
353                 if (non_ascii(ch) || ch == '\n')
354                         return 1;
355                 if ((i + 1 < len) && (ch == '=' && line[i+1] == '?'))
356                         return 1;
357         }
358
359         return 0;
360 }
361
362 static void add_rfc2047(struct strbuf *sb, const char *line, size_t len,
363                        const char *encoding, enum rfc2047_type type)
364 {
365         static const int max_encoded_length = 76; /* per rfc2047 */
366         int i;
367         int line_len = last_line_length(sb);
368
369         strbuf_grow(sb, len * 3 + strlen(encoding) + 100);
370         strbuf_addf(sb, "=?%s?q?", encoding);
371         line_len += strlen(encoding) + 5; /* 5 for =??q? */
372
373         while (len) {
374                 /*
375                  * RFC 2047, section 5 (3):
376                  *
377                  * Each 'encoded-word' MUST represent an integral number of
378                  * characters.  A multi-octet character may not be split across
379                  * adjacent 'encoded- word's.
380                  */
381                 const unsigned char *p = (const unsigned char *)line;
382                 int chrlen = mbs_chrlen(&line, &len, encoding);
383                 int is_special = (chrlen > 1) || is_rfc2047_special(*p, type);
384
385                 /* "=%02X" * chrlen, or the byte itself */
386                 const char *encoded_fmt = is_special ? "=%02X"    : "%c";
387                 int         encoded_len = is_special ? 3 * chrlen : 1;
388
389                 /*
390                  * According to RFC 2047, we could encode the special character
391                  * ' ' (space) with '_' (underscore) for readability. But many
392                  * programs do not understand this and just leave the
393                  * underscore in place. Thus, we do nothing special here, which
394                  * causes ' ' to be encoded as '=20', avoiding this problem.
395                  */
396
397                 if (line_len + encoded_len + 2 > max_encoded_length) {
398                         /* It won't fit with trailing "?=" --- break the line */
399                         strbuf_addf(sb, "?=\n =?%s?q?", encoding);
400                         line_len = strlen(encoding) + 5 + 1; /* =??q? plus SP */
401                 }
402
403                 for (i = 0; i < chrlen; i++)
404                         strbuf_addf(sb, encoded_fmt, p[i]);
405                 line_len += encoded_len;
406         }
407         strbuf_addstr(sb, "?=");
408 }
409
410 const char *show_ident_date(const struct ident_split *ident,
411                             const struct date_mode *mode)
412 {
413         timestamp_t date = 0;
414         long tz = 0;
415
416         if (ident->date_begin && ident->date_end)
417                 date = parse_timestamp(ident->date_begin, NULL, 10);
418         if (date_overflows(date))
419                 date = 0;
420         else {
421                 if (ident->tz_begin && ident->tz_end)
422                         tz = strtol(ident->tz_begin, NULL, 10);
423                 if (tz >= INT_MAX || tz <= INT_MIN)
424                         tz = 0;
425         }
426         return show_date(date, tz, mode);
427 }
428
429 void pp_user_info(struct pretty_print_context *pp,
430                   const char *what, struct strbuf *sb,
431                   const char *line, const char *encoding)
432 {
433         struct ident_split ident;
434         char *line_end;
435         const char *mailbuf, *namebuf;
436         size_t namelen, maillen;
437         int max_length = 78; /* per rfc2822 */
438
439         if (pp->fmt == CMIT_FMT_ONELINE)
440                 return;
441
442         line_end = strchrnul(line, '\n');
443         if (split_ident_line(&ident, line, line_end - line))
444                 return;
445
446         mailbuf = ident.mail_begin;
447         maillen = ident.mail_end - ident.mail_begin;
448         namebuf = ident.name_begin;
449         namelen = ident.name_end - ident.name_begin;
450
451         if (pp->mailmap)
452                 map_user(pp->mailmap, &mailbuf, &maillen, &namebuf, &namelen);
453
454         if (cmit_fmt_is_mail(pp->fmt)) {
455                 if (pp->from_ident && ident_cmp(pp->from_ident, &ident)) {
456                         struct strbuf buf = STRBUF_INIT;
457
458                         strbuf_addstr(&buf, "From: ");
459                         strbuf_add(&buf, namebuf, namelen);
460                         strbuf_addstr(&buf, " <");
461                         strbuf_add(&buf, mailbuf, maillen);
462                         strbuf_addstr(&buf, ">\n");
463                         string_list_append(&pp->in_body_headers,
464                                            strbuf_detach(&buf, NULL));
465
466                         mailbuf = pp->from_ident->mail_begin;
467                         maillen = pp->from_ident->mail_end - mailbuf;
468                         namebuf = pp->from_ident->name_begin;
469                         namelen = pp->from_ident->name_end - namebuf;
470                 }
471
472                 strbuf_addstr(sb, "From: ");
473                 if (needs_rfc2047_encoding(namebuf, namelen, RFC2047_ADDRESS)) {
474                         add_rfc2047(sb, namebuf, namelen,
475                                     encoding, RFC2047_ADDRESS);
476                         max_length = 76; /* per rfc2047 */
477                 } else if (needs_rfc822_quoting(namebuf, namelen)) {
478                         struct strbuf quoted = STRBUF_INIT;
479                         add_rfc822_quoted(&quoted, namebuf, namelen);
480                         strbuf_add_wrapped_bytes(sb, quoted.buf, quoted.len,
481                                                         -6, 1, max_length);
482                         strbuf_release(&quoted);
483                 } else {
484                         strbuf_add_wrapped_bytes(sb, namebuf, namelen,
485                                                  -6, 1, max_length);
486                 }
487
488                 if (max_length <
489                     last_line_length(sb) + strlen(" <") + maillen + strlen(">"))
490                         strbuf_addch(sb, '\n');
491                 strbuf_addf(sb, " <%.*s>\n", (int)maillen, mailbuf);
492         } else {
493                 strbuf_addf(sb, "%s: %.*s%.*s <%.*s>\n", what,
494                             (pp->fmt == CMIT_FMT_FULLER) ? 4 : 0, "    ",
495                             (int)namelen, namebuf, (int)maillen, mailbuf);
496         }
497
498         switch (pp->fmt) {
499         case CMIT_FMT_MEDIUM:
500                 strbuf_addf(sb, "Date:   %s\n",
501                             show_ident_date(&ident, &pp->date_mode));
502                 break;
503         case CMIT_FMT_EMAIL:
504         case CMIT_FMT_MBOXRD:
505                 strbuf_addf(sb, "Date: %s\n",
506                             show_ident_date(&ident, DATE_MODE(RFC2822)));
507                 break;
508         case CMIT_FMT_FULLER:
509                 strbuf_addf(sb, "%sDate: %s\n", what,
510                             show_ident_date(&ident, &pp->date_mode));
511                 break;
512         default:
513                 /* notin' */
514                 break;
515         }
516 }
517
518 static int is_blank_line(const char *line, int *len_p)
519 {
520         int len = *len_p;
521         while (len && isspace(line[len - 1]))
522                 len--;
523         *len_p = len;
524         return !len;
525 }
526
527 const char *skip_blank_lines(const char *msg)
528 {
529         for (;;) {
530                 int linelen = get_one_line(msg);
531                 int ll = linelen;
532                 if (!linelen)
533                         break;
534                 if (!is_blank_line(msg, &ll))
535                         break;
536                 msg += linelen;
537         }
538         return msg;
539 }
540
541 static void add_merge_info(const struct pretty_print_context *pp,
542                            struct strbuf *sb, const struct commit *commit)
543 {
544         struct commit_list *parent = commit->parents;
545
546         if ((pp->fmt == CMIT_FMT_ONELINE) || (cmit_fmt_is_mail(pp->fmt)) ||
547             !parent || !parent->next)
548                 return;
549
550         strbuf_addstr(sb, "Merge:");
551
552         while (parent) {
553                 struct object_id *oidp = &parent->item->object.oid;
554                 strbuf_addch(sb, ' ');
555                 if (pp->abbrev)
556                         strbuf_add_unique_abbrev(sb, oidp, pp->abbrev);
557                 else
558                         strbuf_addstr(sb, oid_to_hex(oidp));
559                 parent = parent->next;
560         }
561         strbuf_addch(sb, '\n');
562 }
563
564 static char *get_header(const char *msg, const char *key)
565 {
566         size_t len;
567         const char *v = find_commit_header(msg, key, &len);
568         return v ? xmemdupz(v, len) : NULL;
569 }
570
571 static char *replace_encoding_header(char *buf, const char *encoding)
572 {
573         struct strbuf tmp = STRBUF_INIT;
574         size_t start, len;
575         char *cp = buf;
576
577         /* guess if there is an encoding header before a \n\n */
578         while (!starts_with(cp, "encoding ")) {
579                 cp = strchr(cp, '\n');
580                 if (!cp || *++cp == '\n')
581                         return buf;
582         }
583         start = cp - buf;
584         cp = strchr(cp, '\n');
585         if (!cp)
586                 return buf; /* should not happen but be defensive */
587         len = cp + 1 - (buf + start);
588
589         strbuf_attach(&tmp, buf, strlen(buf), strlen(buf) + 1);
590         if (is_encoding_utf8(encoding)) {
591                 /* we have re-coded to UTF-8; drop the header */
592                 strbuf_remove(&tmp, start, len);
593         } else {
594                 /* just replaces XXXX in 'encoding XXXX\n' */
595                 strbuf_splice(&tmp, start + strlen("encoding "),
596                                           len - strlen("encoding \n"),
597                                           encoding, strlen(encoding));
598         }
599         return strbuf_detach(&tmp, NULL);
600 }
601
602 const char *repo_logmsg_reencode(struct repository *r,
603                                  const struct commit *commit,
604                                  char **commit_encoding,
605                                  const char *output_encoding)
606 {
607         static const char *utf8 = "UTF-8";
608         const char *use_encoding;
609         char *encoding;
610         const char *msg = repo_get_commit_buffer(r, commit, NULL);
611         char *out;
612
613         if (!output_encoding || !*output_encoding) {
614                 if (commit_encoding)
615                         *commit_encoding = get_header(msg, "encoding");
616                 return msg;
617         }
618         encoding = get_header(msg, "encoding");
619         if (commit_encoding)
620                 *commit_encoding = encoding;
621         use_encoding = encoding ? encoding : utf8;
622         if (same_encoding(use_encoding, output_encoding)) {
623                 /*
624                  * No encoding work to be done. If we have no encoding header
625                  * at all, then there's nothing to do, and we can return the
626                  * message verbatim (whether newly allocated or not).
627                  */
628                 if (!encoding)
629                         return msg;
630
631                 /*
632                  * Otherwise, we still want to munge the encoding header in the
633                  * result, which will be done by modifying the buffer. If we
634                  * are using a fresh copy, we can reuse it. But if we are using
635                  * the cached copy from get_commit_buffer, we need to duplicate it
636                  * to avoid munging the cached copy.
637                  */
638                 if (msg == get_cached_commit_buffer(r, commit, NULL))
639                         out = xstrdup(msg);
640                 else
641                         out = (char *)msg;
642         }
643         else {
644                 /*
645                  * There's actual encoding work to do. Do the reencoding, which
646                  * still leaves the header to be replaced in the next step. At
647                  * this point, we are done with msg. If we allocated a fresh
648                  * copy, we can free it.
649                  */
650                 out = reencode_string(msg, output_encoding, use_encoding);
651                 if (out)
652                         repo_unuse_commit_buffer(r, commit, msg);
653         }
654
655         /*
656          * This replacement actually consumes the buffer we hand it, so we do
657          * not have to worry about freeing the old "out" here.
658          */
659         if (out)
660                 out = replace_encoding_header(out, output_encoding);
661
662         if (!commit_encoding)
663                 free(encoding);
664         /*
665          * If the re-encoding failed, out might be NULL here; in that
666          * case we just return the commit message verbatim.
667          */
668         return out ? out : msg;
669 }
670
671 static int mailmap_name(const char **email, size_t *email_len,
672                         const char **name, size_t *name_len)
673 {
674         static struct string_list *mail_map;
675         if (!mail_map) {
676                 mail_map = xcalloc(1, sizeof(*mail_map));
677                 read_mailmap(mail_map, NULL);
678         }
679         return mail_map->nr && map_user(mail_map, email, email_len, name, name_len);
680 }
681
682 static size_t format_person_part(struct strbuf *sb, char part,
683                                  const char *msg, int len,
684                                  const struct date_mode *dmode)
685 {
686         /* currently all placeholders have same length */
687         const int placeholder_len = 2;
688         struct ident_split s;
689         const char *name, *mail;
690         size_t maillen, namelen;
691
692         if (split_ident_line(&s, msg, len) < 0)
693                 goto skip;
694
695         name = s.name_begin;
696         namelen = s.name_end - s.name_begin;
697         mail = s.mail_begin;
698         maillen = s.mail_end - s.mail_begin;
699
700         if (part == 'N' || part == 'E') /* mailmap lookup */
701                 mailmap_name(&mail, &maillen, &name, &namelen);
702         if (part == 'n' || part == 'N') {       /* name */
703                 strbuf_add(sb, name, namelen);
704                 return placeholder_len;
705         }
706         if (part == 'e' || part == 'E') {       /* email */
707                 strbuf_add(sb, mail, maillen);
708                 return placeholder_len;
709         }
710
711         if (!s.date_begin)
712                 goto skip;
713
714         if (part == 't') {      /* date, UNIX timestamp */
715                 strbuf_add(sb, s.date_begin, s.date_end - s.date_begin);
716                 return placeholder_len;
717         }
718
719         switch (part) {
720         case 'd':       /* date */
721                 strbuf_addstr(sb, show_ident_date(&s, dmode));
722                 return placeholder_len;
723         case 'D':       /* date, RFC2822 style */
724                 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(RFC2822)));
725                 return placeholder_len;
726         case 'r':       /* date, relative */
727                 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(RELATIVE)));
728                 return placeholder_len;
729         case 'i':       /* date, ISO 8601-like */
730                 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(ISO8601)));
731                 return placeholder_len;
732         case 'I':       /* date, ISO 8601 strict */
733                 strbuf_addstr(sb, show_ident_date(&s, DATE_MODE(ISO8601_STRICT)));
734                 return placeholder_len;
735         }
736
737 skip:
738         /*
739          * reading from either a bogus commit, or a reflog entry with
740          * %gn, %ge, etc.; 'sb' cannot be updated, but we still need
741          * to compute a valid return value.
742          */
743         if (part == 'n' || part == 'e' || part == 't' || part == 'd'
744             || part == 'D' || part == 'r' || part == 'i')
745                 return placeholder_len;
746
747         return 0; /* unknown placeholder */
748 }
749
750 struct chunk {
751         size_t off;
752         size_t len;
753 };
754
755 enum flush_type {
756         no_flush,
757         flush_right,
758         flush_left,
759         flush_left_and_steal,
760         flush_both
761 };
762
763 enum trunc_type {
764         trunc_none,
765         trunc_left,
766         trunc_middle,
767         trunc_right
768 };
769
770 struct format_commit_context {
771         const struct commit *commit;
772         const struct pretty_print_context *pretty_ctx;
773         unsigned commit_header_parsed:1;
774         unsigned commit_message_parsed:1;
775         struct signature_check signature_check;
776         enum flush_type flush_type;
777         enum trunc_type truncate;
778         const char *message;
779         char *commit_encoding;
780         size_t width, indent1, indent2;
781         int auto_color;
782         int padding;
783
784         /* These offsets are relative to the start of the commit message. */
785         struct chunk author;
786         struct chunk committer;
787         size_t message_off;
788         size_t subject_off;
789         size_t body_off;
790
791         /* The following ones are relative to the result struct strbuf. */
792         size_t wrap_start;
793 };
794
795 static void parse_commit_header(struct format_commit_context *context)
796 {
797         const char *msg = context->message;
798         int i;
799
800         for (i = 0; msg[i]; i++) {
801                 const char *name;
802                 int eol;
803                 for (eol = i; msg[eol] && msg[eol] != '\n'; eol++)
804                         ; /* do nothing */
805
806                 if (i == eol) {
807                         break;
808                 } else if (skip_prefix(msg + i, "author ", &name)) {
809                         context->author.off = name - msg;
810                         context->author.len = msg + eol - name;
811                 } else if (skip_prefix(msg + i, "committer ", &name)) {
812                         context->committer.off = name - msg;
813                         context->committer.len = msg + eol - name;
814                 }
815                 i = eol;
816         }
817         context->message_off = i;
818         context->commit_header_parsed = 1;
819 }
820
821 static int istitlechar(char c)
822 {
823         return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
824                 (c >= '0' && c <= '9') || c == '.' || c == '_';
825 }
826
827 static void format_sanitized_subject(struct strbuf *sb, const char *msg)
828 {
829         size_t trimlen;
830         size_t start_len = sb->len;
831         int space = 2;
832
833         for (; *msg && *msg != '\n'; msg++) {
834                 if (istitlechar(*msg)) {
835                         if (space == 1)
836                                 strbuf_addch(sb, '-');
837                         space = 0;
838                         strbuf_addch(sb, *msg);
839                         if (*msg == '.')
840                                 while (*(msg+1) == '.')
841                                         msg++;
842                 } else
843                         space |= 1;
844         }
845
846         /* trim any trailing '.' or '-' characters */
847         trimlen = 0;
848         while (sb->len - trimlen > start_len &&
849                 (sb->buf[sb->len - 1 - trimlen] == '.'
850                 || sb->buf[sb->len - 1 - trimlen] == '-'))
851                 trimlen++;
852         strbuf_remove(sb, sb->len - trimlen, trimlen);
853 }
854
855 const char *format_subject(struct strbuf *sb, const char *msg,
856                            const char *line_separator)
857 {
858         int first = 1;
859
860         for (;;) {
861                 const char *line = msg;
862                 int linelen = get_one_line(line);
863
864                 msg += linelen;
865                 if (!linelen || is_blank_line(line, &linelen))
866                         break;
867
868                 if (!sb)
869                         continue;
870                 strbuf_grow(sb, linelen + 2);
871                 if (!first)
872                         strbuf_addstr(sb, line_separator);
873                 strbuf_add(sb, line, linelen);
874                 first = 0;
875         }
876         return msg;
877 }
878
879 static void parse_commit_message(struct format_commit_context *c)
880 {
881         const char *msg = c->message + c->message_off;
882         const char *start = c->message;
883
884         msg = skip_blank_lines(msg);
885         c->subject_off = msg - start;
886
887         msg = format_subject(NULL, msg, NULL);
888         msg = skip_blank_lines(msg);
889         c->body_off = msg - start;
890
891         c->commit_message_parsed = 1;
892 }
893
894 static void strbuf_wrap(struct strbuf *sb, size_t pos,
895                         size_t width, size_t indent1, size_t indent2)
896 {
897         struct strbuf tmp = STRBUF_INIT;
898
899         if (pos)
900                 strbuf_add(&tmp, sb->buf, pos);
901         strbuf_add_wrapped_text(&tmp, sb->buf + pos,
902                                 (int) indent1, (int) indent2, (int) width);
903         strbuf_swap(&tmp, sb);
904         strbuf_release(&tmp);
905 }
906
907 static void rewrap_message_tail(struct strbuf *sb,
908                                 struct format_commit_context *c,
909                                 size_t new_width, size_t new_indent1,
910                                 size_t new_indent2)
911 {
912         if (c->width == new_width && c->indent1 == new_indent1 &&
913             c->indent2 == new_indent2)
914                 return;
915         if (c->wrap_start < sb->len)
916                 strbuf_wrap(sb, c->wrap_start, c->width, c->indent1, c->indent2);
917         c->wrap_start = sb->len;
918         c->width = new_width;
919         c->indent1 = new_indent1;
920         c->indent2 = new_indent2;
921 }
922
923 static int format_reflog_person(struct strbuf *sb,
924                                 char part,
925                                 struct reflog_walk_info *log,
926                                 const struct date_mode *dmode)
927 {
928         const char *ident;
929
930         if (!log)
931                 return 2;
932
933         ident = get_reflog_ident(log);
934         if (!ident)
935                 return 2;
936
937         return format_person_part(sb, part, ident, strlen(ident), dmode);
938 }
939
940 static size_t parse_color(struct strbuf *sb, /* in UTF-8 */
941                           const char *placeholder,
942                           struct format_commit_context *c)
943 {
944         const char *rest = placeholder;
945         const char *basic_color = NULL;
946
947         if (placeholder[1] == '(') {
948                 const char *begin = placeholder + 2;
949                 const char *end = strchr(begin, ')');
950                 char color[COLOR_MAXLEN];
951
952                 if (!end)
953                         return 0;
954
955                 if (skip_prefix(begin, "auto,", &begin)) {
956                         if (!want_color(c->pretty_ctx->color))
957                                 return end - placeholder + 1;
958                 } else if (skip_prefix(begin, "always,", &begin)) {
959                         /* nothing to do; we do not respect want_color at all */
960                 } else {
961                         /* the default is the same as "auto" */
962                         if (!want_color(c->pretty_ctx->color))
963                                 return end - placeholder + 1;
964                 }
965
966                 if (color_parse_mem(begin, end - begin, color) < 0)
967                         die(_("unable to parse --pretty format"));
968                 strbuf_addstr(sb, color);
969                 return end - placeholder + 1;
970         }
971
972         /*
973          * We handle things like "%C(red)" above; for historical reasons, there
974          * are a few colors that can be specified without parentheses (and
975          * they cannot support things like "auto" or "always" at all).
976          */
977         if (skip_prefix(placeholder + 1, "red", &rest))
978                 basic_color = GIT_COLOR_RED;
979         else if (skip_prefix(placeholder + 1, "green", &rest))
980                 basic_color = GIT_COLOR_GREEN;
981         else if (skip_prefix(placeholder + 1, "blue", &rest))
982                 basic_color = GIT_COLOR_BLUE;
983         else if (skip_prefix(placeholder + 1, "reset", &rest))
984                 basic_color = GIT_COLOR_RESET;
985
986         if (basic_color && want_color(c->pretty_ctx->color))
987                 strbuf_addstr(sb, basic_color);
988
989         return rest - placeholder;
990 }
991
992 static size_t parse_padding_placeholder(struct strbuf *sb,
993                                         const char *placeholder,
994                                         struct format_commit_context *c)
995 {
996         const char *ch = placeholder;
997         enum flush_type flush_type;
998         int to_column = 0;
999
1000         switch (*ch++) {
1001         case '<':
1002                 flush_type = flush_right;
1003                 break;
1004         case '>':
1005                 if (*ch == '<') {
1006                         flush_type = flush_both;
1007                         ch++;
1008                 } else if (*ch == '>') {
1009                         flush_type = flush_left_and_steal;
1010                         ch++;
1011                 } else
1012                         flush_type = flush_left;
1013                 break;
1014         default:
1015                 return 0;
1016         }
1017
1018         /* the next value means "wide enough to that column" */
1019         if (*ch == '|') {
1020                 to_column = 1;
1021                 ch++;
1022         }
1023
1024         if (*ch == '(') {
1025                 const char *start = ch + 1;
1026                 const char *end = start + strcspn(start, ",)");
1027                 char *next;
1028                 int width;
1029                 if (!end || end == start)
1030                         return 0;
1031                 width = strtol(start, &next, 10);
1032                 if (next == start || width == 0)
1033                         return 0;
1034                 if (width < 0) {
1035                         if (to_column)
1036                                 width += term_columns();
1037                         if (width < 0)
1038                                 return 0;
1039                 }
1040                 c->padding = to_column ? -width : width;
1041                 c->flush_type = flush_type;
1042
1043                 if (*end == ',') {
1044                         start = end + 1;
1045                         end = strchr(start, ')');
1046                         if (!end || end == start)
1047                                 return 0;
1048                         if (starts_with(start, "trunc)"))
1049                                 c->truncate = trunc_right;
1050                         else if (starts_with(start, "ltrunc)"))
1051                                 c->truncate = trunc_left;
1052                         else if (starts_with(start, "mtrunc)"))
1053                                 c->truncate = trunc_middle;
1054                         else
1055                                 return 0;
1056                 } else
1057                         c->truncate = trunc_none;
1058
1059                 return end - placeholder + 1;
1060         }
1061         return 0;
1062 }
1063
1064 static int match_placeholder_arg_value(const char *to_parse, const char *candidate,
1065                                        const char **end, const char **valuestart,
1066                                        size_t *valuelen)
1067 {
1068         const char *p;
1069
1070         if (!(skip_prefix(to_parse, candidate, &p)))
1071                 return 0;
1072         if (valuestart) {
1073                 if (*p == '=') {
1074                         *valuestart = p + 1;
1075                         *valuelen = strcspn(*valuestart, ",)");
1076                         p = *valuestart + *valuelen;
1077                 } else {
1078                         if (*p != ',' && *p != ')')
1079                                 return 0;
1080                         *valuestart = NULL;
1081                         *valuelen = 0;
1082                 }
1083         }
1084         if (*p == ',') {
1085                 *end = p + 1;
1086                 return 1;
1087         }
1088         if (*p == ')') {
1089                 *end = p;
1090                 return 1;
1091         }
1092         return 0;
1093 }
1094
1095 static int match_placeholder_bool_arg(const char *to_parse, const char *candidate,
1096                                       const char **end, int *val)
1097 {
1098         const char *argval;
1099         char *strval;
1100         size_t arglen;
1101         int v;
1102
1103         if (!match_placeholder_arg_value(to_parse, candidate, end, &argval, &arglen))
1104                 return 0;
1105
1106         if (!argval) {
1107                 *val = 1;
1108                 return 1;
1109         }
1110
1111         strval = xstrndup(argval, arglen);
1112         v = git_parse_maybe_bool(strval);
1113         free(strval);
1114
1115         if (v == -1)
1116                 return 0;
1117
1118         *val = v;
1119
1120         return 1;
1121 }
1122
1123 static int format_trailer_match_cb(const struct strbuf *key, void *ud)
1124 {
1125         const struct string_list *list = ud;
1126         const struct string_list_item *item;
1127
1128         for_each_string_list_item (item, list) {
1129                 if (key->len == (uintptr_t)item->util &&
1130                     !strncasecmp(item->string, key->buf, key->len))
1131                         return 1;
1132         }
1133         return 0;
1134 }
1135
1136 static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */
1137                                 const char *placeholder,
1138                                 void *context)
1139 {
1140         struct format_commit_context *c = context;
1141         const struct commit *commit = c->commit;
1142         const char *msg = c->message;
1143         struct commit_list *p;
1144         const char *arg;
1145         size_t res;
1146         char **slot;
1147
1148         /* these are independent of the commit */
1149         res = strbuf_expand_literal_cb(sb, placeholder, NULL);
1150         if (res)
1151                 return res;
1152
1153         switch (placeholder[0]) {
1154         case 'C':
1155                 if (starts_with(placeholder + 1, "(auto)")) {
1156                         c->auto_color = want_color(c->pretty_ctx->color);
1157                         if (c->auto_color && sb->len)
1158                                 strbuf_addstr(sb, GIT_COLOR_RESET);
1159                         return 7; /* consumed 7 bytes, "C(auto)" */
1160                 } else {
1161                         int ret = parse_color(sb, placeholder, c);
1162                         if (ret)
1163                                 c->auto_color = 0;
1164                         /*
1165                          * Otherwise, we decided to treat %C<unknown>
1166                          * as a literal string, and the previous
1167                          * %C(auto) is still valid.
1168                          */
1169                         return ret;
1170                 }
1171         case 'w':
1172                 if (placeholder[1] == '(') {
1173                         unsigned long width = 0, indent1 = 0, indent2 = 0;
1174                         char *next;
1175                         const char *start = placeholder + 2;
1176                         const char *end = strchr(start, ')');
1177                         if (!end)
1178                                 return 0;
1179                         if (end > start) {
1180                                 width = strtoul(start, &next, 10);
1181                                 if (*next == ',') {
1182                                         indent1 = strtoul(next + 1, &next, 10);
1183                                         if (*next == ',') {
1184                                                 indent2 = strtoul(next + 1,
1185                                                                  &next, 10);
1186                                         }
1187                                 }
1188                                 if (*next != ')')
1189                                         return 0;
1190                         }
1191                         rewrap_message_tail(sb, c, width, indent1, indent2);
1192                         return end - placeholder + 1;
1193                 } else
1194                         return 0;
1195
1196         case '<':
1197         case '>':
1198                 return parse_padding_placeholder(sb, placeholder, c);
1199         }
1200
1201         /* these depend on the commit */
1202         if (!commit->object.parsed)
1203                 parse_object(the_repository, &commit->object.oid);
1204
1205         switch (placeholder[0]) {
1206         case 'H':               /* commit hash */
1207                 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT));
1208                 strbuf_addstr(sb, oid_to_hex(&commit->object.oid));
1209                 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
1210                 return 1;
1211         case 'h':               /* abbreviated commit hash */
1212                 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_COMMIT));
1213                 strbuf_add_unique_abbrev(sb, &commit->object.oid,
1214                                          c->pretty_ctx->abbrev);
1215                 strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
1216                 return 1;
1217         case 'T':               /* tree hash */
1218                 strbuf_addstr(sb, oid_to_hex(get_commit_tree_oid(commit)));
1219                 return 1;
1220         case 't':               /* abbreviated tree hash */
1221                 strbuf_add_unique_abbrev(sb,
1222                                          get_commit_tree_oid(commit),
1223                                          c->pretty_ctx->abbrev);
1224                 return 1;
1225         case 'P':               /* parent hashes */
1226                 for (p = commit->parents; p; p = p->next) {
1227                         if (p != commit->parents)
1228                                 strbuf_addch(sb, ' ');
1229                         strbuf_addstr(sb, oid_to_hex(&p->item->object.oid));
1230                 }
1231                 return 1;
1232         case 'p':               /* abbreviated parent hashes */
1233                 for (p = commit->parents; p; p = p->next) {
1234                         if (p != commit->parents)
1235                                 strbuf_addch(sb, ' ');
1236                         strbuf_add_unique_abbrev(sb, &p->item->object.oid,
1237                                                  c->pretty_ctx->abbrev);
1238                 }
1239                 return 1;
1240         case 'm':               /* left/right/bottom */
1241                 strbuf_addstr(sb, get_revision_mark(NULL, commit));
1242                 return 1;
1243         case 'd':
1244                 load_ref_decorations(NULL, DECORATE_SHORT_REFS);
1245                 format_decorations(sb, commit, c->auto_color);
1246                 return 1;
1247         case 'D':
1248                 load_ref_decorations(NULL, DECORATE_SHORT_REFS);
1249                 format_decorations_extended(sb, commit, c->auto_color, "", ", ", "");
1250                 return 1;
1251         case 'S':               /* tag/branch like --source */
1252                 if (!(c->pretty_ctx->rev && c->pretty_ctx->rev->sources))
1253                         return 0;
1254                 slot = revision_sources_at(c->pretty_ctx->rev->sources, commit);
1255                 if (!(slot && *slot))
1256                         return 0;
1257                 strbuf_addstr(sb, *slot);
1258                 return 1;
1259         case 'g':               /* reflog info */
1260                 switch(placeholder[1]) {
1261                 case 'd':       /* reflog selector */
1262                 case 'D':
1263                         if (c->pretty_ctx->reflog_info)
1264                                 get_reflog_selector(sb,
1265                                                     c->pretty_ctx->reflog_info,
1266                                                     &c->pretty_ctx->date_mode,
1267                                                     c->pretty_ctx->date_mode_explicit,
1268                                                     (placeholder[1] == 'd'));
1269                         return 2;
1270                 case 's':       /* reflog message */
1271                         if (c->pretty_ctx->reflog_info)
1272                                 get_reflog_message(sb, c->pretty_ctx->reflog_info);
1273                         return 2;
1274                 case 'n':
1275                 case 'N':
1276                 case 'e':
1277                 case 'E':
1278                         return format_reflog_person(sb,
1279                                                     placeholder[1],
1280                                                     c->pretty_ctx->reflog_info,
1281                                                     &c->pretty_ctx->date_mode);
1282                 }
1283                 return 0;       /* unknown %g placeholder */
1284         case 'N':
1285                 if (c->pretty_ctx->notes_message) {
1286                         strbuf_addstr(sb, c->pretty_ctx->notes_message);
1287                         return 1;
1288                 }
1289                 return 0;
1290         }
1291
1292         if (placeholder[0] == 'G') {
1293                 if (!c->signature_check.result)
1294                         check_commit_signature(c->commit, &(c->signature_check));
1295                 switch (placeholder[1]) {
1296                 case 'G':
1297                         if (c->signature_check.gpg_output)
1298                                 strbuf_addstr(sb, c->signature_check.gpg_output);
1299                         break;
1300                 case '?':
1301                         switch (c->signature_check.result) {
1302                         case 'G':
1303                         case 'B':
1304                         case 'E':
1305                         case 'U':
1306                         case 'N':
1307                         case 'X':
1308                         case 'Y':
1309                         case 'R':
1310                                 strbuf_addch(sb, c->signature_check.result);
1311                         }
1312                         break;
1313                 case 'S':
1314                         if (c->signature_check.signer)
1315                                 strbuf_addstr(sb, c->signature_check.signer);
1316                         break;
1317                 case 'K':
1318                         if (c->signature_check.key)
1319                                 strbuf_addstr(sb, c->signature_check.key);
1320                         break;
1321                 case 'F':
1322                         if (c->signature_check.fingerprint)
1323                                 strbuf_addstr(sb, c->signature_check.fingerprint);
1324                         break;
1325                 case 'P':
1326                         if (c->signature_check.primary_key_fingerprint)
1327                                 strbuf_addstr(sb, c->signature_check.primary_key_fingerprint);
1328                         break;
1329                 default:
1330                         return 0;
1331                 }
1332                 return 2;
1333         }
1334
1335
1336         /* For the rest we have to parse the commit header. */
1337         if (!c->commit_header_parsed)
1338                 parse_commit_header(c);
1339
1340         switch (placeholder[0]) {
1341         case 'a':       /* author ... */
1342                 return format_person_part(sb, placeholder[1],
1343                                    msg + c->author.off, c->author.len,
1344                                    &c->pretty_ctx->date_mode);
1345         case 'c':       /* committer ... */
1346                 return format_person_part(sb, placeholder[1],
1347                                    msg + c->committer.off, c->committer.len,
1348                                    &c->pretty_ctx->date_mode);
1349         case 'e':       /* encoding */
1350                 if (c->commit_encoding)
1351                         strbuf_addstr(sb, c->commit_encoding);
1352                 return 1;
1353         case 'B':       /* raw body */
1354                 /* message_off is always left at the initial newline */
1355                 strbuf_addstr(sb, msg + c->message_off + 1);
1356                 return 1;
1357         }
1358
1359         /* Now we need to parse the commit message. */
1360         if (!c->commit_message_parsed)
1361                 parse_commit_message(c);
1362
1363         switch (placeholder[0]) {
1364         case 's':       /* subject */
1365                 format_subject(sb, msg + c->subject_off, " ");
1366                 return 1;
1367         case 'f':       /* sanitized subject */
1368                 format_sanitized_subject(sb, msg + c->subject_off);
1369                 return 1;
1370         case 'b':       /* body */
1371                 strbuf_addstr(sb, msg + c->body_off);
1372                 return 1;
1373         }
1374
1375         if (skip_prefix(placeholder, "(trailers", &arg)) {
1376                 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
1377                 struct string_list filter_list = STRING_LIST_INIT_NODUP;
1378                 struct strbuf sepbuf = STRBUF_INIT;
1379                 size_t ret = 0;
1380
1381                 opts.no_divider = 1;
1382
1383                 if (*arg == ':') {
1384                         arg++;
1385                         for (;;) {
1386                                 const char *argval;
1387                                 size_t arglen;
1388
1389                                 if (match_placeholder_arg_value(arg, "key", &arg, &argval, &arglen)) {
1390                                         uintptr_t len = arglen;
1391
1392                                         if (!argval)
1393                                                 goto trailer_out;
1394
1395                                         if (len && argval[len - 1] == ':')
1396                                                 len--;
1397                                         string_list_append(&filter_list, argval)->util = (char *)len;
1398
1399                                         opts.filter = format_trailer_match_cb;
1400                                         opts.filter_data = &filter_list;
1401                                         opts.only_trailers = 1;
1402                                 } else if (match_placeholder_arg_value(arg, "separator", &arg, &argval, &arglen)) {
1403                                         char *fmt;
1404
1405                                         strbuf_reset(&sepbuf);
1406                                         fmt = xstrndup(argval, arglen);
1407                                         strbuf_expand(&sepbuf, fmt, strbuf_expand_literal_cb, NULL);
1408                                         free(fmt);
1409                                         opts.separator = &sepbuf;
1410                                 } else if (!match_placeholder_bool_arg(arg, "only", &arg, &opts.only_trailers) &&
1411                                            !match_placeholder_bool_arg(arg, "unfold", &arg, &opts.unfold) &&
1412                                            !match_placeholder_bool_arg(arg, "valueonly", &arg, &opts.value_only))
1413                                         break;
1414                         }
1415                 }
1416                 if (*arg == ')') {
1417                         format_trailers_from_commit(sb, msg + c->subject_off, &opts);
1418                         ret = arg - placeholder + 1;
1419                 }
1420         trailer_out:
1421                 string_list_clear(&filter_list, 0);
1422                 strbuf_release(&sepbuf);
1423                 return ret;
1424         }
1425
1426         return 0;       /* unknown placeholder */
1427 }
1428
1429 static size_t format_and_pad_commit(struct strbuf *sb, /* in UTF-8 */
1430                                     const char *placeholder,
1431                                     struct format_commit_context *c)
1432 {
1433         struct strbuf local_sb = STRBUF_INIT;
1434         int total_consumed = 0, len, padding = c->padding;
1435         if (padding < 0) {
1436                 const char *start = strrchr(sb->buf, '\n');
1437                 int occupied;
1438                 if (!start)
1439                         start = sb->buf;
1440                 occupied = utf8_strnwidth(start, -1, 1);
1441                 occupied += c->pretty_ctx->graph_width;
1442                 padding = (-padding) - occupied;
1443         }
1444         while (1) {
1445                 int modifier = *placeholder == 'C';
1446                 int consumed = format_commit_one(&local_sb, placeholder, c);
1447                 total_consumed += consumed;
1448
1449                 if (!modifier)
1450                         break;
1451
1452                 placeholder += consumed;
1453                 if (*placeholder != '%')
1454                         break;
1455                 placeholder++;
1456                 total_consumed++;
1457         }
1458         len = utf8_strnwidth(local_sb.buf, -1, 1);
1459
1460         if (c->flush_type == flush_left_and_steal) {
1461                 const char *ch = sb->buf + sb->len - 1;
1462                 while (len > padding && ch > sb->buf) {
1463                         const char *p;
1464                         if (*ch == ' ') {
1465                                 ch--;
1466                                 padding++;
1467                                 continue;
1468                         }
1469                         /* check for trailing ansi sequences */
1470                         if (*ch != 'm')
1471                                 break;
1472                         p = ch - 1;
1473                         while (ch - p < 10 && *p != '\033')
1474                                 p--;
1475                         if (*p != '\033' ||
1476                             ch + 1 - p != display_mode_esc_sequence_len(p))
1477                                 break;
1478                         /*
1479                          * got a good ansi sequence, put it back to
1480                          * local_sb as we're cutting sb
1481                          */
1482                         strbuf_insert(&local_sb, 0, p, ch + 1 - p);
1483                         ch = p - 1;
1484                 }
1485                 strbuf_setlen(sb, ch + 1 - sb->buf);
1486                 c->flush_type = flush_left;
1487         }
1488
1489         if (len > padding) {
1490                 switch (c->truncate) {
1491                 case trunc_left:
1492                         strbuf_utf8_replace(&local_sb,
1493                                             0, len - (padding - 2),
1494                                             "..");
1495                         break;
1496                 case trunc_middle:
1497                         strbuf_utf8_replace(&local_sb,
1498                                             padding / 2 - 1,
1499                                             len - (padding - 2),
1500                                             "..");
1501                         break;
1502                 case trunc_right:
1503                         strbuf_utf8_replace(&local_sb,
1504                                             padding - 2, len - (padding - 2),
1505                                             "..");
1506                         break;
1507                 case trunc_none:
1508                         break;
1509                 }
1510                 strbuf_addbuf(sb, &local_sb);
1511         } else {
1512                 int sb_len = sb->len, offset = 0;
1513                 if (c->flush_type == flush_left)
1514                         offset = padding - len;
1515                 else if (c->flush_type == flush_both)
1516                         offset = (padding - len) / 2;
1517                 /*
1518                  * we calculate padding in columns, now
1519                  * convert it back to chars
1520                  */
1521                 padding = padding - len + local_sb.len;
1522                 strbuf_addchars(sb, ' ', padding);
1523                 memcpy(sb->buf + sb_len + offset, local_sb.buf,
1524                        local_sb.len);
1525         }
1526         strbuf_release(&local_sb);
1527         c->flush_type = no_flush;
1528         return total_consumed;
1529 }
1530
1531 static size_t format_commit_item(struct strbuf *sb, /* in UTF-8 */
1532                                  const char *placeholder,
1533                                  void *context)
1534 {
1535         int consumed;
1536         size_t orig_len;
1537         enum {
1538                 NO_MAGIC,
1539                 ADD_LF_BEFORE_NON_EMPTY,
1540                 DEL_LF_BEFORE_EMPTY,
1541                 ADD_SP_BEFORE_NON_EMPTY
1542         } magic = NO_MAGIC;
1543
1544         switch (placeholder[0]) {
1545         case '-':
1546                 magic = DEL_LF_BEFORE_EMPTY;
1547                 break;
1548         case '+':
1549                 magic = ADD_LF_BEFORE_NON_EMPTY;
1550                 break;
1551         case ' ':
1552                 magic = ADD_SP_BEFORE_NON_EMPTY;
1553                 break;
1554         default:
1555                 break;
1556         }
1557         if (magic != NO_MAGIC)
1558                 placeholder++;
1559
1560         orig_len = sb->len;
1561         if (((struct format_commit_context *)context)->flush_type != no_flush)
1562                 consumed = format_and_pad_commit(sb, placeholder, context);
1563         else
1564                 consumed = format_commit_one(sb, placeholder, context);
1565         if (magic == NO_MAGIC)
1566                 return consumed;
1567
1568         if ((orig_len == sb->len) && magic == DEL_LF_BEFORE_EMPTY) {
1569                 while (sb->len && sb->buf[sb->len - 1] == '\n')
1570                         strbuf_setlen(sb, sb->len - 1);
1571         } else if (orig_len != sb->len) {
1572                 if (magic == ADD_LF_BEFORE_NON_EMPTY)
1573                         strbuf_insert(sb, orig_len, "\n", 1);
1574                 else if (magic == ADD_SP_BEFORE_NON_EMPTY)
1575                         strbuf_insert(sb, orig_len, " ", 1);
1576         }
1577         return consumed + 1;
1578 }
1579
1580 static size_t userformat_want_item(struct strbuf *sb, const char *placeholder,
1581                                    void *context)
1582 {
1583         struct userformat_want *w = context;
1584
1585         if (*placeholder == '+' || *placeholder == '-' || *placeholder == ' ')
1586                 placeholder++;
1587
1588         switch (*placeholder) {
1589         case 'N':
1590                 w->notes = 1;
1591                 break;
1592         case 'S':
1593                 w->source = 1;
1594                 break;
1595         }
1596         return 0;
1597 }
1598
1599 void userformat_find_requirements(const char *fmt, struct userformat_want *w)
1600 {
1601         struct strbuf dummy = STRBUF_INIT;
1602
1603         if (!fmt) {
1604                 if (!user_format)
1605                         return;
1606                 fmt = user_format;
1607         }
1608         strbuf_expand(&dummy, fmt, userformat_want_item, w);
1609         strbuf_release(&dummy);
1610 }
1611
1612 void repo_format_commit_message(struct repository *r,
1613                                 const struct commit *commit,
1614                                 const char *format, struct strbuf *sb,
1615                                 const struct pretty_print_context *pretty_ctx)
1616 {
1617         struct format_commit_context context;
1618         const char *output_enc = pretty_ctx->output_encoding;
1619         const char *utf8 = "UTF-8";
1620
1621         memset(&context, 0, sizeof(context));
1622         context.commit = commit;
1623         context.pretty_ctx = pretty_ctx;
1624         context.wrap_start = sb->len;
1625         /*
1626          * convert a commit message to UTF-8 first
1627          * as far as 'format_commit_item' assumes it in UTF-8
1628          */
1629         context.message = repo_logmsg_reencode(r, commit,
1630                                                &context.commit_encoding,
1631                                                utf8);
1632
1633         strbuf_expand(sb, format, format_commit_item, &context);
1634         rewrap_message_tail(sb, &context, 0, 0, 0);
1635
1636         /* then convert a commit message to an actual output encoding */
1637         if (output_enc) {
1638                 if (same_encoding(utf8, output_enc))
1639                         output_enc = NULL;
1640         } else {
1641                 if (context.commit_encoding &&
1642                     !same_encoding(context.commit_encoding, utf8))
1643                         output_enc = context.commit_encoding;
1644         }
1645
1646         if (output_enc) {
1647                 size_t outsz;
1648                 char *out = reencode_string_len(sb->buf, sb->len,
1649                                                 output_enc, utf8, &outsz);
1650                 if (out)
1651                         strbuf_attach(sb, out, outsz, outsz + 1);
1652         }
1653
1654         free(context.commit_encoding);
1655         repo_unuse_commit_buffer(r, commit, context.message);
1656 }
1657
1658 static void pp_header(struct pretty_print_context *pp,
1659                       const char *encoding,
1660                       const struct commit *commit,
1661                       const char **msg_p,
1662                       struct strbuf *sb)
1663 {
1664         int parents_shown = 0;
1665
1666         for (;;) {
1667                 const char *name, *line = *msg_p;
1668                 int linelen = get_one_line(*msg_p);
1669
1670                 if (!linelen)
1671                         return;
1672                 *msg_p += linelen;
1673
1674                 if (linelen == 1)
1675                         /* End of header */
1676                         return;
1677
1678                 if (pp->fmt == CMIT_FMT_RAW) {
1679                         strbuf_add(sb, line, linelen);
1680                         continue;
1681                 }
1682
1683                 if (starts_with(line, "parent ")) {
1684                         if (linelen != the_hash_algo->hexsz + 8)
1685                                 die("bad parent line in commit");
1686                         continue;
1687                 }
1688
1689                 if (!parents_shown) {
1690                         unsigned num = commit_list_count(commit->parents);
1691                         /* with enough slop */
1692                         strbuf_grow(sb, num * (GIT_MAX_HEXSZ + 10) + 20);
1693                         add_merge_info(pp, sb, commit);
1694                         parents_shown = 1;
1695                 }
1696
1697                 /*
1698                  * MEDIUM == DEFAULT shows only author with dates.
1699                  * FULL shows both authors but not dates.
1700                  * FULLER shows both authors and dates.
1701                  */
1702                 if (skip_prefix(line, "author ", &name)) {
1703                         strbuf_grow(sb, linelen + 80);
1704                         pp_user_info(pp, "Author", sb, name, encoding);
1705                 }
1706                 if (skip_prefix(line, "committer ", &name) &&
1707                     (pp->fmt == CMIT_FMT_FULL || pp->fmt == CMIT_FMT_FULLER)) {
1708                         strbuf_grow(sb, linelen + 80);
1709                         pp_user_info(pp, "Commit", sb, name, encoding);
1710                 }
1711         }
1712 }
1713
1714 void pp_title_line(struct pretty_print_context *pp,
1715                    const char **msg_p,
1716                    struct strbuf *sb,
1717                    const char *encoding,
1718                    int need_8bit_cte)
1719 {
1720         static const int max_length = 78; /* per rfc2047 */
1721         struct strbuf title;
1722
1723         strbuf_init(&title, 80);
1724         *msg_p = format_subject(&title, *msg_p,
1725                                 pp->preserve_subject ? "\n" : " ");
1726
1727         strbuf_grow(sb, title.len + 1024);
1728         if (pp->print_email_subject) {
1729                 if (pp->rev)
1730                         fmt_output_email_subject(sb, pp->rev);
1731                 if (needs_rfc2047_encoding(title.buf, title.len, RFC2047_SUBJECT))
1732                         add_rfc2047(sb, title.buf, title.len,
1733                                                 encoding, RFC2047_SUBJECT);
1734                 else
1735                         strbuf_add_wrapped_bytes(sb, title.buf, title.len,
1736                                          -last_line_length(sb), 1, max_length);
1737         } else {
1738                 strbuf_addbuf(sb, &title);
1739         }
1740         strbuf_addch(sb, '\n');
1741
1742         if (need_8bit_cte == 0) {
1743                 int i;
1744                 for (i = 0; i < pp->in_body_headers.nr; i++) {
1745                         if (has_non_ascii(pp->in_body_headers.items[i].string)) {
1746                                 need_8bit_cte = 1;
1747                                 break;
1748                         }
1749                 }
1750         }
1751
1752         if (need_8bit_cte > 0) {
1753                 const char *header_fmt =
1754                         "MIME-Version: 1.0\n"
1755                         "Content-Type: text/plain; charset=%s\n"
1756                         "Content-Transfer-Encoding: 8bit\n";
1757                 strbuf_addf(sb, header_fmt, encoding);
1758         }
1759         if (pp->after_subject) {
1760                 strbuf_addstr(sb, pp->after_subject);
1761         }
1762         if (cmit_fmt_is_mail(pp->fmt)) {
1763                 strbuf_addch(sb, '\n');
1764         }
1765
1766         if (pp->in_body_headers.nr) {
1767                 int i;
1768                 for (i = 0; i < pp->in_body_headers.nr; i++) {
1769                         strbuf_addstr(sb, pp->in_body_headers.items[i].string);
1770                         free(pp->in_body_headers.items[i].string);
1771                 }
1772                 string_list_clear(&pp->in_body_headers, 0);
1773                 strbuf_addch(sb, '\n');
1774         }
1775
1776         strbuf_release(&title);
1777 }
1778
1779 static int pp_utf8_width(const char *start, const char *end)
1780 {
1781         int width = 0;
1782         size_t remain = end - start;
1783
1784         while (remain) {
1785                 int n = utf8_width(&start, &remain);
1786                 if (n < 0 || !start)
1787                         return -1;
1788                 width += n;
1789         }
1790         return width;
1791 }
1792
1793 static void strbuf_add_tabexpand(struct strbuf *sb, int tabwidth,
1794                                  const char *line, int linelen)
1795 {
1796         const char *tab;
1797
1798         while ((tab = memchr(line, '\t', linelen)) != NULL) {
1799                 int width = pp_utf8_width(line, tab);
1800
1801                 /*
1802                  * If it wasn't well-formed utf8, or it
1803                  * had characters with badly defined
1804                  * width (control characters etc), just
1805                  * give up on trying to align things.
1806                  */
1807                 if (width < 0)
1808                         break;
1809
1810                 /* Output the data .. */
1811                 strbuf_add(sb, line, tab - line);
1812
1813                 /* .. and the de-tabified tab */
1814                 strbuf_addchars(sb, ' ', tabwidth - (width % tabwidth));
1815
1816                 /* Skip over the printed part .. */
1817                 linelen -= tab + 1 - line;
1818                 line = tab + 1;
1819         }
1820
1821         /*
1822          * Print out everything after the last tab without
1823          * worrying about width - there's nothing more to
1824          * align.
1825          */
1826         strbuf_add(sb, line, linelen);
1827 }
1828
1829 /*
1830  * pp_handle_indent() prints out the intendation, and
1831  * the whole line (without the final newline), after
1832  * de-tabifying.
1833  */
1834 static void pp_handle_indent(struct pretty_print_context *pp,
1835                              struct strbuf *sb, int indent,
1836                              const char *line, int linelen)
1837 {
1838         strbuf_addchars(sb, ' ', indent);
1839         if (pp->expand_tabs_in_log)
1840                 strbuf_add_tabexpand(sb, pp->expand_tabs_in_log, line, linelen);
1841         else
1842                 strbuf_add(sb, line, linelen);
1843 }
1844
1845 static int is_mboxrd_from(const char *line, int len)
1846 {
1847         /*
1848          * a line matching /^From $/ here would only have len == 4
1849          * at this point because is_empty_line would've trimmed all
1850          * trailing space
1851          */
1852         return len > 4 && starts_with(line + strspn(line, ">"), "From ");
1853 }
1854
1855 void pp_remainder(struct pretty_print_context *pp,
1856                   const char **msg_p,
1857                   struct strbuf *sb,
1858                   int indent)
1859 {
1860         int first = 1;
1861         for (;;) {
1862                 const char *line = *msg_p;
1863                 int linelen = get_one_line(line);
1864                 *msg_p += linelen;
1865
1866                 if (!linelen)
1867                         break;
1868
1869                 if (is_blank_line(line, &linelen)) {
1870                         if (first)
1871                                 continue;
1872                         if (pp->fmt == CMIT_FMT_SHORT)
1873                                 break;
1874                 }
1875                 first = 0;
1876
1877                 strbuf_grow(sb, linelen + indent + 20);
1878                 if (indent)
1879                         pp_handle_indent(pp, sb, indent, line, linelen);
1880                 else if (pp->expand_tabs_in_log)
1881                         strbuf_add_tabexpand(sb, pp->expand_tabs_in_log,
1882                                              line, linelen);
1883                 else {
1884                         if (pp->fmt == CMIT_FMT_MBOXRD &&
1885                                         is_mboxrd_from(line, linelen))
1886                                 strbuf_addch(sb, '>');
1887
1888                         strbuf_add(sb, line, linelen);
1889                 }
1890                 strbuf_addch(sb, '\n');
1891         }
1892 }
1893
1894 void pretty_print_commit(struct pretty_print_context *pp,
1895                          const struct commit *commit,
1896                          struct strbuf *sb)
1897 {
1898         unsigned long beginning_of_body;
1899         int indent = 4;
1900         const char *msg;
1901         const char *reencoded;
1902         const char *encoding;
1903         int need_8bit_cte = pp->need_8bit_cte;
1904
1905         if (pp->fmt == CMIT_FMT_USERFORMAT) {
1906                 format_commit_message(commit, user_format, sb, pp);
1907                 return;
1908         }
1909
1910         encoding = get_log_output_encoding();
1911         msg = reencoded = logmsg_reencode(commit, NULL, encoding);
1912
1913         if (pp->fmt == CMIT_FMT_ONELINE || cmit_fmt_is_mail(pp->fmt))
1914                 indent = 0;
1915
1916         /*
1917          * We need to check and emit Content-type: to mark it
1918          * as 8-bit if we haven't done so.
1919          */
1920         if (cmit_fmt_is_mail(pp->fmt) && need_8bit_cte == 0) {
1921                 int i, ch, in_body;
1922
1923                 for (in_body = i = 0; (ch = msg[i]); i++) {
1924                         if (!in_body) {
1925                                 /* author could be non 7-bit ASCII but
1926                                  * the log may be so; skip over the
1927                                  * header part first.
1928                                  */
1929                                 if (ch == '\n' && msg[i+1] == '\n')
1930                                         in_body = 1;
1931                         }
1932                         else if (non_ascii(ch)) {
1933                                 need_8bit_cte = 1;
1934                                 break;
1935                         }
1936                 }
1937         }
1938
1939         pp_header(pp, encoding, commit, &msg, sb);
1940         if (pp->fmt != CMIT_FMT_ONELINE && !pp->print_email_subject) {
1941                 strbuf_addch(sb, '\n');
1942         }
1943
1944         /* Skip excess blank lines at the beginning of body, if any... */
1945         msg = skip_blank_lines(msg);
1946
1947         /* These formats treat the title line specially. */
1948         if (pp->fmt == CMIT_FMT_ONELINE || cmit_fmt_is_mail(pp->fmt))
1949                 pp_title_line(pp, &msg, sb, encoding, need_8bit_cte);
1950
1951         beginning_of_body = sb->len;
1952         if (pp->fmt != CMIT_FMT_ONELINE)
1953                 pp_remainder(pp, &msg, sb, indent);
1954         strbuf_rtrim(sb);
1955
1956         /* Make sure there is an EOLN for the non-oneline case */
1957         if (pp->fmt != CMIT_FMT_ONELINE)
1958                 strbuf_addch(sb, '\n');
1959
1960         /*
1961          * The caller may append additional body text in e-mail
1962          * format.  Make sure we did not strip the blank line
1963          * between the header and the body.
1964          */
1965         if (cmit_fmt_is_mail(pp->fmt) && sb->len <= beginning_of_body)
1966                 strbuf_addch(sb, '\n');
1967
1968         unuse_commit_buffer(commit, reencoded);
1969 }
1970
1971 void pp_commit_easy(enum cmit_fmt fmt, const struct commit *commit,
1972                     struct strbuf *sb)
1973 {
1974         struct pretty_print_context pp = {0};
1975         pp.fmt = fmt;
1976         pretty_print_commit(&pp, commit, sb);
1977 }