Emacs configuration file

About

This is an Emacs configuration file written in Org mode. It is an attempt to keep my ~/.emacs.d tidy, but still be able to keep it all in one file. I aim to briefly explain all my configurations as I go along!

I would not recommend using this configuration as-is, because it probably contains a lot you don’t really need. I do, however, hope people find some golden nuggets that they can smuggle into their own configs.

If you really do want to try this config out, this is how I’d go about it:

Clone the repo.

git clone https://github.com/larstvei/dot-emacs

Backup your old ~/.emacs.d (if necessary).

mv ~/.emacs.d ~/.emacs.d-bak

Backup your old ~/.emacs-file (if necessary).

mv ~/.emacs ~/.emacs-bak

And finally

mv dot-emacs ~/.emacs.d

On first run it should install a bunch of packages (this might take a while), and you might have to restart your Emacs the first time. If you experience bugs, please let me know!

Configurations

Meta

All changes to the configuration should be done in init.org, not in init.el. Any changes in the init.el will be overwritten by saving init.org. The init.el in this repo should not be tracked by git, and is replaced the first time Emacs is started (assuming it has been renamed to ~/.emacs.d).

Emacs can’t load .org-files directly, but org-mode provides functions to extract the code blocks and write them to a file. There are multiple ways of handling this; like suggested by this StackOverflow post, one could just use org-babel-load-file, but I had problems with byte-compilation. Previously I tracked both the org.- and el.-files, but the git commits got a little messy. So here is a new approach.

When this configuration is loaded for the first time, the init.el is the file that is loaded. It looks like this:

;; This file replaces itself with the actual configuration at first run.

