Uniquify your Buffer Names in emacs with use-package

Recently I have been working on projects that often have multiple files of the same name. By default emacs doesn’t give much information to help you switch between the buffers of open files of the same name. At the same moment that I was thinking I need to find a solution to this Pragmatic Emacs posted a nice little solution using uniquify.

This is how do the same using use-package:

(use-package uniquify
  :config
  (setq uniquify-buffer-name-style 'forward)
  (setq uniquify-separator "/")
  (setq uniquify-after-kill-buffer-p t)    ; rename after killing uniquified
  (setq uniquify-ignore-buffers-re "^\\*") ; don't muck with special buffers
  )

 

Launch emacs from cygwin

cygwin and emacs logos with love heart in between

I have written about about using emacs in cygwin and how to launch emacs from cygwin, but I had some problems with the batch file approach in that emacs’ path differ from bash’s. Then ack fails to work from within emacs which makes me sad.

After googling around a bit, I saw a few suggestion that trie to fix the path in emacs, but I think a better approach is to launch emacs from within bash so it inherits the bash environment.

Here is my attempt using vbscript:

Dim WinScriptHost
Set WinScriptHost = CreateObject("WScript.Shell")

strCmd = "C:\cygwin\bin\bash --login -c '/usr/local/bin/emacsclient -c -a /usr/local/bin/emacs.exe"

    If WScript.Arguments.Count = 1 Then
        'strCmd = strCmd & " " &"""" & WScript.Arguments(0) & """'" 
		wScript.Echo strCmd
	else
		strCmd = strCmd & "'" 'close single quote
    End If

WinScriptHost.Run strCmd,0 
Set WinScriptHost = Nothing

Save that script somewhere and then make a Windows Shortcut to it but incle the wscript.exe in the target:

C:\Windows\System32\wscript.exe C:\Users\jason\launchemacs1.vbs

You can then launch it from the Start Menu in Windows 7.

Emacs: yank a line multiple times from the kill ring

a line of php repeated 8 times

Today I needed to copy a line multiple times in emacs. I needed 8 copies, but how to do that in emacs short of pressing C-y to yank 8 times? My initial guess was to try C-u 8 C-y but that yanks the 8th item from the kill ring.

Fuco on #emacs supplied the awesome answer:

F3 C-y C-8 F4

So what does that do? F3starts recording a macro, C-yyanks the line, then within the macro itself you can add a numeric argument of 8 using C-8. End recording of the macro with F4. Emacs then runs the macro 8 times. Recall that pressing F4 after ending recording of the macro runs the macro.

Launching cygwin emacs from native win32 programs

My business’s accounting program, which I’ll call Canopus, has issues. One of which is that it assumes wordpad.exe will be in c:\windows. As far as I know, Microsoft moved wordpad.exe’s default location away from c:\windows about 20 years ago. Canopus live in hope that it will be there so installing Canopus always requires one to copy wordpad.exe to c:\windows

The other problem with Canopus is that it does not fork when launching wordpad.exe, so you can’t continue using it until you close wordpad. This is stupid as most likely you need the information in wordpad to do further work in Canopus.

So a long time ago I came up with a solution. With the help of a friend (well, he wrote it for me in Delphi) I developed a small program called wordpad.exe which reads a config.ini file to configure which editor to open. It makes a copy of the file in $1 and launches whatever editor you specify in the config.ini with $1 as its parameter.

This worked well and everyone was happy until I decided to use cygwin emacs instead of the native win32 compiled emacs.

The problem is that cygwin emacs expects paths to be of the unix flavour (/home/jason/whatever) rather than the dos flavour (c:\users\jason\whatever). And so the rabbit hole needed and extension.

I didn’t want to have to modify my wordpad.exe program as that would require me to get the lazarus (open source delphi replacement) toolchain working again, so I decided to write a shell script wrapper to do it.

launchemacs.sh:

#!/bin/bash
/usr/local/bin/emacsclient.exe -n $(cygpath "$1")

and my config.ini for wordpad.exe:

[Config]
Exe=c:\cygwin\bin\run.exe
option=/usr/bin/bash.exe "/cygdrive/c/Users/jason/launchemacs.sh"

You can see that wordpad.exe launches the cygwin run.exe which calls the launchemacs.sh file with the first parameter.

Project Euler No. 2 in Emacs elisp

My second Project Euler solution.

Project Euler No. 2

This was a little tougher to solve than No. 1. I decided to use recursion to solve it, and as I haven’t had to write anything that used recursion since I was at Uni, it took me a while go remember how to do it. Also, it was an elisp learning exercise.

Things I learnt:

  1. successive statements inside an if statement need to be inside a progn.
  2. passing in the evens variable was the way to solve this without needing a static variable. Thanks to spacebat for that one. Apparently that is the functional programming way of doing things.
;; Project Euler no 2. Calculate the sum of all even terms in the
;; fibonacci sequence of numbers that do not exceed 4,000,000

(defun fibonacci (x y)
  "calculate the next number in the fibonacci sequenece"
  (+ x y))


(defun fibonacci-sum  (fib1 fib2 target &optional evens)
  "find the next fibonacci number bigger than target, given fib1 and fib2"
  (unless evens
    (setq evens 0))
  (let ((fib3 (fibonacci fib1 fib2 ))
        )
    (if (<=  fib3 target)
        (progn (if (zerop (mod fib3 2))
                   (setq evens (+ fib3 evens)))
               (message (format "fib3 is: %d, evens: %d" fib3 evens))
               (setq fib3  (fibonacci-sum fib2 fib3 target evens)))
      (format "fib3: %d > %d target, evens = %d" fib3 target evens)
      )
    )
  )

(fibonacci-sum 0 1 4000000)

emacs elisp first attempts

For a long time I have wanted to learn elisp in emacs. I tried the various tutorials but I get bored of them too quickly. Too many words not enough action for me. I was reminded of Project Euler by Daniel Silverstone so I thought I’d have a crack at one of the problems. No. 1, Multiples of 3 and 5 seemed like a good place to start.

Here are my first attempts and questions I came up against. Many thanks to the people of #emacs on freenode for answering my questions.

Q: Why doesn’t the elisp doco within emacs have examples?

A: Often it does. But if not, check the elisp info pages. info-apropos. Or use s in an info buffer to search.

Q: is there a printf equivalent in lisp?
A: format – at first this confused me as I thought it would just format a string and not print it. I think it was a fundamental misunderstanding of what print actually does.

Q: in a defun, what should you do if the caller supplies an invalid parameter? like supplying a float instead of an int?
A: (error “Fail!”), check with integerp
(error ‘wrong-type-argument “Foo is bad, and you should feel bad.”)

Q: how would I check if a number is divisible by another number? (to give an integer result)
A: ijp | k-man: (defun (divisiblep x y) "is x divisible by y?" (zerop (mod x y)))

My final hurdle was having too many brackets around an if statement. I had written

if (or ((divisibleby i 3))

instead of

if (or (divisibleby i 3)

Once I had fixed that my program worked.

installing emacs in cygwin

Update: See my other post, launching emacs from cygwin

There are a few tricks to installing emacs in cygwin. Here’s what I do.

Installing cygwin

First, install cygwin.

Then, install the very nice tool apt-cyg which makes package management much easier in cygwin.

Then to save yourself lots of agony of trying to work out which cygwin packages you need to install to be able to compile emacs, here is the list of all the packages I have installed. It may be a little bit of overkill but it will save you time. I obtained the list like this:

jason@jade ~
$ apt-cyg show | tr '\n' ' '

Install them with:

$ apt-cyg install 
_autorebase _update-info-dir alternatives autoconf autoconf2.1 \
 autoconf2.5 automake automake1.10 automake1.11 automake1.12 \
automake1.4 automake1.5 automake1.6 automake1.7 automake1.8 \
 automake1.9 base-cygwin base-files bash bash-completion bc binutils \
bzip2 ca-certificates cmake coreutils cpio crypt csih curl cvs cvsps \
cygrunsrv cygutils cygwin cygwin-doc dash dbus diffutils dos2unix \
editrights file findutils gamin gawk gcc-tools-epoch1-autoconf \
gcc-tools-epoch1-automake gcc-tools-epoch2-autoconf \
gcc-tools-epoch2-automake gcc4 gcc4-core gcc4-g++ gccmakedep gettext \
gettext-devel git git-completion git-gui git-svn gitk gitk grep groff \
gsettings-desktop-schemas gsettings-desktop-schemas gzip imake \
ipc-utils less libX11_6 libX11_6 libXau6 libXau6 libXdmcp6 libXdmcp6 \
libXext6 libXext6 libXft2 libXft2 libXrender1 libXrender1 libXss1 \
libXss1 libapr1 libapr1 libaprutil1 libaprutil1 libasn1_8 libattr1 \
libblkid1 libbz2_1 libcharset1 libcloog0 libcom_err-devel libcom_err2 \
libcurl-devel libcurl4 libdb4.5 libdb4.5-devel libdb4.5-devel libdb4.8 \
libdb4.8 libdbus1_3 libdbus1_3 libedit0 libedit0 libexpat1 libfam0 \
libfam0 libffi4 libfontconfig1 libfontconfig1 libfreetype6 \
libfreetype6 libgcc1 libgcrypt11 libgdbm4 libgettextpo0 libgettextpo0 \
libggi2 libggi2-display-terminfo libgii1 libgii1 libglib2.0_0 \
libglib2.0_0 libgmp3 libgmpxx4 libgnutls26 libgomp1 libgpg-error0 \
libgssapi3 libhdb9 libhdb9 libheimbase1 libheimntlm0 libhx509_5 \
libiconv libiconv libiconv2 libidn-devel libidn-devel libidn11 \
libintl8 libkadm5clnt7 libkadm5clnt7 libkadm5srv8 libkadm5srv8 \
libkafs0 libkafs0 libkdc2 libkdc2 libkrb5-devel libkrb5-devel \
libkrb5_26 liblzma5 liblzo2_2 libmetalink3 libmpc1 libmpfr1 libmpfr4 \
libncurses-devel libncurses10 libncurses7 libncurses8 libncurses8 \
libncurses9 libncurses9 libncursesw-devel libncursesw10 libneon27 \
libneon27 libopenldap2_3_0 libopenldap2_3_0 libopenldap2_4_2 \
libopenssl098 libopenssl100 libp11-kit0 libpcre0 libpcre1 libpcre1 \
libpopt0 libppl libpq-devel libpq-devel libpq5 libpq5 libproxy1 \
libproxy1 libreadline6 libreadline6 libreadline7 libroken18 libsasl2 \
libsasl2-devel libsasl2-devel libserf0_1 libserf0_1 libserf1_0 \
libserf1_0 libsigsegv2 libsl0 libsl0 libsqlite3_0 libssh2-devel \
libssh2-devel libssh2_1 libssp0 libstdc++6 libstdc++6-devel libtasn1_3 \
libuuid1 libuuid1 libwind0 libwrap0 libxcb1 libxcb1 libxml2 login m4 \
make makedepend makedepend man mintty nano ncurses ncurses-demo \
ncursesw ncursesw-demo openldap-devel openldap-devel openssh openssl \
openssl openssl-devel openssl-devel perl perl-Error \
perl-Locale-gettext perl_vendor python rebase run sed stgit subversion \
subversion subversion-perl subversion-perl tar tcl tcl tcl-tk tcl-tk \
termcap terminfo terminfo-extra terminfo0 terminfo0 terminfo0-extra \
texinfo tzcode unzip util-linux w32api w32api-headers w32api-runtime \
wget which xorg-cf-files xorg-cf-files xz zlib zlib-devel zlib-devel \
zlib0

Go and have a cup of tea while its installing.

git clone git://git.savannah.gnu.org/emacs.git
cd emacs
./configure --with-w32 #  to ditch gtk and the concomitant gtk bug, thanks jlf
make

If make is successful, test the build by running emacs from the src directory:

src/emacs -Q

If that worked ok, you can:

make install

Setting up your home

I like my cygwin home directory to be the same as windows %USERPROFILE% so I set the environment variable HOME=%USERPROFILE%.

Set up a shortcut to launch emacs

Make a shortcut to c:\cygwin\bin\run.exe on your desktop, and rename it to emacs.
Edit the shortcut to:
Target: C:\cygwin\bin\run.exe /usr/local/bin/emacsclient "-c" "-a" "/usr/local/bin/emacs.exe" #
Start in: %USERPROFILE%

The target part makes sure emacs launches a new window whether or not its already running. If it is already running and as a server, it will create a new frame connected to the server.

The start in part makes sure the new instance’s default-directory is your home directory which I think makes most sense for when you are launching from a shortcut.

Drop the shortcut onto your start menu. You should now be able to launch emacs from the start menu, or by pressing the Windows key and typing emacs.

OAuth 2.0 in emacs – Part 1

I want to write something in emacs to let me edit WordPress posts directly. There is of course the blogger-mode in emacs, but I’ve never managed to make that work. Then I noticed that JetPack in WordPress has a JSON interface. Supposedly it will let me do stuff to my blog via a REST interface.

What better way to learn something than try and learn 10 new things at once?! I mentioned my plan on #emacs and Nic Ferrier asked me to document the journey.

First thing is that your app needs to use oauth2 to authenticate. I tried the sample code given on wordpress.com. Before you can do that though, you need to log into wordpress.com and create an “app” and enable the JetPack JSON api module.

<?php 
 $curl = curl_init( "https://public-api.wordpress.com/oauth2/token" );
 $curl_setopt( $curl, CURLOPT_POST, true );
 $curl_setopt( $curl, CURLOPT_POSTFIELDS, array( 'client_id' =--> XXXX,
'redirect_uri' => 'http://emacstragic.net',
'client_secret' => biglongsecretstring,
'code' => $_GET['code'], // The code from the previous request
'grant_type' => 'authorization_code'
) );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$auth = curl_exec( $curl );
$secret = json_decode($auth);
$access_key = $secret->access_token;

echo "auth: $auth";
echo "secret: $secret";
echo "access_key: $access_key";

?>

This results in:


auth: {"error":"invalid_request","error_description":"The required \"code\" parameter is missing."}
Catchable fatal error: Object of class stdClass could not be converted to string in /Users/jason/Dropbox/projects/emacs-wordpress/test.php on line 17

not very helpful. I then decided to see whats available in emacs. And low and behold Julien Danjou has written an OAuth 2.0 library for emacs. It’s available in ELPA in emacs >= 24

I downloaded and installed it no problems but the documentation lacks any kind of working example that I can see.

My first attempt was to run the oauth2-request-authorization function, but it required strange parameters. (oauth2-request-authorization AUTH-URL CLIENT-ID &optional SCOPE STATE
REDIRECT-URI)
What the hell are scope and state?

Then looking through the source I found oauth2-request-access with a more promising (oauth2-request-access TOKEN-URL CLIENT-ID CLIENT-SECRET CODE
&optional REDIRECT-URI)

So I tried that: (oauth2-request-access "https://public-api.wordpress.com/oauth2/token" "XXXX" "longsecretcode" "CODE" "http://emacstragic.net" )

which returned [cl-struct-oauth2-token nil nil "XXXX" "longsecretcode" nil nil "https://public-api.wordpress.com/oauth2/token" ((error_description . "Invalid authorization_code.") (error . "invalid_grant"))]

That looks promising in a way. At least its doing something!

Stay tuned for part 2.