Last active
December 17, 2023 19:43
-
-
Save NPatch/ce4fdb4d85538f4cdfec3886cbc34f49 to your computer and use it in GitHub Desktop.
[obsidian.md] user script for finding the previous daily note and updating its Next link too.
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
function ctimeComparer(a, b) | |
{ | |
if (a.stat.ctime < b.stat.ctime) { | |
return 1; | |
} else if (a.stat.ctime > b.stat.ctime) { | |
return -1; | |
} | |
// a must be equal to b | |
return 0; | |
} | |
async function find_last_daily_note (tp) { | |
today = null; | |
last_created = null; | |
const daily_folder = "Daily Notes/"; | |
const dailies = app.vault.getMarkdownFiles().filter(file=> | |
{ | |
return file.path.startsWith(daily_folder) | |
&& file.basename != tp.file.title; | |
}); | |
if(dailies.length > 0) | |
{ | |
//Sorts with newest in 0 index | |
dailies.sort(ctimeComparer); | |
//First element is the previous daily | |
last_created = dailies[0]; | |
//Get its metadata | |
const last_created_metadata = app.metadataCache.getFileCache(last_created); | |
//Get its links to other files | |
const last_created_links = last_created_metadata?.links; | |
if(last_created_links && last_created_links.length > 0) | |
{ | |
//Find the link that has the Next > display text | |
last_created_next_link = last_created_links.find(x=> x.displayText.includes("Next >")); | |
if(last_created_next_link){ | |
//Generate a link to the newly created daily (today's) with the same display text | |
const new_link = app.fileManager.generateMarkdownLink(tp.config.target_file, tp.config.target_file.path, null, "Next >"); | |
try { | |
app.vault.process(last_created, (data) => { | |
//console.log("Replacing " + last_created_next_link.original + " with " + new_link); | |
return data.replace(last_created_next_link.original, new_link); | |
}) | |
} catch (e) { | |
console.error(e); | |
throw e; | |
} | |
} | |
} | |
return last_created.basename; | |
} | |
return tp.date.yesterday("YYYY-MM-DD"); | |
} | |
module.exports = find_last_daily_note; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment