(Stupid) Useful Emacs Tricks?
Count Fenring writes "Since the Vi version of this question was both interesting and popular, let's hear from the other end of the spectrum. What are your favorite tricks, macros, extensions, and techniques for any of the various Emacs? Myself, I like 'M-x dunnet' ;-)"
I've found this very useful whenever I'm put in front of emacs C-x C-c sudo apt-get -y purge emacs vi
Hopefully this is the last story before we start with "Stupid pet tricks"
[Fuck Beta]
o0t!
There, fixed that for me!
I've found this very useful whenever I'm put in front of emacs
C-x C-c
sudo apt-get -y purge emacs
vi
C-X M-C M-butterfly
Write your own Choose Your Own Adventure. http://www.freegameengines.org/gamebook-engine/
the Vi version of this question was both interesting and popular
Indeed. Probably because Vi is a popular and usable text editor (unlike Emacs).
I am disappointed. I expected this topic a few hours earlier.
Of all the Elisp I've written this grep is what I most miss when I use a coworker's environment.
/dev/null")))
(defun my-grep ()
"grep the whole directory for something defaults to term at cursor position"
(interactive)
(setq default (thing-at-point 'symbol))
(setq needle (or (read-string (concat "grep for <" default "> ")) default))
(setq needle (if (equal needle "") default needle))
(grep (concat "egrep -s -i -n " needle " *
(global-set-key "\C-x." 'my-grep)
(global-set-key [f8] 'next-error)
M-x tetris
M-x doctor
M-x yow
M-x phases-of-moon
Dear Slashdot,
For us Windows users, I would be very much interested in a similar topic for useful Notepad tricks.
Please take this seriously, and don't say that Alt-F4 (or Alt-F, X) is the best trick.
Yours sincerely,
Fred Anboy
(Stupid) Userful Bash Tricks ???
http://www.nasirudheen.blogspot/
(global-set-key (kbd "C-c c") 'comment-dwim)
C-c c to either comment out a region or uncomment it depending on context. Lovely feature.
(global-set-key "\M-g" 'goto-line)
M-g to go to specified line in buffer. Useful for emacs 21.x users where the keybinding is not yet standard.
(menu-bar-mode nil) (scroll-bar-mode nil) (tool-bar-mode nil)
Gets rid of the ugly TK widgets.
(iswitchb-mode t)
Superboosts C-x b.
(global-set-key "\C-z" 'undo)
The normal binding for C-z is suspend-emacs but having it bound as undo is much more useful imo.
Football Odds
in one's .emacs file. Then open remote files with:
Ita erat quando hic adveni.
Forget where I read this...
EMACS: Equine Mammals are Considerably Smaller
Equine Mammals Are Considerably Smaller
I've recently discovered and almost instantly become a fan of org-mode, which is a great outlining tool (including folding, numbering, and other similar things you'd probably expect).
It's also good for lists of things to do, schedules, deadlines, and related stuff. It uses its own really simple markup langauge (similar to trac wiki), but you can include LaTeX and HTML inline.
It comes with exporters to HTML and LaTeX (and iCal for date stuff). You can also put tables inline, and the table editor is excellent for simple tables.
I use it every day for my list of things to do, and use it regularly for outlining text documents, pseudocode, and meeting notes.
When writing scientific papers in LaTeX, there's nothing else that comes close to the power of AUCTeX with preview-latex http://www.gnu.org/software/auctex/preview-latex.html. It allows you to view typeset equations inline with the rest of the document, but on moving the cursor into an equation, shows the original code. After editing, one brief command, and the new equation is typeset and displayed.
C-x ( -- start a macro definition
-- type some commands
C-x ) -- end the macro
C-x e -- execute the last macro
For certain repetitive tasks which didn't warrent a new script I though this macro capability was awesome.
CTRL-X 1|2|3 to divide the editing area according to wish. I simply can't live without this functionality.
Now if anyone makes a Firefox plugin making it possible to do the same in a web browser that would be friggin awesome.
One of my favorite emacsisms a long time ago was ange-ftp, and the modern descendant, tramp, is one of my current faves. It lets you edit remote files over lots of protocols, including: ssh, scp, ftp, rsync, ftp, and smb.
Most emacs stuff works transparently, like dired and archive browsing. When you edit a file and save it, it's automatically put back on the remote machine. I have had trouble with psvn, but that's about the only thing that I kinda expected to work that didn't.
If you edit remote files and you use emacs, you want to start using this.
Hmm.. that didn't work well for me. I tried it, but I ended up in an editor with functionality that was one step above punch cards.
A couple of times the ability of Emacs to record keystrokes and then edit them has been a real power tool, particularly when I've needed to do very complex edits over a set of files.
So I'd record edits on the first file, look at the keyboard recording (doing any substitutes if necessary), bind that to a key combination, then iterate over the list of files. Now if I were a good Emacs hacker, I could have automated the iteration step, too :-)
After 25 years of vi and Emacs, I got fed up and wrote something better. And at 6k lines of C, it's not much bigger than my .emacs file was. :-)
Seriously, people: you don't have to live with the available options. Writing an editor is a easy job.
And yes, I GPL'd it. Have fun.
http://code.google.com/p/aoeui/
"Skill shows through where genius wears thin." -Wittgenstein || Religion: uniting aviation and architecture.
Stupid trick #1: Vi emulation.
Turning an excellent editor into a piece of rubbbihs,
M-x hanoi - plays tower of hanoi for n number of towers
If you've got a file that you always want to set some specific variable to a non-default value for when editing, use something like this (taken from the end of a C file...)
* Local Variables:
* fill-column: 78
* c-basic-offset: 4
* End:
*/
"Little does he know, but there is no 'I' in 'Idiot'!"
Configure emacs auto-mode-alist to open Java archives with archive-mode, and then edit deployment descriptors contained in the archive without having to extract the archive. Bliss.
You must have forgotten order of ln parameters. It is just like cp: ln -s /usr/bin/vim /usr/bin/emacs
Persian Project Management Software as a Service
What, don't remember the eMac?
I'm starting to think GNU is the problem with "GNU/Linux" these days.
I only started to feel like I was beginning to have a clue with emacs when I learned to manage windows .. from then on the learning curve is easy because you're no longer humiliated by the inability to do something you take for granted so much in any GUI
C-x 3 split vertically
C-x 2 split horizontally
C-x o change to the other window
C-x 1 delete the opposite window
C-x 0 delete all other windows
Org-mode is really neat also
m-x org mode
m-x-describe-bindings / C-h b
Also you can use the meta key to access almost any command that also has a C- combination, by its literal full name. You can then use tab completion to jog your memory
eg.
m-x desc gives you the hint for the above, and when the command runs the minibuffer tells you to try C-h b next time
Emacs is surprisingly user friendly, once you get into into the swing of things!
My favorite Emacs trick is defun.
I think this article has been incorrectly filed; please fix, editors. It's been put under "News".
== Jez ==
Do you miss Firefox? Try Pale Moon.
recentf mode, which keeps a list of recently opened files:
(require 'recentf)
(recentf-mode 1)
For bonus points, set a PROJECT environment variable before starting eclipse, and maintain project-specific lists of recently opened files:
(when (getenv "PROJECT")
; project-specific recently opened files
(setq recentf-save-file (concat (getenv "PROJECT") "/.recentf"))
; project-specific emacs config
(when (file-exists-p (concat (getenv "PROJECT") "/.emacs"))
(load-file (concat (getenv "PROJECT") "/.emacs")))
; project-specific TAGS file
(when (file-exists-p (concat (getenv "PROJECT") "TAGS"))
(visit-tags-table (concat (getenv "PROJECT") "TAGS"))))
Take a look to http://www.emacswiki.org/emacs/EmacsNiftyTricks.
1)First, ESS, Emacs speaks statistics, found at http://ess.r-project.org/ . This lets you interface interactively with R, SAS, Stata, etc., all from the common Emacs interface. As a statistician, it's the one piece of software I could not do very well without!
2) The 'ido' package, with flex matching, in my .emacs,
(require 'ido)
(ido-mode t)
(setq ido-enable-flex-matching t)
This lets you open files and switch buffers with fuzzy matching, really nice when you have lots of things open.
See: http://www.emacsblog.org/2008/05/19/giving-ido-mode-a-second-chance/
3) Make the mouse jump away when you type over it.
(mouse-avoidance-mode 'cat-and-mouse)
4) Open two windows side-by-side (C-x 3) one with LaTeX code, one with a pdf, then use this in your .emacs, (add-hook 'doc-view-mode-hook 'auto-revert-mode), when you compile the .tex file into PDF, the PDF automatically updates in Emacs, I used that a lot while working on my CV.
5) The thunderbird extension that lets me compose replies in Emacs using emacsclient.
6) org-mode http://www.org-mode.org/
7) preview-latex, now part of AUCTeX, this lets you see preview versions of formulae and graphics inline in your .text file, *while you edit*. Your formula is replaced by what it will look like when compiled.
8) EmacsWiki: http://www.emacswiki.org/
auto completes based on words that have been seen in the buffer.
Then you forgot to install vim.
My other Slashdot ID is much lower.
It's often the case when you need to check the sectors on your disk for corruption, or just during hard drive testing. One of the coolest things that Emacs allows you to do is check your filesystem. For example on CentOS:
yum -y install emacs*
This will proceed to fill up your hard drive with tons of software until the filesystem is full.
(I kid, I kid)
Lisp is a language that CompScis see for two months at University before leaving it behind. But if you really want to learn tricks with Emacs, you should learn Emacs Lisp - I have all sorts of specials, such as "move text to marker" and modes for handling internal IBM dump formats, that would be impossible in vi.
But if you want one quick piece of advice, here's one that should make someone smile
M-x hippie-expand RET
The ultimate, expand-this-thing-dammit-from-whatever-you-like completion trick.
Cheers,
Toby Haynes
Anything I post is strictly my own thoughts and doesn't necessarily have anything to do with the opinions of IBM.
I once knew a man that typed an emacs sequence, once locked in hidden, ancient papyri. Emacs conducted all of the research for his PhD, typed his dissertation, correctly formatted his bibliography (the most astounding feat of all), setup the defense with his advisory committee, presented and defended his thesis, printed, bound and submitted the dissertation.
EMACS and butterflies
This post brought to you by your friendly neighborhood MBA.
I'll take it you don't eat macaroni then. And that you hated the Macarena. And that you'll steer clear from John Carmack's games. Or...
Troll.
(Full disclaimer: I'm a Mac-loving Vim user)
(Pretend that '.'==' ' because Slashdot hates programmers.)
Before:
After running M-xalign-regexp=:
Dewey, what part of this looks like authorities should be involved?
(defun my-kill-prev-line ()
"Kills from the cursor to the beginning of the line."
(interactive)
(kill-line 0))
(global-set-key "\C-u" 'my-kill-prev-line)
Makes Control-U do what it does in every other place on your computer.
There are a two general and powerful emacs tools that every user should know: keyboard macros and query-replace-regexp.
To record a keyboard macro, hit C-x ( to start recording, type your macro, and hit C-x ) to stop. Bind F5 or another function key to call-last-kbd-macro so it's easy to run a macro many times.
Then practice ;-) Learn to use C-a, C-e, and incremental search in your macros, so you can just hit F5 F5 F5... to perform a repetitive editing task across an entire file. You will be slow at composing the macros at first, but once you get the hang of it, you'll want to do everything using keyboard macros. (That might be a reasonable approach for some folks, but I recommend you keep going -- there's treasure everywhere!)
Once you're good at keyboard macros, the next thing to learn is query-replace-regexp. The hardest thing about query-replace-regexp is that emacs regexp syntax is a bit of an outlier in the regexp family. Once you get over that (which I haven't entirely) you're a ninja.
After those two, you should google around for more tips of enthusiastic emacs users, and generally keep an ear to the ground. Occasionally you'll hear of some command that is a perfect fit for your work or your brain or both.
Finally, elisp programming is essential for serious users. You don't have to immediately set aside time to learn it, but definitely do not shy away from it when you need it. You'll need a very basic understanding to tweak your .emacs file, and your knowledge can grow from there. I've only written half a dozen elisp functions for editing (rather than configuration) but I use a couple of them at least once a week. The first editing command I created in elisp took me half a day to write and debug, but then I used it dozens of times a day for three weeks -- pretty good ROI!
is M-x Viper \[esc]x eshell All the obscureness of vim combined with the bloat of emacs. Then I have lots of fun letting people borrow my computer and watch them get mad at my custom xmodmap while trying to figure out how to get to the "Start" menu because they don't know ratpoison.
We can pick a topic (C++ STL,C++ boost, Eclipse, Electioneering, etc) and then post the many clever/stupid tricks we have learnt.
well...it worked didn't it? :D
M-x yow
and of course, the ever relevant:
M-x psychoanalyze-pinhead
For GNU emacs:
(require 'ffap)
This means "find file at point." If the cursor is on anything that looks like a file (or URL, etc) it'll try to do the right thing for you automatically. RTFM for delicious details.
"M-q" will reindent a paragraph nicely. ." will set a fill prefix, i.e., if you need to reparagraph something with the " >" prefix for mail replies
"C-x
Keyboard macros are great for mass editing files. "C-x (" to start recording, "C-x )" to stop, "C-x e" to execute. Once you've got the macro working, repeat as needed, "C-u 99 C-x e".
My two .emacs modifications I find essential follow.
First, turning off of obnoxious misfeatures:
And second, stealing the beginning-of-line behavior from Dev Studio: if you invoke the command at the beginning of the line, advance to the first non-whitespace-character instead.
This is the first content I've seen in years that appeals to Slashdot's original demographics: hardcore geeks who are passionate about the tools they use. I've picked up a few tips in this series of articles and have enjoyed hearing other people learn about "old" stuff for the first time.
If "(Stupid) Useful $GEEK Tricks" isn't your cup of tea, then please feel free to look elsewhere.
Dewey, what part of this looks like authorities should be involved?
PS1="\w \`if [ \$? = 0 ]; then echo :\\\); else echo :\\\(; fi\` "
:) false :( true :)
~
~
~
This is an ex-parrot!
When in bash, I like this trick:
sudo apt-get -y install zsh; exec zsh
This is some e-lisp to do auto-completion (using dabbrev-expand). If after a semicolon at the end of a line or in the initial whitespace, TAB will indent as usual, otherwise it will auto-complete. C-TAB is mapped to always indent
(add-hook 'c-mode-common-hook 'autotab)
(add-hook 'perl-mode-hook 'autotab)
(add-hook 'cperl-mode-hook 'autotab)
(defun dabbrev-quick ()
(interactive)
(if (save-excursion
(if (not (looking-at "^")) (backward-char))
(while (and (looking-at "[ \t]") (not (looking-at "^"))) (backward-char))
(looking-at "^\\|;")) (indent-for-tab-command) (dabbrev-expand nil))
)
(defun autotab ()
(local-set-key [tab] 'dabbrev-quick)
(local-set-key [C-tab] 'indent-for-tab-command)
)
BSD is for people who love UNIX. Linux is for those who hate Microsoft.
I like emacs but I'm not ready to change over to it 100% yet.
Is there a way to dual boot between Vista and emacs?
M-x tetris
Yes, I am working, thank you very much.
there are 3 kinds of people:
* those who can count
* those who can't
;;
;; Functions to find the 'twin' of the currently-edited file. For instance,
;; executing my-c-find-twin [C-C C-f]] while editing a *.cc file will
;; bring up in a different buffer the *.h file that matches the '*'.
;;
(defun my-c-find-file-with-extension (base extensions default)
(if (null extensions)
(concat base "." default)
(let ((filename (concat base "." (car extensions))))
(if (file-exists-p filename)
filename
(my-c-find-file-with-extension base (cdr extensions) default)))))
(defun my-c-twin-file ()
""
(let ((extension (file-name-extension (buffer-file-name)))
(sans (file-name-sans-extension (buffer-file-name))))
(cond
((string-match "[hH]\\(pp\\)?" extension)
(cond
((string-equal "ObjC" mode-name)
(my-c-find-file-with-extension sans '("m" "mm") "mm"))
((string-equal "C++" mode-name)
(my-c-find-file-with-extension sans '("cc" "cpp" "C") "cc"))
(t
(my-c-find-file-with-extension sans '("m" "mm" "cc" "cpp"
"c" "C" "cp") "cc"))))
(t
(my-c-find-file-with-extension sans '("h" "hpp") "h")))))
(defun my-c-find-twin ()
""
(interactive)
(find-file (my-c-twin-file)))
(defun my-c-find-twin-other-window ()
""
(interactive)
(find-file-other-window (my-c-twin-file)))
(defun my-c-find-twin-other-frame ()
""
(interactive)
(find-file-other-frame (my-c-twin-file)))
(defun my-c-mode ()
(unless (boundp 'my-c-c-c-4-keymap)
(define-prefix-command 'my-c-c-c-4-keymap))
(local-set-key [(control c)(control f)] 'my-c-find-twin)
(local-set-key [(control c)(?4)] 'my-c-c-c-4-keymap)
(local-set-key [(control c)(?4)(?f)] 'my-c-find-twin-other-window)
(unless (boundp 'my-c-c-c-5-keymap)
(define-prefix-command 'my-c-c-c-5-keymap))
(local-set-key [(control c)(?5)] 'my-c-c-c-5-keymap)
(local-set-key [(control c)(?5)(?f)] 'my-c-find-twin-other-frame)
(show-paren-mode t))
My favorite extensions are GNUS, VM, pcl-cvs, and psvn.
My favorite extension that I do not actually use is AUC-TeX.
My favorite extension that I wrote is scroll-in-place.
The command that gets me the most mileage when people ask me how to do some crazy editing task is query-replace-regexp.
Best wishes ---
Eric.
After editing, one brief command, and the new equation is typeset and displayed.
You could just use fontenc and set up a good ~/.XCompose that lets you input most of the symbols you need.
There's no \mathbb{F} that I could find, and taller-than-one-line \Sigma{}s don't show up well in an xterm. But it works.
I asked my email-pal: "UNIX or Windoze?". He replied "UNIX". I said "Ah...me too!".
I asked my email-pal: "Linux or AIX?". He said "Linux, of course". I said "Me too".
I asked him: "Emacs or vi". He replied "Emacs". I said "Me too. Small world."
I asked him: "GNU Emacs or XEmacs?", and he said "GNU Emacs". I said "oh, me too."
I asked him "GNU Emacs 19 or GNU Emacs 20"? and he said "GNU Emacs 19". I said "oh, me too."
I asked him, "GNU Emacs 19.29 or GNU Emacs 19.34", and he replied "GNU Emacs 19.29". I said "DIE YOU OBSOLETE NOGOOD SOCIALLY MALADJUSTED CELIBATE COMMIE FASCIST DORK!", and never emailed him again.
From an old slashdot story
There are a lot of things that you can do with Emacs, but I find the two simplest to share would be related to trailing whitespace:
(when (>= emacs-major-version 21)
(setq-default show-trailing-whitespace t))
(add-hook 'write-file-hooks
'delete-trailing-whitespace)
These days more and more email I get is base64-encoded (usually for no good reason.) Since I'm the kind of caveman who still uses Rmail, I came up with this annoyance-avoider:
(defun rmail-base64-decode ()
"Decode a base64-encoded RMAIL message body or its base64-encoded MIME parts"
(interactive)
(set-buffer rmail-buffer)
(goto-char (point-min))
(while (search-forward-regexp "^[Cc]ontent-[Tt]ransfer-[Ee]ncoding: +base64"
(point-max) t)
(if (search-forward "\n\n")
(let ((inhibit-read-only t)
(base64-start (point)))
(if (search-forward-regexp "\\(^$\\|^-\\)")
(let ((base64-end (- (point) 1)))
(base64-decode-region base64-start base64-end))
)))))
Sorry, I forgot there are ads on the Web; I use Lynx.
What, you run a window manager at all??
There's also this Side-by-side quick-reference chart for (emacs/vi) users stuck with (vi/emacs).
For people who deal with a lot of DOS/UNIX end of line issues. With this command you can get rid of those pesky ^M's when editing files from another OS.
C-x RET f runs the command set-buffer-file-coding-system
which is an interactive compiled Lisp function in `international/mule'.
(set-buffer-file-coding-system CODING-SYSTEM &optional FORCE)
Set the file coding-system of the current buffer to CODING-SYSTEM.
This means that when you save the buffer, it will be converted
according to CODING-SYSTEM. For a list of possible values of CODING-SYSTEM,
use M-x list-coding-systems.
I don't know who decided this was a good idea, but if you run any sort of terminal in emacs ( M-x ansi-term or M-x shell or ...)
the terminal displays your passwords in plain text.
(add-hook 'comint-output-filter-functions
'comint-watch-for-password-prompt)
Will make Emacs hide it if you're typing in passwords. This is also useful for, say, SQL interpreters, which are much easier to use out of emacs than bash.
These set control-shift-v and c to paste and save from the gnome clipboard. (this is in line with gnome-terminal's hotkeys) When I'm alt-tabbing between Firefox and Emacs, this means I don't have to leave the keyboard to copy-paste.
(define-key global-map (kbd "C-S-v") 'clipboard-yank)
(define-key global-map (kbd "C-S-c") 'clipboard-kill-ring-save)
One of my favorite general-purpose commands is "M-|". It lets you run a shell command on a region. Usually, I'll select the whole buffer, then run it. It's useful for testing out scripts (M-| perl RET) or word count (M-| wc RET)
I started on punch cards, you insensitive clod!
One swallow does not a fellatrix make
;; Color parenthesis matching
(show-paren-mode t)
(setq show-paren-style 'parenthesis)
(setq blink-matching-paren-distance 51200)
;; Scrollbar on the right hand side
(set-scroll-bar-mode 'right)
;; Alt-G to jump to certain line number
(global-set-key "\M-g" 'goto-line)
;; Remove the annoying toolbar
(tool-bar-mode 0)
;; Turn off beeping
(setq visible-bell t)
;; No backup files to cleanup later
(setq make-backup-files nil
backup-inhibited t)
;; No more blinking cursor
(blink-cursor-mode nil)
;; Make pgup/dn behavior sane
(setq scroll-preserve-screen-position 1)
;; Highlight current line
(global-hl-line-mode 1)
;; No more annoying startup message
(setq inhibit-startup-message t)
One thing that I use alot is Elscreen (http://www.morishima.net/~naoto/software/elscreen/index.php.en), which basically extends the regular window/buffer functions and adds different "tabs", just like GNU screen does for the shell.
This allows me to have my editing session in one tab, my IRC session on another and my GNUS state in yet another, each screen with his own frame arrangement.
The Emacs Wiki site is probably the best site to find out similar packages and useful tricks (http://www.emacswiki.org/). The sheer breadth of what Emacs provides makes the "vi" comments redundant.
Being able to write a macro in emacs is unbelievably powerful. I use these for a million purposes, every day.
C-x ( to start defining a macro ...now you have a handy macro to capitalize the last word of a line.
C-e M-b M-u C-n
C-x ) to end definition
C-x e run the macro once
C-u C-x e run the macro four times
C-u C-u C-u C-u C-x e run the macro 256 times
By using other powerful tools like regexp search in a macro, you can do almost anything. You can bind the new macro to a key, but it's so easy to define a new one (once it seeps into the subconscious) that I never bother.
[M]/ Will attempt to complete the current word. This is done working backwards from the edit point and can look in other buffers.
If (for example) you are editing a LaTeX document and you wish to cross reference an existing figure with label \label{f:my-figure} entering the following:
\ref{f:[M]/ will repeatedly try to match everything starting with f: , namely all the existing figure labels.
Likewise if referencing a citation in a BibTeX file that is open in another buffer, \cite{startofkey[M]/ works a treat!
Incremental search is also wonderful. When correcting text from (say) a hard-copy simply do [M]S and start typing the first few words of the sentence before the edit point. Magically Emacs will take you there.
This is also very useful for moving around in documents. Simply enter "??" or some other simple placemarker move around, then do [M]S?? and you'll fly back to where you were.
For formatting "paragraphs" [M]Q is the way forward. Quite simply no other editor I have come across has a better understanding of the 'right' behaviour for this.
If you have some text that looks like this (n.b. _ indicates space)
____Some text that is on a line that we wish to wrap around so that the new line starts aligned to the first line. Ordinarily there is no sensible way of doing this bar tab stops, however if you 'do a meta q' it will magically align this paragraph.
Then after a [M]q (fill-paragraph) you will get
____Some text that is on a line that we wish to wrap around so that
____the new line starts aligned to the first line. Ordinarilly there
____is no sensible way of doing this bar tab stops, however if you 'do
____a meta q' it will magically align this paragraph.
So that the paragraph is left aligned to the first line. Finally, as others have said regexp replace and various other packages (e.g. AucTeX) are unparalleled!
Be nice to people on the way up. You will meet them again on your way down!
;; URL shortener especially useful with the It's All Text mozilla addon
(defun wb/web-urlp (string)
"Is STRING a web browsable sort of URL?"
(let ((type (aref (url-generic-parse-url string) 1)))
(cond ((eq type nil) nil)
((string= type "http") t)
((string= type "https") t)
((string= type "ftp") t)
(t nil))))
(require 'mm-url)
(defun wb/shorten-url ()
"Replace the URL around point with an equivalent shortened one.
The short URL is provided by metamark (URL `http://metamark.net')"
(interactive)
(catch 'not-web-url
(let* ((bounds (bounds-of-thing-at-point 'url))
(longurl (buffer-substring (car bounds)
(cdr bounds)))
(url (if (wb/web-urlp longurl)
(concat "http://metamark.net/api/rest/simple?"
(mm-url-encode-www-form-urlencoded
(list (cons "long_url" longurl))))
(throw 'not-web-url (message "Not a web URL"))))
(short-url
(save-excursion
(with-temp-buffer
(mm-url-insert url)
(let* ((bounds (bounds-of-thing-at-point 'url))
(metamark-url (buffer-substring (car bounds)
(cdr bounds))))
(unless (wb/web-urlp metamark-url)
(throw 'not-web-url
(message (car (split-string
(buffer-string) "[\r\n]+")))))
(kill-ring-save (car bounds) (cdr bounds))
metamark-url)))))
(if (or buffer-read-only
(text-property-any (car bounds)
(cdr bounds)
'read-only t))
(message "Yankable shortened URL: %s" short-url)
(kill-region (car bounds) (cdr bounds))
(insert short-url)
(message "Yank to recover the original URL")))))
One thing I'd like to know how to do is to stop emacs from ever loading an X window.
I do a lot of work over ssh and sometimes need X-forwarding to be on. Unfortunately this means by default that emacs will load in an X window taking easily 30 seconds longer to load. I know the command emacs-nox but that's a bitch to type especially when you're in the habit of typing emacs. I do not have any root access to the machines being used so I can't install just emacs-nox.
So, does anyone know of any script or setting I can change for my account only that would prevent this?
Who need's speling and grammar?
Working with rectangular regions is a breeze in emacs (very useful for quickly swapping columns in csv-type files):
Set the mark at the upper left of the rectangle... move the cursor the lower right...
Kill rectangle: c-x r k
Move somewhere else...
Yank rectangle: c-x r y
There are some other rectangle commands, but these are probably the two most useful "unknown" emacs commands I've come across.
-Chris
Except for:
1. constantly moving in and out of command mode
2. reaching for ESC
3. wtf is with the movement keys being shifted one off from the home position for the right hand?
vi seems to be optimized for hunt and peck typers.
Complaining that your pinky buckles under heavy emacs use may be a more valid, but saying that vi is more efficient on typing is only true if you can't really type.
t
Take the shovel.
Eat the shovel.
From the resume:
>> Since the Vi version of this question was both interesting and popular, let's hear from the other end of the spectrum
A bit suspicious, but is there any reason the VIM story ran first than the Emacs one? (and the Emacs' smells like a sort of concession) ... Taco's preferences lurking? It would be interesting to see if the ./ crowd has a marked statistical preference for one of the editors independently of the (religious) reasons; I'd speculate that Vim is a lot more used because its ubiquity in almost every Linux fresh installation.
This is a simple example of something that I've occasionally found really helpful. Split the frame into two windows and create two new buffers. In one buffer type numbers*, eg:
0
1
2
In the other window write some skeletal code, eg:
x[] =
And copy that line twice, eg:
x[] =
x[] =
x[] =
Move the cursor so it's over the x in the first line. Now switch back to the numbers buffer and put the cursor on the first number. Now type C-x ( to start defining a keyboard macro. Type C-space to set the mark, C-e to move to the end of the line, M-w to copy the region, C-a to move to the beginning of the line and C-n to move to the next line. Now type C-x o to move to the other window. Type C-f twice to move the cursor to be over the ] of the first line, then C-y, then C-e, then type space and C-y. Then type C-a and C-n then C-x o . Now type C-x ) and then C-u 2 C-x e.
* These numbers can be auto generated, for when there are many of them, see, eg calc-mode (oh that's a another excellent feature that seems to be underused).
* gnus. The _best_ email reader.
* remember, along with org make your life simpler
* flyspell, for those times my fingers misbehave
* auc-tex mode for writing latex
* w3 for those times you have to cut and past nicely formatted web pages into a buffer
* org-mode again, for table editing
* calc, for a very powerful calculator
* tetris to kill time
* dired mode for browsing directories and acting upon files
* edit-env for modifying environment variables in the running process (and future children)
* mpg123 to play your mp3 collection
* igrep: very nice grep, better than default one.
* yasb: switch buffers via regular expression.
Some nice tricks:
* make-frame-on-display. Start a window of a running process in another Xserver (including a remote one)
* emacs-client -n. Load file in running emacs (in server mode) without waiting
* Being able to run emacs in a Nokia N810! With remember and org this is a killer application.
--dmg
Whenever you download a bunch of code and want to dip your feet in it, it helps getting a good overview.
To that end, ecb-mode can be greatly helpful. It displays navigable directory trees, a list of all symbols defined in your current file, a list of recently visited files, and a compile window. Double-click anything to jump to it, quite nice to use. The symbol list is really neat; I've thrown C, python and makefiles at it, much to my satisfaction. Haskell support is a bit rudimentary, but still very useful. It says it handles perl and TeX specially [they can't be parsed without being partially executed]. I don't know how well.
If you just want to follow symbols around, use etags [use it anyways]. Run etags in your source root (zsh% etags **/*.[ch]), cursor-over a symbol, press M-. to jump to it.
Reposting Logged in....
I tried emacs for about a month, trying to give it an honest shot. I actually quite liked it for editing latex docs. The problem was, there was some key combination I was hitting on accident (probably since I am used to nano keybindings) that was causing me to delete large chunks of my document (usually everything above my current view). I didn't realize it, then I would save and have to restore the file from backup. This happened several times. I think it was happening as I was saving, but could never trace back my error.
Second, although I've read Understanding GNU Emacs and Tabs [northpark.edu] I still couldn't get tabs to just be tabs, especially when using ruby-mode, which apparently sets it's own tab behavior and overwrote my own.
Any ideas? I'd like to give it another shot someday...
The snow doesn't give a soft white damn whom it touches. -- ee cummings
Yeah, given that the *nix thread had over 2000 comments, I'd say there's a significant demand for more of these sorts of posts.
My only regret is that I wish they'd spaced out the articles a bit, so that I had some time to digest the tricks in one article before reading the next one -- I find that if I add too many tricks to my toolbox at once I tend to forget about some of them. I guess I should just re-read the articles in another month or so. (Also an indication that these are quality articles -- there's not many discussion threads on Slashdot that I'd even consider going back and re-reading later.)
It would be tragic to think that bad habits from 20 years ago would be inflicted on a new generation.
The tragic thing is that the new generation are still using 20-year-old ideas for operating systems, databases, text editors and the like, because nothing that's coming along since has managed to do much better.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
I know just enough vi to build emacs (back in the olden days, there were machines that didn't come with emacs).
I've looked at vim before, but emacs has a lot of features I wouldn't want to live without. Not to mention that I've spent 20 years learning it. :-)
I still recall my first session of vi. It was on a 3B2, and I had to unplug the box to exit vi, as there was no documentation available...
I might have converted at some point if the "arrow keys" were on j-k-l-; instead of h-j-k-l. Who thought that would be a good idea?
"Not an actor, but he plays one on TV."
If you are editing html you can insert a link with C-c C-c h and an image with C-c C-c h. If you want to open your html in a browser you can do C-c C-v. When editing perl use cperl-mode for "canonical" syntax and indentation.
ediff/emerge is really pretty slick, once you figure out how to use it.
C-x h M-C-\ reindents the whole buffer according to whatever the mode thinks is proper formatting (i.e., for C, Python, etc.) You have to be a little brave. (And of course you never want to reindent an external project's code before sending back patches)
grep-find is handy.
You can use tags-query-replace to do a multi-file find-and-replace. Just create a TAGS file first (with etags) that contains the files you want to modify.
Incremental regexp search (M-C-r) is nice.
In principal you can open up buffer windows on multiple displays, which would mean that you and your five buddies could all be typing into the same emacs simultaneously. I've never actually used this, though.
You can copy virtually any text anywhere (not sure about the GUI and modeline). I'm always shocked at GUI editors that won't let me copy their messages with anything short of a screenshot. Useless.
Continuous development and improvement over decades by some of the better programmers in the world, and little reason to believe this will ever cease. I wonder how many other pieces of software exist that this is true for. Not very many.
"Not an actor, but he plays one on TV."
I'm a heavy user of GNU Screen - I'm constantly on and off around 20 machines so persistent terminals are a major time saver.
Right now, you can start emacs with the "-nw" flag or you can unset the DISPLAY environment variable to force terminal mode. There is a space between DISPLAY= and the emacs command!
env DISPLAY= emacs
This is convenient in GNU Screen because I can connect right into an existing Emacs session.
Now there are times when I would prefer to forward a display from Emacs over X. With GNU Emacs 22 you can have frames on multiple displays but not ttys and X at the same time. That should change with GNU Emacs 23 - it should be possible to stick an Emacs-terminal process inside a Screen session and ask for frames to opened on a remote display from that Emacs process.
Cheers,
Toby Haynes
Anything I post is strictly my own thoughts and doesn't necessarily have anything to do with the opinions of IBM.
On starting emacs, I was presented with:
"Get help C-h (Hold down CTRL and press h)"
This sequence acts as a backspace key and has no effect on emacs itself other than to delete the random sentences it seems to have filled its default buffer with. Neat trick!
It also seems to have a friendly menu at the top which cannot be reached by any key combination. Minimal browsing on the web suggests that emacs is actually a moded editor, but the normal mode only lasts one command before you need to press an obscure sequence to get back to it. Oops?
-- 'The' Lord and Master Bitman On High, Master Of All
I agree. I really enjoy reading through these, although I probably won't read through this entire thread, since I'm a vim user :)
I have a suggestion/proposal, though: I find these threads really interesting, but they hardly qualify as news and I don't think we want to see them every day. Why not do something like this on Fridays instead of the mailbag? I think many people would prefer that.
I remember when legal used to mean lawful, now it means some kind of loophole. - Leo Kessler
c-x stop
c-x bark
Rethinking email
C234567
Doesn't work for me either. Maybe because I got tired of accidentally hitting C-x C-c and added this to my .xemacs/init.el:
(defun kill-emacs-did-you-really-mean-that ()
(if (yes-or-no-p "Really really really quit Emacs?")
t
nil))
(setq kill-emacs-query-functions (list 'kill-emacs-did-you-really-mean-that))
Hmm.. that didn't work well for me. I tried it, but I ended up in an editor with functionality that was one step above punch cards.
ROFL!
The following functions will save the current location to a register when going to the beginning of the file or end of file with M-. You can then go back to the last place you were with C-x r j 1 ;;; a trick from ispell... ;;; Let ?1 do the right thing when compiled. ;;; ;;; misc. advice stuff
(defun lrd-int-char (char)
(cond
((and (fboundp 'characterp) (characterp char)) char)
((and (fboundp 'int-char) (integerp char)) (int-char char))
((integerp char) char)
(t (error "arg is not an int or a character"))))
(defadvice beginning-of-buffer
(before bob-register first () activate)
"When going to beginning of buffer, save point in register 1"
(point-to-register (lrd-int-char ?1)))
(defadvice end-of-buffer
(before eob-register first () activate)
"When going to end of buffer, save point in register 1"
(point-to-register (lrd-int-char ?1)))
For a while I used emacs as my mail client and news reader. This far I haven't not found another mail client that can match the functionality provided by vm plus the MIT Remembrance Agent. Unfortunately it's something of a pain in the ass to set it all up and I don't get enough non-spam email outside of work to bother with it.
I'm trying to teach myself to set people on fire with my mind... Is it hot in here?
You're really trying my patience, Slashdot.
Do you want me to turn Ad Block back on and go back into lurk mode?
I didn't think so. Straighten up and fly right or you won't get anything useful from me.
By far one of the best enhancement packages to come out for (X)Emacs in a long time is org-mode. It's a feature-full organization and agenda system that all operates on plain text files that are easy to read and write.
The next site to slashdot will be ready soon, but subscribers can beat the rush and start slashdotting it early!
Slashdot posted a story about useful vi tips, realized that it sucked and wrote a story about Emacs: new and better.
(yeah yeah yeah... slashdot doesn't write stories and just approves them; I know...)
The next site to slashdot will be ready soon, but subscribers can beat the rush and start slashdotting it early!
How to prevent long lines from wrapping: (setq truncate-lines t)
How to make Emacs do things when it starts: (add-to-list 'command-line-functions 'my-startup-stuff)
How to input a character for which you have the Unicode hex value: use the ucs input method.
speedbar mode
When you comment out a big chunk of code with M-;, you want to be able to un-comment it. And if that big chunk of code had comments in it, you don't want the comments to be uncommented ;-) You can comment a chunk containing a chunk, and the boundary between the regions still shows.
This even happens in a recursive-friendly way - If I M-x it again (adding some not-yet-commented thing - Remember it's a DWIM, so it attempts to achieve intelligence, and there is nothing as stupd as artificial intelligence), it works correctly (/. "junk character" filter won't allow me to post it - but it adds a level of backslashes). Comments get nicely nested. And de-commentable, step by step.
M-x iso-accents-mode.
This is the easiest way I know to type accented characters on a US keyboard. The version of emacs that gets installed by default on recent Ubuntu versions does not have support for this, but I found that switching to a minor revision older (through synaptic) brings it back.
Useful(Stupid) things to say to get modded Insightful
Useful(Stupid) things to say to get modded Interesting
Useful(Stupid) things to say to get modded Funny
Useful(Stupid) things to say to get modded Troll
Useful(Stupid) things to say to get modded Redundant
Useful(Stupid) things to say to get modded Flamebate
Useful(Stupid) things to say to get modded Overrated
Useful(Stupid) things to say to get modded Stupid
Useful(Stupid) things to say to get modded Useful
The next site to slashdot will be ready soon, but subscribers can beat the rush and start slashdotting it early!
M-x hanoi
Or, for added drama:
M-8 M-x hanoi
Consider it a benchmark.
Error: NSE - No Signature Error
Much goodness has been mentioned here, but not the optional emacs-calc package (does vi do calculus? I think not). Plus picture-mode, great for drawing little boxes and, surprise surprise, putting the row of backslashes down the right edge of newly macrofied code blocks (M-x picture-mode C-c ., set typing direction to vertically downwards).
I use emacs and eclipse everyday. Strangely enough, the thing I miss in Eclipse is zap-to-char. Meta-Z then a character allows you to delete everything up to and including the next occurrence of that character in the file. Great for eating an entire string (zap "), xml tag (zap >), code block (zap }) etc.
ant to book mark a spot in a buffer/file?
C-x r C-SPACE a
Will store the current place holder in register a.
Move around the file, and to jump back just run
C-x r j a
Want to keep a cut and paste?
High light an area and
C-x r s a
Will save the contents of what was high lighted to register a.
To paste it just
C-x r i a
My favorite. Saving frame/buffer layout.
Spent a lot of time arranging your frames and buffers in each and want to move back and forth?
C-x r w a
Will save frame layout in register a.
Go full screen on a single buffer and to return just
C-x r j a
Presto you can jump between multiple layouts.
I find the cscope interface most useful: http://cscope.sourceforge.net/
cscope is good if you get a ton of code that you know nothing about dumped on you. You can quickly jump around files by setting the cursor on a symbol, and it will also tell you stuff like "find functions calling a function."
This also has the advantage of being religion-neutral: cscope also works with vi.
P.S. Sorry to interrupt the flame wars with some potentially useful information.
Schroedinger's Brexit: The UK is both in and out of the EU at the same time!
There's always the classic:
Of course, on the system *I* administrate, vi is symlinked to ed. Emacs has been replaced by a shell script which 1) Generates a syslog message at level LOG_EMERG; 2) reduces the user's disk quota by 100K; and 3) RUNS ED!!!!!!
Source
How dare you be so modest!! You conceited bastard!!
Tapping M-/ completes the word, great when coding and typing variables names, it'll search buffers for matching words. Saves on annoying typos. Repeatedly tapping M-/ cycles matches.
gets you into this wicked adventure. I've collected all the good items, but I've yet to defeat the bad guy at the end of the subnet.
"It doesn't cost enough, and it makes too much sense."
M-x query-replace
using this, and holding down the y key after supplying the necessary parameters, I can blast through a long HTML file deleting thousands of redundant tags that were created by Dreamweaver or Frontpage or some crap.
'... is there any reason the VIM story ran first than the Emacs one?'
Emacs was still loading when it came time to run the story.
Great minds think alike; fools seldom differ.
M-x artist-mode
Case-insensitive subword buffer switching.
Is there an EMACS equivalent of vi's "."? A repeat-last-command sort of deal?
These recent discussion-based articles are great additions to Slashdot. The UNIX/vi/emacs articles bring out Slashdot's aged sages and core demographic, and those of us who are new to the UNIX scene can learn plenty more from the discussion than a 'man' page.
The political discussion articles were, IMHO, great additions to the site, too. Thanks to the brilliance of the moderation system and the myriad views of readers, I could read and participate in intelligent discussions about all 3-4 sides of very important issues and become a more intelligent voter.
So keep the discussion articles coming, Slashdot! You're tapping into your greatest strengths: your readers and your forum/moderation software.
>> Standing on head makes smile of frown, but rest of face also upside down.
Plus for maximum fun, thinking you're in insert mode because you slipped and hit the wrong key, and actually finding you're in command mode and have just made about 452 different random changes to your document with no idea of what has happened or how to fix it...
You are not alone. This is not normal. None of this is normal.
GNUS, CALC, electric-buffer-list, copy or delete rectangle, macros, narrow-to-region, desktop-save, slime
Ctrl-Z kill %1
I personally just wanted to steal other people's emacs tricks, and didn't think of it until the vi question came up and I read the responses to that. Just as I imagine that the vi question came up in response to the Unix one.
Sometimes there's no conspiracy except the conspiracy of coincidence.
that grep macro is nice but if you're a programmer (and the constant need to grep through whole directories from within emacs suggests that you are), then you should really look at etags or cscope modes. etags mode comes built in to emacs (but you need to have etags program installed on the machine to generate the index).
cscope mode AFAIK, doesn't come built in yet. Search for the file xcscope.el on google. And yes, you need to have the cscope program installed on your machine for building the index.
I use the following two aliases to build the cscope and tags databases at the root of any new source tree I need to work in.
alias scopeit='find . \( -iname "*.[ch]" -or -iname "*.rpc" \) -print |tee cscope.files |cscope -k -u -q -b -i - '
alias tagit='find . \( -iname "*.[ch]" -or -iname "*.rpc" -or -iname "*.java" \) -print | etags - '
Now assuming you have cscope and/or tags modes available and loaded, you'd be able to do things that you use your grep macro for but in a much more productive manner. e.g.
(etags)
M-. takes you to the definition of that symbol (function/variable etc.) anywhere in the source tree you indexed
M-s searches for takes you to the first occurence of that symbol anywhere in your source tree and the repeated M-, iterates through all occurences of that symbol.
(cscope)
cscope-find-global-definition
cscope-find-functions-calling-this-function
.
.
etc etc... loads of things.
I should mention cscope works well for C and to some extent for C++. etags works for a wider variety of languages (but your indexing has to include those files of course).
Real men use emacs.
When I was learning Chinese I wrote a translation function, which would take the characters at point, look them up in a dictionary (which gets loaded into its own buffer) (the dictionary I used is cedict, available on the internets somewhere), and then display the translation in the minibuffer.
This combined with an Emacs irc client, and an irc server located in China or Taiwan, was a great way to help out learning the language. And I don't think any of this could have been done in vi...
What are your favorite tricks?
Why do you say what are my favorite tricks?
Have gnu, will travel.
I use cvs, and frequently have several files in emacs buffers when I do a commit. CVS modifies the buffers to put new time-stamps in them, and it used to be, every time I edit a buffer, I get one of these "File modified on disk, really edit? Revert?" things.
So, I wrote my own "revert-all-buffers" command.
Mangled to get through the Slashdot lameness filter.
(defun revert-all-buffers () (interactive) (let ((bufcount 0)) (save-current-buffer
(mapc (lambda (buf) (if (buffer-file-name buf)
(if (verify-visited-file-modtime buf) nil
(progn (set-buffer buf) (revert-buffer t t) (setq bufcount (1+ bufcount))
)) nil )) (buffer-list) ) )
(message "Buffers reverted: %d" bufcount)))
2*3*3*3*3*11*251
Towers of Hanoi is a distant second-place.
I don't care for the ~ extension for backup filenames. I grew up with Gosling Emacs, which uses .bak instead. So now my .emacs has
... CUA-mode with the kiddy keybindings disabled.
icicles is one of the systems that superpower tab completion, and CUA-mode gives your rectangle selections superpowers. I can't live with its "windowsy" C-x / C-c / C-v bindings, but those are easily disabled.
Why, oh why, do you deny us of something which would bring such pleasure to so many people?
Like a Leafs/Habs, Yankees/Dodgers, Celtics/Lakers final, everyone wants to be a part of the ultimate showdown at least once in their life.
M-x spook
Append it to the bottom of all your emails ;)
This isn't one that I use every day, but I find it enormously handy when I do need it:
(defun for-each (begin end place start stop step)
"Copy the active region and replace a placeholder string with a number."
(interactive "r\nsPlaceholder: \nn Start: \nn Stop: \nn Step: ")
(let ((template (buffer-substring begin end))
(count (1+ (/ (- stop start) step))))
(delete-region begin end)
(dotimes (time count)
(let ((value (number-to-string (+ start (* time step))))
(expansion template))
(while (string-match place expansion)
(setq expansion (replace-match value nil t expansion)))
(insert expansion)))))
Select a region, do M-x for-each and then give it a placeholder in the region, starting and stopping numbers and an increment. For example, selecting a region with:
"% bottles of beer on the wall.
% bottles of beer on the wall, % bottles of beer.
Take one down, pass it around, "
and giving it % as the placeholder, 99 as the start value, 1 as the end value, and -1 as the increment will instantly expand it to most of the body of the old song:
"99 bottles of beer on the wall. ..."
99 bottles of beer on the wall, 99 bottles of beer.
Take one down, pass it around, 98 bottles of beer on the wall.
98 bottles of beer on the wall, 98 bottles of beer.
Take one down, pass it around, 97 bottles of beer on the wall.
97 bottles of beer on the wall, 97 bottles of beer.
Take one down, pass it around, 96 bottles of beer on the wall.
You can use multiple placeholders and apply it N times in succession to do N-dimensional expansions as well. I suspect that it has often saved me from what very likely could have been some nasty cut-and-paste errors.
My favorite new-to-me trick by the way, is \, for Elisp code in regexp replacements, as described by Steve Yegge. I've only known about it for a few weeks now and I've already found a ton of handy uses: selectively deleting numbers from a list, converting hh:mm:ss to seconds, etc.
So by the next week we may the OpenOffice tricks?
Agreed. It reminds me of this thread from 2005 where, among other things, I and a few others collaborated to create a one-line script to answer the question "Which commands do I use the most?"This...
... will show you the twenty commands you use the most. I wanted to post this in the first thread of this series but I didn't have time. Luckily there have been these related threads--the next best thing to a dupe! :-)
Dear Slashdot: next time you want to mess with the site, add a rich-text editor for comments.
Plus you can compile over ssh.
It's nice to be able to compile a local directory with M-x compile, then you can jump to errors in the offending file from the *compilation* window.
You can also set to do remote compile from emacs by putting something similar to this in your .emacs:
No you can compile on the remote host AND bring up offending files from the compile output window with the click of a button.
People have already mentioned M-x psychoanalyze-pinhead, but then have you also considered piping the output through M-x dispress?
This sig no verb.
Once you learn to use align-regex, you will look for ways to abuse it, and your code will look all the better for it.
Oh yeah, about what it does: it aligns columns in multiple lines, the regular expression tells it what the column delimiter is.
Enjoy.
BTW, this is my first ever slashdot.org reply..
I just hold down all the modifier keys within reach and roll my forehead across the keyboard, and something cool happens.
Once it wrote a web browser for me.
Once it summoned a powerful djinn with lots of dark chocolate.
Once it washed and waxed my car.
The other day it *almost* decided the US presidential election, but I ran out of swap space so that got decided the old way.
Thanks to X, Emacs has built-in collaborative editing.
You can do this over ssh (X forwarding) to open a frame on someone else's computer (or several other's computers). They get their own cursor and everything, and, if you are looking in the same buffer, you can actively see the other person/people typing away. Just don't C-x C-c or you close it for everyone!
Security note: watch out, because whoever you give a frame to can trivially get shell access in your account.
A useful addition to Gnus (it may be part of the distribution now):
;;
;; remember if we saw *Group*
;; Provide a function to switch to a *Summary buffer or the *Group buffer.
;; Let the user decide whether to bind it. Written by Randell Jesup.
;;
(defun switch-to-gnus ()
"Switch to a *Summary whatever* buffer if one exists. If none exist,
switch to the *Group* buffer. If that doesn't exist, complain."
(interactive)
(let ((buflist (buffer-list))
(done 0)
(saw_group 0))
(while (and (= done 0)
(not (equal buflist nil)))
(let ((candidate (car buflist)))
(let ((candname (prin1-to-string candidate)))
(if (string-match "#<buffer +\\*Summary.*\\*>" candname)
(progn
(switch-to-buffer candidate)
(setq done 1))
(setq buflist (cdr buflist)))
(if (string-equal "#<buffer *Group*>" candname)
(progn
(setq saw_group 1))))))
(if (= done 0)
(if (= saw_group 1)
(switch-to-buffer "*Group*")
(error "Gnus doesn't appear to be running")))))
;; This switches to the a *Summary buffer if one exists, else to *Group*
(global-set-key [f9] 'switch-to-gnus)
A couple of other goodies:
;; If invoked from a non-shell buffer, it changes to or opens a shell
;; buffer with the path set to that of the buffer from which this command
;; was invoked. If invoked from a shell-mode buffer, it changes back to
;; the last buffer from which the shell was invoked whith this command.
(global-set-key [f3] 'shell-pushd-to-buffer-path)
;; make switching buffers easy
(global-set-key [f6] 'other-window)
(defun prev-window ()
"previous window"
(interactive)
(other-window -1))
(global-set-key [S-f6] 'prev-window)
;; Windows-ish commands:
;; Block cut, copy, paste:
;;; KEY: [A-x]: Cut region.
(global-set-key [?\A-x] 'kill-region)
;;; KEY: [A-c]: Copy region.
(global-set-key [?\A-c] 'copy-region-as-kill)
;;; KEY: [A-v]: Paste.
(global-set-key [?\A-v] 'yank)
;;; KEY: [ESC A-v]: If you've just used paste, use this key to cycle through
;;; KEY: previous available pastes on the Emacs clipboard.
(define-key esc-map [?\A-v] 'yank-pop)
I never had to write my own elisp function before, but just yesterday I did. I have been using both emacs and vi for years, and in vi I often used "J" to join the current line with the next while reducing whitespace between them to one space. Emacs has the (join-line &optional arg) function to do the same thing, but by default it works in the opposite direction; joining the current line with the previous. The optional arg, of any non-nil value, joins current with next like vi's "J".
join-line is not bound to any key by default, so I bound it to "C-x j" which was unbound. However neither local-set-key or global-set-key would let me pass a non-nil argument to the function I'm binding the key to. So, I typed the following in the *scratch* buffer:
(defun join-next-line ()
__(interactive)
__(join-line 1))
(global-set-key "\C-x j" 'join-next-line)
Eval'd both, and badda-boom, badda-bing, it works. Copied it to my .emacs, and now I'm shittin' in tall cotton.
"_" in the code represent spaces thanks to /.'s braindead comment entry system.
It's a very dark ride.
What I find tragic is that people actually do say "it's tragic that we're still using the same tools as we used 20 years ago".
Why wouldn't we be? We're pretty much the same people as we were 20 years ago. We still speak the same languages, wear the same clothes, drive vehicles that are only cosmetically different, perform very similar jobs. Sure, our computers are a bit faster, but there's no need to fundamentally change your interface just because there are more transistors behind it.
Suppose I pull up a buffer, like /etc/hosts, and I decide that I want to change it. I currently have to restart emacs as root. I would much prefer a "M-x su" option to become root (or some other user) for just that one buffer.
I know that with the tramp extension, I can do this with an ssh connection to localhost; thanks to those who pointed that out!
Your unmoderated Score 1 comment needs to be expanded; the new Javascript-powered Slashcode puts adverts (mostly ThinkGeek) under the posts it hides. Riddle me this: as a subscriber, I could turn off the adverts, and also could use AdBlock to immunise myself elsewhere, but I don't -- am I really having an impact on the clickthrough rate by seeing but not clicking any ads?
That didn't work for me:
-bash: apt-get: command not found
By the way, it figures that a vi user wouldn't know how to put commands on separate lines. :)
There is more than vi, emacs and ed. The most likely editor that is installed as well is nano.
No discussion of obscure and strange Emacs features is complete without meta-X psychoanalize-pinhead.
See, Emacs has a command to produce a random "Zippy the Pinhead" quote.
And, Emacs has a command to start up the "Eliza" program, which pretends to do psychological analysis based on what you type into it.
So someone wrote some glue code to fire up the Eliza program and feed the Zippy quotes into it, and you access that via meta-X psychoanalize-pinhead. Go ahead and try it out! It's enabled in the version of Emacs bundled with MacOS X, I just checked.
I agree, Don't Stop these articles.
Maybe these "(Stupid) useful $RANDOM tricks" would make at least 1 decent article for idle.slashdot.org?
i.e. its not exactly front page news as such but it is definitely interesting to read and it is news for nerds/stuff that matters.
When people ask if I'm an optimist, I say "I hope so". --Bill Bailey
It's easier to just write:
(defun kill-emacs-did-you-really-mean-that ()
(yes-or-no-p "Really really really quit Emacs?"))
(setq kill-emacs-query-functions '(kill-emacs-did-you-really-mean-that))
Modded Flamebait for suggesting one editor is (maybe) more used than the other... I didn't suspect those old religious sentiments are so alive hitherto.
I'm not sure what it means, but it sure is interesting. // I must do a lot of leaving // I ssh in a lot and *always* check the mail. // what package was that? // I'm in the wrong place // I don't know how to get where I'm going // I'm not who I claim to be // I can't find something // tunes baby! // d // is more //always on, why bother to restart it? // dog // reading Real World Haskell // is teh r0X0r! // sometimes I need to go other places // st! I've got a secret! // borked something again -- force-all // and feather // Dave's alright // does this count for backups?
98 exit
60 mutt
28 apt-cache
26 cd
20 man
19 sudo
19 grep
17 mpc
17 ls
13 less
12 emacs
12 cat
10 runhaskell
10 dtach
9 ssh
8 ps
7 dpkg
5 tar
5 darcs
5 cp
That was fun and insightful for me. Thanks.
oh, and if I ignore the `exit`s, I get // config files require vim. Don't know why, they just do.
4 vim
man, I feel like mold.
I'm not an Emacs user, however I have lately tried to use it a little and become more comfortable with it. One thing I think is really cool is being able to do M-x make-frame-on-display and then have a new frame appearing on a display (obviously). This is pretty useful for collaborative editing more than anything. I wish such a feature existed in Vi/Vim :(
;; hidden backup files - i hate seeing them in listings...
;; prefix with a dot as well as postfix with a tilde
(defun custom-make-backup-file-name ( file )
(let ((d (file-name-directory file))
(f (file-name-nondirectory file)))
(expand-file-name (concat "." f "~") d)))
(setq make-backup-file-name-function 'custom-make-backup-file-name)
(defun backup-file-name-p ( file )
(string-match "\\`\\..+~\\'" (file-name-nondirectory file)))
(defun file-name-sans-versions ( file &optional keep-backups )
(if (or keep-backups (not (backup-file-name-p file)))
file
(let ((d (file-name-directory file))
(f (file-name-nondirectory file)))
(expand-file-name (substring f 1 -1) d))))
I'm not sure if it will be released in Emacs 23, but there is a branch of CVS Emacs that supports lexical binding. And my `cl-macs.el' in Emacs 22 has `loop'...
For text adventures you must always RTFH!
The preferred way to run dunnet is from the command line:
emacs -batch -l dunnet
I didn't really write it with curses mode in mind (although it is somewhat usable).
#Ron (Dunnet author) :-)
You all accidentally verbs so much! it!
You most likely used apt-cache for apt-cache search and apt-cache show, to search through the package list and show details about a package, respectively.
Hey, any chance you can point to a good etags tutorial? I've been interested in using it, but there seems to be a medium-steep learning curve, and the documentation seems somewhat lacking.
But, in many respects, software today is in a different world to 20 years ago. Programming languages have moved on immensely, both in theory and in practice. Usability of end user software has improved greatly in many respects. The Internet was barely a dream at that time.
Plenty of scope for improvement has been identified in the old-style text editors, OS models and DB theory as well, but for some reason possibly connected with a small number of very large software businesses, the world seems stuck in a time warp in these areas.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
Here's a hack I use regularly to step through the files in a directory:
(defun dired-next-file ()
"Kill the current buffer, advance to next line in dired, get that file.
Requires that 'other buffer' be a dired."
(interactive)
(when (eq (cdr (assoc 'major-mode (buffer-local-variables (other-buffer))))
'dired-mode)
(kill-buffer (current-buffer))
(dired-next-line 1)
(dired-find-file)))
(global-set-key "\C-cf" 'dired-next-file)
I want to dispel some myths that are recurring here. I make reference to vi, vim and Eclipse to help explain.
First of: To answer the question:
A great command is M-Q. This is a minimal requirement for any good text editor IMPO.
My recommended .emacs settings are the first things I turn off in emacs:
(custom-set-variables
'(make-backup-files nil)
'(inhibit-splash-screen t))
Emacs is a pig?
There is some talk about Emacs being a heavy text editor and that installs lots of stuff when you install it. In response to that: .Xresources settings)
- For the Windows binary (http://ftp.gnu.org/gnu/emacs/windows/emacs-22.3-bin-i386.zip) is 37MB. There is no installation required, you just extract the zip and run the 'runemacs.exe' command in the bin directory.
- If you want to build Emacs on FreeBSD (for example) you will have to install all of it's build and runtime dependencies. That's a lot of stuff. It will want gnu build tools and X etc. If you pkg_add -r emacs to get the binary, you are not going to have to install as much. The point is: Depending on your OS and package manager you may have a different experience installing Emacs. In the case of Windows it's super easy. Not using Emacs because installing it is difficult just isn't a reality. (sure there are edge cases)
- Emacs 22.3(latest) runs at about 20 or 25 MB resident memory in the latest Ubuntu(ubuntu8041) package and FreeBSD(7.0-R) port. To get a perspective, this is about as much as gnome-terminal. If you don't know if you are using gnome-terminal: If you use gnome2 (Ubuntu) the default terminal is gnome-terminal. (I personally use xterm with some
- Emacs loads quickly (depending at what you want to run at init) and is small enough for most jobs. You will always be able to make the argument the vi is lighter. Yet for me I use Emacs everywhere someone might use vi.
- Emacs also has an emacsclient executable that connects to an emacs server. This allows multiple 'clients' to connect to the server. It makes loading emacs quicker and multiple instances can share memory. I never use it because Emacs isn't that resource intensive in a modern Desktop environment. Even in my VMs.
Emacs vs. Vi (and [insert editor here]):
For the programmer and for text editing intensive work: From what I can tell comparing vi to Emacs, Emacs wins. Comparing vim to Emacs might be more appropriate.
Power in text editors vary. Because there is variance we can say that one is more powerful than the other. That said, Emacs is the more powerful than vi (Remember I said this is a general statement. Such statements are helpful for newcomers to get a perspective not to state a holy war). Textmate, Vim, Eclipse and Visual Studio are all great at many different things. I think the reason we talk about vi and Emacs so much as because they run in terminals and fit into the average Unix user's work-flow much better. They are also old school as well as new school. Those other editors are better described as GUI IDEs. Of all of these vi is the lightest (smaller install, less memory). This is not a statement about what is better. Better is much more relative to the task at hand and the user's preference.
The power of Emacs reveals itself when the editing is beyond basic conf file editing. One could even argue that vi is also too powerful for editing a conf file. But I guess that all depends on how you want to edit conf files. If you do a lot of other things in Emacs (as most users do) then editing a conf file is just one more thing you are doing. I guess it's important to ask why you would use vi if you already have an Emacs instance running? (Remember you can even edit a file over ssh or even FTP)
Emacs as an OS?
In some contexts it's a fair comparison. A better comparison would be to a development platform. Eclipse and Eclipse RCP come to mind (http://wiki.eclipse.org/index.php/Rich_Client_Platform).
Emacs does have dired
...is obvious.
(ducks)
Advice: on VPS providers
Does anyone know of a good way to get emacs to magically blink corresponding parens based on proximity to point, rather than just when deleted/typed/directly demanded by a keypress?
I'm really enjoying this series, thanks ! How about one for stupid ed tricks.
Perhaps I've been working in this field too long, but I sometimes feel some nostalga for ed.
This one set the default command for 'compile'
(setq compile-command "make -k")
Add my favorite commands to the 'compile' history
(setq compile-history
( list compile-command
"cd $HOME/work/project ; make -k"
"cd $HOME/work/project ; make -k build"
"cd $HOME/work/project ; make -k clean all"
"cd $HOME/work/project ; configure"
))
Save all modified files at once
(defun save-all ()
"sauve tout les tampons"
(interactive)
(save-some-buffers 1)
)
Save all modified files and relaunch the last 'compile' command
(defun save-all-and-recompile ()
"Sauve tout les fichiers et lance une compilation"
( interactive)
(save-some-buffers 1)
( recompile )
)
Some fast keyboard shortcuts for compilation
(global-set-key [f6] 'save-all)
(global-set-key [f7] 'compile)
(global-set-key [f8] 'save-all-and-recompile)
(global-set-key [f12] 'next-error)
On some systems, gnu-emacs startup can be quite long because it is waiting for the Window Manager.
The same command also set the colors, font and a few other settings that used to be controlled by the X resources.
(if (eq window-system 'x) ;; prevent slow start
(if (x-display-color-p)
(progn
(modify-frame-parameters nil '((wait-for-wm . nil)))
(set-background-color "#FFDDD0")
(set-foreground-color "black")
(set-frame-font "9x15")
(set-cursor-color "red")
(set-mouse-color "blue")
)))
M-x lisp-interaction-mode
Allow the execution of any emacs lisp command in a buffer (no need to edit your .emacs)
The *scratch* buffer is in that mode by default.
Basically you can do the following:
(1) copy any of the e-lisp examples given in other post
(2) put the cursor after the last ')'
(3) press C-j to execute the command
For example (with indicates where you have to apply C-j):
(defun save-all ()
"sauve tout les tampons"
(interactive)
(save-some-buffers 1)
)
(global-set-key [f6] 'save-all)
and you now have the function 'save-all' bind to F6 in your emacs session.
yeah, that was a joke about "What dang package was I looking for again?"
And to say moderately on topic, I agree with previous posters that these threads are a good thing. Keep 'em coming!
man, I feel like mold.
M-x artist-mode
Extremely useful for drawing ascii figures.
---
http://pranavsbrain.peshwe.com/
From a dired buffer:
M-x wdired-change-to-wdired-mode
The dired buffer then becomes completely editable like a normal text buffer, so you can bulk change filenames, permissions etc., and on save it applies all the changes.
latest cvs have a switch for emacs to run as daemon and have emacs frame (x or tty) spawning super fast
Hehe, just wait another day, then dupe 'em. :)
"What luck for the rulers that men do not think." - Adolph Hitler
Damn straight. I actually miss the kernel update submissions and discussions from '98 - '01 or so. There were several good bits of information, or items that started me down a path that proved useful.
"What luck for the rulers that men do not think." - Adolph Hitler
(global-set-key "\C-x/" 'point-to-register)
(global-set-key "\C-xj" 'jump-to-register)
Now, to save your current location, type C-x-/-X , where X is a number or letter. To jump back to the same point, type C-x-j-X. You can of course have many such points within a file, and it even works across buffers. Can't live without it.
Also, time-stamp mode:
in your .emacs, add:
(add-hook 'write-file-hooks 'time-stamp)
At the top of your files, put
# Time-stamp: <>
The timestamp is automatically inserted each time you save.
Anyone know a good extension for editng / managing PHP code? I currently use "php-mode.el" (http://php-mode.sourceforge.net/), while it's OK I have a feeling there could be something better out there.
http://svn.jamison.tk/repository/dotfiles/
Some highlights:
Also, try C-w when in the middle of an incremental search.
Now that this Emacs and Vi stuff is out of the system, could we please go on to ed?
After all, it's the standard!
http://codeandlife.com