gnuplot with AquaTerm on OSX Snow Leopard

The gnuplot graphing utility has always had excellent support for multiple terminal types. While the X11 terminal is a satisfactory GUI view for the graphs, I prefer to use the AquaTerm terminal on OSX as it is more ‘Mac-like’ and feels more natural.

Also, I do prefer to compile gnuplot by myself on OSX rather than downloading the pre-packaged binaries – as this gives me more control over the compilation (including getting around the stupid Apple readline bug – where Apple has essentially shipped a broken readline by using libedit to emulate the non-existent libreadline).

This local compile requires that AquaTerm be installed so that the library dependencies for aquaterm exists in:

terminal.png

and the corresponding headers are available at:

1____terminal.png
In addition, the AquaTerm.app itself resides in /Applications.

However, on OS X Snow Leopard, there is a catch – the version of AquaTerm is 32 bit, whereas the default compilation of gnuport results in a 64-bit version – which is not able to load the 32-bit libaquaterm dynamic libraries.

littlesnapper.png

In such a case, the gnuplot compilation does succeed – however, the default terminal becomes the X11 version – which is back to square-one.

A darwinports port does exist for gnuplot – however, as mentioned in an earlier post, this port seems to depend on half of the port repository (i.e., a ton of stuff you do NOT want gets installed as well).

However, there is a easier way to get around this situation. Here’s how.

  1. First install the default binary for AquaTerm from SourceForge and install normally. This step is to basically setup the right folders and symlinks so that you do not have to muck with these later
  2. Now install AquaTerm again from Darwinports – this port has the correct patches needed – and more importantly – builds a 64 bit version by default. This will also install the application under /Applications/MacPorts/

2____terminal.png

  1. Now comes the fun part. We will replace two folders from the darwinports version to the previously installed AquaTerm.
    • Step 1: Replace /Library/Frameworks/AquaTerm.framework with /opt/local/Library/Frameworks/AquaTerm.framework. This will ensure that the correct 64 bit AquaTerm libraries get referenced by the gnuplot compilation
    • Step 2: Replace /Applications/AquaTerm.app with /Applications/MacPorts/AquaTerm.app. This will ensure that the correct 64-bit AquaTerm binary is in the correct location
    • Step 3 (Optional): You can now uninstall the darwinports version by running sudo port uninstall aquaterm from a terminal window
  2. Download the source code for gnuplot and extract the same.
  3. Run ./configure (using a command line parameter to ignore the broken Apple readline) and then make and make install (install will happen in /usr/local)

3____terminal.png

That’s it! The compilation should now succeed and gnuplot will be linked with the correct 64-bit aquaterm dynamic library. Enjoy!

4____terminal.png
figure0.png

Advertisements

Snow Leopard – First Impressions

I finally bit the bullet and installed Snow Leopard over last weekend. I did a clean install (i.e., reformat and install afresh) – considering the significant under-the-hood changes that this OS revision has.

The basic steps I followed are:

  1. Cleaned up the existing Leopard install to remove applications, preference panes and documents I did not need
  2. Reviewed the preferences under ~/Library/Preferences as well as the application support items under ~/Library/Application Support and removed the items which were out of date or detritus from old installs
  3. Took an image backup using SuperDuper! of the Leopard install
  4. Took a backup of the disk using Time Machine to allow easier data restore during the installation
  5. De-authorized my iTunes to prevent increment of the install counter after reinstall of the OS
  6. Popped in the Snow Leopard DVD and started the install
  7. During installation, I used the Disk Utility to reformat the Mac OS partition
  8. I also did a custom install to prevent the printer drivers (over 2 GB) being installed. In addition, I selected the optional Rosetta and Quicktime 7 components (seriously Apple, these take less than 10 MB – why the optional tag?)
  9. Waited for around 20 minutes to have the base image installed, and then used the migration assistant to restore data from my Time Machine backup

The install was relatively smooth, and restoring the data from my Time Machine backup also went without any issues. However, post-install, some of the glitches started appearing:

  1. The default font for Safari as well as Firefox went crazy – with large bold fonts appearing. It turned out to be a font substitution issue with the Arial font, which for some reason was missing the “Regular” type. Restored the font from the old image backup and every thing was back to normal. It appears a lot of people are facing this issue
  2. Adobe’s Photoshop Elements 6 refused to start, stating expiry of the license. This also is a known issue, and a restore of the /Library/Application Support/FLEXnet Publisher/ folder from the image backup made things normal again
  3. The key chain was not allowing storage of any new passwords, and was also not allowing viewing of the stored passwords. This is a known issue and my solution was to simply change the login keychain password once and reset it back again to the original password
  4. Emacs 23 was not compiling under Snow Leopard. There is already a patch available in CVS. However, there are incompatibilities with the 64 bit GCC – hence you need to pass a CC=“gcc -arch i386” as part of the ./configure invocation. The compilation succeeded with this. Note that a recompile of some of the user installed lisp packages was required (notably Icicles)

