Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Replace arrows when the markdown typographer is enabled. (#11638)

Roman Rizzi118ea893725f
diff --git a/app/assets/javascripts/discourse/tests/unit/lib/pretty-text-test.js b/app/assets/javascripts/discourse/tests/unit/lib/pretty-text-test.js
index 8f232ae8551..3c7718eef72 100644
--- a/app/assets/javascripts/discourse/tests/unit/lib/pretty-text-test.js
+++ b/app/assets/javascripts/discourse/tests/unit/lib/pretty-text-test.js
@@ -1554,4 +1554,35 @@ var bar = 'bar';
</div></p>`
);
});
+
+ test("typographer arrows", function (assert) {
+ const enabledTypographer = {
+ siteSettings: { enable_markdown_typographer: true },
+ };
+
+ // Replace arrows
+ assert.cookedOptions(
+ "--> <--",
+ enabledTypographer,
+ "<p> \u2192 \u2190 </p>"
+ );
+ assert.cookedOptions("a --> b", enabledTypographer, "<p>a \u2192 b</p>");
+ assert.cookedOptions("-->", enabledTypographer, "<p> \u2192 </p>");
+ assert.cookedOptions("<--", enabledTypographer, "<p> \u2190 </p>");
+
+ // Don't replace arrows
+ assert.cookedOptions("<!-- an html comment -->", enabledTypographer, "");
+ assert.cookedOptions(
+ "(<--not an arrow)",
+ enabledTypographer,
+ "<p>(&lt;–not an arrow)</p>"
+ );
+ assert.cookedOptions("<-->", enabledTypographer, "<p>&lt;–&gt;</p>");
+ assert.cookedOptions("asd-->", enabledTypographer, "<p>asd–&gt;</p>");
+ assert.cookedOptions(" asd--> ", enabledTypographer, "<p>asd–&gt;</p>");
+ assert.cookedOptions(" asd-->", enabledTypographer, "<p>asd–&gt;</p>");
+ assert.cookedOptions("-->asd", enabledTypographer, "<p>–&gt;asd</p>");
+ assert.cookedOptions(" -->asd ", enabledTypographer, "<p>–&gt;asd</p>");
+ assert.cookedOptions(" -->asd", enabledTypographer, "<p>–&gt;asd</p>");
+ });
});
diff --git a/app/assets/javascripts/pretty-text/engines/discourse-markdown/typographer-arrows.js b/app/assets/javascripts/pretty-text/engines/discourse-markdown/typographer-arrows.js
new file mode 100644
index 00000000000..cccea6d47ca
--- /dev/null
+++ b/app/assets/javascripts/pretty-text/engines/discourse-markdown/typographer-arrows.js
@@ -0,0 +1,32 @@
+function replaceArrows(state) {
+ for (let i = 0; i < state.tokens.length; i++) {
+ let token = state.tokens[i];
+
+ if (token.type !== "inline") {
+ continue;
+ }
+
+ const arrowsRegexp = /-->|<--/;
+ if (arrowsRegexp.test(token.content)) {
+ for (let ci = 0; ci < token.children.length; ci++) {
+ let child = token.children[ci];
+
+ if (child.type === "text") {
+ if (arrowsRegexp.test(child.content)) {
+ child.content = child.content
+ .replace(/(^|\s)-->(\s|$)/gm, "\u0020\u2192\u0020")
+ .replace(/(^|\s)<--(\s|$)/gm, "\u0020\u2190\u0020");
+ }
+ }
+ }
+ }
+ }
+}
+
+export function setup(helper) {
+ helper.registerPlugin((md) => {
+ if (md.options.typographer) {
+ md.core.ruler.before("replacements", "typographer-arrow", replaceArrows);
+ }
+ });
+}