obsidian#TFile TypeScript Examples

The following examples show how to use obsidian#TFile. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From obsidian-switcher-plus with GNU General Public License v3.0 7 votes vote down vote up
export function stripMDExtensionFromPath(file: TFile): string {
  let retVal: string = null;

  if (file) {
    const { path } = file;
    retVal = path;

    if (file.extension === 'md') {
      const index = path.lastIndexOf('.');

      if (index !== -1 && index !== path.length - 1 && index !== 0) {
        retVal = path.slice(0, index);
      }
    }
  }

  return retVal;
}
Example #2
Source File: utility.ts    From quickadd with MIT License 7 votes vote down vote up
// Slightly modified version of Templater's user script import implementation
// Source: https://github.com/SilentVoid13/Templater
export async function getUserScript(command: IUserScript, app: App) {
    // @ts-ignore
    const file: TAbstractFile = app.vault.getAbstractFileByPath(command.path);
    if (!file) {
        log.logError(`failed to load file ${command.path}.`);
        return;
    }

    if (file instanceof TFile) {
        let req = (s: string) => window.require && window.require(s);
        let exp: Record<string, unknown> = {};
        let mod = { exports: exp };

        const fileContent = await app.vault.read(file);
        const fn = window.eval(`(function(require, module, exports) { ${fileContent} \n})`);
        fn(req, mod, exp);

        // @ts-ignore
        const userScript = exp['default'] || mod.exports;
        if (!userScript) return;

        let script = userScript;

        const {memberAccess} = getUserScriptMemberAccess(command.name);
        if (memberAccess && memberAccess.length > 0) {
            let member: string;
            while(member = memberAccess.shift()) {
                script = script[member];
            }
        }

        return script;
    }
}
Example #3
Source File: utils.ts    From nldates-obsidian with MIT License 7 votes vote down vote up
export async function getOrCreateDailyNote(date: Moment): Promise<TFile | null> {
  // Borrowed from the Slated plugin:
  // https://github.com/tgrosinger/slated-obsidian/blob/main/src/vault.ts#L17
  const desiredNote = getDailyNote(date, getAllDailyNotes());
  if (desiredNote) {
    return Promise.resolve(desiredNote);
  }
  return createDailyNote(date);
}
Example #4
Source File: defineGenericAnnotation.tsx    From obsidian-annotator with GNU Affero General Public License v3.0 6 votes vote down vote up
function getAbstractFileByPath(path, vault) {
    let p;
    if (
        (p = vault.getAbstractFileByPath(path)) instanceof TFile ||
        (p = vault.getAbstractFileByPath(`${path}.html`)) instanceof TFile
    ) {
        return p;
    }
}
Example #5
Source File: headingsHandler.ts    From obsidian-switcher-plus with GNU General Public License v3.0 6 votes vote down vote up
private makeAliasSuggestion(
    alias: string,
    file: TFile,
    match: SearchResult,
  ): AliasSuggestion {
    return {
      alias,
      file,
      match,
      type: 'alias',
    };
  }
Example #6
Source File: utility.ts    From quickadd with MIT License 6 votes vote down vote up
export async function templaterParseTemplate(app: App, templateContent: string, targetFile: TFile) {
    const templater = getTemplater(app);
    if (!templater) return templateContent;

    return await templater.templater.parse_template({target_file: targetFile, run_mode: 4}, templateContent);
}
Example #7
Source File: annotationFileUtils.tsx    From obsidian-annotator with GNU Affero General Public License v3.0 6 votes vote down vote up
export async function writeAnnotation(annotation: Annotation, plugin: AnnotatorPlugin, annotationFilePath: string) {
    const vault = plugin.app.vault;
    const tfile = vault.getAbstractFileByPath(annotationFilePath);

    let res: ReturnType<typeof writeAnnotationToAnnotationFileString>;
    if (tfile instanceof TFile) {
        const text = await vault.read(tfile);
        res = writeAnnotationToAnnotationFileString(annotation, text, plugin);
        vault.modify(tfile, res.newAnnotationFileString);
    } else {
        res = writeAnnotationToAnnotationFileString(annotation, null, plugin);
        vault.create(annotationFilePath, res.newAnnotationFileString);
    }
    return res.newAnnotation;
}
Example #8
Source File: parser.ts    From obsidian-chartsview-plugin with MIT License 6 votes vote down vote up
async function loadFromCsv(data: string, plugin: ChartsViewPlugin): Promise<DataType> {
    const csvFileNames = data.split(",");
    const value = [];
    for (const name of csvFileNames.values()) {
        const path = plugin.settings.dataPath === '/' ? '' : `${plugin.settings.dataPath}/`;
        const file = plugin.app.vault.getAbstractFileByPath(`${path}${name.trim()}`);
        if (file instanceof TFile) {
            value.push(parseCsv(await plugin.app.vault.read(file)));
        } else {
            value.push({});
        }
    }
    if (value.length == 0) {
        return {};
    }
    if (value.length == 1) {
        return value[0];
    }
    return value;
}
Example #9
Source File: index.ts    From obsidian-dataview with MIT License 6 votes vote down vote up
public constructor(public vault: Vault) {
        super();

        this.cache = new Map();

        // Force-flush the cache on CSV file deletions or modifications.
        this.registerEvent(
            this.vault.on("modify", file => {
                if (file instanceof TFile && PathFilters.csv(file.path)) this.cache.delete(file.path);
            })
        );

        this.registerEvent(
            this.vault.on("delete", file => {
                if (file instanceof TFile && PathFilters.csv(file.path)) this.cache.delete(file.path);
            })
        );
    }
