Настройка Emacs для разделения буферов бок о бок - PullRequest
88 голосов
/ 17 января 2010

Многие функции Emacs автоматически разделяют экран. Тем не менее, все они делают так, чтобы окна находились друг над другом. Есть ли способ разделить их так, чтобы они по умолчанию были рядом друг с другом?

Ответы [ 6 ]

87 голосов
/ 17 января 2010
(setq split-height-threshold nil)
(setq split-width-threshold 0)

Справочное руководство по GNU Emacs Lisp: Выбор параметров окна

5 голосов
/ 31 августа 2014

Два решения здесь, используйте любое, которое вам нравится:

A: Вертикально (влево / вправо) по умолчанию:

(setq split-height-threshold nil)
(setq split-width-threshold 0)

B: автоматически разбивать окно по вертикали (влево / вправо), если текущее окно достаточно широко

(defun display-new-buffer (buffer force-other-window)
  "If BUFFER is visible, select it.
If it's not visible and there's only one window, split the
current window and select BUFFER in the new window. If the
current window (before the split) is more than 100 columns wide,
split horizontally(left/right), else split vertically(up/down).
If the current buffer contains more than one window, select
BUFFER in the least recently used window.
This function returns the window which holds BUFFER.
FORCE-OTHER-WINDOW is ignored."
  (or (get-buffer-window buffer)
    (if (one-window-p)
        (let ((new-win
               (if (> (window-width) 100)
                   (split-window-horizontally)
                 (split-window-vertically))))
          (set-window-buffer new-win buffer)
          new-win)
      (let ((new-win (get-lru-window)))
        (set-window-buffer new-win buffer)
        new-win))))
