Irreal: Emacs Rocks Episode 9 Is Up

Magnar Sveen has another episode of his excellent Emacs Rocks up. In this video he talks about expand-region, an Emacs package that he wrote to help with marking text in an intelligent way. The video is less than 3 minutes so there’s no excuse not to take a look. As with all the Emacs Rocks videos, you won’t be sorry.

Watch the video and if you like what you see, get the code on github.

-1:-- Emacs Rocks Episode 9 Is Up (Post jcs)--L0--C0--January 27, 2012 08:43 PM

Phil Hagelberg: in which an interview is posted

The folks over at The Setup just posted an interview with me wherein I rant about hardware, interactivity, and Emacs.

Note: this was written up over a month ago; if I were interviewed today I couldn't help but mention the Nix package manager. I use it on my Debian Squeeze system to complement apt-get; I get all the system-level stuff that has to be stable from Debian and anything that needs to be fresh from Nix.

-1:-- in which an interview is posted (Post Phil Hagelberg)--L0--C0--January 27, 2012 03:58 AM

Irreal: What Makes Emacs So Great?

Over at The Setup they are featuring Phil Hagelberg who has an especially nice take on what makes Emacs so great. He says that Emacs is as close as you can get on modern systems to the fully dynamic environment of the Lisp Machines of the 80′s. Almost any part of the environment can be changed at runtime without recompiling or restarting.

I think that’s exactly right. There are, I suppose, Emacs users who don’t change anything from the default setup but as Irreal readers know, I have all sorts of customizations to my Emacs and I am not in the least unique in this. One of the nice things about this is that I wrote those customizations using the same mechanisms as the authors of Emacs itself. Hagelberg says, “It’s hard to overstate the benefits of this setup.” It’s something that you get “for free” because when we make extensions to Emacs we’re writing in Lisp and as Doug Hoyte says in Let Over Lambda, “…lisp gives you the same tools available to the people who created your programming environment.”

Hagelberg goes on to say that this reduces the friction of tweaking your environment to such a low level that you’re more willing to experiment and improve things than you would be in a more standard environment. For example, I use OS X and really love it but it’s too hard to make anything other than fairly simple changes to the default behavior and most of those are changes that the system implementors anticipated and provided some way of effecting. I would guess that this ability to customize things is the reason that many Emacs users try to avoid leaving Emacs at all, choosing to read and send mail, use IRC and IM, listen to music, and many other things all from Emacs. Why not? You can pretty much have it anyway you want it.

-1:-- What Makes Emacs So Great? (Post jcs)--L0--C0--January 26, 2012 08:27 PM

