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

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

Re: Inserting output from a program into a buffer


From: Pascal J. Bourguignon
Subject: Re: Inserting output from a program into a buffer
Date: Mon, 22 Feb 2010 10:41:07 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (darwin)

Tim Johnson <tim@johnsons-web.com> writes:

> On 2010-02-22, Pascal J. Bourguignon <pjb@informatimago.com> wrote:
> <..>
>> You could get a string without attribute using the function
>> buffer-substring-no-properties instead of buffer-substring.
>  Oh! Deja vu here... I believe that what I really need is 
>  buffer-substring-<etc> to copy the region directly to a
>  variable.

In general, functions don't modify variables.  This would be a bad case
of side effect.  In emacs lisp it would be somewhat possible, since all
the variables are dynamic variables.  (In Scheme or Common Lisp it
wouldn't even be possible for lexical variables!).  However, even with
dynamic variables, you cannot modify the variables if they are rebound
in an inner dynamic scope.

(defun f (x)
   (let ((var 42))
      (list var
            (progn (set-var x)
                   var))))

(defun set-var (x) 
   (setq var x))

(defvar var 0)
(set-var 33)
var    ; --> 33        ; seems to work.
(f 22) ; --> (42 22)   ; seems to have worked.
var    ; --> 33        ; but it really didn't worked.

Well, really, it worked as it should but not as you would have wanted.

(Notice that this effect is a design bug in LISP that was detected in
1960 and corrected in the following years by the introduction of lexical
variables.  emacs lisp is somewhat retrograde (or at least conservator)
on this point).


Anyways, it is a bad idea to try to modify variables from called
functions.


What you really need is to BIND the RESULT of buffer-string and other
functions TO a variable.  This is done with LET:

(let ((string (buffer-substring (point-min) (+ 10 (point-min)))))
  (string= "Newsgroups" string))

--> t


Or, in the improbable case you need to keep a value across functions,
you may store it in a global variables (but global variables should be
avoided as side effects in functions trying to modify them).

(defvar *my-text* "")
(setf *my-text* (buffer-substring (point-min) (+ 10 (point-min))))
*my-text* ; --> #("Newsgroups" 0 10 (fontified t face message-header-name))

Notice that while there's no lexical variables to protect against, I
still think that we should use the *x* convention in emacs lisp for
global variables, so that they're not accidentally shadowed by normal
variables (lexical wanabees) such as the poor var above.


But who I am to say such things, I'm not RMS...
-- 
__Pascal Bourguignon__


reply via email to

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