1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
//! Provides access to terminal read operations

use std::borrow::Cow;
use std::collections::{HashMap, VecDeque};
use std::io;
use std::mem::replace;
use std::ops::{Deref, DerefMut};
use std::path::{Path, PathBuf};
use std::slice;
use std::sync::{Arc, MutexGuard};
use std::time::Duration;

use mortal::SequenceMap;

use command::{Category, Command};
use complete::{Completer, Completion, DummyCompleter};
use function::Function;
use inputrc::{parse_file, Directive};
use interface::Interface;
use prompter::Prompter;
use sys::path::{env_init_file, system_init_file, user_init_file};
use terminal::{
    CursorMode, RawRead, Signal, SignalSet, Size,
    Terminal, TerminalReader,
};
use util::{first_char, match_name};
use variables::{Variable, Variables, VariableIter};
use writer::PromptData;

/// Default set of string characters
pub const STRING_CHARS: &str = "\"'";

/// Default set of word break characters
pub const WORD_BREAK_CHARS: &str = " \t\n\"\\'`@$><=;|&{(";

/// Indicates the start of a series of invisible characters in the prompt
pub const START_INVISIBLE: char = '\x01';

/// Indicates the end of a series of invisible characters in the prompt
pub const END_INVISIBLE: char = '\x02';

/// Maximum size of kill ring
const MAX_KILLS: usize = 10;

/// Provides access to data related to reading and processing user input.
///
/// Holds a lock on terminal read operations.
/// See [`Interface`] for more information about concurrent operations.
///
/// An instance of this type can be constructed using the
/// [`Interface::lock_reader`] method.
///
/// [`Interface`]: ../interface/struct.Interface.html
/// [`Interface::lock_reader`]: ../interface/struct.Interface.html#method.lock_reader
pub struct Reader<'a, Term: 'a + Terminal> {
    iface: &'a Interface<Term>,
    lock: ReadLock<'a, Term>,
}

pub(crate) struct Read<Term: Terminal> {
    /// Application name
    pub application: Cow<'static, str>,

    /// Pending input
    pub input_buffer: Vec<u8>,
    /// Pending macro sequence
    pub macro_buffer: String,

    pub bindings: SequenceMap<Cow<'static, str>, Command>,
    pub functions: HashMap<Cow<'static, str>, Arc<Function<Term>>>,

    /// Current input sequence
    pub sequence: String,
    /// Whether newline has been received
    pub input_accepted: bool,

    /// Whether overwrite mode is currently active
    pub overwrite_mode: bool,
    /// Characters appended while in overwrite mode
    pub overwritten_append: usize,
    /// Characters overwritten in overwrite mode
    pub overwritten_chars: String,

    /// Configured completer
    pub completer: Arc<Completer<Term>>,
    /// Character appended to completions
    pub completion_append_character: Option<char>,
    /// Current set of possible completions
    pub completions: Option<Vec<Completion>>,
    /// Current "menu-complete" entry being viewed:
    pub completion_index: usize,
    /// Start of the completed word
    pub completion_start: usize,
    /// Start of the inserted prefix of a completed word
    pub completion_prefix: usize,

    pub string_chars: Cow<'static, str>,
    pub word_break: Cow<'static, str>,

    pub last_cmd: Category,
    pub last_yank: Option<(usize, usize)>,
    pub kill_ring: VecDeque<String>,

    pub catch_signals: bool,
    pub ignore_signals: SignalSet,
    pub report_signals: SignalSet,
    pub last_resize: Option<Size>,
    pub last_signal: Option<Signal>,

    variables: Variables,
}

pub(crate) struct ReadLock<'a, Term: 'a + Terminal> {
    term: Box<TerminalReader<Term> + 'a>,
    data: MutexGuard<'a, Read<Term>>,
}