Rubén Berenguel: Learning to use vim in my iPad (even if I'm an emacs geek)


Just in case you don't know, vi is an advanced text editor, drting back from the same era as emacs was developed (emacs started slightly earlier). Sort of the Jekyll to emacs' Dr Hyde. Emacs users despise vi users, and vi users mock emacs users. This is what the editor wars are all about: "Eight Megabytes And Constantly Swapping" versus "vi has two modes: writing and beeping". If you have been long enough in this blog, you know I'm in the emacs side, but you also know I'm curious enough to delve into the other side.


My first contact with vi was in our first programming class at the University, Informatica (Computer Science). Vi was the editor of choice for the course, so much that you did not have any other option given. Along with a Linux cheatsheet and a short C manual came a vi cheatsheet. A lot of people came to hate vi, a lot of people came to love it. I was more in the hating side, but it wasn't that bad. After a while I just started using a "normal" Linux editor (it was Kate, maybe?) and kept using it (or UltraEdit when I was in Windows) until the end of my degree.

When I finished my degree I had to be a teacher of Calcul Numeric (Numerical Analysis), the third (and last) programming class in the degree. At home I was still using Windows, because the wifi card in my notebook had no Linux drivers and in my office we were using Ubuntu. I needed a cross-platform editor that was quick, versatile and could last for a lifetime. I tried vi (again) and emacs, emacs won the war for two reasons. First was the fact that it was extensible programming in Lisp, and I had already a decent knowledge of Lisp. The second was AucTeX and its "preview" option for LaTeX editing. Nothing can beat pressing C-p C-p C-d and seeing your formulae come to life in your editor. I became an emacs advocate for this reason, then after 5 or 6 years I've found many more reasons why this is the editor. Or, the operating system, if you prefer.

But advocacy is nice, but knowing all the players in the field is better. My department pals used vi (at least most of them), and it was impossible to convince them to switch. I decided learning vi (or vim, vi iMproved) was something I had to do some day, to learn what was there. After all, if I liked it so much I could set viper-mode in emacs and use vi keys in emacs. The best of two worlds, if that world is so nice.

Then the guys at Applidium released a Vim port for iOS devices. Whoah! Even if I'm an emacs guy to the bone, a modal editor is way better than anything else available in the app store, at least for raw editing power. And I say with knowledge, because I've tried most writing apps for iOS devices (see this post).

As an additional reason, Matt Might posted a New Year's post detailing several resolutions for programmers. Among them was breaking your comfort zone to keep your mind sharp. The first example? Switching to vi from emacs or vice-versa. He used to be an emacs user before getting to use Vi. I don't think I could go that far, but these were enough reasons: advocacy (from me, not against me), iPad+bluetooth keyboard and breaking my comfort zone.

How is the experience so far?

Well, I'm writing this post in my sofa, with my iPad and my bluetooth keyboard sitting in my lap. I'm still getting used to having to exit editing mode to move around: I'm very used to pressing C-a or C-e to go to the beginning of end of line. An additional problem is that even with the bluetooth keyboard, Esc can't be mapped to the Esc event, and I needed something to do it. I have jk (pressed together) for it. It was a suggestiond I saw in Hacker News' comment thread for the release of the app, and it's quite handy. Not so much with the on-screen keyboard, but for now it's okay. To remap this, press backslash (the current mapping for Esc) and then :imap jk . Of course if your usual writting language involves writing the jk combination frequently (I think I could come up with one or two examples in Icelandic), this is not the best combination. The other suggested option is :imap al . Easy to tap in a virtual keyboard, not so straightforward in a normal keyboard.

I found out also how to change the font size, at least for now this works (maybe there will be more fonts available in the future), type :set guifont=Courier:h24 (for 24 pixels)

To round everything, I just installed the famous solarized color theme, dark in vim for iPad. Until now I had just thought it was an overhyped color scheme: I had tried in my emacs and didn't enjoy it that much. But in my iPad it shines with a distinct colour, it's so much easier on my eyes that it hurts to get out and write an email! To install it in your vim for iOS, first download solarized.vim from the git repository, then plug your iDevice and use iTunes File Sharing to copy this file to the vim app. Then open vim, :e solarized.vim and :call mkdir(.vim/colors/) (to create the directory needed for it) :w .vim/colors/solarized.vim This is just because I didn't seem to get iTunes File Sharing to work with hidden files (a file starting with a dot is hidden). Then you have to add the following to your .vimrc:
syntax enable
set background=dark
colorscheme solarized
I recommend using this app for any emacs lover out there with an iPad. Of course, it is not emacs, but vim is a pretty awesome text editor, and it's always handy to learn to use it.

To have a useful list of vim commands at hand I installed the Vimmy app, a universal app with the most common vi commands. I can switch to it via the multitasking gestures in my iPad, or use it in my iPod Touch while I'm using it in the iPad.

Conclusion

I don't think I'll ever switch from emacs to vim any time in the future, as I said AucTeX is definitely too good. Of course since then I've found many more things I love: having a REPL for Python, Clojure or Lisp inside my editor. There's even a REPL for PostScript! Also local remote editing with tramp... There are too many things I use on a daily basis and I can't barely remember, they are so entrenched in my .emacs file I can't even realise what they are. But for my iPad it is an awesome addition to write text on the go.

Again, if you have never used vim before and are interested, give it a try. Of course the first time you open it it will be... a jump into the unknown. Tap the screen, press :e filename and start editing happily. Esc (well, jk or backslash, as the initial mapping) :w to save. And you can even :q to exit to springboard!





-1:-- Learning to use vim in my iPad (even if I'm an emacs geek) (Post RBerenguel (noreply@blogger.com))--L0--C0--January 26, 2012 02:37 PM

Tom Tromey: Emacs and Common Lisp, Part 2

This is a followup to my earlier post on converting the Emacs C code into Common Lisp.  This one is a bit more technical, diving into some specifics of the conversion process.

Basics

One important fact is that we do not need to convert an arbitrary C program to Common Lisp.  This might or might not be efficiently possible — but we do not care.  We only need to convert Emacs.  This is simpler for two reasons.  First, we can just ignore any C construct that Emacs does not use.  If the translator barfs after some new update, we can fix it then.  Second, Emacs itself is already written in a relatively Lispy style, being a Lisp implementation itself.  We further exploit this by allowing the translator to know some details about Emacs.  As a trivial example, all the Smumble globals created by the DEFUN marco need not be translated into Common Lisp as structure constants — they are an artifact of the implementation, and will show up directly in the generated defuns instead.

What to ignore

A good portion of Emacs is simply redundant in the CL world.  There are a few types (cons, vector, integers, functions) that are shareable — in fact, sharing these is part of the goal of this effort.  There are also a number of functions which are effectively identical.  There are also entire redundant modules, like the garbage collector, or the bytecode interpreter.

The question is how to have the translator differentiate between what is useful and what is not, without breaking builds of future versions of Emacs.

I don’t currently think there is a high road to solving this problem.  For modules like the GC, I plan to have ad hoc translator rules for the particular source files.  For functions and data types, I’m adding new GCC attributes that I can use to mark the ignorable definitions.

Types

There are two type-related issues that arise when translating the source.

First, how should Emacs-specific types be represented?  Primarily these types are structures, like struct buffer or struct string (we cannot use the CL string type, because Emacs adds properties directly to the string, and Emacs has its own idiosyncratic character handling).  My answer here is to just straightforwardly translate them to defstruct.

The other question is when translating a C function, what do we do with the types of local variables?  For the most part I am pretending that they don’t exist.  This works fine except for local arrays and structures, but these are easily handled by initializing variables properly. My rationale is that while this is slower, it lets me get something working more quickly, and we can always update the translator to emit CL type declarations later on.

This simple approach doesn’t actually cover all the needed cases.  For example, there is code in Emacs that takes the address of a local variable and passes it somewhere.  This is easy to deal with; much of the remaining work is just digging through the code looking for special cases to clean up.

I’m similarly omitting type declarations from the generated structures.  One possible nice side effect of this approach is that it will make it easier to lift Emacs’ file-size restrictions, because there will no longer be any code assuming that the size is a fixnum.

Macros

Many low-level details of the Emacs implementation are hidden in macros.  For example, Emacs stuffs some type information into the low-order bits of pointers.  It uses macros to add or remove this information.  For this build, I redefine these macros to do nothing.  This makes the GCC Gimple representation much closer to the abstract meaning of the program, and thus simpler to translate.

There are also some macros that are useful to redefine so that we can more easily hook into them from the translator.  For example, Emacs has a C macro INTEGERP that is used to check whether its argument is an integer.  Normally this macro uses bit twiddling to get its answer, but I redefine it like so:

#undef INTEGERP
extern Lisp_Object *INTEGERP (Lisp_Object)
    __attribute__((lisp_form("integerp")));

Example

The translator is not nearly complete, but it can already do a fair job at translating simple functions.  For example, here is “forward-point” from the Emacs C code:

DEFUN ("forward-point", Fforward_point, Sforward_point, 1, 1, 0,
       doc: /* Return buffer position N characters after (before if N negative) point.  */)
  (Lisp_Object n)
{
  CHECK_NUMBER (n);

  return make_number (PT + XINT (n));
}

Here is what the translator comes up with:

(defun Fforward_point (n)
  (let (
    temp-var-0
    Qintegerp.316
    temp-var-1
    current_buffer.317
    temp-var-2
    )
    (block nil (tagbody
      bb-0
        ; no gimple here
      bb-1
        ; no gimple here
      bb-2
        (setf temp-var-0 (integerp n))
        (if (== temp-var-0 nil)
          (go bb-3)
          (go bb-4))
      bb-3
        (setf Qintegerp.316 Qintegerp)
        (wrong_type_argument Qintegerp.316 n)
      bb-4
        (setf current_buffer.317 current_buffer)
        (setf temp-var-2 (buffer-pt current_buffer.317))
        (setf temp-var-1 (+ temp-var-2 n))
        (return temp-var-1)
  ))))

(defun elisp:forward-point (arg0)
  (Fforward_point arg0))

The output looks pretty weird, because the translator works after GCC’s CFG is built, and so the most straightforward translation is to use this mess with tagbody.  I doubt this matters much, but in any case the translator is readily hackable — it is still less than 400 lines of Python, including comments.

One thing to note is the translation of “PT“.  This is actually a macro that refers to the current buffer:

#define PT (current_buffer->pt + 0)

The translator properly turns this into a reference to “buffer-pt“.

Another detail is the handling of packages.  My plan is to put the Emacs implementation into one package, and then any elisp into a second package called “elisp“.  A DEFUN in the C code will actually generate two functions: the internal one, and the elisp-visible one; hence the “elisp:” in the translation.

Next Steps

There’s still a good amount of work to be done.  The converter punts on various constructs; type translation is implemented but not actually wired up to anything; the translator should emit definitions for alien functions; and plenty more.

-1:-- Emacs and Common Lisp, Part 2 (Post tom)--L0--C0--January 25, 2012 03:01 PM

"David's World": Cognitive Modeling and Computational Linguistics

This workshop provides a venue for work in computational psycholinguistics: we invite a broad spectrum of work in the cognitive science of language, at all levels of analysis from sounds to discourse. It will be held at NAACL-HLT'2012 in Montreal.

Find the full Call for Papers here.

-1:-- Cognitive Modeling and Computational Linguistics (Post David Reitter)--L0--C0--January 25, 2012 02:30 AM

Ben Simon: My Dozen Lines of Code

Today's ProgrammingPraxis challenge is this gem:

A high-school programming teacher recently asked for examples of short programs with a high “cool” factor, the idea being to get his students interested in programming computers. I’m not sure the suggestions would work; today’s high-school students have been surrounded by computers their entire lives, and it takes a lot to make them think a program is cool. Being from a different generation, I can remember when I thought it was cool that a program properly skipped over the perforation on a stack of green-bar paper — many programs didn’t! Your task is to write a cool program in a dozen lines of code. You can define cool in any way that you wish. Try not to abuse the definition of “line of code,” at least not too badly; to be concrete, we will say that your solution must not exceed 12 lines, and each line must not exceed 80 characters including white space. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

The ideal intro-to-programming example should meet two needs: (1) it should be relevant and interesting to students and (2) it should lay the groundwork for learning good habits.

Meeting those two goals in 12 lines of code is tricky. But, I think doable. In fact, I believe I've done it below.

Using AutoHotKey, I've written a simple implementation of the classic Boss Key. While not exactly some exciting 3D game, I'd say that this sort of example is relevant and at least interesting to students. And while it may not be obvious, there are a number of best practices taught, including:

  • Use the right programming language for the job. AutoHotKey makes scripting trivial, so embrace it.
  • Learn about regular expressions
  • Learn how to read language reference documentation
  • Learn about loops
  • Learn that programming is all about solving your problems and making life better
  • Learn about variables and the advantages of not hard coding values throughout code
  • Many opportunities for growing this example

OK, enough talk, here's the code:

;; A simple Boss Key app. My contribution to the dozen-line program contest.
NeedToHide = .*(Mozilla|Explorer|Chrome).*
WantToShow = .*emacs.*
#b::
  SetTitleMatchMode, RegEx
  WinGet, id, list, %NeedToHide%
  Loop, %id% {
    this_id := id%A_Index%
    WinHide, ahk_id %this_id%
  }
  WinActivate, %WantToShow%
  Return,

You can run this by downloading autohotkey (it's free) and running:

  autohotkey bosskey.ahk

Once you run the above code, hitting Windows+b will hide all your browser windows and bring emacs to the front. The windows aren't just minimized, they are hidden so they don't appear in your start bar.

You'll probably want this command available (Windows+w) too, as it restores all your browser windows:

#w::
  DetectHiddenWindows, On
  SetTitleMatchMode, RegEx
  WinGet, id, list, %NeedToHide%
  Loop, %id% {
    this_id := id%A_Index%
    WinShow, ahk_id %this_id%
  }
  WinActivate
  Return

And yes, I know the syntax and semantics of AutoHotKey are hideous. But, given how powerful it is, I think it's a platform worth learning on.

-1:-- My Dozen Lines of Code (Post Ben Simon)--L0--C0--January 24, 2012 01:52 PM

Alex Bennée: Switching buffers and Google+

When you do so much of your work in one text editor the efficiency of switching between buffers becomes more important. For a long time I’ve had two bindings “C-x b” and “C-x C-b” which in days of yore I had bound to bs-show and a hacked up list-buffers that opened another window. These are broadly the “quick switch between working buffers” and “show me all the buffers”.

For some time I’ve relegated bs-show to the longer binding and now use Stephen Bach’s excellent Lusty Explorer which works really well when you know the name of the buffer and it’s fairly unique. However when you’ve been going a while it can get un-manageable with a large number of open buffers, especially if you’ve opened second copy of a file from another source tree. This is what I would use the old classic bs-show for.

A few days ago I discovered ibuffer-mode with it’s ibuffer-bs-show buffer navigator. Looking back through the Planet Emacsen history I can see it has been mentioned before and given it’s been in Emacs since version 22 I’m surprised I hadn’t cottoned on to it earlier.

One thing that might have put me off is the initial buffer list can be quite sparse. By default you only see buffers with files associated which misses out IRC, Edit with Emacs and *scratch* buffers. However hit “h” and you’ll see there are a plethora of quick keys for chaning the view. A quick “//” and all filters are removed and you can quickly filter by different criteria. To get the most out of the mode you’ll probably want to set up some custom filters (“/r<completing filter name”>) to make quickly switching to groups of buffers easy. I currently have “work”, “remote”, “irc” and “logs” as filters. You can filter by name as well as major-mode.

ibuffer-mode does have the concept of Filter Groups although I’m not sure what they add on top of having normal filters which as far as I can tell can be arbitrarily complex. It also has some quite handy sorting and selection modes e.g. “sv” – sort by last viewing time. Given the amount of space the wiki devotes to the topic I wish I’d re-examined my buffer switching habits sooner. The change is already paying dividends for my productivity.

Before I go I thought I’d put in a quick mention of Google+. There is growing community of fellow Emacs users starting to post on it. One thing that attracts me to Google+ over Facebook (too data-miney) and Twitter (too short) is the concept of “Circles”. It makes sharing geeky Emacs posts with people that might actually care easy while sparing them the flood of baby pictures I share with friends and family. If you’d like to follow me or my alter-ego please do mention Emacs in your profile or in a message so I can assign you to the correct circles.

-1:-- Switching buffers and Google+ (Post Alex)--L0--C0--January 24, 2012 08:36 AM

Ignacio Paz Posse: emacs using recode-region for encoding failures

I had an encoding issue that was bugging me inside the remember-data-file. I don’t know exactly how some latin-1 characters copy-pasted there ended up being saved as raw-text and were shown like non-ASCII characters (so a multibyte characters like “é” will appear with it’s escaped octal code “303\251″ )

I tried at first setting the file’s encoding system with the tag “-*-coding: utf-8 -*-”, though it seemed not sufficient. The raw characters remained there and I soon grew tired of having to type in: “utf-8” at the prompt to select the encoding every time I needed to save the file.

Today searching the manual found here one easy cure on the command “recode-region” which allows to convert the text that was decoded with the wrong coding system.

Really all it took after marking the whole buffer (C-x h) was doing: “M-x recode-region RET” “Text was was really in: utf-8” “But was interpreted as: raw-text”

That was it!, the drag is over, I’m back to storing notes quickly doing just C-c r and C-c C-x with the worthy remember mode.


-1:-- emacs using recode-region for encoding failures (Post ignacio)--L0--C0--January 23, 2012 09:07 PM

Got Emacs?: It's not Coincidence, it's Providence!


Browsing my local paper, found this little gem tucked away in a small article.  This year is the 125th birthday celebrations of mathematical genius Ramanujan, so The Hindu runs lots of maths related stuff as well as vignettes about Ramanujan, this year.  Here's a weird but nice clip from the article.

A tale Robert Kanigel repeated a couple of times during his recent visit to Madras to launch the 125th birthday celebrations of mathematical genius Ramanujan related to his first visit to Madras in 1988 to start following the Ramanujan trail on the ground as he got down to working on the mathematician's biography.


That November day he landed from London was a bandh day in Madras and the airport was virtually deserted. There was a lone auto rickshaw with a passenger in it and another person haggling to get aboard. That person was Viswanathan Venkataraman, who had also arrived from London. When he noticed the forlorn foreigner wondering what he should do, Viswanathan told him that the only way to get to the city was to squeeze in with them. And Kanigal joined them for that ride in a sardine tin.


During the ride, Viswanathan discovered that Kanigal was not a tourist but a well known writer who was working on Ramanujan's biography. “What a coincidence,” remarked Viswanathan, “I am the grandson of S. Narayana Aiyar with whom Ramanujan worked in the Port Trust.” No, it's not coincidence, it's Providence, a surprised Kanigal enthusiastically replied. And so began Kanigal's first steps in Madras that led to The Man Who Knew Infinity: A Life of the Genius Ramanujan.


-1:-- It's not Coincidence, it's Providence! (Post sivaram (noreply@blogger.com))--L0--C0--January 23, 2012 04:36 PM

Robert Adesam: First Post

Ok my first blog post, should be about me right? No, you can read about me on my web site http://www.adesam.se/robert/.

Instead let's talk about what I am presumably going to write about. I think it's going to be about computers, technology in general and Emacs in particular. Maybe I will find time to post notes about GTD etc as well...

Emacs -- what is it and why do I use it? It's a way of life... or as stated in Wikipedia, it's a text editor that is higly extensible and customisable. If you know a little bit of LISP one can very quickly tweak Emacs to do what you want. I use Emacs for writing papers, programming, reading/writing emails, and organising my life. Now days I am quite comfortable with Emacs, but over the years I have tried to exchange Emacs for other tools like Eclipse, Thunderbird, Mail.app, etc but I have given up. Emacs is for me, and it works basically the same way on all systems I use: Mac OS X, Windows, Linux, Solaris...
-1:-- First Post (Post Robert Adesam (noreply@blogger.com))--L0--C0--January 23, 2012 04:13 PM

Got Emacs?: A quick round up on Org, Emacs 23.4 news

Looks like I'll be busy for the next couple of weeks on work related stuff.  Here's some newsworthy posts from various mailing lists.

Konrad Hinsen has posted a patch for org-mode for IMAP support for VM links in orgmode.  Possibly of interest only to VM users.

Due to a security issue, there will be a Emacs 23.4 release in the next week or so, here's the announcement of the first release candidate by Chong Yidong.



-1:-- A quick round up on Org, Emacs 23.4 news (Post sivaram (noreply@blogger.com))--L0--C0--January 21, 2012 03:33 PM

Flickr tag 'emacs': Vim user

santosh.wadghule posted a photo:

Vim user

I love vim editor

-1:-- Vim user (Post santosh.wadghule (nobody@flickr.com))--L0--C0--January 21, 2012 02:26 PM

Vincent Toups: Shadchen: A pattern Matching Library for Elisp

A pattern matching library for Emacs Lisp

One of the things I like most about Racket (and other functional programming languages) is that they have good support for pattern matching, which is a great way to simultaneously dispatch on structure type, enforce constraints on values held in a data structure, and bind variables. A tremendous amount of code is devoted to these activities, and pattern matching combines them all in a succinct, easy to read form.

It's been my intent for some time to write a complete pattern matching library for Emacs Lisp, since it is a Lisp which I use very frequently. Shadchen is the first time any attempt to do so has resulted in a reasonable product. Shadchen is a Yiddish word for matchmaker, in case you were wondering about the title. The library is available in my elisp repository. Even though it comes in a giant directory full of junk, it runs standalone.

[EDIT: Here it is in a standalone repo.]

How it Works

Shadchen's interface consists of just three forms. match is the work horse - it actually performs a pattern match. match has the syntax:

(match <VALUE>
 (<PATTERN1> FORMS ...)
 (<PATTERN2> FORMS ...)
 ...
 (<PATTERNN> FORMS ...))

The <VALUE> expression is evaluated, and then each pattern attempts to match against it. If a pattern succeeds, it's associated FORMS are evaluated, in a context where the environment has been extended by the pattern's bindings. If a match fails, the next pattern is tried. If no patterns succeed, an error occurs.

Here is an example:

(match (list 1 2 3)
  ((list x y z) (+ x y z)))

The expression (list x y z) is the pattern in the above expression. Patterns are such that they resemble the code which creates the data structure in question, in this case a three element list. The pattern (list x y z) basically specifies that a match occurs when the input value is a three element list. When a match occurs, x is bound to the first element, y to the second and so on. Hence this form evaluates to 6.

Here is another example: summing a list:

(defun* dummy-sum (lst &optional (acc 0))
 (match lst
  (nil acc)
  ((cons hd tl)
   (dummy-sum tl (+ acc hd)))))

First we specify the pattern nil, which matches only nil. When the input is nil, we return the accumulator. Then we match against (cons hd tl) which matches a cons pair, binding hd to the car and tl to the cdr. We then recur, adding to the accumulator.

The pattern matching language is rich. There are patterns for matching against literals, applying functions to values, matching against arbitrary conditions, matching against structs.

Eg:

(defstruct a-struct f1 f2)

With this struct defined, the pattern:

(struct a-struct (f1 (? #'numberp x)) (f2 (? #'stringp y)))

Matches only a struct whose field f1 is a number, and whose field f2 is a string. When that is true, x and y are bound.

Extending Shadchen

The pattern matcher is user extensible using defpattern. Defpattern defines a function which receives the pattern's arguments, and returns a new pattern which effects the desired match. For instance, the struct pattern is defined thusly:

(defun cl-struct-prepend (s)
  (intern (format "cl-struct-%s" s)))

(defun make-cl-struct-accessor (struct-name slot) 
  (intern (format "%s-%s" struct-name slot)))


(defpattern struct (struct-name &rest fields)
  `(and
    (? #'vectorp)
    (? #'(lambda (x) (> (length x) 0)))
    (? #'(lambda (o)
           (eq (elt o 0) ',(cl-struct-prepend struct-name))))
    ,@(loop for f in fields collect
            `(funcall 
              #',(make-cl-struct-accessor struct-name (car f))
              ,(cadr f)))))

Note that the defpattern body must return a valid pattern in terms of previously defined patterns (or itself, patterns can be recursive). In this case we use the patterns and, ?, and funcall to create a new matcher.

Supported Patterns:

Shadchen supports the following patterns:

Shadchen supports the following built-in patterns.

<SYMBOL>

Matches anything, binding to that value in the body expressions.

<KEYwORD-LITERAL>

Matches only when the value is the same keyword.

<NUMBER-LITERAL>

Matches only when the value is the same number.

<STRING-LITERAL>

Matches only when the value is string= is the same string.

(CONS <PATTERN1> <PATTERN2>)

Matches any CONS cell, or NIL, then matches <PATTERN1> and <PATTERN2>, executing the body in a context where their matches are bound. If the match value is NIL, then each PATTERN matches against NIL.

(LIST <P1> ... <PN>)

Matches a list of length N, then matches each pattern <PN> to the elements of that list.

(LIST-REST <P1> ... <PN> <REST-PATTERN)

Matches - to elements in at list, as in the LIST pattern. The final <REST-PATTERN> is matched against the rest of the list.

(QUOTE DATUM)

Only succeeds when DATUM is EQUALP to the match-value. Binds no values.

 (AND <P1> .. <PN>)

Tests all <PN> against the same value, succeeding only when all patterns match, and binding all variables in all patterns.

 (? PREDICATE <PATTERN>)

Succeeds when (FUNCALL PREDICATE MATCH-VALUE) is true and when <PATTERN> matches the value. Body has the bindings of <PATTERN>.

 (FUNCALL FUN <PATTERN>)

Applies FUN to the match value, then matches <PATTERN> against the result.

 (BQ EXPR)

Matches as if by BACKQUOTE. If EXPR is an atom, then this is equivalent to QUOTE. If EXPR is a list, each element is matches as in QUOTE, unless it is an (UQ <PATTERN>) form, in which case it is matched as a pattern. Eg:

(match (list 1 2 3)
  ((BQ (1 (UQ x) 2)) x))

Will succeed, binding X to 2.

(match (list 10 2 20)
   ((BQ (1 (UQ x) 2)) x))

Will fail, since 10 and 1 don't match.

(values <P1> ... <PN>)

Will match multiple values produced by a (values ...) form.

(struct struct-name (field-name <P1>)
                    (field-name <P2>)
                    ...
                    (field-name <P3>))

Which matches when the input is a struct of type struct-name, whose fields match <P1> ... <PN>.

Conclusions

If you are an elisp hacker like me, now you don't have to envy those snooty Racket, ML and Haskell programmers. Happy Hacking!

(PS - the library is also available in Common Lisp, check my github).

(PPS - I love Racket, ML and Haskell programmers and they aren't at all snooty.


-1:-- Shadchen: A pattern Matching Library for Elisp (Post J.V. Toups (noreply@blogger.com))--L0--C0--January 19, 2012 07:52 PM

sachachua: Emacs: Telling external processes about terminal capabilities, and watching over other people’s shoulders

Justin Giancola (@elucid) wanted to use full-ack.el to search through his project files using the Ack tool, but Ack refused to run because it didn’t think his terminal had enough capabilities. A simple fix was to set the TERM variable with

(setenv "TERM" "xterm")

which told Ack that Emacs was fine with its output.

(Speaking of Ack integration – This being the Emacs world, there’s more than one way to do things. You might also want to check out ack-and-a-half.el, which is midway between ack.el and full-ack.el.)

It was interesting hanging out with someone else who used Emacs, and being able to share tips. I don’t run into many other Emacs geeks, but I sporadically hang out in the #emacs channel or browse Planet Emacsen to be inspired. It’s funny how many of the meetups I go to end up involving Emacs conversations. It’s like I have a big M-x banner hovering over my head. =) It’s awesome, actually!

Read the original or check out the comments on: Emacs: Telling external processes about terminal capabilities, and watching over other people’s shoulders (Sacha Chua's blog)

-1:-- Emacs: Telling external processes about terminal capabilities, and watching over other people’s shoulders (Post Sacha Chua)--L0--C0--January 19, 2012 03:06 AM

John Sullivan: Sent to the ACLU today

I was on the brink of mindlessly clicking through the ACLU action center as usual to send an email opposing SOPA. But then I read their boilerplate text, and ended up cancelling the letter to my rep and instead sending this quick note to the ACLU:

Your SOPA suggested letter text supports current copyright law, and also backhandedly supports PIPA (the Senate version of the bill).

This is far too weak of a position. As a donor, I ask you to take a stronger position that current copyright law unjustly restricts free speech, and that no further enforcement measures should be instituted until that fundamental problem is addressed.

At least take on BOTH of these bills strongly. Most of the significant Internet is blacked out today to oppose both bills -- why would you cede so much ground to copyright maximalists? We have the support to oppose and defeat both bills.

For reference, here was their text:

While I believe it's important to protect copyrighted material online, the language of the Stop Online Piracy Act (SOPA) is flawed and will lead to the blocking of lawful content.

Unlike the Senate version of the bill, SOPA eliminates the concept of sites 'dedicated to infringing activity' and enables law enforcement to target all sites that contain some infringing content -- no matter how trivial. The potential for impact on non-infringing content is much greater under SOPA than under other versions of this bill. Sites with user-generated content, like YouTube, Twitter, and Facebook, would be especially vulnerable, as one small piece of infringing content could lead to blocking the entire site.

Even though proposed changes would narrow the amount of lawful content impacted, the changes don't go far enough. It is still likely that search engines will end up blocking access to perfectly legal online content.

Congress should focus not just on the goal of protecting copyright owners, but also protecting the speech rights of consumers and providers who are reading and producing wholly non-infringing content. Congress must eliminate the collateral damage to protected non-infringing content. Only in that way will Congress truly achieve its goal of protecting authors while respecting the constitutional right to free speech.

Maybe I'm overreacting, but I dislike it when good organizations take weak positions unnecessarily. Usually this is not a problem with the ACLU, for me. It doesn't help that I keep seeing this meme everywhere in the anti-SOPA/PIPA conversation: "I agree we need to do something about piracy, but not this..."

I don't think we need to do anything to fix violations of an extraordinarily unjust law until the law itself is fixed. I don't find that to be a very radical position.

-1:-- Sent to the ACLU today (Post)--L0--C0--January 18, 2012 08:51 PM

Robert Adesam: Issue with VM and IMAP over SSL/stunnel

Problem -- after migrating from Mac to Mac @work I could no longer get emails via imap over ssl/stunnel, using VM 8.1.1 on Emacs 23.3 and stunnel 4.35 with openssl 1.0.0d. The *Messages* buffer stated
vm-imap-protocol-error: IMAP protocol error: "unexpected char (10)"
and the trace buffer of the IMAP over SSL session showed no errors.

With help from my friend, and some ssl/stunnel debugging, I quickly found the problem in the stunnel program, so I set out to revert to the version working on my old Mac, version 4.23. Finding instructions on the Macports wiki page on how to install older ports with subversion, I did
  • jump over the part on installing subversion as a fairly new version comes with Mac OS X 10.6.7,
  • locate and check out the revision, 36499, from the Macports repository containing the old version of stunnel,
    $ svn co -r 36499 https://svn.macports.org/repository/macports/trunk/dports/security/stunnel
  • install it with the port command.
    $ cd stunnel
    $ port install
Problem solved! Now I can once again get emails to VM using IMAP over SSL, stunnel 4.23 with openssl 1.0.0d.

There are quite a few tips on how to test a ssl connection, so I will leave it out and show how I debugged stunnel by
  • creating a stunnel.conf file with
    debug = 7
    output = stunnel.log
    to be appended to the VM generated config file,
  • setting vm-stunnel-program-additional-configuration-file in the VM init file, ~/.vm, to point to to stunnel.conf file, eg
    (setq vm-stunnel-program-additional-configuration-file "/PATH/TO/STUNNEL.CONF")
  • and reloading the VM init file.
Fetching emails now created stunnel.log in the mail folder. This file showed the error
LOG5[3793:140735082364064]: Error detected on socket (read) file descriptor: Socket operation on non-socket (38)
which I could find almost no information about, even less a solution to, so the quick fix was to revert back to an old working version of stunnel as described above.

Update: Since I wrote, but not published, the above text I found out in the stunnel changelog that some Mac OS X bugs have been fixed. Downloaded the latest version, 4.37, and compiled it without any hickups. Though, when now running stunnel it segfaults in addition to the stunnel socket error above...
Update: The above error has been fixed in version 4.52 of stunnel, excellent work from Michał Trojnara!
-1:-- Issue with VM and IMAP over SSL/stunnel (Post Robert Adesam (noreply@blogger.com))--L0--C0--January 18, 2012 01:49 PM

Alex Schroeder: SOPA Blackout Protest

I just saw Twitter CEO says SOPA blackout protest "silly" on BoingBoing. I wonder: Should I shut down Emacs Wiki for US residents? I’d have to do a quick geo location of the IP numbers before serving anything. That sucks.

kensanata
Do US #Emacs users require a reminder to fight #SOPA and # PIPA? I think Emacswiki will stay up for the USA. I doubt US Congress uses it.

I always felt that I was as safe as I can be running Emacs Wiki: I live in Switzerland, the server is hosted in Germany, the domain name registrar is French, the top-level .org domain is the only thing connecting it to the USA. But then I read US Can Extradite UK Student For Copyright Infringement, Despite Site Being Legal In The UK – and now I wonder about the worst case. Perhaps I should get myself a different domain name.

Actually, I think the main problem is that with all the scare mongering around copyright infringement and the astronomical punishments dealt out in the US, I have lost my confidence in their judicial system when it comes to copyright and patents. The most positive explanation for that is that I’m just misinterpreting all the bad news I’m reading online. My impression is formed by following @internetlaw, @privacylaw, @techdirt and @boingboing, following the occasional link. I end up reading Actual damages for single unauthorized download of software program held to be cost of single license fee (from $1,370,590 down to $4,200) and I wonder how much it cost the accused in time, energy and money to get this result. I would not want to fight this battle in court, even if I win.

Case in point: How USPTO's recklessness destroys business, innovation, and competition – a company produces something and years later a competitor is awarded a patent. The cost of going to court is prohibitive, and so they just give up.

Overprotective copyright and a judicial system that encourages statutory damages, patent offices unable to cope with new technology, a highly networked world making it easy to publish internationally with incompatible legal systems. It makes my head hurt!

Update: I decided to post a more personal message on EmacsWiki:2012-01-18.

Tags: RSS RSS RSS RSS RSS RSS

-1:-- SOPA Blackout Protest (Post)--L0--C0--January 17, 2012 09:53 AM

Mickey Petersen: PComplete: Context-Sensitive Completion in Emacs

In my What’s New In Emacs 24 series (part one, part two) I briefly mentioned that pcomplete, the programmable completion library featured prominently in Eshell, now supports M-x shell out of the box. That’s great news for shell mode fans as the completion mechanism adds a lot of nifty functionality to a mode that lacks the native completion provided by underlying the shell itself.

The most amazing thing about the completion mechanism is that it has been in Emacs for ages but never made much of a public appearance and has gone virtually unnoticed due to its limited use in Emacs. In fact, I think it’s only used in EShell, ERC, Org Mode and now, finally, Shell Mode.

Programmable, Context-Sensitive Completion

To use pcomplete you won’t have to do anything, because as of Emacs 24 it is now supported automatically when you launch a new shell session. Emacs ships with a handful of pcomplete functions that enhance the otherwise drab filename completion with context-sensitive completion similar to what you can do with bash/zsh completion. Of particular note is the scp, ssh, mount, umount and make support.

The following table lists the commands supported by shell mode (or indeed any mode that supports pcomplete, including Eshell.)

Command Notes
bzip2 Completes arguments and lists only bzipped files.
cd Completes directories.
chgrp Completes list of known groups on the system.
chown Completes user and group perms, but only if you use user.group.
cvs Completes commands and parameter options and cvs entries and modules.
gdb Completes only directories or files with eXecute permission.
gzip Completes arguments and lists only gzipped files.
kill Lists signals if completed with just a -, otherwise it completes all system PIDs.
make Completes arguments and valid makefiles in the directory; if a valid makefile is completed with make -f FILE a list of rule names from the file itself are completed.
mount Completes arguments and valid filesystem types if completed with mount -t TYPE.
pushd Identical to cd.
rm Completes arguments and filenames and directories.
rmdir Completes directories.
rpm Very sophisticated completion mechanism for most of rpm, the Redhat Package Manager. Context-sensitive completion for almost all commands, including package lookup.
scp Completes arguments, SSH known hosts and remote file lookup (using TRAMP) if the format is scp host:/.
ssh Completes arguments and SSH known hosts.
tar Completes arguments, including context-sensitive completion for POSIX arguments, and file name completion.
time Completes directories and files with eXecutable permission.
umount Completes arguments, mounted directories and filesystem types (like mount)
which Supposed to provide simple filename completion of all known binaries (wouldn’t be useful otherwise!) but appears to not work right.
xargs Completes directories and files with eXecutable permission.

Custom Completion

It goes without saying that a completion library called programmable completion is, well, programmable.

Adding simple parameter completion is an easy job but anything more than that and it gets hairy as, not surprisingly, this library is virtually undocumented (though an optimist would say the source is all the documentation you need…)

I’ll demonstrate how to add rudimentary support for git.

The first thing we need to do is establish the order in which parameters must be given; for git, it’s somewhat consistent: git [options] <command> [<args>]

For now I’ll stick to the commands as that’s what people use the most anyway. The commands, in list form, are:

(defconst pcmpl-git-commands
  '("add" "bisect" "branch" "checkout" "clone"
    "commit" "diff" "fetch" "grep"
    "init" "log" "merge" "mv" "pull" "push" "rebase"
    "reset" "rm" "show" "status" "tag" )
  "List of `git' commands")

The syntax for pcomplete is rather clever: it will use dynamic dispatch to resolve the elisp function provided it is named a certain way. All commands are named pcomplete/COMMAND or pcomplete/MAJOR-MODE/COMMAND. Provided you follow that naming scheme your command will automagically work.

Next, we need to present a list of valid commands — in this case the ones in pcmpl-git-commands, but it could be any form — to the command pcomplete-here.

(defun pcomplete/git ()
  "Completion for `git'"
  (pcomplete-here* pcmpl-git-commands))

Now when you try to tab-complete the first argument to git it will list our commands. Sweet.

Let’s extend it further by adding support for the add and rm commands. I want the aforementioned commands to provide the standard filename/filepath completion if, and only if, the command is add or rm.

This is surprisingly easy to do using pcomplete-match, a function that asserts a certain regexp matches a particular function argument index. Note that the call to pcomplete-here is in a while loop; this is so you can complete as many files as you like, one after another. One advantage of pcomplete-here is that it won’t display files you have already completed earlier in the argument trail — that’s very useful for a command like add.

(defun pcomplete/git ()
  "Completion for `git'"
  ;; Completion for the command argument.
  (pcomplete-here* pcmpl-git-commands)
 
  ;; complete files/dirs forever if the command is `add' or `rm'.
  (if (pcomplete-match (regexp-opt '("add" "rm")) 1)
      (while (pcomplete-here (pcomplete-entries)))))

Ok, that was easy. Now let’s make it a bit more dynamic by extending our code to support the git checkout command so it will complete the list of branches available to us locally.

To do this we need a helper function that takes the output of a call to shell-command and maps it to an internal elisp list. This is easily done with some quick hackery.

The variable pcmpl-git-ref-list-cmd holds the shell command we want Emacs to run for us. It gets every ref there is and we then filter by sub-type (heads, tags, etc.) later. The function pcmpl-git-get-refs takes one argument, type, which is the ref type to filter by.

(defvar pcmpl-git-ref-list-cmd "git for-each-ref refs/ --format='%(refname)'"
  "The `git' command to run to get a list of refs")
 
(defun pcmpl-git-get-refs (type)
  "Return a list of `git' refs filtered by TYPE"
  (with-temp-buffer
    (insert (shell-command-to-string pcmpl-git-ref-list-cmd))
    (goto-char (point-min))
    (let ((ref-list))
      (while (re-search-forward (concat "^refs/" type "/\\(.+\\)$") nil t)
        (add-to-list 'ref-list (match-string 1)))
      ref-list)))

And finally, we put it all together. To keep the code clean I’ve switched to using a cond form for readability.

(defconst pcmpl-git-commands
  '("add" "bisect" "branch" "checkout" "clone"
    "commit" "diff" "fetch" "grep"
    "init" "log" "merge" "mv" "pull" "push" "rebase"
    "reset" "rm" "show" "status" "tag" )
  "List of `git' commands")
 
(defvar pcmpl-git-ref-list-cmd "git for-each-ref refs/ --format='%(refname)'"
  "The `git' command to run to get a list of refs")
 
(defun pcmpl-git-get-refs (type)
  "Return a list of `git' refs filtered by TYPE"
  (with-temp-buffer
    (insert (shell-command-to-string pcmpl-git-ref-list-cmd))
    (goto-char (point-min))
    (let ((ref-list))
      (while (re-search-forward (concat "^refs/" type "/\\(.+\\)$") nil t)
        (add-to-list 'ref-list (match-string 1)))
      ref-list)))
 
(defun pcomplete/git ()
  "Completion for `git'"
  ;; Completion for the command argument.
  (pcomplete-here* pcmpl-git-commands)  
  ;; complete files/dirs forever if the command is `add' or `rm'
  (cond
   ((pcomplete-match (regexp-opt '("add" "rm")) 1)
    (while (pcomplete-here (pcomplete-entries))))
   ;; provide branch completion for the command `checkout'.
   ((pcomplete-match "checkout" 1)
    (pcomplete-here* (pcmpl-git-get-refs "heads")))))

And that’s that. A simple completion mechanism for git. Put this in your .emacs or init file and you’re done.

Share

-1:-- PComplete: Context-Sensitive Completion in Emacs (Post mickey)--L0--C0--January 16, 2012 06:40 PM

Bryan Murdock: What Is So Wrong With Mercurial's Named Branches?

I just installed the very latest version of mercurial, 2.0.2. It added a new little feature that warns you when you create a branch. Huh? This is what it looks like:

$ hg branch foo
marked working directory as branch foo
(branches are permanent and global, did you want a bookmark?)

Really? Have we let the git advocates push us this far? Do we really need to start discouraging named branches?

I googled around to see if I could find where the self-hate for mercurial's named branches is coming from and I found things like this, "it is almost never a good idea to use this facility for short-term branching, since branches created this way are inherently 'eternal'." (those quotes around eternal are good, actually, but you didn't explain why they should be there), and this, "you can never really delete branches (since that would mean altering older commits)." (editing history, oh noes!), and others like this. And these were all written by apparent mercurial supporters! I understand when a git developer writes misinformation about mercurial and uses it to try and make git look better (that's only human), but we mercurial users should know not to listen to it!

Here's what I think is going wrong. Git users love flexibility. The love it so much that they even include modifying their local repository history right into their standard workflow. git rebase is a core command. From what I can gather, even though mercurial now (as of years ago, actually) has powerful rebase and patch queue extensions, mercurial users still get the heebie-jeebies when they think about modifying repository history. This is where the git envy comes from. You see, git useres can alter their branch names, or even delete branch names without using scary rebase. Fact is, though, git could adopt mercurial-style named branches and git users would rebase them away or rename them with rebase willy-nilly just like they do with everything else that they deem needs editing in their history. The fact that git users can rename or delete their branches without using rebase is almost completely incidental. If you allow the use of rebase or patch queues, mercurial named branches are not any more permanent than any other changeset in the repository history. Mercurial bookmarks allow mercurial users flexibility around branch names without needing to resort to scary history editing extensions, and that makes us happy, but I don't think that we should talk down mercurial named branches. There are times when you want the branch name associated with a commit to be just as "permanent" as the commit is. Let us do that without dumb warnings that make named branches sound like a bad idea.

The only other argument people may have against mercurial's named branches is the possibility of name collisions. As if that's something that's really hard to deal with. Anyone who has written a fair amount of C code (I'm looking at you, git developers) knows how to prefix a name to get poor-man's namespaces. Alternatively, many projects require an issue tracker number in a feature-branch or bugfix-branch name. Name collision problem solved.

In conclusion, mercurial named branches are fine. Use them more. Use rebase and/or patch queues[1] to rename or delete the branches when necessary. If that really bothers you, you have bookmarks now, but don't go all git-apologetic on named branches. Mercurial is every bit as awesome as git.

1. Before you push to a publicly accesible repository, of course. Ask a git user why that's important.

-1:-- What Is So Wrong With Mercurial's Named Branches? (Post Bryan (noreply@blogger.com))--L0--C0--January 16, 2012 06:10 PM

John Sullivan: At FOSDEM in February

I will be helping to represent the FSF at FOSDEM next month in Brussels. I'm speaking in the Legal Issues Devroom on Saturday 2012-02-04. The presentation is called "Is copyleft being framed?":

This short talk will address the following questions, to inspire discussion and contemplation about how we frame descriptions of the state of licensing in free software.

  • Numbers are increasingly being cited to show that the use of copyleft licenses, specifically the GPL, is declining. What do these numbers actually show, who is propagating them, and why? What do or might other numbers show?
  • Is the "percentage of free software projects which use copyleft licenses" a useful way to judge the success of copyleft? Does an increase in the percentage of projects using non-copyleft permissive licenses indicate a failure of copyleft?
  • As a small related case study, what role have the licensing terms of popular mobile application stores played in this debate, and how have those terms changed the frame of the discussion?

Let me know if you'll be there too!

-1:-- At FOSDEM in February (Post)--L0--C0--January 15, 2012 11:19 PM

Michael Lockhart: Build and install Emacs24 on Debian squeeze

Hacking in Debian is so easy (one of the reasons I switched). Take, for instance, building Emacs. This is such a piece of cake compared to the weird hoops you have to go through to get all the build dependencies on other platforms. It’s something I never tried before, simply because it was too daunting [...]
-1:-- Build and install Emacs24 on Debian squeeze (Post Mike (sinewalker))--L0--C0--January 15, 2012 12:57 PM

Alex Bennée: Getting organised

What with becoming a parent and getting promoted I suddenly find myself needing to become a lot more organised. Although I’ve been using org-mode for a bit I need to get a lot more organised with it.

Previously I had two sets of org notes. My personal set where sitting on my server which I could access via the terminal. I generally accessed this at home on the odd occasion when I was doing things like the annual round of insurance quote gathering. The second set was a fairly simple time sheet type affair that I was using at work to keep a vague track of where all my time was spent. The big missing part of this is when I’m on the move.

I’ve just recently upgraded my phone to the latest Galaxy Nexus which is a fine Google enabled device. I make no apologies for using Google’s calendering and shared document services. They work very well and importantly allow me to share things with my wife who doesn’t quite share my desire to run everything from a text editor. However for my personal task lists on the move and remembering what’s coming up at work it doesn’t quite cut it. Besides I like org-mode and I’d heard about MobileOrg so I endeavoured to set it up.

MobileOrg has been around some time for the iPhone but the mechanisms it uses for integrating with org-mode are fairly well documented. As a result there is a couple of Android implementations for it. Matthew Jone’s mobileorg-android was the first version I tried.

The original sync method for MobileOrg was to use a service like Dropbox to sync files. Given the history of Dropbox’s security I wasn’t about to move my files into the proprietary cloud. The alternative is to enable WebDAV on my web-server and therefor enable two way communication via HTTP. It was a little concerning to see self-signed SSL wasn’t supported as this does open up a potential attack vector on my machine. I’ve mitigated it a little by using digest authentication instead of basic-auth but I’d still prefer to be conducting these read-write operations over something more secure.

Initial results were a little underwhelming. After some messing around with the format of org-links I eventually got a basic outline summary up. Unfortunately I can’t seem to sync notes created on my phone to the server. This seems to be a Apache problem which I shall have to dig into later.

After perusing the market some more I noticed there is a new project in town. Konstantin’s MobileOrgNG was forked some time ago from Matthew’s code and on installing I found it looked an awful lot better. I’ve still be unable to post any locally added notes (due to previously mentioned Apache config issues). However it’s presentation is a lot slicker and it shows a lot of potential for being a good MobileOrg client.

I’m now stuck with a classic open source fork dilemma. The code bases look to have diverged enough that these two projects are essential going their own way. Looking at the two impact graphs it looks like they diverged around August 2011 and since then MobileOrgNG looks pretty much like a solo effort albeit with an impressive commit rate of new features.

So the questions for my readers. Which code base should I jump on? Has anyone got experience with the two different code bases and the reason they split? Are there any other Android clients for org-mode I should be looking at?

-1:-- Getting organised (Post Alex)--L0--C0--January 13, 2012 10:38 AM

Tassilo Horn: Using Clojure’s core.logic with custom data structures

With a lot of help from Ambrose, I managed to make Clojure’s core.logic library work with my custom Java data structures. In this posting, I’ll explain the code.  I assume that you are already familiar with Clojure in general, and you know core.logic and relational programming at least from a user’s point of view.

Ok, so let’s start.  My custom data structures are TGraphs that we develop here at our institute.  You don’t need to know more than that a graph consists of vertices, and vertices can be connected by edges.  Furthermore, both vertices and edges may have attributes.  When you use such a graph, the graph itself, every vertex, and every edge is one Java object in your memory that implements the interface Graph, Vertex, and Edge, respectively.

I wrote a nice functional Clojure API for working with TGraphs (funtg on clojars; don’t use it for serious purposes, I’m constantly changing things without thinking about compatibility at all).  So probably, if you are reading this, you are in the same situation that I was in: You have a cool data structure, you have a cool API for it, and you are totally curious what you could do with core.logic on your data structure.  So how do I get core.logic to work with my stuff???

The answer is: you have to write relations that use your existing API to access your data structure.  The topic of this posting is mainly how to doing that in a way that core.logic wants.  So let’s start with the namespace declaration for the code:

(ns extend.example
  (:refer-clojure :exclude [==])
  (:use [clojure.core.logic])
  ;; The following two are my functional API
  (:require [de.uni-koblenz.ist.funtg.core :as core])
  (:require [de.uni-koblenz.ist.funtg.funql :as funql]))


Nothing special here, except that you can see that I require my functional TGraph API using prefixes.  So when you see core/foo or funql/bar in the following, you know that I’m calling my functional API there.  As next, I added some helper functions for testing if a logic variable is fresh or ground.  Ignore the comment about being walk-ed for now.

(defn fresh?
  "Returns true, if `x' is fresh.
  `x' must have been `walk'ed before!"
  [x]
  (lvar? x))

(defn ground?
  "Returns true, if `x' is ground.
  `x' must have been `walk'ed before!"
  [x]
  (not (lvar? x)))


Then, I’ll defined a constant +graph+ that holds some example TGraph (some route map like graph).  I decided to keep the graph as a var of the namespace instead of making it a parameter of relations, because my API has no way to enumerate all graphs that happen to be in memory.  If the graph was a parameter of relations, I couldn’t be fully relational, e.g., giving only fresh logic variables to my relations would have to error.

(def +graph+ (core/load-graph "/home/horn/Repos/uni/funtg/test/greqltestgraph.tg"))


Now we’ll come to the actual first relation.  vertexo is a relation where v is a vertex in the graph +graph+.

(defn vertexo
  "A relation where `v' is a vertex."
  [v]
  (fn [a]                                 ;; (1)
    (let [gv (walk a v)]
      (if (fresh? gv)
        (to-stream                        ;; (2)
         (->> (map #(unify a v %)
                   (funql/vseq +graph+))
              (remove not)))
         (if (.containsVertex +graph+ gv)
           a
          (fail a))))))


Basically, the stuff marked with (*) is what’s important. (1) A relation must return a function which gets a so-called substitution a. You can think of it as something like an environment map which knows what logical variables are ground, and if so, what value they have. (walk a v) gets you the value of the variable (or value) v. If v is ground, then you get a value back. If v is fresh, you get a logical variable back. So now the functions fresh? and ground? above make sense, right?

The other important part (2) is that the function returned by a relation has to return a substitution again: A relation returns a function that gets a substitution and returns a substitution. to-stream turns a seq into a choice, which essentially say which possible values are allowed for the relation’s parameters. We declare such a possible binding using unify. funql/vseq returns the lazy seq of the graph’s vertices, each of which may be unified with the parameter v in the substitution a. If v was ground, then it could only be unified with the vertex it is already bound to. Because of that, it’s a good idea to filter out false values in the sequence before giving it to to-stream.

If I had put (2) directly into (1), it would work exactly the same. The additional code is for performance purposes. If v is already ground, there’s no reason to try to unify it with every vertex in the graph just to check if it is contained. Instead, a simple check (via the Java API) to see if that vertex is in the graph is enough. If it’s contained, then the substitution a is correct, so I return it “unchanged” (quotes, because of course we don’t mutate in Clojure). Else, the vertex is not in +graph+, so the binding is invalid and we fail.

That’s it. Now let’s turn to edges which are accessed with a relation of 3 parameters denoting the edge itself, its start vertex, and its end vertex.

(defn edgeo
  "A relation where `e' is an edge from `alpha' to `omega'."
  [e alpha omega]
  (fn [a]
    (let [ge     (walk a e)
          galpha (walk a alpha)
          gomega (walk a omega)]
      (cond
        (ground? ge) (unify a [alpha omega]
                            [(core/alpha ge) (core/omega ge)])
        (ground? galpha) (to-stream
                           (->> (map #(unify a [e omega] [% (core/omega %)])
                                     (funql/iseq galpha nil :out))
                                (remove not)))
        (ground? gomega) (to-stream
                           (->> (map #(unify a [e alpha] [% (core/alpha %)])
                                    (funql/iseq gomega nil :in))
                                (remove not)))
        :else (to-stream
                (->> (for [edge (funql/eseq +graph+)]
                       (unify a [e alpha omega]
                              [edge (core/alpha edge) (core/omega edge)]))
                     (remove not)))))))


Again, basically the relation would work fine if we delete everything except the expression of the :else clause.  That unifies all edges in the graph including their start and end vertices with the parameters of the relation.  The three first clauses of the cond are for performance only.  The first says, if an edge is already given, then we only check the start and end vertex, which is a constant time operation.  The second and third clause say, if either the start or end vertex are already given, then we don’t need to unify all edges in the graph with the parameters but only the edges incident to the given vertex (eseq vs. iseq), which is again much faster.

The last relation I’ll show is concerned with attributes.

(defn valueo
  "A relation where `ae' has value `val' for its `at' attribute."
  [ae at val]
  (fn [a]
    (let [gae (walk a ae)
          gat (walk a at)
          gval (walk a val)]
      (cond
        (and (ground? gae)
             (ground? gat)) (or (unify a [ae at val]
                                       [gae gat (core/value gae gat)]))
        (ground? gae) (to-stream
                        (->> (for [attr (seq (.getAttributeList
                                               (core/attributed-element-class gae)))
                                   :let [an (keyword (.getName attr))]]
                                (unify a [ae at val]
                                      [gae an (core/value gae an)]))
                             (remove not)))
        :else (to-stream
                (->> (for [elem (concat (funql/vseq +graph+)
                                        (funql/eseq +graph+))
                           attr (seq (.getAttributeList
                                       (core/attributed-element-class elem)))
                           :let [an (keyword (.getName attr))]]
                        (unify a [ae at val]
                               [elem an (core/value elem an)]))
                     (remove not)))))))


Again, only the :else part is neccessary.  I unify every vertex and every edge together with every attribute that is defined for them with the given parameters.  Clearly, that’s quite some effort.  The first clause of the cond simply looks up the attribute value if the element and the attribute name are already given.  The second clause deals with the case when at least the graph element is given, in which case only all its attribute/value pairs have to be unified.

So here are some example applications.

What are the 3 first vertices in the graph?

(run 3 [q]
  (vertexo q))
;=> (#<v1: localities.Village>
     #<v2: localities.Village>
     #<v3: localities.Town>)


Is this a vertex of the graph?

(let [v1 (core/vertex +graph+ 1)]
  (run* [q]
    (vertexo v1)))
;=> (_.0)     ; succeeded, so yes, it's a vertex of +graph+


What are the first 3 edges of the graph?

(run 3 [q]
  (fresh [a o]
    (edgeo q a o)))
;=> (#<e1: connections.Footpath>
     #<e2: connections.Footpath>
     #<e3: connections.Footpath>)


What edges end at the vertex v1?

(let [v1 (core/vertex +graph+ 1)]
  (run* [q]
    (fresh [o]
      (edgeo q o v1))))
;=> (#<e-22: localities.ContainsLocality>)


Which attribute of what element has the value 251?

(run* [q]
  (fresh [e a]
    (valueo e a 251)
    (== q [e a])))
;=> ([#<v1: localities.Village> :inhabitants])


So that village has 251 inhabitants.  Pretty small.  What’s the name of that village?

(run* [q]
  (fresh [e a]
    (valueo e a 251)
    (valueo e :name q)))
;=> ("Kammerforst")


Ah, it’s Kammerforst.  Oh, wikipedia says its population has increased to 253. ;-)

Ok, that’s it.  I hope this helps you to make your custom data structures work with core.logic. Have fun!


-1:-- Using Clojure’s core.logic with custom data structures (Post Tassilo Horn)--L0--C0--January 06, 2012 09:37 PM

Tom Tromey: Emacs and Common Lisp

Recently I’ve been thinking about how to rebase Emacs on Common Lisp.

First, why rebase?  Performance is the biggest reason.  Emacs Lisp is a very basic lisp implementation.  It has a primitive garbage collector and basic execution model, and due to how it is written, it is quite hard to improve this in place.

Seccond, why Common Lisp?  Two reasons: first, Emacs Lisp resembles Common Lisp in many ways; elisp is like CL’s baby brother.  Second, all of the hard problems in Lisp execution have already been solved excellently by existing, free-software CL implementations.  In particular, the good CL implementations have much better garbage collectors, native compilation, threads, and FFI; we could expose the latter two to elisp in a straightforward way.

By “rebase” I mean something quite ambitious — rewrite the C source of Emacs into Common Lisp.  I think this can largely be automated via a GCC plugin (e.g., written using David Malcolm’s Python plugin).  Full automation would let the CL port be just another way to build Emacs, following the upstream development directly until all the Emacs maintainers can be convinced to drop C entirely (cough, cough).

Part of the rewrite would be dropping code that can be shared with CL.  For example, we don’t need to translate the Emacs implementation of “cons“, we can just use the CL one.

Some CL glue would be needed to make this all work properly.  These days it can’t be quite as small as elisp.lisp, but it still would not need to be very big.  The trickiest problem is dealing with buffer-local variables; but I think that can be done by judicious use of define-symbol-macro in the elisp reader.

Emacs might be the only program in the world that would see a performance improvement from rewriting in CL :-) .  The reason for this is simple: Emacs’ performance is largely related to how well it executes lisp code, and how well the GC works.

-1:-- Emacs and Common Lisp (Post tom)--L0--C0--January 05, 2012 05:40 PM

Aaron Hawley: Spring cleaning

After 50 years as an academic economist, spending it deconstructing the neo-classical economics of Alfred Marshall and his "Cambridge School" -- of which she was a member early in her career -- and producing work deserving of a Nobel Prize, Joan Robinson would instead see the system resurrected in the US -- notably by the "Chicago School" of Milton Friedman and Fred Hayek. In 1980, she commented on the poverty of orthodox economics and sketched a solution.

After the Second World War, the baton of leadership in teaching economics, along with leadership in the capitalist world, passed to the USA. Instead of meeting the challenge of the Keynesian revolution head on, the profession in the USA split the subject into two parts, macro and micro. In the macro section it was permissible to contemplate fluctuations in employment and even to hint at remedies for a deficiency in effective demand, while micro theory returned to the analysis of equilibrium established by the free play of market forces. Keynesian ideas were allowed a certain sphere of operation while the central doctrine was safely walled off from them.[...]

The whole subject [of inequality] is so embarrassing that in fact it is scarcely mentioned. There is no treatment at all of the determination of the distribution of income in orthodox teaching, and precious little about its consequences. What to the general public appears one of the most interesting of all questions in economics is simply left out of the syllabus.

In its general influence on educated public opinion, orthodox teaching has been not merely feeble and confused but positively pernicious. It gives support to the view that expenditure by a government that is beneficial to the inhabitants of its territory is 'socialism' and must be prevented at all costs. This reconciles an otherwise more or less sane and benevolent public opinion to the arms race which seems to be dragging us all to destruction. But that is another story.

It seems to me that the whole complex of theories and models in the textbooks is in need of a thorough spring cleaning. We should throw out all self-contradictory propositions, unmeasurable quantities and indefinable concepts and reconstruct a logical basis for analysis with what, if anything, remains.

From the essay "The theory of normal prices and reconstruction of economic theory" published in Issues in contemporary macroeconomics and distribution edited by George R. Feiwel.

-1:-- Spring cleaning (Post)--L0--C0--January 05, 2012 05:11 PM

Tim Bielawa: Excluding in the Emacs file completion buffer

I realized tonight While hacking on Taboot that Emacs was showing particularly uninteresting files in the completion buffer when opening a file. For example, scripts.pyc.

I assumed that there was a facility for customizing this, so I did some research on the topic. Trying emacs filter possible completions and emacs filter list of completions both came up with the same documentation. The GNU documentation describes a customization facility similar to the filtering I sought after via the completion-ignored-extensions variable (part of the Dired group). However, it stops a bit short of what I was looking for. Quote from describe-variable for the variable (emphasis added):

Completion ignores file names ending in any string in this list. It does not ignore them if all possible completions end in one of these strings or when displaying a list of completions.

I went through some more search results and sure enough, stackoverflow provides again. In that response the author provided a fantastic defadvice which did exactly what I was looking for. By default it uses the value of your existing completion-ignored-extensions variable.

-1:-- Excluding in the Emacs file completion buffer (Post Tim Bielawa)--L0--C0--January 04, 2012 03:29 AM

Gabriel Saldaña: Easy CSS editing with Emacs

rainbow-mode

Editing CSS in Emacs is very easy since the standard CSS mode comes included by default. But developer Julien Danjou created this nice minor mode called rainbow-mode which will display the color of the code as the background of the code’s text. It is very useful to immediately see the colors right there in the style sheet instead of trying to remember each code and then test in the browser window.

One of the problems I had was when opening any CSS file, it would open by default css-mode, but I had to manually load rainbow-mode every time. The elisp function auto-mode-alist is used to detect a file type by its name and running a function associated with it, generally the function to enable a major mode to edit that type of file. For minor modes I couldn’t find anything that would allow me to launch them without inhibiting the mayor mode’s startup.

So since auto-mode-alist takes a regular expression for the file type and only one function as its arguments, I wrote a function that will run both and use that as the second argument to execute.

;; CSS and Rainbow modes 
(defun all-css-modes() (css-mode) (rainbow-mode)) 

;; Load both major and minor modes in one call based on file type 
(add-to-list 'auto-mode-alist '("\\.css$" . all-css-modes)) 

Hope you find it useful and you like the combination of css-mode and rainbow-mode as much as I do.

Identi.caTwitterFacebookGoogle ReaderRedditShare/Bookmark

Related posts:

  1. Animate your webpage fast and easy with Facebook Animation Library
  2. Easy PHP code test development with SimpleTest unit testing framework
  3. PHP syntax check as you type with Emacs

-1:-- Easy CSS editing with Emacs (Post Gabriel Saldaña)--L0--C0--January 04, 2012 12:18 AM

Julien Danjou: Google Calendar notifications using pynotify

I use Google Calendar to manage my calendars, and I really missed something to warn me whenever I have an appointment with an alert set.

So here is an example of a Python program to do such a thing. It is written using the Google Data APIs Python client library and pynotify.

I'll detail the code here, so you can build your own and adapt it to your needs.

First, we need to import GTK+ and pynotify, and initialize it.

import gtk
import pynotify
pynotify.init(sys.argv[0])

Then, we need to import gdata Calendar API and connect to the calendar. I'll use the simple email/password way to login, which is clearly not the best, but it's also the simplest. Feel free to use OAuth 2.0. :-)

calendar_service = gdata.calendar.service.CalendarService()
calendar_service.email = 'mygooglelogin'
calendar_service.password = 'mygooglepassword'
calendar_service.ProgrammaticLogin()

Now we're ready to request stuff and notify! First, request the events from the default calendar.

feed = calendar_service.GetCalendarEventFeed()

Now we can iterate over feed and do various checks.

for event in feed.entry:
    # If the event status is not confirmed, go to the next event.
    if event.event_status.value != "CONFIRMED":
        continue
    # Now iterate over all the event dates (usually it has one)
    for when in event.when:
        # Parse start and end time
        try:
            start_time = datetime.datetime.strptime(when.start_time.split(".")[0], "%Y-%m-%dT%H:%M:%S")
            end_time = datetime.datetime.strptime(when.end_time.split(".")[0], "%Y-%m-%dT%H:%M:%S")
        except ValueError:
            # ValueError happens on parsing error. Parsing errors
            # usually happen for "all day" events since they have
            # not time, but we do not care about this events.
            continue
        now = datetime.datetime.now()
        # Check that the event hasn't already ended
        if end_time > now:
            # Check each alert
            for reminder in when.reminder:
                # We handle only reminders with method "alert"
                # and whose start time minus the reminder delay has passed
                if reminder.method == "alert" \
                        and start_time - datetime.timedelta(0, 60 * int(reminder.minutes)) < now:
                    # Build the notification
                    notification = pynotify.Notification(summary=event.title.text,
                                                         message=event.content.text)
                    # Set an icon from the GTK+ stock icons
                    notification.set_icon_from_pixbuf(gtk.Label().render_icon(gtk.STOCK_DIALOG_INFO,
                                                                              gtk.ICON_SIZE_LARGE_TOOLBAR))
                    notification.set_timeout(0)
                    # Show the notification
                    notification.show()

Running this program, you should see a notification if an appointment has an alert to be raised at that time.

This should be enough to start to build something.

If you don't want to program this into Python, you might want to take a look at gcalcli.

-1:-- Google Calendar notifications using pynotify (Post Julien Danjou)--L0--C0--January 03, 2012 06:55 PM

Phil Hagelberg: in which local hacking locations are surveyed

I'm lucky to have the chance to do my job remotely from wherever I like. Half the time I work out of my code lab, which is a converted shed in my back yard. But I venture out fairly frequently to local coffee shops. Here are a few of my favourites. I should mention that I'm a big fan of single-origin pour-over brews, so the list is biased in favour of places which serve that well rather than the more traditional espresso drinks. All these have at least one location in North Seattle.

Neptune

I'm here a lot because it's the only one on this list I don't need to get on the freeway for. The decor is a bit sparse, but they're quite friendly here and serve a mean pour-over. They've been known to even serve syphon-brewed coffee, which is always a treat to watch when they fire up the bunsen burner. The proprietor also runs tehcoffee.com, a (Heroku-hosted) site for competition-level baristas can rank and review others. The Greenwood neighborhood is great too; lots of lunch options and bookstores to browse. Bonus fact: Allie, the inventor of the mythical Alot beast has a blend here named after her.

milstead views

Milstead & Co.

This one has only opened relatively recently, but it's made a splash for a number of things, not the least of which is the spectacular waterfront view from under the Aurora bridge. The selection here is excellent; this is the only place on this list that serves beans from multiple roasters, and they offer plenty of variety in brewing methods. The interior is spacious with high ceilings; it's very inviting. Mr. Milstead himself is usually around, and his excitement about his craft is infectious and obvious once you get him talking. I'd be here all the time if it weren't the furthest (south) from where I live.

Zoka

This one is my go-to place. I often run into people I know here, (and sometimes people I don't), and we hold the Seattle Clojure group meetings here as well. The University District location in particular works well for meetings just because it's so spacious; I don't think I've ever seen a larger coffee shop. It's a popular place for students to study, so it's pretty quiet in the back. It can be crowded at times though, probably based on the school schedule. They've got a great selection sourced from all over the world that rotates every so often. It's always fun to read their blog posts about traveling to visit the growers. The "Zoka bars" they serve here are a ridiculously rich treat. The decor here is very warm and comfortable with wood paneling everywhere.

trabant

Trabant

I don't come here often because the parking situation is awful, but if you are in the area (or taking the bus), definitely check out Trabant. They've got good chai, but the thing that keeps bringing me back here is the Clover machine. This contraption is capable of extracting rich flavours out of a bean like nothing else. Unfortunately Starbucks purchased the company that sold them, so there aren't very many places with Clovers that offer good beans. (As the owner of Trabant said about the acquisition, "wearing Air Jordans doesn't make you play like Michael Jordan.") Anyway, the downtown Trabant is very spare, minimalist, and quiet, while the one in the University district (pictured) is bustling and quirky.

Honorable Mentions

Vivace
I'm of the opinion that Vivace has the best espresso in Seattle. It's too far for me to visit regularly, but members of the famed Seattle Ruby Brigade can often be found working here in the afternoon.
Seattle Coffee Works
I've only been here a couple times, but I was floored by their Yirgacheffe both times. They serve their pour-overs at a separate "slow bar" where the baristas are happy to geek out over their creations if you show interest. Again, this one's too far away (Pike St.) to make me a regular.
Green Bean
This one is actually a non-profit which supports a number of other non-profits on a rotating basis. The staff here are really friendly. I like to come here early and get breakfast with my family since they've got a kids' corner.
Chocolati
I don't even come here for their coffee, but their hot chocolate is superb. They've also got great truffles. The Greenwood location is a converted house that offers plenty of space to work, while the Greenlake location is a lot smaller but has nice views of the water.

Enjoy!

-1:-- in which local hacking locations are surveyed (Post Phil Hagelberg)--L0--C0--December 31, 2011 02:25 AM