| 1 |
#!/usr/bin/env perl |
| 2 |
# |
| 3 |
# manexamp -- The examples which appear in the documentation are here. |
| 4 |
# |
| 5 |
# Copyright (C) 2024 Hiroo Hayashi |
| 6 |
# |
| 7 |
# Derived from: examples/manexamp.c in the GNU Readline Library |
| 8 |
# Copyright (C) 1987-2023 Free Software Foundation, Inc. |
| 9 |
|
| 10 |
use strict; |
| 11 |
use warnings; |
| 12 |
use Term::ReadLine; |
| 13 |
|
| 14 |
my $t = new Term::ReadLine 'manexamp'; |
| 15 |
my $a = $t->Attribs; |
| 16 |
|
| 17 |
# **************************************************************** |
| 18 |
# |
| 19 |
# How to Emulate gets () |
| 20 |
# |
| 21 |
# **************************************************************** |
| 22 |
# https://tiswww.case.edu/php/chet/readline/readline.html#Basic-Behavior |
| 23 |
|
| 24 |
# Read a string, and return it. Returns undef on EOF. |
| 25 |
sub rl_gets () { |
| 26 |
return $t->readline(''); |
| 27 |
} |
| 28 |
|
| 29 |
# **************************************************************** |
| 30 |
# |
| 31 |
# Writing a Function to be Called by Readline. |
| 32 |
# |
| 33 |
# **************************************************************** |
| 34 |
# https://tiswww.case.edu/php/chet/readline/readline.html#A-Readline-Example |
| 35 |
|
| 36 |
# Invert the case of the COUNT following characters. |
| 37 |
sub invert_case_line { |
| 38 |
my ($count, $key) = @_; |
| 39 |
|
| 40 |
my $start = $a->{point}; |
| 41 |
|
| 42 |
return 0 if $start >= $a->{end}; |
| 43 |
|
| 44 |
# Find the end of the range to modify. |
| 45 |
my $end = $start + $count; |
| 46 |
|
| 47 |
# Force it to be within range. |
| 48 |
if ($end > $a->{end}) { |
| 49 |
$end = $a->{end}; |
| 50 |
} elsif ($end < 0) { |
| 51 |
$end = 0; |
| 52 |
} |
| 53 |
|
| 54 |
return 0 if $start == $end; |
| 55 |
|
| 56 |
# For positive arguments, put point after the last changed character. For |
| 57 |
# negative arguments, put point before the last changed character. |
| 58 |
$a->{point} = $end; |
| 59 |
|
| 60 |
# Swap start and end if we are moving backwards. |
| 61 |
if ($start > $end) { |
| 62 |
my $temp = $start; |
| 63 |
$start = $end; |
| 64 |
$end = $temp; |
| 65 |
} |
| 66 |
|
| 67 |
# Tell readline that we are modifying the line, so it will save |
| 68 |
# undo information. |
| 69 |
$t->modifying($start, $end); |
| 70 |
|
| 71 |
# I'm happy with Perl :-) |
| 72 |
substr($a->{line_buffer}, $start, $end - $start) =~ tr/A-Za-z/a-zA-Z/; |
| 73 |
|
| 74 |
return 0; |
| 75 |
} |
| 76 |
|
| 77 |
$t->initialize(); |
| 78 |
$t->add_defun('invert-case-line', \&invert_case_line); |
| 79 |
$t->bind_key(ord 'c', 'invert-case-line', 'emacs-meta'); |
| 80 |
while (defined($_ = rl_gets())) { |
| 81 |
invert_case_line(1, ''); |
| 82 |
print "$_\n"; |
| 83 |
} |
| 84 |
exit 0; |