Sync’ up! … without getting drained

aug 1

Calling ed(1) from less(1)

I’m a pretty avid ed(1) user, but my go-to reader is less(1). I like the ‘hjkl’ controls in less(1), and it’s pretty intuitive generally.

Pretty often, I’ll want to change a line while in my reader. When you notice that ‘v’ is the key to take you to an editor, it’s obvious that the editor they want you to use is vi(1). However, I turned my back on this editor a while ago, and am stronger with ed(1) these days.

It’s not as simple as I would have liked to have less(1) fire off ed(1) when pressing ‘v’ while reading a textfile. You can set your ‘EDITOR’ and ‘VISUAL’ environment variables all you like, but less sends along some arguments to your editor of choice that is clearly only intended for vi(1).

If you play around with this and set your ‘EDITOR’ to a script called ‘feedback.csh,’ and put that executable in your ‘bin’ path, you’ll see the following mapping:

  1. ‘${0}’ –> the script/program/editor full path
  2. ‘${1}’ –> the line number to be edited (the middle position of less(1)’s screen buffer)
  3. ‘${2}’ –> the file being read/edited relative path

Here is the content of ‘feedback.csh’:

#

echo '${0} ->' ${0}
echo '${1} ->' ${1}
echo '${2} ->' ${2}

From a dummy file in ‘~’ called ‘FOO,’ this is what we have in place to try this out:

Foo
Bar
Baz

From your home directory, assuming your ‘feedback.csh’ is executable and in a ‘bin’ directory in your path, the following will yield some informative results when we press ‘v’ after viewing the file with less(1) by way of:

$ ( setenv EDITOR ~/bin/feedback.csh; less FOO )

With that, we have everything we need to get ed(1) editing our file from less(1).

Nominal hijacking

At the top of the rearranging list, is our ‘.cshrc’ (or use whatever shell you like). It needs an alias as follows:

...
alias less csh -f ~/bin/myless
...

And in our exported path ‘~/bin’ directory, we need two tiny csh scripts: ‘myless’ and ‘lessed.’

In that order, they are:

#

( setenv EDITOR lessed; less $* )

and

#

set u = $1:s/+//
echo LINE ${u}
ed -s ${2}

Ensuring these two scripts are executable, using less(1) on a textfile then using ‘v’ to edit the file, should give you some unremarkable, yet good results.

Possible improvements

Ideally, I would want my editor to park its position on the line in question from the get-go, but anyone familiar with ed(1) will know that the default position when editing a file in ed(1) is on the last line. That is why we echo to the screen what line should be navigated to.

As well, the line in question is the middle line from what less(1) deems as that window buffer’s center (it will be different with various terminal/console sizing). To calculate what the current window size is, and figure out what to subtract from what is the center line, in order to get a ‘top line of that window’ would be ideal, but far overcooks things for my taste.