lexical-binding not being enabled when evaluating .emacs - emacs

Here are some excerpts from my .emacs:
(setq lexical-binding t)
;; .emacs
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(diff-switches "-u")
'(tab-always-indent (quote complete)))
;...
(require 'dired)
;...
(dotimes (i 12) (define-key dired-mode-map (kbd (concat "<f" (number-to-string (1+ i)) ">"))
(lambda ()
(interactive)
(goto-char (point-min))
(forward-line (+ 4 i)))))
This should bind keys f1 to f12 in dired-mode to commands that jump to particular files in the list of files (ignoring . and ..). However, initially, after starting emacs, these keys don't work - I get an error message forward-line: Symbol's value as variable is void: i. However, when I go to the top line of my .emacs and press C-x C-e to evaluate that line, and then go to the last line quoted above and press C-x C-e to evaluate that dotimes expression, those function keys start working!
Why is that?
By the way, it also doesn't work if I evaluate the whole buffer.

It turns out that it is necessary to replace
(setq lexical-binding t)
with
;; -*- lexical-binding: t -*-
The manual hints suggestively at this, but does not actually say so outright.

Related

(ELisp) automatically nesting next line using brace return

I'm completely new to both Lisp and Emacs. In Emacs, when coding in Java for example, I want to be able to type "{" then hit "ENTER" and have the next line be ready for whatever is nested in the braces. For example, if I have the following line:
public void method()
and I type "{" then hit return I should get this:
public void method() {
// indentation applied, no additional tabbing necessary
}
I'm already able to insert by pairs, for example, typing "{" gives "{}" with my cursor between the braces. I did this by adding these lines to the emacs init file:
;; insert by pairs (parens, quotes, brackets, braces)
(defun insert-pair (leftChar rightChar)
(if (region-active-p)
(let (
(p1 (region-beginning))
(p2 (region-end))
)
(goto-char p2)
(insert rightChar)
(goto-char p1)
(insert leftChar)
(goto-char (+ p2 2))
)
(progn
(insert leftChar rightChar)
(backward-char 1) ) )
)
(defun insert-pair-brace () (interactive) (insert-pair "{" "}") )
(global-set-key (kbd "{") 'insert-pair-brace)
To get the auto-nesting I described above, I added these lines:
;; automatically nest next line
(defun auto-nest ()
(insert "\n\n")
(backward-char 1)
(insert "\t")
)
(defun auto-nest-brace () (interactive) (auto-nest) )
(global-set-key (kbd "{ RET") 'auto-nest-brace)
When I start up Emacs, however, I get this message:
error: Key sequence { RET starts with non-prefix key {
What am I doing wrong, and what can I do to fix it? I don't want to use a different key combination to do this. There are a lot of text editors in which this auto-nesting is standard, and it should be easy enough to code up in ELisp.
It's great that you are trying to add this functionality to Emacs yourself, but there's no need to reinvent the wheel here. Emacs already has a command for the purpose of auto-indenting; it's called newline-and-indent. It is bound to C-j by default, but you can rebind it to RET
globally:
(global-set-key (kbd "RET") 'newline-and-indent)
for a specific mode only:
(require 'cc-mode)
(define-key java-mode-map (kbd "RET") 'newline-and-indent)
java-mode-map is defined in cc-mode.el and not available by default, that's why you have to require cc-mode before you can modify java-mode-map.
Note that newline-and-indent indents according to major mode. That is, if you're e.g. in java-mode and press RET in some random location that's not meaningful w/r/t Java syntax, it won't insert additional whitespace at the beginning of the new line.
To read all there is to know about newline-and-indent do
C-h f newline-and-indent RET
I have something similar in my emacs config which I have been using for a while. It calls 'newline-and-indent twice then moves the point one line up before indenting correctly. Here is the snippet of code to do this from my config file:
;; auto indent on opening brace
(require 'cc-mode)
(defun av/auto-indent-method ()
"Automatically indent a method by adding two newlines.
Puts point in the middle line as well as indent it by correct amount."
(interactive)
(newline-and-indent)
(newline-and-indent)
(forward-line -1)
(c-indent-line-or-region))
(defun av/auto-indent-method-maybe ()
"Check if point is at a closing brace then auto indent."
(interactive)
(let ((char-at-point (char-after (point))))
(if (char-equal ?} char-at-point)
(av/auto-indent-method)
(newline-and-indent))))
(define-key java-mode-map (kbd "RET") 'av/auto-indent-method-maybe)
Pretty straightforward as you can see. Hopefully it will work for you. I have not used it in any other modes except java.
You want a combination of auto pairs (or alternatives) plus auto indentation. Check out the emacswiki on the former: http://www.emacswiki.org/emacs/AutoPairs
And on the latter:
http://www.emacswiki.org/emacs/AutoIndentation

delete (NOT kill) a line in emacs. External clipboard is not appended to the kill ring

Many times I find myself in need of pasting a path from wherever to emacs' minibuffer. To clear the minibuffer fast I navigate to the beginning and do C-k (kill line).
This effectively overrides whatever path I had in the system clipboard with the temporary path I just killed in the minibuffer. Navigating the kill ring with M-y won't bring the path I had in the system clipboard.
Is there a way to delete the current line without killing it( i.e. removing it and adding it to the kill ring)?
So far I'm marking the line and pressing delete having delete-selection-mote active. I would like a one key solution similar to C-k.
As of Emacs 23.2, you can set save-interprogram-paste-before-kill to a non-nil value (hat tip Tyler) to copy the clipboard selection onto the kill ring, so that it is available via C-y M-y:
(setq save-interprogram-paste-before-kill t)
If you're on an older Emacs, the following advice has the same functionality:
(defadvice kill-new (before kill-new-push-xselection-on-kill-ring activate)
"Before putting new kill onto the kill-ring, add the clipboard/external selection to the kill ring"
(let ((have-paste (and interprogram-paste-function
(funcall interprogram-paste-function))))
(when have-paste (push have-paste kill-ring))))
And, you could do something like this (horrible keybinding, customize to suit) to delete the line from the point forward:
(define-key minibuffer-local-map (kbd "C-S-d") 'delete-line)
(defun delete-line (&optional arg)
(interactive "P")
;; taken from kill-line
(delete-region (point)
;; It is better to move point to the other end of the kill
;; before killing. That way, in a read-only buffer, point
;; moves across the text that is copied to the kill ring.
;; The choice has no effect on undo now that undo records
;; the value of point from before the command was run.
(progn
(if arg
(forward-visible-line (prefix-numeric-value arg))
(if (eobp)
(signal 'end-of-buffer nil))
(let ((end
(save-excursion
(end-of-visible-line) (point))))
(if (or (save-excursion
;; If trailing whitespace is visible,
;; don't treat it as nothing.
(unless show-trailing-whitespace
(skip-chars-forward " \t" end))
(= (point) end))
(and kill-whole-line (bolp)))
(forward-visible-line 1)
(goto-char end))))
(point))))
As of Emacs 23.2, this problem can be addressed with save-interprogram-paste-before-kill. If you set this variable to t then stuff in the clipboard gets added to the kill-ring, and isn't discarded by your next kill.
The documentation:
Save clipboard strings into kill ring before replacing them.
When one selects something in another program to paste it into Emacs,
but kills something in Emacs before actually pasting it,
this selection is gone unless this variable is non-nil,
in which case the other program's selection is saved in the `kill-ring'
before the Emacs kill and one can still paste it using C-y M-y.
From Xahlee's page, it shows several commands that are annoying.
(defun my-delete-word (arg)
"Delete characters forward until encountering the end of a word.
With argument, do this that many times.
This command does not push erased text to kill-ring."
(interactive "p")
(delete-region (point) (progn (forward-word arg) (point))))
(defun my-backward-delete-word (arg)
"Delete characters backward until encountering the beginning of a word.
With argument, do this that many times.
This command does not push erased text to kill-ring."
(interactive "p")
(my-delete-word (- arg)))
(defun my-delete-line ()
"Delete text from current position to end of line char."
(interactive)
(delete-region
(point)
(save-excursion (move-end-of-line 1) (point)))
(delete-char 1)
)
(defun my-delete-line-backward ()
"Delete text between the beginning of the line to the cursor position."
(interactive)
(let (x1 x2)
(setq x1 (point))
(move-beginning-of-line 1)
(setq x2 (point))
(delete-region x1 x2)))
; Here's the code to bind them with emacs's default shortcut keys:
(global-set-key (kbd "M-d") 'my-delete-word)
(global-set-key (kbd "<M-backspace>") 'my-backward-delete-word)
(global-set-key (kbd "C-k") 'my-delete-line)
(global-set-key (kbd "C-S-k") 'my-delete-line-backward)
There isn't.
from the GNU Emacs Manual:
We have already described the basic deletion commands C-d
(delete-char) and (delete-backward-char). See Erasing.
The other delete commands are those that delete only whitespace
characters: spaces, tabs and newlines. M-\ (delete-horizontal-space)
deletes all the spaces and tab characters before and after point. With
a prefix argument, this only deletes spaces and tab characters before
point. M- (just-one-space) does likewise but leaves a single
space after point, regardless of the number of spaces that existed
previously (even if there were none before). With a numeric argument
n, it leaves n spaces after point.
What about something like:
(defun del-line (p1)
(interactive "d")
(move-end-of-line 1)
(when (eq p1 (point)) ; special case when p1 is already at the end of the line
(forward-line))
(delete-region p1 (point)))
The behavior should be similar to C-k but without affecting the system clipboard or the kill-ring.
ETA: I read Trey's solution more carefully, and it looks like this is just a simple case of his solution. It worked in my (very!) limited tests, but probably fails for some special cases where the more complicated kill-line code works correctly.
Found an answer to this.
Posted it first here: https://unix.stackexchange.com/questions/26360/emacs-deleting-a-line-without-sending-it-to-the-kill-ring/136581#136581
;; Ctrl-K with no kill
(defun delete-line-no-kill ()
(interactive)
(delete-region
(point)
(save-excursion (move-end-of-line 1) (point)))
(delete-char 1)
)
(global-set-key (kbd "C-k") 'delete-line-no-kill)

Emacs: Tab completion of file name appends an extra i:\cygwin

I am facing some strange behavior with file-name completion in emacs. C-x C-f to find file opens up the minibuffer with i:/cygwin/home/rrajagop/StockScreener/working_copy/master_repo/stock_screener/. Hitting a TAB makes it i:/cygwini:/cygwin/home/rrajagop/StockScreener/working_copy/master_repo/stock_screener/. A couple of interesting things I've noticed:
When the minibuffer opens up, i:/cygwin is greyed out and the path seems to start from /home. A C-a (go to begining of line) takes me to /home and not to i:/cygwin. So it looks like something in emacs is parsing the path to start from /home and not from i:/cygwin.
I checked that TAB runs minibuffer-complete from minibuffer.el (by doing a describe-key for TAB), so it looks like minibuffer-complete is doing some translation for cygwin and appending the extra i:/cygwin.
How would I go about figuring this out/fixing it?
EDIT: Extra Information
I tried opening up emacs with -Q and this problem doesn't happen. So this is something I'm loading in my .emacs. This is what I have in my .emacs
(require 'cl)
; Needed to see how fast Emacs loads. Loading time is printed at the
; and of the execution of .emacs file.
(defvar *emacs-load-start* (current-time))
; I really like this font. I also tried Monaco which you can
; see on lot of Railscasts but I couldn't find the one which
; supports Serbian Cyrillic and Latin letters.
(set-default-font "-outline-Courier New-normal-r-normal-normal-19-142-96-96-c-*-iso8859-1")
;; Don't show that splash screen
(setq inhibit-startup-message t)
; This should allegedly speed up Emacs starting by preventing
; some requests from the window manager back to the Emacs. Frankly
; speaking I didn't notice some speed up but I still keep it:(
(modify-frame-parameters nil '((wait-for-wm . nil)))
;Allows syntax highlighting to work, among other things
(global-font-lock-mode 1)
; Sets initial window position
(set-frame-position (selected-frame) 0 0)
; Sets initial window size to 85 columns and 47 rows
(set-frame-size (selected-frame) 88 32)
; Makes last line ends in carriage return
(setq requre-final-newline t)
; Sets Ctrl-x / key combination for easy commenting
; out of selected lines.
(global-set-key "\C-x/" 'comment-or-uncomment-region)
; Allow resizing of the mini-buffer when necessary
(setq resize-minibuffer-mode t)
; Auto magically read compressed files
(auto-compression-mode 1)
; Set standard indent to 2 rather then 4
(setq standard-indent 2)
; This tells Emacs to create backup files.
(setq make-backup-files t)
; And this will enable versioning with default values.
(setq version-control t)
; Remove annoying message about deleting excess backup of .recentf
; which is list of recent files used
(setq delete-old-versions t)
; Finally do not spread backups all over the disk.
; Just save all backup files in this directory.
(setq backup-directory-alist (quote ((".*" . "~/.emacs_backups/"))))
;; Directory to put various el files.
(add-to-list 'load-path "~/.emacs.d/includes")
(require 'ascii-table)
;; Loading collection of generic modes for different languages
(require 'generic-x)
;; Recent files
(require 'recentf)
(recentf-mode 1)
;; Loads ruby mode when a ruby file is opened.
(autoload 'ruby-mode "ruby-mode" "Major mode for editing ruby scripts." t)
(setq auto-mode-alist (cons '(".rb$" . ruby-mode) auto-mode-alist))
(setq auto-mode-alist (cons '(".rhtml$" . html-mode) auto-mode-alist))
(setq auto-mode-alist (cons '(".html.erb$" . html-mode) auto-mode-alist))
;; Turn on ruby electric (auto completion of parenthesis, etc.)
(add-hook 'ruby-mode-hook
(lambda()
(add-hook 'local-write-file-hooks
'(lambda()
(save-excursion
(untabify (point-min) (point-max))
(delete-trailing-whitespace) )))
(set (make-local-variable 'indent-tabs-mode) 'nil)
(set (make-local-variable 'tab-width) 2)
(imenu-add-to-menubar "IMENU")
(define-key ruby-mode-map "\C-m" 'newline-and-indent)
(require 'ruby-electric)
(ruby-electric-mode t) ))
;; Ruby debugging.
(add-to-list 'load-path "~/.emacs.d/plugins/rdebug")
(autoload 'rdebug "rdebug" "Ruby debugging support." t)
(global-set-key [f9] 'gud-step)
(global-set-key [f10] 'gud-next)
(global-set-key [f11] 'gud-cont)
(global-set-key "\C-c\C-d" 'rdebug)
;; set compile command based on current major mode
(autoload 'mode-compile "mode-compile"
"Command to compile current buffer file based on the major mode" t)
(global-set-key "\C-cc" 'mode-compile)
(autoload 'mode-compile-kill "mode-compile"
"Command to kill a compilation launched by `mode-compile'" t)
(global-set-key "\C-ck" 'mode-compile-kill)
;; yasnippet - adding code snippet insertion
(add-to-list 'load-path "~/.emacs.d/plugins/yasnippet")
(require 'yasnippet) ;; not yasnippet-bundle
(yas/initialize)
(yas/load-directory "~/.emacs.d/plugins/yasnippet/snippets")
;; Use CYGWIN bash
(require 'setup-cygwin)
;; Subversion integration via psvn - not gonna use svn anymore
;; (require 'psvn)
;; add some elisp tutorials to the info directory
(let ((info-root (concat usb-drive-letter "cygwin/usr/local/bin/emacs/info/")))
(setq Info-directory-list (list info-root
(concat info-root "elisp-tutorial-2.04/")
(concat info-root "emacs-lisp-intro-2.14")) )
)
;; Load time for .emacs - this should be the last line in .emacs for accurate load time
(message "ido and org-install took: %ds"
(destructuring-bind (hi lo ms) (current-time)
(- (+ hi lo) (+ (first *emacs-load-start*) (second *emacs-load-start*)) )))
I think my answer to your previous question on finding the package loading tramp will help you out here.
you can control tramp by changing the variable tramp-mode.
Side note, you would probably find it useful to use customize to customize emacs.
I did a customize-apropos with tramp and it found the tramp group. Clicking there showed all the ways to configure tramp, including turning it off.
File-name-shadow-mode greys out the c: in the file name..... so when cygwin-mount-substitute-longest-mount-name runs it does no see the c: and adds another
M-x find-file
c:/home/
> a
c:/home/a ; but the c: is greyed
> TAB
c:c:/home/anything

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)
)
)

How do I duplicate a whole line in Emacs?

I saw this same question for VIM and it has been something that I myself wanted to know how to do for Emacs. In ReSharper I use CTRL-D for this action. What is the least number of commands to perform this in Emacs?
I use
C-a C-SPACE C-n M-w C-y
which breaks down to
C-a: move cursor to start of line
C-SPACE: begin a selection ("set mark")
C-n: move cursor to next line
M-w: copy region
C-y: paste ("yank")
The aforementioned
C-a C-k C-k C-y C-y
amounts to the same thing (TMTOWTDI)
C-a: move cursor to start of line
C-k: cut ("kill") the line
C-k: cut the newline
C-y: paste ("yank") (we're back at square one)
C-y: paste again (now we've got two copies of the line)
These are both embarrassingly verbose compared to C-d in your editor, but in Emacs there's always a customization. C-d is bound to delete-char by default, so how about C-c C-d? Just add the following to your .emacs:
(global-set-key "\C-c\C-d" "\C-a\C- \C-n\M-w\C-y")
(#Nathan's elisp version is probably preferable, because it won't break if any of the key bindings are changed.)
Beware: some Emacs modes may reclaim C-c C-d to do something else.
In addition to the previous answers you can also define your own function to duplicate a line. For example, putting the following in your .emacs file will make C-d duplicate the current line.
(defun duplicate-line()
(interactive)
(move-beginning-of-line 1)
(kill-line)
(yank)
(open-line 1)
(next-line 1)
(yank)
)
(global-set-key (kbd "C-d") 'duplicate-line)
Place cursor on line, if not at beginning do a CTRL-A, then:
CTRL-K
CTRL-K
CTRL-Y
CTRL-Y
My version of a function to duplicate a line that works nice with undo and doesn't mess with the cursor position. It was the result of a discussion in gnu.emacs.sources from November 1997.
(defun duplicate-line (arg)
"Duplicate current line, leaving point in lower line."
(interactive "*p")
;; save the point for undo
(setq buffer-undo-list (cons (point) buffer-undo-list))
;; local variables for start and end of line
(let ((bol (save-excursion (beginning-of-line) (point)))
eol)
(save-excursion
;; don't use forward-line for this, because you would have
;; to check whether you are at the end of the buffer
(end-of-line)
(setq eol (point))
;; store the line and disable the recording of undo information
(let ((line (buffer-substring bol eol))
(buffer-undo-list t)
(count arg))
;; insert the line arg times
(while (> count 0)
(newline) ;; because there is no newline in 'line'
(insert line)
(setq count (1- count)))
)
;; create the undo information
(setq buffer-undo-list (cons (cons eol (point)) buffer-undo-list)))
) ; end-of-let
;; put the point in the lowest line and return
(next-line arg))
Then you can define CTRL-D to call this function:
(global-set-key (kbd "C-d") 'duplicate-line)
Instead of kill-line (C-k) as in C-a C-k C-k C-y C-y use the kill-whole-line command:
C-S-Backspace
C-y
C-y
The advantages over C-k include that it does not matter where point is on the line (unlike C-k which requires being at start of the line) and it also kills the newline (again something C-k does not do).
Here's yet another function for doing this. My version doesn't touch the kill ring, and the cursor ends up on the new line where it was on the original. It will duplicate the region if it's active (transient mark mode), or default to duplicating the line otherwise. It will also make multiple copies if given a prefix arg, and comment out the original line if given a negative prefix arg (this is useful for testing a different version of a command/statement while keeping the old one).
(defun duplicate-line-or-region (&optional n)
"Duplicate current line, or region if active.
With argument N, make N copies.
With negative N, comment out original line and use the absolute value."
(interactive "*p")
(let ((use-region (use-region-p)))
(save-excursion
(let ((text (if use-region ;Get region if active, otherwise line
(buffer-substring (region-beginning) (region-end))
(prog1 (thing-at-point 'line)
(end-of-line)
(if (< 0 (forward-line 1)) ;Go to beginning of next line, or make a new one
(newline))))))
(dotimes (i (abs (or n 1))) ;Insert N times, or once if not specified
(insert text))))
(if use-region nil ;Only if we're working with a line (not a region)
(let ((pos (- (point) (line-beginning-position)))) ;Save column
(if (> 0 n) ;Comment out original with negative arg
(comment-region (line-beginning-position) (line-end-position)))
(forward-line 1)
(forward-char pos)))))
I have it bound to C-c d:
(global-set-key [?\C-c ?d] 'duplicate-line-or-region)
This should never be re-assigned by a mode or anything because C-c followed by a single (unmodified) letter is reserved for user bindings.
Nathan's addition to your .emacs file is the way to go but it could be simplified slightly by replacing
(open-line 1)
(next-line 1)
with
(newline)
yielding
(defun duplicate-line()
(interactive)
(move-beginning-of-line 1)
(kill-line)
(yank)
(newline)
(yank)
)
(global-set-key (kbd "C-d") 'duplicate-line)
install duplicate-thing from melpa:
M-x package-install RET duplicate-thing
and add this keybinding to init file :
(global-set-key (kbd "M-c") 'duplicate-thing)
I don't quite remember how line duplication works anywhere else, but as a former SciTE user I liked one thing about SciTE-way: it doesn't touch the cursor position!
So all the recipies above weren't good enough for me, here's my hippie-version:
(defun duplicate-line ()
"Clone line at cursor, leaving the latter intact."
(interactive)
(save-excursion
(let ((kill-read-only-ok t) deactivate-mark)
(toggle-read-only 1)
(kill-whole-line)
(toggle-read-only 0)
(yank))))
Note that nothing gets actually killed in process, leaving marks and current selection intact.
BTW, why you guys so fond of jerking cursor around when there's this nice'n'clean kill-whole-line thingy (C-S-backspace)?
I have copy-from-above-command bound to a key and use that. It's provided with XEmacs, but I don't know about GNU Emacs.
`copy-from-above-command' is an
interactive compiled Lisp function
-- loaded from "/usr/share/xemacs/21.4.15/lisp/misc.elc"
(copy-from-above-command &optional
ARG)
Documentation: Copy characters from
previous nonblank line, starting just
above point. Copy ARG characters, but
not past the end of that line. If no
argument given, copy the entire rest
of the line. The characters copied are
inserted in the buffer before point.
something you might want to have in your .emacs is
(setq kill-whole-line t)
Which basically kills the entire line plus the newline whenever you invoke kill-line (i.e. via C-k). Then without extra code, you can just do C-a C-k C-y C-y to duplicate the line. It breaks down to
C-a go to beginning of line
C-k kill-line (i.e. cut the line into clipboard)
C-y yank (i.e. paste); the first time you get the killed line back;
second time gives the duplicated line.
But if you use this often then maybe a dedicated key binding might be a better idea, but the advantage of just using C-a C-k C-y C-y is you can duplicate the line elsewhere, instead of just below the current line.
' I wrote my own version of duplicate-line, cause I don't want to screw up the killing ring.
(defun jr-duplicate-line ()
"EASY"
(interactive)
(save-excursion
(let ((line-text (buffer-substring-no-properties
(line-beginning-position)
(line-end-position))))
(move-end-of-line 1)
(newline)
(insert line-text))))
(global-set-key "\C-cd" 'jr-duplicate-line)
There is package called Avy It has command avy-copy-line. When you use that command, every line in your window gets letter combination. Then you just have to type combination and you get that line. This also works for region. Then you just have to type two combination.
Here you can see interface:
because i don't know, i'll start this round of golf with a slowball:
ctrl-k, y, y
C-a C-k C-k C-y C-y
The defaults are horrible for this. However, you can extend Emacs to work like SlickEdit and TextMate, that is, copy/cut the current line when no text is selected:
(transient-mark-mode t)
(defadvice kill-ring-save (before slick-copy activate compile)
"When called interactively with no active region, copy a single line instead."
(interactive
(if mark-active (list (region-beginning) (region-end))
(message "Copied line")
(list (line-beginning-position)
(line-beginning-position 2)))))
(defadvice kill-region (before slick-cut activate compile)
"When called interactively with no active region, kill a single line instead."
(interactive
(if mark-active (list (region-beginning) (region-end))
(list (line-beginning-position)
(line-beginning-position 2)))))
Place the above in .emacs. Then, to copy a line, M-w. To delete a line, C-w. To duplicate a line, C-a M-w C-y C-y C-y ....
I liked FraGGod's version, except for two things: (1) It doesn't check whether the buffer is already read-only with (interactive "*"), and (2) it fails on the last line of the buffer if that last line is empty (as you cannot kill the line in that case), leaving your buffer read-only.
I made the following changes to resolve that:
(defun duplicate-line ()
"Clone line at cursor, leaving the latter intact."
(interactive "*")
(save-excursion
;; The last line of the buffer cannot be killed
;; if it is empty. Instead, simply add a new line.
(if (and (eobp) (bolp))
(newline)
;; Otherwise kill the whole line, and yank it back.
(let ((kill-read-only-ok t)
deactivate-mark)
(toggle-read-only 1)
(kill-whole-line)
(toggle-read-only 0)
(yank)))))
With recent emacs, you can use M-w anywhere in the line to copy it. So it becomes:
M-w C-a RET C-y
I saw very complex solutions, anyway...
(defun duplicate-line ()
"Duplicate current line"
(interactive)
(kill-whole-line)
(yank)
(yank))
(global-set-key (kbd "C-x M-d") 'duplicate-line)
This functionality should match up with JetBrains' implementation in terms of duplicating both by line or region, and then leaving the point and/ or active region as expected:
Just a wrapper to around the interactive form:
(defun wrx/duplicate-line-or-region (beg end)
"Implements functionality of JetBrains' `Command-d' shortcut for `duplicate-line'.
BEG & END correspond point & mark, smaller first
`use-region-p' explained:
http://emacs.stackexchange.com/questions/12334/elisp-for-applying-command-to-only-the-selected-region#answer-12335"
(interactive "r")
(if (use-region-p)
(wrx/duplicate-region-in-buffer beg end)
(wrx/duplicate-line-in-buffer)))
Which calls this,
(defun wrx/duplicate-region-in-buffer (beg end)
"copy and duplicate context of current active region
|------------------------+----------------------------|
| before | after |
|------------------------+----------------------------|
| first <MARK>line here | first line here |
| second item<POINT> now | second item<MARK>line here |
| | second item<POINT> now |
|------------------------+----------------------------|
TODO: Acts funky when point < mark"
(set-mark-command nil)
(insert (buffer-substring beg end))
(setq deactivate-mark nil))
Or this
(defun wrx/duplicate-line-in-buffer ()
"Duplicate current line, maintaining column position.
|--------------------------+--------------------------|
| before | after |
|--------------------------+--------------------------|
| lorem ipsum<POINT> dolor | lorem ipsum dolor |
| | lorem ipsum<POINT> dolor |
|--------------------------+--------------------------|
TODO: Save history for `Cmd-Z'
Context:
http://stackoverflow.com/questions/88399/how-do-i-duplicate-a-whole-line-in-emacs#answer-551053"
(setq columns-over (current-column))
(save-excursion
(kill-whole-line)
(yank)
(yank))
(let (v)
(dotimes (n columns-over v)
(right-char)
(setq v (cons n v))))
(next-line))
And then I have this bound to meta+shift+d
(global-set-key (kbd "M-D") 'wrx/duplicate-line-or-region)
When called interactively with no active region, COPY (M-w) a single line instead :
(defadvice kill-ring-save (before slick-copy activate compile)
"When called interactively with no active region, COPY a single line instead."
(interactive
(if mark-active (list (region-beginning) (region-end))
(message "Copied line")
(list (line-beginning-position)
(line-beginning-position 2)))))
When called interactively with no active region, KILL (C-w) a single line instead.
(defadvice kill-region (before slick-cut activate compile)
"When called interactively with no active region, KILL a single line instead."
(interactive
(if mark-active (list (region-beginning) (region-end))
(message "Killed line")
(list (line-beginning-position)
(line-beginning-position 2)))))
Also, on a related note:
(defun move-line-up ()
"Move the current line up."
(interactive)
(transpose-lines 1)
(forward-line -2)
(indent-according-to-mode))
(defun move-line-down ()
"Move the current line down."
(interactive)
(forward-line 1)
(transpose-lines 1)
(forward-line -1)
(indent-according-to-mode))
(global-set-key [(meta shift up)] 'move-line-up)
(global-set-key [(meta shift down)] 'move-line-down)
#[Kevin Conner]: Pretty close, so far as I know. The only other thing to consider is turning on kill-whole-line to include the newline in the C-k.
ctrl-k, ctrl-k, (position to new location) ctrl-y
Add a ctrl-a if you're not starting at the beginning of the line. And the 2nd ctrl-k is to grab the newline character. It can be removed if you just want the text.
If you're using Spacemacs, you can simply use duplicate-line-or-region, bound to:
SPC x l d
There's a package called 'move-dup' on Melpa that can help you with that.
Disclaimer: I'm the author of that package.
Here's a function for duplicating current line. With prefix arguments, it will duplicate the line multiple times. E.g., C-3 C-S-o will duplicate the current line three times. Doesn't change kill ring.
(defun duplicate-lines (arg)
(interactive "P")
(let* ((arg (if arg arg 1))
(beg (save-excursion (beginning-of-line) (point)))
(end (save-excursion (end-of-line) (point)))
(line (buffer-substring-no-properties beg end)))
(save-excursion
(end-of-line)
(open-line arg)
(setq num 0)
(while (< num arg)
(setq num (1+ num))
(forward-line 1)
(insert line))
)))
(global-set-key (kbd "C-S-o") 'duplicate-lines)
I write one for my preference.
(defun duplicate-line ()
"Duplicate current line."
(interactive)
(let ((text (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
(cur-col (current-column)))
(end-of-line) (insert "\n" text)
(beginning-of-line) (right-char cur-col)))
(global-set-key (kbd "C-c d l") 'duplicate-line)
But I found this would have some problem when current line contains multi-byte characters (e.g. CJK characters). If you encounter this issue, try this instead:
(defun duplicate-line ()
"Duplicate current line."
(interactive)
(let* ((text (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
(cur-col (length (buffer-substring-no-properties (point-at-bol) (point)))))
(end-of-line) (insert "\n" text)
(beginning-of-line) (right-char cur-col)))
(global-set-key (kbd "C-c d l") 'duplicate-line)
I cannot believe all these complicated solutions. This is two keystrokes:
<C-S-backspace> runs the command kill-whole-line
C-/ runs the command undo
So <C-S-backspace> C-/ to "copy" a whole line (kill and undo).
You can, of course, combine this with numeric and negative args to kill multiple lines either forward or backward.
As mentioned in other answers, binding key strokes to lisp code is a better idea than binding them to another key strokes. With #mw's answer, code duplicates the line and moves the mark to end of new line. This modification keeps the mark position at same column on the new line:
fun duplicate-line ()
(interactive)
(let ((col (current-column)))
(move-beginning-of-line 1)
(kill-line)
(yank)
(newline)
(yank)
(move-to-column col)))
With prefix arguments, and what is (I hope) intuitive behaviour:
(defun duplicate-line (&optional arg)
"Duplicate it. With prefix ARG, duplicate ARG times."
(interactive "p")
(next-line
(save-excursion
(let ((beg (line-beginning-position))
(end (line-end-position)))
(copy-region-as-kill beg end)
(dotimes (num arg arg)
(end-of-line) (newline)
(yank))))))
The cursor will remain on the last line.
Alternatively, you might want to specify a prefix to duplicate the next few lines at once:
(defun duplicate-line (&optional arg)
"Duplicate it. With prefix ARG, duplicate ARG times."
(interactive "p")
(save-excursion
(let ((beg (line-beginning-position))
(end
(progn (forward-line (1- arg)) (line-end-position))))
(copy-region-as-kill beg end)
(end-of-line) (newline)
(yank)))
(next-line arg))
I find myself using both often, using a wrapper function to switch the behavior of the prefix argument.
And a keybinding:
(global-set-key (kbd "C-S-d") 'duplicate-line)