|
| 1 | +package md |
| 2 | + |
| 3 | +import ( |
| 4 | + "strings" |
| 5 | + "unicode" |
| 6 | +) |
| 7 | + |
| 8 | +// SmartPunctsCodec wraps another codec, converting certain ASCII punctuations to |
| 9 | +// nicer Unicode counterparts: |
| 10 | +// |
| 11 | +// - A straight double quote (") is converted to a left double quote (“) when |
| 12 | +// it follows a whitespace, or a right double quote (”) when it follows a |
| 13 | +// non-whitespace. |
| 14 | +// |
| 15 | +// - A straight single quote (') is converted to a left single quote (‘) when |
| 16 | +// it follows a whitespace, or a right single quote or apostrophe (’) when |
| 17 | +// it follows a non-whitespace. |
| 18 | +// |
| 19 | +// - A run of two dashes (--) is converted to an en-dash (–). |
| 20 | +// |
| 21 | +// - A run of three dashes (---) is converted to an em-dash (—). |
| 22 | +// |
| 23 | +// - A run of three dot (...) is converted to an ellipsis (…). |
| 24 | +// |
| 25 | +// Start of lines are considered to be whitespaces. |
| 26 | +type SmartPunctsCodec struct{ Inner Codec } |
| 27 | + |
| 28 | +func (c SmartPunctsCodec) Do(op Op) { c.Inner.Do(applySmartPunctsToOp(op)) } |
| 29 | + |
| 30 | +func applySmartPunctsToOp(op Op) Op { |
| 31 | + for i := range op.Content { |
| 32 | + inlineOp := &op.Content[i] |
| 33 | + switch inlineOp.Type { |
| 34 | + case OpText, OpLinkStart, OpLinkEnd, OpImage: |
| 35 | + inlineOp.Text = applySmartPuncts(inlineOp.Text) |
| 36 | + if inlineOp.Type == OpImage { |
| 37 | + inlineOp.Alt = applySmartPuncts(inlineOp.Alt) |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + return op |
| 42 | +} |
| 43 | + |
| 44 | +var applySimpleSmartPuncts = strings.NewReplacer( |
| 45 | + "--", "–", "---", "—", "...", "…").Replace |
| 46 | + |
| 47 | +func applySmartPuncts(s string) string { |
| 48 | + return applySimpleSmartPuncts(applySmartQuotes(s)) |
| 49 | +} |
| 50 | + |
| 51 | +func applySmartQuotes(s string) string { |
| 52 | + if !strings.ContainsAny(s, `'"`) { |
| 53 | + return s |
| 54 | + } |
| 55 | + var sb strings.Builder |
| 56 | + // Start of line is considered to be whitespace |
| 57 | + prev := ' ' |
| 58 | + for _, r := range s { |
| 59 | + if r == '"' { |
| 60 | + if unicode.IsSpace(prev) { |
| 61 | + sb.WriteRune('“') |
| 62 | + } else { |
| 63 | + sb.WriteRune('”') |
| 64 | + } |
| 65 | + } else if r == '\'' { |
| 66 | + if unicode.IsSpace(prev) { |
| 67 | + sb.WriteRune('‘') |
| 68 | + } else { |
| 69 | + sb.WriteRune('’') |
| 70 | + } |
| 71 | + } else { |
| 72 | + sb.WriteRune(r) |
| 73 | + } |
| 74 | + prev = r |
| 75 | + } |
| 76 | + return sb.String() |
| 77 | +} |
0 commit comments