Cosense Toolbox
userscript 一覧テーマ作成使い方パーサーGitHub ↗
選択して自動リンクするuserScript
ツール・エディタ#自動リンク#ポップアップメニュー#選択範囲

選択して自動リンクするuserScript

選択した文章の中から、プロジェクト内に存在するページタイトルを見つけて自動でリンク化してくれます。手作業で [...] を付けて回らなくても、まとめてリンクをつなげられるので、関連ページとのつながりを増やすのが楽になります。すでにリンクやハッシュタグになっている箇所はそのままにします。

使い方:テキストを選択して、出てくるメニューの「🤝 自動リンク」を押します。

デモ

デモ

インストール

設定ページの code:script.js に貼る
import "/api/code/cosense-toolbox/選択して自動リンクするuserScript/script.js";
ソースコード全文を見る(JS)
(() => {
  // lodash.escapeRegExpを参考にした
  const reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  const reHasRegExpChar = RegExp(reRegExpChar.source);
  function escapeRegExp(string) {
    return reHasRegExpChar.test(string) ? string.replace(reRegExpChar, "\\$&") : string;
  }
  function autoLink(lines) {
    const titles = cosense.Project.pages
      .filter((page) => page.title.length > 2 || page.exists) // タイトル3文字以上もしくは存在するページだけが自動リンク対象
      .map((page) => page.title)
      .sort((a, b) => b.length - a.length);

    const newLines = [];
    const usedTitles = [];
    for (const line of lines) {
      if (/[\[\]#]/.test(line)) {
        // 既にリンクがある行は処理しない
        newLines.push(line);
        continue;
      }
      let newLine = line;
      for (const title of titles) {
        const regexp = new RegExp(escapeRegExp(title), "i");
        if (!regexp.test(newLine)) continue;
        if (usedTitles.find((title) => regexp.test(title))) continue;
        newLine = newLine.replace(regexp, (m) => `[${m}]`);
        usedTitles.push(title);
      }
      newLines.push(newLine);
    }
    return newLines;
  }
  cosense.PopupMenu.addButton({
    title: "🤝 自動リンク",
    onClick: (text) => {
      const lines = text.split(/[\r\n]/g);
      const newLines = autoLink(lines);
      console.log(newLines);
      return newLines.join("\n");
    },
  });
})();
元のCosenseページを見る ↗

Cosense Toolbox / Cosense をもっと面白く、もっと強力に使うためのツール群

GitHub ↗

マイ・ツールボックス

    積んだ import を1つにまとめてコピー → 自分の設定ページ(ユーザー名ページ)に貼るだけ。