Instantly share code, notes, and snippets.

Embed
What would you like to do?
A 1Writer action for adding a footnote to a Markdown document.
// Main Steps
let text = editor.getText()
const range = editor.getSelectedRange()
const label = `[^0]`
text = insertFootnote(text, range[1], label)
text = reorderFootnotes(text)
editor.setText(text)
moveCursor(text)
// Function Definitions
function insertFootnote(text, pos, label) {
const note = `\n\n${label}: \n`
return text.slice(0, pos) + label + text.slice(pos) + note
}
function reorderFootnotes(text) {
text = renameLabels(text)
text = reorderNotes(text)
text = cleanLabels(text)
return text
}
function renameLabels(text) {
const label_re = /[^\n]\[\^\d+\]/g
const labels = text.match(label_re)
labels.forEach(function(label, i) {
let num = i + 1
let tmp_label = `[^tmp1_${num}]`
label = label.substring(1)
text = text.split(label).join(tmp_label)
})
return text
}
function reorderNotes(text) {
const note_re = /\[\^tmp1_\d+\]: .*/g
const notes = text.match(note_re)
const ordered_notes = notes.slice(0).sort()
notes.forEach(function(note, i) {
let tmp_note = ordered_notes[i].replace('tmp1', 'tmp2')
text = text.split(note).join(tmp_note)
})
return text
}
function cleanLabels(text) {
const tmp_re = /(\[\^)tmp\d_(\d+\])/g
return text.replace(tmp_re, '$1$2')
}
function moveCursor(text) {
const empty_re = /[\n]\[\^\d+\]: [\n]/
const empty = text.match(empty_re)
editor.setSelectedRange(empty.index + empty[0].length - 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment