Monthly Archives: July 2008

Time Saving Vim Movement Tips

I must admit, even though I’ve been learning how to use Emacs, I’m still learning new tricks for Vim.

When I browse through the Vim help documents, I _always_ learn something new.

Today I will show you some time saving tips for moving around in Vim.

Basic

w - move forward by a word
Jack!  R_e_member that you have an appointment tomorrow.
w
Jack!  Remembe_r_ that you have an appointment tomorrow.

b - move backward by a word
Jack!  Remembe_r_ that you have an appointment tomorrow.
b
Jack!  _R_emember that you have an appointment tomorrow.

fx - search forward for the character x
Jack!  Reme_m_ber that you have an appointment tomorrow.
fo
Jack!  Remember that y_o_u have an appointment tomorrow.

tx - search to the character x
Jack!  Reme_m_ber that you have an appointment tomorrow.
to
Jack!  Remember that _y_ou have an appointment tomorrow.

Fx - search backward to the charater x
Jack!  Remember that _y_ou have an appointment tomorrow.
FR
Jack!  _R_emember that you have an appointment tomorrow.

Tx - search backward to the character x
Jack!  Remember that you have an _a_ppointment tomorrow.
Tc
Jac_k_!  Remember that you have an appointment tomorrow.

; - repeat command
, - repeat command in the opposite direction

% - move to matching paren, e.g. [{()}]
[_[_ -e ~/.xinitrc ]]
%
[[ -e ~/.xinitrc _]_]

Ctrl-U - move the window up a screenful
Ctrl-D - move the window down a screenful
Ctrl-E - move the window up a line (keep the cursor in the same place)
Ctrl-Y - move the window down a line (keep the cursor in the same place)
zt - move the window so the cursor is at the top of the screen
zb - move the window so the cursor is at the bottom of the screen
Advertisements

Configuring the default prompt (PS1)

I use the terminal every day and I have spent a lot of time customising its configuration, particularly the default prompt, to my liking.

Today, I will show you how to customise your default prompt, or PS1.  Before I show you my spartan configuration, let me explain.  I am a minimalist, so I do not see the point of having a long PS1 that shows a multitude of system information when the core *nix utils (/bin) can tell you that anyway.

Note: My terminal is rxvt-unicode, my shell is zsh, and I often run all my cli apps within GNU screen.

PS1="$(print '%{\e[1;31m%}%1%{\e[0m%} %{\e[1;32m%}%B%#%b%{\e[0m%} %(?..(%?%)) %_ \ek\e\\')"

Produces: ~ %

Explanation:  The entire PS1 expression is placed within a print command so my shell outputs a “null title-escape-sequence (<esc>k<esc>\) as a part of the prompt.”  GNU screen will then use the title-escape-sequence when naming the window (normally changed with C-a A).

