Jumping to a specified window in Emacs doesn't work when done programatically - emacs

I am trying to select the third window (I have opened 6 in my frame) in Emacs.
The problem is that this:
(select-window 3)
doesn't work.
It throws this error in debugger:
(wrong-type-argument window-live-p 3)
How to make it work?

select-window takes a window object as argument, not a number. The function window-list gives you a list of window objects in the current frame. You can select one of them to pass to select-window, e.g.
(select-window (nth 2 (window-list)))
will select the window that is the third[1] element of the list that window-list returns.
Do C-h f nth and C-h f window-list for more information on these functions.
EDIT: in response to the comment...
What I know about Windows (which is not much), I've learned by reading parts of the Windows chapter in the Emacs Lisp Reference manual.
Do NOT expect the window number to correspond to anything that you think as "first" or "second" or ...
When you destroy windows and then create new ones, the numbers are going to change unpredictably (at least AFAIK), e.g. I had three windows with numbers 51, 83 and 99. I destroyed window #99 and created a new one: now window-list tells me I have windows with numbers 51, 105 and 83 in that order. I believe (but I may be wrong) that Emacs uses the list returned by window-list in order to implement other-window (C-x o), so the order of the list that window-list returns depends on what your selected window is currently: that' always the first element of the list, so the window you'll select with C-x o is the second element of the current list, but when you get there and do ESC ESC : (window-list), the returned list will have changed - it will be rotated so that where you are is the first element and where you came from is now the last element. See Cyclic Ordering of Windows in the Emacs Lisp Reference manual.
You are correct that the upper case WINDOW in the function description is a hint of its type. For typographic conventions, see the section Conventions in the Emacs Lisp Reference manual and in particular, the subsection A Sample Function Description.
[1] Note that list elements are indexed from 0.

Related

Emacs opens ibuffer or compilation in same window rather than other window

I have been using emacs for many years. The past year or so, there has been an annoying problem, which is that sometimes Ibuffer or the compilation buffer runs in the same window that I am already in. I generally have 2 buffers open, one above the other. I always want Ibuffer to open in the one I am not currently in. But it seems to pick randomly. Is this a bug or feature? Can I stop it? I have searched for an answer several times, but I have not found one. I am running GNU Emacs 24.5.1 in the terminal. Thanks.
The following answer relates to the usage of ibuffer:
The original poster may wish to use the keyboard shortcut bound to the letter o, which is ibuffer-visit-buffer-other-window. The doc-string states that this function is designed to: Visit the buffer on this line in another window. The function ibuffer-visit-buffer-other-window uses pop-to-buffer and switch-to-buffer-other-window, which should avoid a window that is dedicated: http://www.gnu.org/software/emacs/manual/html_node/elisp/Dedicated-Windows.html
The return key is bound to ibuffer-visit-buffer (which uses switch-to-buffer), and the doc-string states that this function is designed to: Visit the buffer on this line. If optional argument SINGLE is non-nil, then also ensure there is only one window. The optional argument can be used interactively by typing C-u RET.

Switch to original buffer after chasing tags in Emacs