Example #10
Source File: annotationFileUtils.tsx    From obsidian-annotator with GNU Affero General Public License v3.0 6 votes vote down vote up
export async function loadAnnotations(
    url: URL | null,
    vault: Vault,
    annotationFilePath: string
): Promise<AnnotationList> {
    const tfile = vault.getAbstractFileByPath(annotationFilePath);
    if (tfile instanceof TFile) {
        const text = await vault.read(tfile);
        return loadAnnotationsAtUriFromFileText(url, text);
    } else {
        return loadAnnotationsAtUriFromFileText(url, null);
    }
}
Example #11
Source File: index.ts    From obsidian-dataview with MIT License 6 votes vote down vote up
/** Queue a file for reloading; this is done asynchronously in the background and may take a few seconds. */
    public async reload(file: TFile): Promise<{ cached: boolean; skipped: boolean }> {
        if (!PathFilters.markdown(file.path)) return { cached: false, skipped: true };

        // The first load of a file is attempted from persisted cache; subsequent loads just use the importer.
        if (this.pages.has(file.path) || this.initialized) {
            await this.import(file);
            return { cached: false, skipped: false };
        } else {
            // Check the cache for the latest data; if it is out of date or non-existent, then reload.
            return this.persister.loadFile(file.path).then(async cached => {
                if (!cached || cached.time < file.stat.mtime || cached.version != this.indexVersion) {
                    // This cache value is out of data, reload via the importer and update the cache.
                    // We will skip files with no active file metadata - they will be caught by a later reload
                    // via the 'resolve' metadata event.
                    let fileCache = this.metadataCache.getFileCache(file);
                    if (fileCache === undefined || fileCache === null) return { cached: false, skipped: true };

                    await this.import(file);
                    return { cached: false, skipped: false };
                } else {
                    // Use the cached data since it is up to date and on the same version.
                    this.finish(file, cached.data);
                    return { cached: true, skipped: false };
                }
            });
        }
    }
Example #12
Source File: annotationFileUtils.tsx    From obsidian-annotator with GNU Affero General Public License v3.0 6 votes vote down vote up
export async function deleteAnnotation(
    annotationId,
    vault: Vault,
    annotationFilePath: string
): Promise<{
    deleted: boolean;
    id: string;
}> {
    const tfile = vault.getAbstractFileByPath(annotationFilePath);
    if (tfile instanceof TFile) {
        const text = await vault.read(tfile);
        const updatedText = deleteAnnotationFromAnnotationFileString(annotationId, text);
        if (text !== updatedText) {
            vault.modify(tfile, updatedText);
            return {
                deleted: true,
                id: annotationId
            };
        }
    }

    return {
        deleted: false,
        id: annotationId
    };
}
Example #13
Source File: import-manager.ts    From obsidian-dataview with MIT License 6 votes vote down vote up
/** Send a new task to the given worker ID. */
    private send(file: TFile, workerId: number) {
        this.busy[workerId] = true;

        this.vault.cachedRead(file).then(c =>
            this.workers[workerId].postMessage({
                path: file.path,
                contents: c,
                stat: file.stat,
                metadata: this.metadataCache.getFileCache(file),
            })
        );
    }
