Im relatively new to obsidian and have 0 programming background. I have been using it to take med school notes that can link to various other ones. I have hundreds of notes at this point.
I’ve been trying now to incorporate spaced repetition, but in order to have separete decks for when I want to study x subject over y, I have to add tags to every one of them so I can sort through the disciplines better.
I’ve been using chatgpt to guide me throught it, and it managed to make a code work through Templater where it would scan a central note for the linked notes in it, and create the uncreated ones adding a tags property with the tag I wanted.
However, the [[notes]] that I had already created and written stuff in them don’t work. I’ve been trying when I can for the past 3 days now and I couldnt get any code the AI created to modify these notes, not add a tags properties, not even add a plain text with the #tag on these notes that were already created.
So I have a template that seems to work to create the unwritten notes, but its essential that I can automize the process of adding the tag to the already written ones, which are much more important.
Here are the codes that I’m running. the 1 one seems fine, it’s the 2 one that Im struggling with, a separate one to try to add a tag to the existing notes somehow.
1
<%*
async function addTagToFileProperty() {
const note = app.workspace.activeLeaf.view.file; // Pega a nota ativa (nota central)
if (!note) {
console.error('Nota ativa não encontrada.');
return;
}
// Pega os links dessa nota
const fileCache = app.metadataCache.getFileCache(note);
const links = fileCache ? fileCache.links : []; // Pega os links, senão um array vazio
if (links.length === 0) {
console.log('Nenhum link encontrado na nota.');
return;
}
// Pega o diretório da nota central
const centralNoteDir = note.path.substring(0, note.path.lastIndexOf('/'));
// Itera sobre os links
for (const link of links) {
let linkedFile = app.vault.getAbstractFileByPath(link.link);
if (linkedFile) {
// Se o arquivo for uma nota válida (TFile), adiciona a tag
if (linkedFile instanceof TFile) {
const filePath = linkedFile.path;
// Pega o conteúdo da nota
const fileContent = await app.vault.read(linkedFile);
// Verifica se a tag '#Anestesiologia' já está presente em qualquer lugar da nota
if (fileContent.includes('#Anestesiologia')) {
console.log(`A tag '#Anestesiologia' já está presente na nota: ${filePath}`);
} else {
// Se não encontrar a tag, adiciona a tag '#Anestesiologia' no final da nota
const updatedContent = fileContent + '\n#Anestesiologia'; // Adiciona a tag no final
// Modifica o arquivo com o novo conteúdo
await app.vault.modify(linkedFile, updatedContent);
console.log(`Tag '#Anestesiologia' adicionada ao final da nota: ${filePath}`);
}
}
} else {
// Se o arquivo não for encontrado (nota não criada), cria a nota
console.log(`Nota não encontrada para o link: ${link.link}. Criando...`);
// Função para garantir que o nome do arquivo é válido no sistema de arquivos
function sanitizeFileName(fileName) {
return fileName
.replace(/[<>:"/\\|?*\x00-\x1F]/g, '') // Remove caracteres inválidos no sistema de arquivos
.replace(/\s+/g, ' ') // Substitui múltiplos espaços por um único
.trim(); // Remove espaços no início e no final
}
// Usar diretamente o nome do link, mas sanitizar o nome do arquivo
const validFileName = sanitizeFileName(link.link); // Limpeza mínima para garantir compatibilidade
// Define o caminho para a nova nota, dentro do mesmo diretório da nota central
const newNotePath = `${centralNoteDir}/${validFileName}.md`; // Cria no mesmo diretório da nota central
// Cria a nova nota e adiciona o conteúdo
const newNoteContent = `Criada automaticamente a partir do link: ${link.link}`;
try {
const newNote = await app.vault.create(newNotePath, newNoteContent);
console.log(`Nota criada no vault: ${newNote.path}`);
// Cria o frontmatter com a tag e o conteúdo
const newNoteContentWithFrontmatter = `---\ntags: [Anestesiologia]\n---\n${newNoteContent}`;
await app.vault.modify(newNote, newNoteContentWithFrontmatter);
console.log(`Tag '#Anestesiologia' adicionada no frontmatter da nova nota: ${newNote.path}`);
} catch (err) {
console.error(`Erro ao criar a nota: ${err}`);
}
}
}
}
// Chama a função principal que processa os links
addTagToFileProperty();
%>
2
<%*
async function removeCreatedFiles() {
const note = app.workspace.activeLeaf.view.file; // Pega a nota ativa (nota central)
if (!note) {
console.error('Nota ativa não encontrada.');
return;
}
// Pega os links dessa nota
const fileCache = app.metadataCache.getFileCache(note);
const links = fileCache ? fileCache.links : []; // Pega os links, senão um array vazio
if (links.length === 0) {
console.log('Nenhum link encontrado na nota.');
return;
}
// Pega o diretório da nota central
const centralNoteDir = note.path.substring(0, note.path.lastIndexOf('/'));
// Itera sobre os links
for (const link of links) {
const validFileName = link.link.replace(/[^\w\s]/g, '') + ".md"; // A forma simples de criar o nome do arquivo
const filePath = `${centralNoteDir}/${validFileName}`; // Gera o caminho completo do arquivo
const file = app.vault.getAbstractFileByPath(filePath);
if (file && file instanceof TFile) {
// Se o arquivo foi criado e existe, apaga
await app.vault.delete(file);
console.log(`Arquivo deletado: ${filePath}`);
} else {
console.log(`Arquivo não encontrado ou não criado: ${filePath}`);
}
}
}
// Chama a função para remover os arquivos criados
removeCreatedFiles();
%>
If I can just fix this 2 one, I can run the 1 one first and then the 2 one to get all the notes from that specific lesson on the same category for the flashcards.
Also, if you have general tips on spaced repetition and how to use in the zettelkasten system, Im trying to figure the best way to use all these tools.
Thank you for your time