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