]> git.donarmstrong.com Git - dactyl.git/blob - common/content/marks.js
Import r6976 from upstream hg supporting Firefox up to 25.*
[dactyl.git] / common / content / marks.js
1 // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
2 // Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
3 // Copyright (c) 2008-2013 Kris Maglione <maglione.k@gmail.com>
4 //
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
7 "use strict";
8
9 /**
10  * @scope modules
11  * @instance marks
12  */
13 var Marks = Module("marks", {
14     init: function init() {
15         this._localMarks = storage.newMap("local-marks", { privateData: true, replacer: Storage.Replacer.skipXpcom, store: true });
16         this._urlMarks = storage.newMap("url-marks", { privateData: true, replacer: Storage.Replacer.skipXpcom, store: true });
17
18         try {
19             if (isArray(Iterator(this._localMarks).next()[1]))
20                 this._localMarks.clear();
21         }
22         catch (e) {}
23
24         this._pendingJumps = [];
25     },
26
27     /**
28      * @property {Array} Returns all marks, both local and URL, in a sorted
29      *     array.
30      */
31     get all() iter(this._localMarks.get(this.localURI) || {},
32                    this._urlMarks
33                   ).sort((a, b) => String.localeCompare(a[0], b[0])),
34
35     get localURI() buffer.focusedFrame.document.documentURI.replace(/#.*/, ""),
36
37     Mark: function Mark(params = {}) {
38         let win = buffer.focusedFrame;
39         let doc = win.document;
40
41         params.location = doc.documentURI.replace(/#.*/, ""),
42         params.offset = buffer.scrollPosition;
43         params.path = DOM(buffer.findScrollable(0, false)).xpath;
44         params.timestamp = Date.now() * 1000;
45         params.equals = function (m) this.location == m.location
46                                   && this.offset.x == m.offset.x
47                                   && this.offset.y == m.offset.y
48                                   && this.path == m.path;
49         return params;
50     },
51
52     /**
53      * Add a named mark for the current buffer, at its current position.
54      * If mark matches [A-Z], it's considered a URL mark, and will jump to
55      * the same position at the same URL no matter what buffer it's
56      * selected from. If it matches [a-z], it's a local mark, and can
57      * only be recalled from a buffer with a matching URL.
58      *
59      * @param {string} name The mark name.
60      * @param {boolean} silent Whether to output error messages.
61      */
62     add: function (name, silent) {
63         let mark = this.Mark();
64
65         if (Marks.isURLMark(name)) {
66             mark.tab = util.weakReference(tabs.getTab());
67             this._urlMarks.set(name, mark);
68             var message = "mark.addURL";
69         }
70         else if (Marks.isLocalMark(name)) {
71             this._localMarks.get(mark.location, {})[name] = mark;
72             this._localMarks.changed();
73             message = "mark.addLocal";
74         }
75
76         if (!silent)
77             dactyl.log(_(message, Marks.markToString(name, mark)), 5);
78         return mark;
79     },
80
81     /**
82      * Push the current buffer position onto the jump stack.
83      *
84      * @param {string} reason The reason for this scroll event. Multiple
85      *      scroll events for the same reason are coalesced. @optional
86      */
87     push: function push(reason) {
88         let store = buffer.localStore;
89         let jump  = store.jumps[store.jumpsIndex];
90
91         if (reason && jump && jump.reason == reason)
92             return;
93
94         let mark = this.add("'");
95         if (jump && mark.equals(jump.mark))
96             return;
97
98         if (!this.jumping) {
99             store.jumps[++store.jumpsIndex] = { mark: mark, reason: reason };
100             store.jumps.length = store.jumpsIndex + 1;
101
102             if (store.jumps.length > this.maxJumps) {
103                 store.jumps = store.jumps.slice(-this.maxJumps);
104                 store.jumpsIndex = store.jumps.length - 1;
105             }
106         }
107     },
108
109     maxJumps: 200,
110
111     /**
112      * Jump to the given offset in the jump stack.
113      *
114      * @param {number} offset The offset from the current position in
115      *      the jump stack to jump to.
116      * @returns {number} The actual change in offset.
117      */
118     jump: function jump(offset) {
119         let store = buffer.localStore;
120         if (offset < 0 && store.jumpsIndex == store.jumps.length - 1)
121             this.push();
122
123         return this.withSavedValues(["jumping"], function _jump() {
124             this.jumping = true;
125             let idx = Math.constrain(store.jumpsIndex + offset, 0, store.jumps.length - 1);
126             let orig = store.jumpsIndex;
127
128             if (idx in store.jumps && !dactyl.trapErrors("_scrollTo", this, store.jumps[idx].mark))
129                 store.jumpsIndex = idx;
130             return store.jumpsIndex - orig;
131         });
132     },
133
134     get jumps() {
135         let store = buffer.localStore;
136         return {
137             index: store.jumpsIndex,
138             locations: store.jumps.map(j => j.mark)
139         };
140     },
141
142     /**
143      * Remove all marks matching *filter*. If *special* is given, removes all
144      * local marks.
145      *
146      * @param {string} filter The list of marks to delete, e.g. "aA b C-I"
147      * @param {boolean} special Whether to delete all local marks.
148      */
149     remove: function (filter, special) {
150         if (special)
151             this._localMarks.remove(this.localURI);
152         else {
153             let pattern = util.charListToRegexp(filter, "a-zA-Z");
154             let local = this._localMarks.get(this.localURI);
155             this.all.forEach(function ([k, ]) {
156                 if (pattern.test(k)) {
157                     local && delete local[k];
158                     marks._urlMarks.remove(k);
159                 }
160             });
161             try {
162                 Iterator(local).next();
163                 this._localMarks.changed();
164             }
165             catch (e) {
166                 this._localMarks.remove(this.localURI);
167             }
168         }
169     },
170
171     /**
172      * Jumps to the named mark. See {@link #add}
173      *
174      * @param {string} char The mark to jump to.
175      */
176     jumpTo: function (char) {
177         if (Marks.isURLMark(char)) {
178             let mark = this._urlMarks.get(char);
179             dactyl.assert(mark, _("mark.unset", char));
180
181             let tab = mark.tab && mark.tab.get();
182             if (!tab || !tab.linkedBrowser || tabs.allTabs.indexOf(tab) == -1)
183                 for ([, tab] in iter(tabs.visibleTabs, tabs.allTabs)) {
184                     if (tab.linkedBrowser.contentDocument.documentURI.replace(/#.*/, "") === mark.location)
185                         break;
186                     tab = null;
187                 }
188
189             if (tab) {
190                 tabs.select(tab);
191                 let doc = tab.linkedBrowser.contentDocument;
192                 if (doc.documentURI.replace(/#.*/, "") == mark.location) {
193                     dactyl.log(_("mark.jumpingToURL", Marks.markToString(char, mark)), 5);
194                     this._scrollTo(mark);
195                 }
196                 else {
197                     this._pendingJumps.push(mark);
198
199                     let sh = tab.linkedBrowser.sessionHistory;
200                     let items = array(util.range(0, sh.count));
201
202                     let a = items.slice(0, sh.index).reverse();
203                     let b = items.slice(sh.index);
204                     a.length = b.length = Math.max(a.length, b.length);
205                     items = array(a).zip(b).flatten().compact();
206
207                     for (let i in items.iterValues()) {
208                         let entry = sh.getEntryAtIndex(i, false);
209                         if (entry.URI.spec.replace(/#.*/, "") == mark.location)
210                             return void tab.linkedBrowser.webNavigation.gotoIndex(i);
211                     }
212                     dactyl.open(mark.location);
213                 }
214             }
215             else {
216                 this._pendingJumps.push(mark);
217                 dactyl.open(mark.location, dactyl.NEW_TAB);
218             }
219         }
220         else if (Marks.isLocalMark(char)) {
221             let mark = (this._localMarks.get(this.localURI) || {})[char];
222             dactyl.assert(mark, _("mark.unset", char));
223
224             dactyl.log(_("mark.jumpingToLocal", Marks.markToString(char, mark)), 5);
225             this._scrollTo(mark);
226         }
227         else
228             dactyl.echoerr(_("mark.invalid"));
229
230     },
231
232     _scrollTo: function _scrollTo(mark) {
233         if (!mark.path)
234             var node = buffer.findScrollable(0, (mark.offset || mark.position).x);
235         else
236             for (node in DOM.XPath(mark.path, buffer.focusedFrame.document))
237                 break;
238
239         util.assert(node);
240         if (node instanceof Element)
241             DOM(node).scrollIntoView();
242
243         if (mark.offset)
244             Buffer.scrollToPosition(node, mark.offset.x, mark.offset.y);
245         else if (mark.position)
246             Buffer.scrollToPercent(node, mark.position.x * 100, mark.position.y * 100);
247     },
248
249     /**
250      * List all marks matching *filter*.
251      *
252      * @param {string} filter List of marks to show, e.g. "ab A-I".
253      */
254     list: function (filter) {
255         let marks = this.all;
256
257         dactyl.assert(marks.length > 0, _("mark.none"));
258
259         if (filter.length > 0) {
260             let pattern = util.charListToRegexp(filter, "a-zA-Z");
261             marks = marks.filter(([k]) => (pattern.test(k)));
262             dactyl.assert(marks.length > 0, _("mark.noMatching", filter.quote()));
263         }
264
265         commandline.commandOutput(
266             template.tabular(
267                 ["Mark",   "HPos",              "VPos",              "File"],
268                 ["",       "text-align: right", "text-align: right", "color: green"],
269                 ([name,
270                   mark.offset ? Math.round(mark.offset.x)
271                               : Math.round(mark.position.x * 100) + "%",
272                   mark.offset ? Math.round(mark.offset.y)
273                               : Math.round(mark.position.y * 100) + "%",
274                   mark.location]
275                   for ([, [name, mark]] in Iterator(marks)))));
276     },
277
278     _onPageLoad: function _onPageLoad(event) {
279         let win = event.originalTarget.defaultView;
280         for (let [i, mark] in Iterator(this._pendingJumps)) {
281             if (win && win.location.href == mark.location) {
282                 this._scrollTo(mark);
283                 this._pendingJumps.splice(i, 1);
284                 return;
285             }
286         }
287     },
288 }, {
289     markToString: function markToString(name, mark) {
290         let tab = mark.tab && mark.tab.get();
291         if (mark.offset)
292             return [name, mark.location,
293                     "(" + Math.round(mark.offset.x * 100),
294                           Math.round(mark.offset.y * 100) + ")",
295                     (tab && "tab: " + tabs.index(tab))
296             ].filter(util.identity).join(", ");
297
298         if (mark.position)
299             return [name, mark.location,
300                     "(" + Math.round(mark.position.x * 100) + "%",
301                           Math.round(mark.position.y * 100) + "%)",
302                     (tab && "tab: " + tabs.index(tab))
303             ].filter(util.identity).join(", ");
304     },
305
306     isLocalMark: bind("test", /^[a-z`']$/),
307
308     isURLMark: bind("test", /^[A-Z]$/)
309 }, {
310     events: function () {
311         let appContent = document.getElementById("appcontent");
312         if (appContent)
313             events.listen(appContent, "load", marks.closure._onPageLoad, true);
314     },
315     mappings: function () {
316         var myModes = config.browserModes;
317
318         mappings.add(myModes,
319             ["m"], "Set mark at the cursor position",
320             function ({ arg }) {
321                 dactyl.assert(/^[a-zA-Z]$/.test(arg), _("mark.invalid"));
322                 marks.add(arg);
323             },
324             { arg: true });
325
326         mappings.add(myModes,
327             ["'", "`"], "Jump to the mark in the current buffer",
328             function ({ arg }) { marks.jumpTo(arg); },
329             { arg: true });
330     },
331
332     commands: function initCommands() {
333         commands.add(["delm[arks]"],
334             "Delete the specified marks",
335             function (args) {
336                 let special = args.bang;
337                 let arg = args[0] || "";
338
339                 // assert(special ^ args)
340                 dactyl.assert( special ||  arg, _("error.argumentRequired"));
341                 dactyl.assert(!special || !arg, _("error.invalidArgument"));
342
343                 marks.remove(arg, special);
344             },
345             {
346                 bang: true,
347                 completer: function (context) completion.mark(context),
348                 literal: 0
349             });
350
351         commands.add(["ma[rk]"],
352             "Mark current location within the web page",
353             function (args) {
354                 let mark = args[0] || "";
355                 dactyl.assert(mark.length <= 1, _("error.trailingCharacters"));
356                 dactyl.assert(/[a-zA-Z]/.test(mark), _("mark.invalid"));
357
358                 marks.add(mark);
359             },
360             { argCount: "1" });
361
362         commands.add(["marks"],
363             "Show the specified marks",
364             function (args) {
365                 marks.list(args[0] || "");
366             }, {
367                 completer: function (context) completion.mark(context),
368                 literal: 0
369             });
370     },
371
372     completion: function initCompletion() {
373         completion.mark = function mark(context) {
374             function percent(i) Math.round(i * 100);
375
376             context.title = ["Mark", "HPos VPos File"];
377             context.keys.description = ([, m]) => (m.offset ? Math.round(m.offset.x) + " " + Math.round(m.offset.y)
378                                                             : percent(m.position.x) + "% " + percent(m.position.y) + "%"
379                                                   ) + " " + m.location;
380             context.completions = marks.all;
381         };
382     },
383     sanitizer: function initSanitizer() {
384         sanitizer.addItem("marks", {
385             description: "Local and URL marks",
386             persistent: true,
387             contains: ["history"],
388             action: function (timespan, host) {
389                 function matchhost(url) !host || util.isDomainURL(url, host);
390                 function match(marks) (k for ([k, v] in Iterator(marks)) if (timespan.contains(v.timestamp) && matchhost(v.location)));
391
392                 for (let [url, local] in marks._localMarks)
393                     if (matchhost(url)) {
394                         for (let key in match(local))
395                             delete local[key];
396                         if (!Object.keys(local).length)
397                             marks._localMarks.remove(url);
398                     }
399                 marks._localMarks.changed();
400
401                 for (let key in match(marks._urlMarks))
402                     marks._urlMarks.remove(key);
403             }
404         });
405     }
406 });
407
408 // vim: set fdm=marker sw=4 sts=4 ts=8 et: