[TxMt] Getting one character from the keyboard for use in Commands

Dr. Drang drdrang at gmail.com
Tue Feb 20 15:10:16 UTC 2007


On Feb 20, 2007, at 5:21 AM, Chris Insinger wrote:

> I'm new to TM and trying to implement a Command that fills the  
> current selection with a character. Right now I have a simple  
> program that replaces every character in the current selection with  
> a space character (but skips CR/LF), so far so good.
> [snip]
> Ideally I'd like to:
>
> 1) select an area of text
> 2) press ^F (or whatever)
> 3) get a character from the keyboard
> 4) use that character to fill the selection
>
> How do I accomplish #3 above?

Others may have better ideas, but I think Step 3 is best done by  
inserting your command as a snippet. Here's a Perl script that seems  
to work.

     #!/usr/bin/env perl
     @lines = split /\n/, $ENV{'TM_SELECTED_TEXT'};
     until ($line = shift @lines) {
       print "\n";
     }
     print '${1:x}' . ('$1' x (length($line)-1));
     foreach $line (@lines) {
       print "\n" . ('$1' x length($line));
     }
     print '$0';

The until loop handles an edge case where the first lines of the  
selection are empty. I would not be surprised to learn of other edge  
cases that I've missed.

Make this a new command, set the input to Selected Text or Nothing  
and the output to Insert as Snippet, and choose whatever Key  
Equivalent you like. To use it, select the text you want to change  
and press the Key Equivalent. Each selected character will change to  
"x," and the first will be selected. Enter the character you want to  
change it to, and they will all change. Press the Tab key to move the  
caret to the end of the original selection.

I've read that Perl "knows" what kind of line ending your system is  
using and automatically adjusts the effective value of "\n" to match  
that. I have no experience with that feature, but that should make  
this work for CRLF line endings as well as LF line endings.

--
Dr. Drang






More information about the textmate mailing list