help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Lexical vs. dynamic: small examples?


From: Emanuel Berg
Subject: Re: Lexical vs. dynamic: small examples?
Date: Sat, 14 Aug 2021 22:16:24 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/28.0.50 (gnu/linux)

Gregory Heytings wrote:

> (defun delete-whitespace-at-eol ()
>   (interactive)
>   (save-excursion (replace-regexp " *$" "" nil (point-min) (point-max))))

OK, that's an example, but let's mention there is
`delete-trailing-whitespace'.

(defun untab-all ()
  (unless (member major-mode '(makefile-gmake-mode
                               makefile-mode) ) ; exceptions
    (untabify (point-min) (point-max)))
  nil) ; "did not write buffer to disk"

(defun before-save-hook-f ()
  (untab-all)
  (delete-trailing-whitespace) )
(add-hook 'before-save-hook #'before-save-hook-f)

> Now if you M-x trim-whitespaces-at-eol in a read-only
> buffer, you'll get a "Buffer is read-only" error.
> Suppose you want to make that function work for read-only
> buffers. If Emacs Lisp only had lexical binding, you would
> have to alter the global "buffer-read-only" variable, that
> is, to do something like:
>
> (defvar saved-buffer-read-only)
> (defun delete-whitespace-at-eol ()
>   (interactive)
>   (setq saved-buffer-read-only buffer-read-only)
>   (setq buffer-read-only nil)
>   (save-excursion (replace-regexp " *$" "" nil (point-min) (point-max)))
>   (setq buffer-read-only saved-buffer-read-only))

OK, but you don't need to store the old value in a global
variable...

> This becomes much simpler with dynamic binding:
>
> (defun delete-whitespace-at-eol ()
>   (interactive)
>   (let ((buffer-read-only nil))
>     (save-excursion (replace-regexp " *$" "" nil (point-min) (point-max)))))

Can't we have two `let', the old let that is lexical/static
and another let that is dynamic, only we call it something
else, and then everyone can use whatever they like and it is
always clear from the code which it is and we can even have
both from the same file, with no need to say it's this way or
the other?

It doesn't work like that? Why not?

-- 
underground experts united
https://dataswamp.org/~incal




reply via email to

[Prev in Thread] Current Thread [Next in Thread]