/// Returned from [`read_line`] to indicate user input
///
/// [`read_line`]: ../interface/struct.Interface.html#method.read_line
#[derive(Debug)]
pub enum ReadResult {
    /// User issued end-of-file
    Eof,
    /// User input received
    Input(String),
    /// Reported signal was received
    Signal(Signal),
}

impl<'a, Term: 'a + Terminal> Reader<'a, Term> {
    pub(crate) fn new(iface: &'a Interface<Term>, lock: ReadLock<'a, Term>)
            -> Reader<'a, Term> {
        Reader{iface, lock}
    }

    /// Interactively reads a line from the terminal device.
    ///
    /// If the user issues an end-of-file, `ReadResult::Eof` is returned.
    ///
    /// If a reported signal (see [`set_report_signal`]) is received,
    /// it is returned as `ReadResult::Signal(_)`.
    ///
    /// Otherwise, user input is collected until a newline is entered.
    /// The resulting input (not containing a trailing newline character)
    /// is returned as `ReadResult::Input(_)`.
    ///
    /// [`set_report_signal`]: #method.set_report_signal
    pub fn read_line(&mut self) -> io::Result<ReadResult> {
        let mut signals = self.lock.report_signals.union(self.lock.ignore_signals);

        // Ctrl-C is always intercepted.
        // By default, linefeed handles it by clearing the current input state.
        signals.insert(Signal::Interrupt);

        // TODO: Try to hold WriteLock continuously when performing multiple
        // write operations in a row. Box<TerminalReader> usage currently makes
        // this a bit tricky.
        let block_signals = !self.lock.catch_signals;
        let state = self.lock.term.prepare(block_signals, signals)?;

        let res = self.read_line_impl();
        self.lock.term.restore(state)?;

        // Restore normal cursor mode
        if self.lock.overwrite_mode {
            self.iface.lock_write()
                .set_cursor_mode(CursorMode::Normal)?;
        }

        res
    }

    /// Acquires the `Interface` write lock and returns a `PromptData` instance.
    ///
    /// The `PromptData` structure enables modification of prompt input data
    /// before a call to `read_line`. Prompt data is reset when a `read_line`
    /// call completes.
    pub fn lock_prompt_data<'b>(&'b mut self) -> PromptData<'b, 'a> {
        // Borrows from &mut Reader lifetime to prevent prompt data from being
        // modified while a read_line call is in progress.
        PromptData::new(self.iface.lock_write_data())
    }

    /// Sets the prompt that will be displayed when `read_line` is called.
    ///
    /// This method internally acquires the `Interface` write lock.
    ///
    /// # Notes
    ///
    /// If `prompt` contains any terminal escape sequences (e.g. color codes),
    /// such escape sequences should be immediately preceded by the character
    /// `'\x01'` and immediately followed by the character `'\x02'`.
    pub fn set_prompt(&mut self, prompt: &str) {
        self.lock_prompt_data().set_prompt(prompt)
    }

    /// Returns the application name
    pub fn application(&self) -> &str {
        &self.lock.application
    }

    /// Sets the application name
    pub fn set_application<T>(&mut self, application: T)
            where T: Into<Cow<'static, str>> {
        self.lock.application = application.into();
    }

    /// Returns a reference to the current completer instance.
    pub fn completer(&self) -> &Arc<Completer<Term>> {
        &self.lock.completer
    }

    /// Replaces the current completer, returning the previous instance.
    pub fn set_completer(&mut self, completer: Arc<Completer<Term>>)
            -> Arc<Completer<Term>> {
        replace(&mut self.lock.completer, completer)
    }

    /// Returns the value of the named variable or `None`
    /// if no such variable exists.
    pub fn get_variable(&self, name: &str) -> Option<Variable> {
        self.lock.get_variable(name)
    }

    /// Sets the value of the named variable and returns the previous
    /// value.
    ///
    /// If `name` does not refer to a variable or the `value` is not
    /// a valid value for the variable, `None` is returned.
    pub fn set_variable(&mut self, name: &str, value: &str) -> Option<Variable> {
        self.lock.set_variable(name, value)
    }

    /// Returns an iterator over stored variables.
    pub fn variables(&self) -> VariableIter {
        self.lock.variables.iter()
    }

    /// Returns whether to "blink" matching opening parenthesis character
    /// when a closing parenthesis character is entered.
    ///
    /// The default value is `false`.
    pub fn blink_matching_paren(&self) -> bool {
        self.lock.blink_matching_paren
    }

    /// Sets the `blink-matching-paren` variable.
    pub fn set_blink_matching_paren(&mut self, set: bool) {
        self.lock.blink_matching_paren = set;
    }

    /// Returns whether `linefeed` will catch certain signals.
    pub fn catch_signals(&self) -> bool {
        self.lock.catch_signals
    }

    /// Sets whether `linefeed` will catch certain signals.
    ///
    /// This setting is `true` by default. It can be disabled to allow the
    /// host program to handle signals itself.
    pub fn set_catch_signals(&mut self, enabled: bool) {
        self.lock.catch_signals = enabled;
    }

    /// Returns whether the given `Signal` is ignored.
    pub fn ignore_signal(&self, signal: Signal) -> bool {
        self.lock.ignore_signals.contains(signal)
    }

    /// Sets whether the given `Signal` will be ignored.
    pub fn set_ignore_signal(&mut self, signal: Signal, set: bool) {
        if set {
            self.lock.ignore_signals.insert(signal);
            self.lock.report_signals.remove(signal);
        } else {
            self.lock.ignore_signals.remove(signal);
        }
    }

    /// Returns whether the given `Signal` is to be reported.
    pub fn report_signal(&self, signal: Signal) -> bool {
        self.lock.report_signals.contains(signal)
    }

    /// Sets whether to report the given `Signal`.
    ///
    /// When a reported signal is received via the terminal, it will be returned
    /// from `Interface::read_line` as `Ok(Signal(signal))`.
    pub fn set_report_signal(&mut self, signal: Signal, set: bool) {
        if set {
            self.lock.report_signals.insert(signal);
            self.lock.ignore_signals.remove(signal);
        } else {
            self.lock.report_signals.remove(signal);
        }
    }

    /// Returns whether Tab completion is disabled.
    ///
    /// The default value is `false`.
    pub fn disable_completion(&self) -> bool {
        self.lock.disable_completion
    }

    /// Sets the `disable-completion` variable.
    pub fn set_disable_completion(&mut self, disable: bool) {
        self.lock.disable_completion = disable;
    }

    /// When certain control characters are pressed, a character sequence
    /// equivalent to this character will be echoed.
    ///
    /// The default value is `true`.
    pub fn echo_control_characters(&self) -> bool {
        self.lock.echo_control_characters
    }

    /// Sets the `echo-control-characters` variable.
    pub fn set_echo_control_characters(&mut self, echo: bool) {
        self.lock.echo_control_characters = echo;
    }

    /// Returns the character, if any, that is appended to a successful completion.
    pub fn completion_append_character(&self) -> Option<char> {
        self.lock.completion_append_character
    }

    /// Sets the character, if any, that is appended to a successful completion.
    pub fn set_completion_append_character(&mut self, ch: Option<char>) {
        self.lock.completion_append_character = ch;
    }

    /// Returns the width of completion listing display.
    ///
    /// If this value is greater than the terminal width, terminal width is used
    /// instead.
    ///
    /// The default value is equal to `usize::max_value()`.
    pub fn completion_display_width(&self) -> usize {
        self.lock.completion_display_width
    }

    /// Sets the `completion-display-width` variable.
    pub fn set_completion_display_width(&mut self, n: usize) {
        self.lock.completion_display_width = n;
    }

    /// Returns the minimum number of completion items that require user
    /// confirmation before listing.
    ///
    /// The default value is `100`.
    pub fn completion_query_items(&self) -> usize {
        self.lock.completion_query_items
    }

    /// Sets the `completion-query-items` variable.
    pub fn set_completion_query_items(&mut self, n: usize) {
        self.lock.completion_query_items = n;
    }

    /// Returns the timeout to wait for further user input when an ambiguous
    /// sequence has been entered. If the value is `None`, wait is indefinite.
    ///
    /// The default value 500 milliseconds.
    pub fn keyseq_timeout(&self) -> Option<Duration> {
        self.lock.keyseq_timeout
    }

    /// Sets the `keyseq-timeout` variable.
    pub fn set_keyseq_timeout(&mut self, timeout: Option<Duration>) {
        self.lock.keyseq_timeout = timeout;
    }

    /// Returns whether to list possible completions one page at a time.
    ///
    /// The default value is `true`.
    pub fn page_completions(&self) -> bool {
        self.lock.page_completions
    }

    /// Sets the `page-completions` variable.
    pub fn set_page_completions(&mut self, set: bool) {
        self.lock.page_completions = set;
    }

    /// Returns whether to list completions horizontally, rather than down
    /// the screen.
    ///
    /// The default value is `false`.
    pub fn print_completions_horizontally(&self) -> bool {
        self.lock.print_completions_horizontally
    }

    /// Sets the `print-completions-horizontally` variable.
    pub fn set_print_completions_horizontally(&mut self, set: bool) {
        self.lock.print_completions_horizontally = set;
    }

    /// Returns the set of characters that delimit strings.
    pub fn string_chars(&self) -> &str {
        &self.lock.string_chars
    }

    /// Sets the set of characters that delimit strings.
    pub fn set_string_chars<T>(&mut self, chars: T)
            where T: Into<Cow<'static, str>> {
        self.lock.string_chars = chars.into();
    }

    /// Returns the set of characters that indicate a word break.
    pub fn word_break_chars(&self) -> &str {
        &self.lock.word_break
    }

    /// Sets the set of characters that indicate a word break.
    pub fn set_word_break_chars<T>(&mut self, chars: T)
            where T: Into<Cow<'static, str>> {
        self.lock.word_break = chars.into();
    }

    /// Returns an iterator over bound sequences
    pub fn bindings(&self) -> BindingIter {
        self.lock.bindings()
    }

    /// Binds a sequence to a command.
    ///
    /// Returns the previously bound command.
    pub fn bind_sequence<T>(&mut self, seq: T, cmd: Command) -> Option<Command>
            where T: Into<Cow<'static, str>> {
        self.lock.bind_sequence(seq, cmd)
    }

    /// Binds a sequence to a command, if and only if the given sequence
    /// is not already bound to a command.
    ///
    /// Returns `true` if a new binding was created.
    pub fn bind_sequence_if_unbound<T>(&mut self, seq: T, cmd: Command) -> bool
            where T: Into<Cow<'static, str>> {
        self.lock.bind_sequence_if_unbound(seq, cmd)
    }

    /// Removes a binding for the given sequence.
    ///
    /// Returns the previously bound command.
    pub fn unbind_sequence(&mut self, seq: &str) -> Option<Command> {
        self.lock.unbind_sequence(seq)
    }

    /// Defines a named function to which sequences may be bound.
    ///
    /// The name should consist of lowercase ASCII letters and numbers,
    /// containing no spaces, with words separated by hyphens. However,
    /// this is not a requirement.
    ///
    /// Returns the function previously defined with the same name.
    pub fn define_function<T>(&mut self, name: T, cmd: Arc<Function<Term>>)
            -> Option<Arc<Function<Term>>> where T: Into<Cow<'static, str>> {
        self.lock.define_function(name, cmd)
    }

    /// Removes a function defined with the given name.
    ///
    /// Returns the defined function.
    pub fn remove_function(&mut self, name: &str) -> Option<Arc<Function<Term>>> {
        self.lock.remove_function(name)
    }

    pub(crate) fn evaluate_directives(&mut self, term: &Term, dirs: Vec<Directive>) {
        self.lock.data.evaluate_directives(term, dirs)
    }

    pub(crate) fn evaluate_directive(&mut self, term: &Term, dir: Directive) {
        self.lock.data.evaluate_directive(term, dir)
    }

    fn read_line_impl(&mut self) -> io::Result<ReadResult> {
        {
            let mut prompter = self.prompter();
            prompter.start_read_line()?;
        }

        let res = loop {
            if let Some(size) = self.lock.take_resize() {
                self.handle_resize(size)?;
            }

            if let Some(sig) = self.lock.take_signal() {
                if self.lock.report_signals.contains(sig) {
                    break ReadResult::Signal(sig);
                }
                if !self.lock.ignore_signals.contains(sig) {
                    self.handle_signal(sig)?;
                }
            }

            if !self.lock.wait_for_input(None)? {
                continue;
            }

            if let Some(ch) = self.lock.read_char()? {
                let mut prompter = self.prompter();

                if let Some(r) = prompter.handle_input(ch)? {
                    break r;
                }
            }
        };

        self.prompter().end_read_line();

        Ok(res)
    }

    fn prompter<'b>(&'b mut self) -> Prompter<'b, 'a, Term> {
        Prompter::new(
            &mut self.lock,
            self.iface.lock_write())
    }

    fn handle_resize(&mut self, size: Size) -> io::Result<()> {
        self.prompter().handle_resize(size)
    }

    fn handle_signal(&mut self, sig: Signal) -> io::Result<()> {
        self.prompter().handle_signal(sig)
    }
}

