## コマンド系
引数は`CommandId`。
```js
app.commands.executeCommandById("workspace:edit-file-title")
```
`CommandId`は`app.commands`で確認できる。
![[Pasted image 20210523143022.png]]
### エディタ上でリネーム開始
```js
app.commands.executeCommandById("workspace:edit-file-title")
```
## ファイル系
### アクティブなファイルの取得
```js
const file = app.workspace.getActiveFile()
```
取得するのはObjectなのでファイルパスなら`file.path`のようにする。
### カレントディレクトリを取得
```js
const file = app.workspace.getActiveFile().parent
```
### ファイル名とディレクトリ名で新規作成
`tp.file.create_new`を使う。
https://silentvoid13.github.io/Templater/internal-functions/internal-modules/file-module.html#tpfilecreate_newtemplate-tfile--string-filename-string-open_new-boolean--false-folder-tfolder
```json
const currentDirectory = app.workspace.getActiveFile().parent
tp.file.create_new("bodyの初期値", "ファイル名.md", true, currentDirectory)
```
### パスでファイルの新規作成
設定に関係なく`path`で指定したファイルを作成する。`.md`の拡張子が必要。
```js
const path = "hoge.md"
app.vault.create(path, "なかみ")
```
### 名称でファイルの新規作成
[[Obsidian]]のファイル作成コマンドから実行したのと同じ。
```js
app.fileManager.createAndOpenMarkdownFile("新しいファイル名")
```
`app.fileManager.createMarkdownFile`はなぜかエラーになる。
### ファイルを開く
`openLinkText`という名前からしてコレジャナイ気もするけど他に見つからなかった..。
```js
app.workspace.openLinkText("", file.path, true)
```
- 第1引数: ???
- 第2引数: 開くファイルのパス
- 第3引数: 新しいpaneで開く場合は`true`
### デフォルトアプリでファイルを開く
[[デフォルト(外部)アプリでファイルやディレクトリを開く (Obsidian)]] を参照。
### エクスプローラーでファイルの場所を開く
[[ファイルエクスプローラーでファイルやディレクトリを開く (Obsidian)]] を参照。
### ファイルの存在確認
パスではなく名前で確認できる。
```js
tp.file.exists("hogehoge")
```
### ファイルの中身を取得する
```js
tp.file.content
```
### [[バックリンク]]を取得
```js
const currentFile = app.workspace.getActiveFile()
app.metadataCache.getBacklinksForFile(currentFile)
```
形式イメージ
```json
{
data: {
[rootからの絶対パス .md含む]: {
{
displayText: "readonly Properties",
link: "readonly Properties",
original: "[[readonly Properties]]",
position: {
start: {line: number, col: number, offset: number},
end: {line: number, col: number, offset: number}
}
}
}[]
}
}
```
## エディタ系
### 取得
#### カーソル下のリンクから文字列を取得
カーソルを取得してから`getClickableTokenAt`を使う。
```js
const cur = app.workspace.activeLeaf.view.editor.getCursor()
const title = app.workspace.activeLeaf.view.editor.getClickableTokenAt(cur)?.text ?? "untitled"
```
#### 選択範囲の文字列を取得
```js
const text = app.workspace.activeLeaf.view.editor.getSelection()
```
#### カーソル行の文字列を取得
```json
const editor = app.workspace.activeLeaf.view.editor
const str = editor.getLine(editor.getCursor().line)
```
### 変更
#### カーソルのあとに文字列を挿入
```js
const editor = app.workspace.activeLeaf.view.editor
editor.replaceSelection("hoge", editor.getCursor())
```
> [!caution]
> 以下のコードはファイルの最後尾に挿入されるので要件を満たさない。(v1.4.4では)
> ```js
> app.workspace.activeLeaf.view.editor.insertText("hoge")
> ```
#### 選択範囲を任意の文字列で置換
```js
app.workspace.activeLeaf.view.editor.replaceSelection("hoge")
```
#### カーソル行を任意の文字列で置換
```json
const editor = app.workspace.activeLeaf.view.editor
editor.setLine(editor.getCursor().line, "hoge")
```
#### アクティブファイルの最後に文字列を挿入
```js
app.workspace.activeLeaf.view.editor.insertText("hoge")
```
> [!info]
> 以前は以下のコードでないとダメだった気がするが、v1.4.4では仕様が変わってる?
> ```js
> /**
> * 最終行にテキストを追加する
> * 最終行が空でない場合は新規に行を追加する
> * @param {*} text
> */
> async function insertNewLineAtLast(text) {
> const editor = app.workspace.activeLeaf.view.editor;
> const lastLineText = editor.getLine(editor.lastLine());
> const insertedText = lastLineText ? `\n${text}` : text;
>
> editor.replaceRange(insertedText, CodeMirror.Pos(editor.lastLine()));
> }
>
> module.exports = insertNewLineAtLast;
> ```
## [[プロパティ (Obsidian)|プロパティ]]系 ([[フロントマター]])
### プロパティの取得
```js
// 現在ファイルから取得する例
app.metadataCache.getFileCache(app.workspace.getActiveFile()).frontmatter
```
### プロパティの挿入/変更
```ts
app.workspace.activeEditor.metadataEditor.insertProperties({keyName: "huga"})
```
- 存在しない場合は新規
- 既に存在する場合は**上書き**
### プロパティの削除
```ts
app.workspace.activeEditor.metadataEditor.insertProperties({keyName: undefined})
```
`removeProperties`ではないのが不思議(何に使うんだろう...)。
### プロパティの値にフォーカスする
```ts
app.workspace.activeEditor.metadataEditor.focusValue("keyName")
```
## 対話系
### ユーザーに値を入力させる
https://silentvoid13.github.io/Templater/internal-functions/internal-modules/system-module.html
`tp.system.prompt`を使う。戻り値は[[Promise]]のため`await`を忘れると予期せぬエラーになるので注意。
```js
const url = await tp.system.prompt("Enter URL")
if (!url) {
return
}
```
## 検索系
### タグ一覧の取得
```js
app.metadataCache.getTags()
```
キーは`#`から始まるタグ名、値は出現回数。
## システム系
### クリップボードに保存
[[Navigator.clipboard]]を使う。
```js
await navigator.clipboard.writeText(テキスト)
```
### Notification(トースター)を表示
[[トースターを表示 (Obsidian)]] を参照。
## [[JavaScript]]のスニペット
### groupBy
```js
const groupBy = (values, toKey) =>
values.reduce(
(prev, cur, _1, _2, k = toKey(cur)) => (
(prev[k] || (prev[k] = [])).push(cur), prev
),
{}
);
```
### orderBy
```js
function sorter(toOrdered, order = "asc") {
return (a, b) =>
order === "asc"
? toOrdered(a) > toOrdered(b)
? 1
: toOrdered(b) > toOrdered(a)
? -1
: 0
: toOrdered(a) < toOrdered(b)
? 1
: toOrdered(b) < toOrdered(a)
? -1
: 0;
};
[1, 2, 1].sort(sorter(x => x))
```