How to automatically evaluate certain lisp code after starting an emacsclient? - emacs

When starting Emacs, init.el (or .emacs.el) is evaluated. However, when starting emacsclient, no similar lisp code is evaluated.
How can I get a lisp file to be evaluated every time I open a new emacsclient?
(This would be handy for frame specific customizations.)
I assume the answer is to use some hook, but I can't seem to find the correct hook to use.
I look forward to your answers.

You can add a function to the hook 'server-visit-hook, which is run every time the server is called (every time you call emacsclient).

I use the following code to automatically change the behavior of server buffers. I use it especially with the Firefox extension It's All Text. In that extension, buffers are named according to the domain name, so you can figure out which rule to apply by using string-match to match the name of the file.
(defun server-edit-presets ()
(cond
;; When editing mail, set the goal-column to 72.
((string-match "mail\\.google\\.com\\.[0-9a-z]+\\.txt" (buffer-name))
(longlines-mode-off)
(auto-fill-mode 1)
(set-fill-column 72)
(save-excursion
;; Don't know if this is necessary, but it seems to help.
(set-buffer (buffer-name))
(goto-char (point-min))
;; Replace non-breaking strange space characters
(while (search-forward (char-to-string 160) nil t)
(replace-match " "))))))
(add-hook 'server-visit-hook 'server-edit-presets)
(add-hook 'server-visit-hook '(lambda () (longlines-mode 1)))

If you really want new frame customizations, there's create-frame-hook which takes one arg (the new frame)...
If you mean gnuclient, you can use the command-line option "-eval" to evaluate something (and then just make an alias to always eval your customizations).

#LSW:
Try 'window-setup-hook. This addresses the annoyance since it is called even if emacsclient is not passed a file.

It seems that those hooks are no more, so here's the new version.
(add-hook 'server-after-make-frame-hook 'consult-recent-file)

Related

Open Org Capture buffer in specific window?