%{\e[1;31m%}

– light red

%1

– trailing component of $PWD

%{\e[0m%}

– resets the color

%{\e[1;32m%}

– light green

%B

– start boldface mode

%#

– prints a # if I am a superuser (root) or a % if I am not.

%b

– end boldface mode

%{\e[0m%}

– resets the color

%(?..(%?%))

– takes advantage of zsh’s ternary expressions, which picks different strings depending on a test.  In this case, a message is displayed only if the exit code is not zero.

%_

: status of the parser (i.e. if, for, then, while)

\ek\e\\

– the title-escape-sequence for GNU screen

Other common variables you can use include:

%h

– history entry number

%m

– current hostname (up to any dot)

%n

– shows username

%D

– the date in yy-mm-dd format

See “zsh: Prompt Expansion” for the definitive list of zsh prompt sequences.

A list of “colour equivalences:”

Black       0;30     Dark Gray     1;30
Blue        0;34     Light Blue    1;34
Green       0;32     Light Green   1;32
Cyan        0;36     Light Cyan    1;36
Red         0;31     Light Red     1;31
Purple      0;35     Light Purple  1;35
Brown       0;33     Yellow        1;33
Light Gray  0;37     White         1;37

Using a handy script I got from the bash manual, here is a picture of my current color scheme (zenburn):

Adding additional email accounts to your email setup

Upon hearing that my college offers email access through its POP and SMTP servers, I immediately set out to integrate it into my email setup.

Today I will show you how.

Note: I use Mutt to read my email, getmail to retrieve my mail, procmail to filter my mail, and msmtp to send my mail.  This tutorial can also be used for configuring a new account in a similar setup.

Because my email setup is quite complicated, this will take longer to configure than it would with a mail client such as Thunderbird or Outlook.  However, I enjoy the level of customization offered by such a setup.

1. Setting up getmail

First, make sure that you have the .getmail directory in your home dir.  If not, create it (mkdir -m 700 ~/.getmail)

~ %  ls -la | grep getmail
drwx------  2 antony antony 4.0K 2008-07-09 17:30 .getmail/

Change to the .getmail directory and create the account file.

~ %  cd .getmail
.getmail %  touch getmailrc_college

Edit the file.  Note: !$ means the last space separated word from the previous command, in this case “getmailrc_college”

.getmail %  vim !$
1 [retriever]
2 type = SimplePOP3SSLRetriever
3 server = pop.college.edu
4 username = name
5 port = 995
6 password = password
7
8 [destination]
9 type = MDA_external
10 path = /usr/bin/procmail

Change the file permissions (read, write for user)

.getmail %  chmod 600 getmailrc_college

2. Setting up procmail

All we have to do is add a filter for email from the college domain address.  Note: Because my college email address can have a number 0-9 appended to the end of the username, I used the regex [0-9], which matches one digit.gt

.getmail %  cd
~ % vim ~/.procmailrc
20 :0
21 * ^TO_name[0-9]@college\.edu
22 college/

3. Setting up msmtp

This is the most involved step.

Security is always first, so check the available authentication options of the server.  I’ll use Gmail as an example (yep, straight from the manpage).

~ %  msmtp --serverinfo --host=smtp.gmail.com --tls=on --port=587 --tls-certcheck=off
SMTP server at smtp.gmail.com (yw-in-f109.google.com [74.125.47.109]), port 587:
    mx.google.com ESMTP 6sm2875694ywp.3
TLS certificate information:
    Owner:
        Common Name: smtp.gmail.com
        Organization: Google Inc
        Locality: Mountain View
        State or Province: California
        Country: US
    Issuer:
        Common Name: Thawte Premium Server CA
        Organization: Thawte Consulting cc
        Organizational unit: Certification Services Division
        Locality: Cape Town
        State or Province: Western Cape
        Country: ZA
[truncated]
Capabilities:
    SIZE 28311552:
        Maximum message size is 28311552 bytes = 27.00 MB
    STARTTLS:
        Support for TLS encryption via the STARTTLS command
    AUTH:
        Supported authentication methods:
        PLAIN LOGIN

The important part here is the issuer of the certificate (shown by the Common Name). In this case, the issuer is “Thawte Premium Server CA” so we need to download that certificate from the Thawte website and place it in our ~/.certs directory.

~ %  cd ~/.certs
.certs %  unzip thawte-roots.zip -d thawte [truncated output]
.certs %  cd thawte
thawte %  cd Thawte\ Server\ Roots
Thawte Server Roots %  ls
Thawte Server Roots.txt    ThawtePremiumServerCA.cer      ThawteServerCA.509  ThawteServerCA_b64.txt
ThawtePremiumServerCA.509  ThawtePremiumServerCA_b64.txt  ThawteServerCA.cer
Thawte Server Roots %  cp ThawtePremiumServerCA.cer ../../
Thawte Server Roots %  cd !$
.certs %  ls
ThawtePremiumServerCA.cer  thawte/  thawte-roots.zip
.certs %  rm -r thawte*

Now you can use TLS, so edit your ~/.msmtprc file

.certs %  cd
~ % vim .msmtprc
21 account college
22 host smtp.college.edu
23 from name@college.edu
24 user name@college.edu
25 password somepassword
26 port 587
27 auth on
28 tls on
29 tls_trust_file /home/antony/.certs/ThawtePremiumServerCA.crt

4. Next, configure Mutt for account switching.

~ %  cd .mutt

Create a profile for each account. Because I include my email address in my signature, I have to switch to a different signature when I change email accounts.  The unmy_hdr resets the my_hdr variable, which is then defined by the following my_hdrset sendmail= tells Mutt to use a different sendmail command.  And set compose_format changes the display at the bottom of the screen so I know which mail account I am using.

~ % vim muttrc.local1
  1 # default Mutt profile
  2 set signature="~/.signature"
  3 unmy_hdr
  4 my_hdr From: Antony Jepson <email@gmail.com>
  5 my_hdr Reply-To: Antony Jepson <email@gmail.com>
  6 set sendmail="/usr/bin/msmtp --account default"
  7 set compose_format="-- default Mutt: Compose [Approx. msg size: %l] Atts:%a]%>-"
~ % vim muttrc.local2
  1 # college Mutt profile
  2 set signature="~/.signature2"
  3 unmy_hdr
  4 my_hdr From: First Last <name@college.edu>
  5 my_hdr Reply-To: First Last <name@college.edu>
  6 set sendmail="/usr/bin/msmtp --account college"
  7 set compose_format="-- college Mutt: Compose [Approx. msg size: %l] Atts:%a]%>-"

All we have to do is add a keyboard-binding that will source each different profile.  This configuration will switch to a different profile when I press Control-q and Control-w.

.mutt %  vim macros.rc
  4 macro index "\Cq" ":source ~/.mutt/muttrc.local1\n" "Load default profile"
  5 macro index "\Cw" ":source ~/.mutt/muttrc.local2\n" "Load college profile"

And, if you are not already sourcing this rc file in the default mutt configuration, add it.

.mutt %  echo "source ~/.mutt/macros.rc" >> ~/.mutt/muttrc

5. Finally, because I will be using this address for the next four years, I’ll add it to my gpg key.

.mutt %  cd
~ %  gpg --edit-key Antony\ Jepson [truncated output]
Command> adduid
Real name: Antony Jepson
Email address: name@college.edu
Comment: College email
You selected this USER-ID:
    "Antony Jepson (College email) <name@college.edu>"

Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O

You need a passphrase to unlock the secret key for
    user: "Antony Jepson (College email) <name@college.edu>"
    [truncated]
    Passphrase: somepassphrase
Command> save

Finally, send your updated key to the keysever.

~ %  gpg --send-key name@college.edu

And that’s it.  You now (or I, at least) have a working, secure, additional, Mutt-enabled, email account!

I’m still getting used to the WYSIWYG WordPress formatting toolbar, I’ll make (hopefully better) use of it as I write more posts.

Setting up Mutt

Mutt is an extremely fast and flexible text-based mail user agent with local maildir, POP3, and IMAP support.  It is my default mail client by choice.  Today, I will show you my Mutt configuration; perhaps it’ll help you to setup Mutt as well.

The diagram to the left (created with Xy-pic) shows my ~/.mutt hierarchy.  I’ll explain what each file/directory contains and then I’ll concatenate my the main configuration file, ~/.mutt/muttrc.

~/.mutt/aliases.rc – contains a list of my contacts in the format:

alias shortname Firstname Lastname email@address.com

~/.mutt/cache/ – contains a cache my mail headers for faster access

~/.mutt/gpg.rc – contains the commands for use with pgp/gpg encryption

~/.mutt/lists.rc – contains the subscribe command for each mailing-list I am subscribed to.  The subscribe command makes Mutt behave differently when reading mailing-lists (changes the default reply-to to the mailing list).

~/.mutt/muttrc – the main configuration file.  It is heavily commented below for your convenience.

~/.mutt/muttrc.local{1,2,3} – supplemental configuration files used for when I switch email accounts.

~ %  cat ~/.mutt/muttrc

#==============================================================================#
set realname="Antony Jepson"    # My real name.
set sendmail="/usr/bin/msmtp"   # Sends the mail.
set edit_headers=no             # Can I edit headers of a message?
set index_format="%4C %Z %d %-15.15L (%-5c) %s" # Specify the index format.
# %4C - index number
# %Z - status flags
# %-15.15F - left justify the From: with a max of 15 characters
# %c - number of characters in the message
# %s - subject line

set date_format="%F"
set wait_key=no                 # Don't wait after using external programs.
set editor="vim + -c 'setlocal tw=72'" # Use vim as my default editor.
set signature="~/.signature"    # Set the default signature file.
#==============================================================================#
set alias_file=~/.mutt/aliases.rc  # Store aliases here.
source ~/.mutt/aliases.rc       # Source the aliases file.
source ~/.mutt/lists.rc         # Source the mailing-lists file.
source ~/.mutt/macros.rc        # Source the macros file.
source ~/.mutt/gpg.rc		# Source the GPG file.
set sort_alias=alias            # Sort the alias list (alphabetically).
set header_cache=~/.mutt/cache/ # Cache headers for speedier message reading.
#==============================================================================#
set folder=/home/antony/mail    # Default mail folder.
set mbox_type=Maildir           # Type of mbox (inbox).
set postpone=yes                # Postpone messages when not sent immediately?
set postponed=+drafts           # Where to store postponed messages.
set spoolfile=+inbox            # Replaces the environment variable $MAIL.
set copy=yes                    # Save a copy of messages?
#==============================================================================#
set include=yes                 # Include copy of message in reply?
set fast_reply=yes              # Prompt for recipients and subjects?
set beep=no                     # Beep when an error occurs?
set move=no                     # Do not move read messages.
set mark_old=no                 # New unread messages = old after exiting mbox?
set sort=threads                # How to sort messages in index menu.
set mail_check=60               # How often to check for mail (every hour).
set smart_wrap                  # Wrap long lines by words.
#==============================================================================#

# mailboxes - which folders receive mail and will be checked for messages.
mailboxes =inbox =quarantined =college

# my_hdr - Create custom header fields which are added to every message sent.
my_hdr From: Antony Jepson 

# ignore * - ignore all headers then specify only the ones wanted.
ignore *
unignore From:
unignore To:
unignore Reply-To:
unignore Subject:
unignore Date:
unignore CC:
unignore BCC:
unignore X-Virus-Status:

folder-hook .           set record="^"
# ^ = save sent messages in currently open folder

# hdr_order - specify the order to present headers.
hdr_order From: To: Reply-To: CC: BCC: Date: Subject: X-Virus-Status:

# pager_context - specify how many lines that are given when changing pages.
set pager_context=5

# pager_index_lines - specify how many lines of the index to show in the pager.
set pager_index_lines=7

# print_command - defines how should mutt print files
# First convert the file for printing with pr and then pipe the output to
# the printer (without a banner)
set print_command="/usr/bin/pr | /usr/bin/lpr -h"

#==============================================================================#
# custom colour scheme
color   hdrdefault      brightcyan      blue
color   header          brightwhite     blue  "^from:"
color   header          brightwhite     blue  "^subject:"
color   quoted          brightgreen     blue
color   signature       brightwhite     blue
color   indicator       blue            green
color   error           red             black
mono    error           bold
color   status          black cyan
mono    status          bold
color   tree            yellow          blue
color   tilde           blue            blue
color   body            brightwhite     blue  "[-a-z_0-9.]+@[-a-z_0-9.]+"
mono    body            bold                  "[-a-z_0-9.]+@[-a-z_0-9.]+"
color   body            brightyellow    black "^Good signature"
mono    body            bold                  "^Good signature"
color   body            brightwhite     red   "^Bad signature from.*"
mono    body            bold                  "^Bad signature from.*"
color   normal          white           blue
color   message         green           black
color   attachment      brightgreen     blue

Diagram

If you wondered how I created the diagram, it’s pretty simple:

tmp %  cat mutt.tex

\documentclass{article}
\usepackage[all]{xy}
\begin{document}

\xymatrix{
& aliases.rc \\
& cache/ \\
& gpg.rc \\
& lists.rc \\
.mutt \ar@/^/[uuuur]
      \ar@/^/[uuur]
      \ar@/^/[uur]
      \ar@/^/[ur]
      \ar[r]
      \ar@/_/[dr]
      \ar@/_/[ddr]
      \ar@/_1pc/[dddr]
      \ar@/_1.8pc/[ddddr] & macros.rc \\
& muttrc \\
& muttrc.local1 \\
& muttrc.local2 \\
& muttrc.local3
}
\end{document}

Take a look at my article on using Xy-pic for some more examples of its capabilities.

Making Diagrams with Xy-pic

Recently, I upgraded my \LaTeX installation from teTeX to TeX Live.  As I was reviewing the available packages, I noticed Xy-pic, a set of macros for creating diagrams and graphs.  I was immediately intrigued and I started reading the relatively short manual.

Today, I will show you a few of the things Xy-pic can do.

1. First, create a file and insert the \LaTeX document class and the macro package.

~ % cd ~/tmp
~ % touch example.tex
~ % vim example.tex
1 \documentclass{article}
2 \usepackage[all]{xy}
3 \begin{document}
4
5 \end{document}

All of our editing will stay between “\begin{document}” and”\end{document}”.

2. Next, let’s begin with our first example.

1 \documentclass{article}
2 \usepackage[all]{xy}
3 \begin{document}
4 \xymatrix@1{A \ar[r] & B}
5 \end{document}

The above example will create:

Explanation: \xymatrix initialises the macro environment and @1 restricts the output to a single line.  \ar creates an arrow and the direction, [r], points the arrow in the right direction.  & separates the columns.  The direction is translated from its mnemonic form (right,left,up,down) into a coordinate pair based upon its initial position.  In this case, [r] means (1,0).  Using [l] would result in an error because [l], which is (-1,0), doesn’t exist.

Throughout the rest of this tutorial, I’ll remove everything except the \xymatrix macro; remember to add the LaTeX commands (lines 1,2, 3, and 5) before you compile the document.  Also, I will bold changes in each progressive example.

3. Let’s add some more letters and arrows to the previous example. (It would have better to use a double headed arrow style, see ex. #7.)

5 \xymatrix@1{A \ar[r] & B \ar[r] & C \ar[l]}

4. Let’s change the C to bullet.

6 \xymatrix@1{A \ar[r] & B \ar[r] & \bullet \ar[l]}

Explanation: \bullet creates a bullet

5. Add another row.

7 \xymatrix{
8 A \ar[r] & B \ar[r] & \bullet \ar[l] \\
9 D & &
10 } 

Explanation: The “\\” creates a linebreak.  Even though no content follows the D, we still have to create the empty columns with &’s.  Since we are now dealing with multiple rows, we have to remove the @1.

6. Create an arrow from A to D.

11 \xymatrix{
12 A \ar[r] \ar[d] & B \ar[r] & \bullet \ar[l] \\
13 D & &
14 }

Explanation: \ar[d] creates a downward arrow to (0,-1), which in this case, is D.

7. Now, let me introduce you to styles.  This time, we’ll begin with a fresh example.

15 \xymatrix@1{
16 A \ar@{<->}[r] & B}

Explanation: The @{<->} is in a @{tail shaft head} format, so in this case, it creates a double-headed arrow.

8. Another example of styling arrows.

17 \xymatrix@1{
18 A \ar@{-}[r] & B}

Explanation: @{-} creates an arrow with only a shaft.

9. Next, an example of labelling arrows.

19 \xymatrix@1{
20 A \ar@{-}[r]^f & B \ar@{-}[r]_f & C }

Explanation: This is not as complicated as it looks.  “^” means up; likewise “_” means down.

10. What about a label with more than one character?

21 \xymatrix@1{
22 A \ar@{-}[r]^{more} & B \ar@{-}[r]_f & C }

Explanation: The “{}” is a container for extra characters.

11. What happens if we lengthen the arrow?

23 \xymatrix@1{
24 A \ar@{-}[rr]^{more} & & B \ar@{-}[r]_f & C }

Explanation: Here, the label stays centered.  Note that we had to modify the direction “[rr]” to account for the blank column between A and B.

12. What about curved arrows?

25 \xymatrix@1{
26 A \ar@{-}@/^/[rr]^{more} & & B \ar@{-}@/_/[r]_f & C }

Explanation: All we did here was add another style “@/^/” and “@/_/”.  /^/ means curve upwards; likewise, /_/ means curve downwards.

13. The last example: a square.

First, we create the outline of the square.

27 \xymatrix{
28 A & B \\
29 C & D
30 }

Next, we connect the corners with arrows.

31 \xymatrix{
32 A \ar[r] \ar[d] & B \ar[d] \\
33 C \ar[r] & D
34 }

Next, we change the styling of the arrows and add labels to each side.

35 \xymatrix{
36 A \ar@{-}[r]^e \ar@{-}[d]_f & B \ar@{-}[d]^g \\
37 C \ar@{-}[r]_h & D
38 }

Finally, let’s add some curved arrows, just for the sake of it.

39 \xymatrix{
40 A \ar@{-}[r]^e \ar@{-}[d]_f & B \ar@{-}[d]^g \ar@/^1pc/[d]\\
41 C \ar@{-}[r]_h \ar@/_1pc/[r]& D
42 }

The added “1pc” makes the curve more prominent so it does not overlap the label.

This tutorial only covers pages 1 – 4 of the 16 page manual.  As you can tell, it is dense.
Xy-pic is a great \LaTeX package that can be used to create beautiful diagrams when typesetting documents.

Changing The Default X Cursor

Although it took me ages to find out how to change the default X cursor the solution is simple.

1. Install the icon/cursor theme using your default package manager (or extract it to /usr/share/icons)

2. List the contents of your /usr/share/icons directory

~ %  ls /usr/share/icons [truncated output]

Chameleon-Anthracite-Large/    Chameleon-Anthracite-Small/ 
HighContrastLargePrint/         LowContrastLargePrint/  gnome/

3. Copy the name of the cursor theme you want (in this case Chameleon-Anthracite-Large)

4. Add the name of theme to ~/.icons/default/index.theme

~ %  vim ~/.icons/default/index.theme
1 [Icon Theme]
2 Inherits=Chameleon-Anthracite-Large

5. Restart the X server

Note: The number next to “[Icon Theme]” and “Inherits” is part of the Vim display (use :set nonumber to get rid of it).  Do not add it to the file.

My Desktop – The Terminal

AJ\'s Workspace (2008-06-25)This will be the final post covering my desktop.
If you look in the bottom left corner of the screenshot, you will see my terminal, rxvt-unicode.

For the most part, I’m a cli person.  I prefer the terminal because of it’s speed.

In the terminal, you can see me running irssi (an irc client) within screen, a detachable terminal multiplex.  Basically, screen allows me to continue using the terminal’s applications even in the event of an X server crash.tirssit

A terminal is basically a portal into the underlying filesystem of my Linux installation.  Much like a MS-DOS prompt, it allows me to navigate this hidden infrastructure with uncanny ease.

Some of my frequently used terminal programs include:

gnu mc (midnight commander) – a file browser

irssi – an irc client (you can find me on freenode)

vim – a text editor (although capable of much, much more)

abcde (A Better CD Encoder) – a cd ripper (makes ripping easy)

nethack – a great rpg

ncmpc – a cli client for mpd (the music player daemon)

mutt – my favourite mail user agent