;; use display-buffer-alist instead of display-buffer-function if the following line won't work
(setq display-buffer-function 'display-new-buffer)

Поместите любой файл в ваш .emacs/init.el файл. Вы можете изменить «100» на желаемое значение в зависимости от экрана.

Если у вас есть два окна в одном кадре, и вы хотите изменить расположение с вертикального на горизонтальное или наоборот, вот решение:

(defun toggle-window-split ()
  (interactive)
    (if (= (count-windows) 2)
      (let* ((this-win-buffer (window-buffer))
            (next-win-buffer (window-buffer (next-window)))
            (this-win-edges (window-edges (selected-window)))
            (next-win-edges (window-edges (next-window)))
            (this-win-2nd
             (not (and (<= (car this-win-edges)
                        (car next-win-edges))
                    (<= (cadr this-win-edges)
                        (cadr next-win-edges)))))
         (splitter
          (if (= (car this-win-edges)
                 (car (window-edges (next-window))))
              'split-window-horizontally
            'split-window-vertically)))
    (delete-other-windows)
    (let ((first-win (selected-window)))
      (funcall splitter)
      (if this-win-2nd (other-window 1))
      (set-window-buffer (selected-window) this-win-buffer)
      (set-window-buffer (next-window) next-win-buffer)
      (select-window first-win)
      (if this-win-2nd (other-window 1))))))
;; C-x 4 t 'toggle-window-split
(define-key ctl-x-4-map "t" 'toggle-window-split)

Поместите его в файл .emacs/init.el. Используйте C-x 4 t для переключения макета ваших окон.

4 голосов
/ 15 ноября 2012

Иногда нам нужно переключаться между горизонтальным и вертикальным в соответствии с текущим отображением и нашим требованием (больше строк или больше столбцов).

Я рекомендую большой ToggleWindowSplit , и я связываю ключ с "C-c y"

http://www.emacswiki.org/emacs/ToggleWindowSplit

4 голосов
/ 22 февраля 2011
(setq split-height-threshold 0) (setq split-width-threshold 0)

- это то, что я должен был использовать, чтобы получить желаемое поведение (без горизонтального разделения)

1 голос
/ 16 марта 2015

Я регулярно использую несколько кадров (окна OSX) в emacs для разных проектов. Вот как я устанавливаю несколько кадров, изначально разделенных на левое и правое окна.

  (defun make-maximized-split-frame (name)
    (let (( f (make-frame (list (cons 'name  name))) ))
      (maximize-frame f)
      (split-window (frame-root-window f) nil t)
      ))

  (make-maximized-split-frame "DocRaptor")
  (make-maximized-split-frame "Gauges")
  (make-maximized-split-frame "Instrumental")
1 голос
/ 12 июля 2012

простой ответ установки 2 переменных на nil и 0 у меня не сработал, поэтому я написал 2 простые функции: одна просто разбивает окно на вертикальные буферы NX и открывает файлы с именем (например) file.1 file.1. 2 ... file.NX в каждом и другом делает то же самое, за исключением того, что делает это в 2D (строки NY по столбцам NX для открытия файлов f.1 f.2 ... f. [NX * NY]). Чтобы установить, добавьте этот код в .emacs:

    (defun grid-files-h (nx wx pfx)
  "Using dotimes, split the window into NX side-by-side buffers of width WX and load files starting with prefix PFX and ending in numbers 1 through NX"
  (let (ox fn k)  ; ox is not used, but fn is used to store the filename, and k to store the index string
    (dotimes (x (- nx 1) ox) ; go through buffers, x goes from 0 to nx-2 and ox is not used here
;     (print x)
      (setq k (number-to-string (+ x 1) ) )  ; k is a string that goes from "1" to "nx-1"
;     (print k)
      (setq fn (concat pfx k) ) ; fn is filename - concatenate prefix with k
;     (print fn)
      (find-file fn) ; open the filename in current buffer
      (split-window-horizontally wx) ; split window (current buffer gets wx-columns)
      (other-window 1) ; switch to the next (right) buffer
      )
    (setq k (number-to-string nx )) ; last (rightmost) buffer gets the "nx" file
    (setq fn (concat pfx k) ) ; fn = "pfx"+"nx"
    (find-file fn ) ; open fn
    (other-window 1) ; go back to the first buffer
    )  
  )

   (defun grid-files-sq (ny wy nx wx pfx)
      "Using dotimes, split the window into NX columns of width WX and NY rows of height WY and load files starting with prefix PFX and ending in numbers 1 through NX*NY"
      (let (oy ox fn k)  
        (dotimes (y ny oy) ; go through rows, y goes from 0 to ny-1 and oy is not used here
          (split-window-vertically wy) ; create this row
          (dotimes (x (- nx 1) ox) ; go through columns, x goes from 0 to nx-2 and ox is not used here
        (setq k (number-to-string (+ 1 (+ x (* y nx) ) ) ) ) ; k must convert 2 indecies (x,y) into one linear one (like sub2ind in matlab)
        (setq fn (concat pfx k) ) ; filename
        (find-file fn ) ; open
        (split-window-horizontally wx) ; create this column in this row (this "cell")
        (other-window 1) ; go to the next buffer on the right 
        )
          (setq k (number-to-string (+ nx (* y nx) ) ) ) ; rightmost buffer in this row needs a file too
          (setq fn (concat pfx k) ) ; filename
          (find-file fn ) ; open
          (other-window 1) ; go to next row (one buffer down)
          )
        )
      )

и затем, чтобы использовать вертикальный, я иду к * scratch * (C-x b *scratch* RET, C-x 1), набираю (grid-files-h 3 20 "file.") затем C-x C-e, или, если вы хотите проверить квадратный qrid, C-x 1, введите (grid-files-sq 2 15 3 20 "f."), а затем C-x C-e, и вы должны увидеть что-то вроде 2x3 grid

Вероятно, это можно сделать лучше / эффективнее, но это начало, и оно делает то, что мне нужно (отображать кучу последовательно именуемых небольших файлов). Не стесняйтесь улучшать или повторно использовать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...