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