completions_tree_view.getCellProperties: fix for XULRunner >= 22
[conkeror.git] / modules / minibuffer-read.js
blob000bbed421d8866c3dce8773a9225f055390f9d8
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 define_variable("default_minibuffer_auto_complete_delay", 150,
10     "Delay (in milliseconds) after the most recent key-stroke "+
11     "before auto-completing.");
13 define_variable("minibuffer_auto_complete_preferences", {});
15 define_variable("minibuffer_auto_complete_default", false,
16     "Boolean specifying whether to auto-complete by default. "+
17     "The user variable `minibuffer_auto_complete_preferences' "+
18     "overrides this.");
20 var minibuffer_history_data = {};
22 /* FIXME: These should possibly be saved to disk somewhere */
23 define_variable("minibuffer_history_max_items", 100,
24     "Maximum number of minibuffer history entries stored. Older "+
25     "history entries are truncated after this limit is reached.");
27 define_variable("minibuffer_completion_rows", 8,
28     "Number of minibuffer completions to display at one time.");
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             var a = atom_service.getAtom("completion-string");
72         else
73             a = atom_service.getAtom("completion-description");
74         if (props)
75             props.AppendElement(a);
76         return a;
77     },
78     getColumnProperties: function (colid, col, props) {}
82 /* The parameter `args' specifies the arguments.  In addition, the
83  * arguments for basic_minibuffer_state are also allowed.
84  *
85  * history:           [optional] specifies a string to identify the history list to use
86  *
87  * completer
88  *
89  * match_required
90  *
91  * default_completion  only used if match_required is set to true
92  *
93  * $valiator          [optional]
94  *          specifies a function
95  */
96 define_keywords("$keymap", "$history", "$validator",
97                 "$completer", "$match_required", "$default_completion",
98                 "$auto_complete", "$auto_complete_initial", "$auto_complete_conservative",
99                 "$auto_complete_delay", "$enable_icons",
100                 "$space_completes");
101 /* FIXME: support completing in another thread */
102 function text_entry_minibuffer_state (minibuffer, continuation) {
103     keywords(arguments, $keymap = minibuffer_keymap,
104              $enable_icons = false);
106     basic_minibuffer_state.call(this, minibuffer, forward_keywords(arguments));
108     this.continuation = continuation;
109     if (arguments.$history) {
110         this.history = minibuffer_history_data[arguments.$history] =
111             minibuffer_history_data[arguments.$history] || [];
112         this.history_index = -1;
113         this.saved_last_history_entry = null;
114     }
116     this.validator = arguments.$validator;
118     if (arguments.$completer != null) {
119         this.completer = arguments.$completer;
120         let auto = arguments.$auto_complete;
121         while (typeof auto == "string")
122             auto = minibuffer_auto_complete_preferences[auto];
123         if (auto == null)
124             auto = minibuffer_auto_complete_default;
125         this.auto_complete = auto;
126         this.auto_complete_initial = !!arguments.$auto_complete_initial;
127         this.auto_complete_conservative = !!arguments.$auto_complete_conservative;
128         let delay = arguments.$auto_complete_delay;
129         if (delay == null)
130             delay = default_minibuffer_auto_complete_delay;
131         this.auto_complete_delay = delay;
132         this.completions = null;
133         this.completions_valid = false;
134         this.space_completes = !!arguments.$space_completes;
135         if (this.space_completes)
136             this.keymaps.push(minibuffer_space_completion_keymap);
137         this.completions_timer_ID = null;
138         this.completions_display_element = null;
139         this.selected_completion_index = -1;
140         this.match_required  = !!arguments.$match_required;
141         this.match_required_default = this.match_required;
142         if (this.match_required)
143             this.default_completion = arguments.$default_completion;
144         this.enable_icons = arguments.$enable_icons;
145     }
147 text_entry_minibuffer_state.prototype = {
148     constructor: text_entry_minibuffer_state,
149     __proto__: basic_minibuffer_state.prototype,
150     load: function () {
151         basic_minibuffer_state.prototype.load.call(this);
152         var window = this.minibuffer.window;
153         if (this.completer) {
154             // Create completion display element if needed
155             if (! this.completion_element) {
156                 /* FIXME: maybe use the dom_generator */
157                 var tree = create_XUL(window, "tree");
158                 var s = this;
159                 tree.addEventListener("select", function () {
160                         s.selected_completion_index = s.completions_display_element.currentIndex;
161                         s.handle_completion_selected();
162                     }, true);
163                 tree.setAttribute("class", "completions");
165                 tree.setAttribute("rows", minibuffer_completion_rows);
167                 tree.setAttribute("collapsed", "true");
169                 tree.setAttribute("hidecolumnpicker", "true");
170                 tree.setAttribute("hideheader", "true");
171                 if (this.enable_icons)
172                     tree.setAttribute("hasicons", "true");
174                 var treecols = create_XUL(window, "treecols");
175                 tree.appendChild(treecols);
176                 var treecol = create_XUL(window, "treecol");
177                 treecol.setAttribute("flex", "1");
178                 treecols.appendChild(treecol);
179                 treecol = create_XUL(window, "treecol");
180                 treecol.setAttribute("flex", "1");
181                 treecols.appendChild(treecol);
182                 tree.appendChild(create_XUL(window, "treechildren"));
184                 this.minibuffer.insert_before(tree);
185                 tree.view = new completions_tree_view(this);
186                 this.completions_display_element = tree;
188                 // This is the initial loading of this minibuffer state.
189                 // If this.auto_complete_initial is true, generate
190                 // completions.
191                 if (this.auto_complete_initial)
192                     this.handle_input();
193             }
194             this.update_completions_display();
195         }
196     },
198     unload: function () {
199         if (this.completions_display_element)
200             this.completions_display_element.setAttribute("collapsed", "true");
201         basic_minibuffer_state.prototype.unload.call(this);
202     },
204     destroy: function () {
205         if (this.completions != null && this.completions.destroy)
206             this.completions.destroy();
207         delete this.completions;
208         if (this.completions_cont)
209             this.completions_cont.throw(abort());
210         delete this.completions_cont;
212         var el = this.completions_display_element;
213         if (el) {
214             el.parentNode.removeChild(el);
215             this.completions_display_element = null;
216         }
217         if (this.continuation)
218             this.continuation.throw(abort());
219         basic_minibuffer_state.prototype.destroy.call(this);
220     },
222     handle_input: function () {
223         if (! this.completer)
224             return;
225         this.completions_valid = false;
226         if (! this.auto_complete)
227             return;
228         var s = this;
229         var window = this.minibuffer.window;
230         if (this.auto_complete_delay > 0) {
231             if (this.completions_timer_ID != null)
232                 window.clearTimeout(this.completions_timer_ID);
233             this.completions_timer_ID = window.setTimeout(
234                 function () {
235                     s.completions_timer_ID = null;
236                     s.update_completions(true /* auto */, true /* update completions display */);
237                 }, this.auto_complete_delay);
238             return;
239         }
240         s.update_completions(true /* auto */, true /* update completions display */);
241     },
243     update_completions_display: function () {
244         var m = this.minibuffer;
245         if (m.current_state == this) {
246             if (this.completions && this.completions.count > 0) {
247                 this.completions_display_element.view = this.completions_display_element.view;
248                 this.completions_display_element.setAttribute("collapsed", "false");
249                 this.completions_display_element.currentIndex = this.selected_completion_index;
250                 var max_display = this.completions_display_element.treeBoxObject.getPageLength();
251                 var mid_point = Math.floor(max_display / 2);
252                 if (this.completions.count - this.selected_completion_index <= mid_point)
253                     var pos = this.completions.count - max_display;
254                 else
255                     pos = Math.max(0, this.selected_completion_index - mid_point);
256                 this.completions_display_element.treeBoxObject.scrollToRow(pos);
257             } else {
258                 this.completions_display_element.setAttribute("collapsed", "true");
259             }
260         }
261     },
263     /* If auto is true, this update is due to auto completion, rather
264      * than specifically requested. */
265     update_completions: function (auto, update_display) {
266         var window = this.minibuffer.window;
267         if (this.completions_timer_ID != null) {
268             window.clearTimeout(this.completions_timer_ID);
269             this.completions_timer_ID = null;
270         }
271         var m = this.minibuffer;
272         if (this.completions_cont) {
273             this.completions_cont.throw(abort());
274             this.completions_cont = null;
275         }
276         let c = this.completer(m._input_text, m._selection_start,
277                                auto && this.auto_complete_conservative);
278         if (is_coroutine(c)) {
279             var s = this;
280             var already_done = false;
281             this.completions_cont = co_call(function () {
282                 try {
283                     var x = yield c;
284                 } catch (e) {
285                     handle_interactive_error(window, e);
286                 } finally {
287                     s.completions_cont = null;
288                     already_done = true;
289                 }
290                 s.update_completions_done(x, update_display);
291             }());
292             // In case the completer actually already finished
293             if (already_done)
294                 this.completions_cont = null;
295         } else
296             this.update_completions_done(c, update_display);
297     },
299     update_completions_done: function (c, update_display) {
300         /* The completer should return undefined if completion was not
301          * attempted due to auto being true.  Otherwise, it can return
302          * null to indicate no completions. */
303         if (this.completions != null && this.completions.destroy)
304             this.completions.destroy();
306         this.completions = c;
307         this.completions_valid = true;
308         this.applied_common_prefix = false;
310         if (c && ("get_match_required" in c))
311             this.match_required = c.get_match_required();
312         if (this.match_required == null)
313             this.match_required = this.match_required_default;
315         if (c && c.count > 0) {
316             var i = -1;
317             if (this.match_required) {
318                 if (c.count == 1)
319                     i = 0;
320                 else if (c.default_completion != null)
321                     i = c.default_completion;
322                 else if (this.default_completion && this.completions.index_of)
323                     i = this.completions.index_of(this.default_completion);
324             }
325             this.selected_completion_index = i;
326         }
328         if (update_display)
329             this.update_completions_display();
330     },
332     select_completion: function (i) {
333         this.selected_completion_index = i;
334         this.completions_display_element.currentIndex = i;
335         if (i >= 0)
336             this.completions_display_element.treeBoxObject.ensureRowIsVisible(i);
337         this.handle_completion_selected();
338     },
340     handle_completion_selected: function () {
341         /**
342          * When a completion is selected, apply it to the input text
343          * if a match is not "required"; otherwise, the completion is
344          * only displayed.
345          */
346         var i = this.selected_completion_index;
347         var m = this.minibuffer;
348         var c = this.completions;
350         if (this.completions_valid && c && !this.match_required && i >= 0 && i < c.count)
351             m.set_input_state(c.get_input_state(i));
352     }
355 function minibuffer_complete (window, count) {
356     var m = window.minibuffer;
357     var s = m.current_state;
358     if (! (s instanceof text_entry_minibuffer_state))
359         throw new Error("Invalid minibuffer state");
360     if (! s.completer)
361         return;
362     var just_completed_manually = false;
363     if (! s.completions_valid || s.completions === undefined) {
364         if (s.completions_timer_ID == null)
365             just_completed_manually = true;
366         //XXX: may need to use ignore_input_events here
367         s.update_completions(false /* not auto */, true /* update completions display */);
369         // If the completer is a coroutine, nothing we can do here
370         if (! s.completions_valid)
371             return;
372     }
374     var c = s.completions;
376     if (! c || c.count == 0)
377         return;
379     var e = s.completions_display_element;
380     var new_index = -1;
381     var common_prefix;
383     if (count == 1 && ! s.applied_common_prefix &&
384         (common_prefix = c.common_prefix_input_state))
385     {
386         //XXX: may need to use ignore_input_events here
387         m.set_input_state(common_prefix);
388         s.applied_common_prefix = true;
389     } else if (!just_completed_manually) {
390         if (e.currentIndex != -1) {
391             new_index = (e.currentIndex + count) % c.count;
392             if (new_index < 0)
393                 new_index += c.count;
394         } else {
395             new_index = (count - 1) % c.count;
396             if (new_index < 0)
397                 new_index += c.count;
398         }
399     }
401     if (new_index != -1) {
402        try {
403             m.ignore_input_events = true;
404             s.select_completion(new_index);
405         } finally {
406             m.ignore_input_events = false;
407         }
408     }
410 interactive("minibuffer-complete", null,
411     function (I) { minibuffer_complete(I.window, I.p); });
412 interactive("minibuffer-complete-previous", null,
413     function (I) { minibuffer_complete(I.window, -I.p); });
415 function exit_minibuffer (window) {
416     var m = window.minibuffer;
417     var s = m.current_state;
418     if (! (s instanceof text_entry_minibuffer_state))
419         throw new Error("Invalid minibuffer state");
421     var val = m._input_text;
423     if (s.validator != null && ! s.validator(val, m))
424         return;
426     var match = null;
428     if (s.completer && s.match_required) {
429         if (! s.completions_valid || s.completions === undefined)
430             s.update_completions(false /* not conservative */, false /* don't update */);
432         let c = s.completions;
433         let i = s.selected_completion_index;
434         if (c != null && i >= 0 && i < c.count) {
435             if (c.get_value != null)
436                 match = c.get_value(i);
437             else
438                 match = c.get_string(i);
439         } else {
440             m.message("No match");
441             return;
442         }
443     }
445     if (s.history) {
446         s.history.push(val);
447         if (s.history.length > minibuffer_history_max_items)
448             s.history.splice(0, s.history.length - minibuffer_history_max_items);
449     }
450     var cont = s.continuation;
451     delete s.continuation;
452     m.pop_state();
453     if (cont) {
454         if (s.match_required)
455             cont(match);
456         else
457             cont(val);
458     }
460 interactive("exit-minibuffer", null,
461     function (I) { exit_minibuffer(I.window); });
463 function minibuffer_history_next (window, count) {
464     var m = window.minibuffer;
465     var s = m.current_state;
466     if (! (s instanceof text_entry_minibuffer_state))
467         throw new Error("Invalid minibuffer state");
468     if (! s.history || s.history.length == 0)
469         throw interactive_error("No history available.");
470     if (count == 0)
471         return;
472     var index = s.history_index;
473     if (count > 0 && index == -1)
474         throw interactive_error("End of history; no next item");
475     else if (count < 0 && index == 0)
476         throw interactive_error("Beginning of history; no preceding item");
477     if (index == -1) {
478         s.saved_last_history_entry = m._input_text;
479         index = s.history.length + count;
480     } else
481         index = index + count;
483     if (index < 0)
484         index = 0;
486     m._restore_normal_state();
487     if (index >= s.history.length) {
488         index = -1;
489         m._input_text = s.saved_last_history_entry;
490     } else {
491         m._input_text = s.history[index];
492     }
493     s.history_index = index;
494     m._set_selection();
495     s.handle_input();
497 interactive("minibuffer-history-next", null,
498     function (I) { minibuffer_history_next(I.window, I.p); });
499 interactive("minibuffer-history-previous", null,
500     function (I) { minibuffer_history_next(I.window, -I.p); });
502 // Define the asynchronous minibuffer.read function
503 minibuffer.prototype.read = function () {
504     var s = new text_entry_minibuffer_state(this, (yield CONTINUATION), forward_keywords(arguments));
505     this.push_state(s);
506     var result = yield SUSPEND;
507     yield co_return(result);
510 minibuffer.prototype.read_command = function () {
511     keywords(
512         arguments,
513         $prompt = "Command", $history = "command",
514         $completer = prefix_completer(
515             $completions = function (visitor) {
516                 for (let [k,v] in Iterator(interactive_commands)) {
517                     visitor(v);
518                 }
519             },
520             $get_string = function (x) x.name,
521             $get_description = function (x) x.shortdoc || "",
522             $get_value = function (x) x.name),
523         $match_required,
524         $space_completes);
525     var result = yield this.read(forward_keywords(arguments));
526     yield co_return(result);
529 minibuffer.prototype.read_user_variable = function () {
530     keywords(
531         arguments,
532         $prompt = "User variable", $history = "user_variable",
533         $completer = prefix_completer(
534             $completions = function (visitor) {
535                 for (var i in user_variables) visitor(i);
536             },
537             $get_string = function (x) x,
538             $get_description = function (x) user_variables[x].shortdoc || "",
539             $get_value = function (x) x),
540         $match_required,
541         $space_completes);
542     var result = yield this.read(forward_keywords(arguments));
543     yield co_return(result);
546 minibuffer.prototype.read_preference = function () {
547     keywords(arguments,
548              $prompt = "Preference:", $history = "preference",
549              $completer = prefix_completer(
550                  $completions = preferences.getBranch(null).getChildList("", {}),
551                  $get_description = function (pref) {
552                      let default_value = get_default_pref(pref);
553                      let value = get_pref(pref);
554                      if (value == default_value)
555                          value = null;
556                      let type;
557                      switch (preferences.getBranch(null).getPrefType(pref)) {
558                      case Ci.nsIPrefBranch.PREF_STRING:
559                          type = "string";
560                          break;
561                      case Ci.nsIPrefBranch.PREF_INT:
562                          type = "int";
563                          break;
564                      case Ci.nsIPrefBranch.PREF_BOOL:
565                          type = "boolean";
566                          break;
567                      }
568                      let out = type + ":";
569                      if (value != null)
570                          out += " " + pretty_print_value(value);
571                      if (default_value != null)
572                          out += " (" + pretty_print_value(default_value) + ")";
573                      return out;
574                  }),
575              $match_required,
576              $space_completes);
577     var result = yield this.read(forward_keywords(arguments));
578     yield co_return(result);
582 define_keywords("$object");
583 minibuffer.prototype.read_object_property = function () {
584     keywords(arguments,
585              $prompt = "Property:");
586     var o = arguments.$object || {};
587     var result = yield this.read(
588         $prompt = arguments.$prompt,
589         $completer = new prefix_completer(
590             $completions = function (push) {
591                 for (var i in o)
592                     push(i);
593             }),
594         $match_required,
595         $space_completes);
596     yield co_return(result);
600 provide("minibuffer-read");