From b1ae1b1a678982e5ba12cb89ea592e9c19cb4cf0 Mon Sep 17 00:00:00 2001 From: Valerio Bozzolan Date: Tue, 26 Mar 2024 11:19:53 +0100 Subject: [PATCH] Remarkup code blocks: guess language from "name=" Summary: The file name is a sufficient source of information, if available. Closes T15729 Test Plan: The new unit test is green. Old unit tests are green. Reviewers: O1 Blessed Committers, avivey Reviewed By: O1 Blessed Committers, avivey Subscribers: avivey, tobiaswiese, Matthew, Cigaryno Maniphest Tasks: T15729 Differential Revision: https://we.phorge.it/D25560 --- .../blockrule/PhutilRemarkupCodeBlockRule.php | 19 +++++++++++++++++++ .../remarkup/code-block-guess-from-name.txt | 7 +++++++ 2 files changed, 26 insertions(+) create mode 100644 src/infrastructure/markup/remarkup/__tests__/remarkup/code-block-guess-from-name.txt diff --git a/src/infrastructure/markup/blockrule/PhutilRemarkupCodeBlockRule.php b/src/infrastructure/markup/blockrule/PhutilRemarkupCodeBlockRule.php index 8b23fe6541..8763111dd1 100644 --- a/src/infrastructure/markup/blockrule/PhutilRemarkupCodeBlockRule.php +++ b/src/infrastructure/markup/blockrule/PhutilRemarkupCodeBlockRule.php @@ -153,6 +153,11 @@ final class PhutilRemarkupCodeBlockRule extends PhutilRemarkupBlockRule { return implode("\n", $out); } + // The name is usually a sufficient source of information for file ext. + if (empty($options['lang']) && isset($options['name'])) { + $options['lang'] = $this->guessFilenameExtension($options['name']); + } + if (empty($options['lang'])) { // If the user hasn't specified "lang=..." explicitly, try to guess the // language. If we fail, fall back to configured defaults. @@ -343,4 +348,18 @@ final class PhutilRemarkupCodeBlockRule extends PhutilRemarkupBlockRule { return $map; } + /** + * Get the extension from a filename. + * @param string "/path/to/something.name" + * @return null|string ".name" + */ + private function guessFilenameExtension($name) { + $name = basename($name); + $pos = strrpos($name, '.'); + if ($pos !== false) { + return substr($name, $pos + 1); + } + return null; + } + } diff --git a/src/infrastructure/markup/remarkup/__tests__/remarkup/code-block-guess-from-name.txt b/src/infrastructure/markup/remarkup/__tests__/remarkup/code-block-guess-from-name.txt new file mode 100644 index 0000000000..5a2c6a7c50 --- /dev/null +++ b/src/infrastructure/markup/remarkup/__tests__/remarkup/code-block-guess-from-name.txt @@ -0,0 +1,7 @@ + name=/etc/phpmyadmin/config.txt + $lol = 1; +~~~~~~~~~~ +
/etc/phpmyadmin/config.txt
$lol = 1;
+~~~~~~~~~~ +name=/etc/phpmyadmin/config.txt + $lol = 1;