impl<'a, Term: 'a + Terminal> ReadLock<'a, Term> {
    pub fn new(term: Box<TerminalReader<Term> + 'a>, data: MutexGuard<'a, Read<Term>>)
            -> ReadLock<'a, Term> {
        ReadLock{term, data}
    }

    pub(crate) fn term(&mut self) -> &mut TerminalReader<Term> {
        &mut *self.term
    }

    /// Waits for input data from the terminal.
    ///
    /// Returns whether input data becomes available before the timeout.
    ///
    /// If queued input exists (in either the macro or input buffer),
    /// returns `Ok(true)` immediately.
    pub fn wait_for_input(&mut self, timeout: Option<Duration>) -> io::Result<bool> {
        if !self.data.macro_buffer.is_empty() ||
                first_char(&self.data.input_buffer)?.is_some() {
            Ok(true)
        } else {
            self.term.wait_for_input(timeout)
        }
    }

    /// Reads the next character of input.
    ///
    /// Performs a non-blocking read from the terminal, if necessary.
    ///
    /// If non-input data was received (e.g. a signal) or insufficient input
    /// is available, `Ok(None)` is returned.
    pub fn read_char(&mut self) -> io::Result<Option<char>> {
        if let Some(ch) = self.macro_pop() {
            return Ok(Some(ch));
        }

        loop {
            if let Some(ch) = self.decode_input()? {
                return Ok(Some(ch));
            }

            match self.term.read(&mut self.data.input_buffer)? {
                RawRead::Bytes(0) => return Ok(None),
                RawRead::Bytes(_) => continue,
                RawRead::Resize(new_size) => {
                    self.last_resize = Some(new_size);
                    continue;
                }
                RawRead::Signal(sig) => {
                    self.last_signal = Some(sig);
                    break;
                }
            }
        }

        Ok(None)
    }

    pub fn try_read_char(&mut self, timeout: Option<Duration>) -> io::Result<Option<char>> {
        if self.wait_for_input(timeout)? {
            self.read_char()
        } else {
            Ok(None)
        }
    }

    fn macro_pop(&mut self) -> Option<char> {
        if self.data.macro_buffer.is_empty() {
            None
        } else {
            Some(self.data.macro_buffer.remove(0))
        }
    }

    fn decode_input(&mut self) -> io::Result<Option<char>> {
        if self.data.input_buffer.is_empty() {
            Ok(None)
        } else {
            let r = first_char(&self.data.input_buffer);

            if let Ok(Some(ch)) = r {
                self.data.input_buffer.drain(..ch.len_utf8());
            }

            r
        }
    }

    pub fn reset_data(&mut self) {
        self.data.reset_data();
    }
}