Example #14
Source File: annotatorView.tsx    From obsidian-annotator with GNU Affero General Public License v3.0 6 votes vote down vote up
getAnnotationTarget(file: TFile): string {
        const annotationTargetPropertyValue = this.plugin.getPropertyValue(ANNOTATION_TARGET_PROPERTY, file);
        if (!annotationTargetPropertyValue) {
            this.plugin.log('Invalid annotation target!');
            return '';
        }
        for (let target of [
            annotationTargetPropertyValue,
            `${this.plugin.settings.customDefaultPath}${annotationTargetPropertyValue}`
        ]) {
            //unpack target if it is is an array (For Metaedit compatability)
            if (Array.isArray(target)) {
                target = target[0];
            }

            if (isUrl(target)) {
                return target;
            }
            let destFile: TFile;
            try {
                destFile = this.app.metadataCache.getFirstLinkpathDest(target, file?.path || '');
            } finally {
                if (destFile) {
                    return destFile.path;
                }
            }
        }

        //unpack target if it is is an array (For Metaedit compatability)
        if (Array.isArray(annotationTargetPropertyValue)) {
            return annotationTargetPropertyValue[0];
        }

        return annotationTargetPropertyValue;
    }
Example #15
Source File: date-suggest.ts    From nldates-obsidian with MIT License 6 votes vote down vote up
onTrigger(
    cursor: EditorPosition,
    editor: Editor,
    file: TFile
  ): EditorSuggestTriggerInfo {
    if (!this.plugin.settings.isAutosuggestEnabled) {
      return null;
    }

    const triggerPhrase = this.plugin.settings.autocompleteTriggerPhrase;
    const startPos = this.context?.start || {
      line: cursor.line,
      ch: cursor.ch - triggerPhrase.length,
    };

    if (!editor.getRange(startPos, cursor).startsWith(triggerPhrase)) {
      return null;
    }

    const precedingChar = editor.getRange(
      {
        line: startPos.line,
        ch: startPos.ch - 1,
      },
      startPos
    );

    // Short-circuit if `@` as a part of a word (e.g. part of an email address)
    if (precedingChar && /[`a-zA-Z0-9]/.test(precedingChar)) {
      return null;
    }

    return {
      start: startPos,
      end: cursor,
      query: editor.getRange(startPos, cursor).substring(triggerPhrase.length),
    };
  }
Example #16
Source File: vault-handler.ts    From folder-note-core with MIT License 6 votes vote down vote up
onDelete = (af: TAbstractFile) => {
    const { getFolderNote, getFolderFromNote } = this.finder;
    if (af instanceof TFolder) {
      const oldNote = getFolderNote(af);
      if (!(this.settings.folderNotePref === NoteLoc.Outside && oldNote))
        return;

      if (this.settings.deleteOutsideNoteWithFolder) {
        this.delete(oldNote);
      } else this.plugin.trigger("folder-note:delete", oldNote, af);
    } else if (af instanceof TFile && isMd(af)) {
      const oldFolder = getFolderFromNote(af);
      if (oldFolder) this.plugin.trigger("folder-note:delete", af, oldFolder);
    }
  };
Example #17
Source File: main.tsx    From obsidian-annotator with GNU Affero General Public License v3.0 6 votes vote down vote up
getDropExtension() {
        return EditorState.transactionFilter.of(transaction => {
            if (transaction.isUserEvent('input.drop')) {
                try {
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    const droppedText = (transaction.changes as any).inserted.map(x => x.text.join('')).join('');

                    if (this.dragData !== null && droppedText == 'drag-event::hypothesis-highlight') {
                        const startPos = transaction.selection.ranges[0].from;
                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                        const leaf: FileView = Object.keys((transaction.state as any).config.address)
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            .map(x => (transaction.state as any).field({ id: x }))
                            .filter(x => x?.file)[0];

                        const targetFile = leaf.file;

                        const annotationFile = this.app.vault.getAbstractFileByPath(this.dragData.annotationFilePath);
                        if (annotationFile instanceof TFile && targetFile instanceof TFile) {
                            const linkString = this.app.fileManager.generateMarkdownLink(
                                annotationFile,
                                targetFile.path,
                                `#^${this.dragData.annotationId}`,
                                this.dragData.annotationText
                            );
                            this.dragData = null;
                            return { changes: { from: startPos, insert: linkString }, selection: { anchor: startPos } };
                        }
                    }
                } catch (e) {}
            }
            return transaction;
        });
    }
