tutorial mac emacs

tutorial - Vuelva a abrir el búfer*scratch*en Emacs?



emacs ubuntu (15)

Si accidentalmente cerré el buffer de scratch en Emacs, ¿cómo creo un nuevo buffer de scratch ?


Cx b y luego escribe *scratch* ↩︎

para crear un nuevo búfer que también esté en modo de interacción de ceceo.


Agrego los siguientes en mis .emacs:

;; bury *scratch* buffer instead of kill it (defadvice kill-buffer (around kill-buffer-around-advice activate) (let ((buffer-to-kill (ad-get-arg 0))) (if (equal buffer-to-kill "*scratch*") (bury-buffer) ad-do-it)))

Si no quiero ver el búfer de rayar , presiono Cx Ck, pero no lo mata, simplemente colócalo al final de la lista de búfer, entonces lo necesito la próxima vez que no tenga que crear uno nuevo.


Como dice el docstring, esta función:

Cambia al buffer de scratch. Si el búfer no existe, créelo y escriba el mensaje inicial en él ".

Esto traerá un nuevo búfer de rayado que se parece al búfer de rayado inicial.

(defun switch-buffer-scratch () "Switch to the scratch buffer. If the buffer doesn''t exist, create it and write the initial message into it." (interactive) (let* ((scratch-buffer-name "*scratch*") (scratch-buffer (get-buffer scratch-buffer-name))) (unless scratch-buffer (setq scratch-buffer (get-buffer-create scratch-buffer-name)) (with-current-buffer scratch-buffer (lisp-interaction-mode) (insert initial-scratch-message))) (switch-to-buffer scratch-buffer))) (global-set-key "/C-cbs" ''switch-buffer-scratch)


Cx b *scratch* RET y RET con iswitchb-mode habilitado.

Solo Cx b *scratch* RET en caso contrario.


Encontré esto hace años cuando comencé a usar emacs; No tengo idea de dónde está ahora, pero siempre ha tenido un hogar en mis archivos .el personales. Aparece en las búsquedas de google.

;;; Prevent killing the *scratch* buffer -- source forgotten ;;;---------------------------------------------------------------------- ;;; Make the *scratch* buffer behave like "The thing your aunt gave you, ;;; which you don''t know what is." (save-excursion (set-buffer (get-buffer-create "*scratch*")) (make-local-variable ''kill-buffer-query-functions) (add-hook ''kill-buffer-query-functions ''kill-scratch-buffer)) (defun kill-scratch-buffer () ;; The next line is just in case someone calls this manually (set-buffer (get-buffer-create "*scratch*")) ;; Kill the current (*scratch*) buffer (remove-hook ''kill-buffer-query-functions ''kill-scratch-buffer) (kill-buffer (current-buffer)) ;; Make a brand new *scratch* buffer (set-buffer (get-buffer-create "*scratch*")) (lisp-interaction-mode) (make-local-variable ''kill-buffer-query-functions) (add-hook ''kill-buffer-query-functions ''kill-scratch-buffer) ;; Since we killed it, don''t let caller do that. nil) ;;;----------------------------------------------------------------------


Enlaces predeterminados de GNU Emacs:

Cx b *scratch* RET

o, más ampliamente

Mx switch-to-buffer *scratch* RET

El búfer *scratch* es el búfer seleccionado al inicio, y tiene el modo principal de interacción Lisp . Nota: el modo para el búfer *scratch* está controlado por la variable initial-major-mode .

En general, puede crear tantos buffers "scratch" como desee, y asígneles el nombre que elija.

Cx b NAME RET

cambia a un buffer NAME , creándolo si no existe. Un nuevo búfer no está asociado con un archivo en el disco hasta que utilice Cx Cw (o Mx write-file RET ) para elegir un archivo donde se debe guardar.

Mx text-mode RET

cambia el modo principal del búfer actual al modo Texto. Para encontrar todos los modos disponibles (es decir, sin requerir ningún paquete nuevo), puede obtener una lista escribiendo:

Mx apropos-command -mode$ RET


Esto es lo que uso, tengo esto ligado a una cómoda pulsación de tecla. Le envía al búfer *scratch* , independientemente de si ya existe o no, y lo configura para que esté en lisp-interaction-mode

(defun eme-goto-scratch () "this sends you to the scratch buffer" (interactive) (let ((eme-scratch-buffer (get-buffer-create "*scratch*"))) (switch-to-buffer eme-scratch-buffer) (lisp-interaction-mode)))


Hay un montón de consejos en esta página de EmacsWiki .

Aquí está el primero:

Una función muy simple para recrear el buffer de scratch:

(defun create-scratch-buffer nil "create a scratch buffer" (interactive) (switch-to-buffer (get-buffer-create "*scratch*")) (lisp-interaction-mode))


He combinado las soluciones publicadas hasta ahora en una función:

(defun --scratch-buffer(&optional reset) "Get the *scratch* buffer object. Make new scratch buffer unless it exists. If RESET is non-nil arrange it that it can''t be killed." (let ((R (get-buffer "*scratch*"))) (unless R (message "Creating new *scratch* buffer") (setq R (get-buffer-create "*scratch*") reset t)) (when reset (save-excursion (set-buffer R) (lisp-interaction-mode) (make-local-variable ''kill-buffer-query-functions) (add-hook ''kill-buffer-query-functions ''(lambda()(bury-buffer) nil) ))) R))