impl<'a, Term: 'a + Terminal> Deref for ReadLock<'a, Term> {
    type Target = Read<Term>;

    fn deref(&self) -> &Read<Term> {
        &self.data
    }
}

impl<'a, Term: 'a + Terminal> DerefMut for ReadLock<'a, Term> {
    fn deref_mut(&mut self) -> &mut Read<Term> {
        &mut self.data
    }
}

impl<Term: Terminal> Deref for Read<Term> {
    type Target = Variables;

    fn deref(&self) -> &Variables {
        &self.variables
    }
}

impl<Term: Terminal> DerefMut for Read<Term> {
    fn deref_mut(&mut self) -> &mut Variables {
        &mut self.variables
    }
}

impl<Term: Terminal> Read<Term> {
    pub fn new(term: &Term, application: Cow<'static, str>) -> Read<Term> {
        let mut r = Read{
            application,

            bindings: default_bindings(),
            functions: HashMap::new(),

            input_buffer: Vec::new(),
            macro_buffer: String::new(),

            sequence: String::new(),
            input_accepted: false,

            overwrite_mode: false,
            overwritten_append: 0,
            overwritten_chars: String::new(),

            completer: Arc::new(DummyCompleter),
            completion_append_character: Some(' '),
            completions: None,
            completion_index: 0,
            completion_start: 0,
            completion_prefix: 0,

            string_chars: STRING_CHARS.into(),
            word_break: WORD_BREAK_CHARS.into(),

            last_cmd: Category::Other,
            last_yank: None,
            kill_ring: VecDeque::with_capacity(MAX_KILLS),

            catch_signals: true,
            ignore_signals: SignalSet::new(),
            report_signals: SignalSet::new(),
            last_resize: None,
            last_signal: None,

            variables: Variables::default(),
        };

        r.read_init(term);
        r
    }

