Search code examples
emacswindow

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


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?


Solution

  • 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.