I've been an Emacs user for about a year or so. I routinely have the same window set up each session (four windows).
I've set up capture templates and can capture what I want, but: instead of capture mode temporarily jerking me out of my window setup, I'd like the chosen capture template to open in a new (fifth) window, preserving my existing layout. I typically want the capture template open for a while, so it's disruptive.
This seems like it would be an obvious option, but I can't figure it out. Thanks in advance to all the Emacs heads out there.
I came up with a easier-to-use version of Dan's answer to the linked question:
(defun my-org-capture-place-template-dont-delete-windows (oldfun &rest args)
(cl-letf (((symbol-function 'delete-other-windows) 'ignore))
(apply oldfun args)))
(with-eval-after-load "org-capture"
(advice-add 'org-capture-place-template :around 'my-org-capture-place-template-dont-delete-windows))
That is, instead of having to modify Org-mode code and remove the call to delete-other-windows, this piece of code temporarily redefines delete-other-windows to ignore while org-capture-place-template is being called.
It doesn't do quite what you want: it picks one of the existing windows and puts the capture buffer there. At least it's better than the default behaviour of removing all previous windows but one.
There's probably a way to do what you want by customising the variable display-buffer-alist, but I couldn't figure it out...
You could also use https://github.com/raxod502/el-patch and patch org-capture after loading (look for the (el-patch-remove (delete-other-windows))):
(el-patch-feature org-capture)
(with-eval-after-load 'org-capture
(el-patch-defun org-capture-place-template (&optional inhibit-wconf-store)
"Insert the template at the target location, and display the buffer.
When `inhibit-wconf-store', don't store the window configuration, as it
may have been stored before."
(unless inhibit-wconf-store
(org-capture-put :return-to-wconf (current-window-configuration)))
(el-patch-remove (delete-other-windows))
(org-switch-to-buffer-other-window
(org-capture-get-indirect-buffer (org-capture-get :buffer) "CAPTURE"))
(widen)
(org-show-all)
(goto-char (org-capture-get :pos))
(setq-local outline-level 'org-outline-level)
(pcase (org-capture-get :type)
((or `nil `entry) (org-capture-place-entry))
(`table-line (org-capture-place-table-line))
(`plain (org-capture-place-plain-text))
(`item (org-capture-place-item))
(`checkitem (org-capture-place-item)))
(org-capture-mode 1)
(setq-local org-capture-current-plist org-capture-plist)) )
For some reason, the #legoscia approach fails for me in emacs 28.
So here is the el-patch snippet as suggested previously:
(el-patch-feature org-capture)
(with-eval-after-load 'org-capture
(el-patch-define-and-eval-template
(defun org-capture-place-template)
(el-patch-remove (delete-other-windows))))

How to display file while still in find-file-hook

Currently, I use find-file-hook to invoke a lengthy compilation/checking of that file. I have therefore to wait for some time to actually see the file. What I would like to do instead is to be able to view (not edit) the file already while the checker is running, thus creating the illusion of instantaneous compilation. How can I do this?
Using find-file-hook means your code will run on every file you open; are you
sure you want this? It may make more sense to create a new major or minor mode
for the type of file you want to run your validation on and then use the
corresponding mode hook. For instance, if you wanted to check all .chk files
(with your new major mode inheriting from prog-mode):
(define-derived-mode check-mode prog-mode "Checker")
(add-to-list 'auto-mode-alist '("\\.chk\\'" . check-mode))
(add-hook 'check-mode-hook 'check-mode-computation-hook)
As for the actual hook, this code (going off phils' comment) works for me:
;;; -*- lexical-binding: t -*-
(defun slow-computation ()
(dotimes (i 10000000)
(+ i 1)))
(defun check-mode-computation-hook ()
(let ((cb (current-buffer))
(ro buffer-read-only))
(setq-local buffer-read-only t)
(run-at-time .1 nil
(lambda ()
(with-current-buffer cb
(message "Loading...")
(slow-computation)
(setq-local buffer-read-only ro)
(message "Loaded!"))))))
Note, though, that though this will display the file, emacs will still be frozen
until it finishes its processing, as
emacs doesn't actually support multithreading. To get around this, you may
have to use a library like async, deferred, or concurrent.
You should considered using Flycheck which provides async syntax checking for most programming languages and provides a nice API for implementing new/custom checkers.

Emacs - Adding abbrevs in ess-mode

I can't seem to get abbrevs working in ess-mode when editing R files.
I have ess-mode hook to activate abbrev-mode, but I get no expansion for my global abbrevs. When I do add-mode-abbrev I can add an abbrev, but it is not written to my abbrev file and of course doesn't get ever expanded (after read-abbrev-file or restart).
If I by hand add something like this into my abbrev file and reload:
(define-abbrev-table 'ess-mode-abbrev-table
'(
("-=" "<-" nil 0)
))
it doesn't work either.
How can I make ess-mode aware of my abbrevs?
I'm using a workaround setting the ess-mode-abbrev-table locally. First I define the abbrev-table, just in case that I load my abbrev-tables later and don't want an error when starting ESS:
(define-abbrev-table 'ess-mode-abbrev-table nil)
(add-hook 'ess-mode-hook
(lambda ()
(setq local-abbrev-table ess-mode-abbrev-table)))
I prefer to use the same abbrevs in the interpreter, so this comes in handy:
(dolist (hook '(ess-mode-hook inferior-ess-mode-hook))
(add-hook hook
(lambda ()
(setq local-abbrev-table ess-mode-abbrev-table))))
Abbreviations are expected to have word-syntax - forward-word is used internally.
Writing/re-defining abbrevs is a costly operation, takes some seconds. Thus this is not done after any edit/definition - except when C-x C-s is asked for explicitly. Abbrev-file commonly is written when session is closed.

difference between calling command directly and using keybinding

I'm new to elisp, so please forgive me if the following approach is totally clumsy.
In the team I'm currently working with, there is an usual convention of closing python blocks with a pass statement (if they aren't ended by closing keywords like else or except or such). While unusual, this has the advantage that one can always recover the original indentation of the program if it is unintentionally changed (using emacs indent-region).
To get existing code in line with this convention, I wrote a small elisp function:
(defun python-check-indent ()
"Check if automatic indentation changes current indent, insert pass keyword if it does."
(interactive)
(move-beginning-of-line 1)
(skip-chars-forward " ")
(if
(< 0
(let (original)
(setq original (point))
(indent-for-tab-command)
(- (point) original)
)
)
(progn
(insert "pass")
(newline)
(indent-for-tab-command)
)
)
(next-line)
)
(global-set-key (kbd "C-`") 'python-check-indent)
The idea is simply to test whether hitting TAB would change the indentation, and insert a pass statement in that case. To facilitate processing longer blocks of code, it then advances to the next line.
When I run it using M-x python-check-indent, it does what I want (except that it moves around empty lines slightly), also when running it repeatedly to process several lines. However, when I run it repeatedly using the C-` keybinding, it starts messing up the code from the second invocation on.
So here are my questions: What is the difference between invoking a command with M-x ... and using its keybinding? And how could I change the function to be not affected by this difference?
emacs-version: GNU Emacs 23.3.1 (x86_64-apple-darwin, NS apple-appkit-1038.35) of 2011-03-10 on black.porkrind.org
(edit) current workaround: I'm now wrapping it inside a keyboard-macro, so it's "bound" to C-x e, and behaves properly.
The general rule is that it is best to avoid complex interactive
commands in your functions because they could be affected by all sorts
of options.
(defun python-check-indent ()
"Check if automatic indentation changes current indent, insert pass keyword if it does."
(interactive)
(goto-char (line-beginning-position))
(skip-chars-forward " ")
(when (< 0
(let (original)
(setq original (point))
(python-indent-line)
(- (point) original)))
(insert "pass\n")
(python-indent-line))
(forward-line))
However, even this is probably not good because python-indent-line's behavior depends on last-command and python-indent-trigger-commands. I think it would be best if you replaced the first invocation of python-indent-line with the code which computes the target indentation instead of actually indenting, something like (nth python-indent-current-level python-indent-levels).
PS. If you still have problems, I suggest that you use edebug and step through the function.

Highlighting symbols automatically in Emacs

I am looking for a way to highlight symbols automatically, possibly using the package highlight-symbol.el (link).
I was wondering, is there a way so that, the first argument of all (setq ) will get automatically highlighted?
(setq thisshouldbehighlighted 1)
..and all the subsequent times when that symbol has been used / will be used.
First of all, the following code is based on version 1.2 of highlight-symbol. Older versions lack the function highlight-symbol-add-symbol.
The basic approach is to search the buffer for "(setq ". The actual regular expression is a bit more complex, as it allows whitespace and handles defvar and defcustom.
(defun highlight-all-symbols ()
(interactive)
(save-excursion
(highlight-symbol-mode 1)
(goto-char (point-min))
(while (re-search-forward (concat "([ \t\n]*"
"\\_<\\(?:"
"setq\\|defvar\\|defcustom"
"\\)\\_>[ \t\n]*"
"\\(\\_<\\(?:\\sw\\|\\s_\\)+\\_>\\)")
nil t)
(highlight-symbol-add-symbol (concat "\\_<"
(regexp-quote (match-string 1))
"\\_>")))))
You'll probably want to include the code in a mode hook
(add-hook 'emacs-lisp-mode-hook 'highlight-all-symbols)
Of course, simply highlighting all symbols set with setq can't be a perfect solution, as it ignores variable namespaces. Handling this correctly is a much bigger task, though, as it requires parsing the code. If you want to go down that rabbit hole, this might give you an idea, but I'm afraid it's not particularly documented.