obsidian#Vault TypeScript Examples
The following examples show how to use
obsidian#Vault.
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 Templater with GNU Affero General Public License v3.0 | 6 votes |
export function get_tfiles_from_folder(
app: App,
folder_str: string
): Array<TFile> {
const folder = resolve_tfolder(app, folder_str);
const files: Array<TFile> = [];
Vault.recurseChildren(folder, (file: TAbstractFile) => {
if (file instanceof TFile) {
files.push(file);
}
});
files.sort((a, b) => {
return a.basename.localeCompare(b.basename);
});
return files;
}
Example #2
Source File: sync.ts From remotely-save with Apache License 2.0 | 6 votes |
fetchMetadataFile = async (
metadataFile: FileOrFolderMixedState,
client: RemoteClient,
vault: Vault,
password: string = ""
) => {
if (metadataFile === undefined) {
log.debug("no metadata file, so no fetch");
return {
deletions: [],
} as MetadataOnRemote;
}
const buf = await client.downloadFromRemote(
metadataFile.key,
vault,
metadataFile.mtimeRemote,
password,
metadataFile.remoteEncryptedKey,
true
);
const metadata = deserializeMetadataOnRemote(buf);
return metadata;
}
Example #3
Source File: main.ts From obsidian-readwise with GNU General Public License v3.0 | 6 votes |
reimportFile(vault: Vault, fileName: string) {
const bookId = this.settings.booksIDsMap[fileName];
try {
fetch(
`${baseURL}/api/refresh_book_export`,
{
headers: {...this.getAuthHeaders(), 'Content-Type': 'application/json'},
method: "POST",
body: JSON.stringify({exportTarget: 'obsidian', books: [bookId]})
}
).then(response => {
if (response && response.ok) {
let booksToRefresh = this.settings.booksToRefresh;
this.settings.booksToRefresh = booksToRefresh.filter(n => ![bookId].includes(n));
this.saveSettings();
vault.delete(vault.getAbstractFileByPath(fileName));
this.startSync();
} else {
this.notice("Failed to reimport. Please try again", true);
}
});
} catch (e) {
console.log("Readwise Official plugin: fetch failed in Reimport current file: ", e);
}
}
Example #4
Source File: manager.ts From better-word-count with MIT License | 6 votes |
constructor(
statusBar: StatusBar,
settings: BetterWordCountSettings,
vault: Vault,
metadataCache: MetadataCache
) {
this.statusBar = statusBar;
this.settings = settings;
this.vault = vault;
this.dataCollector = new DataCollector(vault, metadataCache);
this.dataManager = new DataManager(vault, metadataCache);
this.deboucer = debounce(
(text: string) => this.updateStatusBar(text),
20,
false
);
this.expression = parse(this.settings.statusBarQuery);
}
Example #5
Source File: videoAnnotationFileUtils.tsx From obsidian-annotator with GNU Affero General Public License v3.0 | 6 votes |
export async function deleteVideoAnnotation(
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 = deleteVideoAnnotationFromVideoAnnotationFileString(annotationId, text);
if (text !== updatedText) {
vault.modify(tfile, updatedText);
return {
deleted: true,
id: annotationId
};
}
}
return {
deleted: false,
id: annotationId
};
}
Example #6
Source File: import-manager.ts From obsidian-dataview with MIT License | 6 votes |
public constructor(public numWorkers: number, public vault: Vault, public metadataCache: MetadataCache) {
super();
this.workers = [];
this.busy = [];
this.reloadQueue = [];
this.reloadSet = new Set();
this.callbacks = new Map();
for (let index = 0; index < numWorkers; index++) {
let worker = new DataviewImportWorker({ name: "Dataview Indexer " + (index + 1) });
worker.onmessage = evt => this.finish(evt.data.path, Transferable.value(evt.data.result), index);
this.workers.push(worker);
this.register(() => worker.terminate());
this.busy.push(false);
}
}
Example #7
Source File: checkAndCreateFolder.ts From obsidian-ReadItLater with MIT License | 6 votes |
/**
* Open or create a folderpath if it does not exist
* @param vault
* @param folderpath
*/
export async function checkAndCreateFolder(vault: Vault, folderpath: string) {
folderpath = normalizePath(folderpath);
const folder = vault.getAbstractFileByPath(folderpath);
if (folder && folder instanceof TFolder) {
return;
}
await vault.createFolder(folderpath);
}
Example #8
Source File: tools.ts From obsidian-chartsview-plugin with MIT License | 6 votes |
export function getFolderOptions(app: App) {
const options: Record<string, string> = {};
Vault.recurseChildren(app.vault.getRoot(), (f) => {
if (f instanceof TFolder) {
options[f.path] = f.path;
}
});
return options;
}
Example #9
Source File: task-view.tsx From obsidian-dataview with MIT License | 6 votes |
/** Rewrite a task with the given completion status and new text. */
export async function rewriteTask(vault: Vault, task: STask, desiredStatus: string, desiredText?: string) {
if (desiredStatus == task.status && (desiredText == undefined || desiredText == task.text)) return;
desiredStatus = desiredStatus == "" ? " " : desiredStatus;
let rawFiletext = await vault.adapter.read(task.path);
let hasRN = rawFiletext.contains("\r");
let filetext = rawFiletext.split(/\r?\n/u);
if (filetext.length < task.line) return;
let match = LIST_ITEM_REGEX.exec(filetext[task.line]);
if (!match || match[2].length == 0) return;
let taskTextParts = task.text.split("\n");
if (taskTextParts[0].trim() != match[3].trim()) return;
// We have a positive match here at this point, so go ahead and do the rewrite of the status.
let initialSpacing = /^[\s>]*/u.exec(filetext[task.line])!![0];
if (desiredText) {
let desiredParts = desiredText.split("\n");
let newTextLines: string[] = [`${initialSpacing}${task.symbol} [${desiredStatus}] ${desiredParts[0]}`].concat(
desiredParts.slice(1).map(l => initialSpacing + "\t" + l)
);
filetext.splice(task.line, task.lineCount, ...newTextLines);
} else {
filetext[task.line] = `${initialSpacing}${task.symbol} [${desiredStatus}] ${taskTextParts[0].trim()}`;
}
let newText = filetext.join(hasRN ? "\r\n" : "\n");
await vault.adapter.write(task.path, newText);
}
Example #10
Source File: remoteForOnedrive.ts From remotely-save with Apache License 2.0 | 5 votes |
downloadFromRemote = async (
client: WrappedOnedriveClient,
fileOrFolderPath: string,
vault: Vault,
mtime: number,
password: string = "",
remoteEncryptedKey: string = "",
skipSaving: boolean = false
) => {
await client.init();
const isFolder = fileOrFolderPath.endsWith("/");
if (!skipSaving) {
await mkdirpInVault(fileOrFolderPath, vault);
}
if (isFolder) {
// mkdirp locally is enough
// do nothing here
return new ArrayBuffer(0);
} else {
let downloadFile = fileOrFolderPath;
if (password !== "") {
downloadFile = remoteEncryptedKey;
}
downloadFile = getOnedrivePath(downloadFile, client.remoteBaseDir);
const remoteContent = await downloadFromRemoteRaw(client, downloadFile);
let localContent = remoteContent;
if (password !== "") {
localContent = await decryptArrayBuffer(remoteContent, password);
}
if (!skipSaving) {
await vault.adapter.writeBinary(fileOrFolderPath, localContent, {
mtime: mtime,
});
}
return localContent;
}
}
Example #11
Source File: index.ts From obsidian-dataview with MIT License | 5 votes |
/** I/O access to the Obsidian vault contents. */
public vault: Vault;
Example #12
Source File: main.ts From obsidian-readwise with GNU General Public License v3.0 | 5 votes |
vault: Vault;
Example #13
Source File: import-manager.ts From obsidian-dataview with MIT License | 5 votes |
public constructor(public numWorkers: number, public vault: Vault, public metadataCache: MetadataCache) {}
Example #14
Source File: vault-handler.ts From folder-note-core with MIT License | 5 votes |
private delete: Vault["delete"] = (...args) =>
this.plugin.app.vault.delete(...args);
Example #15
Source File: obsFolderLister.ts From remotely-save with Apache License 2.0 | 5 votes |
listFilesInObsFolder = async (
configDir: string,
vault: Vault,
pluginId: string
) => {
const q = new Queue([configDir]);
const CHUNK_SIZE = 10;
const contents: ObsConfigDirFileType[] = [];
while (q.length > 0) {
const itemsToFetch = [];
while (q.length > 0) {
itemsToFetch.push(q.pop());
}
const itemsToFetchChunks = chunk(itemsToFetch, CHUNK_SIZE);
for (const singleChunk of itemsToFetchChunks) {
const r = singleChunk.map(async (x) => {
const statRes = await statFix(vault, x);
const isFolder = statRes.type === "folder";
let children: ListedFiles = undefined;
if (isFolder) {
children = await vault.adapter.list(x);
}
return {
itself: {
key: isFolder ? `${x}/` : x,
...statRes,
} as ObsConfigDirFileType,
children: children,
};
});
const r2 = flatten(await Promise.all(r));
for (const iter of r2) {
contents.push(iter.itself);
const isInsideSelfPlugin = isPluginDirItself(iter.itself.key, pluginId);
if (iter.children !== undefined) {
for (const iter2 of iter.children.folders) {
if (isFolderToSkip(iter2)) {
continue;
}
if (isInsideSelfPlugin && !isLikelyPluginSubFiles(iter2)) {
// special treatment for remotely-save folder
continue;
}
q.push(iter2);
}
for (const iter2 of iter.children.files) {
if (isFolderToSkip(iter2)) {
continue;
}
if (isInsideSelfPlugin && !isLikelyPluginSubFiles(iter2)) {
// special treatment for remotely-save folder
continue;
}
q.push(iter2);
}
}
}
}
}
return contents;
}
Example #16
Source File: resyncDelFileModal.ts From obsidian-hypothesis-plugin with MIT License | 5 votes |
private vault: Vault;
Example #17
Source File: remoteForS3.ts From remotely-save with Apache License 2.0 | 5 votes |
downloadFromRemote = async (
s3Client: S3Client,
s3Config: S3Config,
fileOrFolderPath: string,
vault: Vault,
mtime: number,
password: string = "",
remoteEncryptedKey: string = "",
skipSaving: boolean = false
) => {
const isFolder = fileOrFolderPath.endsWith("/");
if (!skipSaving) {
await mkdirpInVault(fileOrFolderPath, vault);
}
// the file is always local file
// we need to encrypt it
if (isFolder) {
// mkdirp locally is enough
// do nothing here
return new ArrayBuffer(0);
} else {
let downloadFile = fileOrFolderPath;
if (password !== "") {
downloadFile = remoteEncryptedKey;
}
const remoteContent = await downloadFromRemoteRaw(
s3Client,
s3Config,
downloadFile
);
let localContent = remoteContent;
if (password !== "") {
localContent = await decryptArrayBuffer(remoteContent, password);
}
if (!skipSaving) {
await vault.adapter.writeBinary(fileOrFolderPath, localContent, {
mtime: mtime,
});
}
return localContent;
}
}
Example #18
Source File: fileManager.ts From obsidian-hypothesis-plugin with MIT License | 5 votes |
constructor(vault: Vault, metadataCache: MetadataCache) {
this.vault = vault;
this.metadataCache = metadataCache;
this.renderer = new Renderer();
}
Example #19
Source File: main.ts From obsidian-banners with MIT License | 5 votes |
vault: Vault;
Example #20
Source File: tasks.ts From obsidian-checklist-plugin with MIT License | 5 votes |
parseTodos = async (
files: TFile[],
todoTags: string[],
cache: MetadataCache,
vault: Vault,
includeFiles: string,
showChecked: boolean,
lastRerender: number
): Promise<TodoItem[]> => {
const includePattern = includeFiles.trim() ? includeFiles.trim().split("\n") : "**/*"
const filesWithCache = await Promise.all(
files
.filter((file) => {
if (file.stat.mtime < lastRerender) return false
if (!picomatch.isMatch(file.path, includePattern)) return false
if (todoTags.length === 1 && todoTags[0] === "*") return true
const fileCache = cache.getFileCache(file)
const allTags = getAllTagsFromMetadata(fileCache)
const tagsOnPage = allTags.filter((tag) => todoTags.includes(getTagMeta(tag).main))
return tagsOnPage.length > 0
})
.map<Promise<FileInfo>>(async (file) => {
const fileCache = cache.getFileCache(file)
const tagsOnPage = fileCache?.tags?.filter((e) => todoTags.includes(getTagMeta(e.tag).main)) ?? []
const frontMatterTags = getFrontmatterTags(fileCache, todoTags)
const hasFrontMatterTag = frontMatterTags.length > 0
const parseEntireFile = todoTags[0] === "*" || hasFrontMatterTag
const content = await vault.cachedRead(file)
return {
content,
cache: fileCache,
validTags: tagsOnPage.map((e) => ({ ...e, tag: e.tag.toLowerCase() })),
file,
parseEntireFile,
frontmatterTag: todoTags.length ? frontMatterTags[0] : undefined,
}
})
)
let allTodos = filesWithCache.flatMap(findAllTodosInFile)
if (!showChecked) allTodos = allTodos.filter((f) => !f.checked)
return allTodos
}
Example #21
Source File: annotationFileUtils.tsx From obsidian-annotator with GNU Affero General Public License v3.0 | 5 votes |
export async function getAnnotation(annotationId: string, file: TFile, vault: Vault): Promise<Annotation> {
const text = await vault.read(file);
return getAnnotationFromFileContent(annotationId, text);
}
Example #22
Source File: helpers.ts From obsidian-checklist-plugin with MIT License | 5 votes |
getFileFromPath = (vault: Vault, path: string) => {
let file = vault.getAbstractFileByPath(path)
if (file instanceof TFile) return file
const files = vault.getFiles()
file = files.find((e) => e.name === path)
if (file instanceof TFile) return file
}
Example #23
Source File: videoAnnotationFileUtils.tsx From obsidian-annotator with GNU Affero General Public License v3.0 | 5 votes |
export async function getVideoAnnotation(annotationId: string, file: TFile, vault: Vault): Promise<VideoAnnotation> {
const text = await vault.read(file);
return getVideoAnnotationFromFileContent(annotationId, text);
}
Example #24
Source File: obsidian.ts From obsidian-fantasy-calendar with MIT License | 5 votes |
/** @public */
vault: Vault;
Example #25
Source File: obsidian-extensions.d.ts From obsidian-citation-plugin with MIT License | 5 votes |
export class VaultExt extends Vault {
getConfig(key: string): any;
}
Example #26
Source File: LocalImageModal.ts From obsidian-banners with MIT License | 5 votes |
vault: Vault;
Example #27
Source File: collector.ts From better-word-count with MIT License | 5 votes |
constructor(vault: Vault, metadataCache: MetadataCache) {
this.vault = vault;
this.metadataCache = metadataCache;
}
Example #28
Source File: index.ts From obsidian-dataview with MIT License | 5 votes |
constructor(public vault: Vault, public updateRevision: () => void) {
super();
}
Example #29
Source File: manager.ts From better-word-count with MIT License | 5 votes |
private vault: Vault;