    pub fn bindings(&self) -> BindingIter {
        BindingIter(self.bindings.sequences().iter())
    }

    pub fn variables(&self) -> VariableIter {
        self.variables.iter()
    }

    fn take_resize(&mut self) -> Option<Size> {
        self.last_resize.take()
    }

    fn take_signal(&mut self) -> Option<Signal> {
        self.last_signal.take()
    }

    pub fn queue_input(&mut self, seq: &str) {
        self.macro_buffer.insert_str(0, seq);
    }

    pub fn reset_data(&mut self) {
        self.input_accepted = false;
        self.overwrite_mode = false;
        self.overwritten_append = 0;
        self.overwritten_chars.clear();
        self.sequence.clear();

        self.completions = None;

        self.last_cmd = Category::Other;
        self.last_yank = None;

        self.last_resize = None;
        self.last_signal = None;
    }

    pub fn bind_sequence<T>(&mut self, seq: T, cmd: Command) -> Option<Command>
            where T: Into<Cow<'static, str>> {
        self.bindings.insert(seq.into(), cmd)
    }

    pub fn bind_sequence_if_unbound<T>(&mut self, seq: T, cmd: Command) -> bool
            where T: Into<Cow<'static, str>> {
        use mortal::sequence::Entry;

        match self.bindings.entry(seq.into()) {
            Entry::Occupied(_) => false,
            Entry::Vacant(ent) => {
                ent.insert(cmd);
                true
            }
        }
    }

    pub fn unbind_sequence(&mut self, seq: &str) -> Option<Command> {
        self.bindings.remove(seq)
            .map(|(_, cmd)| cmd)
    }

    pub fn define_function<T>(&mut self, name: T, cmd: Arc<Function<Term>>)
            -> Option<Arc<Function<Term>>> where T: Into<Cow<'static, str>> {
        self.functions.insert(name.into(), cmd)
    }

    pub fn remove_function(&mut self, name: &str) -> Option<Arc<Function<Term>>> {
        self.functions.remove(name)
    }

    fn read_init(&mut self, term: &Term) {
        if let Some(path) = env_init_file() {
            // If `INPUTRC` is present, even if invalid, parse nothing else.
            // Thus, an empty `INPUTRC` will inhibit loading configuration.
            self.read_init_file_if_exists(term, Some(path));
        } else {
            if !self.read_init_file_if_exists(term, user_init_file()) {
                self.read_init_file_if_exists(term, system_init_file());
            }
        }
    }

    fn read_init_file_if_exists(&mut self, term: &Term, path: Option<PathBuf>) -> bool {
        match path {
            Some(ref path) if path.exists() => {
                self.read_init_file(term, path);
                true
            }
            _ => false
        }
    }

    fn read_init_file(&mut self, term: &Term, path: &Path) {
        if let Some(dirs) = parse_file(path) {
            self.evaluate_directives(term, dirs);
        }
    }

    /// Evaluates a series of configuration directives.
    pub(crate) fn evaluate_directives(&mut self, term: &Term, dirs: Vec<Directive>) {
        for dir in dirs {
            self.evaluate_directive(term, dir);
        }
    }

    /// Evaluates a single configuration directive.
    pub(crate) fn evaluate_directive(&mut self, term: &Term, dir: Directive) {
        match dir {
            Directive::Bind(seq, cmd) => {
                self.bind_sequence(seq, cmd);
            }
            Directive::Conditional{name, value, then_group, else_group} => {
                let name = name.as_ref().map(|s| &s[..]);

                if self.eval_condition(term, name, &value) {
                    self.evaluate_directives(term, then_group);
                } else {
                    self.evaluate_directives(term, else_group);
                }
            }
            Directive::SetVariable(name, value) => {
                self.set_variable(&name, &value);
            }
        }
    }

    fn eval_condition(&self, term: &Term, name: Option<&str>, value: &str) -> bool {
        match name {
            None => self.application == value,
            Some("lib") => value == "linefeed",
            Some("mode") => value == "emacs",
            Some("term") => self.term_matches(term, value),
            _ => false
        }
    }

    fn term_matches(&self, term: &Term, value: &str) -> bool {
        match_name(term.name(), value)
    }
}

