minibuffer_history_data: use js object instead of string_hashmap
[conkeror.git] / modules / minibuffer-read.js
blobcea0acfbe00417d574293ec5891d0363bd63b017
1 /**
2  * (C) Copyright 2007-2009 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 /* The parameter `args' specifies the arguments.  In addition, the
31  * arguments for basic_minibuffer_state are also allowed.
32  *
33  * history:           [optional] specifies a string to identify the history list to use
34  *
35  * completer
36  *
37  * match_required
38  *
39  * default_completion  only used if match_required is set to true
40  *
41  * $valiator          [optional]
42  *          specifies a function
43  */
44 define_keywords("$keymap", "$history", "$validator",
45                 "$completer", "$match_required", "$default_completion",
46                 "$auto_complete", "$auto_complete_initial", "$auto_complete_conservative",
47                 "$auto_complete_delay",
48                 "$space_completes");
49 /* FIXME: support completing in another thread */
50 function text_entry_minibuffer_state (window, continuation) {
51     keywords(arguments, $keymap = minibuffer_keymap);
53     basic_minibuffer_state.call(this, window, forward_keywords(arguments));
55     this.continuation = continuation;
56     if (arguments.$history) {
57         this.history = minibuffer_history_data[arguments.$history] =
58             minibuffer_history_data[arguments.$history] || [];
59         this.history_index = -1;
60         this.saved_last_history_entry = null;
61     }
63     this.validator = arguments.$validator;
65     if (arguments.$completer != null) {
66         this.completer = arguments.$completer;
67         let auto = arguments.$auto_complete;
68         while (typeof(auto) == "string")
69             auto = minibuffer_auto_complete_preferences[auto];
70         if (auto == null)
71             auto = minibuffer_auto_complete_default;
72         this.auto_complete = auto;
73         this.auto_complete_initial = !!arguments.$auto_complete_initial;
74         this.auto_complete_conservative = !!arguments.$auto_complete_conservative;
75         let delay = arguments.$auto_complete_delay;
76         if (delay == null)
77             delay = default_minibuffer_auto_complete_delay;
78         this.auto_complete_delay = delay;
79         this.completions = null;
80         this.completions_valid = false;
81         this.space_completes = !!arguments.$space_completes;
82         this.completions_timer_ID = null;
83         this.completions_display_element = null;
84         this.selected_completion_index = -1;
85         this.match_required  = !!arguments.$match_required;
86         this.match_required_default = this.match_required;
87         if (this.match_required)
88             this.default_completion = arguments.$default_completion;
89     }
92 function completions_tree_view (minibuffer_state) {
93     this.minibuffer_state = minibuffer_state;
96 var atom_service = Cc["@mozilla.org/atom-service;1"].getService(Ci.nsIAtomService);
98 completions_tree_view.prototype = {
99     get rowCount () {
100         var c = this.minibuffer_state.completions;
101         if (!c)
102             return 0;
103         return c.count;
104     },
105     getCellText: function (row,column) {
106         var c = this.minibuffer_state.completions;
107         if (row >= c.count)
108             return null;
109         if (column.index == 0)
110             return c.get_string(row);
111         if (c.get_description)
112             return c.get_description(row);
113         return "";
114     },
115     setTree: function (treebox) { this.treebox = treebox; },
116     isContainer: function (row) { return false; },
117     isSeparator: function (row) { return false; },
118     isSorted: function () { return false; },
119     getLevel: function (row) { return 0; },
120     getImageSrc: function (row, col) { return null; },
121     getRowProperties: function (row, props) {},
122     getCellProperties: function (row, col, props) {
123         if (col.index == 0)
124             props.AppendElement(atom_service.getAtom("completion-string"));
125         else
126             props.AppendElement(atom_service.getAtom("completion-description"));
127     },
128     getColumnProperties: function (colid, col, props) {}
131 // inherit from basic_minibuffer_state
132 text_entry_minibuffer_state.prototype = {
133     __proto__: basic_minibuffer_state.prototype,
134     load: function (window) {
135         basic_minibuffer_state.prototype.load.call(this, window);
136         this.window = window;
137         if (this.completer) {
138             // Create completion display element if needed
139             if (!this.completion_element) {
140                 /* FIXME: maybe use the dom_generator */
141                 var tree = create_XUL(window, "tree");
142                 var s = this;
143                 tree.addEventListener("select", function () {
144                         s.selected_completion_index = s.completions_display_element.currentIndex;
145                         s.handle_completion_selected();
146                     }, true);
147                 tree.setAttribute("class", "completions");
149                 tree.setAttribute("rows", "8");
151                 tree.setAttribute("collapsed", "true");
153                 tree.setAttribute("hidecolumnpicker", "true");
154                 tree.setAttribute("hideheader", "true");
156                 var treecols = create_XUL(window, "treecols");
157                 tree.appendChild(treecols);
158                 var treecol = create_XUL(window, "treecol");
159                 treecol.setAttribute("flex", "1");
160                 treecols.appendChild(treecol);
161                 treecol = create_XUL(window, "treecol");
162                 treecol.setAttribute("flex", "1");
163                 treecols.appendChild(treecol);
164                 tree.appendChild(create_XUL(window, "treechildren"));
166                 window.minibuffer.insert_before(tree);
167                 tree.view = new completions_tree_view(this);
168                 this.completions_display_element = tree;
170                 /* This is the initial loading of this minibuffer
171                  * state.  If this.complete_initial is true, generate
172                  * completions. */
173                 if (this.auto_complete_initial)
174                     this.handle_input();
175             }
176             this.update_completions_display();
177         }
178     },
180     unload: function (window) {
181         if (this.completions_display_element)
182             this.completions_display_element.setAttribute("collapsed", "true");
183         basic_minibuffer_state.prototype.unload.call(this, window);
184     },
186     destroy: function (window) {
187         if (this.completions != null && this.completions.destroy)
188             this.completions.destroy();
189         delete this.completions;
190         if (this.completions_cont)
191             this.completions_cont.throw(abort());
192         delete this.completions_cont;
194         var el = this.completions_display_element;
195         if (el) {
196             el.parentNode.removeChild(el);
197             this.completions_display_element = null;
198         }
199         if (this.continuation)
200             this.continuation.throw(abort());
201         basic_minibuffer_state.prototype.destroy.call(this, window);
202     },
204     handle_input: function () {
205         if (!this.completer) return;
207         this.completions_valid = false;
209         if (!this.auto_complete) return;
211         var s = this;
213         if (this.auto_complete_delay > 0) {
214             if (this.completions_timer_ID != null)
215                 this.window.clearTimeout(this.completions_timer_ID);
216             this.completions_timer_ID = this.window.setTimeout(
217                 function () {
218                     s.completions_timer_ID = null;
219                     s.update_completions(true /* auto */, true /* update completions display */);
220                 }, this.auto_complete_delay);
221             return;
222         }
223         s.update_completions(true /* auto */, true /* update completions display */);
224     },
226     ran_minibuffer_command: function () {
227         this.handle_input();
228     },
230     update_completions_display: function () {
231         var m = this.window.minibuffer;
232         if (m.current_state == this) {
233             if (this.completions && this.completions.count > 0) {
234                 this.completions_display_element.view = this.completions_display_element.view;
235                 this.completions_display_element.setAttribute("collapsed", "false");
237                 this.completions_display_element.currentIndex = this.selected_completion_index;
238                 this.completions_display_element.treeBoxObject.scrollToRow(this.selected_completion_index);
239             } else {
240                 this.completions_display_element.setAttribute("collapsed", "true");
241             }
242         }
243     },
245     /* If auto is true, this update is due to auto completion, rather
246      * than specifically requested. */
247     update_completions: function (auto, update_display) {
248         if (this.completions_timer_ID != null) {
249             this.window.clearTimeout(this.completions_timer_ID);
250             this.completions_timer_ID = null;
251         }
253         let m = this.window.minibuffer;
255         if (this.completions_cont) {
256             this.completions_cont.throw(abort());
257             this.completions_cont = null;
258         }
260         let c = this.completer(m._input_text, m._selection_start,
261                                auto && this.auto_complete_conservative);
263         if (is_coroutine(c)) {
264             let s = this;
265             let already_done = false;
266             this.completions_cont = co_call(function () {
267                 var x;
268                 try {
269                     x = yield c;
270                 } catch (e) {
271                     handle_interactive_error(m.window, e);
272                 } finally {
273                     s.completions_cont = null;
274                     already_done = true;
275                 }
276                 s.update_completions_done(x, update_display);
277             }());
279             // In case the completer actually already finished
280             if (already_done)
281                 this.completions_cont = null;
282             return;
283         } else
284             this.update_completions_done(c, update_display);
285     },
287     update_completions_done: function (c, update_display) {
288         /* The completer should return undefined if completion was not
289          * attempted due to auto being true.  Otherwise, it can return
290          * null to indicate no completions. */
291         if (this.completions != null && this.completions.destroy)
292             this.completions.destroy();
294         this.completions = c;
295         this.completions_valid = true;
296         this.applied_common_prefix = false;
298         if (c && ("get_match_required" in c))
299             this.match_required = c.get_match_required();
300         if (this.match_required == null)
301             this.match_required = this.match_required_default;
303         let i = -1;
304         if (c && c.count > 0) {
305             if (this.match_required) {
306                 if (c.count == 1)
307                     i = 0;
308                 else if (c.default_completion != null)
309                     i = c.default_completion;
310                 else if (this.default_completion && this.completions.index_of)
311                     i = this.completions.index_of(this.default_completion);
312             }
313             this.selected_completion_index = i;
314         }
316         if (update_display)
317             this.update_completions_display();
318     },
320     select_completion: function (i) {
321         this.selected_completion_index = i;
322         this.completions_display_element.currentIndex = i;
323         if (i >= 0)
324             this.completions_display_element.treeBoxObject.ensureRowIsVisible(i);
325         this.handle_completion_selected();
326     },
328     handle_completion_selected: function () {
329         /**
330          * When a completion is selected, apply it to the input text
331          * if a match is not "required"; otherwise, the completion is
332          * only displayed.
333          */
334         var i = this.selected_completion_index;
335         var m = this.window.minibuffer;
336         var c = this.completions;
338         if (this.completions_valid && c && !this.match_required && i >= 0 && i < c.count)
339         {
340             m.set_input_state(c.get_input_state(i));
341         }
342     }
345 function minibuffer_complete (window, count) {
346     var m = window.minibuffer;
347     var s = m.current_state;
348     if (!(s instanceof text_entry_minibuffer_state))
349         throw new Error("Invalid minibuffer state");
350     if (!s.completer)
351         return;
352     var just_completed_manually = false;
353     if (!s.completions_valid || s.completions === undefined) {
354         if (s.completions_timer_ID == null)
355             just_completed_manually = true;
356         s.update_completions(false /* not auto */, true /* update completions display */);
358         // If the completer is a coroutine, nothing we can do here
359         if (!s.completions_valid)
360             return;
361     }
363     var c = s.completions;
365     if (!c || c.count == 0)
366         return;
368     var e = s.completions_display_element;
369     var new_index = -1;
371     let common_prefix;
373     if (count == 1 && !s.applied_common_prefix && (common_prefix = c.common_prefix_input_state)) {
374         m.set_input_state(common_prefix);
375         s.applied_common_prefix = true;
376     } else if (!just_completed_manually) {
377         if (e.currentIndex != -1) {
378             new_index = (e.currentIndex + count) % c.count;
379             if (new_index < 0)
380                 new_index += c.count;
381         } else {
382             new_index = (count - 1) % c.count;
383             if (new_index < 0)
384                 new_index += c.count;
385         }
386     }
388     if (new_index != -1)
389         s.select_completion(new_index);
391 interactive("minibuffer-complete", null,
392     function (I) { minibuffer_complete(I.window, I.p); });
393 interactive("minibuffer-complete-previous", null,
394     function (I) { minibuffer_complete(I.window, -I.p); });
396 function exit_minibuffer (window) {
397     var m = window.minibuffer;
398     var s = m.current_state;
399     if (!(s instanceof text_entry_minibuffer_state))
400         throw new Error("Invalid minibuffer state");
402     var val = m._input_text;
404     if (s.validator != null && !s.validator(val, m))
405         return;
407     var match = null;
409     if (s.completer && s.match_required) {
410         if (!s.completions_valid || s.completions === undefined)
411             s.update_completions(false /* not conservative */, false /* don't update */);
413         let c = s.completions;
414         let i = s.selected_completion_index;
415         if (c != null && i >= 0 && i < c.count) {
416             if (c.get_value != null)
417                 match = c.get_value(i);
418             else
419                 match = c.get_string(i);
420         } else {
421             m.message("No match");
422             return;
423         }
424     }
426     if (s.history) {
427         s.history.push(val);
428         if (s.history.length > minibuffer_history_max_items)
429             s.history.splice(0, s.history.length - minibuffer_history_max_items);
430     }
431     var cont = s.continuation;
432     delete s.continuation;
433     m.pop_state();
434     if (cont) {
435         if (s.match_required)
436             cont(match);
437         else
438             cont(val);
439     }
441 interactive("exit-minibuffer", null,
442     function (I) { exit_minibuffer(I.window); });
444 function minibuffer_history_next (window, count) {
445     var m = window.minibuffer;
446     var s = m.current_state;
447     if (!(s instanceof text_entry_minibuffer_state))
448         throw new Error("Invalid minibuffer state");
449     if (!s.history || s.history.length == 0)
450         throw interactive_error("No history available.");
451     if (count == 0)
452         return;
453     var index = s.history_index;
454     if (count > 0 && index == -1)
455         throw interactive_error("End of history; no next item");
456     else if (count < 0 && index == 0)
457         throw interactive_error("Beginning of history; no preceding item");
458     if (index == -1) {
459         s.saved_last_history_entry = m._input_text;
460         index = s.history.length + count;
461     } else
462         index = index + count;
464     if (index < 0)
465         index = 0;
467     m._restore_normal_state();
468     if (index >= s.history.length) {
469         index = -1;
470         m._input_text = s.saved_last_history_entry;
471     } else {
472         m._input_text = s.history[index];
473     }
474     s.history_index = index;
475     m._set_selection();
476     s.handle_input();
478 interactive("minibuffer-history-next", null,
479     function (I) { minibuffer_history_next(I.window, I.p); });
480 interactive("minibuffer-history-previous", null,
481     function (I) { minibuffer_history_next(I.window, -I.p); });
483 // Define the asynchronous minibuffer.read function
484 minibuffer.prototype.read = function () {
485     var s = new text_entry_minibuffer_state(this.window, (yield CONTINUATION), forward_keywords(arguments));
486     this.push_state(s);
487     var result = yield SUSPEND;
488     yield co_return(result);
491 minibuffer.prototype.read_command = function () {
492     keywords(
493         arguments,
494         $prompt = "Command", $history = "command",
495         $completer = prefix_completer(
496             $completions = function (visitor) interactive_commands.for_each_value(visitor),
497             $get_string = function (x) x.name,
498             $get_description = function (x) x.shortdoc || "",
499             $get_value = function (x) x.name),
500         $match_required = true);
501     var result = yield this.read(forward_keywords(arguments));
502     yield co_return(result);
505 minibuffer.prototype.read_user_variable = function () {
506     keywords(
507         arguments,
508         $prompt = "User variable", $history = "user_variable",
509         $completer = prefix_completer(
510             $completions = function (visitor) {
511                 for (var i in user_variables) visitor(i);
512             },
513             $get_string = function (x) x,
514             $get_description = function (x) user_variables[x].shortdoc || "",
515             $get_value = function (x) x),
516         $match_required = true);
517     var result = yield this.read(forward_keywords(arguments));
518     yield co_return(result);
521 minibuffer.prototype.read_preference = function () {
522     keywords(arguments,
523              $prompt = "Preference:", $history = "preference",
524              $completer = prefix_completer(
525                  $completions = preferences.getBranch(null).getChildList("", {}),
526                  $get_description = function (pref) {
527                      let default_value = get_default_pref(pref);
528                      let value = get_pref(pref);
529                      if (value == default_value)
530                          value = null;
531                      let type;
532                      switch (preferences.getBranch(null).getPrefType(pref)) {
533                      case Ci.nsIPrefBranch.PREF_STRING:
534                          type = "string";
535                          break;
536                      case Ci.nsIPrefBranch.PREF_INT:
537                          type = "int";
538                          break;
539                      case Ci.nsIPrefBranch.PREF_BOOL:
540                          type = "boolean";
541                          break;
542                      }
543                      let out = type + ":";
544                      if (value != null)
545                          out += " " + pretty_print_value(value);
546                      if (default_value != null)
547                          out += " (" + pretty_print_value(default_value) + ")";
548                      return out;
549                  }),
550              $match_required = true);
551     var result = yield this.read(forward_keywords(arguments));
552     yield co_return(result);
555 provide("minibuffer-read");