Para aplicar esta función en su .emacs use:

(--scratch-buffer t) (run-with-idle-timer 3 t ''--scratch-buffer)

Esto hará que el buffer de scratch sea indestructible en primer lugar, y si se guarda, se volverá a crear. Además, podemos utilizar un scratch función de acceso directo para abrir rápidamente el búfer:

(defun scratch() "Switch to *scratch*. With prefix-arg delete its contents." (interactive) (switch-to-buffer (--scratch-buffer)) (if current-prefix-arg (delete-region (point-min) (point-max)) (goto-char (point-max))))

En el pasado, ha resultado útil conocer el directorio de inicio original desde el que se inició Emacs. Este es el valor de desktop-dirname o la variable local de default-directory de scratch-buffer:

(defvar --scratch-directory (save-excursion (set-buffer "*scratch*") default-directory) "The `default-directory'' local variable of the *scratch* buffer.") (defconst --no-desktop (member "--no-desktop" command-line-args) "True when no desktop file is loaded (--no-desktop command-line switch set).") (defun --startup-directory () "Return directory from which Emacs was started: `desktop-dirname'' or the `--scratch-directory''. Note also `default-minibuffer-frame''." (if (and (not --no-desktop) desktop-dirname) desktop-dirname --scratch-directory))

Así que --startup-directory siempre devolverá el directorio base de su archivo MAKE, TODO-etc. En caso de que no haya un escritorio ( --no-desktop commandline-switch o no desktop-file) la variable --scratch-directory mantener el directorio Emacs una vez comenzó bajo.


Prefiero que mi memoria temporal sea un archivo real que se guarda automáticamente, y volver a abrirlo es tan simple como abrir un archivo. Al inicio, elimino el valor predeterminado y encuentro el mío así.

(add-hook ''emacs-startup-hook (lambda () (kill-buffer "*scratch*") (find-file "/Users/HOME/Desktop/.scratch")))

Tengo una función personalizada kill-buffer que básicamente hace lo mismo: reabre mi archivo personal scratch saved y mata el scratch predeterminado si eliminé el último buffer visible.

Personalicé algunas de las funciones de desktop.el para cargarlas después (kill-buffer "*scratch*") y (find-file "/Users/HOME/Desktop/.scratch") para que el último archivo visible al salir de Emacs no funcione No ser enterrado por el cero predeterminado o enterrado por mi rasguño personalizado al iniciar Emacs.

Me gusta usar auto-save-buffers-enhanced , que guarda automáticamente cualquier extensión de archivo que no esté específicamente excluida:

https://github.com/kentaro/auto-save-buffers-enhanced/blob/master/auto-save-buffers-enhanced.el

(require ''auto-save-buffers-enhanced) (auto-save-buffers-enhanced t) (setq auto-save-buffers-enhanced-save-scratch-buffer-to-file-p 1) (setq auto-save-buffers-enhanced-exclude-regexps ''("//.txt" "//.el" "//.tex"))

Utilizo una ligera variación de la función de @paprika cuando quiero crear un buffer de visita sin archivo:

(defun lawlist-new-buffer () "Create a new buffer -- /*lawlist/*" (interactive) (let* ( (n 0) bufname) (catch ''done (while t (setq bufname (concat "*lawlist" (if (= n 0) "" (int-to-string n)) "*")) (setq n (1+ n)) (if (not (get-buffer bufname)) (throw ''done nil)) )) (switch-to-buffer (get-buffer-create bufname)) (text-mode) ))


Solía ​​usar la solución de dwj, y me alegré bastante, hasta el día en que me di cuenta de que fallaba cuando cambiaste el nombre del buffer de rayado (por ejemplo, guardándolo).

Luego adopté esto, que funciona bien para mí:

(run-with-idle-timer 1 t ''(lambda () (get-buffer-create "*scratch*")))


Solo para observar el paquete de emacs no unkillable-scratch en MELPA hará esto. También hay scratch-persist que guardará y restaurará automáticamente el buffer entre las sesiones.


Tengo scratch como un comando interactivo para abrir un nuevo búfer de rayado (me gusta tener varios):

(defun scratch () "create a new scratch buffer to work in. (could be *scratch* - *scratchX*)" (interactive) (let ((n 0) bufname) (while (progn (setq bufname (concat "*scratch" (if (= n 0) "" (int-to-string n)) "*")) (setq n (1+ n)) (get-buffer bufname))) (switch-to-buffer (get-buffer-create bufname)) (if (= n 1) initial-major-mode))) ; 1, because n was incremented

adoptado de: http://everything2.com/index.pl?node_id=1038451



(global-set-key (kbd "C-x M-z") ''(lambda () (interactive) (switch-to-buffer "*scratch*")))

Esto no solo cambiará rápidamente al búfer *scratch* (ya que lo hago con frecuencia), sino que recreará un búfer *scratch* y habilitará el modo lisp-interaction-mode automáticamente si lo mata accidentalmente. Cambie el enlace como lo desee.