Skip to content

Instantly share code, notes, and snippets.

@Mearman
Last active April 24, 2024 16:52
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Mearman/ba5b1bcf746b4e04d12865dc09402016 to your computer and use it in GitHub Desktop.
Save Mearman/ba5b1bcf746b4e04d12865dc09402016 to your computer and use it in GitHub Desktop.
Obsidian Snippets
const pre = "Daily";
function separated_date(date_string) {
let lines = {
// day: ["[", moment(date_string).format("DD"), "](", "/", moment(date_string).format("YYYY/YYYY-MM/YYYY-MM-DD"), ".md", ")"].join(""),
day: ["[", moment(date_string).format("DD"), "](", "/", pre, "/", moment(date_string).format("YYYY/YYYY-MM/YYYY-MM-DD/YYYY-MM-DD"), ".md", ")"].join(""),
month: ["[", moment(date_string).format("MM"), "](", "/", pre, "/", moment(date_string).format("YYYY/YYYY-MM/YYYY-MM"), ".md", ")"].join(""),
year: ["[", moment(date_string).format("YYYY"), "](", "/", pre, "/", moment(date_string).format("YYYY/YYYY"), ".md", ")"].join(""),
};
return [
lines.year,
lines.month,
lines.day,
].join("/");
}
module.exports = (tp, full) => {
let note_timestamp = tp.user.get_note_time(tp);
let dayBefore = moment(note_timestamp).subtract(1, "days");
let dayAfter = moment(note_timestamp).add(1, "days");
// << `[ <% moment(dayBefore).format("YYYY/MM/DD") %> ]( <% moment(dayBefore).format("YYYY/YYYY-MM/YYYY-MM-DD") %> )` | [<% note_timestamp.format("YYYY/MM/DD") %>](<% note_timestamp.format("YYYY/YYYY-MM/YYYY-MM-DD") %>) | [ <% moment(dayAfter).format("YYYY/MM/DD") %> ]( <% moment(dayAfter).format("YYYY/YYYY-MM/YYYY-MM-DD") %> ) >>
let line = [
["[", moment(note_timestamp).format("YYYY/MM/DD"), "](", "/", pre, "/", moment(note_timestamp).format("YYYY/YYYY-MM/YYYY-MM-DD/YYYY-MM-DD"), ".md", ")"].join(""),
];
if (moment(tp.file.title).isValid()) {
full = true;
}
if (full) {
line = [].concat(
"<<",
// ["[", moment(dayBefore).format("YYYY/MM/DD"), "](", moment(dayBefore).format("YYYY/YYYY-MM/YYYY-MM-DD"), ")"].join(""),
separated_date(dayBefore),
dayBefore.link,
"|",
// line,
separated_date(note_timestamp),
"|",
separated_date(dayAfter),
// ["[", moment(dayAfter).format("YYYY/MM/DD"), "](", moment(dayAfter).format("YYYY/YYYY-MM/YYYY-MM-DD"), ")"].join(""),
">>"
);
}
return line.join(" ");
};
module.exports = async (tp) => {
const title = await tp.user.name_prompt(tp)
const note_timestamp = tp.user.get_note_time(tp);
const dailyDir = await tp.user.get_day_folder(tp, true);
let lines = []
const frontmatter_object = {
title: '"' + title + "'",
aliases: [
'"' + title + "'"
],
date: moment(note_timestamp).format(),
tags: [
moment(note_timestamp).format("YYYY/MM/DD")
]
}
const formatted_frontmatter = await tp.user.mutate_frontmatter(tp, frontmatter_object)
lines.push(formatted_frontmatter);
lines.push(`# ${title}`);
lines.push(tp.user.date_line(tp));
lines.push("");
lines.push("---");
return lines.join("\n");
};
module.exports = async (tp) => {
const title = await tp.user.name_prompt(tp)
const note_timestamp = tp.user.get_note_time(tp);
const dailyDir = await tp.user.get_day_folder(tp, true);
const frontmatter_object = {
"page-title": title,
aliases: [
title
],
date: moment(note_timestamp).format(),
tags: [
moment(note_timestamp).format("YYYY/MM/DD")
]
}
const formatted_frontmatter = tp.user.formatted_frontmatter(frontmatter_object)
return formatted_frontmatter;
}
module.exports = async (tp, raw) => {
const { position, ...frontmatter } =
tp.frontmatter && Object.keys(tp.frontmatter).length > 0
? tp.frontmatter
: tp;
let output = "";
const yaml = await import("https://unpkg.com/js-yaml?module");
try {
output += yaml.dump(frontmatter, {
// quotingType: '"',
// forceQuotes: true,
});
if (raw) {
return output;
} else {
return ["---", output, "---"].join("\n");
}
} catch (e) {
console.log(e);
}
};
// this is to prevent parsing basic numbers as dates
function isNumeric(num) {
return !isNaN(parseFloat(num)) && isFinite(num);
}
function isValidNumber(num) {
return (
Number.isInteger(num) && num >= 1
) || !isNumeric(num)
}
module.exports = (obj) => {
if (obj.position) {
delete obj.position;
}
for (let key in obj) {
try {
let temp = obj[key];
if (!isValidNumber(temp) && moment(Date.parse(temp)).isValid()) {
return temp;
}
} catch (e) {
console.log(e);
}
}
return;
}
module.exports = async function (tp, make = true) {
const noteTimestamp = moment(tp.user.get_note_time(tp));
const dailyDir = "/Daily/" + moment(noteTimestamp).format("YYYY") + "/" + moment(noteTimestamp).format("YYYY-MM") + "/" + moment(noteTimestamp).format("YYYY-MM-DD") + "/";
if (make) {
try {
await tp.app.vault.createFolder(dailyDir);
} catch (e) {
console.log(e);
}
}
sleep(1);
return dailyDir;
};
module.exports = (tp, format) => {
// console.log("tp.frontmatter.created:", tp.frontmatter.created);
// console.log("tp.frontmatter.date:", tp.frontmatter.date);
// console.log("tp.user.get_datetime_from_object(tp.frontmatter):", tp.user.get_datetime_from_object(tp.frontmatter));
// console.log("tp.file.creation_date():", tp.file.creation_date());
// console.log("tp.date.now():", tp.date.now());
let noteTimestamp =
(moment(tp.file.title).isValid() ? tp.file.title : false) ||
tp.frontmatter.created ||
tp.frontmatter.date ||
tp.user.get_datetime_from_object(tp.frontmatter) ||
tp.file.creation_date() ||
tp.date.now()
console.log(noteTimestamp)
noteTimestamp = moment(Date.parse(noteTimestamp));
if (format) {
return noteTimestamp.format(format);
} else {
return noteTimestamp;
}
};
module.exports = async (dailyDir) => {
}
function isDateFile(path) {
// \/*((\d{4,}(-\d{2}(-\d{2})*)*)\/*)*(\.md)*
let regex = /^\/*((\d{4,}(-\d{2}(-\d{2})*)*)\/*)*(\.md)*$/;
console.log("checking if path is a date file", path);
return regex.test(path);
}
module.exports = async (tp, obsidian) => {
// require get_note_time.js
const timestamp = await tp.user.get_note_time(tp);
let dailyDir = await tp.user.get_day_folder(tp, true);
let title = tp.file.title;
// title = title.replace(/[^a-zA-Z0-9\-_\.]/g, " ");
let newFilename = dailyDir + title;
// replace all invalid filename characters with spaces
console.log("newFilename", newFilename);
console.log("tp.file.path", tp.file.path(true));
if (newFilename + ".md" == "/" + tp.file.path(true)) {
console.log("move not needed");
return "";
}
if (isDateFile(tp.file.path(true))) {
return "";
}
// ---------------------------------------------------------------------------------------------------------------------
// const dir = "folder/folder/something/"
// print all keys and values from this.app
// console.log("keys in this object")
// for (let key in this) {
// console.log(key, this[key]);
// }
// console.log("keys in tp object")
// for (let key in tp) {
// console.log(key, tp[key]);
// }
try {
console.log("creating directory", dailyDir);
if (!tp.file.exists(dailyDir)) {
await obsidian.app.vault.createFolder(dailyDir);
}
} catch (e) {
console.log("error creating directory", dailyDir);
console.log(e);
}
// await tp.file.move(dailyDir + tp.file.title);
// try {
// // creating directory
// console.log("creating directory", dailyDir);
// await tp.obsidian.app.vault.createFolder(dailyDir);
// console.log("directory created");
// } catch (e) {
// console.log("something went wrong");
// console.log("directory might already exist")
// console.log(e);
// }
console.log();
// ---------------------------------------------------------------------------------------------------------------------
// try to move the file twice by calling tp.file.move(newFilename);
let success = false;
for (let i = -1; i <= 2; i++) {
let tempFilename = newFilename += i > 0 ? ` ${i}` : "";
try {
console.log("Trying tp.file.move", tempFilename);
await tp.file.move(tempFilename);
console.log("Success", tempFilename);
success = true;
break;
} catch (e) {
console.log("Failed", tempFilename);
sleep(1);
}
try {
console.log("Trying tp.app.vault.rename", tempFilename);
await tp.app.vault.rename(tempFilename);
console.log("Success", tempFilename);
success = true;
break;
} catch (e) {
console.log("Failed", tempFilename);
sleep(1);
}
}
// if (!success) {
// for (let i = 0; i < 5; i++) {
// let tempFilename = newFilename + " " + i;
// console.log("Trying", tempFilename);
// try {
// await tp.file.rename(tempFilename);
// console.log("Success", tempFilename);
// success = true;
// break;
// } catch (e) {
// console.log("Failed", tempFilename);
// sleep(1);
// }
// }
// }
if (!success) {
throw new Error("Failed to move file");
}
return "";
};
/*jshint esversion: 9 */
module.exports = (tp, attributes = {}) => {
if (typeof attributes !== "object") {
throw new Error("attributes must be an object");
}
let { position, ...frontmatter } =
tp.frontmatter && typeof tp.frontmatter === "object" ? tp.frontmatter : {};
for (let key in attributes) {
if (Array.isArray(frontmatter[key]) || Array.isArray(attributes[key])) {
if (Array.isArray(frontmatter[key]) && Array.isArray(attributes[key])) {
frontmatter[key] = frontmatter[key].concat(attributes[key]);
} else if (
!Array.isArray(frontmatter[key]) &&
Array.isArray(attributes[key])
) {
frontmatter[key] = attributes[key].concat([frontmatter[key]]);
} else if (
Array.isArray(frontmatter[key]) &&
!Array.isArray(attributes[key])
) {
frontmatter[key] = frontmatter[key].concat([attributes[key]]);
} else {
frontmatter[key] = { ...frontmatter[key], ...attributes[key] };
}
frontmatter[key] = Array.from(new Set(frontmatter[key].filter(val => val)));
} else if (
typeof frontmatter[key] === "object" &&
typeof attributes[key] === "object"
) {
frontmatter[key] = { ...frontmatter[key], ...attributes[key] };
} else {
frontmatter[key] = attributes[key];
}
}
// remove duplicates from array values
frontmatter = Object.fromEntries(
Object.entries(frontmatter).map(([key, value]) => {
if (Array.isArray(value)) {
return [key, Array.from(new Set(value))];
}
return [key, value];
})
);
return tp.user.formatted_frontmatter(frontmatter);
};
module.exports = async function (tp) {
console.log("Checking file name");
if (tp.file.title.startsWith("Untitled")) {
console.log("File name is untitled");
let filename = await tp.system.prompt("Note Title");
await tp.file.rename(filename);
return filename;
} else {
console.log("File already has valid name");
console.log("note is already named")
return tp.file.title;
}
}
A collection of snippets
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment