Hooking into new file creation

I know we have daily and Zettelkasten prefixer settings, but I’d really like to make a plugin that’ll let you define a function that specifies the name of new note. I have a personal date-encoding that can’t be directly implemented with Moment formatting.

Is this even something we can hook into? I’ve had a skim of other plugins and most seem to be checking for Moment formatting, or none at all. I also read through the API, but I didn’t spot any events that looked likely to hook into.

Oh, just to say, I’m very comfortable with Typescript.

Answering my own question!

Based on the nuggets in API / callback for 'file-rename' event? - #4 by tgrosinger I found the hook (this.app.vault.on("create", () =>()))

Thanks y’all!

Looks like I was a little pre-emptive. The event fires after creation, and on load (where it’s adding all the items to the vault I presume). Updating the payload will actually affect the UI representation of the files, not how the file was saved (which seems to come earlier in the process).

Investigations continue.

I was able to use Templater to make some custom logic to always add a zettel-id to the beginning of the filename (so this works even if I don’t use the zettel plugin), but also strip out the ID for the first header inside the file. Maybe this could be useful for you?

This template will work from creating a new note via keyboard shortcut, creating a new note via built-in zettel plugin, or from creating a link [[some link]] in a file and clicking on it.

Here is my templates/note.md file:

  const title = await tp.user.zettler(tp);
%># <%* tR += `${title}` %>

<% tp.file.cursor() %>

And in my scripts/zettler.js:

async function zettler (tp) {
  let title = tp.file.title
  const zidRegex = /^\d{8,}\s?/

  console.log("title is", title);

  const matches = title.match(zidRegex);

  if (Array.isArray(matches) && matches.length > 0) {
    console.log('title has zid');
  	// We need to set the note header as the stripped title
  	title = title.replace(zidRegex, '');

    console.log('title without zid is', title);

	if (title.startsWith("Untitled") || title === '') {
      title = await tp.system.prompt("Title");

    console.log('renaming file to ', title);
    await tp.file.rename(`${matches[0]} ${title}`);
  } else {
    console.log('prepending zid');
  	// we need to prepend a zid to the file name on disk
let filename = await tp.date.now("YYYYMMDDHHmm") + ' ' + title
    console.log('renaming to ', filename);
await tp.file.rename(`${filename}`);

  console.log('title is now', title);
  return title;

module.exports = zettler;

The important part is when I call await tp.file.rename() with the new name. This will update the link from the previous file to include the new zettel id.