aboutsummaryrefslogtreecommitdiffstats
path: root/migemized_find.js
blob: dc3ba0341ce678b25f6239248ab400fea7e07b4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
// ==VimperatorPlugin==
// @name           Migemized Find
// @description-ja デフォルトのドキュメント内検索をミゲマイズする。
// @license        Creative Commons 2.1 (Attribution + Share Alike)
// @version        1.2
// ==/VimperatorPlugin==
//
// Usage:
//    検索ワードの一文字目が
//      '/'  => 正規表現検索
//      '?'  => Migemo検索
//      以外 => Migemo検索
//
// Author:
//    anekos
//
// Link:
//    http://d.hatena.ne.jp/nokturnalmortum/20080805#1217941126

(function () { try {

  let XMigemoCore = Components.classes['@piro.sakura.ne.jp/xmigemo/factory;1']
                     .getService(Components.interfaces.pIXMigemoFactory)
                     .getService('ja');

  function getPosition (elem) {
    if (!elem)
      return {x: 0, y: 0};
    let parent = getPosition(elem.offsetParent);
    return { x: (elem.offsetLeft || 0) + parent.x,
             y: (elem.offsetTop  || 0) + parent.y  }
  }

  function slashArray (ary, center) {
    let head = [], tail = [];
    let current = head;
    for (let i = 0; i < ary.length; i++) {
      let it = ary[i];
      if (it == center)
        current = tail;
      else
        current.push(it);
    }
    return [head, tail];
  }

  let MF = {
    // 定数
    MODE_NORMAL: 0,
    MODE_REGEXP: 1,
    MODE_MIGEMO: 2,

    lastSearchText: null,
    lastSearchExpr: null,
    previousSearchText: null,
    lastDirection: null,

    get buffer function () liberator.buffer,

    get document function () content.document,

    // タブ毎に状態を保存するために、変数を用意
    get storage function () (gBrowser.mCurrentTab.__migemized_find_storage || (gBrowser.mCurrentTab.__migemized_find_storage = {})),

    makeBodyRange: function (frame) {
      let range = frame.document.createRange();
      range.selectNodeContents(frame.document.body);
      return range;
    },

    get highlightRemover function () (this.storage.highlightRemover || function () void(0)),
    set highlightRemover function (fun) (this.storage.highlightRemover = fun),

    // 検索文字列から検索モードと検索文字列を得る。
    searchTextToRegExpString: function (str) {
      let [head, tail] = [str[0], str.slice(1)];
      switch (head) {
        case '/':
          return tail;
        case '?':
          return XMigemoCore.getRegExp(tail);
      }
      return XMigemoCore.getRegExp(str);
    },

    removeHighlight: function () {
      this.highlightRemover()
      this.highlightRemover = null;
    },

    focusLink: function (range) {
      let node = range.commonAncestorContainer;
      while (node && node.parentNode) {
        if (node.localName.toString().toLowerCase() == 'a')
          return void(Components.lookupMethod(node, 'focus').call(node));
        node = node.parentNode;
      }
    },

    highlight: function (target, setRemover) {
      let span = this.document.createElement('span');
      let spanStyle = 'background-color: lightblue; color: black; border: dotted 3px blue;';

      span.setAttribute('style', spanStyle);
      target.range.surroundContents(span);

      let scroll = function () {
        let pos = getPosition(span);
        target.frame.scroll(pos.x - (target.frame.innerWidth / 2),
                            pos.y - (target.frame.innerHeight / 2));
      };
      setTimeout(scroll, 0);

      let remover = function () {
        let range = this.document.createRange();
        range.selectNodeContents(span);
        let content = range.extractContents();
        range.setStartBefore(span);
        range.insertNode(content);
        range.selectNode(span); 
        range.deleteContents(); 
      };

      this.focusLink(target.range);

      if (setRemover)
        this.highlightRemover = remover;

      return remover;
    },

    find: function (str, backwards, range, start, end) {
      if (!range)
        range = this.makeBodyRange(this.currentFrames[0]);

      if (!start) {
        start = range.startContainer.ownerDocument.createRange();
        start.setStartBefore(range.startContainer);
      }
      if (!end) {
        end = range.endContainer.ownerDocument.createRange();
        end.setEndAfter(range.endContainer);
      }

      // 検索方向に合わせて、開始終了位置を交換
      if (backwards)
        [start, end] = [end, start];

      try {
        return XMigemoCore.regExpFind(str, 'i', range, start, end, backwards);
      } catch (e) {
        return false;
      }
    },

    findFirst: function (str, backwards) {
      this.lastDirection = backwards;
      this.lastSearchText = str;
      this.lastSearchExpr = str = this.searchTextToRegExpString(str);

      let result, frames = this.currentFrames;
      if (backwards)
        frames = frames.reverse();

      for each (let frame in frames) {
        let ret = this.find(str, backwards, this.makeBodyRange(frame));
        if (ret) {
          result = this.storage.lastResult = {
            frame: frame,
            range: ret,
          };
          break;
        }
      }

      this.removeHighlight();
      if (result)
        this.highlight(result, true);

      return result;
    },

    findAgain: function (reverse) {
      let backwards = !!(!this.lastDirection ^ !reverse);
      let last = this.storage.lastResult;
      let currentFrames = this.currentFrames;

      // 前回の結果がないので、(初め|最後)のフレームを対象にする
      // findFirst と"似た"挙動になる
      if (!last) {
        let idx = backwards ? frames.length - 1 
                            : 0;
        last = {frame: frames[idx], range: this.makeBodyRange(frames[idx])};
      }

      this.removeHighlight();

      let str = this.lastSearchExpr;
      let start, end;

      if (backwards) {
        end = last.range.cloneRange();
        end.setEnd(last.range.startContainer, last.range.startOffset);
      } else {
        start = last.range.cloneRange();
        start.setStart(last.range.endContainer, last.range.endOffset);
      }

      let result;
      let ret = this.find(str, backwards, this.makeBodyRange(last.frame), start, end);

      if (ret) {
        result = {frame: last.frame, range: ret};
      } else {
        // 見つからなかったので、ほかのフレームから検索
        let [head, tail] = slashArray(currentFrames, last.frame);
        let next = backwards ? head.reverse().concat(tail.reverse())
                             : tail.concat(head);
        for each (let frame in next) {
          let r = this.find(str, backwards, this.makeBodyRange(frame));
          if (r) {
            result = {frame: frame, range: r};
            break;
          }
        }
      }

      this.storage.lastResult = result;

      if (result)
        this.highlight(result, true);

      return result;
    },

    submit: function () {
      this.previousSearchText = this.lastSearchText;
    },

    cancel: function () {
      this.lastSearchText = MF.previousSearchText;
    },

    get currentFrames function () {
      let result = [];
      (function (frame) {
        // ボディがない物は検索対象外なので外す
        if (frame.document.body.localName.toLowerCase() == 'body')
          result.push(frame);
        for (let i = 0; i < frame.frames.length; i++)
          arguments.callee(frame.frames[i]);
      })(content);
      return result;
    },
  };


  // 前のタイマーを削除するために保存しておく
  let delayCallTimer = null;

  let migemized = {
    find: function find (str, backwards) {
      // 短時間に何回も検索をしないように遅延させる
      let f = function () MF.findFirst(str, backwards);
      if (delayCallTimer)
        clearTimeout(delayCallTimer);
      delayCallTimer = setTimeout(function () f(), 300);
    },

    findAgain: function findAgain (reverse) {
      MF.findAgain(reverse);
      if (!MF.storage.lastResult)
        liberator.echoerr('not found: ' + MF.lastSearchText);
    },

    searchSubmitted: function searchSubmitted (command, forcedBackward) {
      MF.submit();
      if (!MF.storage.lastResult)
        liberator.echoerr('not found: ' + MF.lastSearchText);
    },

    searchCanceled: function searchCanceled () {
      MF.cancel();
    },
  };


  // オリジナルの状態に戻せるように保存しておく
  {
    let original = {};

    for (let name in migemized)
      original[name] = liberator.search[name];

    function set (funcs) {
      for (let name in funcs)
        liberator.search[name] = funcs[name];
    }

    set(migemized);

    MF.install = function () set(migemized);
    MF.uninstall = function () set(original);
  }


  // 外から使えるように
  liberator.plugins.migemizedFind = MF;

}catch(e){liberator.log(e);}})();