Instantly share code, notes, and snippets.

Embed
What would you like to do?
A 1Writer action for adding Jekyll frontmatter to a Markdown document.
// Main Steps
let text = editor.getText()
text = addFrontMatter(text)
text = removeTitle(text)
editor.setText(text)
moveCursor(text)
// Function Definitions
function addFrontMatter(text) {
const frontMatter =
`---
title: ${getTitle(text)}
layout: ${getLayout()}
date: ${getDateTime()}
excerpt: ${getExcerpt()}
category: ${getCategory()}
tags: ${getTags()}
---`
return frontMatter + text
}
function getTitle(text) {
const title_re = /# ([^\n]+)/
const title_match = text.match(title_re)
const title = (title_match === null) ? '' : title_match[1]
return `${title}`
}
function getLayout() {
return `post`
}
function getDateTime() {
const now = new Date()
const date = now.toJSON().slice(0,10)
const time = now.getHours().toString().padStart(2, '0') + ":" + now.getMinutes().toString().padStart(2, '0') + ":" + now.getSeconds().toString().padStart(2, '0')
const offset = now.getTimezoneOffset() / 60 * -100
const tz = ((offset < 0) ? '-' : '+') + offset.toString().padStart(4, '0')
return `${date} ${time} ${tz}`
}
function getExcerpt() {
return ``
}
function getCategory() {
return ``
}
function getTags() {
return ``
}
function removeTitle(text) {
const title_re = /# [^\n]+/
const title = text.match(title_re)
return text.substring(0, title.index) + text.substring(title.index + title[0].length)
}
function moveCursor(text) {
const excerpt_re = /excerpt:.*/
const excerpt = text.match(excerpt_re)
editor.setSelectedRange(excerpt.index + excerpt[0].length)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment