Last active
June 7, 2021 18:18
-
-
Save torantine/06777a5acc58aa8e8ce7c0f5e268936f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<%* | |
/* | |
Requires: Templater | |
This template will create new files containing the content between | |
each thematic break "---" in the current file (ignoring the metadata) | |
and add links to the new files in the current file. | |
If you don't like the result just undo a few times | |
and delete the newly created files. | |
Will not work if files matching the created ones already exist. | |
Known bugs: | |
- [ ] makes an additional empty file if last character is "---" and there are lines below it | |
To add: | |
- option to not delete current content of file | |
- option to carry over metadata to new files | |
- functionallity to delete/update created files if they exist | |
*/ | |
// get active file | |
let activeFile = app.workspace.activeLeaf.view.file; | |
// get content of activeFile | |
let content = await app.vault.cachedRead(activeFile); | |
// fill an array with sections of content separated by "---" followed by a new line | |
let getSections = (content) => { | |
let sections = content.split(/---\n/); | |
sections[0].length < 1 ? sections.splice(0,2) : null; // if file has frontmatter, remove it from sections | |
return sections; | |
} | |
let getFolder = (file) => { | |
let folder = file.path.replace(file.name, ""); | |
folder.length === 0 ? folder = "/" : null; | |
return folder; | |
} | |
// replace this with a promise.all? | |
// https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop | |
// make files and insert content in them | |
async function makeFile(element, index) { | |
// thanks to https://gist.github.com/GitMurf/817a6c9e73e1d1e312fc1a1735edb8d6 | |
let filePath = getFolder(activeFile)+activeFile.basename+"-"+(index+1)+'.md'; | |
let userFile = this.app.vault.getAbstractFileByPath(filePath); | |
if(!userFile) { | |
userFile = await this.app.vault.create(filePath, ''); | |
await app.vault.modify(userFile, await getSections(content)[index]); | |
// remove the content from the original file and fix the positioning of HRs | |
content = content.replace(getSections(content)[index], "[["+activeFile.basename+"-"+(index+1)+"]]"); | |
await app.vault.modify(activeFile, content); | |
content = content.replace(/(?<=.)---/g, "\n\n---\n"); | |
await app.vault.modify(activeFile, content); | |
} | |
} | |
let makeFiles = getSections(content).forEach(makeFile); | |
%> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment