use-package’s :config vs. :init

I read this Reddit thread about favorite themes, and got intrigued by the spacemacs theme1.

I added that theme to my init file, and tried making it the default theme. I use use-package, and configured the theme as follows:

(use-package spacemacs-theme
:ensure t
:config
(load-theme 'spacemacs-light t)
)

When re-evaluating my init file, the theme didn’t load. I tried to run only the (load-theme 'spacemacs-light t) line, and the theme loaded. I changed the :config to :init in the package configuration, and it loaded when I re-loaded emacs.

What, then, is the difference between :init and :config in use-package?

The answer to that question, which I found it in this stack-overflow answer, is that in use-package, whatever defined inside the :init keyword, will load whenever emacs is loading. What’s in the :config, though, will be executed only when the package is actually loaded (i.e lazy loading)2.

Here’s how my configuration for that theme looks like now:

(use-package spacemacs-theme
:ensure t
:init
(load-theme 'spacemacs-light t)
)

Footnotes:

1

I tried spacemacs before, and liked its look and feel, but didn’t know I can take it back with me to gnu emacs

2

Needless to say that, going back to the use-package documentation, the difference between :init and :config is clearly described…

Elisp Video Tutorial – Notes

I’ve just finished watching Daniel Gopar’s elisp video tutorial. So far there are 4 parts to the tutorial, and based on this thread on Reddit, there are more to come.

After watching the guide I don’t feel more proficient in elisp, yet less timid running evals and more courageous tinkering with my config file.

Following is a short summary of the code exercises and shortcuts I logged while watching.

Part 1 – Intro

Link to episode 1

REPL – read-eval-print-loop

Define functions:

(defun add-num (a b) (+ a b))

Define a test:

(require 'ert)
(ert-deftest add-num-pos ()
         (should
         (equal (add-num 10 10) 20)))

To run the test that I’ve just created: M-x ert-run-tests-interactively

Choose the test I would like to run (in this case “pos-add-num”)

Part 2 – Create A Simple Function And A Test Of That Function

Link to episode 2

setq to set variables and lists (setq my-list '(1 2 3))

add-to-list to add element (add-to-list 'my-list 4)

Another way to add to list, but this time to a copy of the list: (cons 5 my-list) – this will return (5 1 2 3 4) But when inquiring my-list, we will get (1 2 3 4)

car returns the first element in every list (car my-list) -> 1

cdr returns everything from a list, after the first element (crd my-list) -> (2 3 4)

nth return a certain element in the list (nth 4 my-list) -> 3

member check for a certain value in a list, and return the elements in that list from that value on (member 3 my-list) -> (3 4) (member 7 my-list) -> nil

Part 3 – Looping And Local Variables

Link to episode 3

Use the scratch buffer, so I can write in multiple lines

C-x C-e to evaluate code. Point needs to be at the end of the code in order to get evaluated.

Looping through variables:

let to create a local variable

when and if – what they suppose to do…

If there is more than one statement in the if statement, need to use to wrap those lines with progn. There is no such limitation in the else statement.

Part 4 – Interactive Functions

Link to episode 4

Created a function to count words, plus the test for it.

(defun cheap-count-words()
  (interactive)
  (let ((words 0))
    (save-excursion
      (goto-char (point-min))
    (while (forward-word)
      (setq words (1+ words)) ))
    (message (format "Words in Buffer: %s" words))words))



;; Tests
(require 'ert)

(ert-deftest count-words-test ()
  (get-buffer-create "*test*")
  (with-current-buffer "*test*"
    (erase-buffer)
    (insert "Hello world")
    (should (=(cheap-count-words) 2)))
  (kill-buffer "*test*"))

Magit – My Simple Workflow

I still not fluent with Magit’s terminology and workflow. Probably because I’m not using git, in general, too often. When I do, and when I try to use Magit as the interface, I usually get confused by the wealth of options and switches, and resort to git in the terminal.

Today I decided to give Magit yet another try. I read the Getting Started guide, and now things makes much more sense. However, I can see how I forget what I’ve just read a week from now, so here’s the gist of that, my simplest cheat-sheet:

(Ma)git status:

C-x g

(Ma)git add

For each unstage file: s

(Ma)git commit

c c

Type the commit note and then C-c C-c to create the commit.

(Ma)git push

p u

Done. Now I can type q to close the Magit pop-up buffer, and be back on the file I was working on.

Electric Pair Mode In Emacs

So far I’ve used TextExpander for text snippets and, well, text expansion. One of my main uses-cases is character pairings. For example, when I type " I almost always enclose it with another ".

But TextExpander is lacking in several ways:

  1. Performance – it takes a friction of a second for the expansion to happen, but it’s notable, and feels like a little hang.
  2. If I delete one part of the pair, it won’t remove the other.
  3. It won’t work to wrap text. If I typed something, and then want to wrap it with brackets, for example, I can’t select the text and type the bracket character.

In addition to the above technical shortcomings, I don’t plan to keep using TextExpander in the long run. The recent move into subscription based pricing, isn’t something I’m interested in. I mean, paying subscription to text snippets…?

Anyway, Emacs comes with an electric-pair-mode, which enables smart pairing. I turned it on, but out of the box it’s configured to work mainly with programming major modes. I need it also in other text based modes, such as org, markdown and simple text. For example, in org I use ~ for inline code snippets, and ~ isn’t paired by default. Same goes with ".

Luckily, defining more pairs is easy, through modifying the electric-pair-pairs variable.

Here’s my configuration for this mode:

(electric-pair-mode 1)
(setq electric-pair-pairs '(
                            (?\" . ?\")
                            (?\` . ?\`)
                            (?\( . ?\))
                            (?\{ . ?\})
                            ) )

I’ll add more pairs as I encounter them. Also, I’ll need to learn how to add pairs for specific major modes.

Just A Couple Of Emacs Keybindings

Every now and then I’ll type something in Emacs with a certain goal, just to find that I get something completely different from what I’ve intended.

When in org file, I tried to convert a list item to a sub-header. The keybinding to make this conversion is C-c *. But when I (thought I) typed it, instead of getting a sub-header, a new buffer opened at the bottom of the frame – a calculator:

emacs-calc-mode.png

Figure 1: Calc mode

view-lossage

I had no idea how did that happen, and luckily recalled a tip I got, on how to move back in time using the view-lossage command, which display last 300 input keystrokes. Doing so, I found that instead of C-c *, I typed C-x *.

So now I know (and hopefully remember) that:

  1. There’s a calculator1 in Emacs, bound to C-x *
  2. C-h l is a useful way to track back clumsy keystrokes

Footnotes:

1

Not that I had any doubts there is, just didn’t think to look for it just yet. There are so many other “to-learn” things on my list…

Get The Current File’s Path in Emacs

Here’s a small function I borrowed from this question on stack-overflow. It returns the full path of the file I currently edit in the buffer:

(defun show-file-name ()
  "Show the full path file name in the minibuffer."
  (interactive)
  (message (buffer-file-name))
  (kill-new (file-truename buffer-file-name))
)
(global-set-key "\C-cz" 'show-file-name)

You’ll note that this function is bind to C-c z. So when typing it, you should see the path showing in the minibuffer. As a bonus, it stores the path in the kill ring, so C-y (CMD-v works as well on my mac) will paste the value.

Bunch of Emacs Tweaks

Comment\Uncomment a Line

Few useful commands for commenting\uncommenting lines in emacs. Taken from the Emacs tutorial. Sure, I can go back to the manual, but I want to ducument and keep them here, for quicker referrence.

M-; Insert or realign comment on current line; if the region is active, comment or uncomment the region instead (comment-dwim).

C-u M-; Kill comment on current line (comment-kill).

C-x ; Set comment column (comment-set-column).

C-M-j M-j Like RET followed by inserting and aligning a comment (comment-indent-new-line). See Multi-Line Comments.

M-x comment-region

Mastering this command takes me one step further into Emacs, as it used to be one of those funcionalities that keeped drawing me back to Sublime Text.

Quick reload of init.el file

I’m constantly customizing my emacs. I have an init.el file, but most of the configuration in a more literal way, in an org config file.

When I make changes to Emacs settings, I need to reload the init file activate the changes. So far, I typed C-x C-f to find the init file and then M-x [RET] eval-buffer to reload it. Repeating this flow hundreds of times became annoying.

A quick inquery in IRC, and now I know that I can call load-file and give it the name of the file I would like to load. Having a function to load a file, means that I can wrap it with my own function, and reload my init file with a customized keybind.

And with the help of this answer at stack-overflow, I came up with the following shortcut to reload my Emacs configuration:

(global-set-key (kbd "<f6>") (lambda() (interactive)(load-file "~/.emacs.d/init.el")))

New line bellow

I wondered if there’s a command to creat a new line bellow the line my point is on. Here’s what I found in superuser:

C-e C-m – go to the end of the line, create a new line and move the point to that line.

or

C-e C-j – same as the command above, only that the point will indent if neccessery.

There is also a keybind for creating a new line above the current line, and move the point to that line – C-a C-o.

Quick Open a specific file

Now days I start most of my writing in my draft file. I need a quick way to access this file, whether I’m in Emacs or any other application. I know Emacs has the concept of registers, which are special memory slots, that can be accessed with a command. Those registers can store any type of data, such as strings, integers, files and paths.

It’s time to learn how to work with them. When thinking about it, there are other files that I would have liked to access quicker, such as the init.el or config.org.

Google’s first search result was EmacsWiki. Again, it proved to be a great source of information, had I wanted to confuse myself. So I passed. The second result was from Emacs tutorial, which again proved to be clear, concise and informative.

Here are the commands for storing a filename in and loading it from a register:

(set-register r '(file . name))

For example,

(set-register ?r '(file . "~/Dropbox/Notes/posts/pages/posts_drafts.org"))

To load this file, I should type C-x r j r

In the code examples above, r is the name of the register. It can be replaced with any character.

And to see what’s stored in a specific register:

M-x view-register RET r

Again, r is the register I’m querying.

Change cases

Keybinding Action
M-l Convert following word to lower case (downcase-word).
M-u Convert following word to upper case (upcase-word).
M-c Capitalize the following word (capitalize-word).
C-x C-l Convert region to lower case (downcase-region).
C-x C-u Convert region to upper case (upcase-region).