Example #18
Source File: resolver.ts    From folder-note-core with MIT License 6 votes vote down vote up
_createFolderForNote = (file: TFile) => {
    if (!isMd(file)) return null;

    const folderForNotePath = this.getFolderPath(file, false);
    if (
      folderForNotePath &&
      this.vault.getAbstractFileByPath(folderForNotePath)
    ) {
      log.info("createFolderForNote(%o): already folder note", file, file.path);
      return null;
    }

    const newFolderPath = this.getFolderPath(file, true),
      folderExist =
        newFolderPath && this.vault.getAbstractFileByPath(newFolderPath);
    return { newFolderPath, folderExist };
  };
Example #19
Source File: main.tsx    From obsidian-annotator with GNU Affero General Public License v3.0 6 votes vote down vote up
getPropertyValue(propertyName: string, file: TFile) {
        if (!file) {
            return null;
        }
        const dataview = (this.app as any)?.plugins?.getPlugin('dataview'); // eslint-disable-line
        const dataviewApi = dataview?.api;
        const dataviewPage = dataviewApi?.page(file.path);
        const dataViewPropertyValue = dataviewPage?.[propertyName];
        this.log({ dataview, loaded: dataview?._loaded, dataviewApi, dataviewPage, dataViewPropertyValue });
        if (dataViewPropertyValue) {
            if (dataViewPropertyValue.path) {
                return this.app.metadataCache.getFirstLinkpathDest(dataViewPropertyValue.path, file.path)?.path;
            }
            const externalLinkMatch = /^\[.*\]\((.*)\)$/gm.exec(dataViewPropertyValue)?.[1];
            if (externalLinkMatch) {
                return externalLinkMatch;
            }
            return dataViewPropertyValue;
        } else {
            const cache = this.app.metadataCache.getFileCache(file);
            return cache?.frontmatter?.[propertyName];
        }
    }
Example #20
Source File: markers.ts    From obsidian-map-view with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create FileMarker instances for all the files in the given list
 * @param files The list of file objects to find geolocations in.
 * @param settings The plugin settings
 * @param app The Obsidian App instance
 */
export async function buildMarkers(
    files: TFile[],
    settings: PluginSettings,
    app: App
): Promise<FileMarker[]> {
    if (settings.debug) console.time('buildMarkers');
    let markers: FileMarker[] = [];
    for (const file of files) {
        await buildAndAppendFileMarkers(markers, file, settings, app);
    }
    if (settings.debug) console.timeEnd('buildMarkers');
    return markers;
}
Example #21
Source File: main.ts    From obsidian-citation-plugin with MIT License 6 votes vote down vote up
async insertLiteratureNoteLink(citekey: string): Promise<void> {
    this.getOrCreateLiteratureNoteFile(citekey)
      .then((file: TFile) => {
        const useMarkdown: boolean = (<VaultExt>this.app.vault).getConfig(
          'useMarkdownLinks',
        );
        const title = this.getTitleForCitekey(citekey);

        let linkText: string;
        if (useMarkdown) {
          const uri = encodeURI(
            this.app.metadataCache.fileToLinktext(file, '', false),
          );
          linkText = `[${title}](${uri})`;
        } else {
          linkText = `[[${title}]]`;
        }

        this.editor.replaceRange(linkText, this.editor.getCursor());
      })
      .catch(console.error);
  }
Example #22
Source File: path.ts    From obsidian-fantasy-calendar with MIT License 6 votes vote down vote up
constructor(app: App, input: TextComponent, items: TFile[]) {
        super(app, input.inputEl, items);
        this.files = [...items];
        this.text = input;

        this.createPrompts();

        this.inputEl.addEventListener("input", this.getFile.bind(this));
    }
Example #23
Source File: main.ts    From luhman-obsidian-plugin with GNU General Public License v3.0 6 votes vote down vote up
async getAllNoteTitles(): Promise<Map<string, TFile>> {
    const regex = /# (.+)\s*/;

    let titles: Map<string, TFile> = new Map();
    for (const file of this.getZettels()) {
      let text = await this.app.vault.cachedRead(file);

      let match = text.match(regex);
      if (match) {
        titles.set(match[1], file);
      }
    }

    return titles;
  }
