Skip to content

Instantly share code, notes, and snippets.

@pyrmont
Created September 28, 2018 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pyrmont/16e675429891d2a1e08840adbb3013ba to your computer and use it in GitHub Desktop.
Save pyrmont/16e675429891d2a1e08840adbb3013ba to your computer and use it in GitHub Desktop.
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