;; We can't tangle without org!
(require 'org)
;; Open the configuration
(find-file (concat user-emacs-directory "init.org"))
;; tangle it
(org-babel-tangle)
;; load it
(load-file (concat user-emacs-directory "init.el"))
;; finally byte-compile it
(byte-compile-file (concat user-emacs-directory "init.el"))

It tangles the org-file, so that this file is overwritten with the actual configuration.

There is no reason to track the init.el that is generated; by running the following command git will not bother tracking it:

git update-index --assume-unchanged init.el

If one wishes to make changes to the repo-version of init.el start tracking again with:

git update-index --no-assume-unchanged init.el

The init.el should (after the first run) mirror the source blocks in the init.org. We can use C-c C-v t to run org-babel-tangle, which extracts the code blocks from the current file into a source-specific file (in this case a .el-file).

To avoid doing this each time a change is made we can add a function to the after-save-hook ensuring to always tangle and byte-compile the org-document after changes.

(defun tangle-init ()
  "If the current buffer is 'init.org' the code-blocks are
tangled, and the tangled file is compiled."
  (when (equal (buffer-file-name)
               (expand-file-name (concat user-emacs-directory "init.org")))
    ;; Avoid running hooks when tangling.
    (let ((prog-mode-hook nil))
      (org-babel-tangle)
      (byte-compile-file (concat user-emacs-directory "init.el")))))

(add-hook 'after-save-hook 'tangle-init)

I’d like to keep a few settings private, so we load a private.el if it exists after the init-file has loaded.

(add-hook
 'after-init-hook
 (lambda ()
   (let ((private-file (concat user-emacs-directory "private.el")))
     (when (file-exists-p private-file)
       (load-file private-file)))))

Packages

Managing extensions for Emacs is simplified using package which is built in to Emacs 24 and newer. To load downloaded packages we need to initialize package. cl is a library that contains many functions from Common Lisp, and comes in handy quite often, so we want to make sure it’s loaded, along with package, which is obviously needed.

(require 'cl)
(require 'package)
(package-initialize)

Packages can be fetched from different mirrors, melpa is the largest archive and is well maintained.

(setq package-archives
      '(("gnu" . "http://elpa.gnu.org/packages/")
        ("org" . "http://orgmode.org/elpa/")
        ("melpa" . "https://melpa.org/packages/")
        ("melpa-stable" . "https://stable.melpa.org/packages/")))

(add-to-list 'package-pinned-packages '(cider . "melpa-stable") t)

The configuration assumes that the packages listed below are installed. To ensure we install missing packages if they are missing.

(let* ((packages
        '(auto-compile         ; automatically compile Emacs Lisp libraries
          cider                ; Clojure Interactive Development Environment
          company              ; Modular text completion framework
          define-word          ; display the definition of word at point
          diminish             ; Diminished modes from modeline
          drag-stuff           ; Drag stuff around in Emacs
          expand-region        ; Increase selected region by semantic units
          focus                ; Dim color of text in surrounding sections
          idle-require         ; load elisp libraries while Emacs is idle
          geiser               ; GNU Emacs and Scheme talk to each other
          git-gutter-fringe    ; Fringe version of git-gutter.el
          golden-ratio         ; Automatic resizing windows to golden ratio
          haskell-mode         ; A Haskell editing mode
          helm                 ; Incremental and narrowing framework
          helm-company         ; Helm interface for company-mode
          helm-projectile      ; Helm integration for Projectile
          helm-swoop           ; Efficiently hopping squeezed lines
          jedi                 ; Python auto-completion for Emacs
          js2-mode             ; Improved JavaScript editing mode
          magit                ; control Git from Emacs
          markdown-mode        ; Emacs Major mode for Markdown-formatted files
          material-theme       ; A Theme based on Google Material Design
          matlab-mode          ; MATLAB integration with Emacs
          maude-mode           ; Emacs mode for the programming language Maude
          multiple-cursors     ; Multiple cursors for Emacs
          olivetti             ; Minor mode for a nice writing environment
          org                  ; Outline-based notes management and organizer
          paredit              ; minor mode for editing parentheses
          pdf-tools            ; Emacs support library for PDF files
          projectile           ; Manage and navigate projects in Emacs easily
          slime                ; Superior Lisp Interaction Mode for Emacs
          try))                ; Try out Emacs packages
       ;; Remove all packages already installed
       (packages (remove-if 'package-installed-p packages)))
  (when packages
    (ignore-errors (package-refresh-contents)
                   (mapcar 'package-install packages)
                   ;; This package is only relevant for Mac OS X.
                   (when (memq window-system '(mac ns))
                     (package-install 'exec-path-from-shell)))))

Mac OS X

I run this configuration mostly on Mac OS X, so we need a couple of settings to make things work smoothly. In the package section exec-path-from-shell is included (only if you’re running OS X), this is to include environment-variables from the shell. It makes using Emacs along with external processes a lot simpler. I also prefer using the Command-key as the Meta-key.

(when (memq window-system '(mac ns))
  (setq ns-pop-up-frames nil
        mac-option-modifier nil
        mac-command-modifier 'meta
        x-select-enable-clipboard t)
  (exec-path-from-shell-initialize))

Require

Some features are not loaded by default to minimize initialization time, so they have to be required (or loaded, if you will). require-calls tends to lead to the largest bottleneck’s in a configuration. idle-require delays the require-calls to a time where Emacs is in idle. So this is great for stuff you eventually want to load, but is not a high priority.

(require 'idle-require)             ; Need in order to use idle-require

(dolist (feature
         '(auto-compile             ; auto-compile .el files
           jedi                     ; auto-completion for python
           matlab                   ; matlab-mode
           ob-matlab                ; org-babel matlab
           ox-latex                 ; the latex-exporter (from org)
           ox-md                    ; Markdown exporter (from org)
           recentf                  ; recently opened files
           tex-mode))               ; TeX, LaTeX, and SliTeX mode commands
  (idle-require feature))

(setq idle-require-idle-delay 5)
(idle-require-mode 1)

Sane defaults

These are what I consider to be saner defaults.

We can set variables to whatever value we’d like using setq.

(setq auto-revert-interval 1            ; Refresh buffers fast
      custom-file (make-temp-file "")   ; Discard customization's
      default-input-method "TeX"        ; Use TeX when toggling input method
      echo-keystrokes 0.1               ; Show keystrokes asap
      inhibit-startup-message t         ; No splash screen please
      initial-scratch-message nil       ; Clean scratch buffer
      recentf-max-saved-items 100       ; Show more recent files
      ring-bell-function 'ignore        ; Quiet
      sentence-end-double-space nil)    ; No double space
;; Some mac-bindings interfere with Emacs bindings.
(when (boundp 'mac-pass-command-to-system)
  (setq mac-pass-command-to-system nil))

Some variables are buffer-local, so changing them using setq will only change them in a single buffer. Using setq-default we change the buffer-local variable’s default value.

(setq-default fill-column 79                    ; Maximum line width
              truncate-lines t                  ; Don't fold lines
              indent-tabs-mode nil              ; Use spaces instead of tabs
              split-width-threshold 100         ; Split verticly by default
              auto-fill-function 'do-auto-fill) ; Auto-fill-mode everywhere

The load-path specifies where Emacs should look for .el-files (or Emacs lisp files). I have a directory called site-lisp where I keep all extensions that have been installed manually (these are mostly my own projects).

(let ((default-directory (concat user-emacs-directory "site-lisp/")))
  (when (file-exists-p default-directory)
    (setq load-path
          (append
           (let ((load-path (copy-sequence load-path)))
             (normal-top-level-add-subdirs-to-load-path)) load-path))))

Answering yes and no to each question from Emacs can be tedious, a single y or n will suffice.

(fset 'yes-or-no-p 'y-or-n-p)

To avoid file system clutter we put all auto saved files in a single directory.

(defvar emacs-autosave-directory
  (concat user-emacs-directory "autosaves/")
  "This variable dictates where to put auto saves. It is set to a
  directory called autosaves located wherever your .emacs.d/ is
  located.")

;; Sets all files to be backed up and auto saved in a single directory.
(setq backup-directory-alist
      `((".*" . ,emacs-autosave-directory))
      auto-save-file-name-transforms
      `((".*" ,emacs-autosave-directory t)))

Set utf-8 as preferred coding system.

(set-language-environment "UTF-8")

By default the narrow-to-region command is disabled and issues a warning, because it might confuse new users. I find it useful sometimes, and don’t want to be warned.

(put 'narrow-to-region 'disabled nil)

Automaticly revert doc-view-buffers when the file changes on disk.

(add-hook 'doc-view-mode-hook 'auto-revert-mode)

Modes

There are some modes that are enabled by default that I don’t find particularly useful. We create a list of these modes, and disable all of these.

(dolist (mode
         '(tool-bar-mode                ; No toolbars, more room for text
           scroll-bar-mode              ; No scroll bars either
           blink-cursor-mode))          ; The blinking cursor gets old
  (funcall mode 0))

Let’s apply the same technique for enabling modes that are disabled by default.

(dolist (mode
         '(abbrev-mode                  ; E.g. sopl -> System.out.println
           column-number-mode           ; Show column number in mode line
           delete-selection-mode        ; Replace selected text
           dirtrack-mode                ; directory tracking in *shell*
           drag-stuff-global-mode       ; Drag stuff around
           global-company-mode          ; Auto-completion everywhere
           global-git-gutter-mode       ; Show changes latest commit
           global-prettify-symbols-mode ; Greek letters should look greek
           golden-ratio-mode            ; Automatic resizing of windows
           projectile-global-mode       ; Manage and navigate projects
           recentf-mode                 ; Recently opened files
           show-paren-mode))            ; Highlight matching parentheses
  (funcall mode 1))

(when (version< emacs-version "24.4")
  (eval-after-load 'auto-compile
    '((auto-compile-on-save-mode 1))))  ; compile .el files on save

Visual

Change the color-theme to leuven.

(load-theme 'leuven t)

leuven is my preferred light theme, but monokai makes a very nice dark theme. I want to be able to cycle between these.

(defun cycle-themes ()
  "Returns a function that lets you cycle your themes."
  (lexical-let ((themes '#1=(leuven material . #1#)))
    (lambda ()
      (interactive)
      ;; Rotates the thme cycle and changes the current theme.
      (load-theme (car (setq themes (cdr themes))) t))))

Use the Inconsolata font if it’s installed on the system.

(cond ((member "Source Code Pro" (font-family-list))
       (set-face-attribute 'default nil :font "Source Code Pro-13"))
      ((member "Inconsolata" (font-family-list))
       (set-face-attribute 'default nil :font "Inconsolata-14")))

diminish.el allows you to hide or abbreviate their presence in the modeline. I rarely look at the modeline to find out what minor-modes are enabled, so I disable every global minor-mode, and some for lisp editing.

To ensure that the mode is loaded before diminish it, we should use with-eval-after-load. To avoid typing this multiple times a small macro is provided.

(defmacro safe-diminish (file mode &optional new-name)
  `(with-eval-after-load ,file
     (diminish ,mode ,new-name)))

(diminish 'auto-fill-function)
(safe-diminish "eldoc" 'eldoc-mode)
(safe-diminish "flyspell" 'flyspell-mode)
(safe-diminish "helm-mode" 'helm-mode)
(safe-diminish "projectile" 'projectile-mode)
(safe-diminish "paredit" 'paredit-mode "()")

git-gutter-fringe gives a great visual indication of where you’ve made changes since your last commit. There are several packages that performs this task; the reason I’ve ended up with git-gutter-fringe is that it reuses the (already present) fringe, saving a tiny bit of screen-estate.

I smuggled some configurations from torenord, providing a cleaner look.

(require 'git-gutter-fringe)

(dolist (p '((git-gutter:added    . "#0c0")
             (git-gutter:deleted  . "#c00")
             (git-gutter:modified . "#c0c")))
  (set-face-foreground (car p) (cdr p))
  (set-face-background (car p) (cdr p)))

New in Emacs 24.4 is the prettify-symbols-mode! It’s neat.

(setq-default prettify-symbols-alist '(("lambda" . )
                                       ("delta" . )
                                       ("gamma" . )
                                       ("phi" . )
                                       ("psi" . )))

PDF Tools

PDF Tools makes a huge improvement on the built-in doc-view-mode; the only drawback is the pdf-tools-install (which has to be executed before the package can be used) takes a couple of seconds to execute. Instead of running it at init-time, we’ll run it whenever a PDF is opened. Note that it’s only slow on the first run!

(add-hook 'pdf-tools-enabled-hook 'auto-revert-mode)
(add-to-list 'auto-mode-alist '("\\.pdf\\'" . pdf-tools-install))

Completion

Auto-Complete has been a part of my config for years, but I want to try out company-mode. If I code in an environment with good completion, I’ve made an habit of trying to guess function-names, and looking at the completions for the right one. So I want a pretty aggressive completion system, hence the no delay settings and short prefix length.

(setq company-idle-delay 0
      company-echo-delay 0
      company-dabbrev-downcase nil
      company-minimum-prefix-length 2
      company-selection-wrap-around t
      company-transformers '(company-sort-by-occurrence
                             company-sort-by-backend-importance))

Helm

I’ve been a long time user of ido-mode along with ido-vertical-mode, and don’t have any particular complaints. Though I’ve got a feeling I’m missing out on something by not using helm. I will this excellent tutorial as a starting point, along with some of the suggested configurations.

helm has a wonderful feature, being able to grep files by C-s anywhere, which is useful. ack is a great grep-replacement, and is designed to search source code, so I want to use that if it’s available.

Note that some changes in bindings are located in the key bindings (found near the end of the configuration).

(require 'helm)
(require 'helm-config)

(setq helm-split-window-in-side-p t
      helm-M-x-fuzzy-match t
      helm-buffers-fuzzy-matching t
      helm-recentf-fuzzy-match t
      helm-move-to-line-cycle-in-source t
      projectile-completion-system 'helm)

(when (executable-find "ack")
  (setq helm-grep-default-command
        "ack -Hn --no-group --no-color %e %p %f"
        helm-grep-default-recurse-command
        "ack -H --no-group --no-color %e %p %f"))

(set-face-attribute 'helm-selection nil :background "cyan")

(helm-mode 1)
(helm-projectile-on)
(helm-adaptive-mode 1)

Calendar

Define a function to display week numbers in calender-mode. The snippet is from EmacsWiki.

(defun calendar-show-week (arg)
  "Displaying week number in calendar-mode."
  (interactive "P")
  (copy-face font-lock-constant-face 'calendar-iso-week-face)
  (set-face-attribute
   'calendar-iso-week-face nil :height 0.7)
  (setq calendar-intermonth-text
        (and arg
             '(propertize
               (format
                "%2d"
                (car (calendar-iso-from-absolute
                      (calendar-absolute-from-gregorian
                       (list month day year)))))
               'font-lock-face 'calendar-iso-week-face))))

Evaluate the calendar-show-week function.

(calendar-show-week t)

Set Monday as the first day of the week, and set my location.

(setq calendar-week-start-day 1
      calendar-latitude 60.0
      calendar-longitude 10.7
      calendar-location-name "Oslo, Norway")

mu4e and offlineimap

I might not be at a computer using my very specific mail-setup, but if my mail-folder exists, then it’s probably safe to load.

(defvar load-mail-setup (file-exists-p "~/.ifimail"))

I use mu4e (which is a part of mu) along with offlineimap on one of my computers.

mu4e

mu4e must be informed where it can find your mail and where the different folders of interest are located. Some additional mu4e-tweaks are supplied here as well.

message-insert-signature is an existing Emacs function, that adds your signature prefixed by a ~”– “~ at the end of the email, which is a convention I don’t really follow. I redefine it as a function that adds some newlines and my signature at the top of the email.

(when load-mail-setup
  (eval-after-load 'mu4e
    '(progn
       ;; Some basic mu4e settings.
       (setq mu4e-maildir           "~/.ifimail"     ; top-level Maildir
             mu4e-sent-folder       "/Sent Items"    ; folder for sent messages
             mu4e-drafts-folder     "/INBOX.Drafts"  ; unfinished messages
             mu4e-trash-folder      "/INBOX.Trash"   ; trashed messages
             mu4e-get-mail-command  "offlineimap"    ; offlineimap to fetch mail
             mu4e-compose-signature "- Lars"         ; Sign my name
             mu4e-update-interval   (* 5 60)         ; update every 5 min
             mu4e-confirm-quit      nil              ; just quit
             mu4e-view-show-images  t                ; view images
             mu4e-html2text-command
             "html2text -utf8")                      ; use utf-8

       ;; Setup for sending mail.
       (setq user-full-name
             "Lars Tveito"                          ; Your full name
             user-mail-address
             "larstvei@ifi.uio.no"                  ; And email-address
             smtpmail-smtp-server
             "smtp.uio.no"                          ; Host to mail-server
             smtpmail-smtp-service 465              ; Port to mail-server
             smtpmail-stream-type 'ssl              ; Protocol used for sending
             send-mail-function 'smtpmail-send-it   ; Use smpt to send
             mail-user-agent 'mu4e-user-agent)      ; Use mu4e

       ;; Register file types that can be handled by ImageMagick.
       (when (fboundp 'imagemagick-register-types)
         (imagemagick-register-types))

       (add-hook 'mu4e-compose-mode-hook
                 (lambda ()
                   (auto-fill-mode 0)
                   (visual-line-mode 1)
                   (ispell-change-dictionary "norsk")))

       (add-hook 'mu4e-view-mode-hook (lambda () (visual-line-mode 1)))

       (defun message-insert-signature ()
         (goto-char (point-min))
         (search-forward-regexp "^$")
         (insert "\n\n\n" mu4e-compose-signature))))

  (autoload 'mu4e "mu4e" nil t))

Flyspell

Flyspell offers on-the-fly spell checking. We can enable flyspell for all text-modes with this snippet.

(add-hook 'text-mode-hook 'turn-on-flyspell)

To use flyspell for programming there is flyspell-prog-mode, that only enables spell checking for comments and strings. We can enable it for all programming modes using the prog-mode-hook.

(add-hook 'prog-mode-hook 'flyspell-prog-mode)

When working with several languages, we should be able to cycle through the languages we most frequently use. Every buffer should have a separate cycle of languages, so that cycling in one buffer does not change the state in a different buffer (this problem occurs if you only have one global cycle). We can implement this by using a closure.

(defun cycle-languages ()
  "Changes the ispell dictionary to the first element in
ISPELL-LANGUAGES, and returns an interactive function that cycles
the languages in ISPELL-LANGUAGES when invoked."
  (lexical-let ((ispell-languages '#1=("american" "norsk" . #1#)))
    (ispell-change-dictionary (car ispell-languages))
    (lambda ()
      (interactive)
      ;; Rotates the languages cycle and changes the ispell dictionary.
      (ispell-change-dictionary
       (car (setq ispell-languages (cdr ispell-languages)))))))

flyspell signals an error if there is no spell-checking tool is installed. We can advice turn-on-flyspell and flyspell-prog-mode to only try to enable flyspell if a spell-checking tool is available. Also we want to enable cycling the languages by typing C-c l, so we bind the function returned from cycle-languages.

(defadvice turn-on-flyspell (before check nil activate)
  "Turns on flyspell only if a spell-checking tool is installed."
  (when (executable-find ispell-program-name)
    (local-set-key (kbd "C-c l") (cycle-languages))))
(defadvice flyspell-prog-mode (before check nil activate)
  "Turns on flyspell only if a spell-checking tool is installed."
  (when (executable-find ispell-program-name)
    (local-set-key (kbd "C-c l") (cycle-languages))))

Org

I use org-agenda along with org-capture for appointments and such.

(setq org-agenda-files '("~/Dropbox/agenda.org")  ; A list of agenda files
      org-agenda-default-appointment-duration 120 ; 2 hours appointments
      org-capture-templates                       ; Template for adding tasks
      '(("t" "Oppgave" entry (file+headline "~/Dropbox/agenda.org" "Oppgaver")
         "** TODO %?" :prepend t)
        ("m" "Master" entry (file+olp "~/Dropbox/agenda.org" "Oppgaver" "Master")
         "*** TODO %?" :prepend t)
        ("a" "Avtale" entry (file+headline "~/Dropbox/agenda.org" "Avtaler")
         "** %?\n   SCHEDULED: %T" :prepend t)))

When editing org-files with source-blocks, we want the source blocks to be themed as they would in their native mode.

(setq org-src-fontify-natively t
      org-src-tab-acts-natively t
      org-confirm-babel-evaluate nil
      org-edit-src-content-indentation 0)

This is quite an ugly fix for allowing code markup for expressions like =”this string”=, because the quotation marks causes problems.

;;(require 'org)
(eval-after-load "org"
  '(progn
     (setcar (nthcdr 2 org-emphasis-regexp-components) " \t\n,")
     (custom-set-variables `(org-emphasis-alist ',org-emphasis-alist))))

Interactive functions

<sec:defuns>

just-one-space removes all whitespace around a point - giving it a negative argument it removes newlines as well. We wrap a interactive function around it to be able to bind it to a key. In Emacs 24.4 cycle-spacing was introduced, and it works like just-one-space, but when run in succession it cycles between one, zero and the original number of spaces.

(defun cycle-spacing-delete-newlines ()
  "Removes whitespace before and after the point."
  (interactive)
  (if (version< emacs-version "24.4")
      (just-one-space -1)
    (cycle-spacing -1)))

Often I want to find other occurrences of a word I’m at, or more specifically the symbol (or tag) I’m at. The isearch-forward-symbol-at-point in Emacs 24.4 works well for this, but I don’t want to be bothered with the isearch interface. Rather jump quickly between occurrences of a symbol, or if non is found, don’t do anything.

(defun jump-to-symbol-internal (&optional backwardp)
  "Jumps to the next symbol near the point if such a symbol
exists. If BACKWARDP is non-nil it jumps backward."
  (let* ((point (point))
         (bounds (find-tag-default-bounds))
         (beg (car bounds)) (end (cdr bounds))
         (str (isearch-symbol-regexp (find-tag-default)))
         (search (if backwardp 'search-backward-regexp
                   'search-forward-regexp)))
    (goto-char (if backwardp beg end))
    (funcall search str nil t)
    (cond ((<= beg (point) end) (goto-char point))
          (backwardp (forward-char (- point beg)))
          (t  (backward-char (- end point))))))

(defun jump-to-previous-like-this ()
  "Jumps to the previous occurrence of the symbol at point."
  (interactive)
  (jump-to-symbol-internal t))

(defun jump-to-next-like-this ()
  "Jumps to the next occurrence of the symbol at point."
  (interactive)
  (jump-to-symbol-internal))

I sometimes regret killing the *scratch*-buffer, and have realized I never want to actually kill it. I just want to get it out of the way, and clean it up. The function below does just this for the *scratch*-buffer, and works like kill-this-buffer for any other buffer. It removes all buffer content and buries the buffer (this means making it the least likely candidate for other-buffer).

(defun kill-this-buffer-unless-scratch ()
  "Works like `kill-this-buffer' unless the current buffer is the
*scratch* buffer. In witch case the buffer content is deleted and
the buffer is buried."
  (interactive)
  (if (not (string= (buffer-name) "*scratch*"))
      (kill-this-buffer)
    (delete-region (point-min) (point-max))
    (switch-to-buffer (other-buffer))
    (bury-buffer "*scratch*")))

To duplicate either selected text or a line we define this interactive function.

(defun duplicate-thing (comment)
  "Duplicates the current line, or the region if active. If an argument is
given, the duplicated region will be commented out."
  (interactive "P")
  (save-excursion
    (let ((start (if (region-active-p) (region-beginning) (point-at-bol)))
          (end   (if (region-active-p) (region-end) (point-at-eol))))
      (goto-char end)
      (unless (region-active-p)
        (newline))
      (insert (buffer-substring start end))
      (when comment (comment-region start end)))))

To tidy up a buffer we define this function borrowed from simenheg.

(defun tidy ()
  "Ident, untabify and unwhitespacify current buffer, or region if active."
  (interactive)
  (let ((beg (if (region-active-p) (region-beginning) (point-min)))
        (end (if (region-active-p) (region-end) (point-max))))
    (indent-region beg end)
    (whitespace-cleanup)
    (untabify beg (if (< end (point-max)) end (point-max)))))

Org mode does currently not support synctex (which enables you to jump from a point in your TeX-file to the corresponding point in the pdf), and it seems like a tricky problem.

Calling this function from an org-buffer jumps to the corresponding section in the exported pdf (given that the pdf-file exists), using pdf-tools.

(defun org-sync-pdf ()
  (interactive)
  (let ((headline (nth 4 (org-heading-components)))
        (pdf (concat (file-name-base (buffer-name)) ".pdf")))
    (when (file-exists-p pdf)
      (find-file-other-window pdf)
      (pdf-links-action-perform
       (cl-find headline (pdf-info-outline pdf)
                :key (lambda (alist) (cdr (assoc 'title alist)))
                :test 'string-equal)))))

Advice

An advice can be given to a function to make it behave differently. This advice makes eval-last-sexp (bound to C-x C-e) replace the sexp with the value.

(defadvice eval-last-sexp (around replace-sexp (arg) activate)
  "Replace sexp when called with a prefix argument."
  (if arg
      (let ((pos (point)))
        ad-do-it
        (goto-char pos)
        (backward-kill-sexp)
        (forward-sexp))
    ad-do-it))

When interactively changing the theme (using M-x load-theme), the current custom theme is not disabled. This often gives weird-looking results; we can advice load-theme to always disable themes currently enabled themes.

(defadvice load-theme
    (before disable-before-load (theme &optional no-confirm no-enable) activate)
  (mapc 'disable-theme custom-enabled-themes))

global-scale-mode

These functions provide something close to text-scale-mode, but for every buffer, including the minibuffer and mode line.

(lexical-let* ((default (face-attribute 'default :height))
               (size default))

  (defun global-scale-default ()
    (interactive)
    (setq size default)
    (global-scale-internal size))

  (defun global-scale-up ()
    (interactive)
    (global-scale-internal (incf size 20)))

  (defun global-scale-down ()
    (interactive)
    (global-scale-internal (decf size 20)))

  (defun global-scale-internal (arg)
    (set-face-attribute 'default (selected-frame) :height arg)
    (set-temporary-overlay-map
     (let ((map (make-sparse-keymap)))
       (define-key map (kbd "C-=") 'global-scale-up)
       (define-key map (kbd "C-+") 'global-scale-up)
       (define-key map (kbd "C--") 'global-scale-down)
       (define-key map (kbd "C-0") 'global-scale-default) map))))

Mode specific

Shell

I use shell whenever i want to use access the command line in Emacs. I keep a symlink between my ~/.bash_profile (because I run OS X) and ~/.emacs_bash, to make the transition between my standard terminal and the shell as small as possible. To be able to quickly switch back and forth between a shell I make use of this little function.

(defun toggle-shell ()
  "Jumps to eshell or back."
  (interactive)
  (if (string= (buffer-name) "*shell*")
      (switch-to-prev-buffer)
    (shell)))

I’d like the C-l to work more like the standard terminal (which works like running clear), and resolve this by simply removing the buffer-content. Mind that this is not how clear works, it simply adds a bunch of newlines, and puts the prompt at the top of the window, so it does not remove anything. In Emacs removing stuff is less of a worry, since we can always undo!

(defun clear-comint ()
  "Runs `comint-truncate-buffer' with the
`comint-buffer-maximum-size' set to zero."
  (interactive)
  (let ((comint-buffer-maximum-size 0))
    (comint-truncate-buffer)))

Lastly we should bind our functions. The toggle-shell should be a global binding (because we want to be able to switch to a shell from any buffer), but the clear-shell should only affect shell-mode.

(add-hook 'comint-mode-hook (lambda () (local-set-key (kbd "C-l") 'clear-comint)))

Lisp

I use Paredit when editing lisp code, we enable this for all lisp-modes.

(dolist (mode '(cider-repl-mode
                clojure-mode
                ielm-mode
                geiser-repl-mode
                slime-repl-mode
                lisp-mode
                emacs-lisp-mode
                lisp-interaction-mode
                scheme-mode))
  ;; add paredit-mode to all mode-hooks
  (add-hook (intern (concat (symbol-name mode) "-hook")) 'paredit-mode))

Emacs Lisp

In emacs-lisp-mode we can enable eldoc-mode to display information about a function or a variable in the echo area.

(add-hook 'emacs-lisp-mode-hook 'turn-on-eldoc-mode)
(add-hook 'lisp-interaction-mode-hook 'turn-on-eldoc-mode)

Common lisp

I use Slime along with lisp-mode to edit Common Lisp code. Slime provides code evaluation and other great features, a must have for a Common Lisp developer. Quicklisp is a library manager for Common Lisp, and you can install Slime following the instructions from the site along with this snippet.

(defun activate-slime-helper ()
  (when (file-exists-p "~/.quicklisp/slime-helper.el")
    (load (expand-file-name "~/.quicklisp/slime-helper.el"))
    (define-key slime-repl-mode-map (kbd "C-l")
      'slime-repl-clear-buffer))
  (remove-hook 'lisp-mode-hook #'activate-slime-helper))

(add-hook 'lisp-mode-hook #'activate-slime-helper)

We can specify what Common Lisp program Slime should use (I use SBCL).

(setq inferior-lisp-program "sbcl")

More sensible loop indentation, borrowed from simenheg.

(setq lisp-loop-forms-indentation   6
      lisp-simple-loop-indentation  2
      lisp-loop-keyword-indentation 6)

Scheme

Geiser provides features similar to Slime for Scheme editing. Everything works pretty much out of the box, we only need to add auto completion, and specify which scheme-interpreter we prefer.

(eval-after-load "geiser"
  '(setq geiser-active-implementations '(guile)))

Java and C

The c-mode-common-hook is a general hook that work on all C-like languages (C, C++, Java, etc…). I like being able to quickly compile using C-c C-c (instead of M-x compile), a habit from latex-mode.

(defun c-setup ()
  (local-set-key (kbd "C-c C-c") 'compile))

(add-hook 'c-mode-common-hook 'c-setup)

Some statements in Java appear often, and become tedious to write out. We can use abbrevs to speed this up.

(define-abbrev-table 'java-mode-abbrev-table
  '(("psv" "public static void main(String[] args) {" nil 0)
    ("sopl" "System.out.println" nil 0)
    ("sop" "System.out.printf" nil 0)))

To be able to use the abbrev table defined above, abbrev-mode must be activated.

(defun java-setup ()
  (abbrev-mode t)
  (setq-local compile-command (concat "javac " (buffer-name))))

(add-hook 'java-mode-hook 'java-setup)

Assembler

When writing assembler code I use # for comments. By defining comment-start we can add comments using M-; like in other programming modes. Also in assembler should one be able to compile using C-c C-c.

(defun asm-setup ()
  (setq comment-start "#")
  (local-set-key (kbd "C-c C-c") 'compile))

(add-hook 'asm-mode-hook 'asm-setup)

LaTeX and org-mode LaTeX export

.tex-files should be associated with latex-mode instead of tex-mode.

(add-to-list 'auto-mode-alist '("\\.tex\\'" . latex-mode))

Use biblatex for bibliography.

(setq-default bibtex-dialect 'biblatex)

I like using the Minted package for source blocks in LaTeX. To make org use this we add the following snippet.

(eval-after-load 'org
  '(add-to-list 'org-latex-packages-alist '("" "minted")))
(setq org-latex-listings 'minted)

Because Minted uses Pygments (an external process), we must add the -shell-escape option to the org-latex-pdf-process commands. The tex-compile-commands variable controls the default compile command for Tex- and LaTeX-mode, we can add the flag with a rather dirty statement (if anyone finds a nicer way to do this, please let me know).

(eval-after-load 'tex-mode
  '(setcar (cdr (cddaar tex-compile-commands)) " -shell-escape "))

When exporting from Org to LaTeX, use latexmk for compilation.

(eval-after-load 'ox-latex
  '(setq org-latex-pdf-process
         '("latexmk -pdflatex='pdflatex -shell-escape -interaction nonstopmode' -pdf -f %f")))

For my thesis, I need to use our university’s LaTeX class, this snippet makes that class available.

(eval-after-load "ox-latex"
  '(progn
     (add-to-list 'org-latex-classes
                  '("ifimaster"
                    "\\documentclass{ifimaster}
[DEFAULT-PACKAGES]
[PACKAGES]
[EXTRA]
\\usepackage{babel,csquotes,ifimasterforside,url,varioref}"
                   ("\\chapter{%s}" . "\\chapter*{%s}")
                   ("\\section{%s}" . "\\section*{%s}")
                   ("\\subsection{%s}" . "\\subsection*{%s}")
                   ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
                   ("\\paragraph{%s}" . "\\paragraph*{%s}")
                   ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
    (custom-set-variables '(org-export-allow-bind-keywords t))))

Markdown

This makes .md-files open in markdown-mode.

(add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))

I sometimes use a specialized markdown format, where inline math-blocks can be achieved by surrounding a LaTeX formula with $math$ and $/math$. Writing these out became tedious, so I wrote a small function.

(defun insert-markdown-inline-math-block ()
  "Inserts an empty math-block if no region is active, otherwise wrap a
math-block around the region."
  (interactive)
  (let* ((beg (region-beginning))
         (end (region-end))
         (body (if (region-active-p) (buffer-substring beg end) "")))
    (when (region-active-p)
      (delete-region beg end))
    (insert (concat "$math$ " body " $/math$"))
    (search-backward " $/math$")))

Most of my writing in this markup is in Norwegian, so the dictionary is set accordingly. The markup is also sensitive to line breaks, so auto-fill-mode is disabled. Of course we want to bind our lovely function to a key!

(add-hook 'markdown-mode-hook
          (lambda ()
            (auto-fill-mode 0)
            (visual-line-mode 1)
            (ispell-change-dictionary "norsk")
            (local-set-key (kbd "C-c b") 'insert-markdown-inline-math-block)) t)

Python

Haskell

haskell-doc-mode is similar to eldoc, it displays documentation in the echo area. Haskell has several indentation modes - I prefer using haskell-indent.

(add-hook 'haskell-mode-hook 'turn-on-haskell-doc-mode)
(add-hook 'haskell-mode-hook 'turn-on-haskell-indent)

Maude

Use --- for comments in Maude.

(add-hook 'maude-mode-hook
          (lambda ()
            (setq-local comment-start "---")))

Matlab

Matlab-mode works pretty good out of the box, but we can do without the splash screen.

(eval-after-load 'matlab
  '(add-to-list 'matlab-shell-command-switches "-nosplash"))

Key bindings

Inspired by this StackOverflow post I keep a custom-bindings-map that holds all my custom bindings. This map can be activated by toggling a simple minor-mode that does nothing more than activating the map. This inhibits other major-modes to override these bindings. I keep this at the end of the init-file to make sure that all functions are actually defined.

(defvar custom-bindings-map (make-keymap)
  "A keymap for custom bindings.")

Bindings for define-word

(define-key custom-bindings-map (kbd "C-c D") 'define-word-at-point)

Bindings for expand-region

(define-key custom-bindings-map (kbd "C->")  'er/expand-region)
(define-key custom-bindings-map (kbd "C-<")  'er/contract-region)

Bindings for multiple-cursors

(define-key custom-bindings-map (kbd "C-c e")  'mc/edit-lines)
(define-key custom-bindings-map (kbd "C-c a")  'mc/mark-all-like-this)
(define-key custom-bindings-map (kbd "C-c n")  'mc/mark-next-like-this)

Bindings for Magit

(define-key custom-bindings-map (kbd "C-c m") 'magit-status)

Bindings for company-mode

(define-key company-active-map (kbd "C-d") 'company-show-doc-buffer)
(define-key company-active-map (kbd "C-n") 'company-select-next)
(define-key company-active-map (kbd "C-p") 'company-select-previous)
(define-key company-active-map (kbd "<tab>") 'company-complete)

(define-key company-mode-map (kbd "C-:") 'helm-company)
(define-key company-active-map (kbd "C-:") 'helm-company)

Bindings for Helm

(define-key custom-bindings-map (kbd "C-c h")   'helm-command-prefix)
(define-key custom-bindings-map (kbd "M-x")     'helm-M-x)
(define-key custom-bindings-map (kbd "M-y")     'helm-show-kill-ring)
(define-key custom-bindings-map (kbd "C-x b")   'helm-mini)
(define-key custom-bindings-map (kbd "C-x C-f") 'helm-find-files)
(define-key custom-bindings-map (kbd "C-c h o") 'helm-occur)
(define-key custom-bindings-map (kbd "C-c h g") 'helm-google-suggest)
(define-key custom-bindings-map (kbd "M-i")     'helm-swoop)
(define-key custom-bindings-map (kbd "M-I")     'helm-multi-swoop-all)

(define-key helm-map (kbd "<tab>") 'helm-execute-persistent-action)
(define-key helm-map (kbd "C-i")   'helm-execute-persistent-action)
(define-key helm-map (kbd "C-z")   'helm-select-action)

Bindings for built-ins

(define-key custom-bindings-map (kbd "M-u")         'upcase-dwim)
(define-key custom-bindings-map (kbd "M-c")         'capitalize-dwim)
(define-key custom-bindings-map (kbd "M-l")         'downcase-dwim)
(define-key custom-bindings-map (kbd "M-]")         'other-frame)
(define-key custom-bindings-map (kbd "C-j")         'newline-and-indent)
(define-key custom-bindings-map (kbd "C-c s")       'ispell-word)
(define-key custom-bindings-map (kbd "C-c c")       'org-capture)
(define-key custom-bindings-map (kbd "C-x m")       'mu4e)
(define-key custom-bindings-map (kbd "C-c <up>")    'windmove-up)
(define-key custom-bindings-map (kbd "C-c <down>")  'windmove-down)
(define-key custom-bindings-map (kbd "C-c <left>")  'windmove-left)
(define-key custom-bindings-map (kbd "C-c <right>") 'windmove-right)
(define-key custom-bindings-map (kbd "C-c t")
  (lambda () (interactive) (org-agenda nil "n")))

Bindings for functions defined above.

(define-key global-map          (kbd "M-p")     'jump-to-previous-like-this)
(define-key global-map          (kbd "M-n")     'jump-to-next-like-this)
(define-key custom-bindings-map (kbd "M-,")     'jump-to-previous-like-this)
(define-key custom-bindings-map (kbd "M-.")     'jump-to-next-like-this)
(define-key custom-bindings-map (kbd "C-c .")   (cycle-themes))
(define-key custom-bindings-map (kbd "C-x k")   'kill-this-buffer-unless-scratch)
(define-key custom-bindings-map (kbd "C-c C-0") 'global-scale-default)
(define-key custom-bindings-map (kbd "C-c C-=") 'global-scale-up)
(define-key custom-bindings-map (kbd "C-c C-+") 'global-scale-up)
(define-key custom-bindings-map (kbd "C-c C--") 'global-scale-down)
(define-key custom-bindings-map (kbd "C-x t")   'toggle-shell)
(define-key custom-bindings-map (kbd "C-c j")   'cycle-spacing-delete-newlines)
(define-key custom-bindings-map (kbd "C-c d")   'duplicate-thing)
(define-key custom-bindings-map (kbd "<C-tab>") 'tidy)
(define-key custom-bindings-map (kbd "C-c C-q")
  '(lambda ()
     (interactive)
     (focus-mode 1)
     (focus-read-only-mode 1)))
(with-eval-after-load 'org
  (define-key org-mode-map (kbd "C-'") 'org-sync-pdf))

Lastly we need to activate the map by creating and activating the minor-mode.

(define-minor-mode custom-bindings-mode
  "A mode that activates custom-bindings."
  t nil custom-bindings-map)

License

My Emacs configurations written in Org mode.

Copyright (c) 2013 - 2015 Lars Tveito

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.



Emacs configuration file

About

这是使用组织模式编写的Emacs配置文件。这是一个尝试   保持我的〜/ .emacs.d 整洁,但仍然能够保持一切   文件。我的目标是简要解释我所有的配置,我一起去!

我不建议您按原样使用此配置,因为它是   可能包含很多你真的不需要。但是,我希望人们   找到一些金块,他们可以走私他们自己的配置。

如果你真的想尝试这个配置,这是我会如何去做的:

克隆回购。

备份旧的〜/ .emacs.d (如有必要)。

mv ~/.emacs.d ~/.emacs.d-bak

备份旧的〜/ .emacs -file(如有必要)。

mv ~/.emacs ~/.emacs-bak

最后

mv dot-emacs ~/.emacs.d
首先运行它应该安装一堆软件包(这可能需要一个   while),您可能必须首次重新启动Emacs。如果你   经验错误,请让我知道!

Configurations

配置的所有更改都应该在 init.org 而不是中完成    init.el init.el 中的任何更改都将被保存覆盖    init.org 。这个repo中的 init.el 不应该被git跟踪   第一次Emacs被启动时被替换(假设它被重命名)   到〜/ .emacs.d

Emacs无法直接加载 .org -files,但是 org-mode 提供函数   提取代码块并将其写入文件。有多个   处理方式;喜欢由这个StackOverflow的帖子,一个   可以使用 org-babel-load-file ,但是我有问题   字节编译。以前,我跟踪了 org。 el。 -files,   但是git的提交有点混乱。所以这里是一种新的方法

当第一次加载此配置时, init.el 是   加载的文件。看起来像这样:

;; This file replaces itself with the actual configuration at first run.

;; We can't tangle without org! (require 'org) ;; Open the configuration (find-file (concat user-emacs-directory "init.org")) ;; tangle it (org-babel-tangle) ;; load it (load-file (concat user-emacs-directory "init.el")) ;; finally byte-compile it (byte-compile-file (concat user-emacs-directory "init.el"))

它会缠结组织文件,以便该文件被实际覆盖   配置。

没有理由跟踪生成的 init.el ;通过运行   以下命令 git 不会麻烦跟踪它:

git update-index –assume-unchanged init.el

如果希望对 init.el 的repo版本进行更改   再次跟踪:

git update-index –no-assume-unchanged init.el
init.el 应该(第一次运行之后)镜像源块    init.org 。我们可以使用 C-c C-v t 来运行 org-babel-tangle ,其中   将当前文件中的代码块提取为源特定   文件(在这种情况下为 .el -file)。

为避免这样做,每次更改时,我们可以添加一个功能   确保始终纠缠和字节编译的 after-save-hook    org - 文档更改后。

(defun tangle-init ()
  "If the current buffer is 'init.org' the code-blocks are
tangled, and the tangled file is compiled."
  (when (equal (buffer-file-name)
               (expand-file-name (concat user-emacs-directory "init.org")))
    ;; Avoid running hooks when tangling.
    (let ((prog-mode-hook nil))
      (org-babel-tangle)
      (byte-compile-file (concat user-emacs-directory "init.el")))))

(add-hook 'after-save-hook 'tangle-init)

我想保留一些私人设置,所以我们加载了一个 private.el   在init-file加载后存在。

(add-hook
 'after-init-hook
 (lambda ()
   (let ((private-file (concat user-emacs-directory "private.el")))
     (when (file-exists-p private-file)
       (load-file private-file)))))

使用 package 简化了管理Emacs的扩展   内置于Emacs 24和更新版本。加载下载的软件包,我们需要   初始化 cl 是一个包含许多函数的库   普通的Lisp,很常用,所以我们想确保它是   加载,以及显然需要的

(require 'cl)
(require 'package)
(package-initialize)

软件包可以从不同的镜像获取, melpa 是最大的   档案并保持良好状态。

(setq package-archives
      '(("gnu" . "http://elpa.gnu.org/packages/")
        ("org" . "http://orgmode.org/elpa/")
        ("melpa" . "https://melpa.org/packages/")
        ("melpa-stable" . "https://stable.melpa.org/packages/")))

(add-to-list 'package-pinned-packages '(cider . "melpa-stable") t)

该配置假定下面列出的软件包   已安装。确保我们安装丢失的软件包。

(let* ((packages
        '(auto-compile         ; automatically compile Emacs Lisp libraries
          cider                ; Clojure Interactive Development Environment
          company              ; Modular text completion framework
          define-word          ; display the definition of word at point
          diminish             ; Diminished modes from modeline
          drag-stuff           ; Drag stuff around in Emacs
          expand-region        ; Increase selected region by semantic units
          focus                ; Dim color of text in surrounding sections
          idle-require         ; load elisp libraries while Emacs is idle
          geiser               ; GNU Emacs and Scheme talk to each other
          git-gutter-fringe    ; Fringe version of git-gutter.el
          golden-ratio         ; Automatic resizing windows to golden ratio
          haskell-mode         ; A Haskell editing mode
          helm                 ; Incremental and narrowing framework
          helm-company         ; Helm interface for company-mode
          helm-projectile      ; Helm integration for Projectile
          helm-swoop           ; Efficiently hopping squeezed lines
          jedi                 ; Python auto-completion for Emacs
          js2-mode             ; Improved JavaScript editing mode
          magit                ; control Git from Emacs
          markdown-mode        ; Emacs Major mode for Markdown-formatted files
          material-theme       ; A Theme based on Google Material Design
          matlab-mode          ; MATLAB integration with Emacs
          maude-mode           ; Emacs mode for the programming language Maude
          multiple-cursors     ; Multiple cursors for Emacs
          olivetti             ; Minor mode for a nice writing environment
          org                  ; Outline-based notes management and organizer
          paredit              ; minor mode for editing parentheses
          pdf-tools            ; Emacs support library for PDF files
          projectile           ; Manage and navigate projects in Emacs easily
          slime                ; Superior Lisp Interaction Mode for Emacs
          try))                ; Try out Emacs packages
       ;; Remove all packages already installed
       (packages (remove-if 'package-installed-p packages)))
  (when packages
    (ignore-errors (package-refresh-contents)
                   (mapcar 'package-install packages)
                   ;; This package is only relevant for Mac OS X.
                   (when (memq window-system '(mac ns))
                     (package-install 'exec-path-from-shell)))))

Mac OS X

我运行这个配置大多是在Mac OS X上,所以我们需要一些   设置使事情顺利进行。在包装部分   包含了 exec-path-from-shell (只有当你运行的是OS X),这是   以包括来自shell的环境变量。它使用Emacs   以及外部过程更简单。我也喜欢使用   命令 -key作为 Meta -key。

(when (memq window-system '(mac ns))
  (setq ns-pop-up-frames nil
        mac-option-modifier nil
        mac-command-modifier 'meta
        x-select-enable-clipboard t)
  (exec-path-from-shell-initialize))

需要

默认情况下,某些功能未加载以最小化初始化时间,   所以他们必须被要求(或加载,如果你愿意)。 require -calls   往往会导致最大的瓶颈   组态。 idle-require require 延迟到一段时间   Emacs处于空闲状态所以这对你最终想加载的东西很好,   但不是高优先级。

(require 'idle-require)             ; Need in order to use idle-require

(dolist (feature '(auto-compile ; auto-compile .el files jedi ; auto-completion for python matlab ; matlab-mode ob-matlab ; org-babel matlab ox-latex ; the latex-exporter (from org) ox-md ; Markdown exporter (from org) recentf ; recently opened files tex-mode)) ; TeX, LaTeX, and SliTeX mode commands (idle-require feature))

(setq idle-require-idle-delay 5) (idle-require-mode 1)

正常默认值

这些是我认为是默认的默认值。

我们可以将变量设置为我们想要使用 setq 的任何值

(setq auto-revert-interval 1            ; Refresh buffers fast
      custom-file (make-temp-file "")   ; Discard customization's
      default-input-method "TeX"        ; Use TeX when toggling input method
      echo-keystrokes 0.1               ; Show keystrokes asap
      inhibit-startup-message t         ; No splash screen please
      initial-scratch-message nil       ; Clean scratch buffer
      recentf-max-saved-items 100       ; Show more recent files
      ring-bell-function 'ignore        ; Quiet
      sentence-end-double-space nil)    ; No double space
;; Some mac-bindings interfere with Emacs bindings.
(when (boundp 'mac-pass-command-to-system)
  (setq mac-pass-command-to-system nil))
一些变量是缓冲区本地的,所以只能使用 setq 改变它们   在单个缓冲区中更改它们。使用 setq-default 我们改变了   buffer-local变量的默认值。

(setq-default fill-column 79                    ; Maximum line width
              truncate-lines t                  ; Don't fold lines
              indent-tabs-mode nil              ; Use spaces instead of tabs
              split-width-threshold 100         ; Split verticly by default
              auto-fill-function 'do-auto-fill) ; Auto-fill-mode everywhere

load-path 指定Emacs应在哪里查找 .el -files(或   Emacs lisp文件)。我有一个名为 site-lisp 的目录,我保留所有内容   已经手动安装的扩展(这些大部分是我自己的   项目)。

(let ((default-directory (concat user-emacs-directory "site-lisp/")))
  (when (file-exists-p default-directory)
    (setq load-path
          (append
           (let ((load-path (copy-sequence load-path)))
             (normal-top-level-add-subdirs-to-load-path)) load-path))))

从Emacs回答每个问题可能是乏味的,一个   单身或 n 就足够了

(fset 'yes-or-no-p 'y-or-n-p)

为了避免文件系统的混乱,我们将所有自动保存的文件放在一个文件中   目录。

(defvar emacs-autosave-directory
  (concat user-emacs-directory "autosaves/")
  "This variable dictates where to put auto saves. It is set to a
  directory called autosaves located wherever your .emacs.d/ is
  located.")

;; Sets all files to be backed up and auto saved in a single directory. (setq backup-directory-alist ((<span class="pl-s"><span class="pl-pds">&#34;</span>.*<span class="pl-pds">&#34;</span></span> <span class="pl-k">.</span> ,emacs-autosave-directory)) auto-save-file-name-transforms ((".*" ,emacs-autosave-directory t)))

utf-8 设置为首选编码系统。

(set-language-environment "UTF-8")

默认情况下, narrow-to-region 命令被禁用并发出   警告,因为它可能会混淆新用户。我有时会发现它很有用,   并且不想被警告。

(put 'narrow-to-region 'disabled nil)

当文件在磁盘上更改时,自动还原 doc-view -buffers。

(add-hook 'doc-view-mode-hook 'auto-revert-mode)

模式

默认情况下,我没有找到一些模式   特别有用。我们创建这些模式的列表,并禁用所有这些模式   这些。

(dolist (mode
         '(tool-bar-mode                ; No toolbars, more room for text
           scroll-bar-mode              ; No scroll bars either
           blink-cursor-mode))          ; The blinking cursor gets old
  (funcall mode 0))
我们应用相同的技术来启用被禁用的启用模式   默认。

(dolist (mode
         '(abbrev-mode                  ; E.g. sopl -> System.out.println
           column-number-mode           ; Show column number in mode line
           delete-selection-mode        ; Replace selected text
           dirtrack-mode                ; directory tracking in shell
           drag-stuff-global-mode       ; Drag stuff around
           global-company-mode          ; Auto-completion everywhere
           global-git-gutter-mode       ; Show changes latest commit
           global-prettify-symbols-mode ; Greek letters should look greek
           golden-ratio-mode            ; Automatic resizing of windows
           projectile-global-mode       ; Manage and navigate projects
           recentf-mode                 ; Recently opened files
           show-paren-mode))            ; Highlight matching parentheses
  (funcall mode 1))

(when (version< emacs-version "24.4") (eval-after-load 'auto-compile '((auto-compile-on-save-mode 1)))) ; compile .el files on save

Visual

将颜色主题更改为 leuven

(load-theme 'leuven t)

leuven 是我喜欢的轻型主题,但是 monokai 使一个非常好的   黑暗的主题。我想能够在这些之间循环。

(defun cycle-themes ()
  "Returns a function that lets you cycle your themes."
  (lexical-let ((themes '#1=(leuven material . #1#)))
    (lambda ()
      (interactive)
      ;; Rotates the thme cycle and changes the current theme.
      (load-theme (car (setq themes (cdr themes))) t))))

如果系统上已安装 Inconsolata 字体,请使用

(cond ((member "Source Code Pro" (font-family-list))
       (set-face-attribute 'default nil :font "Source Code Pro-13"))
      ((member "Inconsolata" (font-family-list))
       (set-face-attribute 'default nil :font "Inconsolata-14")))

diminish.el 可让您隐藏或缩写他们在   模型。我很少看模特儿,找出什么是次要模式   启用,所以我禁用每个全局小模式,一些用于lisp编辑。

为了确保在减少模式之前加载模式,我们应该使用    with-eval-after-load 为了避免多次输入一个小的宏   提供。

(defmacro safe-diminish (file mode &optional new-name)
  `(with-eval-after-load ,file
     (diminish ,mode ,new-name)))

(diminish 'auto-fill-function) (safe-diminish "eldoc" 'eldoc-mode) (safe-diminish "flyspell" 'flyspell-mode) (safe-diminish "helm-mode" 'helm-mode) (safe-diminish "projectile" 'projectile-mode) (safe-diminish "paredit" 'paredit-mode "()")

git-gutter-fringe 可以很好地显示您所在的位置   自上次提交以来的变化。有几个包执行   这个任务原来我最终使用了 git-gutter-fringe 就是这样   重复使用(已经存在的)条纹,节省了一小部分的屏幕尺寸。

我从 torenord 走私了一些配置,提供了更清洁的外观。

(require 'git-gutter-fringe)

(dolist (p '((git-gutter:added . "#0c0") (git-gutter:deleted . "#c00") (git-gutter:modified . "#c0c"))) (set-face-foreground (car p) (cdr p)) (set-face-background (car p) (cdr p)))

新增Emacs 24.4是 prettify-symbols-mode !很整洁。

(setq-default prettify-symbols-alist '(("lambda" . )
                                       ("delta" . )
                                       ("gamma" . )
                                       ("phi" . )
                                       ("psi" . )))

PDF工具

PDF工具对内置的 doc-view-mode ;唯一的   缺点是 pdf-tools-install (必须在之前执行   包可以使用)需要几个来执行。代替   在init-time运行它,我们将在打开PDF时运行它。注意   这只是第一次运行的缓慢!

(add-hook 'pdf-tools-enabled-hook 'auto-revert-mode)
(add-to-list 'auto-mode-alist '("\.pdf\'" . pdf-tools-install))

完成

自动完成多年来一直是我配置的一部分,但我想尝试   公司模式。如果我在一个完成良好的环境中编码,我已经   习惯于尝试猜测功能名称,并查看   正确的完成。所以我想要一个非常积极的完成   系统,因此无延迟设置和短前缀长度。

(setq company-idle-delay 0
      company-echo-delay 0
      company-dabbrev-downcase nil
      company-minimum-prefix-length 2
      company-selection-wrap-around t
      company-transformers '(company-sort-by-occurrence
                             company-sort-by-backend-importance))

Helm

我已经是 ido-mode 以及 ido-vertical-mode 的长时间用户,   没有任何特别的抱怨。虽然我有一种感觉我失踪了   通过不使用掌舵来进行某些操作。我将这个优秀的教程作为   起点,以及一些建议的配置。

helm 有一个奇妙的功能,能够通过 C-s 在任何地方grep文件,   这是有用的。 ack 是一个很好的 grep - 重新放置,旨在   搜索源代码,所以我想使用它,如果它可用。

请注意,绑定中的某些更改位于密钥绑定中(发现   接近配置结束)。

(require 'helm)
(require 'helm-config)

(setq helm-split-window-in-side-p t helm-M-x-fuzzy-match t helm-buffers-fuzzy-matching t helm-recentf-fuzzy-match t helm-move-to-line-cycle-in-source t projectile-completion-system 'helm)

(when (executable-find "ack") (setq helm-grep-default-command "ack -Hn –no-group –no-color %e %p %f" helm-grep-default-recurse-command "ack -H –no-group –no-color %e %p %f"))

(set-face-attribute 'helm-selection nil :background "cyan")

(helm-mode 1) (helm-projectile-on) (helm-adaptive-mode 1)

日历

定义在 calender-mode 中显示周数的功能。片段   来自 EmacsWiki

(defun calendar-show-week (arg)
  "Displaying week number in calendar-mode."
  (interactive "P")
  (copy-face font-lock-constant-face 'calendar-iso-week-face)
  (set-face-attribute
   'calendar-iso-week-face nil :height 0.7)
  (setq calendar-intermonth-text
        (and arg
             '(propertize
               (format
                "%2d"
                (car (calendar-iso-from-absolute
                      (calendar-absolute-from-gregorian
                       (list month day year)))))
               'font-lock-face 'calendar-iso-week-face))))

评估 calendar-show-week 功能。

(calendar-show-week t)
将星期一设为星期一,并设置我的位置。

(setq calendar-week-start-day 1
      calendar-latitude 60.0
      calendar-longitude 10.7
      calendar-location-name "Oslo, Norway")

mu4e和offlineimap

我可能不是在使用我非常具体的邮件设置的计算机,但如果我的   邮件文件夹存在,那么加载它可能是安全的。

(defvar load-mail-setup (file-exists-p "~/.ifimail"))

我使用 mu4e (这是 mu )以及我之一的 offlineimap   电脑。

mu4e

必须通知mu4e可以在哪里找到您的邮件,以及哪里   感兴趣的不同文件夹位于。一些额外的mu4e调整   也在这里提供。

message-insert-signature 是现有的Emacs功能,它添加了您的   电子邮件结尾处的一个〜 - 〜前缀,这是一个   惯例我没有真正遵循。我重新定义它作为一个功能添加   一些换行符和我的电子邮件顶部的签名。

(when load-mail-setup
  (eval-after-load 'mu4e
    '(progn
       ;; Some basic mu4e settings.
       (setq mu4e-maildir           "~/.ifimail"     ; top-level Maildir
             mu4e-sent-folder       "/Sent Items"    ; folder for sent messages
             mu4e-drafts-folder     "/INBOX.Drafts"  ; unfinished messages
             mu4e-trash-folder      "/INBOX.Trash"   ; trashed messages
             mu4e-get-mail-command  "offlineimap"    ; offlineimap to fetch mail
             mu4e-compose-signature "- Lars"         ; Sign my name
             mu4e-update-interval   (* 5 60)         ; update every 5 min
             mu4e-confirm-quit      nil              ; just quit
             mu4e-view-show-images  t                ; view images
             mu4e-html2text-command
             "html2text -utf8")                      ; use utf-8

   <span class="pl-c"><span class="pl-c">;</span>; Setup for sending mail.</span>
   (<span class="pl-k">setq</span> user-full-name
         <span class="pl-s"><span class="pl-pds">&#34;</span>Lars Tveito<span class="pl-pds">&#34;</span></span>                          <span class="pl-c"><span class="pl-c">;</span> Your full name</span>
         user-mail-address
         <span class="pl-s"><span class="pl-pds">&#34;</span>larstvei@ifi.uio.no<span class="pl-pds">&#34;</span></span>                  <span class="pl-c"><span class="pl-c">;</span> And email-address</span>
         smtpmail-smtp-server
         <span class="pl-s"><span class="pl-pds">&#34;</span>smtp.uio.no<span class="pl-pds">&#34;</span></span>                          <span class="pl-c"><span class="pl-c">;</span> Host to mail-server</span>
         smtpmail-smtp-service <span class="pl-c1">465</span>              <span class="pl-c"><span class="pl-c">;</span> Port to mail-server</span>
         smtpmail-stream-type <span class="pl-c1">&#39;ssl</span>              <span class="pl-c"><span class="pl-c">;</span> Protocol used for sending</span>
         send-mail-function <span class="pl-c1">&#39;smtpmail-send-it</span>   <span class="pl-c"><span class="pl-c">;</span> Use smpt to send</span>
         mail-user-agent <span class="pl-c1">&#39;mu4e-user-agent</span>)      <span class="pl-c"><span class="pl-c">;</span> Use mu4e</span>

   <span class="pl-c"><span class="pl-c">;</span>; Register file types that can be handled by ImageMagick.</span>
   (<span class="pl-k">when</span> (fboundp <span class="pl-c1">&#39;imagemagick-register-types</span>)
     (imagemagick-register-types))

   (add-hook <span class="pl-c1">&#39;mu4e-compose-mode-hook</span>
             (<span class="pl-k">lambda</span> ()
               (auto-fill-mode <span class="pl-c1">0</span>)
               (visual-line-mode <span class="pl-c1">1</span>)
               (ispell-change-dictionary <span class="pl-s"><span class="pl-pds">&#34;</span>norsk<span class="pl-pds">&#34;</span></span>)))

   (add-hook <span class="pl-c1">&#39;mu4e-view-mode-hook</span> (<span class="pl-k">lambda</span> () (visual-line-mode <span class="pl-c1">1</span>)))

   (<span class="pl-k">defun</span> <span class="pl-e">message-insert-signature</span> ()
     (goto-char (point-min))
     (search-forward-regexp <span class="pl-s"><span class="pl-pds">&#34;</span>^$<span class="pl-pds">&#34;</span></span>)
     (insert <span class="pl-s"><span class="pl-pds">&#34;</span><span class="pl-cce">\n\n\n</span><span class="pl-pds">&#34;</span></span> mu4e-compose-signature))))

(autoload 'mu4e "mu4e" nil t))

Flyspell

Flyspell提供即时拼写检查。我们可以为所有人启用flyspell   文字模式与此片段。

(add-hook 'text-mode-hook 'turn-on-flyspell)

要使用flyspell进行编程,只有 flyspell-prog-mode   启用拼写检查注释和字符串。我们可以为所有人启用它   编程模式使用 prog-mode-hook

(add-hook 'prog-mode-hook 'flyspell-prog-mode)

当使用多种语言时,我们应该能够循环使用   我们最常用的语言。每个缓冲区应该有一个单独的   循环语言,使循环在一个缓冲区不改变   状态在不同的缓冲区(如果您只有一个则会出现此问题   全球周期)。我们可以使用关闭来实现。

(defun cycle-languages ()
  "Changes the ispell dictionary to the first element in
ISPELL-LANGUAGES, and returns an interactive function that cycles
the languages in ISPELL-LANGUAGES when invoked."
  (lexical-let ((ispell-languages '#1=("american" "norsk" . #1#)))
    (ispell-change-dictionary (car ispell-languages))
    (lambda ()
      (interactive)
      ;; Rotates the languages cycle and changes the ispell dictionary.
      (ispell-change-dictionary
       (car (setq ispell-languages (cdr ispell-languages)))))))
如果没有拼写检查工具,则

flyspell 发出错误信号   已安装。我们可以将开启flyspell flyspell-prog-mode   只有拼写检查工具可用时才尝试启用 flyspell 。也   我们想通过键入 C-c l 启用循环语言,所以我们绑定   函数从循环语言返回

(defadvice turn-on-flyspell (before check nil activate)
  "Turns on flyspell only if a spell-checking tool is installed."
  (when (executable-find ispell-program-name)
    (local-set-key (kbd "C-c l") (cycle-languages))))
(defadvice flyspell-prog-mode (before check nil activate)
  "Turns on flyspell only if a spell-checking tool is installed."
  (when (executable-find ispell-program-name)
    (local-set-key (kbd "C-c l") (cycle-languages))))

Org

我使用 org-agenda 以及 org-capture 进行约会等等。

(setq org-agenda-files '("~/Dropbox/agenda.org")  ; A list of agenda files
      org-agenda-default-appointment-duration 120 ; 2 hours appointments
      org-capture-templates                       ; Template for adding tasks
      '(("t" "Oppgave" entry (file+headline "~/Dropbox/agenda.org" "Oppgaver")
         "** TODO %?" :prepend t)
        ("m" "Master" entry (file+olp "~/Dropbox/agenda.org" "Oppgaver" "Master")
         "*** TODO %?" :prepend t)
        ("a" "Avtale" entry (file+headline "~/Dropbox/agenda.org" "Avtaler")
         "** %?\n   SCHEDULED: %T" :prepend t)))

当使用源代码块编辑组织文件时,我们希望使用源块   以他们的母语为主题。

(setq org-src-fontify-natively t
      org-src-tab-acts-natively t
      org-confirm-babel-evaluate nil
      org-edit-src-content-indentation 0)

这是一个非常难看的修复,允许代码标记为像   =this string=,因为引号引起问题。

;;(require 'org)
(eval-after-load "org"
  '(progn
     (setcar (nthcdr 2 org-emphasis-regexp-components) " \t\n,")
     (custom-set-variables `(org-emphasis-alist ',org-emphasis-alist))))

互动功能

&lt; sec:defuns&gt;

just-one-space 删除一个点周围的所有空格 - 给它一个   负参数也删除换行符。我们包装一个互动   在其周围功能能够将其绑定到一个键。在Emacs 24.4   引入了 cycle-spacing ,它的作用就像 just-one-space ,但是   当连续运行时,它在一个零和原始之间循环   空格数。

(defun cycle-spacing-delete-newlines ()
  "Removes whitespace before and after the point."
  (interactive)
  (if (version< emacs-version "24.4")
      (just-one-space -1)
    (cycle-spacing -1)))

我常常想找到一个或多个单词的其他事件   特别是我在的符号(或标签)。的   Emacs 24.4中的 isearch-forward-symbol-at-point 很好地适用于此   我不想用 isearch 接口打扰。相反跳   一个符号的出现之间,或者如果找不到,就不要做   任何东西。

(defun jump-to-symbol-internal (&optional backwardp)
  "Jumps to the next symbol near the point if such a symbol
exists. If BACKWARDP is non-nil it jumps backward."
  (let* ((point (point))
         (bounds (find-tag-default-bounds))
         (beg (car bounds)) (end (cdr bounds))
         (str (isearch-symbol-regexp (find-tag-default)))
         (search (if backwardp 'search-backward-regexp
                   'search-forward-regexp)))
    (goto-char (if backwardp beg end))
    (funcall search str nil t)
    (cond ((<= beg (point) end) (goto-char point))
          (backwardp (forward-char (- point beg)))
          (t  (backward-char (- end point))))))

(defun jump-to-previous-like-this () "Jumps to the previous occurrence of the symbol at point." (interactive) (jump-to-symbol-internal t))

(defun jump-to-next-like-this () "Jumps to the next occurrence of the symbol at point." (interactive) (jump-to-symbol-internal))

我有时候后悔杀死 * scratch * -buffer,并意识到我   从来不想真的杀死它。我只是想把它弄出来,和   清理。下面的功能只是为了这个   对于其他任何其他的代码,可以像 kill-this-buffer 一样工作。   缓冲。它删除所有的缓冲区内容,并将缓冲区(这意味着)   使其成为 other-buffer )的最不可能的候选者。

(defun kill-this-buffer-unless-scratch ()
  "Works like `kill-this-buffer' unless the current buffer is the
scratch buffer. In witch case the buffer content is deleted and
the buffer is buried."
  (interactive)
  (if (not (string= (buffer-name) "scratch"))
      (kill-this-buffer)
    (delete-region (point-min) (point-max))
    (switch-to-buffer (other-buffer))
    (bury-buffer "scratch")))

要复制选定的文本或一行,我们定义此交互式   功能。

(defun duplicate-thing (comment)
  "Duplicates the current line, or the region if active. If an argument is
given, the duplicated region will be commented out."
  (interactive "P")
  (save-excursion
    (let ((start (if (region-active-p) (region-beginning) (point-at-bol)))
          (end   (if (region-active-p) (region-end) (point-at-eol))))
      (goto-char end)
      (unless (region-active-p)
        (newline))
      (insert (buffer-substring start end))
      (when comment (comment-region start end)))))

要整理缓冲区,我们定义了从 simenheg 借用的函数。

(defun tidy ()
  "Ident, untabify and unwhitespacify current buffer, or region if active."
  (interactive)
  (let ((beg (if (region-active-p) (region-beginning) (point-min)))
        (end (if (region-active-p) (region-end) (point-max))))
    (indent-region beg end)
    (whitespace-cleanup)
    (untabify beg (if (< end (point-max)) end (point-max)))))

组织模式当前不支持synctex(这使您能够跳转   在你的TeX文件中的一点到pdf中的对应点),以及它   似乎是一个棘手的问题

从组织缓冲区调用此函数跳转到相应的部分   在导出的pdf(给定pdf文件存在)中,使用pdf工具。

(defun org-sync-pdf ()
  (interactive)
  (let ((headline (nth 4 (org-heading-components)))
        (pdf (concat (file-name-base (buffer-name)) ".pdf")))
    (when (file-exists-p pdf)
      (find-file-other-window pdf)
      (pdf-links-action-perform
       (cl-find headline (pdf-info-outline pdf)
                :key (lambda (alist) (cdr (assoc 'title alist)))
                :test 'string-equal)))))

建议

可以给一个函数给它一个不同的行为。这个   建议使 eval-last-sexp (绑定到 C-x C-e )将sexp替换为   值。

(defadvice eval-last-sexp (around replace-sexp (arg) activate)
  "Replace sexp when called with a prefix argument."
  (if arg
      (let ((pos (point)))
        ad-do-it
        (goto-char pos)
        (backward-kill-sexp)
        (forward-sexp))
    ad-do-it))

当交互式更改主题(使用 M-x load-theme )时,   当前的自定义主题未被禁用。这经常给人以奇怪的样子   结果;我们可以建议 load-theme 来永远禁用主题   启用主题。

(defadvice load-theme
    (before disable-before-load (theme &optional no-confirm no-enable) activate)
  (mapc 'disable-theme custom-enabled-themes))

全局尺度-mode

这些函数提供了一些接近 text-scale-mode 的功能   缓冲区,包括minibuffer和模式行。

(lexical-let* ((default (face-attribute 'default :height))
               (size default))

(defun global-scale-default () (interactive) (setq size default) (global-scale-internal size))

(defun global-scale-up () (interactive) (global-scale-internal (incf size 20)))

(defun global-scale-down () (interactive) (global-scale-internal (decf size 20)))

(defun global-scale-internal (arg) (set-face-attribute 'default (selected-frame) :height arg) (set-temporary-overlay-map (let ((map (make-sparse-keymap))) (define-key map (kbd "C-=") 'global-scale-up) (define-key map (kbd "C-+") 'global-scale-up) (define-key map (kbd "C–") 'global-scale-down) (define-key map (kbd "C-0") 'global-scale-default) map))))

Mode specific

Shell

只要我想使用Emacs中的命令行,我使用 shell 。一世   在我的〜/ .bash_profile 之间保留一个符号链接(因为我运行OS X)和   〜/ .emacs_bash ,使我的标准终端和   壳尽可能小。能够快速切换回来   在shell之间使用这个小功能。

(defun toggle-shell ()
  "Jumps to eshell or back."
  (interactive)
  (if (string= (buffer-name) "shell")
      (switch-to-prev-buffer)
    (shell)))

我希望 C-l 更像标准终端(它的工作原理)   像运行 clear ),并通过简单的删除来解决这个问题   缓冲区内容。请注意,这不是 clear 的工作原理,它只是添加一个   一堆换行符,并将提示放在窗口的顶部,所以它   不删除任何东西。在Emacs中删除的东西不用担心,   因为我们可以随时撤消!

(defun clear-comint ()
  "Runs comint-truncate-buffer&#39; with the</span>
<span class="pl-s">comint-buffer-maximum-size' set to zero."
  (interactive)
  (let ((comint-buffer-maximum-size 0))
    (comint-truncate-buffer)))
最后我们应该约束我们的功能。 toggle-shell 应该是   全局绑定(因为我们希望能够从任何一个shell切换到一个shell   缓冲区),但是 clear-shell 只能影响 shell-mode

(add-hook 'comint-mode-hook (lambda () (local-set-key (kbd "C-l") 'clear-comint)))

Lisp

在编辑lisp代码时,我使用 Paredit ,我们为所有的lisp模式启用。

(dolist (mode '(cider-repl-mode
                clojure-mode
                ielm-mode
                geiser-repl-mode
                slime-repl-mode
                lisp-mode
                emacs-lisp-mode
                lisp-interaction-mode
                scheme-mode))
  ;; add paredit-mode to all mode-hooks
  (add-hook (intern (concat (symbol-name mode) "-hook")) 'paredit-mode))

Emacs Lisp

emacs-lisp-mode 中,我们可以启用 eldoc-mode 来显示信息   关于回声区域中的函数或变量。

(add-hook 'emacs-lisp-mode-hook 'turn-on-eldoc-mode)
(add-hook 'lisp-interaction-mode-hook 'turn-on-eldoc-mode)

常用的lisp

我使用 Slime 以及 lisp-mode 来编辑Common Lisp代码。粘液   提供代码评估等功能,一定要有一个   常见的Lisp开发者。 Quicklisp 是Common Lisp的图书馆经理,   您可以按照网站上的说明安装Slime   与此片段。

(defun activate-slime-helper ()
  (when (file-exists-p "~/.quicklisp/slime-helper.el")
    (load (expand-file-name "~/.quicklisp/slime-helper.el"))
    (define-key slime-repl-mode-map (kbd "C-l")
      'slime-repl-clear-buffer))
  (remove-hook 'lisp-mode-hook #'activate-slime-helper))

(add-hook 'lisp-mode-hook #'activate-slime-helper)

我们可以指定什么Common Lisp程序Slime应该使用(我使用SBCL)。

(setq inferior-lisp-program "sbcl")

simenheg 借用更明智的循环缩进。

(setq lisp-loop-forms-indentation   6
      lisp-simple-loop-indentation  2
      lisp-loop-keyword-indentation 6)

方案

Geiser 提供了类似于Slime for Scheme编辑的功能。一切   几乎开箱即用,我们只需要添加自动完成,   并指定我们喜欢哪种方案 - 解释器。

(eval-after-load "geiser"
  '(setq geiser-active-implementations '(guile)))

Java和C

c-mode-common-hook 是一个通用的钩子,适用于所有C类   语言(C,C ++,Java等)。我喜欢能够快速编译   使用 C-c C-c (而不是 M-x compile ),这是习惯从 latex-mode

(defun c-setup ()
  (local-set-key (kbd "C-c C-c") 'compile))

(add-hook 'c-mode-common-hook 'c-setup)

Java中的一些语句经常出现,并且变得乏味写入   出来我们可以使用缩写来加速。

(define-abbrev-table 'java-mode-abbrev-table
  '(("psv" "public static void main(String[] args) {" nil 0)
    ("sopl" "System.out.println" nil 0)
    ("sop" "System.out.printf" nil 0)))

为了能够使用上面定义的缩写表, abbrev-mode 必须是   激活。

(defun java-setup ()
  (abbrev-mode t)
  (setq-local compile-command (concat "javac " (buffer-name))))

(add-hook 'java-mode-hook 'java-setup)

汇编器

编写汇编代码时,我使用进行评论。通过定义    comment-start 我们可以像其他编程一样使用 M - ; 添加注释   模式。也可以在汇编器中使用 C-c C-c 编译

(defun asm-setup ()
  (setq comment-start "#")
  (local-set-key (kbd "C-c C-c") 'compile))

(add-hook 'asm-mode-hook 'asm-setup)

LaTeX和组织模式LaTeX导出

.tex -files应该与 latex-mode 相关联,而不是    tex-mode

(add-to-list 'auto-mode-alist '("\.tex\'" . latex-mode))

使用 biblatex 参考书目。

(setq-default bibtex-dialect 'biblatex)

我喜欢在LaTeX中使用 Minted 软件包中的源代码块。组织机构   使用这个我们添加以下代码段。

(eval-after-load 'org
  '(add-to-list 'org-latex-packages-alist '("" "minted")))
(setq org-latex-listings 'minted)

由于 Minted 使用 Pygments (一个外部过程),我们必须添加    -shell-escape 选项到 org-latex-pdf-process 命令。的    tex-compile-commands 变量控制默认的compile命令   Tex-和LaTeX模式,我们可以添加一个相当脏的语句的标志   (如果有人找到更好的方法来做到这一点,请让我知道)。

(eval-after-load 'tex-mode
  '(setcar (cdr (cddaar tex-compile-commands)) " -shell-escape "))

从Org导出到LaTeX时,请使用 latexmk 进行编译。

(eval-after-load 'ox-latex
  '(setq org-latex-pdf-process
         '("latexmk -pdflatex='pdflatex -shell-escape -interaction nonstopmode' -pdf -f %f")))
对于我的论文,我需要使用我们大学的LaTeX课程,这个片段   使该课程可用。

(eval-after-load "ox-latex"
  '(progn
     (add-to-list 'org-latex-classes
                  '("ifimaster"
                    "\documentclass{ifimaster}
[DEFAULT-PACKAGES]
[PACKAGES]
[EXTRA]
\usepackage{babel,csquotes,ifimasterforside,url,varioref}"
                   ("\chapter{%s}" . "\chapter{%s}")
                   ("\section{%s}" . "\section{%s}")
                   ("\subsection{%s}" . "\subsection{%s}")
                   ("\subsubsection{%s}" . "\subsubsection{%s}")
                   ("\paragraph{%s}" . "\paragraph{%s}")
                   ("\subparagraph{%s}" . "\subparagraph{%s}")))
    (custom-set-variables '(org-export-allow-bind-keywords t))))

Markdown

这使得 .md -files在 markdown-mode 中打开。

(add-to-list 'auto-mode-alist '("\.md\'" . markdown-mode))
我有时使用专门的降价格式,其中内联数学块   可以通过使用 $ math $ 和…覆盖LaTeX公式来实现    $ / math $ 。写这些,变得乏味,所以我写了一个小功能。

(defun insert-markdown-inline-math-block ()
  "Inserts an empty math-block if no region is active, otherwise wrap a
math-block around the region."
  (interactive)
  (let* ((beg (region-beginning))
         (end (region-end))
         (body (if (region-active-p) (buffer-substring beg end) "")))
    (when (region-active-p)
      (delete-region beg end))
    (insert (concat "$math$ " body " $/math$"))
    (search-backward " $/math$")))
我的大部分写作都是挪威语,所以字典是   设置相应。标记对换行也很敏感,所以   自动填充模式被禁用。我们当然希望绑定我们的可爱   功能到一个钥匙!

(add-hook 'markdown-mode-hook
          (lambda ()
            (auto-fill-mode 0)
            (visual-line-mode 1)
            (ispell-change-dictionary "norsk")
            (local-set-key (kbd "C-c b") 'insert-markdown-inline-math-block)) t)

Python

Haskell

haskell-doc-mode 类似于 eldoc ,它显示文档   回波区域。 Haskell有几种缩进模式 - 我喜欢使用    haskell-indent

(add-hook 'haskell-mode-hook 'turn-on-haskell-doc-mode)
(add-hook 'haskell-mode-hook 'turn-on-haskell-indent)

Maude

在Maude中使用来发表评论

(add-hook 'maude-mode-hook
          (lambda ()
            (setq-local comment-start "")))

Matlab

Matlab模式非常好的开箱即用,但我们可以做到没有   启动屏幕。

(eval-after-load 'matlab
  '(add-to-list 'matlab-shell-command-switches "-nosplash"))

Key bindings

此StackOverflow文章的启发,我保留了一个 custom- bindings-map 那个   拥有我所有的自定义绑定。该地图可以通过切换来激活   简单的 minor-mode ,只是激活地图。这个   禁止其他主要模式来覆盖这些绑定。我保持这个   init文件的结尾,以确保所有函数都是实际的   定义。

(defvar custom-bindings-map (make-keymap)
  "A keymap for custom bindings.")

定义词的绑定

(define-key custom-bindings-map (kbd "C-c D") 'define-word-at-point)

展开区域的绑定

(define-key custom-bindings-map (kbd "C->")  'er/expand-region)
(define-key custom-bindings-map (kbd "C-<")  'er/contract-region)

多光标的绑定

(define-key custom-bindings-map (kbd "C-c e")  'mc/edit-lines)
(define-key custom-bindings-map (kbd "C-c a")  'mc/mark-all-like-this)
(define-key custom-bindings-map (kbd "C-c n")  'mc/mark-next-like-this)

绑定< a href =http://magit.github.io> Magit

(define-key custom-bindings-map (kbd "C-c m") 'magit-status)

公司模式的绑定

(define-key company-active-map (kbd "C-d") 'company-show-doc-buffer)
(define-key company-active-map (kbd "C-n") 'company-select-next)
(define-key company-active-map (kbd "C-p") 'company-select-previous)
(define-key company-active-map (kbd "<tab>") 'company-complete)

(define-key company-mode-map (kbd "C-:") 'helm-company) (define-key company-active-map (kbd "C-:") 'helm-company)

绑定< a href =http://emacs-helm.github.io/helm/> Helm

(define-key custom-bindings-map (kbd "C-c h")   'helm-command-prefix)
(define-key custom-bindings-map (kbd "M-x")     'helm-M-x)
(define-key custom-bindings-map (kbd "M-y")     'helm-show-kill-ring)
(define-key custom-bindings-map (kbd "C-x b")   'helm-mini)
(define-key custom-bindings-map (kbd "C-x C-f") 'helm-find-files)
(define-key custom-bindings-map (kbd "C-c h o") 'helm-occur)
(define-key custom-bindings-map (kbd "C-c h g") 'helm-google-suggest)
(define-key custom-bindings-map (kbd "M-i")     'helm-swoop)
(define-key custom-bindings-map (kbd "M-I")     'helm-multi-swoop-all)

(define-key helm-map (kbd "<tab>") 'helm-execute-persistent-action) (define-key helm-map (kbd "C-i") 'helm-execute-persistent-action) (define-key helm-map (kbd "C-z") 'helm-select-action)

内置绑定

(define-key custom-bindings-map (kbd "M-u")         'upcase-dwim)
(define-key custom-bindings-map (kbd "M-c")         'capitalize-dwim)
(define-key custom-bindings-map (kbd "M-l")         'downcase-dwim)
(define-key custom-bindings-map (kbd "M-]")         'other-frame)
(define-key custom-bindings-map (kbd "C-j")         'newline-and-indent)
(define-key custom-bindings-map (kbd "C-c s")       'ispell-word)
(define-key custom-bindings-map (kbd "C-c c")       'org-capture)
(define-key custom-bindings-map (kbd "C-x m")       'mu4e)
(define-key custom-bindings-map (kbd "C-c <up>")    'windmove-up)
(define-key custom-bindings-map (kbd "C-c <down>")  'windmove-down)
(define-key custom-bindings-map (kbd "C-c <left>")  'windmove-left)
(define-key custom-bindings-map (kbd "C-c <right>") 'windmove-right)
(define-key custom-bindings-map (kbd "C-c t")
  (lambda () (interactive) (org-agenda nil "n")))

< svg aria-hidden =trueclass =octicon octicon-linkheight =16version =1.1viewBox =0 0 16 16width =16> 上面定义的功能的绑定。

(define-key global-map          (kbd "M-p")     'jump-to-previous-like-this)
(define-key global-map          (kbd "M-n")     'jump-to-next-like-this)
(define-key custom-bindings-map (kbd "M-,")     'jump-to-previous-like-this)
(define-key custom-bindings-map (kbd "M-.")     'jump-to-next-like-this)
(define-key custom-bindings-map (kbd "C-c .")   (cycle-themes))
(define-key custom-bindings-map (kbd "C-x k")   'kill-this-buffer-unless-scratch)
(define-key custom-bindings-map (kbd "C-c C-0") 'global-scale-default)
(define-key custom-bindings-map (kbd "C-c C-=") 'global-scale-up)
(define-key custom-bindings-map (kbd "C-c C-+") 'global-scale-up)
(define-key custom-bindings-map (kbd "C-c C–") 'global-scale-down)
(define-key custom-bindings-map (kbd "C-x t")   'toggle-shell)
(define-key custom-bindings-map (kbd "C-c j")   'cycle-spacing-delete-newlines)
(define-key custom-bindings-map (kbd "C-c d")   'duplicate-thing)
(define-key custom-bindings-map (kbd "<C-tab>") 'tidy)
(define-key custom-bindings-map (kbd "C-c C-q")
  '(lambda ()
     (interactive)
     (focus-mode 1)
     (focus-read-only-mode 1)))
(with-eval-after-load 'org
  (define-key org-mode-map (kbd "C-'") 'org-sync-pdf))
最后,我们需要通过创建和激活地图来激活地图    minor-mode

(define-minor-mode custom-bindings-mode
  "A mode that activates custom-bindings."
  t nil custom-bindings-map)

License

我的Emacs配置用组织模式写。

版权所有(c)2013 - 2015 Lars Tveito

此程序是免费软件:您可以重新分发和/或修改   它根据GNU通用公共许可证的条款发布   自由软件基金会,版本3的许可证,或   (根据您的选择)任何更高版本。

这个程序是分发的,希望它是有用的,   但不提供任何保证;甚至没有隐含的保证   适销性或特定用途的适用性。见   GNU通用公共许可证,以了解更多细节。

你应该收到GNU通用公共许可证的副本   以及这个程序。如果没有,请参阅 http://www.gnu.org/licenses/




相关问题推荐