Last active
September 27, 2018 10:33
-
-
Save pyrmont/22bb6dbb27420424eb0ba63a2790bede to your computer and use it in GitHub Desktop.
A 1Writer action for adding a reference link to a Markdown document.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Main Steps | |
let text = editor.getText() | |
const range = editor.getSelectedRange() | |
const selection = editor.getSelectedText() | |
process(text, range, selection) | |
// Function Definitions | |
async function process(text, range, selection) { | |
const reference = await input_reference() | |
const url = await input_url() | |
text = insertReference(text, range[0], range[1], selection, reference) | |
text = insertDefinition(text, range[0], reference, url) | |
editor.setText(text) | |
moveCursor(text, reference) | |
} | |
function input_reference() { | |
return new Promise(resolve => { | |
ui.input('Link Reference', '', 'Enter the link reference', resolve) | |
}) | |
} | |
function input_url() { | |
return new Promise(resolve => { | |
ui.input('Link URL', '', 'Enter the link URL', 'url', resolve) | |
}) | |
} | |
function insertReference(text, start, end, selection, reference) { | |
const label = `[${selection}][${reference}]` | |
return text.slice(0, start) + label + text.slice(end) | |
} | |
function insertDefinition(text, start, reference, url) { | |
const paragraph_end = text.indexOf('\n\n', start) | |
const pos = (paragraph_end === -1) ? text.length : paragraph_end | |
const definition = `\n\n[${reference}]: ${url}` | |
return text.slice(0, pos) + definition + text.slice(pos) | |
} | |
function moveCursor(text, reference) { | |
const pattern = `\]\[${reference}\]` | |
const label = text.match(new RegExp(pattern)) | |
const pos = label.index + reference.length + 3 | |
editor.setSelectedRange(pos) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment