Automatically Expanding zsh Global Aliases As You Type

| Comments

Animated demonstration of globalias

Update 2012-11-04: This page is now out of date. Since this entry was published, I cleaned this code up quite a bit. You should definitely check out the new entry.

I am not the first person to think of this idea. My notes seem to think that I originally found the idea on the zsh wiki and I stole the code I started with from hackerific.net.

What are global aliases?

Shell aliases let you condense a long-winded and/or hard-to-remember command down to a short, easy-to-remember word. Old-school shells will only match the alias if it is the first word in the command. Zsh lets you take that one step further by allowing you to define aliases that will be substituted no matter where they appear on the command line. These are global aliases.

Here is one of my global aliases that I use all the time:

1
alias -g G='|& egrep -i'

With this alias defined, these two commands are equivalent:

1
2
cat /proc/cpuinfo G cache
cat /proc/cpuinfo |& egrep -i cache

My problem with global aliases

When I look at a command line with a global alias, it isn’t always entirely clear to me what the command I am about to run is actually going to do. Am I sure my G alias has a -i switch? Does it use |& so that it will also grep stderr?

The existing solution

The handy script at hackerific.net sets things up so that as soon as you hit the space bar after typing the global alias, it is automatically expanded right there on the command line.

This is great for a couple of reasons. You never have to guess what code is hidden inside that alias. The full text of the command will be right there on the command line and in your history, so you’ll never be surprised. It also means you can go back and tweak the command a bit.

What I did differently

There is only one thing I didn’t like about the solution at hackerific.net. Instead of cleanly defining your global aliases with the alias command, you have to add your aliases into a hash table. His code uses that hash table to expand the aliases on the command line and also to create your actual global aliases (so that they still work at the end of the line).

I like that you only have to define them once, but I wanted to build the hash table out of the global aliases that are already defined.

I managed to parse the output of alias -g and stuff it into the hash table, but I wasn’t able to make it work without piping the output to Perl and sourcing the output back in. I tried to make it work with pure shell code, but none of the magic I came up with worked.

Deprecated globalias code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
typeset -A abbrevs

# Begin Ugly Hack

alias -g | perl -e "print 'abbrevs=('; while (<>) { s/^(.+?)='(.+)'/'\$1' '\$2' /g; s/'\\$/\\$'/g; print; } print ')';" > /tmp/cheater.zsh
source /tmp/cheater.zsh

# End Ugly Hack

globalias() {
   local MATCH
   LBUFFER=${LBUFFER%%(#m)[_a-zA-Z0-9\-]#}
   LBUFFER+=${abbrevs[$MATCH]:-$MATCH}
   zle self-insert
}

zle -N globalias

bindkey " " globalias
bindkey "^ " magic-space           # control-space to bypass completion
bindkey -M isearch " " magic-space # normal space during searches

You can probably just paste this into your .zshrc near the end, after all your global aliases are defined.

oh-my-zsh plugin

I’m running my copy as an oh-my-zsh plugin. I haven’t uploaded it to github yet, though. I’d prefer to eliminate the ugly pipe-and-source lines first. I may have to upload it as is if I don’t get around to improving it, though.

You can download my plugin here. It is identical to the code above.

(Not Quite) Native Linux Games for an Arcade Cabinet: Mactabilis

| Comments

I set a goal for myself early in the year. I would like to buy one Indie game for my arcade cabinet every month this year.

I’ve tried my best to find native Linux games, and there are plenty of awesome independent games that run natively on Linux. The problem is that the vast majority of these games require some sort of analog input, usually a mouse. My cabinet has no analog controls…

I have been keeping my eye out looking for Windows games that run well under Wine. There are quite a few Indie games that run very poorly under Wine, most of them were created using GameMaker.

I saw the Buy Games Not Socks and I immediately hoped that Mactabilis would run under Wine. I downloaded the demo and it ran absolutely flawlessly, so I immediately purchased the bundle.

It even runs well on my arcade cabinet with its ancient Nvidia 6200LE video card, even with the video flipped upside down. I do have to run it with the resolution set to 960x540, though.

Mactabilis

I was happy to learn that everything in the game can be controlled with the arrow keys and a handful of buttons. After mapping everything I would, need I still had one button left over on my six-button control panel.

Mactabilis

Mactabilis is an awesome side-scrolling shoot ‘em up. The first thing I noticed when I started playing was that the game felt backwards! I’m so used to my ship being on the left.

This was very easy to get used to. For half of the first level your ship is moving from left to right, but on the second half you reverse direction.

Mactabilis

Mactabilis has an interesting feature that I’ve never seen in a shoot ‘em up before. You can hit a button to move your ship between the foreground and the background layers. Enemies and obstacles seem to occupy one of the two layers.

If things get too crowded or dangerous in the current layer, you can just hit a button to move your ship into the opposite layer. Enemies in the other layer become transparent, blurry, and desaturated.

This is pretty neat, but I was constantly forgetting that this option exists…

Mactabilis

Mactabilis also seems to have a staggeringly huge number of weapons to purchase for your ship. I haven’t had time yet to get very far into the game, so I can’t really comment too much on this. I can say that the weapon screen has a seven-by-seven grid of weapons you can purchase. I can hardly wait to try some of them!

Updating the BIOS on an HP DV8T Laptop Without Windows (You Can’t)

| Comments

Nearly every piece of hardware in my laptop has worked fine, more or less, with Linux since I bought it early in 2010. There is only one minor bug that I am aware of, and it has been a minor nuisance the entire time: ACPI is unable to read the discharge rate of the battery.

This hasn’t really been that big of an issue for me. The battery only lasts about two and a half hours anyway, and there is no trouble reading the current charge left in the battery. I was hoping I’d eventually luck out and a kernel upgrade would magically start seeing the discharge rate. I’m up to 3.0-rc3, and still no luck there.

I didn’t have any reason to attempt to fix this problem until yesterday. I installed a copy of the latest and greatest development version of Powertop, version 1.98. The new version looks very promising. I was interested in trying the new calibration feature. It looks like it does things like cycle your LCD brightness, perform disk I/O, and stress the CPU a bit while monitoring power usage. This doesn’t seem to work so well if Powertop is unable to read the battery discharge rate.

My DV8T has a quad core i7 processor and the BIOS version was F.11. I bought two more DV8T laptops last summer, one for each of my parents. Theirs have Core 2 Duo processors. Luckily for me, I have a VPN between here and my parents’ house. I was able to ssh into my mother’s laptop and take a look around. She has BIOS version F.24, and ACPI has no trouble reading the discharge rate.

Updating the BIOS

I rarely update the BIOS on my machines. As far as I’m concerned, if it ain’t broke, don’t fix it. I decided that, in this case, if it seemed to be working on another very similar machine (with the same BIOS), that it was worth giving it a shot.

Here’s the rub. HP’s flash utility only runs on Windows. I don’t have Windows installed anywhere here at home. I probably have an old Windows XP CD squirreled away somewhere, but I have no idea where it is. I’m disappointed that they don’t have a DOS utility like most of their competition does. It isn’t a deal breaker. I’d still buy another laptop like this; I don’t often want to flash the BIOS on any of my laptops.

I tried a BartPE boot disk, and it blue screened. I ended up downloading the Windows 7 Enterprise 30 day trial from Microsoft and I installed it on an old spare laptop drive. This part of the journey is pretty uninteresting. Windows 7 installed just fine, and the BIOS flashed with just a few clicks.

Total waste of time

I’m up to BIOS version F.25. Here is the result:

wonko@zaphod:~$ cat /proc/acpi/battery/BAT0/state
present:                 yes
capacity state:          ok
charging state:          discharging
present rate:            unknown
remaining capacity:      4640 mAh
present voltage:         16434 mV
wonko@zaphod:~$ cat /sys/class/power_supply/BAT0/current_now 
cat: /sys/class/power_supply/BAT0/current_now: No such device
wonko@zaphod:~$               

Note the present rate: unknown and the No such device. I’m guessing this ACPI problem only exists on the Core i7 DV8T laptops. At least I got to see how much the Windows install process has (and hasn’t!) changed between Windows XP and Windows 7, for whatever that is worth…

Trying Out an Improvised Standing Desk

| Comments

I’ve been reading a lot of good things about standing desks lately. It seems that we can burn up to an extra 50 calories every hour if we stand instead of sit. The entire Internet is also telling us that sitting can literally kill us.

I’m not sure how true either of those articles are, but I still figured I’d give it a try. Setting up a quick, makeshift standing desk was easy and free. I did a bit of measuring and started rummaging through our closets. We have a couple of these large faux-aluminum CD cases that hold 510 discs.

Putting one of those cases on my cocktail arcade cabinet raises my laptop up to about 43 inches. That’s just about elbow height for me. The case also happens to be just about the same length and width as my gigantor 18.4 inch laptop.

Improvised standing desk on top of my cocktail arcade cabinet

Using the standing desk for a few weeks

The first few days, my feet weren’t too happy about standing for such long periods of time. I started out using it for one or two hours each day. At some point during the first week my feet stopped being a problem.

I seem to be a bit more motivated when I’m standing. I think I actually do get a bit more work done, but I haven’t done any science to validate that.

My quick hack of a standing desk has a major flaw: the display is way too low. My shoulders and neck start to get pretty tired after a few hours from looking down all the time.

What can I do about it?

I’d like to continue using the laptop’s keyboard, but I’m not sure I can get the display up high enough without putting too steep of an angle on the keyboard. The display needs to be elevated at least another twelve inches, possibly a bit more.

I have a couple of designs knocking around in my head that I can build out of PVC. I’d like to throw something together soon, but it looks like I’m probably going to be out of town for a month or two. In the mean time, I will continue to make use of what I have set up.

The verdict

Setting up this simple standing desk was definitely worth the very small amount of effort that was required. If you think the idea of a standing desk is interesting, I would encourage you to give it a try for a few days.

I have no plans to convert to using a standing desk full time. My monitors are going to stay firmly attached to my regular desk and you’ll have to pry my Aeron chair out of my cold, dead hands. I think from now on, though, I will always make sure I have somewhere in my office where I can stand up and use my laptop.

Supplementing btrfs-snap With apt-btrfs-snapshot

| Comments

I’ve been a very happy user of btrfs-snap for quite a while now. It is great for taking snapshots of a volume at regular intervals. In my opinion, this is a bit wasteful and cumbersome for the root volume. I don’t tend to change things on the root volume every hour, or even every day.

Ubuntu 11.10 now has apt-btrfs-snapshot available in the universe repository. This is an awesome little script that hooks into apt to create a snapshot right before packages are installed or upgraded.

The only thing I wasn’t too happy about was that apt-btrfs-snapshot doesn’t do any cleanup of old snapshots, so things were getting cluttered pretty quickly:

Screenshot of some btrfs snapshots

Cleaning things up a bit

I threw together my own little snapshot cleanup script to hook into apt. It automatically removes all but the five most recent snapshots. That should be enough history to keep me safe.

Screenshot of some btrfs snapshots, after clean up

Still using btrfs-snap as a safety net

I’m still using btrfs-snap on my root volume, but I’m not keeping anywhere near as much history as I used to. I’m only keeping a few hourly snapshots and one weekly snapshot. I’ll probably end up dropping the weekly snapshot.

Screenshot of btrfs snapshots of my root file system

apt-btrfs-snapshot-cleanup.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
#! /bin/bash

DEVICE=/dev/sda2
KEEP=5
MP=`mktemp -d`

mount $DEVICE $MP

ls -dr $MP/@apt-snapshot-* | tail -n +$KEEP | while read snap ; do
  btrfs subvolume delete $snap
done

umount $MP

I also created a file called /etc/apt/apt.conf.d/81-btrfs-snapshot-cleanup containing this line:

apt-btrfs-snapshot-cleanup.sh
1
DPkg::Pre-Invoke {"if [ -x /usr/bin/apt-btrfs-snapshot ] && apt-btrfs-snapshot supported; then /home/wonko/bin/sbin/apt-btrfs-snapshot-cleanup.sh; fi "; };

This will make apt run this script right after it takes a snapshot. Just tweak that line to match the location of your apt-btrfs-snapshot-cleanup.sh script.

Why I Started Using htop

| Comments

htop in action

I have probably been entertaining the idea of replacing top with htop for quite a few years now. I have even made the attempt a few times. Familiarity and muscle memory always brought me back to top. Until now.

Some advantages of htop

The biggest advantage of htop for me is that it combines the functionality of top and iotop into a single screen, since iotop lets you add disk I/O columns to the output. This feature has saved me quite a bit of time and thought. I don’t have to crossireference processes between top and iotop now, and I also don’t have to fire up vmstat as often as I used to.

You can also highlight a process and hit l to get a list of open files for that process. I haven’t needed to use lsof very often since I learned about this feature.

There are some other small advantages to htop. You can scroll the display horizontally with your mouse, which makes it easy to see the entire command line of a command. You can also select multiple processes to kill or renice.

htop also lets you configure the header area and which columns are displayed in a much more visual manner than top.

Some minor problems with htop

I’m not really a fan of htop’s color schemes. It ships with a half dozen color schemes that are all either very colorful or completely monochromatic. The color schemes are hard coded, so there is no easy way to define your own.

There are top compatibile keys for sorting by memory and CPU usage, but there is no key to sort by I/O. To do that you have to hit F6 or > and use the arrow keys to select the I/O column. This is still better than reaching for iotop, but it isn’t exactly ideal. Setting CPU affinity has the same problem.

Fixing the Horrible Wi-Fi Toggle Button on an HP dv8t Laptop

| Comments

Update 2011-09-06: The fix worked great until yesterday. That’s probably about three and a half months. I solved the problem more permanently this time. I just unplugged the ribbon cable for the capacitive button bar. I now have fewer lights staring back at me and I no longer have dedicated buttons for volume control, but I am confident that my Wi-Fi won’t be turning itself off ever again.

I have had my HP dv8t laptop for a little over a year now. For the most part, I have been very pleased with this machine; it is an excellent quad core desktop replacement. It is a big, heavy laptop with an 18.4” screen. It usually spends most of its time living behind my desk plugged into a pair of external monitors.

A few weeks ago, I did a bit of traveling and I was using it in a hotel, connected to their Wi-Fi. Sometimes things were fine, other times it was disconnecting and reconnecting the Wi-Fi every few minutes.

I’ve had the Wi-Fi inexplicably turn off here at home a few times but I always assumed it was my own fault. The little blue capacitive button to toggle the Wi-Fi is just about a thumb’s length from the right side of the laptop, just above the keyboard. When I am sitting in a chair and I need to lift the laptop to adjust my position, that is precisely where I am most likely to grab a hold of it.

It usually took me a number of seconds to notice that I had inadvertently hit that switch. More and more often lately, though, I haven’t been so sure that I actually touched the switch…

The problem is ridiculously common

I asked my good friend Google about this problem and she showed me all sorts of pages with people complaining about the same problem. It looks like a design flaw. I found an excellent explanation of the problem and a description of the fix on Dave Miller’s blog!

There is a layer of foil that shields the cable that connects the capacitive button panel to the motherboard. It seems that if the laptop body is flexed ever so slightly, like when I pick it up by one side, the foil pulls away from the metal plate and becomes ungrounded. The problem also seems to occur more often when the laptop is hot. I imagine I’ve rarely experienced this problem because the laptop gets pretty good ventilation when I have it “docked” behind my desk.

I saw some forum posts that claimed it also helps to use some foil to shield the area around where the Wi-Fi antenna lead connects to the motherboard. I have no idea if this helps or if it is necessary, but I thought it was a pain in the neck unsnapping all the plastic bits to get the keyboard off. I figured it was best to do everything I might need to do while I was under there!

What I actually did

I ended up taping a piece of aluminum foil over the whole area where the Wi-Fi lead connects to the motherboard. I put some tape on the underside of the foil to make sure it wouldn’t accidentally short anything out.

I made sure that piece of foil was large enough so that it would extend over to the existing foil taped over the capacitive button cable. I know very little about electronics, but I assumed it couldn’t hurt to make sure the new foil shielding was also grounded.

Then I taped down my new foil and I taped down the capacitive panel’s lead.

So far, everything has been working just fine. I haven’t had my Wi-Fi turn off on its own even once. Hopefully the fix will hold up for a long time.

My Take on “The Go Command”

| Comments

When I first saw Zachary Wasserman’s Go Command, I wasn’t entirely convinced that it was a good idea. I figured you could get similar functionality with less typing by enabling autocd, properly configuring binfmt_misc, and setting the execute bit on pretty much every single file…

Those three things would be quite convoluted, and setting the execute bit on every single file would make me a bit nervous… Alexy’s go command is safer, easier to implement, easier to carry along with you, and can give us much finer-grained control over the process.

To me, the go command feels like it could be called the dwim command. I wanted my own go command to do more than change directories and open files in my text editor.

I wanted to limit mine to only open appropriate files in my text editor. I didn’t want to be accidentally opening images or videos in Emacs. I also decided that if a file shouldn’t be opened with a text editor, that it should be handed off to xdg-open. That lets me open images, videos, office documents, and anything else I can think of with the same command.

I also felt it was important to integrate autojump because I am horribly addicted to it. So much so that my muscle memory always wants to type j instead of g… I’m sure if I can start remembering to correct myself, I will have that trained out of me in a week or two.

Here’s the current revision of my take on the go command. It works fine on botth zsh and bash. It fails gracefully if xdg-open or autojump are not found. If you would like to give it a try, you can just copy and paste it into your ~/.zshrc or ~/.bashrc (whichever is appropriate for your shell).

My `go` command
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
go() {
   if [ -f "$1" ]; then
     if [ -n "`file $1 | grep '\(text\|empty\|no magic\)'`" ]; then
       if [ -w "$1" ]; then
         $EDITOR "$1"
       else
          sudo $EDITOR "$1"
          #$EDITOR /sudo::"$1" # For emacsclient+tramp
       fi
     else
       if [ -e "`which xdg-open`" ]; then
         if [ -n "$DISPLAY" ]; then
           xdg-open "$1" > /dev/null
         else
           echo "DISPLAY not set:  xdg-open requires X11"
         fi
       else
         echo "xdg-open not found:  unable to open '$1'"
       fi
     fi
   elif [ -d "$1" ]; then
     cd "$1"
   elif [ "" = "$1" ]; then
     cd
   elif [ -n "`declare -f | grep '^j ()'`" ]; then
     j "$1"
   else
     echo "Ran out of things to do with '$1'"
   fi
 }

 alias g=go

From my perspective, there isn’t any value in automatically running an ls every time I change directories. I prefer to see as many previously run commands on my screen at a time as possible, and an 80x24 terminal is already pretty cramped as it is. Even in the rare instances where I vertically maximize, my terminal I still don’t want to look at the noise of multiple extraneous directory listings staring back at me. You mileage will most likely vary, though.

The disadvantage of the go command

Using three separate commands provides the shell with context to help it provide better completion options to you. I don’t think this is a big loss if you don’t use autojump, though. I haven’t figured out how I want to set up the zsh completion settings for my go command yet. For now, I will just limp along with the basic completion settings.

This is the sort of problem we see with commands like oh-my-zsh’s x/extract command. It will perform a basic extraction for just about any archive you throw at it, but you lose the ability to complete on files inside the archive.

Happy Friday the 13th!

  • Update 2010-05-18: I moved this code into an oh-my-zsh plugin and submitted a pull request a few days ago.
  • Update 2010-05-20: Added a bit of functionality. If the file to edit is read only ,it will be opened using sudo.

My First btrfs Failure and the State of Ubuntu’s btrfs Support

| Comments

I had my first btrfs file system failure this week. The root/home btrfs volume on the Intel X25-M SSD in my laptop became unmountable on Sunday night. It was functioning just fine with no signs of any problems, but it wouldn’t mount after a reboot. I’ve really been waiting for this sort of thing to happen. There has been quite a lot of improvement to btrfs with regards to stability since I formatted this partition.

I tried to run an fsck from the console of the Ubuntu installer, but it failed. I don’t recall the error message, but after the error came up, all CPU and disk activity ceased. I wasn’t terribly interested in recovering the file system anyway. I run a daily backup to an ext4 partition on my laptop’s second hard drive anyway.

Installing a fresh copy of Ubuntu and restoring my data and configuration only took about two hours. That includes the time it took to download and burn a Xubuntu 11.04 installation disc.

I also keep a backup of the output of dpkg --get-selections. You can pretty much just feed that back into dpkg --set-selections, but on this restore I chose not to do that. I’ve been accumulating a lot of package cruft of the last few years and I figured this was a good excuse to do some spring-cleaning.

The state of btrfs support in Ubuntu’s installer

I am very impressed with the way Ubuntu is handling btrfs. I was worried that they were still going to be mounting the primary volume as root; they don’t do this! They create @ and @home subvolumes and mount these as / and /home. I like this convention of using the @ sign. I was previously using a subvolume called root for / and home for /home.

This saved me a lot of recovery time. I was expecting to have to play a game of “musical snapshots” to get things organized like this. Organizing things this way makes it easier to boot off of a previous snapshot.

I did not let the installer format my btrfs partition, though. I wanted to correct a mistake I felt I made the last time I formatted that partition. mkfs.btrfs defaults to using mirrored metadata. I’ve been thinking that that is just a waste of performance and write cycles on an SSD. I’ve already had two instant total failures of my SSD and that seems to be a very common failure mode for solid state drives. I don’t think I’m likely to have to deal with bad sectors inside the metadata areas.

I don’t know if the Ubuntu installer would have created the file system with mirrored metadata. I didn’t think it was worth taking the time to find out.

I’m not giving up on btrfs

I don’t think I have had a complete and total non-hardware related file system failure in over ten years. That failure was with a reiserfs file system and it almost completely put me off of ever using reiserfs again. I only used reiserfs one single time since then and it was to save space with tail packing.

I knew what I was getting into with btrfs, and I know things will continue to get better. I’m not willing to give up on having regular snapshots to pull files out of. I’ve gotten into the habit of just editing my “only” copy of config files without making a quick backup copy first. It is just easier to yank a copy out of a recent snapshot on the times I actually do screw things up than it is to make backups that I don’t end up needing.

I’m also extremely happy that I can boot off of snapshots of previous installs. I wasn’t terribly happy with my upgrade to Ubuntu 11.04. I always take a manual snapshot before big updates like that, so it was trivial to boot off of my 10.10 snapshot. I was then able to chroot into the 11.04 volume and run some apt-get upgrades in there so I could watch for an update to a package relevant to the issues I was having.

Displaying Conky on an Old Android Phone

| Comments

I have had my old HTC Dream sitting around collecting dust for months. I have been trying to come up with a cool use for it for months. After all that time, I think I finally may have come up with a good use: running a small Conky status display on it via VNC.

External Conky display on an Android phone using VNC

How to do it

Install a VNC server and Conky:

1
apt-get install vnc4server conky-all

I am running Ubuntu and chose to install the VNC version 4 server. This ought to work on Debian as well.

Download and install my Conky configuration file and VNC xstartup file:

1
2
3
4
wget https://blog.patshead.com/Assets/conky-phone/conkyrc-phone -O ~/.conkyrc
mkdir ~/.vnc
wget https://blog.patshead.com/Assets/conky-phone/xstartup ~/.vnc/xstartup
chmod +x ~/.xstartup

Then fire up the VNC server:

1
vnc4server -geometry 480x320 :10

If all goes well, there should be a VNC server waiting for a connection on port 5910. I am currently using the Mocha Lite VNC client on my phone. It is the second client I tried and I am not very happy with it. If I end up finding this hack useful, I will probably try to hunt down a better client. I’d like one that will let me disable the status bar and hide the mouse pointer.

My Conky configuration is rather boring. I just trimmed, condensed, and slightly expanded on an old configuration I used to use a long time ago. It is quite utilitarian.

How useful is this?

I am not entirely sure how useful this is going to be; I haven’t been running this for very long. It has already kept me from having to fire up htop a few times already.

I would like to come up with a good way to attach the phone to my monitor stand if I actually end up finding it useful.