|
3 | 3 | declare(strict_types=1); |
4 | 4 |
|
5 | 5 | /** |
6 | | - * Escapes the underscore that starts a path segment, which pandoc 3.13 reads as an RST inline target. |
| 6 | + * Escapes the underscore that starts a path segment and the `::` between two words, which pandoc 3.13 reads as an RST inline target and as a link. |
7 | 7 | */ |
8 | 8 | function before_filter_underscores(string $data, string $folder): ?string |
9 | 9 | { |
10 | | - return preg_replace_callback('/(``.+?``)|\S+/', function (array $matches): string { |
| 10 | + $lines = explode("\n", $data); |
| 11 | + |
| 12 | + foreach (array_keys($lines) as $i) { |
| 13 | + $escaped = escape_inline_targets($lines[$i]); |
| 14 | + $added = strlen($escaped) - strlen($lines[$i]); |
| 15 | + $lines[$i] = $escaped; |
| 16 | + |
| 17 | + if ($added > 0 && isset($lines[$i + 1]) && is_adornment($lines[$i + 1])) { |
| 18 | + $lines[$i + 1] .= str_repeat($lines[$i + 1][0], $added); |
| 19 | + |
| 20 | + if ($i > 0 && is_adornment($lines[$i - 1]) && $lines[$i - 1][0] === $lines[$i + 1][0] && ($i === 1 || trim($lines[$i - 2]) === '')) { |
| 21 | + $lines[$i - 1] .= str_repeat($lines[$i - 1][0], $added); |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + return implode("\n", $lines); |
| 27 | +} |
| 28 | + |
| 29 | +function escape_inline_targets(string $line): string |
| 30 | +{ |
| 31 | + return preg_replace_callback('/(`[^`]+`|``.+?``)|[^\s`]+/', function (array $matches): string { |
11 | 32 | if (isset($matches[1]) || str_contains($matches[0], '://') || str_contains($matches[0], '](')) { |
12 | 33 | return $matches[0]; |
13 | 34 | } |
14 | 35 |
|
15 | | - return preg_replace('#(?<=/)_(?=\w)#', '\\\\_', $matches[0]); |
16 | | - }, $data); |
| 36 | + return preg_replace(['#(?<=/)_(?=\w)#', '/(?<=\w)::(?=\w)/'], ['\\\\_', '\\\\::'], $matches[0]); |
| 37 | + }, $line); |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * Whether `$line` is a run of one punctuation character, as under an RST section title. |
| 42 | + */ |
| 43 | +function is_adornment(string $line): bool |
| 44 | +{ |
| 45 | + return preg_match('/^([!-\/:-@\[-`{-~])\1+$/', $line) === 1; |
17 | 46 | } |
0 commit comments