I use M-. to jump to definitions of class/functions. Sometimes there are multiple classes with the same tag, so I need to use C-u M-. to jump to multiple files, hence multiple buffers. Now my question is, how do I go back to the original buffer quickly? I know C-x b, but you need to type in the buffer name, or it just give you by default the last buffer you visited, is there anyway to go further? For example, go to the previous buffer of the last buffer?
I believe that M-. calls find-tag by default. You should be able to go back up the stack of locations with M-* (pop-tag-mark).
From C-h f find-tag:
A marker representing the point when this command is invoked is pushed
onto a ring and may be popped back to with M-*. Contrast this with the
ring of marks gone to by the command.
Icicles multi-command icicle-find-tag, bound to M-. in Icicle mode, combines all of what vanilla Emacs commands M-. (find-tag), M-, (tags-loop-continue), tags-apropos, and list-tags do. And it does more.
You can complete against any tags, cycle (in different orders) among a subset of tags matching an additional pattern, and so on, visiting multiple tags in a single command invocation. You choose the tags you want to visit, in any order --- you need not visit each one in sequence.
You first enter (using RET) a regexp that all tags you are interested in must match (it could be vacuous, to get all tags).
After that, you can type a pattern that a subset of the tags and or their source files must match.
That is, by default you can complete against multi-completion candidates that are composed of the tag itself and its source file name.
You can choose candidates to visit using C-mouse-2 in *Completions* or by cycling among their names using down and up and then using C-RET to visit.
You can return to your original location using M-* (icicle-pop-tag-mark). You can also return to it by just using C-g to finish your M-. invocation.
More information here.
I use winner-mode for this (and other similar situations).
Add (winner-mode 1) to your init file, and then when you wish to return to the window configuration that you were in before jumping to the tags, you just type:
C-c<left> to call winner-undo (repeating as many times as necessary)
If you had visited multiple tags in another buffer, this will get you back to your original buffer (or the previous buffer, at any rate) in a single step, rather than stepping back through the individual tags one by one.
If the tags have taken you through multiple buffers, then you'll need to type C-c<left> once for each buffer (or C-c<left>C-xzzz... if you'd gone on quite a long detour :)

Emacs Lisp - opening new window

