Pragmatic Emacs: Auto Save and Backup Every Save

Emacs has two useful ways of protecting you from data loss. The first is auto save, which saves a copy of a file every so often while you are editing it. If some catastrophe caused you to close Emacs or shut down your machine without saving the file then you can use M-x recover-file to recover the file from its auto save. By default, the auto save files are saved in the same directory as the original file, and are given a name of the form #file#. This is fine for me, but you can configure this.

I like to make auto saves often, so I make the following tweaks to my emacs config file:

;; auto save often
;; save every 20 characters typed (this is the minimum)
(setq auto-save-interval 20)

When you save a file, the auto save file is deleted.

The other way Emacs protects you is to make backups of your files. By default the backup file is made in the same directory as the original with a name like file~. The way the backup works is that Emacs makes a copy of a file the first time you save it in an Emacs session. It only makes that one backup though, so this is not very useful if you keep your session running for a long time and want to recover an earlier version of a file.

The following code sets some general backup options and then configures Emacs to make a backup of a file every time you save it. The code builds on bits from here and here, and the comments should be quite self-explanatory.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; backup settings                                                        ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; https://www.emacswiki.org/emacs/BackupFiles
(setq
 backup-by-copying t     ; don't clobber symlinks
 kept-new-versions 10    ; keep 10 latest versions
 kept-old-versions 0     ; don't bother with old versions
 delete-old-versions t   ; don't ask about deleting old versions
 version-control t       ; number backups
 vc-make-backup-files t) ; backup version controlled files

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; backup every save                                                      ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; http://stackoverflow.com/questions/151945/how-do-i-control-how-emacs-makes-backup-files
;; https://www.emacswiki.org/emacs/backup-each-save.el
(defvar bjm/backup-file-size-limit (* 5 1024 1024)
  "Maximum size of a file (in bytes) that should be copied at each savepoint.

If a file is greater than this size, don't make a backup of it.
Default is 5 MB")

(defvar bjm/backup-location (expand-file-name "~/emacs-backups")
  "Base directory for backup files.")

(defvar bjm/backup-trash-dir (expand-file-name "~/.Trash")
  "Directory for unwanted backups.")

(defvar bjm/backup-exclude-regexp "\\[Gmail\\]"
  "Don't back up files matching this regexp.

Files whose full name matches this regexp are backed up to `bjm/backup-trash-dir'. Set to nil to disable this.")

;; Default and per-save backups go here:
;; N.B. backtick and comma allow evaluation of expression
;; when forming list
(setq backup-directory-alist
      `(("" . ,(expand-file-name "per-save" bjm/backup-location))))

;; add trash dir if needed
(if bjm/backup-exclude-regexp
    (add-to-list 'backup-directory-alist `(,bjm/backup-exclude-regexp . ,bjm/backup-trash-dir)))

(defun bjm/backup-every-save ()
  "Backup files every time they are saved.

Files are backed up to `bjm/backup-location' in subdirectories \"per-session\" once per Emacs session, and \"per-save\" every time a file is saved.

Files whose names match the REGEXP in `bjm/backup-exclude-regexp' are copied to `bjm/backup-trash-dir' instead of the normal backup directory.

Files larger than `bjm/backup-file-size-limit' are not backed up."

  ;; Make a special "per session" backup at the first save of each
  ;; emacs session.
  (when (not buffer-backed-up)
    ;;
    ;; Override the default parameters for per-session backups.
    ;;
    (let ((backup-directory-alist
           `(("." . ,(expand-file-name "per-session" bjm/backup-location))))
          (kept-new-versions 3))
      ;;
      ;; add trash dir if needed
      ;;
      (if bjm/backup-exclude-regexp
          (add-to-list
           'backup-directory-alist
           `(,bjm/backup-exclude-regexp . ,bjm/backup-trash-dir)))
      ;;
      ;; is file too large?
      ;;
      (if (<= (buffer-size) bjm/backup-file-size-limit)
          (progn
            (message "Made per session backup of %s" (buffer-name))
            (backup-buffer))
        (message "WARNING: File %s too large to backup - increase value of bjm/backup-file-size-limit" (buffer-name)))))
  ;;
  ;; Make a "per save" backup on each save.  The first save results in
  ;; both a per-session and a per-save backup, to keep the numbering
  ;; of per-save backups consistent.
  ;;
  (let ((buffer-backed-up nil))
    ;;
    ;; is file too large?
    ;;
    (if (<= (buffer-size) bjm/backup-file-size-limit)
        (progn
          (message "Made per save backup of %s" (buffer-name))
          (backup-buffer))
      (message "WARNING: File %s too large to backup - increase value of bjm/backup-file-size-limit" (buffer-name)))))

;; add to save hook
(add-hook 'before-save-hook 'bjm/backup-every-save)

Files are backed up to a customisable directory in subdirectories per-session once per Emacs session, and per-save every time a file is saved. You can specify a maximum file size for files that will be backed up, and a regular expression to specify files that will not be backed up. I use the latter to avoid making backups of my emails by using the regular expression \\[Gmail\\] which matches emails I compose with mu4e. You can set this to nil if you want to disable this.

-1:-- Auto Save and Backup Every Save (Post Ben Maughan)--L0--C0--May 23, 2016 08:30 PM

sachachua: 2016-05-23 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-05-23 Emacs News appeared first on sacha chua :: living an awesome life.

-1:-- 2016-05-23 Emacs News (Post Sacha Chua)--L0--C0--May 23, 2016 04:41 PM

Irreal: Not an Editor, Not an Operating System...

This is where its power really comes from.

-1:-- Not an Editor, Not an Operating System... (Post jcs)--L0--C0--May 23, 2016 02:21 PM

Marcin Borkowski: Literal values and destructive functions

In Lisp literature you can often find a warning about not using destructive functions (like sort or nconc) on values coming from literals. This is a good advice, and you should follow it. Here’s a short stab at a (partial) explanation (note that all examples are in Emacs Lisp).
-1:-- Literal values and destructive functions (Post)--L0--C0--May 23, 2016 05:02 AM

Grant Rettke: Three Ways to Quote in your Notes with Org-Mode

Here are three ways that I might want to quote content in my personal notes with Org-Mode:

My friends really might want to know how.

-1:-- Three Ways to Quote in your Notes with Org-Mode (Post Grant)--L0--C0--May 23, 2016 01:49 AM

Chen Bin (redguardtoo): Complete line with ivy-mode

Complete current line by git grep and ivy-mode.

(defun counsel-escape (keyword)
  (setq keyword (replace-regexp-in-string "\\$" "\\\\\$" keyword))
  (replace-regexp-in-string "\"" "\\\\\"" keyword))

(defun counsel-replace-current-line (leading-spaces content)
  (beginning-of-line)
  (kill-line)
  (insert (concat leading-spaces content))
  (end-of-line))

(defun counsel-git-grep-complete-line ()
  (interactive)
  (let* (cmd
        (cur-line (buffer-substring-no-properties (line-beginning-position)
                                                  (line-end-position)))
        (default-directory (locate-dominating-file
                            default-directory ".git"))
        keyword
        (leading-spaces "")
        collection)
    (setq keyword (counsel-escape (if (region-active-p)
                                      (buffer-substring-no-properties (region-beginning)
                                                                      (region-end))
                                    (replace-regexp-in-string "^[ \t]*" "" cur-line))))
    ;; grep lines without leading/trailing spaces
    (setq cmd (format "git --no-pager grep -I -h --no-color -i -e \"^[ \\t]*%s\" | sed s\"\/^[ \\t]*\/\/\" | sed s\"\/[ \\t]*$\/\/\" | sort | uniq" keyword))
    (when (setq collection (split-string (shell-command-to-string cmd) "\n" t))
      (if (string-match "^\\([ \t]*\\)" cur-line)
          (setq leading-spaces (match-string 1 cur-line)))
      (cond
       ((= 1 (length collection))
        (counsel-replace-current-line leading-spaces (car collection)))
       ((> (length collection) 1)
        (ivy-read "lines:"
                  collection
                  :action (lambda (l)
                            (counsel-replace-current-line leading-spaces l))))))
    ))
(global-set-key (kbd "C-x C-l") 'counsel-git-grep-complete-line)

I also tried grep which is too slow for my project.

-1:-- Complete line with ivy-mode (Post Chen Bin)--L0--C0--May 23, 2016 01:41 AM

Mark Hershberger: Making git and Emacs’ eshell work together

tl;dr

I often end up in eshell.

Sometimes, because I’m running Emacs on Windows (where shells work, but it’s a pain), and sometimes just because.  The problem, until today, was that anytime I would invoke a git command that wanted to call the pager (say, diff), I would see the following annoying message from less:

WARNING: terminal is not fully functional
-  (press RETURN)

This happens because eshell sets $TERM to “dumb”.  It doesn’t try to fool anyone.  It’s dumb.

But, since I’m stubborn and lazy, I just put up with it the stupidity of eshell and the annoyance of git’s invocation of less.  Till today.

Some would say the answer is “Don’t use git in emacs — use magit!” And they’d be right. I do use magit, but commands should work, too.

So, after a spree of productivity yesterday, I woke up today and hit that annoying message again.  I decided to track it down.

I came across this StackOverflow thread. There is a hint there — I didn’t know less could be told to only page in certain cases — but not anything that says “only sometimes use less”.

So I managed to hack something together:

git config --global core.pager '`test "$TERM" = "dumb" && echo cat || echo less`'

I haven’t tried this under Windows, yet, but I’m hoping it works.

Image CC-by-SA: Richard Bartz, Munich Makro Freak

-1:-- Making git and Emacs’ eshell work together (Post hexmode)--L0--C0--May 22, 2016 04:30 PM

punchagan: blog-admin and Nikola

Another post about blogging.

blog-admin now supports Nikola, thanks to yours truly. blog-admin is an Emacs package by CodeFalling that lets you view and manage your (static site generated) blog from within inside Emacs.

Nikola's command line utility is pretty nifty and does a bunch of useful things. I had a few utility functions to do common tasks like create new post and deploy blog. This worked well, but moment I came across this blog-admin's tabular view, I was sold!

org2blog (a blogging tool I used previously) had a tracking file that kept track of all the posts I made, and I used it quite a bit for navigation – thanks to org-mode's search functionality. The tabular view of blog-admin is even better! I really like the fact that the author has tried to keep the package generic enough to support any blog, and adding support for Nikola has been quite easy.

The filtering functionality is crude, but good enough for a start. One thing I want to add is a preview functionality for drafts. Showing some (writing) statistics would also be nice – No. posts in the last month, total published posts, etc. No promises, but you may see some of these things, soon. :)

-1:-- blog-admin and Nikola (Post punchagan)--L0--C0--May 21, 2016 02:58 PM

Pragmatic Emacs: Jump to matching parenthesis

With the cursor on an opening parenthesis ([{ etc, use C-M-n to jump to the matching closing one. This works even if there are nested parentheses. You can use C-M-p to go back.

Emacs has other ways of moving by parentheses, but this is the one I find most useful.

-1:-- Jump to matching parenthesis (Post Ben Maughan)--L0--C0--May 20, 2016 08:11 PM

Raimon Grau: emacs 25.1 NEWS

emacs 25.1 is around the corner, and I've been browsing the NEWS file for interesting improvements. Here's my selection of the most important ones. Enjoy!
-1:-- emacs 25.1 NEWS (Post Raimon Grau (noreply@blogger.com))--L0--C0--May 20, 2016 02:12 PM

Irreal: Count Days Between Dates

Álvaro Ramírez points out that Emacs has the built-in capability to calculate the number of days between two dates. It's easy to do; the tl;dr is:

M-x calendar
<mark the region between the two dates (inclusive)>
M-= (or M-x calendar-count-days-region)

Ramírez has some animated screen shots that show how it works and also a shortcut for going to the endpoints of the date range.

It's a nice trick and it's all already there. Read the post and try it out.

-1:-- Count Days Between Dates (Post jcs)--L0--C0--May 19, 2016 07:44 PM

Phillip Lord: Emacs Testing with Assess

Assess is my new package supporting testing in Emacs. It has grown out of my frustration with the existing framework while building the lentic package [1].

For quite a while, the only testing framework in Emacs has been ERT (the Emacs Regression Testing tool) which is part of core. More recently, there have been a number of new ones arriving. For example, buttercup and ecukes both provide behaviour driven testing, rather like Jasmine or Cucumber respectively. Both worth looking at — I’ve used Ecukes for testing Cask, and it’s nicely implemented and very usable. Assess is rather less radical than this though. It focuses on providing a general set of tools for testing, mostly in terms of some macros and predicates that should be useful.

For example, a recurrent problem during the development of lentic was ensuring that no buffers were left around after a test. Particularly when a test fails, this can lead to unexpected failures in later tests. For this purpose, I have added a macro called assess-with-preserved-buffer-list. Any buffers at all created inside this macro will be removed after. Hence this:

(assess-with-preserved-buffer-list
  (get-buffer-create "a")
  (get-buffer-create "b")
  (get-buffer-create "c"))

Which preserves the buffer state. a, b and c will be removed after the macro exits.

Assess also provides some handy predicates for testing. So, we can compare the contents of strings, buffer and files easily. For example:

;; Compare Two Strings
(assess= "hello" "goodbye")

;; Compare the contents of Two Buffers
(assess=
  (assess-buffer "assess.el")
  (assess-buffer "assess-previous.el"))

;; Compare the contents of Two files
(assess=
  (assess-file "~/.emacs")
  (assess-file "~/.emacs"))

Again, this has all been done carefully to avoid changing state. The last example, should work whether ~/.emacs is open already or not, and will not result in new buffer creation.

As well as string comparison, we can also check that indentation is working correctly. This example, for instance, takes a indented string, un-indents and re-indents according to a specific mode, then checks that nothing has changed.

(assess-roundtrip-indentation=
  'emacs-lisp-mode
  "(assess-with-find-file\n    \"~/.emacs\"\n  (buffer-string))")

Likewise, we can check fontification with the assess-face-at= function. In this case, we are checking that three words get highlighted correctly.

(assess-face-at=
 "(defun x ())\n(defmacro y ())\n(defun z ())"
 'emacs-lisp-mode
 '("defun" "defmacro" "defun")
 'font-lock-keyword-face)

Finally, in terms of test functions, I have recently added two new pieces of functionality. Call capturing was an idea I stole from buttercup — this is a non-interative equivalent to the function tracing, returning parameters and return values to a function call.

(assess-call-capture
  '+
  (lambda()
    (+ 1 1)))
;; => (((1 1) . 2))

And discover provides a drop in replacement for ert-run-tests-batch-and-exit except that it automatically finds and loads test files, based on a set of heuritstics. I’ve already started to use this instead of ert-runner, as it requires no configuration.

The final thing I wanted to address was better reporting. While everything described so far as test environment agnostic, I’ve only managed to advance reporting for ERT. All of the functions that I have written plug into ERT, so produce richer output. So instead of:

F temp
    (ert-test-failed
     ((should
       (string= "a" "b"))
      :form
      (string= "a" "b")
      :value nil))

When comparing "a" and "b", this output is fine, but if the strings are more complex (say, for example, the a short piece of code that you expect to indent in a certain way), it is hard to work out what the differences are.

So, assess extends ERT so that that it now calls diff on the strings. We now get this explanation instead:

F test-assess=
    (ert-test-failed
     ((should
       (assess= "a" "b"))
      :form
      (assess= "a" "b")
      :value nil :explanation "Strings:
a
and
b
Differ at:*** /tmp/a935uPW      2016-01-20 13:25:47.373076381 +0000
--- /tmp/b9357Zc        2016-01-20 13:25:47.437076381 +0000
***************
*** 1 ****
! a
\\ No newline at end of file
--- 1 ----
! b
\\ No newline at end of file

"))

Verbose for sure, but very useful for identifying issues, especially white space related. By default, this uses the diff command, but this is also extensible, and has a simple fallback in its absence.

There is more functionality to assess than that shown here: it can create multiple temporary buffers in a single scope; it can create “related” temporary files, prevent conflicts if files are already open; it can re-indent the contents of files rather than buffers, and so on. I think assess is a nice addition to the testing capabilities of Emacs.

More is needed and some of this involve changes to Emacs core — packages which are noisy, enforce interactivity, and so forth. I would also like to add support for “robotized” tests running keyboard macros, tests for checking hooks, output to the message buffer, and testing for asynchronous call backs. But assess is quick, easy to use and makes testing of many features of Emacs much easier. I’ve started to use it in my own packages, and will eventually use it in all of them.

My plans for the future are to move assess to ELPA, and then eventually to Emacs core after 25.1, probably as ert-assess. I hope that along with my restructuring of the Emacs unit tests files, this will make testing of Emacs core simpler and more straight forward; if it does this should make the merge hassles (mostly to other people, sadly) caused by file moves worthwhile. Emacs will be easier to develop, and simpler to change.

Feedback is, as always, welcome.

References

  1. P. Lord, "lentic 0.9", An Exercise in Irrelevance, 2015. http://www.russet.org.uk/blog/3071
-1:-- Emacs Testing with Assess (Post Phillip Lord)--L0--C0--May 18, 2016 01:18 PM

Ben Simon: The KenKen Solutiont that Can't

Mark over at brainwagon recounted his frustration with an especially tricky KenKen puzzle and like any good programmer turned to a software solution:

Lately, my lunch hours have been spent working on the NYT Crossword with my lunch companion Tom. While I find that the Thursday crosswords are often beyond my ability to do in the allotted time, between the two of us, more often than not we manage to plow through them. Slowly over time, we’ve begun to solve them slightly quicker, so I’ve branched out to doing the KenKen puzzles.
...
By the end up twenty minutes I was annoyed, knew I had made a mistake, but decided to give into the urge to write a program to solve it. How long could it take?

Well, the answer was about 27 minutes.

Well Mark, Challenge Accepted.

After reading his post (and without looking at his solution) I decided I needed to create my own KenKen solver. I busted out my Samsung Galaxy Note 5, Perixx keyboard and a new app configuration: Termux + emacs + TinyScheme and went to work.

After a weekend of thinking through a solution, I had my solver written up fairly quickly:

;; http://brainwagon.org/2016/05/12/kenken-puzzle-solver/

(define (show . words)
  (for-each (lambda (w)
       (display w)
       (display " "))
     words)
  (newline))

(define (unique? items)
  (if (null? items)
      #t
      (and (not (member (car items) (cdr items)))
    (unique? (cdr items)))))

(define (solved? puzzle)
  (not (member '? puzzle)))

(define (blank-puzzle n)
  (if (= 0 n)
      '()
      (cons '? (blank-puzzle (- n 1)))))

(define (try sym puzzle)
  (if (null? puzzle)
      (error (format "Whoa, can't try ~a in a blank puzzle" sym))
      (if (eq? (car puzzle) '?)
   (cons sym (cdr puzzle))
   (cons (car puzzle)
  (try sym (cdr puzzle))))))

(define (ok? puzzle constraints)
  (if (null? constraints)
      #t
      (let* ((params (map (lambda (i) (list-ref puzzle i))
     (car (car constraints))))
      (valid? (if (solved? params)
    (apply (cdr (car constraints)) params)
    #t)))
 (and valid? (ok? puzzle (cdr constraints))))))


(define (solve puzzle dictionary constraints)
  (define (go puzzle pool)
    (cond ((solved? puzzle)
    puzzle)
   ((null? pool) #f)
   (else
    (let* ((next-attempt (try (car pool) puzzle))
    (valid (and (ok? next-attempt constraints)
         (go next-attempt dictionary))))
      (if valid
   valid
   (begin
     ;; (show "Rejecting:" next-attempt)
     (go puzzle (cdr pool))))))))
  (go puzzle dictionary))

(define (uni . args)
  (unique? args))

(define (is op val)
  (lambda args
    (or (= val (apply op args))
 (= val (apply op (reverse args))))))

The program works by taking in a blank puzzle, a dictionary of values to solve with (in a 4x4 puzzle, that would be (1 2 3 4)) and a set of constraints and does a brute force attack to find a combination of symbols that satisfy all the constraints. KenKen puzzles assume that all rows and columns are unique and that clusters of cells either add, subtract, multiply or divide to form a particular value; these form my constraints.

Here's the code to solve a 3x3 puzzle:

(define kk-3x3-cons
  `(((0 1 2) . ,uni)
    ((3 4 5) . ,uni)
    ((6 7 8) . ,uni)
    ((0 3 6) . ,uni)
    ((1 4 7) . ,uni)
    ((2 5 8) . ,uni)))

(define kk-p1-cons
  `(((0 3) . ,(is + 3))
    ((2 5 4) . ,(is + 8))
    ((7 8) . ,(is + 3))
    ((6) . ,(is + 3))
    ((1) . ,(is + 1))))

(define kk-3x3-dict '(1 2 3))


(solve (blank-puzzle 9) kk-3x3-dict (append kk-3x3-cons kk-p1-cons))

For clarity, the first set of constraints ensure that every row and column is unique, whereas the second set of constraints describe this particular puzzle. For example, grid entries 2, 5 and 4 must add up to 8.

One compromise I made was to have the solver work in terms of a list rather than a grid. The result was that I had to create little paper maps to help me translate from grid to list coordinates:

For 3x3 and 4x4 puzzles my little solution worked. In fact, I spent more time debugging typos in my transcription of constraints than I did in writing the actual core solution. Here's some proof that this actually runs on my cell phone:

Unfortunately, my brute-force solution just doesn't cut it for the 6x6 puzzle Mark was working on. I setup the constraints and kicked the program off:

(define kk-6x6-cons
  `(((00 01 02 03 04 05) . ,uni)
    ((06 07 08 09 10 11) . ,uni)
    ((12 13 14 15 16 17) . ,uni)
    ((18 19 20 21 22 23) . ,uni)
    ((24 25 26 27 28 29) . ,uni)
    ((30 31 32 33 34 35) . ,uni)
    ((00 06 12 18 24 30) . ,uni)
    ((01 07 13 19 25 31) . ,uni)
    ((02 08 14 20 26 32) . ,uni)
    ((03 09 15 21 27 33) . ,uni)
    ((04 10 16 22 28 34) . ,uni)
    ((05 11 17 23 29 35) . ,uni)))

(define kk-6x6-dict '(1 2 3 4 5 6))

(define kk-p4-cons
  `(((0 1 6) . ,(is * 12))
    ((2 3 4) . ,(is + 11))
    ((5 11)    . ,(is + 7))
    ((17 23 29) . ,(is + 8))
    ((28 34 35) . ,(is * 72))
    ((27 33) . ,(is + 5))
    ((32) . ,(is + 3))
    ((30 31) . ,(is - 1))
    ((12 18 24 25) . ,(is + 12))
    ((13 19) . ,(is / 2))
    ((20 26) . ,(is / 2))
    ((14 15 16 10) . ,(is + 19))
    ((9) . ,(is + 3))
    ((7 8) . ,(is - 5))
    ((21 22) . ,(is - 5))))

(solve (blank-puzzle 36) kk-6x6-dict (append kk-p4-cons kk-6x6-cons))

I enabled some debugging and got a whole lot of this:

After hours of waiting for a solution to be spit out, I finally killed the process. Would it eventually complete and give me the answer? Did I have a bug in my constraints or program that insures it won't even give me an answer? I don't know. But for now, I need to put this problem down and return to it when I'm ready to try a new approach.

Mark, my hat is off to you for your 27 minute solution that completes in 1 millisecond! You da man!

While I don't have my solution yet, this was hardly a bust. A few positive notes:

  • A brute force recursive solution was surprisingly easy to write for this sort of problem, and for small enough problem sets, works well. You essentially leverage the interpreter to gain access to backtracking, rather than needing to build it out explicitly.
  • Scheme sexpr's make an ideal 'UI' to this sort of problem, with the constraints being comparably easy to read and write without any additional coding effort.
  • Termux is sweet. I'm not sure it's going to replace GNURoot, but it's certainly a top notch option. The API opens up some impressive scripting options I'm going to have to explore in another post.
  • TinyScheme is a beast. I threw this massive recursive problem at it and it just chugged away. I let the program spin for hours, and it didn't bat an eye. I suppose that's what Tail Call Optimization is all about, but still, it's remarkable to see it in action.
  • The solution I came up with is nice and flexible and should work for related puzzles, such as Sudoku. I hope I can keep this general constraint solving nature while also gaining some critical speed.

So yeah, KenKen 1, Ben 0. But this isn't over. I'll be back.

-1:-- The KenKen Solutiont that Can't (Post Ben Simon (noreply@blogger.com))--L0--C0--May 18, 2016 11:59 AM

Alex Schroeder: Renaming Files

I had a bunch of files named like this, from various albums.

Cure - [1984] The top - 01 - Shake dog shake.mp3
Cure - [1984] The top - 02 - Bird mad girl.mp3
Cure - [1984] The top - 03 - Wailing wall.mp3

I wanted to move them into subdirectories, one for each album.

(dolist (file (directory-files "c:/Users/asc/Music/The Cure" t "\\.mp3$"))
  (let* ((name (file-name-nondirectory file))
	 (data (split-string name " - "))
	 (album (nth 1 data)))
    (unless (file-directory-p (concat "c:/Users/asc/Music/The Cure/" album))
      (make-directory (concat "c:/Users/asc/Music/The Cure/" album)))
    (rename-file file (concat "c:/Users/asc/Music/The Cure/" album "/" name))))

Tags: RSS

-1:-- Renaming Files (Post)--L0--C0--May 18, 2016 07:26 AM

Chen Bin (redguardtoo): Make Messages Buffer modifiable in Emacs 24.4

Insert below code into the beginning of ~/.emacs because any part of .emacs may create Messages Buffer instance.

(when (boundp 'messages-buffer-mode-hook)
  (defun messages-buffer-mode-hook-setup ()
    (read-only-mode -1))
  (add-hook 'messages-buffer-mode-hook 'messages-buffer-mode-hook-setup))
-1:-- Make Messages Buffer modifiable in Emacs 24.4 (Post Chen Bin)--L0--C0--May 18, 2016 12:42 AM

Endless Parentheses: Locally configure or disable show-paren-mode

show-paren-mode is a minor-mode that highlights the bracket at point (be it round, square, or curly) as well as its corresponding open/close counterpart. I find it a must-have for Elisp and Clojure programming. On the other hand, when editing Ruby code, it also highlights whole block delimiters, like def, do, if, and end, and all that must-haviness quickly turns into in-your-faceviness.

The catch here is that show-paren-mode is a global minor-mode. So you can’t just enable it locally in lisp-mode-hook, and if you try to do (show-paren-mode -1) in ruby-mode-hook you’re going to disable it globally every time you visit a ruby file.

Fortunately, show-paren-function checks the value of the variable show-paren-mode, so we can pseudo-disable it by setting this variable locally.

(show-paren-mode 1)

(defun endless/locally-disable-show-paren ()
  (interactive)
  (setq-local show-paren-mode nil))

(add-hook 'ruby-mode-hook
          #'endless/locally-disable-show-paren)

With this, the mode will still be active in ruby-mode buffers, but it won’t actually do anything.

Alternatively, you could reset show-paren-data-function to its original value (also inside ruby-mode-hook). This will keep only the basic bracket highlighting.

(setq-local show-paren-data-function #'show-paren--default)

Comment on this.

-1:-- Locally configure or disable show-paren-mode (Post)--L0--C0--May 18, 2016 12:00 AM

Marcin Borkowski: Emacs Lisp closures demystified

It is often claimed that one of the advantages of closures (as in “lexical scoping”) is information hiding (a.k.a. encapsulation). This is true, but as this post shows, you can’t really hide anything in Emacs Lisp;-).
-1:-- Emacs Lisp closures demystified (Post)--L0--C0--May 17, 2016 05:49 PM

Grant Rettke: Emacs Keyboard Design 37: Possible

  • Small changes to a 104 key ANSI skyrocket the price
  • Stay close to the standard to make it affordable

keyboard-layout-37.png

  • Start with the ANSI 104 preset
  • Delete the numpad to make it a tenkeyless
  • Make the spacebar 6w, they do exist
  • Make Ctrl, Win, Menu 1w
    • Make them Emacs keys, with the front text the real key code
  • Difficult to press shift-C-M-s-H, so add Ultra
    • C-M-s-H is easily done
  • Place Alt and Gui below Delete and End
  • Meh key below PgDn
    • No better name, this is the standard
    • Control-Alt-Shift
  • Fn below Alt for F13-F24
    • For anything more, makes sense
    • Faster than toggling to a layer
    • Add mouse keys here maybe
  • Layer below Meh
    • Easily toggle to any particular layer
    • Don’t need individual keys for them
  • Thoughts
    • Can buy keycap set from any MX compatible provider (nearly all of them)
      • Costs less
    • Pay for a 104 key keycap set and repurpose the numpad keys as Emacs keys
      • Costs less
    • Sticks with 6 rows
      • Keys at correct height
    • OS and Emacs keys can happily and easily coexist
    • Fn and Layer handle just about everything
-1:-- Emacs Keyboard Design 37: Possible (Post Grant)--L0--C0--May 17, 2016 02:03 AM

sachachua: 2016-05-16 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-05-16 Emacs News appeared first on sacha chua :: living an awesome life.

-1:-- 2016-05-16 Emacs News (Post Sacha Chua)--L0--C0--May 16, 2016 04:34 PM

Alex Schroeder: Gmail, Gnus, GPG Guide Update

I updated my Gmail, Gnus, GPG Guide. It now includes all the stuff about setting up the GPG Agent.

The GPG Agent is a service that will remember your passphrase for a short while. If you don’t use it, Gnus will ask you for your passphrase for every backend it uses (because it needs to log in) and for every encrypted mail you read and for every encrypted mail you send. You’ll be typing your passphrase a lot. You want to use it.

Please let me know if you tried to follow the instructions and it didn’t work. I’d like to make the instructions very easy to follow and troubleshoot. So if you missed something and ran into errors, I’d still like to know so that I can start adding typical problems people might have and how to resolve them.

And finally, feel free to test this system by sending me encrypted email! See Contact for more.

Tags: RSS RSS RSS

-1:-- Gmail, Gnus, GPG Guide Update (Post)--L0--C0--May 15, 2016 11:35 AM

Raimon Grau: Asymmetry on searching

Recently I started using helm-occur as a default for c-s. It has some nice things like searching for the word at point, which many times is what you want to do [1].  But it also has its drawbacks.

  • One of them is speed. For big buffers it can be quite slow [2].  
  • Also,when there's more than one match in a line, you can't easily keep pressing c-s and move along the matches.
  • If the matches far in long lines, you don't see them. Can't decide where to stop when lines are similar at start.
  • It doesn't work as a navigation tool [3].

Try to open a giant xml file (all in one line), and work with it. You'll understand it.


But! it's not all lost yet. I found out that if I keep c-r as isearch-backward, I can then press c-s and be in the good old isearch. So you get both functionalities, and the keybindings are not confusing. you just have to remember that sometimes, the fastest way to move forward is to go backwards.




[1]. that same functionality can be done with '*' in evil (but you'll have to configure syntax tables to make it match the whole word instead of symbol). Also, pressing c-w on isearch-mode will add next word to the searched content.

[2]. Some say ivy is faster, but the times I tried m-x ivy-mode, it takes over the whole emacs input system. Probably I should invest more time on learning how to activate it just for buffer searches.

[3]. And I don't buy the yak shaving 'you should use ace-jump', because its aim is not the same (doesn't work to move where you WANT but don't SEE), and now I have 2 problems.
-1:-- Asymmetry on searching (Post Raimon Grau (noreply@blogger.com))--L0--C0--May 13, 2016 04:25 PM

William Denton: Conforguring dotfiles

I’ve added my dotfiles to Conforguration: they are there as raw files in the dotfiles directory, and conforguration.org has code blocks that will put them in place on localhost or remote machines.

I did some general cleanup to the file as well. There’s a lot of duplication, which I think some metaprogramming might fix, but for now it works and does what I need. My .bashrc is now finally the same everywhere (custom settings go in .bash.$HOSTNAME.rc) which is a plus.

-1:-- Conforguring dotfiles (Post William Denton)--L0--C0--May 10, 2016 02:24 PM

Endless Parentheses: validate.el: Schema validation for Emacs-Lisp

Emacs’ customizable variables (a.k.a., defcustom) are allowed to specify a :type parameter for setting its custom-type. The customize interface uses this information to produce a sophisticated menu for the user to customize that variable. However, a large fraction of users use setq to directly edit custom variables, and even some packages programmatically change the value of other package’s custom variables. Ultimately, there are no guarantees that the value in question matches the :type specified in the variable.

validate.el tries to address that by offering a small set of functions and macros to validate that a value matches a :type schema, throwing an error when it doesn’t. Most importantly, in case of error it provides very informative messages about what part of the value failed to validate. So, instead of getting some obscure wrong-type-argument error deep down in the code, you’ll get a message like the following as soon as the variable is used:

Looking for ‘(repeat (choice string number))’ in ‘("aa" 90 la)’ failed because:
Looking for ‘(choice string number)’ in ‘la’ failed because:
  all of the options failed
    Looking for ‘string’ in ‘la’ failed because:
      not a string
    Looking for ‘number’ in ‘la’ failed because:
      not a number

There are 3 main use-cases for this:

  1. As an end-user of a package, you can use validate-setq instead of setq for editing variables. This will ensure the configuration you provide matches the schema specified by the developer, and thus prevents you from misconfiguring stuff.

    Also note that this works on any defcustom defined with a :type. That is, it doesn’t matter if the package itself uses validate.el.

  2. As a developer, when using a variable, use (validate-variable 'var-name). This will be identical to just using var-name if the value passes validation, but will immediately throw an error if it doesn’t.
  3. Also as a developer, you can call (validate-mark-safe-local 'var-name) which will create a safe-local predicate for the variable whenever the local value satisfies its schema.

validate.el is available on GNU Elpa, so you can install it from the package-menu or add it as a dependency in your package.

;; Package-Requires: ((validate "0.3"))

Comment on this.

-1:-- validate.el: Schema validation for Emacs-Lisp (Post)--L0--C0--May 10, 2016 12:00 AM

William Denton: Conforguration

Conforguration is a basic working example of configuration management in Org. I use source code blocks and tangling to make shell scripts that get synced to a remote machine and then download, install and configure R from source.

Trees

conforguration.org (that’s a file, not a site) has all the code. It really did work for me, and it might work for you. Is this a reasonable way of doing configuration management? I don’t know, but it’s worth trying. I’ll add things as I come across them.

I don’t know anything about formal configuration management, and I’ve never done literate programming and tangling in Org before. Anyone who’s interested in having a go at conforguring something else is most welcome to do so!

-1:-- Conforguration (Post William Denton)--L0--C0--May 05, 2016 04:09 AM

emacspeak: Emacspeak 44.0 (SteadyDog) Unleashed


Emacspeak 44.0—SteadyDog—Unleashed!

For Immediate Release:


San Jose, Calif., (May 1, 2016)
Emacspeak: Redefining Accessibility In The Era Of (Real)Intelligent Computing
–Zero cost of Ownership makes priceless software Universally affordable!


Emacspeak Inc (NASDOG: ESPK) --http://emacspeak.sf.net– announces the
immediate world-wide availability of Emacspeak 44.0 (SteadyDog) –a
powerful audio desktop for leveraging today's evolving data, social
and service-oriented Internet cloud.


1 Investors Note:

With several prominent tweeters expanding coverage of
#emacspeak, NASDOG: ESPK has now been consistently trading over
the social net at levels close to that once attained by DogCom
high-fliers—and as of May 2016 is trading at levels close to
that achieved by once better known stocks in the tech sector.


2 What Is It?

Emacspeak is a fully functional audio desktop that provides complete
eyes-free access to all major 32 and 64 bit operating environments. By
seamlessly blending live access to all aspects of the Internet such as
Web-surfing, blogging, social computing and electronic messaging into
the audio desktop, Emacspeak enables speech access to local and remote
information with a consistent and well-integrated user interface. A
rich suite of task-oriented tools provides efficient speech-enabled
access to the evolving service-oriented social Internet cloud.


3 Major Enhancements:

  • Enable playing multiple media streams using mplayer. 🔊
  • Smart Ladspa effects in mplayer, including panning. 🕪
  • Sound theme chimes has been spatialized to create theme pan-chimes. 🕭-
  • Package elpy has been speech-enabled. 🐍
  • Emacspeak now implements automatic soundscapes. 🏙
  • Speech-enables package helm.𝍎
  • Emacs EWW: Consume Web content efficiently. 🕷
  • Updated Info manual 🕮
  • emacspeak-url-templates: Smart Web access. ♅
  • emacspeak-websearch.el Find things fast. ♁
  • And a lot more than wil fit this margin. …

4 Establishing Liberty, Equality And Freedom:

Never a toy system, Emacspeak is voluntarily bundled with all
major Linux distributions. Though designed to be modular,
distributors have freely chosen to bundle the fully integrated
system without any undue pressure—a documented success for
the integrated innovation embodied by Emacspeak. As the system
evolves, both upgrades and downgrades continue to be available at
the same zero-cost to all users. The integrity of the Emacspeak
codebase is ensured by the reliable and secure Linux platform
used to develop and distribute the software.


Extensive studies have shown that thanks to these features, users
consider Emacspeak to be absolutely priceless. Thanks to this
wide-spread user demand, the present version remains priceless
as ever—it is being made available at the same zero-cost as
previous releases.


At the same time, Emacspeak continues to innovate in the area of
eyes-free social interaction and carries forward the
well-established Open Source tradition of introducing user
interface features that eventually show up in luser environments.


On this theme, when once challenged by a proponent of a crash-prone
but well-marketed mousetrap with the assertion "Emacs is a system from
the 70's", the creator of Emacspeak evinced surprise at the unusual
candor manifest in the assertion that it would take popular
idiot-proven interfaces until the year 2070 to catch up to where the
Emacspeak audio desktop is today. Industry experts welcomed this
refreshing breath of Courage Certainty and Clarity (CCC) at a time
when users are reeling from the Fear Uncertainty and Doubt (FUD)
unleashed by complex software systems backed by even more convoluted
press releases.


5 Independent Test Results:

Independent test results have proven that unlike some modern (and
not so modern) software, Emacspeak can be safely uninstalled without
adversely affecting the continued performance of the computer. These
same tests also revealed that once uninstalled, the user stopped
functioning altogether. Speaking with Aster Labrador, the creator of
Emacspeak once pointed out that these results re-emphasize the
user-centric design of Emacspeak; "It is the user –and not the
computer– that stops functioning when Emacspeak is uninstalled!".


5.1 Note from Aster,Bubbles and Tilden:

UnDoctored Videos Inc. is looking for volunteers to star in a
video demonstrating such complete user failure.


6 Obtaining Emacspeak:

Emacspeak can be downloaded from GitHub –see
https://github.com/tvraman/emacspeak you can visit Emacspeak on the
WWW at http://emacspeak.sf.net. You can subscribe to the emacspeak
mailing list — emacspeak@cs.vassar.edu — by sending mail to the
list request address emacspeak-request@cs.vassar.edu. The Emacspeak
Blog
is a good source for news about recent enhancements and how to
use them.


The latest development snapshot of Emacspeak is always available via
Git from GitHub at
Emacspeak GitHub .


7 History:

  • Emacspeak 44.0 continues the steady pace of innovation on the
    audio desktop.
  • Emacspeak 43.0 brings even more end-user efficiency by leveraging the
    ability to spatially place multiple audio streams to provide timely
    auditory feedback.
  • Emacspeak 42.0 while moving to GitHub from Google Code continues to
    innovate in the areas of auditory user interfaces and efficient,
    light-weight Internet access.
  • Emacspeak 41.0 continues to improve
    on the desire to provide not just equal, but superior access —
    technology when correctly implemented can significantly enhance the
    human ability.
  • Emacspeak 40.0 goes back to Web basics by enabling
    efficient access to large amounts of readable Web content.
  • Emacspeak 39.0 continues the Emacspeak tradition of increasing the breadth of
    user tasks that are covered without introducing unnecessary
    bloatware.
  • Emacspeak 38.0 is the latest in a series of award-winning
    releases from Emacspeak Inc.
  • Emacspeak 37.0 continues the tradition of
    delivering robust software as reflected by its code-name.
  • Emacspeak 36.0 enhances the audio desktop with many new tools including full
    EPub support — hence the name EPubDog.
  • Emacspeak 35.0 is all about
    teaching a new dog old tricks — and is aptly code-named HeadDog in
    on of our new Press/Analyst contact. emacspeak-34.0 (AKA Bubbles)
    established a new beach-head with respect to rapid task completion in
    an eyes-free environment.
  • Emacspeak-33.0 AKA StarDog brings
    unparalleled cloud access to the audio desktop.
  • Emacspeak 32.0 AKA
    LuckyDog continues to innovate via open technologies for better
    access.
  • Emacspeak 31.0 AKA TweetDog — adds tweeting to the Emacspeak
    desktop.
  • Emacspeak 30.0 AKA SocialDog brings the Social Web to the
    audio desktop—you cant but be social if you speak!
  • Emacspeak 29.0—AKAAbleDog—is a testament to the resilliance and innovation
    embodied by Open Source software—it would not exist without the
    thriving Emacs community that continues to ensure that Emacs remains
    one of the premier user environments despite perhaps also being one of
    the oldest.
  • Emacspeak 28.0—AKA PuppyDog—exemplifies the rapid pace of
    development evinced by Open Source software.
  • Emacspeak 27.0—AKA
    FastDog—is the latest in a sequence of upgrades that make previous
    releases obsolete and downgrades unnecessary.
  • Emacspeak 26—AKA
    LeadDog—continues the tradition of introducing innovative access
    solutions that are unfettered by the constraints inherent in
    traditional adaptive technologies.
  • Emacspeak 25 —AKA ActiveDog
    —re-activates open, unfettered access to online
    information.
  • Emacspeak-Alive —AKA LiveDog —enlivens open, unfettered
    information access with a series of live updates that once again
    demonstrate the power and agility of open source software
    development.
  • Emacspeak 23.0 – AKA Retriever—went the extra mile in
    fetching full access.
  • Emacspeak 22.0 —AKA GuideDog —helps users
    navigate the Web more effectively than ever before.
  • Emacspeak 21.0
    —AKA PlayDog —continued the
    Emacspeak tradition of relying on enhanced
    productivity to liberate users.
  • Emacspeak-20.0 —AKA LeapDog —continues
    the long established GNU/Emacs tradition of integrated innovation to
    create a pleasurable computing environment for eyes-free
    interaction.
  • emacspeak-19.0 –AKA WorkDog– is designed to enhance
    user productivity at work and leisure.
  • Emacspeak-18.0 –code named
    GoodDog– continued the Emacspeak tradition of enhancing user
    productivity and thereby reducing total cost of
    ownership.
  • Emacspeak-17.0 –code named HappyDog– enhances user
    productivity by exploiting today's evolving WWW
    standards.
  • Emacspeak-16.0 –code named CleverDog– the follow-up to
    SmartDog– continued the tradition of working better, faster,
    smarter.
  • Emacspeak-15.0 –code named SmartDog–followed up on TopDog
    as the next in a continuing series of award-winning audio desktop
    releases from Emacspeak Inc.
  • Emacspeak-14.0 –code named TopDog–was

the first release of this millennium.

  • Emacspeak-13.0 –codenamed
    YellowLab– was the closing release of the
    20th. century.
  • Emacspeak-12.0 –code named GoldenDog– began
    leveraging the evolving semantic WWW to provide task-oriented speech
    access to Webformation.
  • Emacspeak-11.0 –code named Aster– went the
    final step in making Linux a zero-cost Internet access solution for
    blind and visually impaired users.
  • Emacspeak-10.0 –(AKA
    Emacspeak-2000) code named WonderDog– continued the tradition of
    award-winning software releases designed to make eyes-free computing a
    productive and pleasurable experience.
  • Emacspeak-9.0 –(AKA
    Emacspeak 99) code named BlackLab– continued to innovate in the areas
    of speech interaction and interactive accessibility.
  • Emacspeak-8.0 –(AKA Emacspeak-98++) code named BlackDog– was a major upgrade to
    the speech output extension to Emacs.
  • Emacspeak-95 (code named Illinois) was released as OpenSource on
    the Internet in May 1995 as the first complete speech interface
    to UNIX workstations. The subsequent release, Emacspeak-96 (code
    named Egypt) made available in May 1996 provided significant
    enhancements to the interface. Emacspeak-97 (Tennessee) went
    further in providing a true audio desktop. Emacspeak-98
    integrated Internetworking into all aspects of the audio desktop
    to provide the first fully interactive speech-enabled WebTop.

8 About Emacspeak:

Originally based at Cornell (NY) —
http://www.cs.cornell.edu/home/raman —home to Auditory User
Interfaces (AUI) on the WWW, - Emacspeak is now maintained on GitHub
https://github.com/tvraman/emacspeak. The system is mirrored
world-wide by an international network of software archives and
bundled voluntarily with all major Linux distributions. On Monday,
April 12, 1999, Emacspeak became part of the Smithsonian's Permanent
Research Collection
on Information Technology at the Smithsonian's
National Museum of American History.


The Emacspeak mailing list is archived at Vassar –the home of the
Emacspeak mailing list– thanks to Greg Priest-Dorman, and provides a
valuable knowledge base for new users.


9 Press/Analyst Contact: Tilden Labrador

Going forward, Tilden acknowledges his exclusive monopoly on
setting the direction of the Emacspeak Audio Desktop, and
promises to exercise this freedom to innovate and her resulting
power responsibly (as before) in the interest of all dogs.


*About This Release:



Windows-Free (WF) is a favorite battle-cry of The League Against
Forced Fenestration (LAFF). –see
http://www.usdoj.gov/atr/cases/f3800/msjudgex.htm for details on
the ill-effects of Forced Fenestration.


CopyWrite )C( Aster, Hubbell and Tilden Labrador. All Writes Reserved.
HeadDog (DM), LiveDog (DM), GoldenDog (DM), BlackDog (DM) etc., are Registered
Dogmarks of Aster, Hubbell and Tilden Labrador. All other dogs belong to
their respective owners.

-1:-- Emacspeak 44.0 (SteadyDog) Unleashed (Post T. V. Raman (noreply@blogger.com))--L0--C0--April 30, 2016 05:51 PM

John Stevenson: Getting Started With Cider Repl for Clojure on Emacs Live

CIDER is the Clojure IDE and REPL for Emacs. It is built on top of nREPL, the Clojure networked REPL server and replaces the direct use of nREPL in Emacs.

In this article we are using CIDER that is packaged in Emacs Live, a very complete, well organised and extensible configuration for Clojure and many other things in Emacs.

CIDER includes the standard interactive code evaluation developers are used to. There are also many other features that I want to explore further, including error and warning highlighting, human-friendly stacktraces, smart code completion, definition & documentation lookup, value inspector & function tracing, interactive macroexpansion, Grimoire integration, clojure.test integration, classpath browser, namespace browser, nREPL session management, scratchpad, minibuffer code evaluation, integration with company-mode and auto-complete-mode

Emacs Live

CIDER is now the default in the latest version of Emacs Live, so there no set up to do if you already have the latest version. If you need to update, or are not sure you are on the latest version of Emacs live, simply run a git pull from within ~/.emacs.d directory:

git pull origin master

If you dont have Emacs Live, you can install it from the Emacs Live Github repository and either clone the repository into ~/.emacs.d (moving or deleting any existing directory) or preferably use the install script that also sets up a ~/.live-packs extension directory.

1
2
3
4
5
6
7
8
9
10
11
12
    bash <(curl -fksSL https://raw.github.com/overtone/emacs-live/master/installer/install-emacs-live.sh)
```

## Leiningen configuration

CIDER requires the use of [nREPL middleware](https://github.com/clojure-emacs/cider-nrepl) between Emacs and Leiningen. For example, when you run CIDER `M-x cider-jack-in` in Emacs it calls Leiningen to start the REPL. So you need to add a plugin to your Leiningen configuration.

Edit the `~/.lein/plugings.clj` file (or create this file if it does not exist yet) and add the `[cider/cider-nrepl "0.8.1"]` plugin. The `~/.lein/plugings.clj` should look similar to this:

```clojure
{:user {:plugins [[lein-pprint "1.1.1"]
[cider/cider-nrepl "0.8.1"]]}}

You can find the available versions of the cider-nrepl plugin on Clojars.org. The plugin version should be the same version of CIDER you are using in your Emacs configuration, which at the time of writing was 0.8.1.

Running CIDER in Emacs

Either create a new Clojure project using lein new my-project-name or open an existing project in Emacs (either the project.clj file or a .clj file from src/my-project-name/).

With your cursor in the Clojure file buffer, run CIDER using the keybinding C-c M-j or the emacs command

M-x cider-jack-in

Emacs Live - CIDER jack in - C-c M-j

Alternatively, you could run a REPL using lein repl on the command line and connect to that REPL using C-c M-c or M-x cider. You will be prompted for the connection details of the running repl, ie. host, port.

Using CIDER in Emacs

There are a number of Cider keyboard shortcuts (keybindings) already defined, here are some of the most common ones I use:

  • C-c C-e - evaluates the form immediately before the cursor and shows the result in the minibuffer. So place your cursor right after the closing parentheses ) of your expression, hit the keybinding and see the minibuffer for the result.

Emacs Live - CIDER eval form with result in minibuffer - C-c C-e

  • C-c M-e - the same as above except the result is sent to the REPL

Emacs Live - CIDER eval form with result in the REPL - C-c M-e

  • C-c C-k - evaluate the whole buffer. So with the cursor in a Clojure source file, all the forms / expressions are evaluate as if the code was loaded in from scratch.

  • C-c C-d d - show the documentaion as you would with (doc function-name). Place the cursor over a function name, hit the keybinding and see the documenation for that funtion. This also works inside the REPL buffer, so no need to use (doc), which is not loaded by default.

  • C-c M-n - switch to namespace of current Clojure buffer. So with the cursor in a Clojure source file, hit the keybinding and your REPL buffer will now be in the namespace for that Clojure code.

Emacs Live - CIDER change to namespace of current Clojure code - C-c M-n

Changing into a namespace does not automatically evaluate the code in that namespace, so evaluate the whole buffer C-c C-k or evaluate specific expressions (forms) C-c M-e. Once evaluated, you can evaluate that code in the REPL.

  • M-> or M-x cider-jump-to-var prompts you for a var, a function (defn) or symbol name (def) and moves the cursor to its definition. If the cusor is already on a matching name the the cursor jumps straight to that definition.

  • C-c C-q or M-x cider-quit - close the REPL and its associated buffer.

    There are many more things you can do within Clojure files and the REPL, so take a look at the Cider keyboard shortcuts (keybindings) once you have the basics mastered.

Further reading

Some further reading around CIDER:

Thank you.
@jr0cket

-1:-- Getting Started With Cider Repl for Clojure on Emacs Live (Post)--L0--C0--April 28, 2016 12:18 PM

John Stevenson: Github Pages for Reveal.js Slides Created With Emacs Org-Mode

In previous articles I showed how to setup Emacs Org-reveal & Reveal.js to generate your own presentations from Emacs Org-mode files. This time I’ll show you how to publish those presentations on Github Pages as I have done for my own presentations.

Github Pages are a great place for publishing your Reveal.js presentations or any static web content. For existing repositories you simply commit your content to a gh-pages branch or to the master branch of a user or organisation repository.

Github Pages are great for websites that is self-contained, in that there is no reliance on a database or other services running locally. You can even create great looking pages without any coding by using the Github authoring tool.

Existing code repositories

If you already have a repository for your code and want to add web page documentation, then you can simply add a gh-pages branch and commit your web content to that branch.

Content only repositories

If you only have content then you can use a user or organisation repository. This is a specifically named repository in the form of name.github.io where name is the exact name of your Github account or Github organisation you are part of.

In my case I created a repository named jr0cket.github.io, as my Github user account name is jr0cket.

Once created, you can type in the name of this repository into your browser and it will display any content you have committed into the repository and pushed it to Github.

Your user or org repository also forms the entry point for other project, so if you have a project called slides with web content in its gh-pages branch, you can see that content using the address: http://jr0cket.github.io/slides

Separating slide content into their own repository

As I planed to create a number of presentations, I use both an account repository as the home page and created a new repository called slides to host all my presentations.  This allows all my presentations to be easily cloned or forked by others easily without getting content that is only relevant to me on my Github pages home page.

Keeping the presentations all in one repository keeps things simple should I define my own Reveal.js themes or if there are Reveal.js updates.

I added  everything to the gh-pages branch (reveal.js, images, org & generated html files).  Then I generate the Reveal.js slides locally using org-reveal in Emacs, so I can check they look okay.  Once I am happy with the slides I commit the html and .org files to Git and push them up to Github.

Setting up a Github Pages user account repository

Creating an user repository on Github is just the same as for any other repository, except that the name must match the form name.github.io - where name is exactly the same as you Github user name.

I created a new repository called jr0cket.github.io, this has a web address (URL) of http://jr0cket.github.io

I used the Automatic Page Generator from Github to create the site without coding and with a handful of nice templates to choose from.  You can of course add your own HTML, CSS & JavaScript if you wish.  The Automatic Page Generator is in on the Settings page of your repository, under the Github pages section.  This section shows you the repository URL and a button to generate a page for you.

If you are going to use your user or org repository for your slides, then jump to the secion on “Adding Reveal.js to your repository”

Creating a repository for your Reveal.js slides

If you don’t already have a Github repository for your slides (and are not using your user or org repository), go to your account on Github and create a new repository.

git clone https://github.com/username/repository.git

Create an orphaned gh-pages branch

Github pages publishes content only from the branch gh-pages (unless you are using a user or org repository). In your local repository, create a new branch called gh-pages. According to Github, the gh-pages branch should be an orphaned branch.

cd your-local-repository
git checkout --orphan gh-pages

An orphaned branch is one that is not connected to another branch, in this case its not attached to master. Technically I don’t think gh-pages branch needs to be orphaned to publish your content, especially if there is nothing in the master branch, but this is the approach that Github recommends.

Once you have the gh-pages branch you can commit your files to that branch as normal.

git add .
git commit -m "Adding Reveal.js files for presentation"
git push origin gh-pages

Pushing your Reveal.js slides at this point will not give you the desired results, as we haven’t added the Reveal.js files to the repository.  So lets do that next.

Adding Reveal.js to your repository

You need to provide the JavaScript and CSS files from Reveal.js to make your slides display correctly.  I copy the following folders from within the reveal.js folder into the root of my slides project

cd  /path/to/revealjs/css    ~/my-slides
cd  /path/to/revealjs/js     ~/my-slides
cd  /path/to/revealjs/lib    ~/my-slides
cd  /path/to/revealjs/plugin ~/my-slides

You also need to check that the HTML for your web pages references Reveal.js files correctly.  The best way to do this is in the configuration for Emacs Org-reveal.

In my Org-reveal setup, I have defined the root for the Reveal.js files in my live-pack init.el file as follows:

(setq org-reveal-root "")

So long at this org-reveal setting is loaded, it shouldn’t matter which file you add it to in your Emacs configuration.

The HTML you generate with Org-reveal in Emacs should have references to the Reveal.js includes in the <head> section. Here is an example:

<html lang=”en”>
<head>
  <meta charset=”utf-8”/>
  <title>(My presentation title)</title>
  <meta name=”author” content=”(John Stevenson)”/>
  <link rel=”stylesheet” href=”./css/reveal.min.css”/>
  <link rel=”stylesheet” href=”./css/theme/jr0cket.cssid=”theme”/>
  <link rel=”stylesheet” href=”./css/print/pdf.csstype=”text/cssmedia=”print”/>
  <meta name=”description” content=”My presentation title“>
</head>

The final push

Then push the Reveal.js files to your Github repository (and any updated to your Org & html files)

git add .
git commit -m "Adding Reveal.js files for presentation"
git push origin gh-pages

Browsing your Slides

If you added your slides to a user or org repository, then you should be able to browse to http://name.github.io where name is your Github user or org name (eg. http://jr0cket.github.io).

If, like me, you created a seperate repository for all your slides, you can brows them by going to http://name.github.io/repo-name where name is your Github user name and repo-name is the name of the repository you added Reveal.js and your slides to (eg. http://jr0cket.github.io/slides).

Note that you need to add the html filename to the URL to browse your presentation, or as I have done add links to the page on jr0cket.github.io

Using Hub as an alternative way to create your Github pages repository

Hub is a command line tool for working with git repositories and Github. Hub makes it easy to create and fork repositories on Github without having to visit the Github website.

  • Install Hub
  • Create a folder called name.github.io on your laptop, where name is your Github user name or organisation name
  • Inside that folder, initialise a git repository - git init
  • Rename the master branch to gh-pages - git branch -m gh-pages
  • Use hub to to create the repository on github - hub create -d "optional description of the repository"
    — If you want to specify the repository name using hub, use the command form - hub create account-name.github.io -d "optional description of the repository"

  • Create and commit your content in the local repository on the gh-branch, then push the gh-pages branch to github github push -u origin gh-pages

— The -u option sets origin to be the default remote repository to and the gh-pages the default branch. So next time you do a push or pull you dont need to specify the remote repository or branch, you can simply do git push and git pull

Example Reveal.js presentations on Github pages

See my Github page for my published presentations, created with Emacs Org-mode, Org-reveal and Reveal.js.

Thank you.
@jr0cket

-1:-- Github Pages for Reveal.js Slides Created With Emacs Org-Mode (Post)--L0--C0--April 28, 2016 12:18 PM

Wilfred Hughes: Effortless Major Mode Development

It’s now easier than ever to write major modes in Emacs. If you haven’t written a major mode in a while, or you’re just starting out, here are my three top tips:

Use regexp-opt

As of Emacs 24, regexp-opt takes a 'symbols option. You should write your font-lock keywords like this:

(defvar js-mode-font-lock-keywords
  `((,(regexp-opt
       '("var" "for" "function" "if" "else")
       'symbols)
     . font-lock-keyword-face)

This has two advantages. By whitelisting keywords, users can quickly spot mistakes when editing:

This also prevents a classic bug where Emacs highlights substrings that happen to be keywords:

(Don’t) use company

Company is excellent, and I highly recommend it. However, not all Emacsers use company. You don’t need to force company on your users.

Instead, you can use completion-at-point-functions. Your completion functionality will work in stock Emacs, and company users will benefit too through company-capf.

Ah, but what about all the extra annotations you can supply to company? We can have our cake and eat it too:

(defun racer-complete-at-point ()
  "Complete the symbol at point."
  (unless (nth 3 (syntax-ppss)) ;; not in string
    (let* ((bounds (bounds-of-thing-at-point 'symbol))
           (beg (or (car bounds) (point)))
           (end (or (cdr bounds) (point))))
      (list beg end
            (completion-table-dynamic #'racer-complete)
            :annotation-function #'racer-complete--annotation
            :company-prefix-length (racer-complete--prefix-p beg end)
            :company-docsig #'racer-complete--docsig
            :company-location #'racer-complete--location))))

Test with assess

Historically, it’s been rather awkward to test major modes. Many authors didn’t bother.

That’s all changed with the release of assess. Assess provides great assertions with readable error messages.

For example, here’s a simple indentation test from cask-mode:

(ert-deftest cask-mode-indent-inside-development ()
  "Ensure we correctly indent inside (development ...) blocks."
  (should (assess-indentation=
           'cask-mode
           ;; before:
           "
(development
(depends-on \"foo\"))"
           ;; after:
           "
(development
 (depends-on \"foo\"))")))

Highlighting is particularly helped by assess:

(ert-deftest cask-mode-highlight-sources ()
  "Ensure we highlight known values for source."
  (should (assess-face-at=
           "(source melpa)"
           'cask-mode
           "melpa"
           'cask-mode-source-face)))

If this test fails, we get a helpful message describing which faces were actually used:

#("Face does not match expected value
   Expected: cask-mode-source-face
   Actual: font-lock-keyword-face
   Location: 9
   Line Context: (source melpa)
   bol Position: 1"

These tips are all new things I’ve learnt writing a new major mode for Cask files. If you’re just getting started with Emacs development, check out adding a new language to Emacs. Finally, if I’ve missed your favourite tip, leave a comment on the /r/emacs discussion!

-1:-- Effortless Major Mode Development (Post Wilfred Hughes (me@wilfred.me.uk))--L0--C0--April 28, 2016 12:00 AM

Sebastian Wiesner: Show Magit Status window in fullscreen

When I moved back to my own Emacs configuration from Spacemacs one thing that I missed most was to have Magit’s status window cover the whole frame.

Luckily this feature is easy to reproduce with a simple entry in display-buffer-alist:

(add-to-list 'display-buffer-alist
             `(,(rx "*magit: ")
               (lunaryorn-display-buffer-fullframe)
               (reusable-frames . nil)))

Unfortunately there’s no built-in display function to show a window covering the whole frame but it’s easy enough to write one:

(defun lunaryorn-display-buffer-fullframe (buffer alist)
  "Display BUFFER in fullscreen.

ALIST is a `display-buffer' ALIST.

Return the new window for BUFFER."
  (let ((window (display-buffer-pop-up-window buffer alist)))
    (when window
      (delete-other-windows window))
    window))

We simply need to get hold of any arbitrary window for the buffer, and then just delete all other windows, leaving only the window for our buffer.

That’s it. Enjoy and share :)

-1:-- Show Magit Status window in fullscreen (Post)--L0--C0--April 27, 2016 10:00 PM

(or emacs: Ivy 0.8.0 is out

Intro

Ivy is a completion method that's similar to Ido, but with emphasis on simplicity and customizability.

New package names

Changes on MELPA

Due to multiple requests, in an attempt to simplify things a new package ivy has been released on MELPA. The old package swiper, which used to provide most of the ivy features, now only provides swiper.el and depends on ivy. The third package counsel, which provides most of the goodies using ivy hasn't been changed and is still on MELPA. All three packages have the version 0.8.0 currently.

To reiterate the dependencies:

  • ivy depends on Emacs version larger than 24.1, preferably at least 24.3 (the most common one bundled currently with Linux distributions).
  • swiper depends on ivy and provides basically 3 commands: swiper, swiper-multi and swiper-all.
  • counsel depends on swiper and provides around 50 commands for all kinds of stuff. My favorites are counsel-M-x, counsel-git-grep, counsel-rhythmbox and counsel-grep-or-swiper.

Changes on GNU ELPA

On GNU ELPA, a single package ivy-0.8.0 has replaced the previous stable version swiper-0.7.0. This package provides all the files combined of the three separate MELPA packages.

Release summary

The release consists of 282 commits over 5 months by 15 authors. The detailed Changelog is available here, thanks to the ever useful Org mode export. The raw Org file is in doc/Changelog.org in the main repository.

The detailed documentation is available as an (ivy) Info node and also in HTML form here. If anyone wants to document something that's missing there, I'd appreciate the help: simply edit doc/ivy.org and send me a PR.

Release highlights

Below, I'll highlight some of the new features.

Allow to compose collections

For example, to stack the top 10 elements of recentf on top of counsel-locate, use this code:

(defun small-test ()
  (cl-subseq recentf-list 0 10))

(ivy-set-sources
 'counsel-locate
 '((small-test)
   (original-source)))

Here, (original-source) represents the async candidates of counsel-locate. All extra sources are static - each function is called once to generate a list of strings, which will be filtered later.

See #373 for more info.

Improved documentation

If you're not yet familiar with Ivy, you can get a quick reference card by pressing C-h m during any completion session. It will pop up an Org-mode buffer that describes most of the minibuffer key bindings.

Additionally, C-o (hydra-ivy/body), which serves a quick reference as well, received a small restructuring and a new binding. Press D to go to the definition of this hydra. This is useful to see what each key does, you might even want to customize some of it.

Completion in region

From now on, ivy-mode will also set completion-in-region-function. This means that functions like:

  • C-M-i complete-symbol in many major modes,
  • TAB while in the M-: (eval-expression) minibuffer,
  • TAB in a shell buffer,

will use ivy for completion.

Many improvements to ivy-occur-mode

You can "permanently" save any completion session by pressing C-c C-o (ivy-occur). This will generate a new buffer in ivy-occur-mode with all your current candidates inserted there. Clicking or pressing f on any of the candidates in that buffer will result in the appropriate action being called with that candidate.

ivy-occur-mode.png

The *ivy-occur ...* buffers can actually be customized per collection type. Specifically for swiper, counsel-git-grep, counsel-grep and counsel-ag, the customizations are already in place that allow you to:

  • Edit the buffer with wgrep by pressing C-x C-q (ivy-wgrep-change-to-wgrep-mode).
  • Refresh the buffer due to the original files being changed by pressing g (ivy-occur-revert-buffer).

The second feature is often useful to me when I want to somehow change a symbol throughout the project. First I make a list of all occurrences via e.g. swiper and ivy-occur. After I went through some of the occurrences, I can press g to refresh the search for the same symbol and see how many I still have left.

Yet another cool feature is to press c (ivy-occur-toggle-calling) to toggle calling the action after each line movement and cycle through candidates by holding either j (ivy-occur-next-line) or k (ivy-occur-previous-line).

ivy-set-action can work on all commands

Here's the code I'm using currently in my config:

(defun ivy-insert-action (x)
  (with-ivy-window
    (insert x)))

(ivy-set-actions
 t
 '(("I" ivy-insert-action "insert")))

This allows me to press M-o I to insert the current candidate into the buffer. For instance, if I want to quote an Emacs command, I can M-x (counsel-M-x), select the command I want and press M-o I to insert it instead of calling it.

Virtual views in ivy-switch-buffer

Here, "virtual" buffer means something that's close to a buffer but not an actual buffer. If you were using the setting ivy-use-virtual-buffers, you'd have your bookmarks and recentf items available to you as virtual buffers.

The new feature allows to select a whole window configuration with many buffers inside nested horizontal and vertical splits from ivy-switch-buffer.

To use it, set ivy-views, since it's nil by default. For instance, here's what I have in my config:

(setq ivy-views
      '(("dutch + notes {}"
         (vert
          (file "dutch.org")
          (buffer "notes")))
        ("ivy {}"
         (horz
          (file "ivy.el")
          (buffer "*scratch*")))))

For a more elaborate and detailed use, see this post by Manuel Uberti.

Magic slash in file name completion

From now on, if you want to enter a directory, simply select a candidate which is a directory and press /. You can still use the old binding C-j (ivy-alt-done), but / is shorter and easier to get used to if you're switching from Ido.

Note that this does not prevent the use of old functionality like:

  • // to enter the root directory,
  • /ssh: RET to connect via TRAMP.

A better way to search with counsel-grep-or-swiper

If you've ever been annoyed with the long start-up time of swiper in huge buffers, switch to this setting:

(global-set-key "\C-s" 'counsel-grep-or-swiper)

This command will use swiper for small buffers, and counsel-grep for large buffers.

Something very similar to this command was highlighted in this post by Karl Voit.

Just to give you an idea of how fast counsel-grep is:

  • It has 0s start-up time, since it's async.
  • For a two million line file weighing 50MB produced by copying org.el a few times, it takes 0.2s to find the 17,664 occurrences of the word hook. It still takes 7.5s to search for org in that file, simply because there are 500,000 candidates and it takes time for Emacs to simply receive that input.

A list of all new commands

The new commands since 0.7.0 are: counsel-tmm, counsel-imenu, counsel-decbinds, counsel-list-processes, ivy-switch-buffer-other-window, counsel-git-stash, counsel-git-log, counsel-pt, counsel-linux-app, counsel-ace-link, counsel-esh-history, counsel-shell-history, counsel-grep-or-swiper.

If any of those sound interesting, go ahead and try them out.

Outro

Thanks to all the contributors. Happy hacking!

-1:-- Ivy 0.8.0 is out (Post)--L0--C0--April 25, 2016 09:00 PM