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>
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
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 });
19 if (isArray(Iterator(this._localMarks).next()[1]))
20 this._localMarks.clear();
24 this._pendingJumps = [];
28 * @property {Array} Returns all marks, both local and URL, in a sorted
31 get all() iter(this._localMarks.get(this.localURI) || {},
33 ).sort((a, b) => String.localeCompare(a[0], b[0])),
35 get localURI() buffer.focusedFrame.document.documentURI.replace(/#.*/, ""),
37 Mark: function Mark(params = {}) {
38 let win = buffer.focusedFrame;
39 let doc = win.document;
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;
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.
59 * @param {string} name The mark name.
60 * @param {boolean} silent Whether to output error messages.
62 add: function (name, silent) {
63 let mark = this.Mark();
65 if (Marks.isURLMark(name)) {
66 mark.tab = util.weakReference(tabs.getTab());
67 this._urlMarks.set(name, mark);
68 var message = "mark.addURL";
70 else if (Marks.isLocalMark(name)) {
71 this._localMarks.get(mark.location, {})[name] = mark;
72 this._localMarks.changed();
73 message = "mark.addLocal";
77 dactyl.log(_(message, Marks.markToString(name, mark)), 5);
82 * Push the current buffer position onto the jump stack.
84 * @param {string} reason The reason for this scroll event. Multiple
85 * scroll events for the same reason are coalesced. @optional
87 push: function push(reason) {
88 let store = buffer.localStore;
89 let jump = store.jumps[store.jumpsIndex];
91 if (reason && jump && jump.reason == reason)
94 let mark = this.add("'");
95 if (jump && mark.equals(jump.mark))
99 store.jumps[++store.jumpsIndex] = { mark: mark, reason: reason };
100 store.jumps.length = store.jumpsIndex + 1;
102 if (store.jumps.length > this.maxJumps) {
103 store.jumps = store.jumps.slice(-this.maxJumps);
104 store.jumpsIndex = store.jumps.length - 1;
112 * Jump to the given offset in the jump stack.
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.
118 jump: function jump(offset) {
119 let store = buffer.localStore;
120 if (offset < 0 && store.jumpsIndex == store.jumps.length - 1)
123 return this.withSavedValues(["jumping"], function _jump() {
125 let idx = Math.constrain(store.jumpsIndex + offset, 0, store.jumps.length - 1);
126 let orig = store.jumpsIndex;
128 if (idx in store.jumps && !dactyl.trapErrors("_scrollTo", this, store.jumps[idx].mark))
129 store.jumpsIndex = idx;
130 return store.jumpsIndex - orig;
135 let store = buffer.localStore;
137 index: store.jumpsIndex,
138 locations: store.jumps.map(j => j.mark)
143 * Remove all marks matching *filter*. If *special* is given, removes all
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.
149 remove: function (filter, special) {
151 this._localMarks.remove(this.localURI);
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);
162 Iterator(local).next();
163 this._localMarks.changed();
166 this._localMarks.remove(this.localURI);
172 * Jumps to the named mark. See {@link #add}
174 * @param {string} char The mark to jump to.
176 jumpTo: function (char) {
177 if (Marks.isURLMark(char)) {
178 let mark = this._urlMarks.get(char);
179 dactyl.assert(mark, _("mark.unset", char));
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)
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);
197 this._pendingJumps.push(mark);
199 let sh = tab.linkedBrowser.sessionHistory;
200 let items = array(util.range(0, sh.count));
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();
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);
212 dactyl.open(mark.location);
216 this._pendingJumps.push(mark);
217 dactyl.open(mark.location, dactyl.NEW_TAB);
220 else if (Marks.isLocalMark(char)) {
221 let mark = (this._localMarks.get(this.localURI) || {})[char];
222 dactyl.assert(mark, _("mark.unset", char));
224 dactyl.log(_("mark.jumpingToLocal", Marks.markToString(char, mark)), 5);
225 this._scrollTo(mark);
228 dactyl.echoerr(_("mark.invalid"));
232 _scrollTo: function _scrollTo(mark) {
234 var node = buffer.findScrollable(0, (mark.offset || mark.position).x);
236 for (node in DOM.XPath(mark.path, buffer.focusedFrame.document))
240 if (node instanceof Element)
241 DOM(node).scrollIntoView();
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);
250 * List all marks matching *filter*.
252 * @param {string} filter List of marks to show, e.g. "ab A-I".
254 list: function (filter) {
255 let marks = this.all;
257 dactyl.assert(marks.length > 0, _("mark.none"));
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()));
265 commandline.commandOutput(
267 ["Mark", "HPos", "VPos", "File"],
268 ["", "text-align: right", "text-align: right", "color: green"],
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) + "%",
275 for ([, [name, mark]] in Iterator(marks)))));
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);
289 markToString: function markToString(name, mark) {
290 let tab = mark.tab && mark.tab.get();
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(", ");
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(", ");
306 isLocalMark: bind("test", /^[a-z`']$/),
308 isURLMark: bind("test", /^[A-Z]$/)
310 events: function () {
311 let appContent = document.getElementById("appcontent");
313 events.listen(appContent, "load", marks.closure._onPageLoad, true);
315 mappings: function () {
316 var myModes = config.browserModes;
318 mappings.add(myModes,
319 ["m"], "Set mark at the cursor position",
321 dactyl.assert(/^[a-zA-Z]$/.test(arg), _("mark.invalid"));
326 mappings.add(myModes,
327 ["'", "`"], "Jump to the mark in the current buffer",
328 function ({ arg }) { marks.jumpTo(arg); },
332 commands: function initCommands() {
333 commands.add(["delm[arks]"],
334 "Delete the specified marks",
336 let special = args.bang;
337 let arg = args[0] || "";
339 // assert(special ^ args)
340 dactyl.assert( special || arg, _("error.argumentRequired"));
341 dactyl.assert(!special || !arg, _("error.invalidArgument"));
343 marks.remove(arg, special);
347 completer: function (context) completion.mark(context),
351 commands.add(["ma[rk]"],
352 "Mark current location within the web page",
354 let mark = args[0] || "";
355 dactyl.assert(mark.length <= 1, _("error.trailingCharacters"));
356 dactyl.assert(/[a-zA-Z]/.test(mark), _("mark.invalid"));
362 commands.add(["marks"],
363 "Show the specified marks",
365 marks.list(args[0] || "");
367 completer: function (context) completion.mark(context),
372 completion: function initCompletion() {
373 completion.mark = function mark(context) {
374 function percent(i) Math.round(i * 100);
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;
383 sanitizer: function initSanitizer() {
384 sanitizer.addItem("marks", {
385 description: "Local and URL marks",
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)));
392 for (let [url, local] in marks._localMarks)
393 if (matchhost(url)) {
394 for (let key in match(local))
396 if (!Object.keys(local).length)
397 marks._localMarks.remove(url);
399 marks._localMarks.changed();
401 for (let key in match(marks._urlMarks))
402 marks._urlMarks.remove(key);
408 // vim: set fdm=marker sw=4 sts=4 ts=8 et: