Debian package: consistently use "touch $@" for stamp files
[conkeror.git] / modules / minibuffer-read.js
blobbe35ed38f44497702e8545b2effe200dee98b535
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             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", minibuffer_completion_rows);
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 state.
186                 // If this.auto_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)
221             return;
222         this.completions_valid = false;
223         if (! this.auto_complete)
224             return;
225         var s = this;
226         var window = this.minibuffer.window;
227         if (this.auto_complete_delay > 0) {
228             if (this.completions_timer_ID != null)
229                 window.clearTimeout(this.completions_timer_ID);
230             this.completions_timer_ID = window.setTimeout(
231                 function () {
232                     s.completions_timer_ID = null;
233                     s.update_completions(true /* auto */, true /* update completions display */);
234                 }, this.auto_complete_delay);
235             return;
236         }
237         s.update_completions(true /* auto */, true /* update completions display */);
238     },
240     update_completions_display: function () {
241         var m = this.minibuffer;
242         if (m.current_state == this) {
243             if (this.completions && this.completions.count > 0) {
244                 this.completions_display_element.view = this.completions_display_element.view;
245                 this.completions_display_element.setAttribute("collapsed", "false");
246                 this.completions_display_element.currentIndex = this.selected_completion_index;
247                 var max_display = this.completions_display_element.treeBoxObject.getPageLength();
248                 var mid_point = Math.floor(max_display / 2);
249                 if (this.completions.count - this.selected_completion_index <= mid_point)
250                     var pos = this.completions.count - max_display;
251                 else
252                     pos = Math.max(0, this.selected_completion_index - mid_point);
253                 this.completions_display_element.treeBoxObject.scrollToRow(pos);
254             } else {
255                 this.completions_display_element.setAttribute("collapsed", "true");
256             }
257         }
258     },
260     /* If auto is true, this update is due to auto completion, rather
261      * than specifically requested. */
262     update_completions: function (auto, update_display) {
263         var window = this.minibuffer.window;
264         if (this.completions_timer_ID != null) {
265             window.clearTimeout(this.completions_timer_ID);
266             this.completions_timer_ID = null;
267         }
268         var m = this.minibuffer;
269         if (this.completions_cont) {
270             this.completions_cont.throw(abort());
271             this.completions_cont = null;
272         }
273         let c = this.completer(m._input_text, m._selection_start,
274                                auto && this.auto_complete_conservative);
275         if (is_coroutine(c)) {
276             var s = this;
277             var already_done = false;
278             this.completions_cont = co_call(function () {
279                 try {
280                     var x = yield c;
281                 } catch (e) {
282                     handle_interactive_error(window, e);
283                 } finally {
284                     s.completions_cont = null;
285                     already_done = true;
286                 }
287                 s.update_completions_done(x, update_display);
288             }());
289             // In case the completer actually already finished
290             if (already_done)
291                 this.completions_cont = null;
292         } else
293             this.update_completions_done(c, update_display);
294     },
296     update_completions_done: function (c, update_display) {
297         /* The completer should return undefined if completion was not
298          * attempted due to auto being true.  Otherwise, it can return
299          * null to indicate no completions. */
300         if (this.completions != null && this.completions.destroy)
301             this.completions.destroy();
303         this.completions = c;
304         this.completions_valid = true;
305         this.applied_common_prefix = false;
307         if (c && ("get_match_required" in c))
308             this.match_required = c.get_match_required();
309         if (this.match_required == null)
310             this.match_required = this.match_required_default;
312         if (c && c.count > 0) {
313             var i = -1;
314             if (this.match_required) {
315                 if (c.count == 1)
316                     i = 0;
317                 else if (c.default_completion != null)
318                     i = c.default_completion;
319                 else if (this.default_completion && this.completions.index_of)
320                     i = this.completions.index_of(this.default_completion);
321             }
322             this.selected_completion_index = i;
323         }
325         if (update_display)
326             this.update_completions_display();
327     },
329     select_completion: function (i) {
330         this.selected_completion_index = i;
331         this.completions_display_element.currentIndex = i;
332         if (i >= 0)
333             this.completions_display_element.treeBoxObject.ensureRowIsVisible(i);
334         this.handle_completion_selected();
335     },
337     handle_completion_selected: function () {
338         /**
339          * When a completion is selected, apply it to the input text
340          * if a match is not "required"; otherwise, the completion is
341          * only displayed.
342          */
343         var i = this.selected_completion_index;
344         var m = this.minibuffer;
345         var c = this.completions;
347         if (this.completions_valid && c && !this.match_required && i >= 0 && i < c.count)
348             m.set_input_state(c.get_input_state(i));
349     }
352 function minibuffer_complete (window, count) {
353     var m = window.minibuffer;
354     var s = m.current_state;
355     if (! (s instanceof text_entry_minibuffer_state))
356         throw new Error("Invalid minibuffer state");
357     if (! s.completer)
358         return;
359     var just_completed_manually = false;
360     if (! s.completions_valid || s.completions === undefined) {
361         if (s.completions_timer_ID == null)
362             just_completed_manually = true;
363         //XXX: may need to use ignore_input_events here
364         s.update_completions(false /* not auto */, true /* update completions display */);
366         // If the completer is a coroutine, nothing we can do here
367         if (! s.completions_valid)
368             return;
369     }
371     var c = s.completions;
373     if (! c || c.count == 0)
374         return;
376     var e = s.completions_display_element;
377     var new_index = -1;
378     var common_prefix;
380     if (count == 1 && ! s.applied_common_prefix &&
381         (common_prefix = c.common_prefix_input_state))
382     {
383         //XXX: may need to use ignore_input_events here
384         m.set_input_state(common_prefix);
385         s.applied_common_prefix = true;
386     } else if (!just_completed_manually) {
387         if (e.currentIndex != -1) {
388             new_index = (e.currentIndex + count) % c.count;
389             if (new_index < 0)
390                 new_index += c.count;
391         } else {
392             new_index = (count - 1) % c.count;
393             if (new_index < 0)
394                 new_index += c.count;
395         }
396     }
398     if (new_index != -1) {
399        try {
400             m.ignore_input_events = true;
401             s.select_completion(new_index);
402         } finally {
403             m.ignore_input_events = false;
404         }
405     }
407 interactive("minibuffer-complete", null,
408     function (I) { minibuffer_complete(I.window, I.p); });
409 interactive("minibuffer-complete-previous", null,
410     function (I) { minibuffer_complete(I.window, -I.p); });
412 function exit_minibuffer (window) {
413     var m = window.minibuffer;
414     var s = m.current_state;
415     if (! (s instanceof text_entry_minibuffer_state))
416         throw new Error("Invalid minibuffer state");
418     var val = m._input_text;
420     if (s.validator != null && ! s.validator(val, m))
421         return;
423     var match = null;
425     if (s.completer && s.match_required) {
426         if (! s.completions_valid || s.completions === undefined)
427             s.update_completions(false /* not conservative */, false /* don't update */);
429         let c = s.completions;
430         let i = s.selected_completion_index;
431         if (c != null && i >= 0 && i < c.count) {
432             if (c.get_value != null)
433                 match = c.get_value(i);
434             else
435                 match = c.get_string(i);
436         } else {
437             m.message("No match");
438             return;
439         }
440     }
442     if (s.history) {
443         s.history.push(val);
444         if (s.history.length > minibuffer_history_max_items)
445             s.history.splice(0, s.history.length - minibuffer_history_max_items);
446     }
447     var cont = s.continuation;
448     delete s.continuation;
449     m.pop_state();
450     if (cont) {
451         if (s.match_required)
452             cont(match);
453         else
454             cont(val);
455     }
457 interactive("exit-minibuffer", null,
458     function (I) { exit_minibuffer(I.window); });
460 function minibuffer_history_next (window, count) {
461     var m = window.minibuffer;
462     var s = m.current_state;
463     if (! (s instanceof text_entry_minibuffer_state))
464         throw new Error("Invalid minibuffer state");
465     if (! s.history || s.history.length == 0)
466         throw interactive_error("No history available.");
467     if (count == 0)
468         return;
469     var index = s.history_index;
470     if (count > 0 && index == -1)
471         throw interactive_error("End of history; no next item");
472     else if (count < 0 && index == 0)
473         throw interactive_error("Beginning of history; no preceding item");
474     if (index == -1) {
475         s.saved_last_history_entry = m._input_text;
476         index = s.history.length + count;
477     } else
478         index = index + count;
480     if (index < 0)
481         index = 0;
483     m._restore_normal_state();
484     if (index >= s.history.length) {
485         index = -1;
486         m._input_text = s.saved_last_history_entry;
487     } else {
488         m._input_text = s.history[index];
489     }
490     s.history_index = index;
491     m._set_selection();
492     s.handle_input();
494 interactive("minibuffer-history-next", null,
495     function (I) { minibuffer_history_next(I.window, I.p); });
496 interactive("minibuffer-history-previous", null,
497     function (I) { minibuffer_history_next(I.window, -I.p); });
499 // Define the asynchronous minibuffer.read function
500 minibuffer.prototype.read = function () {
501     var s = new text_entry_minibuffer_state(this, (yield CONTINUATION), forward_keywords(arguments));
502     this.push_state(s);
503     var result = yield SUSPEND;
504     yield co_return(result);
507 minibuffer.prototype.read_command = function () {
508     keywords(
509         arguments,
510         $prompt = "Command", $history = "command",
511         $completer = prefix_completer(
512             $completions = function (visitor) {
513                 for (let [k,v] in Iterator(interactive_commands)) {
514                     visitor(v);
515                 }
516             },
517             $get_string = function (x) x.name,
518             $get_description = function (x) x.shortdoc || "",
519             $get_value = function (x) x.name),
520         $match_required,
521         $space_completes);
522     var result = yield this.read(forward_keywords(arguments));
523     yield co_return(result);
526 minibuffer.prototype.read_user_variable = function () {
527     keywords(
528         arguments,
529         $prompt = "User variable", $history = "user_variable",
530         $completer = prefix_completer(
531             $completions = function (visitor) {
532                 for (var i in user_variables) visitor(i);
533             },
534             $get_string = function (x) x,
535             $get_description = function (x) user_variables[x].shortdoc || "",
536             $get_value = function (x) x),
537         $match_required,
538         $space_completes);
539     var result = yield this.read(forward_keywords(arguments));
540     yield co_return(result);
543 minibuffer.prototype.read_preference = function () {
544     keywords(arguments,
545              $prompt = "Preference:", $history = "preference",
546              $completer = prefix_completer(
547                  $completions = preferences.getBranch(null).getChildList("", {}),
548                  $get_description = function (pref) {
549                      let default_value = get_default_pref(pref);
550                      let value = get_pref(pref);
551                      if (value == default_value)
552                          value = null;
553                      let type;
554                      switch (preferences.getBranch(null).getPrefType(pref)) {
555                      case Ci.nsIPrefBranch.PREF_STRING:
556                          type = "string";
557                          break;
558                      case Ci.nsIPrefBranch.PREF_INT:
559                          type = "int";
560                          break;
561                      case Ci.nsIPrefBranch.PREF_BOOL:
562                          type = "boolean";
563                          break;
564                      }
565                      let out = type + ":";
566                      if (value != null)
567                          out += " " + pretty_print_value(value);
568                      if (default_value != null)
569                          out += " (" + pretty_print_value(default_value) + ")";
570                      return out;
571                  }),
572              $match_required,
573              $space_completes);
574     var result = yield this.read(forward_keywords(arguments));
575     yield co_return(result);
579 define_keywords("$object");
580 minibuffer.prototype.read_object_property = function () {
581     keywords(arguments,
582              $prompt = "Property:");
583     var o = arguments.$object || {};
584     var result = yield this.read(
585         $prompt = arguments.$prompt,
586         $completer = new prefix_completer(
587             $completions = function (push) {
588                 for (var i in o)
589                     push(i);
590             }),
591         $match_required,
592         $space_completes);
593     yield co_return(result);
597 provide("minibuffer-read");