Skip to content
This repository was archived by the owner on Nov 23, 2026. It is now read-only.

Commit 31b51be

Browse files
committed
Inline code samples into the pages
1 parent cd87e1a commit 31b51be

4 files changed

Lines changed: 125 additions & 22 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ Generation of the final documentation uses [MkDocs](https://www.mkdocs.org/) wit
4949
## Next Steps:
5050

5151
- [x] Build converter script to convert all files from rst to md
52-
- [ ] Modify converter to insert code samples and remove unnecessary files.
52+
- [x] Modify converter to insert code samples and remove unnecessary files.
5353
- [ ] Review and clean up converted files
5454
- [ ] Review and clean up overall structure of documentation
5555
- [ ] Standardize how pages are written to include cohesive structure and examples

‎admin/convert.php‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,6 @@ function checkPandocVersion(): void {
8383
define('AFTER_FILTERS', [
8484
'images',
8585
'alerts',
86-
'includes',
8786
'dollarSign',
8887
'versionAdded',
8988
'versionDeprecated',
@@ -93,6 +92,7 @@ function checkPandocVersion(): void {
9392
'contents',
9493
'docLink',
9594
'codeBlocks',
95+
'includes',
9696
]);
9797

9898
function loadFilters(): void {
@@ -384,7 +384,7 @@ function runPandoc(array $jobs, array $copies): array {
384384
}
385385

386386
/**
387-
* Mirrors `$source` into `$target`, copying every file except the RST pages, which it appends to `$jobs`.
387+
* Mirrors `$source` into `$target`, appending the RST pages to `$jobs` and skipping the PHP samples, which the includes filter inlines.
388388
*
389389
* @param list<array{source: string, target: string}> $jobs Accumulated RST conversion jobs
390390
*/
@@ -414,7 +414,7 @@ function convert(string $source, string $target, array &$jobs): void {
414414
convert($sourceFile, $targetFile, $jobs);
415415
} else if (preg_match('/\.rst$/', $file)) {
416416
$jobs[] = ['source' => $sourceFile, 'target' => preg_replace('/\.rst$/', '.md', $targetFile)];
417-
} else {
417+
} elseif (! str_ends_with($file, '.php')) {
418418
echo "Copying $sourceFile\n";
419419
copy($sourceFile, $targetFile);
420420
}

‎admin/filters/includes.php‎

Lines changed: 121 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,131 @@
11
<?php
22

3-
// Handle including code samples
4-
function before_filter_includes($data, $folder) {
5-
$literal = ' .. literalinclude::';
6-
if (str_contains($data, $literal)) {
7-
$data = str_replace($literal, '.. literalinclude::', $data);
3+
declare(strict_types=1);
4+
5+
/**
6+
* Samples held back from the other filters, keyed by the number in their `CI4SAMPLE<n>` marker.
7+
*
8+
* @return list<array{language: string, lines: list<string>}>
9+
*/
10+
function &includedSamples(): array {
11+
static $samples = [];
12+
13+
return $samples;
14+
}
15+
16+
/**
17+
* Replaces each `literalinclude` with a `CI4SAMPLE<n>` marker line at the directive's indentation.
18+
*/
19+
function before_filter_includes(string $data, string $folder): ?string {
20+
$samples = &includedSamples();
21+
$lines = explode("\n", $data);
22+
$result = [];
23+
24+
for ($i = 0; $i < count($lines); $i++) {
25+
if (! preg_match('/^(\s*)\.\.\s+literalinclude::\s*(\S+)\s*$/', $lines[$i], $matches)) {
26+
$result[] = $lines[$i];
27+
28+
continue;
29+
}
30+
31+
$indent = $matches[1];
32+
$directive = [$lines[$i]];
33+
$options = [];
34+
35+
while (isset($lines[$i + 1]) && preg_match('/^(\s+):([a-z-]+):\s*(.*)$/', $lines[$i + 1], $option) && strlen($option[1]) > strlen($indent)) {
36+
$options[$option[2]] = trim($option[3]);
37+
$directive[] = $lines[++$i];
38+
}
39+
40+
$file = str_starts_with($matches[2], '/') ? rtrim(SOURCE_DIR, '/') . $matches[2] : $folder . '/' . $matches[2];
41+
42+
if (! is_file($file)) {
43+
fwrite(STDERR, "Warning: sample {$matches[2]} not found for literalinclude in {$folder}\n");
44+
array_push($result, ...$directive);
45+
46+
continue;
47+
}
48+
49+
$sample = explode("\n", file_get_contents($file));
50+
51+
if (isset($options['lines'])) {
52+
$sample = selectSampleLines($sample, $options['lines']);
53+
}
54+
55+
$result[] = $indent . 'CI4SAMPLE' . count($samples);
56+
$samples[] = ['language' => $options['language'] ?? 'php', 'lines' => trimBlankLines($sample)];
857
}
958

10-
return $data;
59+
return implode("\n", $result);
1160
}
1261

13-
function after_filter_includes($data, $folder) {
14-
// We only need a parent folder
15-
$folder = explode('/', trim($folder, '/'));
16-
$folder = array_pop($folder);
62+
/**
63+
* Replaces each `CI4SAMPLE<n>` marker line with its sample as a fenced block, prefixed like the marker.
64+
*/
65+
function after_filter_includes(string $data, string $folder): ?string {
66+
$samples = &includedSamples();
67+
68+
return preg_replace_callback('/^(.*?)CI4SAMPLE(\d+)[ \t]*$/m', function (array $matches) use ($samples): string {
69+
// Sphinx renders an indented sample outside any container as a plain block, not a blockquote.
70+
$prefix = preg_replace('/> ?/', '', $matches[1]);
71+
$sample = $samples[(int) $matches[2]];
72+
73+
preg_match_all('/`+/', implode("\n", $sample['lines']), $runs);
74+
$fence = str_repeat('`', max(3, ...array_map(fn (string $run): int => strlen($run) + 1, $runs[0] ?: [''])));
1775

18-
$pattern = '/<div class="literalinclude"\s*(?:lines="(-?\d+(?:-\d*)?)")?>\s*(.*?)\s*<\/div>/s';
76+
$block = [$prefix . $fence . $sample['language']];
1977

20-
return preg_replace_callback($pattern, function($matches) use ($folder) {
21-
$content = trim($matches[2]);
22-
$lines = empty($matches[1]) ? '' : ':' . str_replace('-', ':', $matches[1]);
23-
return "```php\n--8<--\n" . "{$folder}/{$content}{$lines}\n--8<--\n```";
78+
foreach ($sample['lines'] as $line) {
79+
$block[] = rtrim($prefix . $line);
80+
}
81+
82+
$block[] = $prefix . $fence;
83+
84+
return implode("\n", $block);
2485
}, $data);
2586
}
87+
88+
/**
89+
* Lines picked by a Sphinx `:lines:` option such as `2-`, `3-10` or `1,4-6`, counted from 1.
90+
*
91+
* @param list<string> $lines
92+
*
93+
* @return list<string>
94+
*/
95+
function selectSampleLines(array $lines, string $spec): array {
96+
$selected = [];
97+
98+
foreach (explode(',', $spec) as $part) {
99+
$part = trim($part);
100+
101+
if (preg_match('/^(\d*)-(\d*)$/', $part, $matches)) {
102+
$from = $matches[1] === '' ? 1 : (int) $matches[1];
103+
$to = $matches[2] === '' ? count($lines) : (int) $matches[2];
104+
} else {
105+
$from = $to = (int) $part;
106+
}
107+
108+
for ($i = max(1, $from); $i <= min($to, count($lines)); $i++) {
109+
$selected[] = $lines[$i - 1];
110+
}
111+
}
112+
113+
return $selected;
114+
}
115+
116+
/**
117+
* @param list<string> $lines
118+
*
119+
* @return list<string>
120+
*/
121+
function trimBlankLines(array $lines): array {
122+
while ($lines !== [] && trim($lines[0]) === '') {
123+
array_shift($lines);
124+
}
125+
126+
while ($lines !== [] && trim(end($lines)) === '') {
127+
array_pop($lines);
128+
}
129+
130+
return $lines;
131+
}

‎mkdocs.yml‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,6 @@ copyright: Copyright &copy; 2023 CodeIgniter Foundation.
6161

6262
markdown_extensions:
6363
- admonition
64-
- pymdownx.snippets:
65-
base_path: ["docs"]
66-
check_paths: false
6764
- pymdownx.superfences
6865
- pymdownx.highlight:
6966
use_pygments: false

0 commit comments

Comments
 (0)