Other than the issues listed. rest of the experience seems OK so far. The look and feel is not too different and most of the user visible changes are subtle – except for the new QuickTime Player – which is a dumbed down and dressed up version of the venerable QT Player.

In summary, this is an OS upgrade that does have the potential to break some of the old applications, though most of the issues do seem to have work arounds – it is also going to become a required update pretty soon – given the internals changes that Apple has made. No need to rush out right now (mea culpa!) to upgrade – but do be prepared to do the update in the near future.

Importing contacts from OSX Addressbook to Emacs BBDB

A major aspect of using Emacs is that it is more than a text editor – it is more of an application platform – some would call it an Operating System – that allows a host of applications to run within the same context and session – and vastly enrich the user experience. This is in fact a primary reason why many Emacs users spend their entire computer interaction via Emacs.

This unique aspect of Emacs is made possible by the availability of Emacs Lisp as a first class scripting/programming interface for the editor – and has made possible application packages such as W3 (a web browser), Gnus (the NNTP and mail reader), Eshell (a lisp based shell), Wanderlust (a very capable email client), and the Insidious Big Brother Database – aka BBDB – which is a contact manager and the subject of this post.

(BTW, the list of application is only a very small fraction of what is actually available on Emacs – see www.emacswiki.org for a ton of other packages).

As EmacsWiki points out, BBDB is:

“A complete address book for nearly every email and news client written for Emacs, and its functionality supports (by default) making entries in the address book automatically when reading email or posts by people, and easy lookup of addresses while composing messages.”

In essence, it is an always available address book that works with other packages such as mail, Gnus and org-mode to provide a easy to access repository of contact information. The repository itself is a plain text lisp file which by default is stored as ~/.bbdb.

However, as with any contact manager, the problems are usually with:

  1. Initial data import, and
  2. Synchronization with other repositories and devices

For my platform (Apple OSX), the first problem above translates to data import from my primary OS level address book – the AddressBook.app. The second problem is not much of an issue for me since I use AddressBook.app as the primary contact list elsewhere and sync my devices to that. For keeping BBDB in sync, I have a cron job to automate the scripts below.

The contacts import to BBDB requires a data conversion of the address from custom format in which AddressBook.app stores the contacts to the BBDB lisp format. The steps required are as follows:

  1. Extract the records from AddressBook.app
  2. Parse and reformat the relevant fields that BBDB requires, and
  3. Output the reformatted records in the BBDB lisp format

Luckily, for step # 1, an open source command line utility already exists – appropriately called contacts. It is available from http://gnufoo.org/contacts/ and is a svelte 194KB download. This utility allows querying of the OSX Address book and extraction of specific fields and records. The output is a simple CSV text file.

For step # 2 and #3, additional scripting is required. I have written a simple Ruby script called contacts2bbdb.rb to run the contacts utility and output the BBDB repository file:

