xkcd-mode: use buffer_loaded_hook instead of buffer_dom_content_loaded_hook
[conkeror.git] / modules / minibuffer-read.js
blobbea8c31576a344337b735ecb040a40d00d0ef198
1 /**
2  * (C) Copyright 2007-2010 John J. Foerch
3  * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
4  *
5  * Use, modification, and distribution are subject to the terms specified in the
6  * COPYING file.
7 **/
9 in_module(null);
11 define_variable("default_minibuffer_auto_complete_delay", 150,
12     "Delay (in milliseconds) after the most recent key-stroke "+
13     "before auto-completing.");
15 define_variable("minibuffer_auto_complete_preferences", {});
17 define_variable("minibuffer_auto_complete_default", false,
18     "Boolean specifying whether to auto-complete by default. "+
19     "The user variable `minibuffer_auto_complete_preferences' "+
20     "overrides this.");
22 var minibuffer_history_data = {};
24 /* FIXME: These should possibly be saved to disk somewhere */
25 define_variable("minibuffer_history_max_items", 100,
26     "Maximum number of minibuffer history entries stored. Older "+
27     "history entries are truncated after this limit is reached.");
30 var atom_service = Cc["@mozilla.org/atom-service;1"].getService(Ci.nsIAtomService);
32 function completions_tree_view (minibuffer_state) {
33     this.minibuffer_state = minibuffer_state;
35 completions_tree_view.prototype = {
36     constructor: completions_tree_view,
37     QueryInterface: XPCOMUtils.generateQI([Ci.nsITreeView]),
38     get rowCount () {
39         var c = this.minibuffer_state.completions;
40         if (!c)
41             return 0;
42         return c.count;
43     },
44     getCellText: function (row,column) {
45         var c = this.minibuffer_state.completions;
46         if (row >= c.count)
47             return null;
48         if (column.index == 0)
49             return c.get_string(row);
50         if (c.get_description)
51             return c.get_description(row);
52         return "";
53     },
54     setTree: function (treebox) { this.treeBox = treebox; },
55     isContainer: function (row) { return false; },
56     isSeparator: function (row) { return false; },
57     isSorted: function () { return false; },
58     getLevel: function (row) { return 0; },
59     getImageSrc: function (row, col) {
60         var c = this.minibuffer_state.completions;
61         if (this.minibuffer_state.enable_icons &&
62             c.get_icon && col.index == 0)
63         {
64             return c.get_icon(row);
65         }
66         return null;
67     },
68     getRowProperties: function (row, props) {},
69     getCellProperties: function (row, col, props) {
70         if (col.index == 0)
71             props.AppendElement(atom_service.getAtom("completion-string"));
72         else
73             props.AppendElement(atom_service.getAtom("completion-description"));
74     },
75     getColumnProperties: function (colid, col, props) {}
79 /* The parameter `args' specifies the arguments.  In addition, the
80  * arguments for basic_minibuffer_state are also allowed.
81  *
82  * history:           [optional] specifies a string to identify the history list to use
83  *
84  * completer
85  *
86  * match_required
87  *
88  * default_completion  only used if match_required is set to true
89  *
90  * $valiator          [optional]
91  *          specifies a function
92  */
93 define_keywords("$keymap", "$history", "$validator",
94                 "$completer", "$match_required", "$default_completion",
95                 "$auto_complete", "$auto_complete_initial", "$auto_complete_conservative",
96                 "$auto_complete_delay", "$enable_icons",
97                 "$space_completes");
98 /* FIXME: support completing in another thread */
99 function text_entry_minibuffer_state (minibuffer, continuation) {
100     keywords(arguments, $keymap = minibuffer_keymap,
101              $enable_icons = false);
103     basic_minibuffer_state.call(this, minibuffer, forward_keywords(arguments));
105     this.continuation = continuation;
106     if (arguments.$history) {
107         this.history = minibuffer_history_data[arguments.$history] =
108             minibuffer_history_data[arguments.$history] || [];
109         this.history_index = -1;
110         this.saved_last_history_entry = null;
111     }
113     this.validator = arguments.$validator;
115     if (arguments.$completer != null) {
116         this.completer = arguments.$completer;
117         let auto = arguments.$auto_complete;
118         while (typeof(auto) == "string")
119             auto = minibuffer_auto_complete_preferences[auto];
120         if (auto == null)
121             auto = minibuffer_auto_complete_default;
122         this.auto_complete = auto;
123         this.auto_complete_initial = !!arguments.$auto_complete_initial;
124         this.auto_complete_conservative = !!arguments.$auto_complete_conservative;
125         let delay = arguments.$auto_complete_delay;
126         if (delay == null)
127             delay = default_minibuffer_auto_complete_delay;
128         this.auto_complete_delay = delay;
129         this.completions = null;
130         this.completions_valid = false;
131         this.space_completes = !!arguments.$space_completes;
132         if (this.space_completes)
133             this.keymaps.push(minibuffer_space_completion_keymap);
134         this.completions_timer_ID = null;
135         this.completions_display_element = null;
136         this.selected_completion_index = -1;
137         this.match_required  = !!arguments.$match_required;
138         this.match_required_default = this.match_required;
139         if (this.match_required)
140             this.default_completion = arguments.$default_completion;
141         this.enable_icons = arguments.$enable_icons;
142     }
144 text_entry_minibuffer_state.prototype = {
145     constructor: text_entry_minibuffer_state,
146     __proto__: basic_minibuffer_state.prototype,
147     load: function () {
148         basic_minibuffer_state.prototype.load.call(this);
149         var window = this.minibuffer.window;
150         if (this.completer) {
151             // Create completion display element if needed
152             if (!this.completion_element) {
153                 /* FIXME: maybe use the dom_generator */
154                 var tree = create_XUL(window, "tree");
155                 var s = this;
156                 tree.addEventListener("select", function () {
157                         s.selected_completion_index = s.completions_display_element.currentIndex;
158                         s.handle_completion_selected();
159                     }, true);
160                 tree.setAttribute("class", "completions");
162                 tree.setAttribute("rows", "8");
164                 tree.setAttribute("collapsed", "true");
166                 tree.setAttribute("hidecolumnpicker", "true");
167                 tree.setAttribute("hideheader", "true");
168                 if (this.enable_icons)
169                     tree.setAttribute("hasicons", "true");
171                 var treecols = create_XUL(window, "treecols");
172                 tree.appendChild(treecols);
173                 var treecol = create_XUL(window, "treecol");
174                 treecol.setAttribute("flex", "1");
175                 treecols.appendChild(treecol);
176                 treecol = create_XUL(window, "treecol");
177                 treecol.setAttribute("flex", "1");
178                 treecols.appendChild(treecol);
179                 tree.appendChild(create_XUL(window, "treechildren"));
181                 this.minibuffer.insert_before(tree);
182                 tree.view = new completions_tree_view(this);
183                 this.completions_display_element = tree;
185                 /* This is the initial loading of this minibuffer
186                  * state.  If this.complete_initial is true, generate
187                  * completions. */
188                 if (this.auto_complete_initial)
189                     this.handle_input();
190             }
191             this.update_completions_display();
192         }
193     },
195     unload: function () {
196         if (this.completions_display_element)
197             this.completions_display_element.setAttribute("collapsed", "true");
198         basic_minibuffer_state.prototype.unload.call(this);
199     },
201     destroy: function () {
202         if (this.completions != null && this.completions.destroy)
203             this.completions.destroy();
204         delete this.completions;
205         if (this.completions_cont)
206             this.completions_cont.throw(abort());
207         delete this.completions_cont;
209         var el = this.completions_display_element;
210         if (el) {
211             el.parentNode.removeChild(el);
212             this.completions_display_element = null;
213         }
214         if (this.continuation)
215             this.continuation.throw(abort());
216         basic_minibuffer_state.prototype.destroy.call(this);
217     },
219     handle_input: function () {
220         if (!this.completer) return;
222         this.completions_valid = false;
224         if (!this.auto_complete) return;
226         var s = this;
227         var window = this.minibuffer.window;
229         if (this.auto_complete_delay > 0) {
230             if (this.completions_timer_ID != null)
231                 window.clearTimeout(this.completions_timer_ID);
232             this.completions_timer_ID = window.setTimeout(
233                 function () {
234                     s.completions_timer_ID = null;
235                     s.update_completions(true /* auto */, true /* update completions display */);
236                 }, this.auto_complete_delay);
237             return;
238         }
239         s.update_completions(true /* auto */, true /* update completions display */);
240     },
242     update_completions_display: function () {
243         var m = this.minibuffer;
244         if (m.current_state == this) {
245             if (this.completions && this.completions.count > 0) {
246                 this.completions_display_element.view = this.completions_display_element.view;
247                 this.completions_display_element.setAttribute("collapsed", "false");
248                 this.completions_display_element.currentIndex = this.selected_completion_index;
249                 var max_display = this.completions_display_element.treeBoxObject.getPageLength();
250                 var mid_point = Math.floor(max_display / 2);
251                 if (this.completions.count - this.selected_completion_index <= mid_point)
252                     var pos = this.completions.count - max_display;
253                 else
254                     pos = Math.max(0, this.selected_completion_index - mid_point);
255                 this.completions_display_element.treeBoxObject.scrollToRow(pos);
256             } else {
257                 this.completions_display_element.setAttribute("collapsed", "true");
258             }
259         }
260     },
262     /* If auto is true, this update is due to auto completion, rather
263      * than specifically requested. */
264     update_completions: function (auto, update_display) {
265         var window = this.minibuffer.window;
266         if (this.completions_timer_ID != null) {
267             window.clearTimeout(this.completions_timer_ID);
268             this.completions_timer_ID = null;
269         }
271         let m = this.minibuffer;
273         if (this.completions_cont) {
274             this.completions_cont.throw(abort());
275             this.completions_cont = null;
276         }
278         let c = this.completer(m._input_text, m._selection_start,
279                                auto && this.auto_complete_conservative);
281         if (is_coroutine(c)) {
282             let s = this;
283             let already_done = false;
284             this.completions_cont = co_call(function () {
285                 var x;
286                 try {
287                     x = yield c;
288                 } catch (e) {
289                     handle_interactive_error(window, e);
290                 } finally {
291                     s.completions_cont = null;
292                     already_done = true;
293                 }
294                 s.update_completions_done(x, update_display);
295             }());
297             // In case the completer actually already finished
298             if (already_done)
299                 this.completions_cont = null;
300             return;
301         } else
302             this.update_completions_done(c, update_display);
303     },
305     update_completions_done: function (c, update_display) {
306         /* The completer should return undefined if completion was not
307          * attempted due to auto being true.  Otherwise, it can return
308          * null to indicate no completions. */
309         if (this.completions != null && this.completions.destroy)
310             this.completions.destroy();
312         this.completions = c;
313         this.completions_valid = true;
314         this.applied_common_prefix = false;
316         if (c && ("get_match_required" in c))
317             this.match_required = c.get_match_required();
318         if (this.match_required == null)
319             this.match_required = this.match_required_default;
321         let i = -1;
322         if (c && c.count > 0) {
323             if (this.match_required) {
324                 if (c.count == 1)
325                     i = 0;
326                 else if (c.default_completion != null)
327                     i = c.default_completion;
328                 else if (this.default_completion && this.completions.index_of)
329                     i = this.completions.index_of(this.default_completion);
330             }
331             this.selected_completion_index = i;
332         }
334         if (update_display)
335             this.update_completions_display();
336     },
338     select_completion: function (i) {
339         this.selected_completion_index = i;
340         this.completions_display_element.currentIndex = i;
341         if (i >= 0)
342             this.completions_display_element.treeBoxObject.ensureRowIsVisible(i);
343         this.handle_completion_selected();
344     },
346     handle_completion_selected: function () {
347         /**
348          * When a completion is selected, apply it to the input text
349          * if a match is not "required"; otherwise, the completion is
350          * only displayed.
351          */
352         var i = this.selected_completion_index;
353         var m = this.minibuffer;
354         var c = this.completions;
356         if (this.completions_valid && c && !this.match_required && i >= 0 && i < c.count)
357             m.set_input_state(c.get_input_state(i));
358     }
361 function minibuffer_complete (window, count) {
362     var m = window.minibuffer;
363     var s = m.current_state;
364     if (!(s instanceof text_entry_minibuffer_state))
365         throw new Error("Invalid minibuffer state");
366     if (!s.completer)
367         return;
368     var just_completed_manually = false;
369     if (!s.completions_valid || s.completions === undefined) {
370         if (s.completions_timer_ID == null)
371             just_completed_manually = true;
372         //XXX: may need to use ignore_input_events here
373         s.update_completions(false /* not auto */, true /* update completions display */);
375         // If the completer is a coroutine, nothing we can do here
376         if (!s.completions_valid)
377             return;
378     }
380     var c = s.completions;
382     if (!c || c.count == 0)
383         return;
385     var e = s.completions_display_element;
386     var new_index = -1;
388     let common_prefix;
390     if (count == 1 && !s.applied_common_prefix && (common_prefix = c.common_prefix_input_state)) {
391         //XXX: may need to use ignore_input_events here
392         m.set_input_state(common_prefix);
393         s.applied_common_prefix = true;
394     } else if (!just_completed_manually) {
395         if (e.currentIndex != -1) {
396             new_index = (e.currentIndex + count) % c.count;
397             if (new_index < 0)
398                 new_index += c.count;
399         } else {
400             new_index = (count - 1) % c.count;
401             if (new_index < 0)
402                 new_index += c.count;
403         }
404     }
406     if (new_index != -1) {
407        try {
408             m.ignore_input_events = true;
409             s.select_completion(new_index);
410         } finally {
411             m.ignore_input_events = false;
412         }
413     }
415 interactive("minibuffer-complete", null,
416     function (I) { minibuffer_complete(I.window, I.p); });
417 interactive("minibuffer-complete-previous", null,
418     function (I) { minibuffer_complete(I.window, -I.p); });
420 function exit_minibuffer (window) {
421     var m = window.minibuffer;
422     var s = m.current_state;
423     if (!(s instanceof text_entry_minibuffer_state))
424         throw new Error("Invalid minibuffer state");
426     var val = m._input_text;
428     if (s.validator != null && !s.validator(val, m))
429         return;
431     var match = null;
433     if (s.completer && s.match_required) {
434         if (!s.completions_valid || s.completions === undefined)
435             s.update_completions(false /* not conservative */, false /* don't update */);
437         let c = s.completions;
438         let i = s.selected_completion_index;
439         if (c != null && i >= 0 && i < c.count) {
440             if (c.get_value != null)
441                 match = c.get_value(i);
442             else
443                 match = c.get_string(i);
444         } else {
445             m.message("No match");
446             return;
447         }
448     }
450     if (s.history) {
451         s.history.push(val);
452         if (s.history.length > minibuffer_history_max_items)
453             s.history.splice(0, s.history.length - minibuffer_history_max_items);
454     }
455     var cont = s.continuation;
456     delete s.continuation;
457     m.pop_state();
458     if (cont) {
459         if (s.match_required)
460             cont(match);
461         else
462             cont(val);
463     }
465 interactive("exit-minibuffer", null,
466     function (I) { exit_minibuffer(I.window); });
468 function minibuffer_history_next (window, count) {
469     var m = window.minibuffer;
470     var s = m.current_state;
471     if (!(s instanceof text_entry_minibuffer_state))
472         throw new Error("Invalid minibuffer state");
473     if (!s.history || s.history.length == 0)
474         throw interactive_error("No history available.");
475     if (count == 0)
476         return;
477     var index = s.history_index;
478     if (count > 0 && index == -1)
479         throw interactive_error("End of history; no next item");
480     else if (count < 0 && index == 0)
481         throw interactive_error("Beginning of history; no preceding item");
482     if (index == -1) {
483         s.saved_last_history_entry = m._input_text;
484         index = s.history.length + count;
485     } else
486         index = index + count;
488     if (index < 0)
489         index = 0;
491     m._restore_normal_state();
492     if (index >= s.history.length) {
493         index = -1;
494         m._input_text = s.saved_last_history_entry;
495     } else {
496         m._input_text = s.history[index];
497     }
498     s.history_index = index;
499     m._set_selection();
500     s.handle_input();
502 interactive("minibuffer-history-next", null,
503     function (I) { minibuffer_history_next(I.window, I.p); });
504 interactive("minibuffer-history-previous", null,
505     function (I) { minibuffer_history_next(I.window, -I.p); });
507 // Define the asynchronous minibuffer.read function
508 minibuffer.prototype.read = function () {
509     var s = new text_entry_minibuffer_state(this, (yield CONTINUATION), forward_keywords(arguments));
510     this.push_state(s);
511     var result = yield SUSPEND;
512     yield co_return(result);
515 minibuffer.prototype.read_command = function () {
516     keywords(
517         arguments,
518         $prompt = "Command", $history = "command",
519         $completer = prefix_completer(
520             $completions = function (visitor) interactive_commands.for_each_value(visitor),
521             $get_string = function (x) x.name,
522             $get_description = function (x) x.shortdoc || "",
523             $get_value = function (x) x.name),
524         $match_required,
525         $space_completes);
526     var result = yield this.read(forward_keywords(arguments));
527     yield co_return(result);
530 minibuffer.prototype.read_user_variable = function () {
531     keywords(
532         arguments,
533         $prompt = "User variable", $history = "user_variable",
534         $completer = prefix_completer(
535             $completions = function (visitor) {
536                 for (var i in user_variables) visitor(i);
537             },
538             $get_string = function (x) x,
539             $get_description = function (x) user_variables[x].shortdoc || "",
540             $get_value = function (x) x),
541         $match_required,
542         $space_completes);
543     var result = yield this.read(forward_keywords(arguments));
544     yield co_return(result);
547 minibuffer.prototype.read_preference = function () {
548     keywords(arguments,
549              $prompt = "Preference:", $history = "preference",
550              $completer = prefix_completer(
551                  $completions = preferences.getBranch(null).getChildList("", {}),
552                  $get_description = function (pref) {
553                      let default_value = get_default_pref(pref);
554                      let value = get_pref(pref);
555                      if (value == default_value)
556                          value = null;
557                      let type;
558                      switch (preferences.getBranch(null).getPrefType(pref)) {
559                      case Ci.nsIPrefBranch.PREF_STRING:
560                          type = "string";
561                          break;
562                      case Ci.nsIPrefBranch.PREF_INT:
563                          type = "int";
564                          break;
565                      case Ci.nsIPrefBranch.PREF_BOOL:
566                          type = "boolean";
567                          break;
568                      }
569                      let out = type + ":";
570                      if (value != null)
571                          out += " " + pretty_print_value(value);
572                      if (default_value != null)
573                          out += " (" + pretty_print_value(default_value) + ")";
574                      return out;
575                  }),
576              $match_required,
577              $space_completes);
578     var result = yield this.read(forward_keywords(arguments));
579     yield co_return(result);
582 provide("minibuffer-read");