Example #24
Source File: path.ts    From obsidian-fantasy-calendar with MIT License 6 votes vote down vote up
selectSuggestion({ item }: FuzzyMatch<TFile | BlockCache | HeadingCache>) {
        let link: string;
        if (item instanceof TFile) {
            this.file = item;
            link = item.basename;
        } else if (Object.prototype.hasOwnProperty.call(item, "heading")) {
            link = this.file.basename + "#" + (<HeadingCache>item).heading;
        } else if (Object.prototype.hasOwnProperty.call(item, "id")) {
            link = this.file.basename + "^" + (<BlockCache>item).id;
        }
        const path = this.file.path.split("/").slice(0, -1);
        if (path.length) {
            this.link = path.join("/") + "/" + link;
        } else {
            this.link = link;
        }
        this.text.setValue(link);

        this.close();
        this.onClose();
    }
Example #25
Source File: files-manager.ts    From Obsidian_to_Anki with GNU General Public License v3.0 6 votes vote down vote up
getFolderPathList(file: TFile): TFolder[] {
        let result: TFolder[] = []
        let abstractFile: TAbstractFile = file
        while (abstractFile.hasOwnProperty('parent')) {
            result.push(abstractFile.parent)
            abstractFile = abstractFile.parent
        }
        result.pop() // Removes top-level vault
        return result
    }
Example #26
Source File: path.ts    From obsidian-fantasy-calendar with MIT License 6 votes vote down vote up
getItemText(item: TFile | HeadingCache | BlockCache) {
        if (item instanceof TFile) return item.path;
        if (Object.prototype.hasOwnProperty.call(item, "heading")) {
            return (<HeadingCache>item).heading;
        }
        if (Object.prototype.hasOwnProperty.call(item, "id")) {
            return (<BlockCache>item).id;
        }
    }
Example #27
Source File: main.ts    From obsidian-custom-attachment-location with GNU General Public License v3.0 6 votes vote down vote up
async handleFileOpen(file: TFile | null){
        console.log('Handle File Open');
        
        if (file == null) {
            console.log("No file open");
            return;
        }

        let mdFileName = file.basename;

        let path = this.getAttachmentFolderPath(mdFileName);

        this.updateAttachmentFolderConfig(path);
    }
Example #28
Source File: Templater.ts    From Templater with GNU Affero General Public License v3.0 6 votes vote down vote up
create_running_config(
        template_file: TFile,
        target_file: TFile,
        run_mode: RunMode
    ): RunningConfig {
        const active_file = this.app.workspace.getActiveFile();

        return {
            template_file: template_file,
            target_file: target_file,
            run_mode: run_mode,
            active_file: active_file,
        };
    }
Example #29
Source File: utils.ts    From obsidian-map-view with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create a new markdown note and populate with the location
 * @param app The Obsidian App instance
 * @param newNoteType The location format to encode as
 * @param directory The directory path to put the file in
 * @param fileName The name of the file
 * @param location The geolocation
 * @param templatePath Optional path to a template to use for constructing the new file
 */
export async function newNote(
    app: App,
    newNoteType: NewNoteType,
    directory: string,
    fileName: string,
    location: string,
    templatePath?: string
): Promise<TFile> {
    // `$CURSOR$` is used to set the cursor
    let content =
        newNoteType === 'singleLocation'
            ? `---\nlocation: [${location}]\n---\n\n${CURSOR}`
            : `---\nlocations:\n---\n\n\[${CURSOR}](geo:${location})\n`;
    let templateContent = '';
    if (templatePath && templatePath.length > 0)
        templateContent = await app.vault.adapter.read(templatePath);
    if (!directory) directory = '';
    if (!fileName) fileName = '';
    // Apparently in Obsidian Mobile there is no path.join function, not sure why.
    // So in case the path module doesn't contain `join`, we do it manually, assuming Unix directory structure.
    const filePath = path?.join
        ? path.join(directory, fileName)
        : directory
        ? directory + '/' + fileName
        : fileName;
    let fullName = sanitizeFileName(filePath);
    if (await app.vault.adapter.exists(fullName + '.md'))
        fullName += Math.random() * 1000;
    try {
        return app.vault.create(fullName + '.md', content + templateContent);
    } catch (e) {
        console.log('Map View: cannot create file', fullName);
        throw Error(`Cannot create file named ${fullName}: ${e}`);
    }
}