I'd like to write an emacs lisp function that will write output to a window other than the current window. It should create a new window if only the current one exists, and it should use an existing one otherwise. This is similar to what happens when you run C-h-f (Describe Function), and the description pops up in another window. What is the best way to do this?
See display-buffer:
display-buffer is an interactive
compiled Lisp function in `window.el'.
It is bound to C-x 4 C-o.
(display-buffer buffer-or-name
&optional not-this-window frame)
Make buffer buffer-or-name appear in
some window but don't select it.
buffer-or-name must be a buffer or the
name of an existing buffer. Return
the window chosen to display
buffer-or-name or nil if no such
window is found.
Optional argument not-this-window
non-nil means display the buffer in a
window other than the selected one,
even if it is already displayed in the
selected window.
Optional argument frame specifies
which frames to investigate when the
specified buffer is already displayed.
If the buffer is already displayed in
some window on one of these frames
simply return that window. Possible
values of frame are:
`visible' - consider windows on all
visible frames.
0 - consider windows on all visible or
iconified frames.
t - consider windows on all frames.
A specific frame - consider windows on
that frame only.
nil - consider windows on the selected
frame (actually the last
non-minibuffer frame) only. If,
however, either
display-buffer-reuse-frames' or
pop-up-frames' is non-nil (non-nil
and not graphic-only on a text-only
terminal), consider all visible or
iconified frames.
Or you can use pop-to-buffer if you want that buffer to be selected (which it sounds like you don't), or with-output-to-temp-buffer which binds the standard-output to be sent to the temporary buffer - read the documentation for more details (hat tip to Michael for that).

Emacs remember text selection

I decided that I was ready to try something new, after a few years of using gEdit for most of my coding needs, and try to learn using Emacs. I knew this would be difficult, as I have heard how complex Emacs can be, but I was lured by its power. The hardest thing has been getting used to writing ELisp in the .emacs file to change things about the editor. I can't currently do it myself, but I have found a few helpful snippets here and there to change some options.
One thing I have been having a lot of problems with is getting Emacs to remember the text I have selected after a command. For instance, I commonly highlight a section of code to mass indent it. However, if I do this in Emacs, it will move the selected text only once before unselecting all of the text. Does anyone know a way around this?
Anyway, I apologize for what seems to me to be an easy question, but after an hour of Google searching and looking around here on SO, I thought it was worth asking. I have a few more questions about Emacs, but I will save them and ask separately after I get this straightened out. Thanks!
UPDATE
A few people have asked about what mod I am using and what type of text I am entering. While I don't know much about Emacs modes, I am editing a pure text file at the moment. Something like this:
Hello, I am a simple text file
that is made up of three separate
lines.
If I highlight all three lines and hit TAB, I get this:
Hello, I am a simple text file
that is made up of three separate
lines.
This is great, however, if I use C-x C-x like some suggest below to reselect the text and hit TAB again, I get this:
Hello, I am a simple text file
that is made up of three separate
lines.
I hope this helps!
FWIW, here is the reason for the behaviour of your newly-added example. (I'm not 'solving' the issue here, but I'm posting it to demystify what you're seeing.)
This was determined with emacs -q which disables my customisations, so the following is default behaviour for emacs 23.2.
You are in text-mode. You should see (Text) or similar in the mode line at the bottom of the screen, and C-h m will tell you (under the list of minor modes) "Text mode: Major mode for editing text written for humans to read." Emacs decides (by way of the auto-mode-alist variable) that it should switch to text-mode if you visit a filename matching certain extensions (such as .txt).
In text-mode pressing TAB with a region highlighted causes indent-according-to-mode to be called on each line of the region in sequence. The slightly convoluted path to finding this out starts at C-h k TAB, which tells us that TAB is bound to indent-for-tab-command, which in this instance calls indent-region -- that function name is not stated explicitly in the help, but can be seen in the code -- which checks the buffer-local indent-region-function variable, which is nil, and: "A value of nil means really run indent-according-to-mode on each line."
indent-according-to-mode checks the indent-line-function variable, which has the buffer-local value indent-relative.
Use C-h f indent-relative RET to see the help for this function. (Read this).
Although you probably won't yet have had the experience to know how to check all that (or necessarily even want to!), and fully understand everything it tells you, this is an example of how the self-documenting aspect of Emacs enables a user to figure out what is going on (which then makes it feasible to change things). I essentially just used C-h k (describe-key), C-h f (describe-function), and C-h v (describe-variable) to follow the documentation. Looking at the source code for indent-for-tab-command was as simple as clicking the file name shown as part of its help page.
I suggest doing the following to help see what is happening when indent-relative runs on each line:
M-x set-variable x-stretch-cursor t
M-x set-variable ruler-mode-show-tab-stops t
M-x ruler-mode
Now for each line in turn, put the cursor at the very start of the line and press TAB. You'll end up with all three lines indented to the first tab-stop ('T' in the ruler).
Now repeat this -- again, ensure you are at the very start of each line, in front of the existing indentation.
The first character of the first line (which is currently a tab) is once again indented to the first tab-stop, as there is no preceding line for it to examine.
Next, the first character of the second line is indented to match the position of the first non-white-space character of the preceding line. Because the first character of the second line is also a tab, the actual text of the second line is pushed one tab further along.
The third line follows suit. Its first tab character is lined up with the first non-white-space character of the second line, with the same relative effect as before, giving you the final state in your example.
To emphasise, note what happens if you now put enter the line "a b c" above the existing lines, then move back to the start of the next line (what was previously the first line) and press TAB. The first tab character will now be indented in line with the 'b'. Provided that the indent-tabs-mode variable is true (meaning you have actual tab characters), then this will have no practical effect on the position of the words in the line, as 'indenting' a tab with spaces will not have an effect until the number of spaces exceeds the width of the tab (but that's another kettle of fish entirely!)
All this really means is that text-mode in Emacs doesn't behave the way you'd like it to in this situation. Other major modes can do completely different things when you press TAB, of course.
As is invariably the case with Emacs, things you don't like can be changed or circumvented with elisp. Some searching (especially at the Emacs Wiki) will frequently turn up useful solutions to problems you encounter.
Try typing C-x C-x after Emacs unselects it.
Then, instead of hitting tab (I never knew that tab does what you said! That's totally whacked.), do M-8 C-x C-i. Pity it's so many keys, but it ought to do what you want -- namely, shove everything over 8 columns. Obviously replace the M-8 with something else if you want some other number of columns.
What I usually do is simply type C-x C-x (exchange-point-and-mark) after a command that deactives the region.
How are you indenting, and in which mode?
The indentation rules in any programming mode should generally just get it right. (If they don't, that's probably more indicative that you want to configure the rules for that mode differently, but I suspect that's a different question which has been asked already).
If you're in text-mode or similar and just using TAB, then I can see the problem.
Note that if you're using indent-rigidly (C-x C-i, or C-x TAB which is the same thing) then you can repeatedly indent the same region simply by repeating the command, even if the highlighting has disappeared from view.
You can also use a prefix arg to indent-rigidly to make it indent many times. e.g. C-u C-u C-x C-i (easier to type than it looks) will indent 16 spaces (4 x 4, as the prefix arg defaults to 4, and it multiplies on each repeat). Similarly, M-8 C-x C-i indents 8 spaces. This is fine in some circumstances, and way too cumbersome in others.
Personally I suggest putting (cua-selection-mode 1) into your .emacs and using that for rigid indentation. Trey Jackson made a handy blog about it. With this, you can C-RET to start rectangle selection, down as many lines as you need, TAB repeatedly to indent the lines, and C-RET to exit the mode.
While the rectangle is active, RET cycles through the corners. For left-hand corners, typing inserts in front. For right-hand corners, typing inserts after. For the single-column rectangle, bottom counts as 'left' and top counts as 'right' for this purpose.
Trey's blog lists all the available features (or look in the source file: cua-base.el)
Be warned that indentation in Emacs is generally an unexpectedly complicated topic.
You can do this with something like the following:
(add-hook 'text-mode-hook (lambda ()
(set (make-local-variable 'indent-region-function)
(lambda (s e)
(indent-rigidly s e tab-width)))))
Then selecting a region and hitting TAB. will indent the region by a tab-width. You can then exchange point and mark with C-x C-x and hit TAB again to repeat.
I do, however, agree with the previous answers that suggest using indent-rigidly directly.

emacs/elisp: What is the hash (pound, number sign, octothorp) symbol used for?

What does this do?
(add-hook 'compilation-mode-hook #'my-setup-compile-mode)
...and is it different than
(add-hook 'compilation-mode-hook 'my-setup-compile-mode)
There is no difference:
(eq 'my-add #'my-add)
yields t
The # can be used in front of a lambda expression indicating to the byte-compiler that the following expression can be byte compiled, see the docs for Anonymous Functions. But there's nothing to compile in the case of a symbol.
In general, it is used in the printed representation along with the left angle bracket (<) to indicate that the object printed is a description (but cannot be read). For example:
#<buffer foo.txt>
It is also used in constructs by the reader to represent circular structures. See the docs for Read Syntax for Circular Objects.
And then you have its use for denoting the base for integers, e.g. #x2c -> 44.
Plus more I'm sure.
The should-be-comprehensive list can be found at the top of the Emacs lisp reference index.
Edit: Or even more conveniently, from within Emacs itself:
M-x info RET (open the info browser)
d m elisp RET (open the elisp manual)
I # RET (list the entries for # in the index)
I found this question while searching for what the hash meant in something I found while hacking mode-line-format:
#("-%-" 0 3
(help-echo "Display as tooltip when mouse hovers or with display-local-help."))
which is a format used for text properties in strings where:
"-%-", text to be propertized: one dash and a %-construct that results in "dashes sufficient to fill the remainder of the mode line", resulting in the famous Emacs ------.
0, the first character upon which the text properties apply.
3, the last character upon which the text properties apply, i.e. the entire "-%-".
(help-echo "..."), a property and a string as its argument.
This can be created with the propertize function:
(propertize "Hover over me!" 'help-echo '"congratulations!")
would be the same as #("Hover over me!" 0 14 (help-echo "Congratulations!")):
If you're using font lock mode, using the buffer-substring command might produce something like this:
(buffer-substring 1 28) ; First 27 characters in the current buffer
⇒ #(";; This buffer is for notes"
0 3
(fontified t face font-lock-comment-delimiter-face)
3 27
(fontified t face font-lock-comment-face))
So you could create something like: