Sunday, December 16, 2012

Edit/open files quick


As developers, we edit lot of source files, and each has a specific extension
and mostly we either type them or let the shell do the auto-completion.
Most of the source files that I work on, follow this long_underscore_separated_names convention, and I hate to even press TAB TAB TAB...
When I know a file name, or am seeing it on console (with the previous ls), I want to be able to open a file (in the current directory) with as few keystrokes as possible.

I came up with a small Perl script, which, when combined with shell aliases
can be a real time saver (and save you from RSI as well! :) )
The same effect can be achieved with sed/awk or any other regex-well-supported
languages, but Perl is my favorite.

Approach

Given a file like: my_lisp_parser.c,  I want to be able to call it as
m l p or just mlp (first letters of the words, assuming file names separated with
underscore, or hyphen)
The extensions, lets not worry for now...
So, how do we go about?
The regex way...
build a regex from these characters and then do a quick look-up in the current dir:
like, m_l_p.
How to build this regex:
simple, split the input if its one word, or concat if its multiple words, but
before joining, add [^_-]*, that's the equivalent of our something above.

What to do in case of ambiguity, i.e, if we have a file like
my_lex_print.c (some hypothetical name, duh!)
then, using mlp will have a problem, so we should say
m le p
where le is the disambiguator.

So, now we can edit some files, with some extensions, what about those with
no extension ? usually I edit a lot of Makefile, that, I can handle as a
special case.

The extension is given as an argument to the script, but while using this
script, we do not invoke it directly, but with shell aliases, therefore
typing the extension will not be necessary. I use bash BTW, so here are my bash aliases (for most commonly used file extensions)

alias vc='~/short_open.pl c'
alias vh='~/short_open.pl h'
alias vp='~/short_open.pl p[ly]'
alias vy='~/short_open.pl yml'
alias vd='~/short_open.pl diff'
alias vs='~/short_open.pl sh'
alias vl='~/short_open.pl l[ou][ga]'
alias vm='~/short_open.pl mk'
 

I can open a .c file like vc mlp, or a .h file like vh mlp

The full script is here:

$editor = shift;
$ext = shift;

