Grant Rettke: Hide uninteresting files in dired-mode

Via here:

I just found a neat trick today i.e hiding uninteresting(temporary files like backup or autosave files, all files of a particular extension or a particular set of files which match a regexp) files in dired-mode using dired-x. Here’s how I did it in my .emacs :-

(use-package dired-x
  :config
  (progn
(setq dired-omit-verbose nil)
;; toggle `dired-omit-mode' with C-x M-o
(add-hook 'dired-mode-hook #'dired-omit-mode)
(setq dired-omit-files
      (concat dired-omit-files "\\|^.DS_STORE$\\|^.projectile$"))))

There is also dired-omit-extensions which can be used to hide all files of a particular extension.

-1:-- Hide uninteresting files in dired-mode (Post Grant)--L0--C0--September 24, 2016 06:47 PM

Irreal: Kill This Buffer

[Editorial Note: Sorry about the lousy formatting. Org2blog is misbehaving again so I had to paste the HTML into the WordPress editor.]

Ben Maughan over at Pragmatic Emacs has a really nice tip. It's one of
those things that you (or at least I) don't think about but once you
see the tip, you think, “That's just what I need.” The idea is to kill
the current buffer without asking
.

Maughan asks how many times you've called kill-buffer via
Ctrl+x k】and wanted to kill some buffer other than the one you're in. I can't
ever remember doing that. Maughan provides a one line fix to your
init.el that will just delete the current buffer without asking.
Perfect.

If you think you'll sometimes want the old behavior and don't want to
remember kill-buffer, it's trivial to add a bit of Elisp that
calls kill-this-buffer unless the universal argument is provided in
which case it calls kill-buffer. Bind this to
Ctrl+x k】 and you have the best of both worlds.
Here's some code that does that

(defun jcs-kill-a-buffer (askp)
  (interactive "P")
  (if askp
      (kill-buffer (funcall completing-read-function
                            "Kill buffer: "
                            (mapcar #'buffer-name (buffer-list))))
    (kill-this-buffer)))

(global-set-key (kbd "C-x k") 'jcs-kill-a-buffer)
-1:-- Kill This Buffer (Post jcs)--L0--C0--September 24, 2016 06:23 PM

Pragmatic Emacs: Don’t kill-buffer, kill-this-buffer instead

Here’s a tiny tip. By default C-x k runs the command kill-buffer which prompts you for which buffer you want to kill, defaulting to the current active buffer. I don’t know about you, but I rarely want to kill a different buffer than the one I am looking at, so I rebind C-x k to kill-this-buffer which just kills the current buffer without prompting (unless there are unsaved changes).

Just add this to your emacs config file

(global-set-key (kbd "C-x k") 'kill-this-buffer)
-1:-- Don’t kill-buffer, kill-this-buffer instead (Post Ben Maughan)--L0--C0--September 23, 2016 06:56 PM

Grant Rettke: lbForth, Common Lisp, and Forth Emacs fmacs

lbForth is bootstrapped by a forth-metacompiler and used to implement fmacs.

-1:-- lbForth, Common Lisp, and Forth Emacs fmacs (Post Grant)--L0--C0--September 23, 2016 12:31 AM

Irreal: An Example of pcase-lambda

Over at the Emacs reddit, instant_sunshine has an example of using pcase-lambda. It's not used very often but can be useful if you have to write functions that need to look inside Lisp objects. The documentation for pcase-lambda is a bit obscure so it helps to have an example of its use.

The idea is that it's like lambda except that the arguments can be any pattern accepted by pcase. Take a look at the pcase documentation or John Wiegley's pcase post to understand what those patterns are.

UPDATE 2016-09-22 19:39:09: Added link.

-1:-- An Example of pcase-lambda (Post jcs)--L0--C0--September 22, 2016 05:49 PM

sachachua: 2016-09-19 Emacs News

Links from reddit.com/r/emacs, /r/orgmode, Hacker News, planet.emacsen.org, Youtube, the changes to the Emacs NEWS file, and emacs-devel.

Past Emacs News round-ups

The post 2016-09-19 Emacs News appeared first on sacha chua :: living an awesome life.

-1:-- 2016-09-19 Emacs News (Post Sacha Chua)--L0--C0--September 20, 2016 03:34 AM

Pragmatic Emacs: View-mode makes for great read-only reading

The built-in view-mode turns the current buffer into a read-only pager, with SPACE and DEL to scroll up and down by page. This is a nice way to comfortably read files. Simply toggle on or off with M-x view-mode (or use e to exit view-mode). You can also tell Emacs to always open read-only files in view-mode with:

(setq view-read-only t)
-1:-- View-mode makes for great read-only reading (Post Ben Maughan)--L0--C0--September 19, 2016 09:23 PM

Marcin Borkowski: C-x SPC (rectangle-mark-mode)

It’s old news, but I was reminded about it recently. While Emacs has had support for rectangle operations (press C-x r C-h and look for commands with “rectangle” in their name) since a very long time, it acquired rectangle-mark-mode rather recently (a few years ago, in v24.4).
-1:-- C-x SPC (rectangle-mark-mode) (Post)--L0--C0--September 19, 2016 07:42 PM

Got Emacs?: Windows Binaries are out too

Looks like the binaries for Windows 32 and 64 bit can be found in the pretest folder, done by Philip Lord.  If you have any worries about downloading from sourceforge that is.
-1:-- Windows Binaries are out too (Post sivaram (noreply@blogger.com))--L0--C0--September 18, 2016 12:28 PM

Got Emacs?: Emacs 25.1 released

Finally, Emacs 25.1 is released.  The windows binaries would take some time to turn up. Hopefully the new TLS features would help in setting up mail connectivity easier to deal with.
-1:-- Emacs 25.1 released (Post sivaram (noreply@blogger.com))--L0--C0--September 18, 2016 02:32 AM

Mathias Dahl: barebones.el - the most basic .emacs file I use

Today I decided to write a little bit of documentation for my most basic version of .emacs or init.el that I use. It gets me up to 80% or so of full productivity for basic text editing on a new installation.

It can be found here:

https://github.com/mathiasdahl/dotemacs (download the barebones.el file)

Perhaps someone else will find it useful, as it is or as a simple start for their own Emacs customizations.

Enjoy!

-1:-- barebones.el - the most basic .emacs file I use (Post Mathias Dahl (noreply@blogger.com))--L0--C0--September 12, 2016 09:35 PM

Marcin Borkowski: Running Emacs commands not too often

If you are like me, you probably check your email too often. (Maybe nobody does anything stupid like that and it’s only me who has such unproductive habits, but I doubt it;-)…) As many Emacs users, I try to boost my productivity, and email notifications or checking email too often is a great way to actually worsen it.
-1:-- Running Emacs commands not too often (Post)--L0--C0--September 12, 2016 12:36 PM

sachachua: 2016-09-12 Emacs News

Links from reddit.com/r/emacs, /r/orgmode, Hacker News, planet.emacsen.org, Youtube, the changes to the Emacs NEWS file, and emacs-devel.

Past Emacs News round-ups

The post 2016-09-12 Emacs News appeared first on sacha chua :: living an awesome life.

-1:-- 2016-09-12 Emacs News (Post Sacha Chua)--L0--C0--September 12, 2016 05:18 AM

Rubén Berenguel: More emacs configuration tweaks (multiple-cursor on click, minimap, code folding, ensime eval overlays)

At Affectv we use a wide range of editors: Sublime, Atom, Emacs, Pycharm, IntelliJ... Actually only two people use the same editor! As such, from time to time I see things in other people's editors that I would like to have as well. So, yesterday I decided to improve on some configuration settings on Spacemacs.

Click for multiple-cursors

I saw this on Jordi's Sublime, and it is much more comfortable than using more-like-this or similar helper functions, even if I need to use the trackpad to do so. After all, a multi-cursor edit (proper edit, not as a substitute for a macro) is rare enough that I can tolerate leaving the home row. Easy enough to configure thanks to Magnar Sveen.

(global-unset-key (kbd "M-<down-mouse-1>"))
(global-set-key (kbd "M-<mouse-1>") 'mc/add-cursor-on-click)


Minimap

Also from Sublime, I had this on my old emacs setup. As simple as adding minimap to the list of additional packages and configuring its property group. See animation below.

dotspacemacs-additional-packages '(helm-dash key-chord pig-mode mmm-mode minimap origami ansible)

Folding

I have always loved how clean vim's folding works, and how Sublime has this nice folding. Then I found origami-mode and my emacs-life was complete. I tweaked a little the folding functions so that minimap was updated on fold (for some reason it is not, I guess minimap is tied to the "modified" hook or similar). I bound z and Z (and A-z which maps to æ in Colemak) to the basic fold operations.

(eval-after-load 'origami
'(progn
(defun rb-show-only (buffer point)
(interactive (list (current-buffer) (point)))
(progn (origami-show-only-node buffer point)
(minimap-new-minimap)))

(defun rb-toggle-rec (buffer point)
(interactive (list (current-buffer) (point)))
(progn (origami-recursively-toggle-node buffer point)
(minimap-new-minimap)))

(define-key evil-normal-state-map "æ" 'rb-show-only)
(define-key evil-normal-state-map "Z" 'origami-toggle-node)
(define-key evil-visual-state-map "Z" 'origami-toggle-node)
(define-key evil-insert-state-map "C-Z" 'origami-toggle-node)
(define-key evil-normal-state-map "z" 'rb-toggle-rec)
(define-key evil-visual-state-map "z" 'rb-toggle-rec)
(define-key evil-insert-state-map "C-z" 'rb-toggle-rec)
)))


For some reason just advising the functions with after didn't work, this is not great but does work. I left the Z bindings as they are, since I have not used them yet, and will probably delete them if I keep not using them.


Execution overlays in Ensime (Scala)

I saw this for Cider in the emacs church meeting from August, and heard @fommil (I think it was him) mention that it was coming to ensime. And indeed it was. And it's easy enough to use C-c C-v C-r (thing of it as extended command, eval, region to remember), given an open inferior Scala interpreter. Symbol prettify does not apply to overlays, so you need to customise the arrow used therein.




-1:-- More emacs configuration tweaks (multiple-cursor on click, minimap, code folding, ensime eval overlays) (Post Rubén Berenguel (noreply@blogger.com))--L0--C0--September 11, 2016 03:34 PM

John Stevenson: Kanban in Emacs Org-Mode to Get More Work Done

A Kanban board is a way to visualise your work and help you get more work done. You organise your work into tasks that need completeing and use the board to show the state of each card. Kanban encourages you to get work finished before starting new work.

The amazing Emacs Org-mode can be used to create a very fast and easy to use Kanban board that is with you where ever you are.

Update: Using Org-mode doesnt give me everything I want from a Kanban board, but it was an interesting exersice. For now, I am just sticking to my list view of a Kanban board.

Org-mode is built into Emacs / Spacemacs so there is no need to install any packages or layers for any of the following.

Designing a kanban board

The columns on your kanban board represent the state of work and represent your typical workflow. You can represent the states as the most generic todo, doing, done workflow, or anything more specific that adds value to how you manage work.

I have been using kanban for a while, so I am using a five stage workflow: planning, in progress, blocked, review, done

  • planning - work I’d like to do that needs organising so I can do it.
  • in progress - what I am currently working on. I try and keep this to a minimum so I get things done
  • blocked - things I’ve started working on but currently arent able to complete
  • review - work I have completed. Check if there are any follow on tasks or lessons learnt
  • done - things I have completed. Gives feeling of satisfaction

Creating Org-mode stages

Its easy to create your own Org-mode stages, to represent the state of work in your Kanban board. Please see my earlier article on Configuring Emacs Org-Mode to Managing Your Tasks

Create an Org-mode file

Create a new file by opening a new buffer M-x find-files and type in the new file name, ending in .org. Any files with a .org filename extension will automatically set the Emacs major mode to Org-mode.

I use a file called kanban.org for my kanban board.

Spacemacs Emacs
SPC f f C-x C-f
M-x spacemacs/helm-find-files M-x find-files

Create a kanban board

Lets assume you created a file called kanban.org. Edit this file and create a table for the kanban board. You can start creating ths manually by typing | for the table layout or use M-x org-table-create and enter the number of columns and rows for the table. For example, to create for a table with 5 columns and 3 rows, you would speciify 5x3

Add the names of the kanban board in the first row of the table. If you did not use M-x org-table-create then add a header row with M-x org-table-insert-hline.

In my kanban board, this gives

Emacs Org-mode table as Kanban board

Adding tasks to the kanban board

Each item on the board represents a task and we use the Org-mode interal link to jump from the board to the details of the task. To create a link of the same name as the task, simply type the name inside double square brakets [[]].

Emacs Org-mode table as Kanban board - task entry

Moving the tasks across the board

Its easy enough to move the columns around with Alt - <arrow-keys> in org-mode, but there is not a single keybinding to move a cell.

To move the individual tasks between the columns use selective cut and paste:

  • Move the cursor to the cell you want to move and use C-c C-x C-w
  • Use TAB to move to the new cell
  • Paste/Yank the value into the new cell using C-c C-x C-y

However, simply moving the task does not update the Org-mode stage. As each task is a link, I can click on that link and I am taken to the task and can easily update the task stage to match the board.

It would be great if moving the tasks on the board updated the associated task stage and vice versa.

El Kanban - updating the board from task stage changes

I found the El Kanban package that will updated the kanban board based on the task org-mode stages. This uses the Org-mode table format directive that you run each time you want to update the board.

I installed this package and it did pull in my custom org-mode stages for the headers. Unfortunately it did not pull in the tasks to the board, so I will either need to fix the package or find another solution.

Any suggestions are more than welcome.

References

Thank you.
@jr0cket

-1:-- Kanban in Emacs Org-Mode to Get More Work Done (Post)--L0--C0--September 09, 2016 12:38 PM

Raimon Grau: slime inspect + eval

When inspecting some value in slime-inspector, you may want to evaluate forms on that value.

That's what 'e' `slime-inspector-eval' is for.  What the docs do not put very clear is that '*' is the variable bound to the value.


-1:-- slime inspect + eval (Post Raimon Grau (noreply@blogger.com))--L0--C0--August 30, 2016 01:13 PM

Phil Hagelberg: in which a surprising affinity is pondered

When I got started with Lua, everything about it seemed to be the opposite of what I would like in a language, especially coming from Racket, Clojure, OCaml, and Erlang. It's unabashedly imperative, has nils everywhere, and lacks a macro system or any kind of static analysis. But now after spending over a year with it, I've developed a fondness for it, and the reasons are not what I would have expected.

The most obvious strength of Lua is its relentless simplicity. The small number of concepts you have to keep in your head when writing Lua can really help you focus, and it picks just the right concepts to build on[1]. For instance, the module system is largely just constructed out of tables and closures. What more do you need? It brings to mind the simplicity of Scheme and its "perfection is achieved when there is nothing left to remove" philosophy, but I believe Scheme's insistence on lists as the fundamental data type actually does a great disservice—fitting sequential data into an associative data type is much more natural than going the other way around[2].

There are two advanced features which can be confusing: metatables and coroutines. But when used judiciously, these can allow you to overcome the limitations of normal tables and functions in ways that feel seamless, like the way itch.io uses coroutines to hide the fact that many of its functions use asynchronous I/O and avoids structuring everything around callback soup.

But what you most often hear touted as Lua's appeal is actually in its ease of embedding. Now obviously when people talk about this they are usually referring to how seamless it is to add the Lua runtime to a large C program and expose its functionality to code that can be written by the end user. And this is huge; empowering users to control your programs by doing their own coding pays major dividends, and here again Lua's simplicity means more users are likely to be able to take advantage of it. But even though I don't write large C programs, I found that the ability to embed Lua execution inside a Lua program is very valuable.

This advantage is not at all intuitive if you haven't seen it, but one distinguishing factor of Lua is that it allows sandboxed execution contexts to be constructed trivially:

local chunk = assert(loadstring(user_code))
setfenv(chunk, {api = require("my.api")})
return chunk()

In these three lines the code loaded from the user_code string will run with no access to any functions outside the api table you provide. (In practice you would also include a whitelist of pure functions for tables, strings, math, etc.) But that's all it takes to allow user code to run inside your own limited sandbox.

Now Lua lacks any notion of first-class interfaces. The idea of passing a table in which must conform to a certain specified shape of fields and functions is fully ad-hoc and must be communicated entirely through documentation. And unfortunately it's somewhat unusual for Lua programmers to specify which functions in a module are for public consumption vs which are internal implementation details. But first-class sandboxes as extension points actually address many of the same problems as interfaces! Instead of saying "you must provide an implementation of this interface that has these fields and these functions" you can say "Provide your own code here; you will have access to call only this limited subset of functions which we've designated as a public API. The implementation details aren't even visible to you."

Now this can break down badly when the sandbox doesn't expose enough functionality to get the job done. This is why it's important not to tack on "scriptability" as a checkbox you fulfill at the end, but to embrace internal reprogrammability from the very start. If you use the same methods to build the program in the first place as the end users use to customize it, you force yourself to be honest and to give the end users everything they need.

9 and 9 coffee

So from this perspective, we can agree that yes, Lua's imperative nature and sloppy semantics (especially around nils) put it at a disadvantage for large codebases vs languages that have the advantage of immutability and/or intelligent type systems. But the fact that it offers setfenv makes it uniquely suited for constructing larger codebases out of small codebases. This is the approach I take in my game Bussard, where I have four separate execution contexts, none of which have much more than 3,000 lines of code in them. Each small codebase is perfectly manageable on its own, and the interfaces between them are concise and clearly-defined despite Lua lacking first-class features for defining interfaces as we normally think of them.


[1] I have found that this simplicity also makes it a great choice for teaching programming, especially to younger kids who haven't reached the developmental stages where they can appreciate the more abstract, mathematical approach espoused by Racket.

[2] I know this method has a bad reputation because JavaScript and PHP do it very badly, but Lua shows it can be done well. There is a bit of awkwardness around ambiguity between array-like tables and key/value tables, but it is not nearly as awkward as using alists.

-1:-- in which a surprising affinity is pondered (Post Phil Hagelberg)--L0--C0--August 29, 2016 07:56 PM

(or emacs: elf-mode - view the symbol list in a binary

Recently, I've been looking at libigl. I didn't manage to fully figure out their CMake build system for tutorials: although each tutorial has a CMakeLists.txt, it's only possible to build them all at once.

So I decided to replace CMakeLists.txt with a good-old Makefile; how hard can it be? Concerning includes, not at all hard: the missing files are found with counsel-locate and added to the include path.

But I had some trouble matching a missing ld dependency to a library file. Fixed it with a bunch of googling and guesswork; I still wonder if there's a better way. But in the process, I've found this useful command:

readelf --syms libGL.so

which produces e.g.:


Symbol table '.dynsym' contains 2732 entries:
   Num:    Value          Size Type    Bind   Vis      Ndx Name
     0: 0000000000000000     0 NOTYPE  LOCAL  DEFAULT  UND
     1: 000000000004faf0     0 SECTION LOCAL  DEFAULT    8
     2: 00000000000e8f20     0 FUNC    GLOBAL DEFAULT   11 glGetIntegerui64i_vNV
     3: 00000000000e13e0     0 FUNC    GLOBAL DEFAULT   11 glGetMultiTexEnvfvEXT
     4: 00000000000d7440     0 FUNC    GLOBAL DEFAULT   11 glProgramUniform2uiv
     5: 00000000000cfdc0     0 FUNC    GLOBAL DEFAULT   11 glMultiTexCoord3sv

This is a pretty good representation of a binary file: in this example, instead of one megabyte of gibberish I see a bit more than 2732 lines describing the functions this file uses and provides.

Viewing the symbol list automatically

I liked the above representation so much that I want to see it by default. In Emacs, it's pretty easy to do with auto-mode-alist:

(add-to-list 'auto-mode-alist '("\\.\\(?:a\\|so\\)\\'" . elf-mode))

The above code instructs Emacs to call elf-mode function whenever the file name ends in *.a or *.so.

And here's the body of elf-mode:

(defvar-local elf-mode nil)

;;;###autoload
(defun elf-mode ()
  (interactive)
  (let ((inhibit-read-only t))
    (if elf-mode
        (progn
          (delete-region (point-min) (point-max))
          (insert-file-contents (buffer-file-name))
          (setq elf-mode nil))
      (setq elf-mode t)
      (delete-region (point-min) (point-max))
      (insert (shell-command-to-string
               (format "readelf --syms %s" (buffer-file-name)))))
    (set-buffer-modified-p nil)
    (read-only-mode 1)))

The idea is very simple: elf-mode is a toggle function that replaces the buffer contents with the shell command output. It carefully uses read-only-mode and set-buffer-modified-p so that the file will not be overwritten by accident with the symbol names.

Using autoload to avoid overhead

As you might imagine, looking at binaries isn't really a common task. Is it worth to be dragging this code around from now on, loading it on each start? The answer is yes, of course. Since the actual cost is negligible until the feature is used.

If you look above, elf-mode has an ;;;###autoload cookie before it. The cookie results in this line in my loaddefs.el:

(autoload 'elf-mode "modes/ora-elf" "" t nil)

My init.el always loads loaddefs.el, but never loads ora-elf.el where the function is defined. That file is only loaded when the function elf-mode is called for the first time. The above autoload statement simply instructs Emacs to load a particular file when elf-mode needs to be called.

When you use the package manager, the autoloads file is generated and loaded for you automatically:

$ tree elpa/ace-link-20160811.112/

elpa/ace-link-20160811.112/
├── ace-link-autoloads.el
├── ace-link.el
├── ace-link.elc
└── ace-link-pkg.el

0 directories, 4 files

Here, the package manager will always load ace-link-autoloads.el, which instructs Emacs to load ace-link.el when one of the ;;;###autoload functions is called and ace-link.el isn't yet loaded.

As an example of how useful delayed loading is: my 6000 line config starts in 1.8 seconds. About 40% of that time is spent on (package-initialize), which I assume is the package manager loading all those *-autoloads.el files that I have in my elpa/.

Outro

Let me know if there's interest to have elf-mode on MELPA. Also, if anyone knows how to set mode automatically based on the first few chars of the file (all binaries seem to start with ^?ELF), I'd like to know that as well. Happy hacking!

-1:-- elf-mode - view the symbol list in a binary (Post)--L0--C0--August 27, 2016 10:00 PM

Wilfred Hughes: Rustdoc Meets The Self-Documenting Editor

Emacs Lisp has a delightful help system. You can view the docstring for any function under the cursor, making it easy to learn functionality.

Rust goes a step further. All the standard library documentation is written with the source code. This means we can find docs programmatically!

When I learnt that racer recently added support for rustdoc, I couldn’t resist adding support to racer.el.

The new racer-describe command actually renders the markdown in rustdoc comments. Since we’re showing a separate buffer, we can render the docs and throw away the markdown syntax. We can even convert external hyperlinks to clickable links!

This is a really nice example of composing Emacs functionality. Since we can easily highlight code snippets (it’s an editor!), we actually apply syntax highlighting to inline code! Note how Vec and T are highlighted as types in the above screenshot.

Whilst we don’t use *Help* buffers, we extend the same keymaps, so all the relevant help shortcuts just work too.

We have hit a few teething issues in racer (namely #594 and #597) but it’s changed the way I explore Rust APIs. It’s particularly useful for learning functionality via examples, without worrying about implementation:

I hope it will also encourage users to write great docstrings for their own projects.

Love it? Hate it? Let me know what you think in the /r/rust discussion.

(It’s hot off the press, so there will be bugs. If you find one, please file it on GitHub.)

-1:-- Rustdoc Meets The Self-Documenting Editor (Post Wilfred Hughes (me@wilfred.me.uk))--L0--C0--August 27, 2016 12:00 AM

Chen Bin (redguardtoo): Emacs as C++ IDE, easy way

I design a quick and newbie friendly solution.

It works at Linux/OSX/Cygwin (should work at Windows, but I don't develop at Windows).

Setup is minimum. You only need install GNU Global and two Emacs plugins:

Here is the step to step guide.

1 Step 1, create sample projects for experiment

Say I have two projects ~/proj1 and ~/proj2. Both projects will use third party library C++ header files from read-only directory /usr/include.

A new directory ~/obj to store the index files of third party libraries.

mkdir -p ~/{proj1,proj2,obj}

The content of ~/proj2/lib.cpp,

void proj2_hello(int a2, char* b2) {
}

The content of ~/proj1/main.cpp,

void proj1_hello(int a1, char* b1) {
}

int main(int argc, char *argv[]) {
    return 0;
}

2 Step 2, scan C++ code and setup Emacs

Run below command in shell to scan code,

cd /usr/include && MAKEOBJDIRPREFIX=~/obj gtags -O && cd ~/proj1 && gtags && cd ~/proj2 && gtags

After setting up the corresponding Emacs plugins (minimum setup copied from their website is enough), insert below code into ~/.emacs,

;; Please note `file-truename' must be used!
(setenv "GTAGSLIBPATH" (concat "/usr/include"
                               ":"
                               (file-truename "~/proj2")
                               ":"
                               (file-truename "~/proj1")))
(setenv "MAKEOBJDIRPREFIX" (file-truename "~/obj/"))
(setq company-backends '((company-dabbrev-code company-gtags)))

3 Usage

Use the Emacs plugins as usual.

But you need install latest company built on 25th August because I fixed a company issue yesterday.

Screenshot,

cpp-gtags-demo-nq8.png

4 Technical Details (Optional)

Check GNU Global manual to understand environment variables GTAGSLIBPATH and MAKEOBJDIRPREFIX.

-1:-- Emacs as C++ IDE, easy way (Post Chen Bin)--L0--C0--August 25, 2016 02:20 PM

Ben Simon: An Emacs Friendly Caps Lock Configuration on Windows

While this may be obvious, I was pretty dang pleased with myself when I managed to turn the Caps Lock key on my Windows 10 computer into an emacs friendly Hyper key. Here's what I did:

Step 1. Use AutoHotKey to trivially map the Caps Lock key to the Windows Menu key, or as AutoHotKey calls it, the AppsKey.

;; Add this to your standard AutoHotKey configuration
CapsLock::AppsKey

Step 2. Use this elisp code to capture the Menu key from within emacs and map it to the Hyper modifier:

;; http://ergoemacs.org/emacs/emacs_hyper_super_keys.html
(setq w32-pass-apps-to-system nil)
(setq w32-apps-modifier 'hyper) ; Menu/App key

Step 3. Enjoy! I can now map any key binding using the H- modifier. Here's some code I added to my PHP setup:

(defun bs-php-mode-hook ()
  (local-set-key '[backtab] 'indent-relative)
  (local-set-key (kbd "<H-left>") 'beginning-of-defun)
  (local-set-key (kbd "<H-right>") 'end-of-defun)
  (auto-complete-mode t)
  (require 'ac-php)
  (setq ac-sources  '(ac-source-php ))
  (yas-global-mode 1)
  (setq indent-tabs-mode nil)
  (setq php-template-compatibility nil)
  (setq c-basic-offset 2))

The result: when I open up a PHP file, I can jump between function definitions by holding down Caps Lock and left or right arrow.

I feel like I just won the keyboard shortcut lottery!

-1:-- An Emacs Friendly Caps Lock Configuration on Windows (Post Ben Simon (noreply@blogger.com))--L0--C0--August 25, 2016 02:11 PM

William Denton: Image display size in Org

I just discovered that it’s possible to change the size of an image as displayed in Org while leaving the actual file unchanged. This is great: I can scale it down so it’s just large enough I know what it is but it doesn’t get in my way or take up much real estate.

The variable is org-image-actual-width. C-h v org-image-actual-width shows the documentation:

org-image-actual-width is a variable defined in ‘org.el’. Its value is t

Documentation: Should we use the actual width of images when inlining them?

When set to t, always use the image width.

When set to a number, use imagemagick (when available) to set the image’s width to this value.

When set to a number in a list, try to get the width from any #+ATTR.* keyword if it matches a width specification like

#+ATTR_HTML: :width 300px

and fall back on that number if none is found.

When set to nil, try to get the width from an #+ATTR.* keyword and fall back on the original width if none is found.

This requires Emacs >= 24.1, build with imagemagick support.

(I build Emacs from source, and it has ImageMagick support, though I forget if I had to do anything to get that working. I think just installing ImageMagick is enough. Do ./configure | grep -i imagemagick to check if Emacs knows about it.)

I could set the variable in an init file:

(setq org-image-actual-width nil)

But for now I’m just using it as a file local variable, with this as the first line of the Org file:

# -*- org-image-actual-width: nil; -*-

Then I have, for example, this raw text:

#+NAME: fig:moodleviz
#+CAPTION: Screenshot from Moodleviz.
#+ATTR_ORG: :width 600
#+ATTR_LATEX: :width 5in
[[file:figures/moodleviz-laps.png]]

That image is 1520 pixels wide (wider than my personal laptop—it’s a screenshot taken on a larger screen) and it’s annoying to move by it up or down, so shrinking the displayed size is great. It looks like this scaled down to 600 pixels wide:

Image resized to be smaller. Image resized to be smaller.

ATTR_LATEX shrinks the image to a nice size when I export the document to PDF. There is no HTML version so I don’t care about resizing for that.

-1:-- Image display size in Org (Post William Denton)--L0--C0--August 25, 2016 01:25 PM

Ben Simon: Emacs + PHP - A Modern and (Far More Complete) Recipe

Recently, I had a chance to do a bit of emacs evangelism. Man, is that a soapbox I like to climb on! I hit all my favorite features from dired and dynamic abbreviation expansion to under appreciated gems like ispell. I talked about the power of having a fully programmable, self documenting editor at your fingertips. When I was done, I thought for sure I had managed to add another member to the tribe.

Then, yesterday, my possible convert came to me with a simple question: what mode do you use to edit PHP? Considering that most of the code I write is PHP, you'd think I would be ready to deliver a solid answer. Instead, I mumbled something about having a hacked bit of code I relied on, but really wouldn't recommend it for the general use. Yeah, not cool. I closed out the conversation with a promise: I'd see what the latest PHP options were and report back.

PHP is actually a fairly tricky language to build an editor for. That's because depending on the style it's written in, it can range from disciplined C like code to a gobbly gook C like code with HTML, CSS and JavaScript all mixed in. Add to that the classic emacs problem of having too many 85% solutions, and there's definitely room for frustration. Check out the emacs wiki to see what I mean. You'll find lots of promising options, but no one definitive solution.

After reading up on my choices and trying out some options, I do believe I have a new recipe for PHP + emacs success. Here goes.

Step 1: Setup Melpa

Melpa is a code repository that emacs can magically pull in packages from. Back in the day, adding packages to emacs meant downloading, untarring, and running make. Like all things emacs, the process has been both streamlined, and of course, is fully executable from within emacs. To add Melpa, you'll need to follow the instructions here. Assuming you have a modern version of emacs, this probably just means adding the following to your .emacs:

(add-to-list 'package-archives
             '("melpa" . "https://melpa.org/packages/"))

Step 2: Install the Melpa available PHP Mode

Emacs comes with a PHP mode out of the box, but it seems as though this one (also named php-mode) is more modern. I love that the README talks about PHP 7, showing just how up to date this mode is with respect to the latest language constructs.

Installing this mode, assuming Melpa is cooperating, couldn't be easier. Just run: M-x package-install and enter php-mode.

My preference for indentation is 2 spaces and no insertion of tab characters. Two other tweaks I was after was to turn off HTML support from within PHP and enable subword-mode. All these tweaks are stored in a function and attached to the php-mode-hook. This is all standard .emacs stuff:

(defun bs-php-mode-hook ()
  (setq indent-tabs-mode nil)
  (setq c-basic-offset 2)
  (setq php-template-compatibility nil)
  (subword-mode 1))

(add-hook 'php-mode-hook 'bs-php-mode-hook)

Step 3: Install Web-Mode.el

php-mode above is ideal for code centric PHP files. But what about those pesky layout files that contain HTML, CSS and JavaScript? For that, web-mode.el looks especially promising. Installation and configuration mirrors php-mode. Here's the code I use to customize it:

(defun bs-web-mode-hook ()
  (local-set-key '[backtab] 'indent-relative)
  (setq indent-tabs-mode nil)
  (setq web-mode-markup-indent-offset 2
        web-mode-css-indent-offset 2
        web-mode-code-indent-offset 2))

(add-hook 'web-mode-hook 'bs-web-mode-hook)

Web-mode.el is quite impressive and who knows, it may actually fulfill all my PHP needs. If that's the case, I may choose to stop using the php-mode. However, for now, I like the idea of being able to switch between the two modes. Which brings me to the next step...

Step 4: Add a Quick Mode Toggle

Inspired by this tip on the EmacsWiki, I went ahead and setup a quick toggle between php-mode and web-mode. Here's that code:

(defun toggle-php-flavor-mode ()
  (interactive)
  "Toggle mode between PHP & Web-Mode Helper modes"
  (cond ((string= mode-name "PHP")
         (web-mode))
        ((string= mode-name "Web")
         (php-mode))))

(global-set-key [f5] 'toggle-php-flavor-mode)

Now I'm only an F5 keystroke away from two different editor strategies.

When I have a say in the matter, I tend to be pretty particular about which files in my source tree are pure code and which are pure markup. At some point, I could codify this so that files in the snippets directory, for example, always open in web-mode, whereas files loaded from under lib start off in php-mode. Such is the joy of having a fully programmable editor at your fingertips. You make up the rules!

Step 5: Bonus - Setup aggressive auto-completion

For bonus points, I decided to play with ac-php, a library that supports auto completion of function and class names. I followed the install here, updated my .emacs file as noted below, created the empty file named .ac-php-conf.json in my project's root and then ran M-x ac-php-remake-tags-all. Once that's done, emacs now shouts completions like crazy at me:

It's slick, I'll give you that. I think I may have to see if I can turn down the volume, a bit. Here's what my .emacs now looks like to configure php-mode: now looks like:

(defun bs-php-mode-hook ()
  (auto-complete-mode t)                 ;; «
  (require 'ac-php)                      ;; «
  (setq ac-sources  '(ac-source-php ))   ;; «
  (yas-global-mode 1)                    ;; «
  (setq indent-tabs-mode nil)
  (setq php-template-compatibility nil)
  (setq c-basic-offset 2))

Bye-bye hacked PHP code. Hello modern, feature filled, super easy to install, mega powerful code.

Update: updated the web-mode hook I'm using to make sure all code on the page, not just markup code, is indented 2 steps.

-1:-- Emacs + PHP - A Modern and (Far More Complete) Recipe (Post Ben Simon (noreply@blogger.com))--L0--C0--August 25, 2016 04:33 AM

Flickr tag 'emacs': DSCF2762_gmpd

MGdesigner posted a photo:

DSCF2762_gmpd

The secret attendee in coscup 2016

-1:-- DSCF2762_gmpd (Post MGdesigner (nobody@flickr.com))--L0--C0--August 22, 2016 09:25 AM

Flickr tag 'emacs': DSCF2758_gpmd

MGdesigner posted a photo:

DSCF2758_gpmd

The secret attendee in coscup 2016

-1:-- DSCF2758_gpmd (Post MGdesigner (nobody@flickr.com))--L0--C0--August 22, 2016 09:25 AM

Chen Bin (redguardtoo): No worries when elpa is down

I use one liner shell command to clone Emacs Lisp Package Archive (ELPA):

mkdir -p ~/elpaclone && cd ~/elpaclone && curl -L https://elpa.gnu.org/packages/archive-contents | perl -pe 's/(^\(1|\n)//g' | perl -pe 's/\]\)/])\n/g' | perl -pe 's/^ *\(([a-z0-9A-Z-]*).*\[\(([0-9 ]*).*(single|tar).*/\1-\2.\3/g' | perl -pe 's/ /./g' | perl -pe 's/single/el/g' | perl -pe 's/\)//g' | xargs -I {} curl -L  -O https://elpa.gnu.org/packages/{} && curl -L -O https://elpa.gnu.org/packages/archive-contents

The https://elpa.gnu.org/packages/archive-contents contains all the information of packages. I re-organize it to make sure each line corresponds to one package. Then I use cURL to download everything.

Usage is simple.

Insert below line at the beginning of ~/.emacs when elpa.gnu.org is down:

(setq package-archives '(("elpaclone" . "~/elpaclone")))

This solution also works for MELPA.

-1:-- No worries when elpa is down (Post Chen Bin)--L0--C0--August 14, 2016 12:52 PM

Chris Wellons: An Elfeed Database Analysis

The end of the month marks Elfeed’s third birthday. Surprising to nobody, it’s also been three years of heavy, daily use by me. While I’ve used Elfeed concurrently on a number of different machines over this period, I’ve managed to keep an Elfeed database index with a lineage going all the way back to the initial development stages, before the announcement. It’s a large, organically-grown database that serves as a daily performance stress test. Hopefully this means I’m one of the first people to have trouble if an invisible threshold is ever exceeded.

I’m also the sort of person who gets excited when I come across an interesting dataset, and I have this gem sitting right in front of me. So a couple of days ago I pushed a new Elfeed function, elfeed-csv-export, which exports a database index into three CSV files. These are intended to serve as three tables in a SQL database, exposing the database to interesting relational queries and joins. Entry content (HTML, etc.) has always been considered volatile, so this is not exported. The export function isn’t interactive (yet?), so if you want to generate your own you’ll need to (require 'elfeed-csv) and evaluate it yourself.

All the source code for performing the analysis below on your own database can be found here:

The three exported tables are feeds, entries, and tags. Here are the corresponding columns (optional CSV header) for each:

url, title, canonical-url, author
id, feed, title, link, date
entry, feed, tag

And here’s the SQLite schema I’m using for these tables:

CREATE TABLE feeds (
    url TEXT PRIMARY KEY,
    title TEXT,
    canonical_url TEXT,
    author TEXT
);

CREATE TABLE entries (
    id TEXT NOT NULL,
    feed TEXT NOT NULL REFERENCES feeds (url),
    title TEXT,
    link TEXT NOT NULL,
    date REAL NOT NULL,
    PRIMARY KEY (id, feed)
);

CREATE TABLE tags (
    entry TEXT NOT NULL,
    feed TEXT NOT NULL,
    tag TEXT NOT NULL,
    FOREIGN KEY (entry, feed) REFERENCES entries (id, feed)
);

Web authors are notoriously awful at picking actually-unique entry IDs, even when using the smarter option, Atom. I still simply don’t trust that entry IDs are unique, so, as usual, I’ve qualified them by their source feed URL, hence the primary key on both columns in entries.

At this point I wish I had collected a lot more information. If I were to start fresh today, Elfeed’s database schema would not only fully match Atom’s schema, but also exceed it with additional logging:

  • When was each entry actually fetched?
  • How did each entry change since the last fetch?
  • When and for what reason did a feed fetch fail?
  • When did an entry stop appearing in a feed?
  • How long did fetching take?
  • How long did parsing take?
  • Which computer (hostname) performed the fetch?
  • What interesting HTTP headers were included?
  • Even if not kept for archival, how large was the content?

I may start tracking some of these. If I don’t, I’ll be kicking myself three years from now when I look at this again.

A look at my index

So just how big is my index? It’s 25MB uncompressed, 2.5MB compressed. I currently follow 117 feeds, but my index includes 43,821 entries from 309 feeds. These entries are marked with 53,360 tags from a set of 35 unique tags. Some of these datapoints are the result of temporarily debugging Elfeed issues and don’t represent content that I actually follow. I’m more careful these days to test in a temporary database as to avoid contamination. Some are duplicates due to feeds changing URLs over the years. Some are artifacts from old bugs. This all represents a bit of noise, but should be negligible. During my analysis I noticed some of these anomalies and took a moment to clean up obviously bogus data (weird dates, etc.), all by adjusting tags.

The first thing I wanted to know is the weekday frequency. A number of times I’ve blown entire Sundays working on Elfeed, and, as if to frustrate my testing, it’s not unusual for several hours to pass between new entries on Sundays. Is this just my perception or are Sundays really that slow?

Here’s my query. I’m using SQLite’s strftime to shift the result into my local time zone, Eastern Time. This time zone is the source, or close to the source, of a large amount of the content. This also automatically accounts for daylight savings time, which can’t be done with a simple divide and subtract.

SELECT tag,
       cast(strftime('%w', date, 'unixepoch', 'localtime') AS INT) AS day,
       count(id) AS count
FROM entries
JOIN tags ON tags.entry = entries.id AND tags.feed = entries.feed
GROUP BY tag, day;

The most frequent tag (13,666 appearances) is “youtube”, which marks every YouTube video, and I’ll use gnuplot to visualize it. The input “file” is actually a command since gnuplot is poor at filtering data itself, especially for histograms.

plot '< grep ^youtube, weekdays.csv' using 2:3 with boxes

Wow, things do quiet down dramatically on weekends! From the glass-half-full perspective, this gives me a chance to catch up when I inevitably fall behind on these videos during the week.

The same is basically true for other types of content, including “comic” (12,465 entries) and “blog” (7,505 entries).

However, “emacs” (2,404 entries) is a different story. It doesn’t slow down on the weekend, but Emacs users sure love to talk about Emacs on Mondays. In my own index, this spike largely comes from Planet Emacsen. Initially I thought maybe this was an artifact of Planet Emacsen’s date handling — i.e. perhaps it does a big fetch on Mondays and groups up the dates — but I double checked: they pass the date directly through from the original articles.

Conclusion: Emacs users love Mondays. Or maybe they hate Mondays and talk about Emacs as an escape.

I can reuse the same query to look at different time scales. When during the day do entries appear? Adjusting the time zone here becomes a lot more important.

SELECT tag,
       cast(strftime('%H', date, 'unixepoch', 'localtime') AS INT) AS hour,
       count(id) AS count
FROM entries
JOIN tags ON tags.entry = entries.id AND tags.feed = entries.feed
GROUP BY tag, hour;

Emacs bloggers tend to follow a nice Eastern Time sleeping schedule. (I wonder how Vim bloggers compare, since, as an Emacs user, I naturally assume Vim users’ schedules are as undisciplined as their bathing habits.) However, this also might be prolific the Irreal breaking the curve.

The YouTube channels I follow are a bit more erratic, but there’s still a big drop in the early morning and a spike in the early afternoon. It’s unclear if the timestamp published in the feed is the upload time or the publication time. This would make a difference in the result (e.g. overnight video uploads).

Do you suppose there’s a slow month?

SELECT tag,
       cast(strftime('%m', date, 'unixepoch', 'localtime') AS INT) AS day,
       count(id) AS count
FROM entries
JOIN tags ON tags.entry = entries.id AND tags.feed = entries.feed
GROUP BY tag, day;

December is a big drop across all tags, probably for the holidays. Both “comic” and “blog” also have an interesting drop in August. For brevity, I’ll only show one. This might be partially due my not waiting until the end of this month for this analysis, since there are only 2.5 Augusts in my 3-year dataset.

Unfortunately the timestamp is the only direct numerical quantity in the data. So far I’ve been binning data points and counting to get a second numerical quantity. Everything else is text, so I’ll need to get more creative to find other interesting relationships.

So let’s have a look a the lengths of entry titles.

SELECT tag,
       length(title) AS length,
       count(*) AS count
FROM entries
JOIN tags ON tags.entry = entries.id AND tags.feed = entries.feed
GROUP BY tag, length
ORDER BY length;

The shortest are the webcomics. I’ve complained about poor webcomic titles before, so this isn’t surprising. The spikes are from comics that follow a strict (uncreative) title format.

Emacs article titles follow a nice distribution. You can tell these are programmers because so many titles are exactly 32 characters long. Picking this number is such a natural instinct that we aren’t even aware of it. Or maybe all their database schemas have VARCHAR(32) title columns?

Blogs in general follow a nice distribution. The big spike is from the Dwarf Fortress development blog, which follows a strict date format.

The longest on average are YouTube videos. This is largely due to the kinds of videos I watch (“Let’s Play” videos), which tend to have long, predictable names.

And finally, here’s the most interesting-looking graph of them all.

SELECT ((date - 4*60*60) % (24*60*60)) / (60*60) AS day_time,
       length(title) AS length
FROM entries
JOIN tags ON tags.entry = entries.id AND tags.feed = entries.feed;

This is the title length versus time of day (not binned). Each point is one of the 53,360 posts.

set style fill transparent solid 0.25 noborder
set style circle radius 0.04
plot 'length-vs-daytime.csv' using 1:2 with circles

(This is a good one to follow through to the full size image.)

Again, all Eastern Time since I’m self-centered like that. Vertical lines are authors rounding their post dates to the hour. Horizontal lines are the length spikes from above, such as the line of entries at title length 10 in the evening (Dwarf Fortress blog). There’s a the mid-day cloud of entries of various title lengths, with the shortest title cloud around mid-morning. That’s probably when many of the webcomics come up.

Additional analysis could look further at textual content, beyond simply length, in some quantitative way (n-grams? soundex?). But mostly I really need to keep track of more data!

-1:-- An Elfeed Database Analysis (Post)--L0--C0--August 12, 2016 03:20 AM

Rubén Berenguel: Moving from Emacs to Spacemacs

A couple of days ago I attended (first time I managed in almost 6 months) the London chapter of the Emacs Church (also known as the local meetup for emacs lovers). In this event we were shown how to use emacs effectively for Clojure development (using Cider) and I saw in real life Spacemacs.

In case you don't know, Spacemacs is a "distribution" of Emacs prepared (is open source, of course) to be easy to setup, and somehow specially prepared for former Vim users to move to Emacs. For instance, on startup asks if you want to be in Emacs mode, evil mode or hybrid (Emacs mode keys in vim insert mode) by default.

As you may remember, I've been using Emacs with evil for around 3 years already, and have been pretty happy with it. I'm not so happy about the state of my .emacs file: currently it is 2652 lines long (of course around 400 or 500 of those are generated automatically by custom). Too big and unwieldy. And I'm too lazy to move all the nuts and bolts to something more lightweight and sane.

I thought that trying out Spacemacs could be the perfect excuse to clean the mess off my .emacs file, since I could carefully move piece by piece whatever I needed as I needed it (like I usually do when upgrading computers).

For a start, the beginning was a good experience. Since by default it includes most of the fancy stuff I use normally (helm being the biggest, fanciest helper I need, I only needed to tweak helm-files and switch-buffer, and add recentf) and I no longer use mu4e on a day-to-day basis, I could easily switch to it.

It's actually really easy to try Spacemacs alongside your normal emacs: just download it and from the spacemacs folder run something like
HOME=~/fromsource/spacemacs /Applications/Emacs.app/Contents/MacOS/Emacs
or the equivalent in your environment. Caveat: multi-term/ansi-term won't work as expected (best solution is to actually move to using Spacemacs as default). Aside from that I have had no other big issues, and recently moved to Spacemacs to be the main Emacs and if needed I can run my old configuration with the "HOME trick".

One thing I have not figured out how to exactly do "the Spacemacs way" but I needed no matter what is having my set of normal Emacs keybindings in evil insert and normal modes. Hybrid mode covers insert more or less nicely, but some commands I need them as they are because not only are they part of my muscle memory, but I also happen to like them and use them everywhere (OS X input fields, terminal windows). I tried to set this up in many places in the .spacemacs file (the user-config section, using the -init or -after macros of package initialisation...) And finally this made it work, so, in case you need to modify evil insert or normal key maps in Spacemacs:

(eval-after-load 'evil 
'(progn
(define-key evil-normal-state-map (kbd "SPC") 'ace-jump-mode)
(define-key evil-insert-state-map (kbd "C-a") 'move-beginning-of-line)
(define-key evil-insert-state-map (kbd "C-e") 'move-end-of-line)
(define-key evil-insert-state-map (kbd "C-k") 'kill-line)
(define-key evil-insert-state-map (kbd "C-w") 'kill-region)
(define-key evil-visual-state-map (kbd "C-a") 'move-beginning-of-line)
(define-key evil-visual-state-map (kbd "C-e") 'move-end-of-line)
(define-key evil-normal-state-map (kbd "C-a") 'move-beginning-of-line)
(define-key evil-normal-state-map (kbd "C-e") 'move-end-of-line)
(define-key evil-normal-state-map (kbd "C-k") 'kill-line)
(define-key evil-normal-state-map (kbd "C-y") 'yank)
(define-key evil-insert-state-map (kbd "C-y") 'yank)
(define-key evil-insert-state-map (kbd "C-t") 'transpose-chars)
(define-key evil-normal-state-map (kbd "C-w") 'kill-region)
(define-key evil-visual-state-map (kbd "C-w") 'kill-region)
(define-key evil-visual-state-map (kbd "SPC") 'ace-jump-mode)))
Something I found surprising though is the load time: Spacemacs does not load packages on startup and my .emacs setup did, and they roughly start up at the same speed. Somehow I expected a faster startup time.

Worth also downloading the latest emacs port for homebrew, which fixes some annoyances with powerline colours as well as being quite more up to date than Carbon Emacs.

Now the only big thing left I have is reconfiguring multiple-cursors and my definitions of more-like-this and all that to be a happy Spacemacs user.
-1:-- Moving from Emacs to Spacemacs (Post Rubén Berenguel (noreply@blogger.com))--L0--C0--August 07, 2016 08:42 PM

John Stevenson: YASnippets for Faster Clojure Coding

Using snippets saves you time typing common coding structures and helps you avoid silly typos too. Simply typing in a snippet name and pressing M-/ or using M-x yas-expand gives you the full text & code structure from the snippet template.

For example, if you are defining a new function in Clojure then type defn and press M-/ to expand to the full definition structure, including all parens. Then use TAB to move through the structure to complete the name, doc-string, arguments and behaviour of the function.

Lets look at the built-in snippets that come with the Clojure layer in Spacemacs (and should be the default in Emacs YASnippet package).

Its easy to wrtie your own snippets for Clojure or any other language you use with Spacemacs / Emacs

Where do Snippets fit in

There are several ways to speed up typing your Clojure code, Leiningen Templates, autocompletion, clj-refactor and YASnippets.

Snippets are a great way to create much of the common code structures you typically write as you are developing your code. The snippets I use the most are defn, let, ifl and for.

Some of the snippets are made redundant by other Clojure layer features in Spacemacs. For example, when I create a new file then the namespace is automatically added, so I rarely use the ns snippet. I also use clj-refactor which takes care of adding require statements for me, so the require snippet is rarely used.

Note: Smartparens does not work when you are completing an expanded snippet the first time. However, as soon as you tab out of the end of the snippet then smartparens works again. I havent determined if this is simply a missing config or some conflict between YASnippets & Smartparens.

Default snippets for Clojure

The snippets that are available in Spacemacs can be found in the yasnippet github repository or in the ~/.emacs.d/elpa/yasnippet-20160501.1841/snippets/clojure-mode directory on your laptop (when yasnippet package is updated then name of that directory will change).

All the current snippets for Clojure mode are in the following table, indicating which tab stops they have.

Snippet Description Tab Stops
bench benchmark an expression, using the time function body
bp depreciated: break point in swank
def def expression N/A
defm defmacro expression, with name, doc-string, arguments & body tabstops name, docstring, args, body
defn defn expression, with name, doc-string, arguments & body tabstops name, docstring, args, body
defr defrecord docstring, object, args, body
deft deftype docstring, object, args, body
doseq doseq name, body
fn fn - anonymous function name, body
for for condition, body
if if condition, body
ifl if-let - if true, bind a local name binding, body
import import java library library name
is is - clojure test assertion value, expected
let let - bind a local name to a value name, value, body
map map fn, col, col
map.lambda map with anonymous function #() fn, body
mdoc metadata docstring docstring
ns ns - expression with the current namespace inserted automatically N/A
opts destructuring a map with :keys, :or for default values, :as for entire vector :key binding, or defaults, :as binding
pr prn - print function string/value
print println - print function string/value
reduce reduce - reduce expression with an anonymous function args, body
require :require expression with library and alias library, alias
test deftest expression test description, value/expected
try try & catch expression try expression, exception name, body
use depreciated: use require instead
when when when expression, body
whenl when-let - local binding on when condition binding, body

Hint: The above table was created in Emacs markdown mode by enabling the minor mode: orgtbl-mode. Start the table with a | character followed by a word and use TAB to create and align the table as you go through. If you already have content, use the function orgtbl-create-or-convert-from-region. To enable orgtbl-mode by default when in markdown major mode, edit your ~/.spacemacs file, in the dotspacemacs/user section add the line (add-hook 'markdown-mode-hook 'turn-on-orgtbl).

Hope you have fun speeding up the writing of your Clojure code (and any other common text) in Spacemacs / Emacs.

Thank you.
@jr0cket

-1:-- YASnippets for Faster Clojure Coding (Post)--L0--C0--July 30, 2016 02:52 PM

Wilfred Hughes: Example Driven Development

“Hey $COLLEAGUE, is there any function that takes this list and returns a list like this?”

Some functions are hard to Google. It’s often easier to speak about concrete examples: I have a list '(x y z), and an index 1, and I want a list without the element at that position: '(x z).

I was blown away when I saw this feature implemented in Smalltalk. I decided to build an Emacs implementation and it’s super helpful when you need it. The screenshot above shows it in action.

Lisp Wins

This project is much easier in a language with little syntax. Suppose we’re looking for arithmetic functions:

suggest.el simply has a list of functions, and tries each one in turn. The fact that + is syntactically the same as any other function is a big help here. We don’t need to do any special formatting for infix functions.

Brute-Force Performance

suggest.el brute-force searches its list of functions. It ignores anything that throws an error, or returns a value different to the output requested.

We currently have a list of 140 functions. I was expecting this to be slow, but it’s instant.

We also need to try every permutation of arguments, which is computationally expensive. We want users to discover functions like nth, even if they get arguments in the wrong order. There are a lot of permutations, but typically users only use 1-3 arguments, so it’s not a problem.

If suggest.el find a match, then it doesn’t try any other orderings. This prevents us suggesting both (+ 2 3) and (+ 3 2) – the user would probably prefer the order they’ve proposed anyway.

Eval All The Way

suggest.el evals all the expressions given, allowing users to enter literals, variables, or even function expressions. This is convenient when developing new packages and you want to use values from your package.

In the above screenshot, note how the suggested expression (-sum (list 2 3 4)) uses exactly the expression given, so it can be copy-pasted. However, we show the final value => 9, so it’s clear what the function is doing.

Exploiting The Emacs UI

To take best advantage of Emacs, the UI needs to work like a text editor. suggest-mode derives from emacs-lisp-mode, so your favourite lisp packages just work. The entire buffer is a valid lisp file and we get highlighting for free.

suggest.el adds a few extra touches on top. We use overlays to highlight the headings, which overrides the comment highlighting. Headings and output also use the special property read-only to guide users into typing in the correct places.

suggest.el also uses change hooks (pictured above) to inform the user that they need to re-run suggest-update. This shows C-c C-c (the default keybinding) by default. Just like the Emacs tutorial, suggest.el will always use the current keybindings.

Choosing Functions

suggest.el has a whitelist of functions that are safe to run. Which functions should we include? suggest.el is in a position of responsibility, as it affects the code that users write.

Functions absolutely cannot have side-effects. Calling delete-file could be catastrophic. If a function only mutated its input arguments, that would be safe, but it’s not necessarily what the user expected.

Strictly requiring pure functions means that many built-in Emacs functions aren’t offered. Wherever possible, we suggest built-in functions, and show them first.

suggest.el has to decide which function aliases to show. I’ve been convincingly persuaded that predicate functions should use -p, so suggest.el prefers those aliases. suggest.el also favours cl-lib over the popular, but deprecated cl (e.g. cl-first not first).

We also have to decide which packages to include. suggest.el includes third-party packages that I consider important (dash.el, s.el and f.el). Long term, I hope packages will add to suggest-functions using eval-after-load.

Third-party packages often have a higher proportion of pure functions. In the case of f.el, I’ve included a few impure functions that read the filesystem, as they’re safe.

It’s also tricky to pick which functions belong in the whitelist. suggest.el tries to offer functions that you’re likely to ‘stumble across’.

I found that the best functions take 1-3 arguments of simple types. You’re unlikely to find a higher-order function from a random example. We also want functions that are characterised by a single example. Single-argument predicates aren’t much use, since they need several examples to demonstrate their behaviour.

We currently have functions for lists, alists, plists, hash tables, numbers, strings, symbols and paths. This covers much of my day-to-day development, and I’ve already learnt some new functions!

Give It A Try!

suggest.el is on GitHub, on MELPA, and I would love to hear your feedback. You can tweet at me or file an issue.

-1:-- Example Driven Development (Post Wilfred Hughes (me@wilfred.me.uk))--L0--C0--July 30, 2016 12:00 AM