<%*
/*
*/
const view = app.workspace.activeLeaf.view;
const editor = view.editor;
const curLineNum = editor.getCursor().line;
const curLineText = editor.getLine(curLineNum);
const title = tp.file.title;
const today = title.match(/\d{4}\-\d{2}\-\d{2} .+/) //are we on the DNP?
? null //if on the DNP, today is set to null
: moment(Date.now()).format("YYYY-MM-DD dddd"); //set today
let newLineText = curLineText.replace(
/!?\[\[([^\]\|]*\/)?([^\]\|\/]+)\|?([^\]]*)?\]\]/,
(match,p1,p2,p3) => `${today?"###":"##"} ${p3??p2}\n![[${(p1??"")+p2}#${(today?today+" ":"") + title}]]`
);
editor.setLine(curLineNum, newLineText);
let fname = newLineText.match(/!\[\[(.*?)#.*?]]/)[1];
let file = app.metadataCache.getFirstLinkpathDest(fname,view.file.path);
if(!file) {
if(!fname.endsWith(".md")) fname=fname+".md";
file = await app.vault.create(fname,"# Notes\n");
}
const data = await app.vault.read(file);
const parts = data.split(/# Notes(?:\n|\r\n|\r)/);
newLineText = `## ${today?"[["+today+"]], ":""}[[${title}]]`;
if(parts.length === 2) {
await app.vault.modify(file,parts[0]+"# Notes\n"+newLineText+"\n\n"+parts[1]);
} else {
await app.vault.modify(file,data+"# Notes\n"+newLineText+"\n\n");
}
await app.workspace.openLinkText(fname, view.file.path);
let i=0;
const lineCount = editor.lineCount();
while(editor.getLine(i)!==newLineText && i<lineCount) i++;
editor.setCursor(i+1);
%>
@zsviczian Good point and I never realized Mac didn't use \n! That didn't turn out to be the problem though I tried the new version on Mac and Windows and both work - not sure if it would have failed earlier. I figured it out though and it was mainly my bad. When I started experimenting with it, somehow I ended up getting an extra "# Notes" appended on the end of some text in my note, so the script was matching that even though it wasn't a heading. I never noticed this and couldn't replicate the problem out of this one note so I think it's solved.
Some possible improvements for increased stability in the script. 1) could possibly regex match "# Notes" to account for the newline (\n\r combo) at the beginning as well as the end to avoid my issue (if the file doesn't have a newline at the end, the script currently doesn't create one before adding the notes section either, which I think caused my problem). 2) Weirder one but in my experimenting I had also manually added another "# Notes" so data.split()'s output was > 2, leading the script to continuously create new sections. You might just make it check for length of at least 2 to avoid this, but I don't know who would want multiple sections anyway so maybe unnecessary.
I also just posted something unrelated to your video comments :) Thanks for the awesome video and code!