/// Iterator over `Reader` bindings
pub struct BindingIter<'a>(slice::Iter<'a, (Cow<'static, str>, Command)>);

impl<'a> ExactSizeIterator for BindingIter<'a> {}

impl<'a> Iterator for BindingIter<'a> {
    type Item = (&'a str, &'a Command);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|&(ref s, ref cmd)| (&s[..], cmd))
    }

    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.0.nth(n).map(|&(ref s, ref cmd)| (&s[..], cmd))
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl<'a> DoubleEndedIterator for BindingIter<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.next_back().map(|&(ref s, ref cmd)| (&s[..], cmd))
    }
}

fn default_bindings() -> SequenceMap<Cow<'static, str>, Command> {
    use command::Command::*;

    SequenceMap::from(vec![
        // Carriage return and line feed
        ("\r".into(), AcceptLine),
        ("\n".into(), AcceptLine),

        // Possible sequences for arrow keys, Home, End
        ("\x1b[A".into(), PreviousHistory),
        ("\x1b[B".into(), NextHistory),
        ("\x1b[C".into(), ForwardChar),
        ("\x1b[D".into(), BackwardChar),
        ("\x1b[H".into(), BeginningOfLine),
        ("\x1b[F".into(), EndOfLine),

        // More possible sequences for arrow keys, Home, End
        ("\x1bOA".into(), PreviousHistory),
        ("\x1bOB".into(), NextHistory),
        ("\x1bOC".into(), ForwardChar),
        ("\x1bOD".into(), BackwardChar),
        ("\x1bOH".into(), BeginningOfLine),
        ("\x1bOF".into(), EndOfLine),

        // Possible sequences for Insert, Delete
        ("\x1b[2~".into(), OverwriteMode),
        ("\x1b[3~".into(), DeleteChar),

        // Basic commands
        ("\x01"    .into(), BeginningOfLine),           // Ctrl-A
        ("\x02"    .into(), BackwardChar),              // Ctrl-B
        ("\x04"    .into(), DeleteChar),                // Ctrl-D
        ("\x05"    .into(), EndOfLine),                 // Ctrl-E
        ("\x06"    .into(), ForwardChar),               // Ctrl-F
        ("\x07"    .into(), Abort),                     // Ctrl-G
        ("\x08"    .into(), BackwardDeleteChar),        // Ctrl-H
        ("\x0b"    .into(), KillLine),                  // Ctrl-K
        ("\x0c"    .into(), ClearScreen),               // Ctrl-L
        ("\x0e"    .into(), NextHistory),               // Ctrl-N
        ("\x10"    .into(), PreviousHistory),           // Ctrl-P
        ("\x12"    .into(), ReverseSearchHistory),      // Ctrl-R
        ("\x14"    .into(), TransposeChars),            // Ctrl-T
        ("\x15"    .into(), BackwardKillLine),          // Ctrl-U
        ("\x16"    .into(), QuotedInsert),              // Ctrl-V
        ("\x17"    .into(), UnixWordRubout),            // Ctrl-W
        ("\x19"    .into(), Yank),                      // Ctrl-Y
        ("\x1d"    .into(), CharacterSearch),           // Ctrl-]
        ("\x7f"    .into(), BackwardDeleteChar),        // Rubout
        ("\x1b\x08".into(), BackwardKillWord),          // Escape, Ctrl-H
        ("\x1b\x1d".into(), CharacterSearchBackward),   // Escape, Ctrl-]
        ("\x1b\x7f".into(), BackwardKillWord),          // Escape, Rubout
        ("\x1bb"   .into(), BackwardWord),              // Escape, b
        ("\x1bd"   .into(), KillWord),                  // Escape, d
        ("\x1bf"   .into(), ForwardWord),               // Escape, f
        ("\x1bt"   .into(), TransposeWords),            // Escape, t
        ("\x1by"   .into(), YankPop),                   // Escape, y
        ("\x1b#"   .into(), InsertComment),             // Escape, #
        ("\x1b<"   .into(), BeginningOfHistory),        // Escape, <
        ("\x1b>"   .into(), EndOfHistory),              // Escape, >

        // Completion commands
        ("\t"   .into(), Complete),             // Tab
        ("\x1b?".into(), PossibleCompletions),  // Escape, ?
        ("\x1b*".into(), InsertCompletions),    // Escape, *

        // Digit commands
        ("\x1b-".into(), DigitArgument),    // Escape, -
        ("\x1b0".into(), DigitArgument),    // Escape, 0
        ("\x1b1".into(), DigitArgument),    // Escape, 1
        ("\x1b2".into(), DigitArgument),    // Escape, 2
        ("\x1b3".into(), DigitArgument),    // Escape, 3
        ("\x1b4".into(), DigitArgument),    // Escape, 4
        ("\x1b5".into(), DigitArgument),    // Escape, 5
        ("\x1b6".into(), DigitArgument),    // Escape, 6
        ("\x1b7".into(), DigitArgument),    // Escape, 7
        ("\x1b8".into(), DigitArgument),    // Escape, 8
        ("\x1b9".into(), DigitArgument),    // Escape, 9
    ])
}