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-2012 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(function (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 = params || {};
43 params.location = doc.documentURI.replace(/#.*/, ""),
44 params.offset = buffer.scrollPosition;
45 params.path = DOM(buffer.findScrollable(0, false)).xpath;
46 params.timestamp = Date.now() * 1000;
47 params.equals = function (m) this.location == m.location
48 && this.offset.x == m.offset.x
49 && this.offset.y == m.offset.y
50 && this.path == m.path;
55 * Add a named mark for the current buffer, at its current position.
56 * If mark matches [A-Z], it's considered a URL mark, and will jump to
57 * the same position at the same URL no matter what buffer it's
58 * selected from. If it matches [a-z], it's a local mark, and can
59 * only be recalled from a buffer with a matching URL.
61 * @param {string} name The mark name.
62 * @param {boolean} silent Whether to output error messages.
64 add: function (name, silent) {
65 let mark = this.Mark();
67 if (Marks.isURLMark(name)) {
68 mark.tab = util.weakReference(tabs.getTab());
69 this._urlMarks.set(name, mark);
70 var message = "mark.addURL";
72 else if (Marks.isLocalMark(name)) {
73 this._localMarks.get(mark.location, {})[name] = mark;
74 this._localMarks.changed();
75 message = "mark.addLocal";
79 dactyl.log(_(message, Marks.markToString(name, mark)), 5);
84 * Push the current buffer position onto the jump stack.
86 * @param {string} reason The reason for this scroll event. Multiple
87 * scroll events for the same reason are coalesced. @optional
89 push: function push(reason) {
90 let store = buffer.localStore;
91 let jump = store.jumps[store.jumpsIndex];
93 if (reason && jump && jump.reason == reason)
96 let mark = this.add("'");
97 if (jump && mark.equals(jump.mark))
101 store.jumps[++store.jumpsIndex] = { mark: mark, reason: reason };
102 store.jumps.length = store.jumpsIndex + 1;
104 if (store.jumps.length > this.maxJumps) {
105 store.jumps = store.jumps.slice(-this.maxJumps);
106 store.jumpsIndex = store.jumps.length - 1;
114 * Jump to the given offset in the jump stack.
116 * @param {number} offset The offset from the current position in
117 * the jump stack to jump to.
118 * @returns {number} The actual change in offset.
120 jump: function jump(offset) {
121 let store = buffer.localStore;
122 if (offset < 0 && store.jumpsIndex == store.jumps.length - 1)
125 return this.withSavedValues(["jumping"], function _jump() {
127 let idx = Math.constrain(store.jumpsIndex + offset, 0, store.jumps.length - 1);
128 let orig = store.jumpsIndex;
130 if (idx in store.jumps && !dactyl.trapErrors("_scrollTo", this, store.jumps[idx].mark))
131 store.jumpsIndex = idx;
132 return store.jumpsIndex - orig;
137 let store = buffer.localStore;
139 index: store.jumpsIndex,
140 locations: store.jumps.map(function (j) j.mark)
145 * Remove all marks matching *filter*. If *special* is given, removes all
148 * @param {string} filter The list of marks to delete, e.g. "aA b C-I"
149 * @param {boolean} special Whether to delete all local marks.
151 remove: function (filter, special) {
153 this._localMarks.remove(this.localURI);
155 let pattern = util.charListToRegexp(filter, "a-zA-Z");
156 let local = this._localMarks.get(this.localURI);
157 this.all.forEach(function ([k, ]) {
158 if (pattern.test(k)) {
159 local && delete local[k];
160 marks._urlMarks.remove(k);
164 Iterator(local).next();
165 this._localMarks.changed();
168 this._localMarks.remove(this.localURI);
174 * Jumps to the named mark. See {@link #add}
176 * @param {string} char The mark to jump to.
178 jumpTo: function (char) {
179 if (Marks.isURLMark(char)) {
180 let mark = this._urlMarks.get(char);
181 dactyl.assert(mark, _("mark.unset", char));
183 let tab = mark.tab && mark.tab.get();
184 if (!tab || !tab.linkedBrowser || tabs.allTabs.indexOf(tab) == -1)
185 for ([, tab] in iter(tabs.visibleTabs, tabs.allTabs)) {
186 if (tab.linkedBrowser.contentDocument.documentURI.replace(/#.*/, "") === mark.location)
193 let doc = tab.linkedBrowser.contentDocument;
194 if (doc.documentURI.replace(/#.*/, "") == mark.location) {
195 dactyl.log(_("mark.jumpingToURL", Marks.markToString(char, mark)), 5);
196 this._scrollTo(mark);
199 this._pendingJumps.push(mark);
201 let sh = tab.linkedBrowser.sessionHistory;
202 let items = array(util.range(0, sh.count));
204 let a = items.slice(0, sh.index).reverse();
205 let b = items.slice(sh.index);
206 a.length = b.length = Math.max(a.length, b.length);
207 items = array(a).zip(b).flatten().compact();
209 for (let i in items.iterValues()) {
210 let entry = sh.getEntryAtIndex(i, false);
211 if (entry.URI.spec.replace(/#.*/, "") == mark.location)
212 return void tab.linkedBrowser.webNavigation.gotoIndex(i);
214 dactyl.open(mark.location);
218 this._pendingJumps.push(mark);
219 dactyl.open(mark.location, dactyl.NEW_TAB);
222 else if (Marks.isLocalMark(char)) {
223 let mark = (this._localMarks.get(this.localURI) || {})[char];
224 dactyl.assert(mark, _("mark.unset", char));
226 dactyl.log(_("mark.jumpingToLocal", Marks.markToString(char, mark)), 5);
227 this._scrollTo(mark);
230 dactyl.echoerr(_("mark.invalid"));
234 _scrollTo: function _scrollTo(mark) {
236 var node = buffer.findScrollable(0, (mark.offset || mark.position).x)
238 for (node in DOM.XPath(mark.path, buffer.focusedFrame.document))
242 if (node instanceof Element)
243 DOM(node).scrollIntoView();
246 Buffer.scrollToPosition(node, mark.offset.x, mark.offset.y);
247 else if (mark.position)
248 Buffer.scrollToPercent(node, mark.position.x * 100, mark.position.y * 100);
252 * List all marks matching *filter*.
254 * @param {string} filter List of marks to show, e.g. "ab A-I".
256 list: function (filter) {
257 let marks = this.all;
259 dactyl.assert(marks.length > 0, _("mark.none"));
261 if (filter.length > 0) {
262 let pattern = util.charListToRegexp(filter, "a-zA-Z");
263 marks = marks.filter(function ([k, ]) pattern.test(k));
264 dactyl.assert(marks.length > 0, _("mark.noMatching", filter.quote()));
267 commandline.commandOutput(
269 ["Mark", "HPos", "VPos", "File"],
270 ["", "text-align: right", "text-align: right", "color: green"],
272 mark.offset ? Math.round(mark.offset.x)
273 : Math.round(mark.position.x * 100) + "%",
274 mark.offset ? Math.round(mark.offset.y)
275 : Math.round(mark.position.y * 100) + "%",
277 for ([, [name, mark]] in Iterator(marks)))));
280 _onPageLoad: function _onPageLoad(event) {
281 let win = event.originalTarget.defaultView;
282 for (let [i, mark] in Iterator(this._pendingJumps)) {
283 if (win && win.location.href == mark.location) {
284 this._scrollTo(mark);
285 this._pendingJumps.splice(i, 1);
291 markToString: function markToString(name, mark) {
292 let tab = mark.tab && mark.tab.get();
294 return [name, mark.location,
295 "(" + Math.round(mark.offset.x * 100),
296 Math.round(mark.offset.y * 100) + ")",
297 (tab && "tab: " + tabs.index(tab))
298 ].filter(util.identity).join(", ");
301 return [name, mark.location,
302 "(" + Math.round(mark.position.x * 100) + "%",
303 Math.round(mark.position.y * 100) + "%)",
304 (tab && "tab: " + tabs.index(tab))
305 ].filter(util.identity).join(", ");
309 isLocalMark: bind("test", /^[a-z`']$/),
311 isURLMark: bind("test", /^[A-Z]$/)
313 events: function () {
314 let appContent = document.getElementById("appcontent");
316 events.listen(appContent, "load", marks.closure._onPageLoad, true);
318 mappings: function () {
319 var myModes = config.browserModes;
321 mappings.add(myModes,
322 ["m"], "Set mark at the cursor position",
324 dactyl.assert(/^[a-zA-Z]$/.test(arg), _("mark.invalid"));
329 mappings.add(myModes,
330 ["'", "`"], "Jump to the mark in the current buffer",
331 function ({ arg }) { marks.jumpTo(arg); },
335 commands: function initCommands() {
336 commands.add(["delm[arks]"],
337 "Delete the specified marks",
339 let special = args.bang;
340 let arg = args[0] || "";
342 // assert(special ^ args)
343 dactyl.assert( special || arg, _("error.argumentRequired"));
344 dactyl.assert(!special || !arg, _("error.invalidArgument"));
346 marks.remove(arg, special);
350 completer: function (context) completion.mark(context),
354 commands.add(["ma[rk]"],
355 "Mark current location within the web page",
357 let mark = args[0] || "";
358 dactyl.assert(mark.length <= 1, _("error.trailingCharacters"));
359 dactyl.assert(/[a-zA-Z]/.test(mark), _("mark.invalid"));
365 commands.add(["marks"],
366 "Show the specified marks",
368 marks.list(args[0] || "");
370 completer: function (context) completion.mark(context),
375 completion: function initCompletion() {
376 completion.mark = function mark(context) {
377 function percent(i) Math.round(i * 100);
379 context.title = ["Mark", "HPos VPos File"];
380 context.keys.description = function ([, m]) (m.offset ? Math.round(m.offset.x) + " " + Math.round(m.offset.y)
381 : percent(m.position.x) + "% " + percent(m.position.y) + "%"
382 ) + " " + m.location;
383 context.completions = marks.all;
386 sanitizer: function initSanitizer() {
387 sanitizer.addItem("marks", {
388 description: "Local and URL marks",
390 contains: ["history"],
391 action: function (timespan, host) {
392 function matchhost(url) !host || util.isDomainURL(url, host);
393 function match(marks) (k for ([k, v] in Iterator(marks)) if (timespan.contains(v.timestamp) && matchhost(v.location)));
395 for (let [url, local] in marks._localMarks)
396 if (matchhost(url)) {
397 for (let key in match(local))
399 if (!Object.keys(local).length)
400 marks._localMarks.remove(url);
402 marks._localMarks.changed();
404 for (let key in match(marks._urlMarks))
405 marks._urlMarks.remove(key);
411 // vim: set fdm=marker sw=4 ts=4 et: