Using generateMarkdownLink on Obsidian version 1.8.7 (Installer 1.5.11) seems to outright not work?
Trying a basic example such as
app.fileManager.generateMarkdownLink(app.vault.getAbstractFileByPath('Folder/A.md'), 'Folder/B.md')
gives me:
Uncaught TypeError: Cannot read properties of null (reading 'extension')
at t.fileToLinktext (app.js:1:1921765)
at e.generateMarkdownLink (app.js:1:1269853)
at <anonymous>:1:17
t.fileToLinktext @ app.js:1
e.generateMarkdownLink @ app.js:1
(anonymous) @ VM434:1
Is it me who’s using it wrong or is this a bug?
Basically, what I want to do is generate a link to a non existing file.
In your code app.vault.getAbstractFileByPath('Folder/A.md')
returned null
, so the file couldn’t be found. Ensure you have the correct case-sensitive path
ush
March 5, 2025, 9:10am
3
You can’t do that with Obsidian API. You need to do it manually.
For example:
this.app.vault.getConfig("useMarkdownLinks")
? `[${getBasenameFromPath(path)}](${encodeLinktext(path)})`
: `[[${path}]]`
But in reallity there are a lot more to consider, for example the “new link format” option and the file type. If you can create the target file first, that would be better
1 Like
Actually, it is possible to generate a link to a non-existing file, but it’s quite challenging. I have it in my library:
export function fixFrontmatterMarkdownLinks(cache: CachedMetadata): boolean {
return _fixFrontmatterMarkdownLinks(cache.frontmatter, '', cache);
}
/**
* Generates a markdown link based on the provided parameters.
*
* @param options - The options for generating the markdown link.
* @returns The generated markdown link.
*/
export function generateMarkdownLink(options: GenerateMarkdownLinkOptions): string {
const { app } = options;
const configurableDefaultOptionsFn = (app.fileManager.generateMarkdownLink as Partial<GenerateMarkdownLinkDefaultOptionsWrapper>).defaultOptionsFn
?? ((): Partial<GenerateMarkdownLinkOptions> => ({}));
const configurableDefaultOptions = configurableDefaultOptionsFn();
const DEFAULT_OPTIONS: Partial<GenerateMarkdownLinkOptions> = {
isEmptyEmbedAliasAllowed: true
};
isEmbed?: boolean;
/**
* Whether to allow an empty alias for embeds. Defaults to `true`.
*/
isEmptyEmbedAliasAllowed?: boolean;
/**
* Whether to allow non-existing files. If `false` and `pathOrFile` is a non-existing file, an error will be thrown. Defaults to `false`.
*/
isNonExistingFileAllowed?: boolean;
/**
* Indicates if the link should be a wikilink. If not provided, it will be inferred based on the Obsidian settings.
*/
isWikilink?: boolean;
/**
* The original link text. If provided, it will be used to infer the values of `isEmbed`, `isWikilink`, `useLeadingDot`, and `useAngleBrackets`.
* These inferred values will be overridden by corresponding settings if specified.
*/
2 Likes