コンテンツにスキップ

利用者:Yuukin0248/autoLink.js

お知らせ: 保存した後、ブラウザのキャッシュをクリアしてページを再読み込みする必要があります。

多くの WindowsLinux のブラウザ

  • Ctrl を押しながら F5 を押す。

Mac における Safari

  • Shift を押しながら、更新ボタン をクリックする。

Mac における ChromeFirefox

  • Cmd Shift を押しながら R を押す。

詳細についてはWikipedia:キャッシュを消すをご覧ください。

/**
 * autoLink.js
 * 差分画面や編集要約欄の "[[Sample]]" "{{Sample}}" という文字列から [[Sample]] や [[Template:Sample]] にリンク
 */

$.when($.ready, mw.loader.using('mediawiki.Title')).then(function () {
  $('span.comment, .diff-addedline, .diff-deletedline, .diff-context').each(function () {
    const elem = $(this);
    let html = elem.html();

    // 自動挿入される要約と、a 要素は無視
    const ignoreString = elem.find('.autocomment, a');
    const replaceFieldName = 'tempReplaceField';

    // 自動挿入される要約と、a 要素を一時除去
    ignoreString.each(function (index) {
      html = html.replace(this.innerHTML, replaceFieldName + index);
    });

    const re = /((?<!\{)\{\{[^#<>\{\}\[\]]+?(\||\}\}))|(\[\[[^#<>\{\}\[\]]+?(\||\]\]))/g;
    html.match(re)?.forEach(function (text) {
      const title = text.replace(/\[|\]|\{|\}|\||subst:/g, '').trim();
      const mwTitle = (function () {
        const patterns = {
          '&lt;': '<',
          '&gt;': '>',
          '&amp;': '&',
          '&quot;': '"',
          '&#x27;': "'",
          '&#x60;': '`',
        };
        const decodedTitle = title.replace(/&(lt|gt|amp|quot|#x27|#x60);/g, (match) => patterns[match]);
        // テンプレート名前空間にあるテンプレートの参照読み込みの場合はテンプレート名前空間を明示的に指定する
        return text.startsWith('{{') && !decodedTitle.includes(':') ? new mw.Title(decodedTitle, 10) : new mw.Title(decodedTitle);
      })();

      // リンクを追加
      const newText = text.replace(title, title.link(mwTitle.getUrl()));
      html = html.replace(text, newText);
    });

    // 自動挿入される要約と、a 要素を復帰
    ignoreString.each(function (index) {
      html = html.replace(replaceFieldName + index, this.innerHTML);
    });

    elem.html(html);
  });
});