Riaprire il buffer * scratch * in Emacs?


168

Se sbaglio ho chiuso la scratch buffer in Emacs, come faccio a creare un nuovo scratch buffer?

Risposte:


199

Collegamenti predefiniti di GNU Emacs:

C-xb *scratch* RET

o, più verbalmente

M-x switch-to-buffer *scratch* RET

Il *scratch*buffer è il buffer selezionato all'avvio e ha la modalità principale Interazione Lisp . Nota: la modalità per il *scratch*buffer è controllata dalla variabile initial-major-mode.

In generale puoi creare tutti i buffer "scratch" che vuoi e nominarli come preferisci.

C-xb NAME RET

passa a un buffer NAME, creandolo se non esiste. Un nuovo buffer non è associato a un file su disco fino a quando non si utilizza C-xC-w(o M-x write-file RET) per scegliere un file in cui deve essere salvato.

M-x text-mode RET

cambia la modalità principale del buffer corrente in modalità testo. Per trovare tutte le modalità disponibili (ovvero senza richiedere nuovi pacchetti), puoi ottenere un elenco digitando:

M-x apropos-command -mode$ RET


8
Nota che c'è qualcosa di speciale in scratch , almeno in GNU Emacs 21 e versioni successive: il passaggio a un nuovo buffer scratch lo riporterà in modalità Interazione Lisp.
Peter S. Housel,

Proprio come un rapido follow-up a questo, se si .emacsdefinisce una diversa modalità scratch predefinita , questa sarà la modalità per la nuova modalità scratch - non per la lista di interazione.
Ocodo

23

Aggiungo quanto segue nel mio .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)))

Se non voglio vedere il buffer scratch, premo Cx Ck, ma non lo uccide, basta posizionarlo alla fine dell'elenco buffer, quindi la prossima volta che ne ho bisogno non è necessario crearne uno nuovo.


Quando provo questo consiglio da "ibuffer", il consiglio viene ignorato. Ma come meglio posso dire, "ibuffer" sta usando "kill-buffer". Mi potete aiutare?
A.Ellett,

Bene, premendo "close buffer" nell'interfaccia grafica scratch viene cancellato. Funziona solo per Cx k,
Maurizio Loreti,

15

Ci sono molti suggerimenti in questa pagina di EmacsWiki .

Ecco il primo:

Una funzione molto semplice per ricreare il buffer scratch:

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

9

Cx b *scratch*RET y RET con modalità iswitchb abilitata.

Solo Cx b *scratch*RET altrimenti.


Con collegamenti predefiniti, il 'RET y' non è necessario e solo inserisce un 'y' e una nuova riga nella appena creato graffio buffer.
Trey Jackson,

Spiacenti, forse proviene dalla modalità iswitchb. Mi dispiace per quello. Su un altro argomento, prova la modalità iswitchb;)
Steven Huwig,

Non si dovrebbe, inoltre, non c'è niente di speciale nel nome scratch . Si può usare Cx b per creare un numero qualsiasi di buffer "scratch", con nomi arbitrari.
Chris Conway,

1
V'è qualcosa di speciale nel nome * scratch * (come indicato nella risposta accettata) - se si crea un buffer denominato * scratch * la modalità principale sarà impostato in base alla initial-major-modevariabile (lisp-interaction-mode per impostazione predefinita).
phils,

4

L'ho scoperto anni fa quando ho iniziato a usare emacs; Non ho idea di dove ora ma ha sempre avuto una casa nei miei file .el personali. Viene visualizzato nelle ricerche di 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)
;;;----------------------------------------------------------------------

3

Usavo la soluzione di dwj, e ne ero abbastanza contento, fino al giorno in cui mi sono reso conto che falliva quando in realtà hai rinominato il buffer di (ad esempio salvandolo).

Quindi ho adottato questo, che funziona bene per me:

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

3

Ho scratchcome comando interattivo per aprire un nuovo buffer di memoria virtuale (mi piace averne diversi):

(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

adottato da: http://everything2.com/index.pl?node_id=1038451


Come è superiore al semplice passaggio a un nuovo buffer (Cx b bufname RET)?
bignose,

@bignose: io uso ido-modee di solito ho molti buffer aperti. Creare un nuovo buffer usando C-x bsarebbe davvero noioso. Dovrei trovare un nome univoco che non corrisponda a nessuno dei buffer attualmente presenti.
paprika,

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

Questo non solo passerà rapidamente al *scratch*buffer (poiché lo faccio spesso), ma ricrea un *scratch*buffer e lo abilita lisp-interaction-modeautomaticamente se lo uccidi accidentalmente. Cambia l'associazione come preferisci.


3

Solo per notare che il pacchetto emacs unkillable-scratchin MELPA lo farà. C'è anche scratch-persistche salverà e ripristinerà automaticamente il buffer tra le sessioni.


2

Come dice il docstring, questa funzione:

Passa al buffer di memoria virtuale. Se il buffer non esiste, crearlo e scrivere il messaggio iniziale in esso. "

Questo farà apparire un nuovo buffer scratch che assomiglia al buffer scratch iniziale.

(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)

2

Questo è quello che uso - ho questo legato a una sequenza di tasti conveniente. Ti invia al *scratch*buffer, indipendentemente dal fatto che esista o meno, e lo imposta per essere inlisp-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)))

2

Preferisco che il mio buffer di memoria virtuale sia un file reale che viene automaticamente salvato e riaprirlo è semplice come aprire un file. All'avvio, uccido l'impostazione predefinita e trovo la mia in questo modo.

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

Ho una funzione di kill-buffer personalizzata che fa sostanzialmente la stessa cosa: riapre il mio file salvato scratch personale e uccide lo scratch predefinito se ho ucciso l'ultimo buffer visibile.

Ho personalizzato alcune delle desktop.elfunzioni da caricare dopo (kill-buffer "*scratch*") e(find-file "/Users/HOME/Desktop/.scratch") modo che l'ultimo file visibile all'uscita da Emacs non venga seppellito dal graffio predefinito o sepolto dal mio graffio personalizzato all'avvio di Emacs.

Mi piace usare auto-save-buffers-enhanced, che salva automaticamente qualsiasi estensione di file non specificamente esclusa:

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"))

Uso una leggera variazione della funzione di @paprika quando voglio creare un buffer di visita senza file:

(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) ))

1

Ho combinato le soluzioni pubblicate finora in un'unica funzione:

(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))

Per applicare questa funzione nel tuo .emacs usa:

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

Ciò renderà indistruttibile il buffer di memoria virtuale e, se salvato, verrà ricreato. Inoltre, possiamo utilizzare una funzione di scelta rapida scratchper richiamare rapidamente il buffer:

(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))))

In passato si è dimostrato utile conoscere la directory di avvio originale da cui è stato avviato Emacs. Questo è il valore desktop-dirnameo la default-directoryvariabile locale del buffer di memoria :

(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))

Quindi --startup-directory restituirà sempre la directory di base del tuo makefile, file TODO ecc. Nel caso in cui non ci sia desktop ( --no-desktop command-switch o nessun file-desktop) la --scratch-directoryvariabile conterrà la directory Emacs una volta iniziato sotto.



0

Per aggiungere alla risposta accettata, se hai attivato la modalità ILO (e dopo si completa automaticamente C-x b, quindi non ti consente di scrivere *scratch*), prova a:

C-xb C-b*scratch* RET

C-x b C-b *scratch* RET


-3

C-xb e quindi digitare *scratch* ↩︎

per creare un nuovo buffer che è anche in modalità di interazione lisp.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.