readline_ttytter.pm untested

filter: Statementstmt 0.0% 0 / 771 Branchbran 0.0% 0 / 510 Conditioncond 0.0% 0 / 286 MC/DCmcdc 0.0% 0 / 166 Subroutinesub 0.0% 0 / 119 Podpod 0.0% 0 / 111 totaltotal 0.0% 0 / 1963 CC 256 SCAR 69.5
CC
256
Cov
0%
preinit
3540.0
redisplay
1560.0
readline
812.0
CRAP 1046.4
1 require 5.006;
2  
3 ##
4 ## Term::Readline::Perl -> Term::Readline::TTYtter (Cameron Kaiser)
5 ## it's much better.
6 ## Same license as T::RL::Perl. But awesome.
7 ## Fixes: UTF-8 safe now (crosses fingers) on Mac OS X, Ubuntu and more
8 ## Upgrades: Repaintable readline/removeable readline, signal chaining,
9 ## character count.
10 ##
11 ############################################################################
12 ##
13 ## Perl Readline -- The Quick Help
14 ## (see the manual for complete info)
15 ##
16 ## Once this package is included (require'd), you can then call
17 ## $text = &readline'readline($input);
18 ## to get lines of input from the user.
19 ##
20 ## Normally, it reads ~/.inputrc when loaded... to suppress this, set
21 ## $readline'rl_NoInitFromFile = 1;
22 ## before requiring the package.
23 ##
24 ## Call rl_bind to add your own key bindings, as in
25 ## &readline'rl_bind('C-L', 'possible-completions');
26 ##
27 ## Call rl_set to set mode variables yourself, as in
28 ## &readline'rl_set('TcshCompleteMode', 'On');
29 ##
30 ## To change the input mode (emacs or vi) use ~/.inputrc or call
31 ## &readline::rl_set('EditingMode', 'vi');
32 ## or &readline::rl_set('EditingMode', 'emacs');
33 ##
34 ## Call rl_basic_commands to set your own command completion, as in
35 ## &readline'rl_basic_commands('print', 'list', 'quit', 'run', 'status');
36 ##
37 ##
38  
39 # Wrap the code below (initially Perl4, now partially Perl4) into a fake
40 # Perl5 pseudo-module; mismatch of package and file name is intentional
41 # to make is harder to abuse this (very fragile) code...
42 package readline_ttytter;
43  
44 my $autoload_broken = 1; # currently: defined does not work with a-l
45 my $useioctl = 1;
46 my $usestty = 1;
47 my $max_include_depth = 10; # follow $include's in init files this deep
48 my $background_control = 0; # see hook_background_control
49  
50 eval 'use POSIX; $readline_ttytter::SIGUSR1 = POSIX::SIGUSR1';
51 $SIGUSR1 ||= 30;
52  
53 BEGIN { # Some old systems have ioctl "unsupported"
54 *ioctl = sub ($$$) { eval { ioctl $_[0], $_[1], $_[2] } };
55 }
56  
57 ##
58 ## BLURB:
59 ## A pretty full-function package similar to GNU's readline.
60 ## Includes support for EUC-encoded Japanese text.
61 ##
62 ## Written by Jeffrey Friedl, Omron Corporation (jfriedl@omron.co.jp)
63 ##
64 ## Comments, corrections welcome.
65 ##
66 ## Thanks to the people at FSF for readline (and the code I referenced
67 ## while writing this), and for Roland Schemers whose line_edit.pl I used
68 ## as an early basis for this.
69 ##
70 $VERSION = $VERSION = '1.4';
71  
72 ## - Changes from Slaven Rezic (slaven@rezic.de):
73 ## * reverted the usage of $ENV{EDITOR} to set startup mode
74 ## only ~/.inputrc or an explicit call to rl_set should
75 ## be used to set startup mode
76 ##
77 # 1011109.011 - Changes from Russ Southern (russ@dvns.com):
78 ## * Added $rl_vi_replace_default_on_insert
79 # 1000510.010 - Changes from Joe Petolino (petolino@eng.sun.com), requested
80 ## by Ilya:
81 ##
82 ## * Make it compatible with perl 5.003.
83 ## * Rename getc() to getc_with_pending().
84 ## * Change unshift(@Pending) to push(@Pending).
85 ##
86 ## 991109.009 - Changes from Joe Petolino (petolino@eng.sun.com):
87 ## Added vi mode. Also added a way to set the keymap default
88 ## action for multi-character keymaps, so that a 2-character
89 ## sequence (e.g. <esc>A) can be treated as two one-character
90 ## commands (<esc>, then A) if the sequence is not explicitly
91 ## mapped.
92 ##
93 ## Changed subs:
94 ##
95 ## * preinit(): Initialize new keymaps and other data structures.
96 ## Use $ENV{EDITOR} to set startup mode.
97 ##
98 ## * init(): Sets the global *KeyMap, since &F_ReReadInitFile
99 ## may have changed the key map.
100 ##
101 ## * InitKeymap(): $KeyMap{default} is now optional - don't
102 ## set it if $_[1] eq '';
103 ##
104 ## * actually_do_binding(): Set $KeyMap{default} for '\*' key;
105 ## warning if double-defined.
106 ##
107 ## * rl_bind(): Implement \* to set the keymap default. Also fix
108 ## some existing regex bugs that I happened to notice.
109 ##
110 ## * readline(): No longer takes input from $pending before
111 ## calling &$rl_getc(); instead, it calls getc_with_pending(),
112 ## which takes input from the new array @Pending
113 ## before calling &$rl_getc(). Sets the global
114 ## *KeyMap after do_command(), since do_command()
115 ## may change the keymap now. Does some cursor
116 ## manipulation after do_command() when at the end
117 ## of the line in vi command mode, to match the
118 ## behavior of vi.
119 ##
120 ## * rl_getc(): Added a my declaration for $key, which was
121 ## apparently omitted by the author. rl_getc() is
122 ## no longer called directly; instead, getc_with_pending() calls
123 ## it only after exhausting any requeued characters
124 ## in @Pending. @Pending is used to implement the
125 ## vi '.' command, as well as the emacs DoSearch
126 ## functionality.
127 ##
128 ## * do_command(): Now defaults the command to 'F_Ding' if
129 ## $KeyMap{default} is undefined. This is part
130 ## of the new \* feature.
131 ##
132 ## * savestate()/getstate(): Now use an anonymous array instead
133 ## of packing the fields into a string.
134 ##
135 ## * F_AcceptLine(): Code moved to new sub add_line_to_history(),
136 ## so that it may be called by F_SaveLine()
137 ## as well as by F_AcceptLine().
138 ##
139 ## * F_QuotedInsert(): Calls getc_with_pending() instead of &$rl_getc().
140 ##
141 ## * F_UnixWordRubout(): Fixed bug: changed 'my' declaration of
142 ## global $rl_basic_word_break_characters to 'local'.
143 ##
144 ## * DoSearch(): Calls getc_with_pending() instead of &$rl_getc(). Ungets
145 ## character onto @Pending instead of $pending.
146 ##
147 ## * F_EmacsEditingMode(): Resets global $Vi_mode;
148 ##
149 ## * F_ToggleEditingMode(): Deleted. We use F_ViInput() and
150 ## F_EmacsEditingMode() instead.
151 ##
152 ## * F_PrefixMeta(): Calls getc_with_pending() instead of &$rl_getc().
153 ##
154 ## * F_DigitArgument(): Calls getc_with_pending() instead of &$rl_getc().
155 ##
156 ## * F_Ding(): Returns undef, for testing by vi commands.
157 ##
158 ## * F_Complete(): Returns true if a completion was done, false
159 ## otherwise, so vi completion routines can test it.
160 ##
161 ## * complete_internal(): Returns true if a completion was done,
162 ## false otherwise, so vi completion routines can
163 ## test it. Does a little cursor massaging in vi
164 ## mode, to match the behavior of ksh vi mode.
165 ##
166 ## Disclaimer: the original code dates from the perl 4 days, and
167 ## isn't very pretty by today's standards (for example,
168 ## extensive use of typeglobs and localized globals). In the
169 ## interests of not breaking anything, I've tried to preserve
170 ## the old code as much as possible, and I've avoided making
171 ## major stylistic changes. Since I'm not a regular emacs user,
172 ## I haven't done much testing to see that all the emacs-mode
173 ## features still work.
174 ##
175 ## 940817.008 - Added $var_CompleteAddsuffix.
176 ## Now recognizes window-change signals (at least on BSD).
177 ## Various typos and bug fixes.
178 ## Changes from Chris Arthur (csa@halcyon.com):
179 ## Added a few new keybindings.
180 ## Various typos and bug fixes.
181 ## Support for use from a dumb terminal.
182 ## Pretty-printing of filename-completion matches.
183 ##
184 ## 930306.007 - Added rl_start_default_at_beginning.
185 ## Added optional message arg to &redisplay.
186 ## Added explicit numeric argument var to functions that use it.
187 ## Redid many commands to simplify.
188 ## Added TransposeChars, UpcaseWord, CapitalizeWord, DownCaseWord.
189 ## Redid key binding specs to better match GNU.. added
190 ## undocumented "new-style" bindings.... can now bind
191 ## arrow keys and other arbitrairly long key sequences.
192 ## Added if/else/then to .inputrc.
193 ##
194 ## 930305.006 - optional "default" added (from mmuegel@cssmp.corp.mot.com).
195 ##
196 ## 930211.005 - fixed strange problem with eval while keybinding
197 ##
198  
199 ##
200 ## Ilya:
201 ##
202 ## Added support for ReadKey,
203 ##
204 ## Added customization variable $minlength
205 ## to denote minimal lenth of a string to be put into history buffer.
206 ##
207 ## Added support for a bug in debugger: preinit cannot be a subroutine ?!!!
208 ## (See immendiately below)
209 ##
210 ## Added support for WINCH hooks. The subroutine references should be put into
211 ## @winchhooks.
212 ##
213 ## Added F_ToggleInsertMode, F_HistorySearchBackward,
214 ## F_HistorySearchForward, PC keyboard bindings.
215 ## 0.93: Updates to Operate, couple of keybindings added.
216 ## $rl_completer_terminator_character, $rl_correct_sw added.
217 ## Reload-init-file moved to C-x C-x.
218 ## C-x ? and C-x * list/insert possible completions.
219  
220 $rl_getc = \&rl_getc;
221  
222 &preinit;
223 &init;
224  
225 # # # # use strict 'vars';
226  
227 # # # # # Separation into my and vars needs some thought...
228  
229 # # # # use vars qw(@KeyMap %KeyMap $rl_screen_width $rl_start_default_at_beginning
230 # # # # $rl_completion_function $rl_basic_word_break_characters
231 # # # # $rl_completer_word_break_characters $rl_special_prefixes
232 # # # # $rl_readline_name @rl_History $rl_MaxHistorySize
233 # # # # $rl_max_numeric_arg $rl_OperateCount
234 # # # # $KillBuffer $dumb_term $stdin_not_tty $InsertMode
235 # # # # $rl_NoInitFromFile);
236  
237 # # # # my ($InputLocMsg, $term_OUT, $term_IN);
238 # # # # my ($winsz_t, $TIOCGWINSZ, $winsz, $rl_margin, $hooj, $force_redraw);
239 # # # # my ($hook, %var_HorizontalScrollMode, %var_EditingMode, %var_OutputMeta);
240 # # # # my ($var_HorizontalScrollMode, $var_EditingMode, $var_OutputMeta);
241 # # # # my (%var_ConvertMeta, $var_ConvertMeta, %var_MarkModifiedLines, $var_MarkModifiedLines);
242 # # # # my ($term_readkey, $inDOS);
243 # # # # my (%var_PreferVisibleBell, $var_PreferVisibleBell);
244 # # # # my (%var_TcshCompleteMode, $var_TcshCompleteMode);
245 # # # # my (%var_CompleteAddsuffix, $var_CompleteAddsuffix);
246 # # # # my ($minlength, @winchhooks);
247 # # # # my ($BRKINT, $ECHO, $FIONREAD, $ICANON, $ICRNL, $IGNBRK, $IGNCR, $INLCR,
248 # # # # $ISIG, $ISTRIP, $NCCS, $OPOST, $RAW, $TCGETS, $TCOON, $TCSETS, $TCXONC,
249 # # # # $TERMIOS_CFLAG, $TERMIOS_IFLAG, $TERMIOS_LFLAG, $TERMIOS_NORMAL_IOFF,
250 # # # # $TERMIOS_NORMAL_ION, $TERMIOS_NORMAL_LOFF, $TERMIOS_NORMAL_LON,
251 # # # # $TERMIOS_NORMAL_OOFF, $TERMIOS_NORMAL_OON, $TERMIOS_OFLAG,
252 # # # # $TERMIOS_READLINE_IOFF, $TERMIOS_READLINE_ION, $TERMIOS_READLINE_LOFF,
253 # # # # $TERMIOS_READLINE_LON, $TERMIOS_READLINE_OOFF, $TERMIOS_READLINE_OON,
254 # # # # $TERMIOS_VMIN, $TERMIOS_VTIME, $TIOCGETP, $TIOCGWINSZ, $TIOCSETP,
255 # # # # $fion, $fionread_t, $mode, $sgttyb_t,
256 # # # # $termios, $termios_t, $winsz, $winsz_t);
257 # # # # my ($line, $initialized, $term_readkey);
258  
259  
260 # # # # # Global variables added for vi mode (I'm leaving them all commented
261 # # # # # out, like the declarations above, until SelfLoader issues
262 # # # # # are resolved).
263  
264 # # # # # True when we're in one of the vi modes.
265 # # # # my $Vi_mode;
266  
267 # # # # # Array refs: saves keystrokes for '.' command. Undefined when we're
268 # # # # # not doing a '.'-able command.
269 # # # # my $Dot_buf; # Working buffer
270 # # # # my $Last_vi_command; # Gets $Dot_buf when a command is parsed
271  
272 # # # # # These hold state for vi 'u' and 'U'.
273 # # # # my($Dot_state, $Vi_undo_state, $Vi_undo_all_state);
274  
275 # # # # # Refs to hashes used for cursor movement
276 # # # # my($Vi_delete_patterns, $Vi_move_patterns,
277 # # # # $Vi_change_patterns, $Vi_yank_patterns);
278  
279 # # # # # Array ref: holds parameters from the last [fFtT] command, for ';'
280 # # # # # and ','.
281 # # # # my $Last_findchar;
282  
283 # # # # # Globals for history search commands (/, ?, n, N)
284 # # # # my $Vi_search_re; # Regular expression (compiled by qr{})
285 # # # # my $Vi_search_reverse; # True for '?' search, false for '/'
286  
287  
288 ##
289 ## What's Cool
290 ## ----------------------------------------------------------------------
291 ## * hey, it's in perl.
292 ## * Pretty full GNU readline like library...
293 ## * support for ~/.inputrc
294 ## * horizontal scrolling
295 ## * command/file completion
296 ## * rebinding
297 ## * history (with search)
298 ## * undo
299 ## * numeric prefixes
300 ## * supports multi-byte characters (at least for the Japanese I use).
301 ## * Has a tcsh-like completion-function mode.
302 ## call &readline'rl_set('tcsh-complete-mode', 'On') to turn on.
303 ##
304  
305 ##
306 ## What's not Cool
307 ## ----------------------------------------------------------------------
308 ## Can you say HUGE?
309 ## I can't spell, so comments riddled with misspellings.
310 ## Written by someone that has never really used readline.
311 ## History mechanism is slightly different than GNU... may get fixed
312 ## someday, but I like it as it is now...
313 ## Killbuffer not a ring.. just one level.
314 ## Obviously not well tested yet.
315 ## Written by someone that doesn't have a bell on his terminal, so
316 ## proper readline use of the bell may not be here.
317 ##
318  
319  
320 ##
321 ## Functions beginning with F_ are functions that are mapped to keys.
322 ## Variables and functions beginning rl_ may be accessed/set/called/read
323 ## from outside the package. Other things are internal.
324 ##
325 ## Some notable internal-only variables of global proportions:
326 ## $prompt -- line prompt (passed from user)
327 ## $line -- the line being input
328 ## $D -- ``Dot'' -- index into $line of the cursor's location.
329 ## $InsertMode -- usually true. False means overwrite mode.
330 ## $InputLocMsg -- string for error messages, such as "[~/.inputrc line 2]"
331 ## *emacs_keymap -- keymap for emacs-mode bindings:
332 ## @emacs_keymap - bindings indexed by ASCII ordinal
333 ## $emacs_keymap{'name'} = "emacs_keymap"
334 ## $emacs_keymap{'default'} = "SelfInsert" (default binding)
335 ## *vi_keymap -- keymap for vi input mode bindings
336 ## *vicmd_keymap -- keymap for vi command mode bindings
337 ## *vipos_keymap -- keymap for vi positioning command bindings
338 ## *visearch_keymap -- keymap for vi search pattern input mode bindings
339 ## *KeyMap -- current keymap in effect.
340 ## $LastCommandKilledText -- needed so that subsequent kills accumulate
341 ## $lastcommand -- name of command previously run
342 ## $lastredisplay -- text placed upon screen during previous &redisplay
343 ## $si -- ``screen index''; index into $line of leftmost char &redisplay'ed
344 ## $force_redraw -- if set to true, causes &redisplay to be verbose.
345 ## $AcceptLine -- when set, its value is returned from &readline.
346 ## $ReturnEOF -- unless this also set, in which case undef is returned.
347 ## @Pending -- characters to be used as input.
348 ## @undo -- array holding all states of current line, for undoing.
349 ## $KillBuffer -- top of kill ring (well, don't have a kill ring yet)
350 ## @tcsh_complete_selections -- for tcsh mode, possible selections
351 ##
352 ## Some internal variables modified by &rl_set (see comment at &rl_set for
353 ## info about how these set'able variables work)
354 ## $var_EditingMode -- a keymap typeglob like *emacs_keymap or *vi_keymap
355 ## $var_TcshCompleteMode -- if true, the completion function works like
356 ## in tcsh. That is, the first time you try to complete something,
357 ## the common prefix is completed for you. Subsequent completion tries
358 ## (without other commands in between) cycles the command line through
359 ## the various possibilities. If/when you get the one you want, just
360 ## continue typing.
361 ## Other $var_ things not supported yet.
362 ##
363 ## Some variables used internally, but may be accessed from outside...
364 ## $VERSION -- just for good looks.
365 ## $rl_readline_name = name of program -- for .initrc if/endif stuff.
366 ## $rl_NoInitFromFile -- if defined when package is require'd, ~/.inputrc
367 ## will not be read.
368 ## @rl_History -- array of previous lines input
369 ## $rl_HistoryIndex -- history pointer (for moving about history array)
370 ## $rl_completion_function -- see "How Command Completion Works" (way) below.
371 ## $rl_basic_word_break_characters -- string of characters that can cause
372 ## a word break for forward-word, etc.
373 ## $rl_start_default_at_beginning --
374 ## Normally, the user's cursor starts at the end of any default text
375 ## passed to readline. If this variable is true, it starts at the
376 ## beginning.
377 ## $rl_completer_word_break_characters --
378 ## like $rl_basic_word_break_characters (and in fact defaults to it),
379 ## but for the completion function.
380 ## $rl_completer_terminator_character -- what to insert to separate
381 ## a completed token from the rest. Reset at beginning of
382 ## completion to ' ' so completion function can change it.
383 ## $rl_special_prefixes -- characters that are part of this string as well
384 ## as of $rl_completer_word_break_characters cause a word break for the
385 ## completer function, but remain part of the word. An example: consider
386 ## when the input might be perl code, and one wants to be able to
387 ## complete on variable and function names, yet still have the '$',
388 ## '&', '@',etc. part of the $text to be completed. Then set this var
389 ## to '&@$%' and make sure each of these characters is in
390 ## $rl_completer_word_break_characters as well....
391 ## $rl_MaxHistorySize -- maximum size that the history array may grow.
392 ## $rl_screen_width -- width readline thinks it can use on the screen.
393 ## $rl_correct_sw -- is substructed from the real width of the terminal
394 ## $rl_margin -- scroll by moving to within this far from a margin.
395 ## $rl_CLEAR -- what to output to clear the screen.
396 ## $rl_max_numeric_arg -- maximum numeric arg allowed.
397 ## $rl_vi_replace_default_on_insert
398 ## Normally, the text you enter is added to any default text passed to
399 ## readline. If this variable is true, default text will start out
400 ## highlighted (if supported by your terminal) and text entered while the
401 ## default is highlighted (during the _first_ insert mode only) will
402 ## replace the entire default line. Once you have left insert mode (hit
403 ## escape), everything works as normal.
404 ## - This is similar to many GUI controls' behavior, which select the
405 ## default text so that new text replaces the old.
406 ## - Use with $rl_start_default_at_beginning for normal-looking behavior
407 ## (though it works just fine without it).
408 ## Notes/Bugs:
409 ## - Control characters (like C-w) do not actually terminate this replace
410 ## mode, for the same reason it does not work in emacs mode.
411 ## - Spine-crawlingly scary subroutine redefinitions
412 ## $rl_mark - start of the region
413 ## $line_rl_mark - the line on which $rl_mark is active
414 ## $_rl_japanese_mb - For character movement suppose Japanese (which?!)
415 ## multi-byte encoding. (How to make a sane default?)
416 ##
417  
418 sub get_window_size
419 {
420 return unless (-t $term_OUT);
421  
422 my $sig = shift;
423 my ($num_cols,$num_rows);
424 local($., $@, $!, $^E, $?);
425  
426 if (defined $term_readkey) {
427 ($num_cols,$num_rows) = Term::ReadKey::GetTerminalSize($term_OUT);
428 $rl_screen_width = $num_cols - $rl_correct_sw
429 if defined($num_cols) && $num_cols;
430 } elsif (defined $TIOCGWINSZ and &ioctl($term_IN,$TIOCGWINSZ,$winsz)) {
431 ($num_rows,$num_cols) = unpack($winsz_t,$winsz);
432 $rl_screen_width = $num_cols - $rl_correct_sw
433 if defined($num_cols) && $num_cols;
434 }
435 $rl_margin = int($rl_screen_width/3);
436 if (defined $sig) {
437 $force_redraw = 1;
438 &redisplay();
439 }
440  
441 for $hook (@winchhooks) {
442 eval {&$hook()}; warn $@ if $@ and $^W;
443 }
444 local $^W = 0; # WINCH may be illegal...
445 $SIG{'WINCH'} = "readline_ttytter::get_window_size";
446 }
447  
448 # Fix: case-sensitivity of inputrc on/off keywords in
449 # `set' commands. readline lib doesn't care about case.
450 # changed case of keys 'On' and 'Off' to 'on' and 'off'
451 # &rl_set changed so that it converts the value to
452 # lower case before hash lookup.
453 sub preinit
454 {
455 ## Set up the input and output handles
456  
457 $term_IN = \*STDIN unless defined $term_IN;
458 $term_OUT = \*STDOUT unless defined $term_OUT;
459 ## not yet supported... always on.
460 $var_HorizontalScrollMode = 1;
461 $var_HorizontalScrollMode{'On'} = 1;
462 $var_HorizontalScrollMode{'Off'} = 0;
463  
464 $var_EditingMode{'emacs'} = *emacs_keymap;
465 $var_EditingMode{'vi'} = *vi_keymap;
466 $var_EditingMode{'vicmd'} = *vicmd_keymap;
467 $var_EditingMode{'vipos'} = *vipos_keymap;
468 $var_EditingMode{'visearch'} = *visearch_keymap;
469  
470 ## this is an addition. Very nice.
471 $var_TcshCompleteMode = 0;
472 $var_TcshCompleteMode{'On'} = 1;
473 $var_TcshCompleteMode{'Off'} = 0;
474  
475 $var_CompleteAddsuffix = 1;
476 $var_CompleteAddsuffix{'On'} = 1;
477 $var_CompleteAddsuffix{'Off'} = 0;
478  
479 $var_DeleteSelection = $var_DeleteSelection{'On'} = 1;
480 $var_DeleteSelection{'Off'} = 0;
481 *rl_delete_selection = \$var_DeleteSelection; # Alias
482  
483 ## not yet supported... always on
484 for ('InputMeta', 'OutputMeta') {
485 ${"var_$_"} = 1;
486 ${"var_$_"}{'Off'} = 0;
487 ${"var_$_"}{'On'} = 1;
488 }
489  
490 ## not yet supported... always off
491 for ('ConvertMeta', 'MetaFlag', 'MarkModifiedLines', 'PreferVisibleBell',
492 'BlinkMatchingParen', 'VisibleStats', 'ShowAllIfAmbiguous',
493 'PrintCompletionsHorizontally', 'MarkDirectories', 'ExpandTilde',
494 'EnableKeypad', 'DisableCompletion', 'CompletionIgnoreCase') {
495 ${"var_$_"} = 0;
496 ${"var_$_"}{'Off'} = 0;
497 ${"var_$_"}{'On'} = 1;
498 }
499  
500 # To conform to interface
501 $minlength = 1 unless defined $minlength;
502  
503 # WINCH hooks
504 @winchhooks = ();
505  
506 $inDOS = $^O eq 'os2' || defined $ENV{OS2_SHELL} unless defined $inDOS;
507 eval {
508 require Term::ReadKey; $term_readkey++;
509 } unless defined $ENV{PERL_RL_USE_TRK}
510 and not $ENV{PERL_RL_USE_TRK};
511 unless ($term_readkey) {
512 eval {require "ioctl.pl"}; ## try to get, don't die if not found.
513 eval {require "sys/ioctl.ph"}; ## try to get, don't die if not found.
514 eval {require "sgtty.ph"}; ## try to get, don't die if not found.
515 if ($inDOS and !defined $TIOCGWINSZ) {
516 $TIOCGWINSZ=0;
517 $TIOCGETP=1;
518 $TIOCSETP=2;
519 $sgttyb_t="I5 C8";
520 $winsz_t="";
521 $RAW=0xf002;
522 $ECHO=0x0008;
523 }
524 $TIOCGETP = &TIOCGETP if defined(&TIOCGETP);
525 $TIOCSETP = &TIOCSETP if defined(&TIOCSETP);
526 $TIOCGWINSZ = &TIOCGWINSZ if defined(&TIOCGWINSZ);
527 $FIONREAD = &FIONREAD if defined(&FIONREAD);
528 $TCGETS = &TCGETS if defined(&TCGETS);
529 $TCSETS = &TCSETS if defined(&TCSETS);
530 $TCXONC = &TCXONC if defined(&TCXONC);
531 $TIOCGETP = 0x40067408 if !defined($TIOCGETP);
532 $TIOCSETP = 0x80067409 if !defined($TIOCSETP);
533 $TIOCGWINSZ = 0x40087468 if !defined($TIOCGWINSZ);
534 $FIONREAD = 0x4004667f if !defined($FIONREAD);
535 $TCGETS = 0x40245408 if !defined($TCGETS);
536 $TCSETS = 0x80245409 if !defined($TCSETS);
537 $TCXONC = 0x20005406 if !defined($TCXONC);
538  
539 ## TTY modes
540 $ECHO = &ECHO if defined(&ECHO);
541 $RAW = &RAW if defined(&RAW);
542 $RAW = 040 if !defined($RAW);
543 $ECHO = 010 if !defined($ECHO);
544 #$CBREAK = 002 if !defined($CBREAK);
545 $mode = $RAW; ## could choose CBREAK for testing....
546  
547 $IGNBRK = 1 if !defined($IGNBRK);
548 $BRKINT = 2 if !defined($BRKINT);
549 $ISTRIP = 040 if !defined($ISTRIP);
550 $INLCR = 0100 if !defined($INLCR);
551 $IGNCR = 0200 if !defined($IGNCR);
552 $ICRNL = 0400 if !defined($ICRNL);
553 $OPOST = 1 if !defined($OPOST);
554 $ISIG = 1 if !defined($ISIG);
555 $ICANON = 2 if !defined($ICANON);
556 $TCOON = 1 if !defined($TCOON);
557 $TERMIOS_READLINE_ION = $BRKINT;
558 $TERMIOS_READLINE_IOFF = $IGNBRK | $ISTRIP | $INLCR | $IGNCR | $ICRNL;
559 $TERMIOS_READLINE_OON = 0;
560 $TERMIOS_READLINE_OOFF = $OPOST;
561 $TERMIOS_READLINE_LON = 0;
562 $TERMIOS_READLINE_LOFF = $ISIG | $ICANON | $ECHO;
563 $TERMIOS_NORMAL_ION = $BRKINT;
564 $TERMIOS_NORMAL_IOFF = $IGNBRK;
565 $TERMIOS_NORMAL_OON = $OPOST;
566 $TERMIOS_NORMAL_OOFF = 0;
567 $TERMIOS_NORMAL_LON = $ISIG | $ICANON | $ECHO;
568 $TERMIOS_NORMAL_LOFF = 0;
569  
570 #$sgttyb_t = 'C4 S';
571 #$winsz_t = "S S S S"; # rows,cols, xpixel, ypixel
572 $sgttyb_t = 'C4 S' if !defined($sgttyb_t);
573 $winsz_t = "S S S S" if !defined($winsz_t);
574 # rows,cols, xpixel, ypixel
575 $winsz = pack($winsz_t,0,0,0,0);
576 $fionread_t = "L";
577 $fion = pack($fionread_t, 0);
578 $NCCS = 17;
579 $termios_t = "LLLLc" . ("c" x $NCCS); # true for SunOS 4.1.3, at least...
580 $termios = ''; ## just to shut up "perl -w".
581 $termios = pack($termios, 0); # who cares, just make it long enough
582 $TERMIOS_IFLAG = 0;
583 $TERMIOS_OFLAG = 1;
584 $TERMIOS_CFLAG = 2;
585 $TERMIOS_LFLAG = 3;
586 $TERMIOS_VMIN = 5 + 4;
587 $TERMIOS_VTIME = 5 + 5;
588 }
589 $rl_delete_selection = 1;
590 $rl_correct_sw = ($inDOS ? 1 : 0);
591 $rl_scroll_nextline = 0 unless defined $rl_scroll_nextline;
592 $rl_last_pos_can_backspace = ($inDOS ? 0 : 1) # Can backspace when the
593 unless defined $rl_last_pos_can_backspace; # whole line is filled?
594  
595 $rl_start_default_at_beginning = 0;
596 $rl_vi_replace_default_on_insert = 0;
597 $rl_screen_width = 79; ## default
598  
599 $rl_completion_function = "rl_filename_list"
600 unless defined($rl_completion_function);
601 $rl_basic_word_break_characters = "\\\t\n' \"`\@\$><=;|&{(";
602 $rl_completer_word_break_characters = $rl_basic_word_break_characters;
603 $rl_special_prefixes = '';
604 ($rl_readline_name = $0) =~ s#.*[/\\]## if !defined($rl_readline_name);
605  
606 @rl_History=() if !(@rl_History);
607 $rl_MaxHistorySize = 100 if !defined($rl_MaxHistorySize);
608 $rl_max_numeric_arg = 200 if !defined($rl_max_numeric_arg);
609 $rl_OperateCount = 0 if !defined($rl_OperateCount);
610  
611 $rl_term_set = \@Term::ReadLine::TermCap::rl_term_set;
612 @$rl_term_set or $rl_term_set = ["","","",""];
613  
614 $InsertMode=1;
615 $KillBuffer='';
616 $line='';
617 $D = 0;
618 $InputLocMsg = ' [initialization]';
619  
620 &InitKeymap(*emacs_keymap, 'SelfInsert', 'emacs_keymap',
621 ($inDOS ? () : ('C-@', 'SetMark') ),
622 'C-a', 'BeginningOfLine',
623 'C-b', 'BackwardChar',
624 'C-c', 'Interrupt',
625 'C-d', 'DeleteChar',
626 'C-e', 'EndOfLine',
627 'C-f', 'ForwardChar',
628 'C-g', 'Abort',
629 'M-C-g', 'Abort',
630 'C-h', 'BackwardDeleteChar',
631 "TAB" , 'Complete',
632 "C-j" , 'AcceptLine',
633 'C-k', 'KillLine',
634 'C-l', 'ClearScreen',
635 "C-m" , 'AcceptLine',
636 'C-n', 'NextHistory',
637 'C-o', 'OperateAndGetNext',
638 'C-p', 'PreviousHistory',
639 'C-q', 'QuotedInsert',
640 #'C-r', 'ReverseSearchHistory',
641 'C-r', 'Repaint',
642 'C-s', 'ForwardSearchHistory',
643 'C-t', 'TransposeChars',
644 'C-u', 'UnixLineDiscard',
645 ##'C-v', 'QuotedInsert',
646 'C-v', 'HistorySearchForward',
647 'C-w', 'UnixWordRubout',
648 qq/"\cX\cX"/, 'ExchangePointAndMark',
649 qq/"\cX\cR"/, 'ReReadInitFile',
650 qq/"\cX?"/, 'PossibleCompletions',
651 qq/"\cX*"/, 'InsertPossibleCompletions',
652 qq/"\cX\cU"/, 'Undo',
653 qq/"\cXu"/, 'Undo',
654 qq/"\cX\cW"/, 'KillRegion',
655 qq/"\cXw"/, 'CopyRegionAsKill',
656 qq/"\cX\ec\\*"/, 'DoControlVersion',
657 qq/"\cX\ec\0"/, 'SetMark',
658 qq/"\cX\ec\@"/, 'SetMark',
659 qq/"\cX\ec "/, 'SetMark',
660 qq/"\cX\em\\*"/, 'DoMetaVersion',
661 qq/"\cX\@c\\*"/, 'DoControlVersion',
662 qq/"\cX\@c\0"/, 'SetMark',
663 qq/"\cX\@c\@"/, 'SetMark',
664 qq/"\cX\@c "/, 'SetMark',
665 qq/"\cX\@m\\*"/, 'DoMetaVersion',
666 'C-y', 'Yank',
667 'C-z', 'Suspend',
668 'C-\\', 'Ding',
669 'C-^', 'Ding',
670 'C-_', 'Undo',
671 'DEL', ($inDOS ?
672 'BackwardKillWord' : # <Control>+<Backspace>
673 'BackwardDeleteChar'
674 ),
675 'M-<', 'BeginningOfHistory',
676 'M->', 'EndOfHistory',
677 'M-DEL', 'BackwardKillWord',
678 'M-C-h', 'BackwardKillWord',
679 'M-C-j', 'ViInput',
680 'M-C-v', 'QuotedInsert',
681 'M-b', 'BackwardWord',
682 'M-c', 'CapitalizeWord',
683 'M-d', 'KillWord',
684 'M-f', 'ForwardWord',
685 'M-h', 'PrintHistory',
686 'M-l', 'DownCaseWord',
687 'M-r', 'RevertLine',
688 'M-t', 'TransposeWords',
689 'M-u', 'UpcaseWord',
690 'M-v', 'HistorySearchBackward',
691 'M-y', 'YankPop',
692 "M-?", 'PossibleCompletions',
693 "M-TAB", 'TabInsert',
694 'M-#', 'SaveLine',
695 qq/"\e[A"/, 'previous-history',
696 qq/"\e[B"/, 'next-history',
697 qq/"\e[C"/, 'forward-char',
698 qq/"\e[D"/, 'backward-char',
699 qq/"\eOA"/, 'previous-history',
700 qq/"\eOB"/, 'next-history',
701 qq/"\eOC"/, 'forward-char',
702 qq/"\eOD"/, 'backward-char',
703 qq/"\eOy"/, 'HistorySearchBackward', # vt: PageUp
704 qq/"\eOs"/, 'HistorySearchForward', # vt: PageDown
705 qq/"\e[[A"/, 'previous-history',
706 qq/"\e[[B"/, 'next-history',
707 qq/"\e[[C"/, 'forward-char',
708 qq/"\e[[D"/, 'backward-char',
709 qq/"\e[2~"/, 'ToggleInsertMode', # X: <Insert>
710 # Mods: 1 + bitmask: 1 Shift, 2 Alt, 4 Control, 8 (sometimes) Meta
711 qq/"\e[2;2~"/, 'YankClipboard', # <Shift>+<Insert>
712 qq/"\e[3;2~"/, 'KillRegionClipboard', # <Shift>+<Delete>
713 #qq/"\0\16"/, 'Undo', # <Alt>+<Backspace>
714 qq/"\eO5D"/, 'BackwardWord', # <Ctrl>+<Left arrow>
715 qq/"\eO5C"/, 'ForwardWord', # <Ctrl>+<Right arrow>
716 qq/"\e[5D"/, 'BackwardWord', # <Ctrl>+<Left arrow>
717 qq/"\e[5C"/, 'ForwardWord', # <Ctrl>+<Right arrow>
718 qq/"\eO5F"/, 'KillLine', # <Ctrl>+<End>
719 qq/"\e[5F"/, 'KillLine', # <Ctrl>+<End>
720 qq/"\e[4;5~"/, 'KillLine', # <Ctrl>+<End>
721 qq/"\eO5s"/, 'EndOfHistory', # <Ctrl>+<Page Down>
722 qq/"\e[6;5~"/, 'EndOfHistory', # <Ctrl>+<Page Down>
723 qq/"\e[5H"/, 'BackwardKillLine', # <Ctrl>+<Home>
724 qq/"\eO5H"/, 'BackwardKillLine', # <Ctrl>+<Home>
725 qq/"\e[1;5~"/, 'BackwardKillLine', # <Ctrl>+<Home>
726 qq/"\eO5y"/, 'BeginningOfHistory', # <Ctrl>+<Page Up>
727 qq/"\e[5;5y"/, 'BeginningOfHistory', # <Ctrl>+<Page Up>
728 qq/"\e[2;5~"/, 'CopyRegionAsKillClipboard', # <Ctrl>+<Insert>
729 qq/"\e[3;5~"/, 'KillWord', # <Ctrl>+<Delete>
730  
731 # XTerm mouse editing (f202/f203 not in mainstream yet):
732 # Paste may be: move f200 STRING f201
733 # or f202 move f200 STRING f201 f203;
734 # and Cut may be f202 move delete f203
735 qq/"\e[200~"/, 'BeginPasteGroup', # Pre-paste
736 qq/"\e[201~"/, 'EndPasteGroup', # Post-paste
737 qq/"\e[202~"/, 'BeginEditGroup', # Pre-edit
738 qq/"\e[203~"/, 'EndEditGroup', # Post-edit
739  
740 # OSX xterm:
741 # OSX xterm: home \eOH end \eOF delete \e[3~ help \e[28~ f13 \e[25~
742 # gray- \eOm gray+ \eOk gray-enter \eOM gray* \eOj gray/ \eOo gray= \eO
743 # grayClear \e\e.
744  
745 qq/"\eOH"/, 'BeginningOfLine', # home
746 qq/"\eOF"/, 'EndOfLine', # end
747  
748 # HP xterm
749 #qq/"\e[A"/, 'PreviousHistory', # up arrow
750 #qq/"\e[B"/, 'NextHistory', # down arrow
751 #qq/"\e[C"/, 'ForwardChar', # right arrow
752 #qq/"\e[D"/, 'BackwardChar', # left arrow
753 qq/"\e[H"/, 'BeginningOfLine', # home
754 #'C-k', 'KillLine', # clear display
755 qq/"\e[5~"/, 'HistorySearchBackward', # prev
756 qq/"\e[6~"/, 'HistorySearchForward', # next
757 qq/"\e[\0"/, 'BeginningOfLine', # home
758  
759 # These contradict:
760 ($^O =~ /^hp\W?ux/i ? (
761 qq/"\e[1~"/, 'HistorySearchForward', # find
762 qq/"\e[3~"/, 'ToggleInsertMode', # insert char
763 qq/"\e[4~"/, 'ToggleInsertMode', # select
764 ) : ( # "Normal" xterm
765 qq/"\e[1~"/, 'BeginningOfLine', # home
766 qq/"\e[3~"/, 'DeleteChar', # delete
767 qq/"\e[4~"/, 'EndOfLine', # end
768 )),
769  
770 # hpterm
771  
772 (($ENV{'TERM'} and $ENV{'TERM'} eq 'hpterm') ?
773 (
774 qq/"\eA"/, 'PreviousHistory', # up arrow
775 qq/"\eB"/, 'NextHistory', # down arrow
776 qq/"\eC"/, 'ForwardChar', # right arrow
777 qq/"\eD"/, 'BackwardChar', # left arrow
778 qq/"\eS"/, 'BeginningOfHistory', # shift up arrow
779 qq/"\eT"/, 'EndOfHistory', # shift down arrow
780 qq/"\e&r1R"/, 'EndOfLine', # shift right arrow
781 qq/"\e&r1L"/, 'BeginningOfLine', # shift left arrow
782 qq/"\eJ"/, 'ClearScreen', # clear display
783 qq/"\eM"/, 'UnixLineDiscard', # delete line
784 qq/"\eK"/, 'KillLine', # clear line
785 qq/"\eG\eK"/, 'BackwardKillLine', # shift clear line
786 qq/"\eP"/, 'DeleteChar', # delete char
787 qq/"\eL"/, 'Yank', # insert line
788 qq/"\eQ"/, 'ToggleInsertMode', # insert char
789 qq/"\eV"/, 'HistorySearchBackward',# prev
790 qq/"\eU"/, 'HistorySearchForward',# next
791 qq/"\eh"/, 'BeginningOfLine', # home
792 qq/"\eF"/, 'EndOfLine', # shift home
793 qq/"\ei"/, 'Suspend', # shift tab
794 ) :
795 ()
796 ),
797 ($inDOS ?
798 (
799 qq/"\0\2"/, 'SetMark', # 2: <Control>+<Space>
800 qq/"\0\3"/, 'SetMark', # 3: <Control>+<@>
801 qq/"\0\4"/, 'YankClipboard', # 4: <Shift>+<Insert>
802 qq/"\0\5"/, 'KillRegionClipboard', # 5: <Shift>+<Delete>
803 qq/"\0\16"/, 'Undo', # 14: <Alt>+<Backspace>
804 # qq/"\0\23"/, 'RevertLine', # 19: <Alt>+<R>
805 # qq/"\0\24"/, 'TransposeWords', # 20: <Alt>+<T>
806 # qq/"\0\25"/, 'YankPop', # 21: <Alt>+<Y>
807 # qq/"\0\26"/, 'UpcaseWord', # 22: <Alt>+<U>
808 # qq/"\0\31"/, 'ReverseSearchHistory', # 25: <Alt>+<P>
809 # qq/"\0\40"/, 'KillWord', # 32: <Alt>+<D>
810 # qq/"\0\41"/, 'ForwardWord', # 33: <Alt>+<F>
811 # qq/"\0\46"/, 'DownCaseWord', # 38: <Alt>+<L>
812 #qq/"\0\51"/, 'TildeExpand', # 41: <Alt>+<\'>
813 # qq/"\0\56"/, 'CapitalizeWord', # 46: <Alt>+<C>
814 # qq/"\0\60"/, 'BackwardWord', # 48: <Alt>+<B>
815 # qq/"\0\61"/, 'ForwardSearchHistory', # 49: <Alt>+<N>
816 #qq/"\0\64"/, 'YankLastArg', # 52: <Alt>+<.>
817 qq/"\0\65"/, 'PossibleCompletions', # 53: <Alt>+</>
818 qq/"\0\107"/, 'BeginningOfLine', # 71: <Home>
819 qq/"\0\110"/, 'previous-history', # 72: <Up arrow>
820 qq/"\0\111"/, 'HistorySearchBackward', # 73: <Page Up>
821 qq/"\0\113"/, 'backward-char', # 75: <Left arrow>
822 qq/"\0\115"/, 'forward-char', # 77: <Right arrow>
823 qq/"\0\117"/, 'EndOfLine', # 79: <End>
824 qq/"\0\120"/, 'next-history', # 80: <Down arrow>
825 qq/"\0\121"/, 'HistorySearchForward', # 81: <Page Down>
826 qq/"\0\122"/, 'ToggleInsertMode', # 82: <Insert>
827 qq/"\0\123"/, 'DeleteChar', # 83: <Delete>
828 qq/"\0\163"/, 'BackwardWord', # 115: <Ctrl>+<Left arrow>
829 qq/"\0\164"/, 'ForwardWord', # 116: <Ctrl>+<Right arrow>
830 qq/"\0\165"/, 'KillLine', # 117: <Ctrl>+<End>
831 qq/"\0\166"/, 'EndOfHistory', # 118: <Ctrl>+<Page Down>
832 qq/"\0\167"/, 'BackwardKillLine', # 119: <Ctrl>+<Home>
833 qq/"\0\204"/, 'BeginningOfHistory', # 132: <Ctrl>+<Page Up>
834 qq/"\0\x92"/, 'CopyRegionAsKillClipboard', # 146: <Ctrl>+<Insert>
835 qq/"\0\223"/, 'KillWord', # 147: <Ctrl>+<Delete>
836 qq/"\0#"/, 'PrintHistory', # Alt-H
837 )
838 : ( 'C-@', 'Ding')
839 )
840 );
841  
842 *KeyMap = *emacs_keymap;
843 my @add_bindings = ();
844 foreach ('-', '0' .. '9') { push(@add_bindings, "M-$_", 'DigitArgument'); }
845 foreach ("A" .. "Z") {
846 next if # defined($KeyMap[27]) && defined (%{"$KeyMap{name}_27"}) &&
847 defined $ {"$KeyMap{name}_27"}[ord $_];
848 push(@add_bindings, "M-$_", 'DoLowercaseVersion');
849 }
850 if ($inDOS) {
851 # Default translation of Alt-char
852 $ {"$KeyMap{name}_0"}{'Esc'} = *{"$KeyMap{name}_27"};
853 $ {"$KeyMap{name}_0"}{'default'} = 'F_DoEscVersion';
854 }
855 &rl_bind(@add_bindings);
856
857 # Vi input mode.
858 &InitKeymap(*vi_keymap, 'SelfInsert', 'vi_keymap',
859  
860 "\e", 'ViEndInsert',
861 'C-c', 'Interrupt',
862 'C-h', 'BackwardDeleteChar',
863 'C-w', 'UnixWordRubout',
864 'C-u', 'UnixLineDiscard',
865 'C-v', 'QuotedInsert',
866 'DEL', 'BackwardDeleteChar',
867 "\n", 'ViAcceptInsert',
868 "\r", 'ViAcceptInsert',
869 );
870  
871 # Vi command mode.
872 &InitKeymap(*vicmd_keymap, 'Ding', 'vicmd_keymap',
873  
874 'C-c', 'Interrupt',
875 'C-e', 'EmacsEditingMode',
876 'C-h', 'ViMoveCursor',
877 'C-l', 'ClearScreen',
878 "\n", 'ViAcceptLine',
879 "\r", 'ViAcceptLine',
880  
881 ' ', 'ViMoveCursor',
882 '#', 'SaveLine',
883 '$', 'ViMoveCursor',
884 '%', 'ViMoveCursor',
885 '*', 'ViInsertPossibleCompletions',
886 '+', 'NextHistory',
887 ',', 'ViMoveCursor',
888 '-', 'PreviousHistory',
889 '.', 'ViRepeatLastCommand',
890 '/', 'ViSearch',
891  
892 '0', 'ViMoveCursor',
893 '1', 'ViDigit',
894 '2', 'ViDigit',
895 '3', 'ViDigit',
896 '4', 'ViDigit',
897 '5', 'ViDigit',
898 '6', 'ViDigit',
899 '7', 'ViDigit',
900 '8', 'ViDigit',
901 '9', 'ViDigit',
902  
903 ';', 'ViMoveCursor',
904 '=', 'ViPossibleCompletions',
905 '?', 'ViSearch',
906  
907 'A', 'ViAppendLine',
908 'B', 'ViMoveCursor',
909 'C', 'ViChangeLine',
910 'D', 'ViDeleteLine',
911 'E', 'ViMoveCursor',
912 'F', 'ViMoveCursor',
913 'G', 'ViHistoryLine',
914 'H', 'PrintHistory',
915 'I', 'ViBeginInput',
916 'N', 'ViRepeatSearch',
917 'P', 'ViPutBefore',
918 'R', 'ViReplaceMode',
919 'S', 'ViChangeEntireLine',
920 'T', 'ViMoveCursor',
921 'U', 'ViUndoAll',
922 'W', 'ViMoveCursor',
923 'X', 'ViBackwardDeleteChar',
924 'Y', 'ViYankLine',
925  
926 '\\', 'ViComplete',
927 '^', 'ViMoveCursor',
928  
929 'a', 'ViAppend',
930 'b', 'ViMoveCursor',
931 'c', 'ViChange',
932 'd', 'ViDelete',
933 'e', 'ViMoveCursor',
934 'f', 'ViMoveCursorFind',
935 'h', 'ViMoveCursor',
936 'i', 'ViInput',
937 'j', 'NextHistory',
938 'k', 'PreviousHistory',
939 'l', 'ViMoveCursor',
940 'n', 'ViRepeatSearch',
941 'p', 'ViPut',
942 'r', 'ViReplaceChar',
943 's', 'ViChangeChar',
944 't', 'ViMoveCursorTo',
945 'u', 'ViUndo',
946 'w', 'ViMoveCursor',
947 'x', 'ViDeleteChar',
948 'y', 'ViYank',
949  
950 '|', 'ViMoveCursor',
951 '~', 'ViToggleCase',
952  
953 (($inDOS
954 and (not $ENV{'TERM'} or $ENV{'TERM'} !~ /^(vt|xterm)/i)) ?
955 (
956 qq/"\0\110"/, 'PreviousHistory', # 72: <Up arrow>
957 qq/"\0\120"/, 'NextHistory', # 80: <Down arrow>
958 qq/"\0\113"/, 'BackwardChar', # 75: <Left arrow>
959 qq/"\0\115"/, 'ForwardChar', # 77: <Right arrow>
960 "\e", 'ViCommandMode',
961 ) :
962  
963 (('M-C-j','EmacsEditingMode'), # Conflicts with \e otherwise
964 (($ENV{'TERM'} and $ENV{'TERM'} eq 'hpterm') ?
965 (
966 qq/"\eA"/, 'PreviousHistory', # up arrow
967 qq/"\eB"/, 'NextHistory', # down arrow
968 qq/"\eC"/, 'ForwardChar', # right arrow
969 qq/"\eD"/, 'BackwardChar', # left arrow
970 qq/"\e\\*"/, 'ViAfterEsc',
971 ) :
972  
973 # Default
974 (
975 qq/"\e[A"/, 'PreviousHistory', # up arrow
976 qq/"\e[B"/, 'NextHistory', # down arrow
977 qq/"\e[C"/, 'ForwardChar', # right arrow
978 qq/"\e[D"/, 'BackwardChar', # left arrow
979 qq/"\e\\*"/, 'ViAfterEsc',
980 qq/"\e[\\*"/, 'ViAfterEsc',
981 )
982 ))),
983 );
984  
985 # Vi positioning commands (suffixed to vi commands like 'd').
986 &InitKeymap(*vipos_keymap, 'ViNonPosition', 'vipos_keymap',
987  
988 '^', 'ViFirstWord',
989 '0', 'BeginningOfLine',
990 '1', 'ViDigit',
991 '2', 'ViDigit',
992 '3', 'ViDigit',
993 '4', 'ViDigit',
994 '5', 'ViDigit',
995 '6', 'ViDigit',
996 '7', 'ViDigit',
997 '8', 'ViDigit',
998 '9', 'ViDigit',
999 '$', 'EndOfLine',
1000 'h', 'BackwardChar',
1001 'l', 'ForwardChar',
1002 ' ', 'ForwardChar',
1003 'C-h', 'BackwardChar',
1004 'f', 'ViForwardFindChar',
1005 'F', 'ViBackwardFindChar',
1006 't', 'ViForwardToChar',
1007 'T', 'ViBackwardToChar',
1008 ';', 'ViRepeatFindChar',
1009 ',', 'ViInverseRepeatFindChar',
1010 '%', 'ViFindMatchingParens',
1011 '|', 'ViMoveToColumn',
1012  
1013 # Arrow keys
1014 ($inDOS ?
1015 (
1016 qq/"\0\115"/, 'ForwardChar', # 77: <Right arrow>
1017 qq/"\0\113"/, 'BackwardChar', # 75: <Left arrow>
1018 "\e", 'ViPositionEsc',
1019 ) :
1020  
1021 ($ENV{'TERM'} and $ENV{'TERM'} eq 'hpterm') ?
1022 (
1023 qq/"\eC"/, 'ForwardChar', # right arrow
1024 qq/"\eD"/, 'BackwardChar', # left arrow
1025 qq/"\e\\*"/, 'ViPositionEsc',
1026 ) :
1027  
1028 # Default
1029 (
1030 qq/"\e[C"/, 'ForwardChar', # right arrow
1031 qq/"\e[D"/, 'BackwardChar', # left arrow
1032 qq/"\e\\*"/, 'ViPositionEsc',
1033 qq/"\e[\\*"/, 'ViPositionEsc',
1034 )
1035 ),
1036 );
1037  
1038 # Vi search string input mode for '/' and '?'.
1039 &InitKeymap(*visearch_keymap, 'SelfInsert', 'visearch_keymap',
1040  
1041 "\e", 'Ding',
1042 'C-c', 'Interrupt',
1043 'C-h', 'ViSearchBackwardDeleteChar',
1044 'C-w', 'UnixWordRubout',
1045 'C-u', 'UnixLineDiscard',
1046 'C-v', 'QuotedInsert',
1047 'DEL', 'ViSearchBackwardDeleteChar',
1048 "\n", 'ViEndSearch',
1049 "\r", 'ViEndSearch',
1050 );
1051  
1052 # These constant hashes hold the arguments to &forward_scan() or
1053 # &backward_scan() for vi positioning commands, which all
1054 # behave a little differently for delete, move, change, and yank.
1055 #
1056 # Note: I originally coded these as qr{}, but changed them to q{} for
1057 # compatibility with older perls at the expense of some performance.
1058 #
1059 # Note: Some of the more obscure key combinations behave slightly
1060 # differently in different vi implementation. This module matches
1061 # the behavior of /usr/ucb/vi, which is different from the
1062 # behavior of vim, nvi, and the ksh command line. One example is
1063 # the command '2de', when applied to the string ('^' represents the
1064 # cursor, not a character of the string):
1065 #
1066 # ^5.6 7...88888888
1067 #
1068 # With /usr/ucb/vi and with this module, the result is
1069 #
1070 # ^...88888888
1071 #
1072 # but with the other three vi implementations, the result is
1073 #
1074 # ^ 7...88888888
1075  
1076 $Vi_delete_patterns = {
1077 ord('w') => q{(?:\w+|[^\w\s]+|)\s*},
1078 ord('W') => q{\S*\s*},
1079 ord('b') => q{\w+\s*|[^\w\s]+\s*|^\s+},
1080 ord('B') => q{\S+\s*|^\s+},
1081 ord('e') => q{.\s*\w+|.\s*[^\w\s]+|.\s*$},
1082 ord('E') => q{.\s*\S+|.\s*$},
1083 };
1084  
1085 $Vi_move_patterns = {
1086 ord('w') => q{(?:\w+|[^\w\s]+|)\s*},
1087 ord('W') => q{\S*\s*},
1088 ord('b') => q{\w+\s*|[^\w\s]+\s*|^\s+},
1089 ord('B') => q{\S+\s*|^\s+},
1090 ord('e') => q{.\s*\w*(?=\w)|.\s*[^\w\s]*(?=[^\w\s])|.?\s*(?=\s$)},
1091 ord('E') => q{.\s*\S*(?=\S)|.?\s*(?=\s$)},
1092 };
1093  
1094 $Vi_change_patterns = {
1095 ord('w') => q{\w+|[^\w\s]+|\s},
1096 ord('W') => q{\S+|\s},
1097 ord('b') => q{\w+\s*|[^\w\s]+\s*|^\s+},
1098 ord('B') => q{\S+\s*|^\s+},
1099 ord('e') => q{.\s*\w+|.\s*[^\w\s]+|.\s*$},
1100 ord('E') => q{.\s*\S+|.\s*$},
1101 };
1102  
1103 $Vi_yank_patterns = {
1104 ord('w') => q{(?:\w+|[^\w\s]+|)\s*},
1105 ord('W') => q{\S*\s*},
1106 ord('b') => q{\w+\s*|[^\w\s]+\s*|^\s+},
1107 ord('B') => q{\S+\s*|^\s+},
1108 ord('e') => q{.\s*\w*(?=\w)|.\s*[^\w\s]*(?=[^\w\s])|.?\s*(?=\s$)},
1109 ord('E') => q{.\s*\S*(?=\S)|.?\s*(?=\s$)},
1110 };
1111  
1112 my $default_mode = 'emacs';
1113  
1114 *KeyMap = $var_EditingMode = $var_EditingMode{$default_mode};
1115  
1116 ## my $name;
1117 ## for $name ( keys %{'readline::'} ) {
1118 ## # Create aliases accessible via tied interface
1119 ## *{"rl_$1"} = \$ {"var_$1"} if $name =~ /$var_(.*)/;
1120 ## }
1121  
1122 1; # Returning a glob causes a bug in db5.001m
1123 }
1124  
1125 sub init
1126 {
1127 if ($ENV{'TERM'} and ($ENV{'TERM'} eq 'emacs' || $ENV{'TERM'} eq 'dumb')) {
1128 $dumb_term = 1;
1129 } elsif (! -c $term_IN && $term_IN eq \*STDIN) { # Believe if it is given
1130 $stdin_not_tty = 1;
1131 } else {
1132 &get_window_size;
1133 &F_ReReadInitFile if !defined($rl_NoInitFromFile);
1134 $InputLocMsg = '';
1135 *KeyMap = $var_EditingMode;
1136 }
1137  
1138 $initialized = 1;
1139 }
1140  
1141  
1142 ##
1143 ## InitKeymap(*keymap, 'default', 'name', bindings.....)
1144 ##
1145 sub InitKeymap
1146 {
1147 local(*KeyMap) = shift(@_);
1148 my $default = shift(@_);
1149 my $name = $KeyMap{'name'} = shift(@_);
1150  
1151 # 'default' is now optional - if '', &do_command() defaults it to
1152 # 'F_Ding'. Meta-maps now don't set a default - this lets
1153 # us detect multiple '\*' default declarations. JP
1154 if ($default ne '') {
1155 my $func = $KeyMap{'default'} = "F_$default";
1156 ### Temporarily disabled
1157 die qq/Bad default function [$func] for keymap "$name"/
1158 if !$autoload_broken and !defined(&$func);
1159 }
1160  
1161 &rl_bind if @_ > 0; ## The rest of @_ gets passed silently.
1162 }
1163  
1164 ##
1165 ## Accepts an array as pairs ($keyspec, $function, [$keyspec, $function]...).
1166 ## and maps the associated bindings to the current KeyMap.
1167 ##
1168 ## keyspec should be the name of key sequence in one of two forms:
1169 ##
1170 ## Old (GNU readline documented) form:
1171 ## M-x to indicate Meta-x
1172 ## C-x to indicate Ctrl-x
1173 ## M-C-x to indicate Meta-Ctrl-x
1174 ## x simple char x
1175 ## where 'x' above can be a single character, or the special:
1176 ## special means
1177 ## -------- -----
1178 ## space space ( )
1179 ## spc space ( )
1180 ## tab tab (\t)
1181 ## del delete (0x7f)
1182 ## rubout delete (0x7f)
1183 ## newline newline (\n)
1184 ## lfd newline (\n)
1185 ## ret return (\r)
1186 ## return return (\r)
1187 ## escape escape (\e)
1188 ## esc escape (\e)
1189 ##
1190 ## New form:
1191 ## "chars" (note the required double-quotes)
1192 ## where each char in the list represents a character in the sequence, except
1193 ## for the special sequences:
1194 ## \\C-x Ctrl-x
1195 ## \\M-x Meta-x
1196 ## \\M-C-x Meta-Ctrl-x
1197 ## \\e escape.
1198 ## \\x x (if not one of the above)
1199 ##
1200 ##
1201 ## FUNCTION should be in the form 'BeginningOfLine' or 'beginning-of-line'.
1202 ## It is an error for the function to not be known....
1203 ##
1204 ## As an example, the following lines in .inputrc will bind one's xterm
1205 ## arrow keys:
1206 ## "\e[[A": previous-history
1207 ## "\e[[B": next-history
1208 ## "\e[[C": forward-char
1209 ## "\e[[D": backward-char
1210 ##
1211  
1212 sub filler_Pending ($) {
1213 my $keys = shift;
1214 sub {
1215 my $c = shift;
1216 push @Pending, map chr, @$keys;
1217 return if not @$keys or $c == 1 or not defined(my $in = &getc_with_pending);
1218 # provide the numeric argument
1219 local(*KeyMap) = $var_EditingMode;
1220 $doingNumArg = 1; # Allow NumArg inside NumArg
1221 &do_command(*KeyMap, $c, ord $in);
1222 return;
1223 }
1224 }
1225  
1226 sub _unescape ($) {
1227 my($key, @keys) = shift;
1228 ## New-style bindings are enclosed in double-quotes.
1229 ## Characters are taken verbatim except the special cases:
1230 ## \C-x Control x (for any x)
1231 ## \M-x Meta x (for any x)
1232 ## \e Escape
1233 ## \* Set the keymap default (JP: added this)
1234 ## (must be the last character of the sequence)
1235 ##
1236 ## \x x (unless it fits the above pattern)
1237 ##
1238 ## Look for special case of "\C-\M-x", which should be treated
1239 ## like "\M-\C-x".
1240  
1241 while (length($key) > 0) {
1242  
1243 # JP: fixed regex bugs below: changed all 's#' to 's#^'
1244  
1245 if ($key =~ s#^\\C-\\M-(.)##) {
1246 push(@keys, ord("\e"), &ctrl(ord($1)));
1247 } elsif ($key =~ s#^\\(M-|e)##) {
1248 push(@keys, ord("\e"));
1249 } elsif ($key =~ s#^\\C-(.)##) {
1250 push(@keys, &ctrl(ord($1)));
1251 } elsif ($key =~ s#^\\x([0-9a-fA-F]{2})##) {
1252 push(@keys, eval('0x'.$1));
1253 } elsif ($key =~ s#^\\([0-7]{3})##) {
1254 push(@keys, eval('0'.$1));
1255 } elsif ($key =~ s#^\\\*$##) { # JP: added
1256 push(@keys, 'default');
1257 } elsif ($key =~ s#^\\([afnrtv])##) {
1258 push(@keys, ord(eval(qq("\\$1"))));
1259 } elsif ($key =~ s#^\\d##) {
1260 push(@keys, 4); # C-d
1261 } elsif ($key =~ s#^\\b##) {
1262 push(@keys, 0x7f); # Backspace
1263 } elsif ($key =~ s#^\\(.)##) {
1264 push(@keys, ord($1));
1265 } else {
1266 push(@keys, ord($key));
1267 substr($key,0,1) = '';
1268 }
1269 }
1270 @keys
1271 }
1272  
1273 sub RL_func ($) {
1274 my $name_or_macro = shift;
1275 if ($name_or_macro =~ /^"((?:\\.|[^\\\"])*)"|^'((?:\\.|[^\\\'])*)'/s) {
1276 filler_Pending [_unescape "$+"];
1277 } else {
1278 "F_$name_or_macro";
1279 }
1280 }
1281  
1282 sub actually_do_binding
1283 {
1284 ##
1285 ## actually_do_binding($function1, \@sequence1, ...)
1286 ##
1287 ## Actually inserts the binding for @sequence to $function into the
1288 ## current map. @sequence is an array of character ordinals.
1289 ##
1290 ## If @sequence is more than one element long, all but the last will
1291 ## cause meta maps to be created.
1292 ##
1293 ## $Function will have an implicit "F_" prepended to it.
1294 ##
1295 while (@_) {
1296 my $func = shift;
1297 my ($key, @keys) = @{shift()};
1298 $key += 0;
1299 local(*KeyMap) = *KeyMap;
1300 my $map;
1301 while (@keys) {
1302 if (defined($KeyMap[$key]) && ($KeyMap[$key] ne 'F_PrefixMeta')) {
1303 warn "Warning$InputLocMsg: ".
1304 "Re-binding char #$key from [$KeyMap[$key]] to meta for [@keys] => $func.\n" if $^W;
1305 }
1306 $KeyMap[$key] = 'F_PrefixMeta';
1307 $map = "$KeyMap{'name'}_$key";
1308 InitKeymap(*$map, '', $map) if !(%$map);
1309 *KeyMap = *$map;
1310 $key = shift @keys;
1311 #&actually_do_binding($func, \@keys);
1312 }
1313  
1314 my $name = $KeyMap{'name'};
1315 if ($key eq 'default') { # JP: added
1316 warn "Warning$InputLocMsg: ".
1317 " changing default action to $func in $name key map\n"
1318 if $^W && defined $KeyMap{'default'};
1319  
1320 $KeyMap{'default'} = RL_func $func;
1321 }
1322 else {
1323 if (defined($KeyMap[$key]) && $KeyMap[$key] eq 'F_PrefixMeta'
1324 && $func ne 'PrefixMeta')
1325 {
1326 warn "Warning$InputLocMsg: ".
1327 " Re-binding char #$key to non-meta ($func) in $name key map\n"
1328 if $^W;
1329 }
1330 $KeyMap[$key] = RL_func $func;
1331 }
1332 }
1333 }
1334  
1335 # These functions are custom for TTYtter and are used by the client.
1336 sub rl_removereadline
1337 # call to remove the readline from the screen temporarily.
1338 {
1339 my $out = "\r" . (" " x ($rl_screen_width || 79)) . "\r";
1340 print $term_OUT $out;
1341 }
1342  
1343 sub rl_redisplay
1344 # call to force a repaint. won't respond if we're not displaying a prompt.
1345 {
1346 return unless ($in_readline);
1347 $force_redraw = 1;
1348 redisplay();
1349 }
1350 sub rl_hook_background_control
1351 # call to bind background control to a pid (USR1 = halt output, USR2 = ok).
1352 {
1353 $background_control = $main::child;
1354 }
1355 sub rl_hook_use_ansi
1356 # call to synchronize internal use of ANSI with the user's
1357 {
1358 $use_ansi = $main::ansi;
1359 }
1360 sub rl_hook_no_counter
1361 # call to synchronize user preferences for counter (and prompts)
1362 {
1363 $dont_use_counter = $main::dont_use_counter;
1364 }
1365 sub rl_hook_no_tco
1366 # call to synchronize using t.co length computations. this is a little
1367 # different. by default we do NOT so this can be used for other applications.
1368 # if TTYtter has notco NOT set, then we turn on t.co length computations when
1369 # this is called (and vice versa). if this is never called, t.co length
1370 # computation is never used (so don't call it if this is not a Twitter client).
1371 # we then use TTYtter's internal tco logic so upgrading that doesn't need
1372 # a T:RL:T update too.
1373 {
1374 $do_tco = ($main::notco) ? 0 : $main::tco_sub;
1375 }
1376  
1377 sub rl_bind
1378 {
1379 my (@keys, $key, $func, $ord, @arr);
1380  
1381 while (defined($key = shift(@_)) && defined($func = shift(@_)))
1382 {
1383 ##
1384 ## Change the function name from something like
1385 ## backward-kill-line
1386 ## to
1387 ## BackwardKillLine
1388 ## if not already there.
1389 ##
1390 unless ($func =~ /^[\"\']/) {
1391 $func = "\u$func";
1392 $func =~ s/-(.)/\u$1/g;
1393  
1394 # Temporary disabled
1395 if (!$autoload_broken and !defined($ {'readline::'}{"F_$func"})) {
1396 warn "Warning$InputLocMsg: bad bind function [$func]\n" if $^W;
1397 next;
1398 }
1399 }
1400  
1401 ## print "sequence [$key] func [$func]\n"; ##DEBUG
1402  
1403 @keys = ();
1404 ## See if it's a new-style binding.
1405 if ($key =~ m/"((?:\\.|[^\\])*)"/s) {
1406 @keys = _unescape "$1";
1407 } else {
1408 ## ol-dstyle binding... only one key (or Meta+key)
1409 my ($isctrl, $orig) = (0, $key);
1410 $isctrl = $key =~ s/\b(C|Control|CTRL)-//i;
1411 push(@keys, ord("\e")) if $key =~ s/\b(M|Meta)-//i; ## is meta?
1412 ## Isolate key part. This matches GNU's implementation.
1413 ## If the key is '-', be careful not to delete it!
1414 $key =~ s/.*-(.)/$1/;
1415 if ($key =~ /^(space|spc)$/i) { $key = ' '; }
1416 elsif ($key =~ /^(rubout|del)$/i) { $key = "\x7f"; }
1417 elsif ($key =~ /^tab$/i) { $key = "\t"; }
1418 elsif ($key =~ /^(return|ret)$/i) { $key = "\r"; }
1419 elsif ($key =~ /^(newline|lfd)$/i) { $key = "\n"; }
1420 elsif ($key =~ /^(escape|esc)$/i) { $key = "\e"; }
1421 elsif (length($key) > 1) {
1422 warn "Warning$InputLocMsg: strange binding [$orig]\n" if $^W;
1423 }
1424 $key = ord($key);
1425 $key = &ctrl($key) if $isctrl;
1426 push(@keys, $key);
1427 }
1428  
1429 #
1430 ## Now do the mapping of the sequence represented in @keys
1431 #
1432 # print "&actually_do_binding($func, @keys)\n"; ##DEBUG
1433 push @arr, $func, [@keys];
1434 #&actually_do_binding($func, \@keys);
1435 }
1436 &actually_do_binding(@arr);
1437 }
1438  
1439 sub read_an_init_file {
1440 my $file = shift;
1441 my $include_depth = shift;
1442 local *RC;
1443 $file =~ s/^~([\\\/])/$ENV{HOME}$1/ if not -f $file and exists $ENV{HOME};
1444 return unless open RC, "< $file";
1445 my (@action) = ('exec'); ## exec, skip, ignore (until appropriate endif)
1446 my (@level) = (); ## if, else
1447  
1448 local $/ = "\n";
1449 while (<RC>) {
1450 s/^\s+//;
1451 next if m/^\s*(#|$)/;
1452 $InputLocMsg = " [$file line $.]";
1453 if (/^\$if\s+(.*)/) {
1454 my($test) = $1;
1455 push(@level, 'if');
1456 if ($action[$#action] ne 'exec') {
1457 ## We're supposed to be skipping or ignoring this level,
1458 ## so for subsequent levels we really ignore completely.
1459 push(@action, 'ignore');
1460 } else {
1461 ## We're executing this IF... do the test.
1462 ## The test is either "term=xxxx", or just a string that
1463 ## we compare to $rl_readline_name;
1464 if ($test =~ /term=([a-z0-9]+)/) {
1465 $test = ($ENV{'TERM'} && $1 eq $ENV{'TERM'});
1466 } else {
1467 $test = $test =~ /^(perl|$rl_readline_name)\s*$/i;
1468 }
1469 push(@action, $test ? 'exec' : 'skip');
1470 }
1471 next;
1472 } elsif (/^\$endif\b/) {
1473 die qq/\rWarning$InputLocMsg: unmatched endif\n/ if @level == 0;
1474 pop(@level);
1475 pop(@action);
1476 next;
1477 } elsif (/^\$else\b/) {
1478 die qq/\rWarning$InputLocMsg: unmatched else\n/ if
1479 @level == 0 || $level[$#level] ne 'if';
1480 $level[$#level] = 'else'; ## an IF turns into an ELSE
1481 if ($action[$#action] eq 'skip') {
1482 $action[$#action] = 'exec'; ## if were SKIPing, now EXEC
1483 } else {
1484 $action[$#action] = 'ignore'; ## otherwise, just IGNORE.
1485 }
1486 next;
1487 } elsif (/^\$include\s+(\S+)/) {
1488 if ($include_depth > $max_include_depth) {
1489 warn "Deep recursion in \$include directives in $file.\n";
1490 } else {
1491 read_an_init_file($1, $include_depth + 1);
1492 }
1493 } elsif ($action[$#action] ne 'exec') {
1494 ## skipping this one....
1495 # readline permits trailing comments in inputrc
1496 # this seems to solve the warnings caused by trailing comments in the
1497 # default /etc/inputrc on Mandrake Linux boxes.
1498 } elsif (m/\s*set\s+(\S+)\s+(\S*)/) { # Allow trailing comment
1499 &rl_set($1, $2, $file);
1500 } elsif (m/^\s*(\S+):\s+("(?:\\.|[^\\\"])*"|'(\\.|[^\\\'])*')/) { # Allow trailing comment
1501 &rl_bind($1, $2);
1502 } elsif (m/^\s*(\S+):\s+(\S+)/) { # Allow trailing comment
1503 &rl_bind($1, $2);
1504 } else {
1505 chomp;
1506 warn "\rWarning$InputLocMsg: Bad line [$_]\n" if $^W;
1507 }
1508 }
1509 close(RC);
1510 }
1511  
1512 sub F_ReReadInitFile
1513 {
1514 my ($file) = $ENV{'TRP_INPUTRC'};
1515 $file = $ENV{'INPUTRC'} unless defined $file;
1516 unless (defined $file) {
1517 return unless defined $ENV{'HOME'};
1518 $file = "$ENV{'HOME'}/.inputrc";
1519 }
1520 read_an_init_file($file, 0);
1521 }
1522  
1523 sub get_ornaments_selected {
1524 return if @$rl_term_set >= 6;
1525 local $^W=0;
1526 my $Orig = $Term::ReadLine::TTYtter::term->ornaments();
1527 eval {
1528 # Term::ReadLine does not expose its $terminal, so make another
1529 require Term::Cap;
1530 my $terminal = Tgetent Term::Cap ({OSPEED=>9600});
1531 # and be sure the terminal supports highlighting
1532 $terminal->Trequire('mr');
1533 };
1534 if (!$@ and $Orig ne ',,,'){
1535 my @set = @$rl_term_set;
1536  
1537 $Term::ReadLine::TTYtter::term->ornaments
1538 (join(',', (split(/,/, $Orig))[0,1]) . ',mr,me') ;
1539 @set[4,5] = @$rl_term_set[2,3];
1540 $Term::ReadLine::TTYtter::term->ornaments($Orig);
1541 @$rl_term_set = @set;
1542 } else {
1543 @$rl_term_set[4,5] = @$rl_term_set[2,3];
1544 }
1545 }
1546  
1547 sub readline_dumb {
1548 local $\ = '';
1549 print $term_OUT $prompt;
1550 local $/ = "\n";
1551 return undef
1552 if !defined($line = $Term::ReadLine::TTYtter::term->get_line);
1553 chomp($line);
1554 $| = $oldbar;
1555 select $old;
1556 return $line;
1557 }
1558  
1559 ##
1560 ## This is it. Called as &readline'readline($prompt, $default),
1561 ## (DEFAULT can be omitted) the next input line is returned (undef on EOF).
1562 ##
1563 sub readline
1564 {
1565  
1566 # UTF-8 locale? if so, prepare for Unicode from the keyboard (incomplete)
1567 # nasty kludge for accounting for all the places this could be
1568 $LANG = $ENV{'LANG'} || $ENV{'GDM_LANG'} || $ENV{'LC_CTYPE'} || $ENV{'ALL'}
1569 || '';
1570 $UUTF8 = ($LANG =~ /UTF-?8/i) ? 1 : 0;
1571 $ULATIN1 = ($LANG =~ /8859/) ? 1 : 0;
1572  
1573 $Term::ReadLine::TTYtter::term->register_Tk
1574 if not $Term::ReadLine::registered and $Term::ReadLine::toloop
1575 and defined &Tk::DoOneEvent;
1576 if ($stdin_not_tty) {
1577 local $/ = "\n";
1578 return undef if !defined($line = <$term_IN>);
1579 chomp($line);
1580 return $line;
1581 }
1582  
1583 $old = select $term_OUT;
1584 $oldbar = $|;
1585 local($|) = 1;
1586 local($input);
1587  
1588 ## prompt should be given to us....
1589 $prompt = defined($_[0]) ? $_[0] : 'INPUT> ';
1590  
1591 # Try to move cursor to the beginning of the next line if this line
1592 # contains anything.
1593  
1594 # On DOSish 80-wide console
1595 # perl -we "print 1 x shift, qq(\b2\r3); sleep 2" 79
1596 # prints 3 on the same line,
1597 # perl -we "print 1 x shift, qq(\b2\r3); sleep 2" 80
1598 # on the next; $rl_screen_width is 79.
1599  
1600 # on XTerm one needs to increase the number by 1.
1601  
1602 print $term_OUT ' ' x ($rl_screen_width - !$rl_last_pos_can_backspace) . "\b \r"
1603 if $rl_scroll_nextline;
1604  
1605 if ($dumb_term) {
1606 return readline_dumb;
1607 }
1608  
1609 # test if we resume an 'Operate' command
1610 if ($rl_OperateCount > 0 && (!defined $_[1] || $_[1] eq '')) {
1611 ## it's from a valid previous 'Operate' command and
1612 ## user didn't give a default line
1613 ## we leave $rl_HistoryIndex untouched
1614 $line = $rl_History[$rl_HistoryIndex];
1615 } else {
1616 ## set history pointer at the end of history
1617 $rl_HistoryIndex = $#rl_History + 1;
1618 $rl_OperateCount = 0;
1619 $line = defined $_[1] ? $_[1] : '';
1620 }
1621 $rl_OperateCount-- if $rl_OperateCount > 0;
1622  
1623 $line_for_revert = $line;
1624  
1625 # I don't think we need to do this, actually...
1626 # while (&ioctl(STDIN,$FIONREAD,$fion))
1627 # {
1628 # local($n_chars_available) = unpack ($fionread_t, $fion);
1629 # ## print "n_chars = $n_chars_available\n";
1630 # last if $n_chars_available == 0;
1631 # $line .= getc_with_pending; # should we prepend if $rl_start_default_at_beginning?
1632 # }
1633  
1634 $D = $rl_start_default_at_beginning ? 0 : length($line); ## set dot.
1635 $LastCommandKilledText = 0; ## heck, was no last command.
1636 $lastcommand = ''; ## Well, there you go.
1637 $line_rl_mark = -1;
1638  
1639 ##
1640 ## some stuff for &redisplay.
1641 ##
1642 $lastredisplay = ''; ## Was no last redisplay for this time.
1643 $lastlen = length($lastredisplay);
1644 $lastpromptlen = 0;
1645 $lastdelta = 0; ## Cursor was nowhere
1646 $si = 0; ## Want line to start left-justified
1647 $force_redraw = 1; ## Want to display with brute force.
1648 $in_readline = 1;
1649 $dont_use_counter ||= 0;
1650 $do_tco ||= 0;
1651 $ansi ||= 0;
1652 if (!eval {SetTTY()}) { ## Put into raw mode.
1653 warn $@ if $@;
1654 $dumb_term = 1;
1655 return readline_dumb;
1656 }
1657  
1658 *KeyMap = $var_EditingMode;
1659 undef($AcceptLine); ## When set, will return its value.
1660 undef($ReturnEOF); ## ...unless this on, then return undef.
1661 @Pending = (); ## Contains characters to use as input.
1662 @undo = (); ## Undo history starts empty for each line.
1663 @undoGroupS = (); ## Undo groups start empty for each line.
1664 undef $memorizedArg; ## No digitArgument memorized
1665 undef $memorizedPos; ## No position memorized
1666  
1667 undef $Vi_undo_state;
1668 undef $Vi_undo_all_state;
1669  
1670 # We need to do some additional initialization for vi mode.
1671 # RS: bug reports/platform issues are welcome: russ@dvns.com
1672 if ($KeyMap{'name'} eq 'vi_keymap'){
1673 &F_ViInput();
1674 if ($rl_vi_replace_default_on_insert){
1675 local $^W=0;
1676 my $Orig = $Term::ReadLine::TTYtter::term->ornaments();
1677 eval {
1678 # Term::ReadLine does not expose its $terminal, so make another
1679 require Term::Cap;
1680 my $terminal = Tgetent Term::Cap ({OSPEED=>9600});
1681 # and be sure the terminal supports highlighting
1682 $terminal->Trequire('mr');
1683 };
1684 if (!$@ and $Orig ne ',,,'){
1685 $Term::ReadLine::TTYtter::term->ornaments
1686 (join(',', (split(/,/, $Orig))[0,1]) . ',mr,me')
1687 }
1688 my $F_SelfInsert_Real = \&F_SelfInsert;
1689 *F_SelfInsert = sub {
1690 $Term::ReadLine::TTYtter::term->ornaments($Orig);
1691 &F_ViChangeEntireLine;
1692 local $^W=0;
1693 *F_SelfInsert = $F_SelfInsert_Real;
1694 &F_SelfInsert;
1695 };
1696 my $F_ViEndInsert_Real = \&F_ViEndInsert;
1697 *F_ViEndInsert = sub {
1698 $Term::ReadLine::TTYtter::term->ornaments($Orig);
1699 local $^W=0;
1700 *F_SelfInsert = $F_SelfInsert_Real;
1701 *F_ViEndInsert = $F_ViEndInsert_Real;
1702 &F_ViEndInsert;
1703 $force_redraw = 1;
1704 redisplay();
1705 };
1706 }
1707 }
1708  
1709 if ($rl_default_selected) {
1710 redisplay_high();
1711 } else {
1712 &redisplay(); ## Show the line (prompt+default at this point).
1713 }
1714  
1715 # pretend input if we 'Operate' on more than one line
1716 &F_OperateAndGetNext($rl_OperateCount) if $rl_OperateCount > 0;
1717  
1718 $rl_first_char = 1;
1719 while (!defined($AcceptLine)) {
1720 ## get a character of input (this can be UTF-8 now)
1721 $input = &getc_with_pending(); # bug in debugger, returns 42. - No more!
1722  
1723 if (unpack("H*", $input) eq '04' && $rl_first_char) { # CTRL-D
1724 $AcceptLine = $ReturnEOF = 1;
1725 last;
1726 }
1727  
1728 unless (defined $input) {
1729 # XXX What to do??? Until this is clear, just pretend we got EOF
1730 $AcceptLine = $ReturnEOF = 1;
1731 last;
1732 }
1733 preserve_state();
1734  
1735 $ThisCommandKilledText = 0;
1736 ##print "\n\rline is @$D:[$line]\n\r"; ##DEBUG
1737 kill($SIGUSR1, $background_control) if ($background_control);
1738  
1739 my $cmd = get_command($var_EditingMode, ord($input));
1740 if ( $rl_first_char && $cmd =~ /^F_(SelfInsert$|Yank)/
1741 && length $line && $rl_default_selected ) {
1742 # (Backward)?DeleteChar specialcased in the code
1743 $line = '';
1744 $D = 0;
1745 $cmd = 'F_BackwardDeleteChar' if $cmd eq 'F_DeleteChar';
1746 }
1747 undef $doingNumArg;
1748 &$cmd(1, ord($input)); ## actually execute input
1749 $rl_first_char = 0;
1750 $lastcommand = $cmd;
1751 *KeyMap = $var_EditingMode; # JP: added
1752  
1753 # In Vi command mode, don't position the cursor beyond the last
1754 # character of the line buffer.
1755 &F_BackwardChar(1) if $Vi_mode and $line ne ''
1756 and &at_end_of_line and $KeyMap{'name'} eq 'vicmd_keymap';
1757  
1758 &redisplay();
1759 $LastCommandKilledText = $ThisCommandKilledText;
1760 kill($SIGUSR1, $background_control) if ($background_control);
1761 }
1762  
1763 $in_readline = 0;
1764 undef @undo; ## Release the memory.
1765 undef @undoGroupS; ## Release the memory.
1766 &ResetTTY; ## Restore the tty state.
1767 $| = $oldbar;
1768 select $old;
1769 return undef if defined($ReturnEOF);
1770 $AcceptLine = "\x{263A}".$AcceptLine;
1771 #print STDOUT "hex line is ", unpack("H*", $AcceptLine), "\n";
1772 $AcceptLine = pack("U0H*", substr(unpack("U0H*", $AcceptLine), 6));
1773 #print STDOUT "line is ",unpack("H*", $AcceptLine), "\n";
1774 #print STDOUT "|al=`$AcceptLine'";
1775 $AcceptLine; ## return the line accepted.
1776 }
1777  
1778 ## ctrl(ord('a')) will return the ordinal for Ctrl-A.
1779 sub ctrl {
1780 $_[0] ^ (($_[0]>=ord('a') && $_[0]<=ord('z')) ? 0x60 : 0x40);
1781 }
1782  
1783  
1784  
1785 sub SetTTY {
1786 return if $dumb_term || $stdin_not_tty;
1787 #return system 'stty raw -echo' if defined &DB::DB;
1788 if (defined $term_readkey) {
1789 Term::ReadKey::ReadMode(4, $term_IN);
1790 if ($^O eq 'MSWin32') {
1791 # If we reached this, Perl isn't cygwin; Enter sends \r; thus we need binmode
1792 # XXXX Do we need to undo??? $term_IN is most probably private now...
1793 binmode $term_IN;
1794 }
1795 return 1;
1796 }
1797 # system 'stty raw -echo';
1798  
1799 $sgttyb = ''; ## just to quiet "perl -w";
1800 if ($useioctl && $^O ne 'solaris' && defined $TIOCGETP
1801 && &ioctl($term_IN,$TIOCGETP,$sgttyb)) {
1802 @tty_buf = unpack($sgttyb_t,$sgttyb);
1803 if (defined $ENV{OS2_SHELL}) {
1804 $tty_buf[3] &= ~$mode;
1805 $tty_buf[3] &= ~$ECHO;
1806 } else {
1807 $tty_buf[4] |= $mode;
1808 $tty_buf[4] &= ~$ECHO;
1809 }
1810 $sgttyb = pack($sgttyb_t,@tty_buf);
1811 &ioctl($term_IN,$TIOCSETP,$sgttyb) || die "Can't ioctl TIOCSETP: $!";
1812 } elsif (!$usestty) {
1813 return 0;
1814 } else {
1815 warn <<EOW if $useioctl and not defined $ENV{PERL_READLINE_NOWARN};
1816 Can't ioctl TIOCGETP: $!
1817 Consider installing Term::ReadKey from CPAN site nearby
1818 at http://www.perl.com/CPAN
1819 Or use
1820 perl -MCPAN -e shell
1821 to reach CPAN. Falling back to 'stty'.
1822 If you do not want to see this warning, set PERL_READLINE_NOWARN
1823 in your environment.
1824 EOW
1825 # '; # For Emacs.
1826 $useioctl = 0;
1827 system 'stty raw -echo' and ($usestty = 0, die "Cannot call `stty': $!");
1828 if ($^O eq 'MSWin32') {
1829 # If we reached this, Perl isn't cygwin, but STTY is present ==> cygwin
1830 # The symptoms: now Enter sends \r; thus we need binmode
1831 # XXXX Do we need to undo??? $term_IN is most probably private now...
1832 binmode $term_IN;
1833 }
1834 }
1835 return 1;
1836 }
1837  
1838 sub ResetTTY {
1839 return if $dumb_term || $stdin_not_tty;
1840 #return system 'stty -raw echo' if defined &DB::DB;
1841 if (defined $term_readkey) {
1842 return Term::ReadKey::ReadMode(0, $term_IN);
1843 }
1844  
1845 # system 'stty -raw echo';
1846 if ($useioctl) {
1847 &ioctl($term_IN,$TIOCGETP,$sgttyb) || die "Can't ioctl TIOCGETP: $!";
1848 @tty_buf = unpack($sgttyb_t,$sgttyb);
1849 if (defined $ENV{OS2_SHELL}) {
1850 $tty_buf[3] |= $mode;
1851 $tty_buf[3] |= $ECHO;
1852 } else {
1853 $tty_buf[4] &= ~$mode;
1854 $tty_buf[4] |= $ECHO;
1855 }
1856 $sgttyb = pack($sgttyb_t,@tty_buf);
1857 &ioctl($term_IN,$TIOCSETP,$sgttyb) || die "Can't ioctl TIOCSETP: $!";
1858 } elsif ($usestty) {
1859 system 'stty -raw echo' and die "Cannot call `stty': $!";
1860 }
1861 }
1862  
1863 # Substr_with_props: gives the substr of prompt+string with embedded
1864 # face-change commands
1865  
1866 sub substr_with_props {
1867 my ($p, $s, $from, $len, $ket, $bsel, $esel) = @_;
1868 my $lp = length $p;
1869  
1870 defined $from or $from = 0;
1871 defined $len or $len = length($p) + length($s) - $from;
1872 unless (defined $ket) {
1873 warn 'bug in Term::ReadLine::Perl, please report to its author cpan@ilyaz.org';
1874 $ket = '';
1875 }
1876 # We may draw over to put cursor in a correct position:
1877 $ket = '' if $len < length($p) + length($s) - $from; # Not redrawn
1878  
1879 if ($from >= $lp) {
1880 $p = '';
1881 $s = substr $s, $from - $lp;
1882 $lp = 0;
1883 } else {
1884 $p = substr $p, $from;
1885 $lp -= $from;
1886 $from = 0;
1887 }
1888 $s = substr $s, 0, $len - $lp;
1889 $p =~ s/^(\s*)//; my $bs = $1;
1890 $p =~ s/(\s*)$//; my $as = $1;
1891 $p = $rl_term_set->[0] . $p . $rl_term_set->[1]
1892 if (length($p) && $use_ansi) ;
1893 $p = "$bs$p$as";
1894 $ket = chop $s if $ket;
1895 if (defined $bsel and $bsel != $esel) {
1896 $bsel = $len if $bsel > $len;
1897 $esel = $len if $esel > $len;
1898 }
1899 if (defined $bsel and $bsel != $esel) {
1900 get_ornaments_selected;
1901 $bsel -= $lp; $esel -= $lp;
1902 my ($pre, $sel, $post) =
1903 (substr($s, 0, $bsel),
1904 substr($s, $bsel, $esel-$bsel),
1905 substr($s, $esel));
1906 if ($use_ansi) {
1907 $pre = $rl_term_set->[2] . $pre . $rl_term_set->[3] if length $pre;
1908 $sel = $rl_term_set->[4] . $sel . $rl_term_set->[5] if length $sel;
1909 $post = $rl_term_set->[2] . $post . $rl_term_set->[3] if length $post;
1910 }
1911 $s = "$pre$sel$post"
1912 } else {
1913 $s = $rl_term_set->[2] . $s . $rl_term_set->[3] if
1914 (length($s) && $use_ansi);
1915 }
1916  
1917 if (!$lp) { # Should not happen...
1918 return $s;
1919 } elsif (!length $s) { # Should not happen
1920 return $p;
1921 } else { # Do not underline spaces in the prompt
1922 return ("$p$s"
1923 . (length $ket ? ($rl_term_set->[0] . $ket . $rl_term_set->[1]) : ''))
1924 if ($use_ansi);
1925 return "$p$s$ket";
1926 }
1927 }
1928  
1929 sub redisplay_high {
1930 get_ornaments_selected();
1931 @$rl_term_set[2,3,4,5] = @$rl_term_set[4,5,2,3];
1932 &redisplay(); ## Show the line, default inverted.
1933 @$rl_term_set[2,3,4,5] = @$rl_term_set[4,5,2,3];
1934 $force_redraw = 1;
1935 }
1936  
1937 ## compute the displayed length of the line. affected by $do_tco.
1938 sub dlength {
1939 my $x = shift;
1940 return ($do_tco) ? length(&$do_tco($x)) : length($x);
1941 }
1942  
1943 ##
1944 ## redisplay()
1945 ##
1946 ## Updates the screen to reflect the current $line.
1947 ##
1948 ## For the purposes of this routine, we prepend the prompt to a local copy of
1949 ## $line so that we display the prompt as well. We then modify it to reflect
1950 ## that some characters have different sizes (i.e. control-C is represented
1951 ## as ^C, tabs are expanded, etc.)
1952 ##
1953 ## This routine is somewhat complicated by two-byte characters.... must
1954 ## make sure never to try do display just half of one.
1955 ##
1956 ## NOTE: If an argument is given, it is used instead of the prompt.
1957 ##
1958 ## This is some nasty code.
1959 ##
1960 sub redisplay
1961 {
1962 ## local $line has prompt also; take that into account with $D.
1963 local($prompt) = defined($_[0]) ? $_[0] : $prompt;
1964 my ($thislen, $have_bra);
1965 my($dline) = $prompt . $line;
1966 local($D) = $D + length($prompt);
1967 my ($bsel, $esel);
1968 if (defined pos $line) {
1969 $bsel = (pos $line) + length $prompt;
1970 }
1971 my ($have_ket) = '';
1972  
1973 ##
1974 ## If the line contains anything that might require special processing
1975 ## for displaying (such as tabs, control characters, etc.), we will
1976 ## take care of that now....
1977  
1978 # not UTF-8 safe?
1979  
1980 ##
1981 if ($dline =~ m/[^\x20-\x7e]/)
1982 {
1983 local($new, $Dinc, $c) = ('', 0);
1984  
1985 ## Look at each character of $dline in turn.....
1986 for ($i = 0; $i < length($dline); $i++) {
1987 $c = substr($dline, $i, 1);
1988  
1989 ## A tab to expand...
1990 if ($c eq "\t") {
1991 $c = ' ' x (8 - (($i-length($prompt)) % 8));
1992  
1993 ## A control character....
1994 } elsif ($c =~ tr/\000-\037//) {
1995 $c = sprintf("^%c", ord($c)+ord('@'));
1996  
1997 ## the delete character....
1998 } elsif (ord($c) == 127) {
1999 $c = '^?';
2000 }
2001 $new .= $c;
2002  
2003 ## Bump over $D if this char is expanded and left of $D.
2004 $Dinc += length($c) - 1 if (length($c) > 1 && $i < $D);
2005 ## Bump over $bsel if this char is expanded and left of $bsel.
2006 $bsel += length($c) - 1 if (defined $bsel && length($c) > 1 && $i < $bsel);
2007 }
2008 $dline = $new;
2009 $D += $Dinc;
2010 }
2011  
2012 ##
2013 ## Now $dline is what we'd like to display.
2014 ##
2015 ## If it's too long to fit on the line, we must decide what we can fit.
2016 ##
2017 ## If we end up moving the screen index ($si) [index of the leftmost
2018 ## character on the screen], to some place other than the front of the
2019 ## the line, we'll have to make sure that it's not on the first byte of
2020 ## a 2-byte character, 'cause we'll be placing a '<' marker there, and
2021 ## that would screw up the 2-byte character.
2022 ##
2023 ## $si is preserved between several displays (if possible).
2024 ##
2025 ## Similarly, if the line needs chopped off, we make sure that the
2026 ## placement of the tailing '>' won't screw up any 2-byte character in
2027 ## the vicinity.
2028 ##
2029 if ($D == length($prompt)) {
2030 $si = 0; ## display from the beginning....
2031 } elsif ($si >= $D) { # point to the left
2032 $si = &max(0, $D - $rl_margin - 7);
2033 $si-- if $si > 0 && $si != length($prompt) && !&OnSecondByte($si);
2034 } elsif ($si + $rl_screen_width - 7 <= $D) { # Point to the right
2035 $si = &min(length($dline), ($D - $rl_screen_width) + $rl_margin);
2036 $si-- if $si > 0 && $si != length($prompt) && !&OnSecondByte($si);
2037 } elsif (length($dline) - $si < $rl_screen_width - $rl_margin and $si) {
2038 # Too little of the line shown
2039 $si = &max(0, length($dline) - $rl_screen_width + 3);
2040 $si-- if $si > 0 && $si != length($prompt) && !&OnSecondByte($si);
2041 } else {
2042 ## Fine as-is.... don't need to change $si.
2043 }
2044 $have_bra = 1 if $si != 0; # Need the "chopped-off" marker
2045  
2046 $thislen = &min(length($dline) - $si, $rl_screen_width - 7);
2047 # lengthy
2048 if ($si + $thislen < length($dline)) {
2049 ## need to place a '>'... make sure to place on first byte.
2050 $thislen-- if &OnSecondByte($si+$thislen-1);
2051 substr($dline, $si+$thislen-1,1) = '>';
2052 $have_ket = 1;
2053 }
2054  
2055 ##
2056 ## Now know what to display.
2057 ## Must get substr($dline, $si, $thislen) on the screen,
2058 ## with the cursor at $D-$si characters from the left edge.
2059 ##
2060 $dline = substr($dline, $si, $thislen);
2061 $delta = $D - $si; ## delta is cursor distance from beginning of $dline.
2062 if (defined $bsel) {
2063 $bsel -= $si;
2064 $esel = $delta;
2065 ($bsel, $esel) = ($esel, $bsel) if $bsel > $esel;
2066 $bsel = 0 if $bsel < 0;
2067 if ($have_ket) {
2068 $esel = $thislen - 1 if $esel > $thislen - 1;
2069 } else {
2070 $esel = $thislen if $esel > $thislen;
2071 }
2072 }
2073 if ($si >= length($prompt)) { # Keep $dline for $lastredisplay...
2074 $prompt = ($have_bra ? "<" : "");
2075 $dline = substr $dline, 1; # After prompt
2076 $bsel = 1 if defined $bsel and $bsel == 0;
2077 } else {
2078 $dline = substr($dline, (length $prompt) - $si);
2079 $prompt = substr($prompt,$si);
2080 substr($prompt, 0, 1) = '<' if $si > 0;
2081 }
2082 # Now $dline is the part after the prompt...
2083  
2084 # add our character counter, plus padding if we deleted a wide character
2085 $dline = $dline.($dont_use_counter ? ' ' :
2086 (' <'.sprintf("%03i", &dlength($line)))) . " ";
2087  
2088 ##
2089 ## Now must output $dline, with cursor $delta spaces from left of TTY
2090 ##
2091  
2092 local ($\, $,) = ('','');
2093  
2094 #print $term_OUT "xyz" . $prompt . $dline;
2095 #$force_redraw = 1;
2096  
2097 ##
2098 ## If $force_redraw is not set, we can attempt to optimize the redisplay
2099 ## However, if we don't happen to find an easy way to optimize, we just
2100 ## fall through to the brute-force method of re-drawing the whole line.
2101 ##
2102 if (not $force_redraw and not defined $bsel)
2103 {
2104 ## can try to optimize here a bit.
2105  
2106 ## For when we only need to move the cursor
2107 if ($lastredisplay eq $dline and $lastpromptlen == length $prompt) {
2108 ## If we need to move forward, just overwrite as far as we need.
2109 if ($lastdelta < $delta) {
2110 print $term_OUT
2111 substr_with_props($prompt, $dline,
2112 $lastdelta, $delta-$lastdelta, $have_ket);
2113 ## Need to move back.
2114 } elsif($lastdelta > $delta) {
2115 ## Two ways to move back... use the fastest. One is to just
2116 ## backspace the proper amount. The other is to jump to the
2117 ## the beginning of the line and overwrite from there....
2118  
2119 my $out = substr_with_props($prompt, $dline, 0, $delta, $have_ket);
2120 if ($lastdelta - $delta <= length $out) {
2121 print $term_OUT "\b" x ($lastdelta - $delta);
2122 } else {
2123 print $term_OUT "\r", $out;
2124 }
2125 }
2126 ($lastlen, $lastredisplay, $lastdelta, $lastpromptlen)
2127 = ($thislen, $dline, $delta, length $prompt);
2128 # print $term_OUT "\a"; # Debugging
2129 return;
2130 }
2131  
2132 ## for when we've just added stuff to the end
2133 if ($thislen > $lastlen &&
2134 $lastdelta == $lastlen &&
2135 $delta == $thislen &&
2136 $lastpromptlen == length($prompt) &&
2137 substr($dline, 0, $lastlen - $lastpromptlen) eq $lastredisplay)
2138 {
2139 print $term_OUT substr_with_props($prompt, $dline,
2140 $lastdelta, undef, $have_ket);
2141 # print $term_OUT "\a"; # Debugging
2142 ($lastlen, $lastredisplay, $lastdelta, $lastpromptlen)
2143 = ($thislen, $dline, $delta, length $prompt);
2144 return;
2145 }
2146  
2147 ## There is much more opportunity for optimizing.....
2148 ## something to work on later.....
2149 }
2150  
2151 ##
2152 ## Brute force method of redisplaying... redraw the whole thing.
2153 ##
2154  
2155 print $term_OUT "\r" . substr_with_props($prompt, $dline, 0, undef, $have_ket, $bsel, $esel);
2156 my $back = length ($dline) + length ($prompt) - $delta;
2157 $back += $lastlen - $thislen,
2158 print $term_OUT ' ' x ($lastlen - $thislen) if $lastlen > $thislen;
2159  
2160 if ($back) {
2161 my $out = substr_with_props($prompt, $dline, 0, $delta, $have_ket, $bsel, $esel);
2162 if ($back <= length $out and not defined $bsel) {
2163 print $term_OUT "\b" x $back;
2164 } else {
2165 print $term_OUT "\r" . $out;
2166 }
2167 }
2168  
2169 ($lastlen, $lastredisplay, $lastdelta, $lastpromptlen)
2170 = ($thislen, $dline, $delta, length $prompt);
2171  
2172 $force_redraw = 0;
2173 }
2174  
2175 sub min { $_[0] < $_[1] ? $_[0] : $_[1]; }
2176  
2177 sub getc_hex {
2178 # this is definitely the WRONG WAY to fix this non-UTF-8 safe code, but
2179 # it works with the really old moldy code and new stuff, so there it is.
2180 # we use U0 when in a UTF-8 locale to help us on other systems like Ubuntu
2181 # and 10.6. systems like 10.4 (mostly) pass us UTF-8 regardless of locale.
2182 # we can't trust what we get from @Pending *or* rl_getc, so we need to
2183 # parse it all out.
2184 #
2185 my $w = (unpack(
2186 (($UUTF8) ? "U0H*" : "H*"), (@Pending ? shift(@Pending) : &$rl_getc)));
2187 #print $term_OUT "\nsequence: $w\n";
2188 # Mac OS X 10.4 keeps inserting these spurious $16 characters.
2189 return &getc_hex if ($w eq '16'); # recursive call
2190 return $w if (length($w) == 2); # UNICODE
2191 my $i;
2192 my $j = '';
2193 for($i=0; $i<length($w); $i+=2) {
2194 my $p = substr($w, $i, 2); # UNICODE
2195 $j .= $p if ($p ne '16');
2196 }
2197 return $j;
2198 }
2199 sub getc_with_pending {
2200 # use our stubbed out getc_hex to safely return hex fragments of a UTF-8 char.
2201 my $wey = &getc_hex; # this could get any number of bytes. we accommodate.
2202 my $key = $wey;
2203 my $i = hex(substr($key, 0, 2));
2204 my $chars_in_seq = ($ULATIN1) ? 2 :
2205 ($i >= 194 && $i <= 223) ? 4 :
2206 ($i >= 224 && $i <= 239) ? 6 :
2207 ($i >= 240 && $i <= 244) ? 8 : 2;
2208 while (length($key) < $chars_in_seq) {
2209 # this is a gross hack to deal with ISO-8859-1 getting in our
2210 # stream. it should work even if we get multiple Latin-1 chars
2211 # back to back, but could spew invalid UTF-8, so deal or fix your
2212 # keymap locale, beyotches.
2213 my $i = &getc_hex;
2214 last if (hex($i) < 128 || hex($i) > 191);
2215 $key .= $i;
2216 }
2217 $key = (length($key) == 2)
2218 ? ((hex($key) < 128) ? pack("H*", $key) :
2219 pack("U*", unpack("C*", pack("H*", $key)))) # AUGH THE PAIN THE PAIN
2220 : pack("U0H*", $key);
2221  
2222 #print STDOUT "result = ", unpack("H*", $key), "\n";
2223  
2224 # Save keystrokes for vi '.' command
2225 push(@$Dot_buf, $key) if $Dot_buf;
2226  
2227 $key;
2228 }
2229  
2230 sub rl_getc {
2231 my $key; # JP: Added missing declaration
2232 if (defined $term_readkey) { # XXXX ???
2233 $Term::ReadLine::TTYtter::term->Tk_loop
2234 if $Term::ReadLine::toloop && defined &Tk::DoOneEvent;
2235 $key = Term::ReadKey::ReadKey(0, $term_IN);
2236 } else {
2237 $key = $Term::ReadLine::TTYtter::term->get_c;
2238 }
2239 }
2240  
2241 ##
2242 ## get_command(keymap, ord_command_char)
2243 ##
2244 ## If the KEYMAP has an entry for COMMAND, it is returned.
2245 ## Otherwise, the default command is returned.
2246 ##
2247 sub get_command
2248 {
2249 local *KeyMap = shift;
2250 my ($key) = @_;
2251 my $cmd = defined($KeyMap[$key]) ? $KeyMap[$key]
2252 : ($KeyMap{'default'} || 'F_Ding');
2253 if (!defined($cmd) || $cmd eq ''){
2254 warn "internal error (key=$key)";
2255 $cmd = 'F_Ding';
2256 }
2257 $cmd
2258 }
2259  
2260 ##
2261 ## do_command(keymap, numericarg, command)
2262 ##
2263 ## If the KEYMAP has an entry for COMMAND, it is executed.
2264 ## Otherwise, the default command for the keymap is executed.
2265 ##
2266 sub do_command
2267 {
2268 my ($keymap, $count, $key) = @_;
2269 my $cmd = get_command($keymap, $key);
2270  
2271 local *KeyMap = $keymap; # &$cmd may expect it...
2272 &$cmd($count, $key);
2273 $lastcommand = $cmd;
2274 }
2275  
2276 ##
2277 ## Save whatever state we wish to save as an anonymous array.
2278 ## The only other function that needs to know about its encoding is getstate/preserve_state.
2279 ##
2280 sub savestate
2281 {
2282 [$D, $si, $LastCommandKilledText, $KillBuffer, $line, @_];
2283 }
2284  
2285 # consolidate only-movement changes together...
2286 sub preserve_state {
2287 return if $Vi_mode;
2288 push(@undo, savestate()), return unless @undo;
2289 my $last = $undo[-1];
2290 my @only_movement;
2291 if ( #$last->[1] == $si and $last->[2] eq $LastCommandKilledText
2292 # and $last->[3] eq $KillBuffer and
2293 $last->[4] eq $line ) {
2294 # Only position changed; remove old only-position-changed records
2295 pop @undo if $undo[-1]->[5];
2296 @only_movement = 1;
2297 }
2298 push(@undo, savestate(@only_movement));
2299 }
2300  
2301 ##
2302 ## $_[1] is an ASCII ordinal; inserts as per $count.
2303 ##
2304 sub F_SelfInsert
2305 {
2306 remove_selection();
2307 my ($count, $ord) = @_;
2308 #my $text2add = pack('C', $ord) x $count;
2309 my $text2add = chr($ord) x $count;
2310  
2311 if ($InsertMode) {
2312 substr($line,$D,0) .= $text2add;
2313 } else {
2314 ## note: this can screw up with 2-byte characters.
2315 substr($line,$D,length($text2add)) = $text2add;
2316 }
2317 $D += length($text2add);
2318 }
2319  
2320 ##
2321 ## Return the line as-is to the user.
2322 ##
2323 sub F_AcceptLine
2324 {
2325 &add_line_to_history;
2326 $AcceptLine = $line;
2327 local $\ = '';
2328 print $term_OUT "\r\n";
2329 $force_redraw = 0;
2330 (pos $line) = undef; # Another way to force redraw...
2331 }
2332  
2333 sub add_line_to_history
2334 {
2335 ## Insert into history list if:
2336 ## * bigger than the minimal length
2337 ## * not same as last entry
2338 ##
2339 if (length($line) >= $minlength
2340 && (!@rl_History || $rl_History[$#rl_History] ne $line)
2341 ) {
2342 ## if the history list is full, shift out an old one first....
2343 while (@rl_History >= $rl_MaxHistorySize) {
2344 shift(@rl_History);
2345 $rl_HistoryIndex--;
2346 }
2347  
2348 push(@rl_History, $line); ## tack new one on the end
2349 }
2350 }
2351  
2352  
2353 sub remove_selection {
2354 if ( $rl_first_char && length $line && $rl_default_selected ) {
2355 $line = '';
2356 $D = 0;
2357 return 1;
2358 }
2359 if ($rl_delete_selection and defined pos $line and $D != pos $line) {
2360 kill_text(pos $line, $D);
2361 return 1;
2362 }
2363 return;
2364 }
2365  
2366 #sub F_ReReadInitFile;
2367 #sub rl_getc;
2368 sub F_ForwardChar;
2369 sub F_BackwardChar;
2370 sub F_BeginningOfLine;
2371 sub F_EndOfLine;
2372 sub F_ForwardWord;
2373 sub F_BackwardWord;
2374 sub F_RedrawCurrentLine;
2375 sub F_ClearScreen;
2376 # sub F_SelfInsert;
2377 sub F_QuotedInsert;
2378 sub F_TabInsert;
2379 #sub F_AcceptLine;
2380 sub F_OperateAndGetNext;
2381 sub F_BackwardDeleteChar;
2382 sub F_DeleteChar;
2383 sub F_UnixWordRubout;
2384 sub F_UnixLineDiscard;
2385 sub F_UpcaseWord;
2386 sub F_DownCaseWord;
2387 sub F_CapitalizeWord;
2388 sub F_TransposeWords;
2389 sub F_TransposeChars;
2390 sub F_PreviousHistory;
2391 sub F_NextHistory;
2392 sub F_BeginningOfHistory;
2393 sub F_EndOfHistory;
2394 sub F_ReverseSearchHistory;
2395 sub F_ForwardSearchHistory;
2396 sub F_HistorySearchBackward;
2397 sub F_HistorySearchForward;
2398 sub F_KillLine;
2399 sub F_BackwardKillLine;
2400 sub F_Yank;
2401 sub F_YankPop;
2402 sub F_YankNthArg;
2403 sub F_KillWord;
2404 sub F_BackwardKillWord;
2405 sub F_Abort;
2406 sub F_DoLowercaseVersion;
2407 sub F_DoMetaVersion;
2408 sub F_DoControlVersion;
2409 sub F_Undo;
2410 sub F_RevertLine;
2411 sub F_EmacsEditingMode;
2412 sub F_Interrupt;
2413 sub F_PrefixMeta;
2414 sub F_UniversalArgument;
2415 sub F_DigitArgument;
2416 sub F_OverwriteMode;
2417 sub F_InsertMode;
2418 sub F_ToggleInsertMode;
2419 sub F_Suspend;
2420 sub F_Ding;
2421 sub F_PossibleCompletions;
2422 sub F_Complete;
2423 sub F_YankClipboard;
2424 sub F_CopyRegionAsKillClipboard;
2425 sub F_KillRegionClipboard;
2426 sub clipboard_set;
2427 sub F_BeginUndoGroup;
2428 sub F_EndUndoGroup;
2429 sub F_DoNothing;
2430 sub F_ForceMemorizeDigitArgument;
2431 sub F_MemorizeDigitArgument;
2432 sub F_UnmemorizeDigitArgument;
2433 sub F_ResetDigitArgument;
2434 sub F_MergeInserts;
2435 sub F_MemorizePos;
2436 sub F_BeginPasteGroup;
2437 sub F_EndPasteGroup;
2438 sub F_BeginEditGroup;
2439 sub F_EndEditGroup;
2440 sub F_Repaint;
2441  
2442 # Comment next line and __DATA__ line below to disable the selfloader.
2443  
2444 use SelfLoader;
2445  
2446 1;
2447  
2448 __DATA__