#!/usr/bin/env ruby -w
#
# Filename: contacts2bbdb.rb
# Description: Converts addresses from OSX Addressbook.app to BBDB format
# Author: Anupam Sengupta (anupamsg ... A-T ... G - M - A - I - L )
# Maintainer: Anupam Sengupta
#
# (c) 2007-2016 Anupam Sengupta.
#
# Created: Fri May 25 15:53:22 2007
# Version: 1.0
# Last-Updated:
#           By: Anupam Sengupta
#     Update #: 733
# URL: https://slashusr.wordpress.com
# Keywords: `BBDB’, ‘OSX’, ‘contacts’, ‘convert’
# Compatibility: GNU Emacs 21 and above
#
#--------------------------------------------------------------------
#
# Commentary:
#
#  Converts the addresses and contacts from Apple OSX’s system addressbook
#  format (Addressbook.app) to Emacs’ BBDB format.
#
#  Requires the following additional software:
#
#  1. Ruby V1.8 and above (http://www.ruby-lang.org/)
#  2. Big Brother Database (BBDB) package for Emacs (http://bbdb.sourceforge.net/)
#  3. The ‘contacts’ program to read Addressbook’s contacts
#     (http://gnufoo.org/contacts/)
#
# Usage:
#
#  1. Install Ruby, BBDB and contacts, if not already present
#  2. Backup the OSX Address book (export the addresses as addressbook archive)
#  3. Run this Ruby script to generate the converted records in BBDB format in the STDOUT
#  4. Save the STDOUT output of this script to bbdb.new
#
#     $ ruby contacts2bbdb.rb > bbdb.new
#
#  5. Replace your .bbdb file with bbdb.new
#
#--------------------------------------------------------------------
#
# Change log:
#
#
#--------------------------------------------------------------------
#
# License: GNU GPL V2.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING.  If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street, Fifth
# Floor, Boston, MA 02110-1301, USA.
#--------------------------------------------------------------------
#
Delim = “\t”                    # Default delimiter
ContactsProg = ‘/usr/bin/env contacts’ # The contacts program
#
ContactsProgParams = ‘-H -l’
#
# A map between the LDIF field names and the actual field name
ContactFields = {
:fn => ‘firstName’,
:ln => ‘lastName’,
:c  => ‘company’,
:nn => ‘nickName’,
:he => ‘homeEmail’,
:we => ‘workEmail’,
: oe => ‘otherEmail’,
:hp => ‘Home’,
:mp => ‘Mobile’,
:Mp => ‘Main’,
:wp => ‘Work’,
}
#
ContactFormatOpts = ContactFields.keys #  Options to pass to the contacts program
ContactsProgFormat =  “‘%” + ContactFormatOpts.inject { |s, f| s.to_s + “#{Delim}%#{f.to_s}” } + “‘“
ContactsFullExec = “#{ContactsProg} #{ContactsProgParams} -f #{ContactsProgFormat}”
#
output = `#{ContactsFullExec}`.split(/\n/) # Read the output of contacts program
#
# Start parsing the contacts output
records = output.map do |line|
record = Hash.new(nil)
line.chomp.split(Delim).each_with_index { |f, i| record[ContactFields[ContactFormatOpts[i]]] = f.strip unless f =~ /^\s*$/ }
record
end
#
# Start outputing the details to STDOUT
puts <<END
;; -*-coding: utf-8-emacs;-*-
;;; file-version: 6
END
#
for r in records do
r[‘nickName’] = nil           # No need for the nick names.
outs = %w{ firstName lastName nickName company }.inject(“[“) { |s, f| s + (r[f] ? “\”#{r[f]}\” “ : “nil “) }
outs = %w{ Home Main Mobile Work}.inject(outs + “(“) { |s, f| r[f] ? s + “[\”#{f}\” \”#{r[f].strip}\”] “ : s } + “) “
outs = %w{ homeEmail workEmail otherEmail }.inject(outs + “ nil (“) { |s, f| r[f] ? s + “\”#{r[f]}\” “ : s } + “) “
outs += “((creation-date . \”2009-02-08\”) (timestamp . \”2009-02-08\”)) nil]”
puts outs
end
# End of contacts2bbdb.rb script

A companion shell script to automate the execution of the Ruby program and also backup the previous BBDB file is also provided. Before usage, please edit the BBDB folder and file names:

#!/bin/sh
#
# Filename: contacts2bbdb.sh
# Description: Converts addresses from OSX Addressbook.app to BBDB format
# Author: Anupam Sengupta (anupamsg@gmail.com)
# Maintainer: Anupam Sengupta
#
# (c) 2007-2016 Anupam Sengupta.
#
# Created: Fri May 25 15:53:22 2007
# Version: 1.0
# Last-Updated:
#           By: Anupam Sengupta
#     Update #: 740
# URL: https://slashusr.wordpress.com
# Keywords: `BBDB’, ‘OSX’, ‘contacts’, ‘convert’
# Compatibility: GNU Emacs 21 and above
#
#--------------------------------------------------------------------
#
# Commentary:
#
# Runs the export of OS X Address Book contacts to the Emacs BBDB file.
#
# Requires:
#   1. The contacts2bbdb.rb Ruby script
#      (https://slashusr.wordpress.com/)
#   2. The Ruby interpreter (Version 1.8 and above)
#      (http://www.ruby-lang.org/)
#   3. The Big Brother Database (BBDB) Emacs Package
#      (http://bbdb.sourceforge.net/)
#   4. The contacts command line program to extract the records
#      (http://gnufoo.org/contacts/)
#
# Usage:
#   1. Backup the Addressbook.app’s addresses
#   2. Install BBDB and ‘contacts’, if not already present
#   3. Edit the BBDBDIR and RUBYPROG variables below
#   4. Open Terminal.app and run this script
#   5. The script will also create a backup of the previous bbdb file
#
#
#
# TODO: Edit these variables to match the file locations
BBDBDIR=$HOME/.emacs.d/data     # Edit this to match location of the bbdb file
BBDBFILE=bbdb                   # Edit this to match your bbdb file name
RUBYPROG=$HOME/bin/contacts2bbdb.rb # Name and loction of the Ruby Script
#
#######################################  Do not edit beyond this point !
#
RUBYEXEC=`which ruby`
#
if [ -x ${RUBYEXEC} ]; then
cp ${BBDBDIR}/$BBDBFILE ${BBDBDIR}/bbdb.bak
${RUBYEXEC} ${RUBYPROG} > $BBDBDIR/$BBDBFILE
fi
echo “BBDB Export and conversion completed.”
#
# End of contacts2bbdb.sh

Do remember to take a backup of your existing BBDB file as well as a backup of the OSX address-book before running the scripts!

Enjoy!

Update [17th Aug 2009]: Emacs-fu has a nice bbdb tutorial at emacs-fu: managing e-mail addresses with bbdb

Replacing Mail.app with Gmail on OSX

Off late the Mail.app email client on OSX has been acting up on me. It often stalls or displays the spinning beach ball of death till a forced quit is required. Also, it seems to have display rendering issues when a mail classified incorrectly as junk is moved back to the inbox.

I tend to use the Mail.app as a local email client for three main purposes:

  1. Offline mode for reading my emails when there is no Internet connection available
  2. Easy desktop search for the mails via Spotlight, and
  3. Easy archival of important mail in my project workspaces (either in Devonthink or plain text export)

The other features (TODO and Notes) are nice, but not really useful for me as I use other tools for these items. The mail itself is served out via gmail accounts and IMAP synchronization.

However, Mail.app is one of the few (only?) Apple provided applications that I have a love-hate relationship with. I love the fact that it integrates seamlessly with iCal and Address Book, and the other features such as support for multiple signatures, digital signing and encryption via the GPG plugin and the smart quote while responding are quite good. the threading is also functional.

But the incessant crashes and freeze ups are getting to be more than annoying. I have tried the various cures such as re-synching the entire mailbox, rebuilding the mailbox, trashing preferences, changing the cache setting and a ton of other voodoo. These seem to be temporary solutions however, and the problems come back pretty fast. Apparently I am not alone in my suffering though – Apple’s discussion and support forums are full of unhappy Mail.app users.

So I am now on the hunt for an alternative offline/local client solution. I have already tried Mozilla Thunderbird, and it looks too ugly for my tastes (though an excellent client on the Windows platform). In addition, two more deal-breakers exist right now:

  1. Getting Spotlight to work with Thunderbird requires a third party indexer which seems to be a hack. It looks like an experimental mdimporter plugin does come with version 2.0 but is flacky
  2. Missing integration with the system provided AddressBook.app application (I need to sync the addresses with my Blackberry, and AddressBook.app is a core part of the synchronization workflow)

Another promising solution seems to be using Gmail directly as the primary email client. This requires a few additional steps to enable a seamless offline operation:

  1. Installation of the Google Gears extension for the browser (no support yet for the latest Safari 4.x version) – this enables a copy of the emails to be stored on the local disk and allows access and usage of the gmail interface when offline – note that the first-time sync takes a long time as last 6 months worth of emails are downloaded to your computer – it is pretty peppy from then on
  2. Installation of the Gmail Notifier application which provides notifications on receipt of new emailgooglenotifiersignin.png
  3. Setting up Gmail as the default mail handler from URLs by using an option on the Gmail notifiergooglenotifierpreferences1.png
  4. Using a Site Specific Browser such as Fluid.app or Mozilla Prism and creation of a Gmail SSB application (remember to set a nice icon)fluid1.png
  5. Setting up the Gmail SSB as the default mail application by setting the “Default Mail Reader” option from Mail.app’s general preferencesmail-appgeneralpreferences1.png
  6. Synchronizing the addresses between Addressbook.app and Gmail using iSyncaddressbookpreferences.png
  7. Using Google Desktop for searching the mails on Gmail

Whew! Quite a bit of setup here to do – and it is still not perfect. Lets look at the pros and cons:

Pros:

  1. Can use the excellent Gmail UI everywhere, online or offline – on all platforms. Hurray for Web apps!
  2. Great keyboard shortcuts – much better than Mail.app
  3. Using the SSB allows a smooth integration of the mail experience with rest of the desktop
  4. No more waiting for the local client to download the mails before accessing – it is near instantaneous after the first offline synchronization
  5. No more crashes!

Cons:

  1. It is a hack right now – definitely not a “download and start using” solution
  2. Google Desktop is duplicating search functionality that already exists via Spotlight
  3. Synchronization of the addresses between Gmail and AddressBook is not reliable
  4. No support for multiple signatures (can get around with a auto-typing solution such as Typinator or TextExpander)
  5. Cannot export the emails (not the contacts) from Gmail to the local computer

I intend to use this setup for the next couple of weeks to get a better feel of the system. Will follow up with a post on the findings. Do let me know what you think.

Tips for using emacsclient and server-mode on OSX

Emacs is a great editor, but has one setback – it is slow to startup if you have loads of packages to load. On my G4 iBook, it takes around 45 seconds before Emacs becomes usable (OK – I use lots of packages).

However, Emacs is not meant to be restarted every so often. The canonical usage is to start Emacs once, invoke the server mode (see EmacsClient) and then use the emacsclient from the command line to invoke the editor instance when needed. I.e., the classic client/server model for editing!

Note that by default, this uses local sockets and hence the clients can connect only to the local machine’s server. However, there is an alternate mechanism to use standard TCP/IP sockets, which allows connections to remote Emacs servers. See the emacsclient info page  for details.

(Note: With the latest 23.1 version of Emacs, there is an alternate mechanism to start Emacs in a server mode – will post this in a future article).

In order to enable this feature, server-mode needs to be run within an active Emacs session (V22 and above). This can be achieved by:

M-x server-start

Alternatively, you can add the following line at end of your .emacs file:

(server-start)

Note that a running Emacs session needs to be present before the clients can connect.

The next step is to invoke emacsclient from the command line (or from a script) with the file name to edit.

$ emacsclient <file to edit>

This will cause a new file buffer with the requested file to be opened in the running Emacs session. The emacsclient that invoked the edit will block till the running Emacs returns control via ‘C-x #’ (server-edit)

You can use the -n option to the emacsclient invocation to prevent the blocking.

On my system, I have aliased the ‘emacsclient’ binary to be ‘ec’, which is much simpler to type.

I.e., in my `.bashrc’, I have

alias ec emacsclient

I have also defined $EDITOR to use ‘emacsclient’ when possible, and ‘vi’ otherwise. However, instead of directly assigning to the $EDITOR environment variable, I have a small shell-script to define the default editor I want to use. This script is then assigned to the $EDITOR variable.

The code for the default-editor shell-script (named ‘default-editor’) is:

#!/bin/bash
# Set up a default editor for the shell
# Use Emacs if already open, and vi in other cases (including fallback)

# Note that this will set the default emacsclient, which may not be what you want
# if multiple versions of emacs are available. In that case, you can put the absolute path
# of the emacsclient that needs to be used.
# E.g., the Cocoa 23.1 emacsclient on OSX is actually located at:
# /Applications/Emacs.app/Contents/MacOS/bin/emacsclient
EMACS_EDITOR=`which emacsclient`

if [ -x "$EMACS_EDITOR" ]; then
   $EMACS_EDITOR -a vi "$@"
else
   vi "$@"                     # Never fails!
fi

And then, in the .bashrc file, I have:

if [ -x $HOME/bin/default_editor ]; then
   export EDITOR=$HOME/bin/default_editor
else
   export EDITOR=`which vi`
fi

BTW, the code above assumes that you use bash as the primary shell in your terminal. You can however trivially modify the scripts above for your specific shell.

Using M-` from switching Emacs Frames on OSX

The standard Emacs key-binding for moving to the other frame (‘other-frame’) is C-x 5 o. That’s quite a few key-strokes, and also does not match with the standard OS X key-mapping for switching windows, which is Command-`. On OS X, the Command key maps to Meta in Emacs.

However, this is easy to fix. Put the following code-fragment into your .emacs file:

(define-key icicle-mode-map [?\M-`] nil) # Only needed if you use Icicles
 (global-set-key [?\M-`] 'other-frame) # This sets the key binding

Note that by default M-` invokes ‘tmm-menubar’ which can also be accessed via [F10]. Also, you do not need the first line (to undefine the key binding in Icicles) if you do not use that package.

Emulate a three button Mouse in Emacs on a single button Mac trackpad/mouse

Traditionally, mice on Macs have had just one button (including the iBook/Powerbook trackpads) – even through Mac OS (including OS X) can accept 2 or 3 button input without any problems.

Emacs on the other hand maps quite a few functions to the second and third chords of the mice. If you want to emulate a three button mouse in Emacs on OS X, a simple customization option will do the trick.

Invoke:

M-x customize-group and enter mac. Navigate to the “Mac Emulate Three Button Mouse” and select option 2 or option 3. Voila!

Note: This works for Carbon Emacs – the customization group is not available on the latest 23.1 Cocoa Emacs.