In emacs, how do I save without running save hooks? - emacs

I have various things set up in my 'before-save-hook. For example, I run 'delete-trailing-whitespace. This is what I want in almost all occasions.
But sometimes, I'm working on files that are shared with other people, and the file already has a bunch of trailing whitespace. If I save the file, I'll get a big diff that's pretty confusing, as my change is buried in dozens or hundreds of meaningless changes. Yes, everyone could just tell their diff tool to not show whitespace changes, but that's something that everyone has to do every time they look at the diff. I'd rather not even have the whitespace change.
Is there anything I can do to save the file without the whitespace changes, short of starting a new instance of Emacs with no init.el file, or with a modified init.el that doesn't have the hook?

Here is how I save without triggering delete-trailing-whitespace:
C-x C-q C-x C-s C-x C-q: read-only, save, revert read-only

A simpler solution I came up with is that my fundamental-mode has no hooks installed, because I want it to be as plain as possible. Thus if I want to save a file without running hooks, I temporarily switch to fundamental-mode.

Based on a comment discussion with #Stefan, here are two possible (untested) solutions:
Use let:
(defun save-buffer-without-dtw ()
(interactive)
(let ((b (current-buffer))) ; memorize the buffer
(with-temp-buffer ; new temp buffer to bind the global value of before-save-hook
(let ((before-save-hook (remove 'delete-trailing-whitespace before-save-hook)))
(with-current-buffer b ; go back to the current buffer, before-save-hook is now buffer-local
(let ((before-save-hook (remove 'delete-trailing-whitespace before-save-hook)))
(save-buffer)))))))
Use unwind-protect:
(defun save-buffer-without-dtw ()
(interactive)
(let ((restore-global
(memq 'delete-trailing-whitespace (default-value before-save-hook)))
(restore-local
(and (local-variable-p 'before-save-hook)
(memq 'delete-trailing-whitespace before-save-hook))))
(unwind-protect
(progn
(when restore-global
(remove-hook 'before-save-hook 'delete-trailing-whitespace))
(when restore-local
(remove-hook 'before-save-hook 'delete-trailing-whitespace t))
(save-buffer))
(when restore-global
(add-hook 'before-save-hook 'delete-trailing-whitespace))
(when restore-local
(add-hook 'before-save-hook 'delete-trailing-whitespace nil t)))))
The problem with the second solution is that the order of functions in the before-save-hook may change.

Here's another solution:
(defvar my-inhibit-dtw nil)
(defun my-delete-trailing-whitespace ()
(unless my-inhibit-dtw (delete-trailing-whitespace)))
(add-hook 'before-save-hook 'my-delete-trailing-whitespace)
and then
(defun my-inhibit-dtw ()
(interactive)
(set (make-local-variable 'my-inhibit-dtw) t))
so you can M-x my-inhibit-dtw RET in the buffers where you don't want to trim whitespace.

I wrote a command inspired by Nicholas Douma's solution.
(defun olav-save-buffer-as-is ()
"Save file \"as is\", that is in read-only-mode."
(interactive)
(if buffer-read-only
(save-buffer)
(read-only-mode 1)
(save-buffer)
(read-only-mode 0)))

What we need to do is remove 'delete-trailing-whitespace from before-save-hook, save the buffer, then add it back.
This code will do that, but only remove and add it if it's there to begin with.
;; save the buffer, removing and readding the 'delete-trailing-whitespace function
;; to 'before-save-hook if it's there
(defun save-buffer-no-delete-trailing-whitespace ()
(interactive)
(let ((normally-should-delete-trailing-whitespace (memq 'delete-trailing-whitespace before-save-hook)))
(when normally-should-delete-trailing-whitespace
(remove-hook 'before-save-hook 'delete-trailing-whitespace))
(save-buffer)
(when normally-should-delete-trailing-whitespace
(add-hook 'before-save-hook 'delete-trailing-whitespace))))
(global-set-key (kbd "C-c C-s") 'save-buffer-no-delete-trailing-whitespace)
It also binds the command to (kbd C-c C-s), for convenience.

Related

Emacs: load-file .emacs when saved

I'm new to emacs and lisp.
I wanted to auto-load the dot file when it was saved. Meaning, when I save my .emacs file, it would automatically call load-file on it (thus letting me know right away if I messed up).
But I can't seen to be able to find a comprehensive tutorial on hooks in emacs.
This is what I've come up with:
(defun load-init-after-save ()
"After saving this file, load it"
(if (eq bname this) ('load-file this) (nil))
)
(add-hook 'after-save-hook 'load-init-after-save)
Of course, this is incorrect: bname and this are just placeholders. And I don't want this function to run on all saves, just when the .emacs file is saved.
Does anyone know how to do this? Is there a better, easier way?
The following code loads your .emacs or ~/.emacs.d/init.el file after save:
(defun my-load-user-init-file-after-save ()
(when (string= (file-truename user-init-file)
(file-truename (buffer-file-name)))
(let ((debug-on-error t))
(load (buffer-file-name)))))
(add-hook 'after-save-hook #'my-load-user-init-file-after-save)
Since your intended use is error-checking, the code also enables the debugger while loading the init file, so that you get a nice backtrace in case of errors.
For error checking of your init file you may also find Flycheck useful. It checks your init file on the fly with the byte compiler, highlights any errors and warnings in the buffer, and—optionally—gives you a list of all errors and warnings.
Disclaimer: I'm the maintainer of this library.
Way 1
One way of doing is to install auto-compile-mode from MELPA, and enable it:
(defun my-emacs-lisp-hook ()
(auto-compile-mode 1))
(add-hook 'emacs-lisp-mode-hook 'my-emacs-lisp-hook)
Now each time you save an Elisp file that's byte-compiled, it will be
re-compiled. Compilation will usually catch some bad errors.
To compile any Elisp file, select it in dired (C-x d)
and press B (dired-do-byte-compile).
Way 2
Use this custom code I wrote.
(defun test-emacs ()
(interactive)
(require 'async)
(async-start
(lambda () (shell-command-to-string "emacs --batch --eval \"(condition-case e (progn (load \\\"~/.emacs\\\") (message \\\"-OK-\\\")) (error (message \\\"ERROR!\\\") (signal (car e) (cdr e))))\""))
`(lambda (output)
(if (string-match "-OK-" output)
(when ,(called-interactively-p 'any)
(message "All is well"))
(switch-to-buffer-other-window "*startup error*")
(delete-region (point-min) (point-max))
(insert output)
(search-backward "ERROR!")))))
(defun auto-test-emacs ()
(when (eq major-mode 'emacs-lisp-mode))
(test-emacs))
(add-hook 'after-save-hook 'auto-test-emacs)
This will start a new Emacs instance in the background each time you
save a file. If something goes wrong, it will complain.
The second approach uses async.
If you really want to do this just for .emacs user this:
(defun auto-test-emacs ()
(when (and (eq major-mode 'emacs-lisp-mode)
(equal (file-truename user-init-file)
(expand-file-name
buffer-file-truename)))
(test-emacs)))

How to create a hook which fires when I pause typing in Emacs?

I want to implement a hook which will work similar to Automatic LaTeX plugin for Vim: when I pause typing in emacs org mode, hook should fire and do (org-beamer-export-to-pdf t) in background.
How to create such a hook?
Thanks to #legoscia for the idea. Solved my problem using Real auto saving for emacs script with slightly modified real-auto-save function:
(defun real-auto-save()
(interactive)
(if real-auto-save-p
(progn
(save-excursion
(dolist (elem real-auto-save-alist)
(set-buffer elem)
(if (and (buffer-file-name) (buffer-modified-p))
(progn
(write-file (buffer-file-name))
(if (boundp 'org-beamer-mode)
(org-beamer-export-to-pdf t))
)))))))
In my init.el file:
(require 'real-auto-save)
(add-hook 'org-mode-hook 'turn-on-real-auto-save)
(setq real-auto-save-interval 2)
Everything is working perfect, no overhead or error messages.

Using ediff with C-x s (save-some-buffers) in Emacs?

C-x s uses diff to show changes. How can I use ediff instead?
I can see a couple of approaches to doing this. The first is to replace the save-some-buffers-action-alist variable with modified code, which is more straightforward. The second is to advise save-some-buffers and redefine the functions called by those actions, but that's a bit trickier.
I tried it both ways, and I think this is the best option:
;; Use ediff instead of diff in `save-some-buffers'
(eval-after-load "files"
'(progn
(setcdr (assq ?d save-some-buffers-action-alist)
`(,(lambda (buf)
(if (null (buffer-file-name buf))
(message "Not applicable: no file")
(add-hook 'ediff-after-quit-hook-internal
'my-save-some-buffers-with-ediff-quit t)
(save-excursion
(set-buffer buf)
(let ((enable-recursive-minibuffers t))
(ediff-current-file)
(recursive-edit))))
;; Return nil to ask about BUF again.
nil)
,(purecopy "view changes in this buffer")))
(defun my-save-some-buffers-with-ediff-quit ()
"Remove ourselves from the ediff quit hook, and
return to the save-some-buffers minibuffer prompt."
(remove-hook 'ediff-after-quit-hook-internal
'my-save-some-buffers-with-ediff-quit)
(exit-recursive-edit))))
My attempt at using advice is flawed (it breaks the C-r behaviour which also calls view-buffer, which caused me to reconsider using advice for this purpose), but FWIW:
(defadvice save-some-buffers (around my-save-some-buffers-with-ediff)
"Use ediff instead of diff."
(require 'cl)
(flet ((view-buffer (&rest) nil)
(diff-buffer-with-file
(buf)
(add-hook 'ediff-after-quit-hook-internal
'my-save-some-buffers-with-ediff-quit t)
(save-excursion
(set-buffer buf)
(ediff-current-file))))
(let ((enable-recursive-minibuffers t))
ad-do-it)))
(ad-activate 'save-some-buffers)
(defun my-save-some-buffers-with-ediff-quit ()
"Remove ourselves from the ediff quit hook, and
return to the save-some-buffers minibuffer prompt."
(remove-hook 'ediff-after-quit-hook-internal
'my-save-some-buffers-with-ediff-quit)
(exit-recursive-edit))
The variable diff-command is customizable, says the documentation. However, remember that it points to an external program, and not an elisp function. ediff is an elisp function that is in ediff.el. You might have to edit diff.el to (require 'ediff) and then tweak here and there in diff.el to see that you break nothing else.

Close all buffers besides the current one in Emacs

How do I close all but the current buffer in Emacs? Similar to "Close other tabs" feature in modern web browsers?
For a more manual approach, you can list all buffers with C-x C-b, mark buffers in the list for deletion with d, and then use x to remove them.
I also recommend replacing list-buffers with the more advanced ibuffer: (global-set-key (kbd "C-x C-b") 'ibuffer). The above will work with ibuffer, but you could also do this:
m (mark the buffer you want to keep)
t (toggle marks)
D (kill all marked buffers)
I also use this snippet from the Emacs Wiki, which would further streamline this manual approach:
;; Ensure ibuffer opens with point at the current buffer's entry.
(defadvice ibuffer
(around ibuffer-point-to-most-recent) ()
"Open ibuffer with cursor pointed to most recent buffer name."
(let ((recent-buffer-name (buffer-name)))
ad-do-it
(ibuffer-jump-to-buffer recent-buffer-name)))
(ad-activate 'ibuffer)
From EmacsWiki: Killing Buffers:
(defun kill-other-buffers ()
"Kill all other buffers."
(interactive)
(mapc 'kill-buffer
(delq (current-buffer)
(remove-if-not 'buffer-file-name (buffer-list)))))
Edit: updated with feedback from Gilles
There isn't a way directly in emacs to do this.
You could write a function to do this. The following will close all the buffers:
(defun close-all-buffers ()
(interactive)
(mapc 'kill-buffer (buffer-list)))
There is a built in command m-x kill-some-buffers (I'm using 24.3.50) In my nextstep gui (not tried in a terminal but sure it's similar) you can then approve which buffers to kill.
(defun only-current-buffer ()
(interactive)
(let ((tobe-killed (cdr (buffer-list (current-buffer)))))
(while tobe-killed
(kill-buffer (car tobe-killed))
(setq tobe-killed (cdr tobe-killed)))))
It works as you expected.
And after reading #Starkey's answer, I think this will be better:
(defun only-current-buffer ()
(interactive)
(mapc 'kill-buffer (cdr (buffer-list (current-buffer)))))
(buffer-list (current-buffer)) will return a list that contains all the existing buffers, with the current buffer at the head of the list.
This is my first answer on StackOverflow. Hope it helps :)
I found this solution to be the simplest one. This deletes every buffer except the current one. You have to add this code to your .emacs file
(defun kill-other-buffers ()
"Kill all other buffers."
(interactive)
(mapc 'kill-buffer (delq (current-buffer) (buffer-list))))
Of course, then you use it with M-x kill-other-buffers RET or you paste the following code in the .emacs file too and then just press C-xC-b
(global-set-key (kbd "C-x C-b") 'kill-other-buffers)
You can like this one as well - kill all buffers except current one, *Messages* and *scratch* (which are handy to have, I call them "toolkit"), close redundant windows as well, living you which one window which current buffer.
(defun my/kill-all-buffers-except-toolbox ()
"Kill all buffers except current one and toolkit (*Messages*, *scratch*). Close other windows."
(interactive)
(mapc 'kill-buffer (remove-if
(lambda (x)
(or
(eq x (current-buffer))
(member (buffer-name x) '("*Messages*" "*scratch*"))))
(buffer-list)))
(delete-other-windows))
I've use crux-kill-other-buffers for some months.
But I want dired buffers get deleted too. #Euge's and #wenjun.yan's answers solve this. But it will delete special buffers (e.g *git-credential-cache--daemon*, *scratch*, helm operation, and etc). So I came up with this (current) solution.
(defun aza-kill-other-buffers ()
"Kill all buffers but current buffer and special buffers"
(interactive)
(dolist (buffer (delq (current-buffer) (buffer-list)))
(let ((name (buffer-name buffer)))
(when (and name (not (string-equal name ""))
(/= (aref name 0) ?\s)
(string-match "^[^\*]" name))
(funcall 'kill-buffer buffer)))))
Inspired from kill-matching-buffers. You can add more condition on other buffer-name to exclude, if you want to.
Hope it helps :)
I've used one of the solutions in this list for years, but now I have a new one of my own.
(defun kill-all-file-buffers ()
"Kills all buffers that are open to files. Does not kill
modified buffers or special buffers."
(interactive)
(mapc 'kill-buffer (cl-loop for buffer being the buffers
when (and (buffer-file-name buffer)
(not (buffer-modified-p buffer)))
unless (eq buffer (current-buffer))
collect buffer)))
cl-loop has buffers built in as a collection that you can iterate over. It gives you a chance to parse out anything you don't want to close. Here, I've made sure that it doesn't close anything you've modified, and it uses buffer-file-name instead of just buffer-name so it doesn't kill special buffers. I also added an 'unless' to take out the current buffer (though you could obviously add it to the 'when', I just thought this was clearer).
But for an even more generic solution, we can define this as a macro, and pass in a function that will apply to all these buffers.
(defmacro operate-on-file-buffers (func)
"Takes any function that takes a single buffer as an argument
and applies that to all open file buffers that haven't been
modified, and aren't the current one."
`(mapc ,func (cl-loop for buffer being the buffers
when (and (buffer-file-name buffer)
(not (buffer-modified-p buffer)))
unless (eq buffer (current-buffer))
collect buffer)))
Now if you want to kill all buffers that match this, you can call it like this
(operate-on-file-buffers 'kill-buffer)
This is what you want:
C-x 1
source: https://blasphemousbits.wordpress.com/2007/05/04/learning-emacs-part-4-buffers-windows-and-frames/

What's in your .emacs?

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I've switched computers a few times recently, and somewhere along the way I lost my .emacs. I'm trying to build it up again, but while I'm at it, I thought I'd pick up other good configurations that other people use.
So, if you use Emacs, what's in your .emacs?
Mine is pretty barren right now, containing only:
Global font-lock-mode! (global-font-lock-mode 1)
My personal preferences with respect to indentation, tabs, and spaces.
Use cperl-mode instead of perl-mode.
A shortcut for compilation.
What do you think is useful?
Use the ultimate dotfiles site. Add your '.emacs' here. Read the '.emacs' of others.
My favorite snippet. The ultimate in Emacs eye candy:
;; real lisp hackers use the lambda character
;; courtesy of stefan monnier on c.l.l
(defun sm-lambda-mode-hook ()
(font-lock-add-keywords
nil `(("\\<lambda\\>"
(0 (progn (compose-region (match-beginning 0) (match-end 0)
,(make-char 'greek-iso8859-7 107))
nil))))))
(add-hook 'emacs-lisp-mode-hook 'sm-lambda-mode-hook)
(add-hook 'lisp-interactive-mode-hook 'sm-lamba-mode-hook)
(add-hook 'scheme-mode-hook 'sm-lambda-mode-hook)
So you see i.e. the following when editing lisp/scheme:
(global-set-key "^Cr" '(λ () (interactive) (revert-buffer t t nil)))
I have this to change yes or no prompt to y or n prompts:
(fset 'yes-or-no-p 'y-or-n-p)
I have these to start Emacs without so much "fanfare" which I got from this question.
(setq inhibit-startup-echo-area-message t)
(setq inhibit-startup-message t)
And Steve Yegge's function to rename a file that you're editing along with its corresponding buffer:
(defun rename-file-and-buffer (new-name)
"Renames both current buffer and file it's visiting to NEW-NAME."
(interactive "sNew name: ")
(let ((name (buffer-name))
(filename (buffer-file-name)))
(if (not filename)
(message "Buffer '%s' is not visiting a file!" name)
(if (get-buffer new-name)
(message "A buffer named '%s' already exists!" new-name)
(progn
(rename-file name new-name 1)
(rename-buffer new-name)
(set-visited-file-name new-name)
(set-buffer-modified-p nil))))))
One thing that can prove very useful: Before it gets too big, try to split it into multiple files for various tasks: My .emacs just sets my load-path and the loads a bunch of files - I've got all my mode-specific settings in mode-configs.el, keybindings in keys.el, et cetera
My .emacs is only 127 lines, here are the most useful little snippets:
;; keep backup files neatly out of the way in .~/
(setq backup-directory-alist '(("." . ".~")))
This makes the *~ files which I find clutter up the directory go into a special directory, in this case .~
;; uniquify changes conflicting buffer names from file<2> etc
(require 'uniquify)
(setq uniquify-buffer-name-style 'reverse)
(setq uniquify-separator "/")
(setq uniquify-after-kill-buffer-p t) ; rename after killing uniquified
(setq uniquify-ignore-buffers-re "^\\*") ; don't muck with special buffers
This sets up uniquify which changes those ugly file<2> etc. buffer names you get when multiple files have the same name into a much neater unambiguous name using as much of the whole path of the file as it has to.
That's about it... the rest is pretty standard stuff that I'm sure everyone knows about.
This is not the whole kit and kaboodle, but it is some of the more useful snippets I've gathered:
(defadvice show-paren-function (after show-matching-paren-offscreen
activate)
"If the matching paren is offscreen, show the matching line in the
echo area. Has no effect if the character before point is not of
the syntax class ')'."
(interactive)
(let ((matching-text nil))
;; Only call `blink-matching-open' if the character before point
;; is a close parentheses type character. Otherwise, there's not
;; really any point, and `blink-matching-open' would just echo
;; "Mismatched parentheses", which gets really annoying.
(if (char-equal (char-syntax (char-before (point))) ?\))
(setq matching-text (blink-matching-open)))
(if (not (null matching-text))
(message matching-text))))
;;;;;;;;;;;;;;;
;; UTF-8
;;;;;;;;;;;;;;;;;;;;
;; set up unicode
(prefer-coding-system 'utf-8)
(set-default-coding-systems 'utf-8)
(set-terminal-coding-system 'utf-8)
(set-keyboard-coding-system 'utf-8)
;; This from a japanese individual. I hope it works.
(setq default-buffer-file-coding-system 'utf-8)
;; From Emacs wiki
(setq x-select-request-type '(UTF8_STRING COMPOUND_TEXT TEXT STRING))
;; Wwindows clipboard is UTF-16LE
(set-clipboard-coding-system 'utf-16le-dos)
(defun jonnay-timestamp ()
"Spit out the current time"
(interactive)
(insert (format-time-string "%Y-%m-%d")))
(defun jonnay-sign ()
"spit out my name, email and the current time"
(interactive)
(insert "-- Jonathan Arkell (jonathana#criticalmass.com)")
(jonnay-timestamp))
;; Cygwin requires some seriosu setting up to work the way i likes it
(message "Setting up Cygwin...")
(let* ((cygwin-root "c:")
(cygwin-bin (concat cygwin-root "/bin"))
(gambit-bin "/usr/local/Gambit-C/4.0b22/bin/")
(snow-bin "/usr/local/snow/current/bin")
(mysql-bin "/wamp/bin/mysql/mysql5.0.51a/bin/"))
(setenv "PATH" (concat cygwin-bin ";" ;
snow-bin ";"
gambit-bin ";"
mysql-bin ";"
".;")
(getenv "PATH"))
(setq exec-path (cons cygwin-bin exec-path)))
(setq shell-file-name "bash")
(setq explicit-shell-file-name "bash")
(require 'cygwin-mount)
(cygwin-mount-activate)
(message "Setting up Cygwin...Done")
; Completion isn't perfect, but close
(defun my-shell-setup ()
"For Cygwin bash under Emacs 20+"
(setq comint-scroll-show-maximum-output 'this)
(setq comint-completion-addsuffix t)
(setq comint-eol-on-send t)
(setq w32-quote-process-args ?\")
(make-variable-buffer-local 'comint-completion-addsuffix))
(setq shell-mode-hook 'my-shell-setup)
(add-hook 'emacs-startup-hook 'cygwin-shell)
; Change how home key works
(global-set-key [home] 'beginning-or-indentation)
(substitute-key-definition 'beginning-of-line 'beginning-or-indentation global-map)
(defun yank-and-down ()
"Yank the text and go down a line."
(interactive)
(yank)
(exchange-point-and-mark)
(next-line))
(defun kill-syntax (&optional arg)
"Kill ARG sets of syntax characters after point."
(interactive "p")
(let ((arg (or arg 1))
(inc (if (and arg (< arg 0)) 1 -1))
(opoint (point)))
(while (not (= arg 0))
(if (> arg 0)
(skip-syntax-forward (string (char-syntax (char-after))))
(skip-syntax-backward (string (char-syntax (char-before)))))
(setq arg (+ arg inc)))
(kill-region opoint (point))))
(defun kill-syntax-backward (&optional arg)
"Kill ARG sets of syntax characters preceding point."
(interactive "p")
(kill-syntax (- 0 (or arg 1))))
(global-set-key [(control shift y)] 'yank-and-down)
(global-set-key [(shift backspace)] 'kill-syntax-backward)
(global-set-key [(shift delete)] 'kill-syntax)
(defun insert-file-name (arg filename)
"Insert name of file FILENAME into buffer after point.
Set mark after the inserted text.
Prefixed with \\[universal-argument], expand the file name to
its fully canocalized path.
See `expand-file-name'."
;; Based on insert-file in Emacs -- ashawley 2008-09-26
(interactive "*P\nfInsert file name: ")
(if arg
(insert (expand-file-name filename))
(insert filename)))
(defun kill-ring-save-filename ()
"Copy the current filename to the kill ring"
(interactive)
(kill-new (buffer-file-name)))
(defun insert-file-name ()
"Insert the name of the current file."
(interactive)
(insert (buffer-file-name)))
(defun insert-directory-name ()
"Insert the name of the current directory"
(interactive)
(insert (file-name-directory (buffer-file-name))))
(defun jonnay-toggle-debug ()
"Toggle debugging by toggling icicles, and debug on error"
(interactive)
(toggle-debug-on-error)
(icicle-mode))
(defvar programming-modes
'(emacs-lisp-mode scheme-mode lisp-mode c-mode c++-mode
objc-mode latex-mode plain-tex-mode java-mode
php-mode css-mode js2-mode nxml-mode nxhtml-mode)
"List of modes related to programming")
; Text-mate style indenting
(defadvice yank (after indent-region activate)
(if (member major-mode programming-modes)
(indent-region (region-beginning) (region-end) nil)))
I have a lot of others that have already been mentioned, but these are absolutely necessary in my opinion:
(transient-mark-mode 1) ; makes the region visible
(line-number-mode 1) ; makes the line number show up
(column-number-mode 1) ; makes the column number show up
You can look here: http://www.dotemacs.de/
And my .emacs is pretty long to put it here as well, so it will make the answer not too readable. Anyway, if you wish I can sent it to you.
Also I would recomend you to read this: http://steve.yegge.googlepages.com/my-dot-emacs-file
Here are some key mappings that I've become dependent upon:
(global-set-key [(control \,)] 'goto-line)
(global-set-key [(control \.)] 'call-last-kbd-macro)
(global-set-key [(control tab)] 'indent-region)
(global-set-key [(control j)] 'join-line)
(global-set-key [f1] 'man)
(global-set-key [f2] 'igrep-find)
(global-set-key [f3] 'isearch-forward)
(global-set-key [f4] 'next-error)
(global-set-key [f5] 'gdb)
(global-set-key [f6] 'compile)
(global-set-key [f7] 'recompile)
(global-set-key [f8] 'shell)
(global-set-key [f9] 'find-next-matching-tag)
(global-set-key [f11] 'list-buffers)
(global-set-key [f12] 'shell)
Some other miscellaneous stuff, mostly for C++ development:
;; Use C++ mode for .h files (instead of plain-old C mode)
(setq auto-mode-alist (cons '("\\.h$" . c++-mode) auto-mode-alist))
;; Use python-mode for SCons files
(setq auto-mode-alist (cons '("SConstruct" . python-mode) auto-mode-alist))
(setq auto-mode-alist (cons '("SConscript" . python-mode) auto-mode-alist))
;; Parse CppUnit failure reports in compilation-mode
(require 'compile)
(setq compilation-error-regexp-alist
(cons '("\\(!!!FAILURES!!!\nTest Results:\nRun:[^\n]*\n\n\n\\)?\\([0-9]+\\)) test: \\([^(]+\\)(F) line: \\([0-9]+\\) \\([^ \n]+\\)" 5 4)
compilation-error-regexp-alist))
;; Enable cmake-mode from http://www.cmake.org/Wiki/CMake_Emacs_mode_patch_for_comment_formatting
(require 'cmake-mode)
(setq auto-mode-alist
(append '(("CMakeLists\\.txt\\'" . cmake-mode)
("\\.cmake\\'" . cmake-mode))
auto-mode-alist))
;; "M-x reload-buffer" will revert-buffer without requiring confirmation
(defun reload-buffer ()
"revert-buffer without confirmation"
(interactive)
(revert-buffer t t))
To refresh the webpage you're editing from within Emacs
(defun moz-connect()
(interactive)
(make-comint "moz-buffer" (cons "127.0.0.1" "4242"))
(global-set-key "\C-x\C-g" '(lambda ()
(interactive)
(save-buffer)
(comint-send-string "*moz-buffer*" "this.BrowserReload()\n"))))
Used in combination with http://hyperstruct.net/projects/mozlab
You can find my configuration (both in html & in tar'ed archive) on my site. It contains lot of settings for different modes
This block is the most important for me:
(setq locale-coding-system 'utf-8)
(set-terminal-coding-system 'utf-8)
(set-keyboard-coding-system 'utf-8)
(set-selection-coding-system 'utf-8)
(prefer-coding-system 'utf-8)
I've never been clear on the difference between those, though. Cargo cult, I guess...
I try to keep my .emacs organized. The configuration will always be a work in progress, but I'm starting to be satisfied with the overall structure.
All stuff is under ~/.elisp, a directory that is under version control (I use git, if that's of interest). ~/.emacs simply points to ~/.elisp/dotemacs which itself just loads ~/.elisp/cfg/init. That file in turn imports various configuration files via require. This means that the configuration files need to behave like modes: they import stuff they depend on and they provide themselves at the end of the file, e.g. (provide 'my-ibuffer-cfg). I prefix all identifiers that are defined in my configuration with my-.
I organize the configuration in respect to modes/subjects/tasks, not by their technical implications, e.g. I don't have a separate config file in which all keybindings or faces are defined.
My init.el defines the following hook to make sure that Emacs recompiles configuration files whenever saved (compiled Elisp loads a lot faster but I don't want to do this step manually):
;; byte compile config file if changed
(add-hook 'after-save-hook
'(lambda ()
(when (string-match
(concat (expand-file-name "~/.elisp/cfg/") ".*\.el$")
buffer-file-name)
(byte-compile-file buffer-file-name))))
This is the directory structure for ~/.elisp:
~/.elisp/todo.org: Org-mode file in which I keep track of stuff that still needs to be done (+ wish list items).
~/.elisp/dotemacs: Symlink target for ~/.emacs, loads ~/.elisp/cfg/init.
~/.elisp/cfg: My own configuration files.
~/.elisp/modes: Modes that consist only of a single file.
~/.elisp/packages: Sophisticated modes with lisp, documentation and probably resource files.
I use GNU Emacs, that version does not have real support for packages. Therefore I organize them manually, usually like this:
~/.elisp/packages/foobar-0.1.3 is the root directory for the package. Subdirectory lisp holds all the lisp files and info is where the documentation goes. ~/.elisp/packages/foobar is a symlink that points to the currently used version of the package so that I don't need to change my configuration files when I update something. For some packages I keep an ~/.elisp/packages/foobar.installation file around in which I keep notes about the installation process. For performance reasons I compile all elisp files in newly installed packages, should this not be the case by default.
Here's a couple of my own stuff:
Inserts date in ISO 8601 format:
(defun insertdate ()
(interactive)
(insert (format-time-string "%Y-%m-%d")))
(global-set-key [(f5)] 'insertdate)
For C++ programmers, creates a class skeleton (class's name will be the same as the file name without extension):
(defun createclass ()
(interactive)
(setq classname (file-name-sans-extension (file-name-nondirectory buffer-file-name)))
(insert
"/**
* " classname".h
*
* Author: Your Mom
* Modified: " (format-time-string "%Y-%m-%d") "
* Licence: GNU GPL
*/
#ifndef "(upcase classname)"
#define "(upcase classname)"
class " classname "
{
public:
"classname"();
~"classname"();
private:
};
#endif
"))
Automatically create closing parentheses:
(setq skeleton-pair t)
(setq skeleton-pair-on-word t)
(global-set-key (kbd "[") 'skeleton-pair-insert-maybe)
(global-set-key (kbd "(") 'skeleton-pair-insert-maybe)
(global-set-key (kbd "{") 'skeleton-pair-insert-maybe)
(global-set-key (kbd "<") 'skeleton-pair-insert-maybe)
i use paredit for easy (e)lisp handling and ido-mode minibuffer completions.
It's hard to answer this question, because everyone uses Emacs for very different purposes.
Further more, a better practice may be to KISS your dotemacs. Since the Easy Customization Interface is widely supported amongst Emacs' modes, you should store all your customization in your custom-file (which may be a separate place in your dotemacs), and for the dotemacs, put in it only load path settings, package requires, hooks, and key bindings. Once you start using Emacs Starter Kit, a whole useful bunch of settings may removed from your dotemacs, too.
See EmacsWiki's DotEmacs category. It provides lots of links to pages addressing this question.
(put 'erase-buffer 'disabled nil)
(put 'downcase-region 'disabled nil)
(set-variable 'visible-bell t)
(set-variable 'tool-bar-mode nil)
(set-variable 'menu-bar-mode nil)
(setq load-path (cons (expand-file-name "/usr/share/doc/git-core/contrib/emacs") load-path))
(require 'vc-git)
(when (featurep 'vc-git) (add-to-list 'vc-handled-backends 'git))
(require 'git)
(autoload 'git-blame-mode "git-blame"
"Minor mode for incremental blame for Git." t)
I set up some handy shortcuts to web pages and searches using webjump
(require 'webjump)
(global-set-key [f2] 'webjump)
(setq webjump-sites
(append '(
("Reddit Search" .
[simple-query "www.reddit.com" "http://www.reddit.com/search?q=" ""])
("Google Image Search" .
[simple-query "images.google.com" "images.google.com/images?hl=en&q=" ""])
("Flickr Search" .
[simple-query "www.flickr.com" "flickr.com/search/?q=" ""])
("Astar algorithm" .
"http://www.heyes-jones.com/astar")
)
webjump-sample-sites))
Blog post about how this works here
http://justinsboringpage.blogspot.com/2009/02/search-reddit-flickr-and-google-from.html
Also I recommend these:
(setq visible-bell t) ; no beeping
(setq transient-mark-mode t) ; visually show region
(setq line-number-mode t) ; show line numbers
(setq global-font-lock-mode 1) ; everything should use fonts
(setq font-lock-maximum-decoration t)
Also I get rid of some of the superfluous gui stuff
(if (fboundp 'scroll-bar-mode) (scroll-bar-mode -1))
(if (fboundp 'tool-bar-mode) (tool-bar-mode -1))
(if (fboundp 'menu-bar-mode) (menu-bar-mode -1)))
One line to amend the load path
One line to load my init library
One line to load my emacs init files
Of course, the "emacs init files" are quite numerous, one per specific thing, loaded in a deterministic order.
emacs-starter-kit as a base, then I've added.. vimpulse.el, whitespace.el, yasnippet, textmate.el and newsticker.el.
In my ~/.emacs.d/$USERNAME.el (dbr.el) file:
(add-to-list 'load-path (concat dotfiles-dir "/vendor/"))
;; Snippets
(add-to-list 'load-path "~/.emacs.d/vendor/yasnippet/")
(require 'yasnippet)
(yas/initialize)
(yas/load-directory "~/.emacs.d/vendor/yasnippet/snippets")
;; TextMate module
(require 'textmate)
(textmate-mode 'on)
;; Whitespace module
(require 'whitespace)
(add-hook 'ruby-mode-hook 'whitespace-mode)
(add-hook 'python-mode-hook 'whitespace-mode)
;; Misc
(flyspell-mode 'on)
(setq viper-mode t)
(require 'viper)
(require 'vimpulse)
;; IM
(eval-after-load 'rcirc '(require 'rcirc-color))
(setq rcirc-default-nick "_dbr")
(setq rcirc-default-user-name "_dbr")
(setq rcirc-default-user-full-name "_dbr")
(require 'jabber)
;;; Google Talk account
(custom-set-variables
'(jabber-connection-type (quote ssl))
'(jabber-network-server "talk.google.com")
'(jabber-port 5223)
'(jabber-server "mysite.tld")
'(jabber-username "myusername"))
;; Theme
(color-theme-zenburn)
;; Key bindings
(global-set-key (kbd "M-z") 'undo)
(global-set-key (kbd "M-s") 'save-buffer)
(global-set-key (kbd "M-S-z") 'redo)
Always save my config in svn http://my-trac.assembla.com/ez-conf/browser/emacs.d
After reading this, I figured it would be good to have a simple site just for the best .emacs modifications. Feel free to post and vote on them here:
http://dotemacs.slinkset.com/
https://b7j0c.org/stuff/dotemacs.html
I'm new to emacs, in my .emacs file there are
indentation configuration
color theme
php mode, coffee mode and js2 mode
ido mode
FWIW, my .emacs is here:
http://svn.red-bean.com/repos/kfogel/trunk/.emacs
lots of stuff: https://github.com/tavisrudd/emacs.d
el-get has made managing it and dependencies a lot easier: https://github.com/tavisrudd/emacs.d/blob/master/dss-init-el-get.el
For Scala coders
;; Load the ensime lisp code... http://github.com/aemoncannon/ensime
(add-to-list 'load-path "ENSIME_ROOT/elisp/")
(require 'ensime)
;; This step causes the ensime-mode to be started whenever ;; scala-mode is started for a buffer. You may have to customize this step ;; if you're not using the standard scala mode.
(add-hook 'scala-mode-hook 'ensime-scala-mode-hook)
;; MINI HOWTO: ;; Open .scala file. M-x ensime (once per project)
My emacs configuration has grown up pretty big over the years and I have lot of useful stuff for me there but if I have two functions it probably would have been those ones.
Define C-x UP and C-x DOWN to move the current line or down keeping the cursor at the right place :
;Down/UP the current line
(global-set-key '[(control x) (up)] 'my-up-line)
(global-set-key '[(control x) (down)] 'my-down-line)
(defun my-down-line()
(interactive)
(let ((col (current-column)))
(forward-line 1)
(transpose-lines 1)
(forward-line -1)
(forward-char col)
)
)
(defun my-up-line()
(interactive)
(let ((col (current-column)))
(transpose-lines 1)
(forward-line -2)
(forward-char col)
)
)