if ( scalar(@ARGV) == 1 ) {
    $in = shift;
    if ((length($in) == 1) and ($in eq 'm')) {
        system("$editor [Mm]akefile");
        exit 0;
    }
    if ((length($in) == 1) and ($in eq 'R')) {
        system("$editor README");
        exit 0;
    }
    if ((length($in) == 1) and ($in eq 'w')) {
        system("$editor wscript");
        exit 0;
    }
    @p = split( //, $in ); # 1 arg - pick and split each char
}
else {
    @p = (@ARGV); # multi arg - use them as is
}
$res = '^';
$res .= join( '[^_-]*[-_]', @p );
$res .= '[^_-]*[.]';
$res .= $ext . '$'; 
$re = qr/$res/;
foreach $a ( glob("*.$ext") ) {
    if ( $a =~ m/$re/ ) {
        print " [$a] \n";
        system ("$editor $a");
        exit 0;
    }
}

# If it were not really a long name with underscore, then try
# a plain short name (assume 1 arg)
if ( scalar(@ARGV) > 1 ) {
    exit 1;
}
$res = $in;  
$res .= '.*[.]';  # deliberate unbounded match so that any part
$res .= $ext;     # of the file name can be input
$re = qr/$res/;
foreach $a ( glob("*.$ext") ) {
    if ( $a =~ m/$re/ ) {
        print " [$a] \n";
        system ("$editor $a");
        exit 0;
    }
}


A safe `rm' for bash


I have many times typed
rm -rf *  !!
in a hurry, unknowingly
This can be really really upsetting, depending on which directory you
are in ! :)
While talking to my teammates on how to make rm a little safe, I
tried the following:
alias rm to a function, which will check the args and then force
interactive mode. The option check is simple, the only problem is
your function will not receive '*', as the shell would have already
expanded it!
The solution is to club alias and function, with disable globbing
and then re-enable it!

Thanks to Simon's article which helped me with this.

Full bash function here:

alias rm='set -f;rm_in'
rm_in() {
    local YN HIT LAST N
    N=$#
    LAST=${!N}
    if [[ $1 =~ -[fr]+ ]] && [[ $2 == '*' ]] ; then
        HIT=1
        echo -n "Are you insane ? (y/n): "
        read YN
    fi
    if [[ -z $HIT ]] ; then
        if [[ $LAST == '*' ]]; then
            HIT=1
            echo -n "This is li'll scary, are you sure ? (y/n): "
            read YN
        fi
    fi
    set +f
    if [[ ! -z $YN ]]; then
        if [[ $YN =~ [yY] ]] ; then
            echo "May it be! .."
            eval command rm "$@"
        else
            echo "Thank God!"
        fi
    fi
    if [[ -z $HIT ]] ; then
        eval command rm "$@"
    fi
}
  

Friday, September 21, 2012

How to format/highlight code/commands in mails

I hate to see mails which are not formatted, do not use monospaced font for code/command/logs. What is the point of writing a mail, without proper formatting, spell check, emphasis, punctuation!? I will leave the spell-check and punctuation for now. As a programmer, let me rant on the fonts and colors! ;-)

Monospace it!

How difficult is it to change the font of code snippets and commands, or logs to monospaced font!? I used to think, maybe its quite a bit of work, but... NO! Its really simple, I started using a simple macro with Outlook and Word, to change selected text to monospace (and I like Courier New) its really easy, I wont go into the details, there are lots of blogs and MS articles explaining how. Here is the code in VB:

Sub Change2MonoSpace()
' Macro - For MS WOrd
    Selection.Font.Name = "Courier New"
    Selection.Font.Size = 10
End Sub

Sub OLChange2Mono()
' Macro - For MS Outlook
    Dim objOL As Application
    Dim objDoc As Object
    Dim objSel As Object
    Set objOL = Application
    Set objDoc = objOL.ActiveInspector.WordEditor
    Set objSel = objDoc.Windows(1).Selection
    objSel.Font.Name = "Courier New"
    objSel.Font.Size = 10
End Sub


vim: TOhtml of the C classic.
Colorize

For code snippets, just making it monospaced, isn't sufficient IMO, its better to syntax highlight it, like your editor does. Again, this isn't difficult, I can think of more than one way to do it, which one is easy/simple - is a matter of personal taste.

1 - with PuTTY
    PuTTY has an option in Windows->Selection, "Paste to clipboard in RTF and plain text", enabling this, the selection, when pasted in MS Word or Outlook retains the colors.
 
2 - Vim
    Vim does too many things, and one of which is, the ex-mode command, :TOhtml, with which, a window appears, which has the HTML format of the current file/buffer - this can be saved, and later opened in IE to copy (the syntax highlight and background is as seen in the editor, the color scheme can be changed before conversion to suit needs)

3 - A special editor
    ScITE - Scintilla text editor has a copy option, to copy in RTF (but the highlight is only for supported languages, adding a new one is not simple, requires change in the code not like vim - i.e, users cant write a config/syntax-file)

4 - A utility
    Andre Simon's page has 2 awesome utilities:
    Highlight - syntax highlight source files
    Ansifilter - to colorize the console dumps which contain ANSI escape sequences

In these days where plain text mails are seldom used, the rich-text/HTML mails that we send/receive, can, and should be made to look much more beautiful!

Do not fear learning - fear only forgetting!

This might sound stupid, like, why would anyone fear learning!? But from my observation, once an engineer has been in the industry for long, there is some reluctance to change, changing to new language, or to a new platform, or even to change to a new company.  The reason seems to be fear, at least in part! The fear to cope up with change, and the fear to learn! When it comes to software, which is changing so rapidly, if we are not learning new things every now and then, for sure we will be left behind!

My fear is, on the contrary, about forgetting!, There are so many things which I had learnt as a fresh grad, as a fresher in my first company... but without constant use, all those seems to have faded from memory! :-(. The only way, is to constantly refresh things I've learnt.  At some point, I thought, how nice it would be, if my memory was like a fast access disk - low latency, huge store!  but then, even a fast SDD (using DRAM), requires a periodic memory refresh cycle to retain the charge!!  :-)
So, refresh is the only defense!

Thursday, September 20, 2012

Why is command line cool!? :)

As a developer, I love command-line!, instead of a few clicks here and there on a GUI, I would rather pipe, filter, combine and make new shortcuts to do things quickly and efficiently.
libcli generated CLI sample
While in college, once I got used to the Unix shells, doing anything on Windows shell was a pain!, mainly because of the lack of auto-completion! It was even more painful, when I started using Java on windows (without any funky IDEs). First of all, I hate CamelCase, and since that is default in Java, running
javac SomeLongFileName.java
and then
java SomeLongFile...
over and over, in the edit-compile cycle, made me create my first shell! :). I called it ACSH (Auto Command Completion Shell) :), all it did was to find the file names in current directory (DIRENT..), and then do the completion based on the first few characters, finally, on Enter, use system() :). Simple, but worked well, some of my friends also used it.

At that point, I didn't know about command modes, or, structuring the commands in a tree like hierarchy. Only after encountering the IOS (note the case - not iOS!) parser did I get more ideas on command line. But then I had lost my ACSH source (since Yahoo Geocities closed down, and I didn't take a backup! :-(, I might still have it somewhere on old Floppies or disks, I don't have time to find it!), while discussing the IOS command line capability with a friend, I created a bare-bones implementation using a Trie, worked well  long time after, when I started working on a module, which had a simulator and dumb CLI, I could not bear to use it! I enhanced my Trie based CLI to create a library, with some capabilities of IOS parser and a few bash like features, and plugged it in. I continue to maintain it, and keep adding new features, whenever I get some idea about how-to-make-command-line-more-usable :)

Many people think command line is dead!, and funky GUIs are the way to go! that isn't true!, just think - why did MS create the PowerShell in 2006 !?

CLI is cool because it get things done, quick! and it can be re-combined, re-configured, aliased, with use, you can be faster ...