From 1b02a6384809866db1f2ffca76e605fd5c7da1e9 Mon Sep 17 00:00:00 2001 From: Kevin Ansfield Date: Mon, 14 May 2018 17:29:49 +0100 Subject: [PATCH] Koenig - Expand `--` to en dash and `---` to em dash refs https://github.com/TryGhost/Ghost/issues/9623 - match `--` and `---` and convert if followed by a space or any character respectively - include guards to ensure that expansion doesn't occur inside code blocks --- .../addon/options/text-expansions.js | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/ghost/admin/lib/koenig-editor/addon/options/text-expansions.js b/ghost/admin/lib/koenig-editor/addon/options/text-expansions.js index fd8190200a..6071cd079c 100644 --- a/ghost/admin/lib/koenig-editor/addon/options/text-expansions.js +++ b/ghost/admin/lib/koenig-editor/addon/options/text-expansions.js @@ -85,6 +85,55 @@ export default function (editor, koenig) { /* inline markdown ------------------------------------------------------ */ + // --\s = en dash – + // ---. = em dash — + // separate to the grouped replacement functions because we're matching on + // the trailing character which can be anything + editor.onTextInput({ + name: 'hyphens', + match: /---?.$/, + run(editor) { + let {range} = editor; + + let text = editor.range.head.section.textUntil(editor.range.head); + + // do not match if we're in code formatting + if (editor.hasActiveMarkup('code') || text.match(/[^\s]?`[^\s]/)) { + return; + } + + let ndashMatch = text.match(/[^-]--(\s)$/); + if (ndashMatch) { + let match = ndashMatch[0]; + range = range.extend(-(match.length - 1)); + + if (editor.detectMarkupInRange(range, 'code')) { + return; + } + + return editor.run((postEditor) => { + let position = postEditor.deleteRange(range); + postEditor.insertText(position, `–${ndashMatch[1]}`); + }); + } + + let mdashMatch = text.match(/---([^-])$/); + if (mdashMatch) { + let match = mdashMatch[0]; + range = range.extend(-(match.length)); + + if (editor.detectMarkupInRange(range, 'code')) { + return; + } + + return editor.run((postEditor) => { + let position = postEditor.deleteRange(range); + postEditor.insertText(position, `—${mdashMatch[1]}`); + }); + } + } + }); + function matchStrongStar(editor, text) { let {range} = editor; let matches = text.match(/(?:^|\s)\*\*([^\s*]+|[^\s*][^*]*[^\s])\*\*/);