Open a file in callback

Is there any API provided by obsidian that allows me to open a particular file (in TFile variable type) in any callback function? For example

const trigger = this.addRibbonIcon('dice', 'Open File', (evt: MouseEvent) => {
          // open file with path all/programming/python/tutorial.md
}

I’ve used the tp.file.find_tfile() method from Templater to locate tFile’s so far. Today I looked at the source of Templater and found it’s definition here, and it says:

    generate_find_tfile(): (filename: string) => TFile | null {
        return (filename: string) => {
            const path = normalizePath(filename);
            return app.metadataCache.getFirstLinkpathDest(path, "");
        };
    }

Here the normalizePath is imported from the obsidian module, so you’ll need to access that somehow. During my testing I’ve found the two following approaches produces a tFile:

// Using Templater's tp.file.find_tfile
const tp = app.plugins.plugins['templater-obsidian'].templater.current_functions_object
const tFile = await tp.file.find_tfile(file.path)

// Using _Dataview_ functions
const tFile =
  app.metadataCache
     .getFirstLinkpathDest(dv.io.normalize(file.path, "")

I think OP is asking about how to actually open a given TFile, not how to get TFile from a string path.

(And you can access normalizePath by tp.obsidian.normalizePath. Plus, in this case we have a proper path already, so we will not need to call it. cf. About normalizePath)

To answer the original question, you can use, for example,

2 Likes