22

In Elisp I have introduced for a special custom mode a variable like:

(defvar leo-special-var "")
(make-variable-buffer-local 'leo-special-var)

Now I set this variable in files I with the lines (in the file to edit):

# Local Variables:
# leo-special-var: "-d http://www.google.com.au"
# End:

And I want to consider this variable as "safe for all its values. That's why safe-local-variable-values doesn't help. Instead I tried (in the lisp code):

# setting the symbol property of the variable
(put 'leo-special-var 'safe-local-variable 'booleanp)

but without success. Do I do something wrong when setting the symbol property? Or is there another way?

halloleo
  • 9,216
  • 13
  • 64
  • 122

3 Answers3

27

You want to use

(put 'leo-special-var 'safe-local-variable #'stringp)

to say that it is safe as long as it's a string.

Stefan
  • 27,908
  • 4
  • 53
  • 82
16

If you really want to state that it is safe for all values then use this:

(put 'leo-special-var 'safe-local-variable (lambda (_) t))

The function to test safety here returns non-nil for any value.

(But I'd think that you probably do not want to state that a variable is safe for any value.)

Drew
  • 29,895
  • 7
  • 74
  • 104
  • 2
    This is not what I *wanted* (I wanted a solution making it only safe for strings), but it is what I *asked* for. Good on you, @Drew! – halloleo Nov 07 '13 at 00:06
  • I'd recommend against using this because it's erring on the unsafe side. – Stefan Sep 10 '18 at 14:35
  • @stefan: I recommended against it also. But the question was how to do it. – Drew May 15 '20 at 23:14
5

It's in the manual: (elisp) File Local Variables

   You can specify safe values for a variable with a
`safe-local-variable' property.  The property has to be a function of
one argument; any value is safe if the function returns non-`nil' given
that value.  Many commonly-encountered file variables have
`safe-local-variable' properties; these include `fill-column',
`fill-prefix', and `indent-tabs-mode'.  For boolean-valued variables
that are safe, use `booleanp' as the property value.  Lambda
expressions should be quoted so that `describe-variable' can display
the predicate.

   When defining a user option using `defcustom', you can set its
`safe-local-variable' property by adding the arguments `:safe FUNCTION'
to `defcustom' (*note Variable Definitions::).
phils
  • 71,335
  • 11
  • 153
  • 198
  • 2
    I know of this documentation, but I don't understand it fully: Should I replace `'boleanp` withn `stringp`, because `leo-special-var`myvariable is a string variable? – halloleo Nov 06 '13 at 12:49
  • Yes, `stringp` would be what you need. If you check the help for `booleanp` you'll see that it returns `t` *only* for the values `t` and `nil`, so it would have returned `nil` for all the values you used, thus indicating that they were not safe. – phils Nov 06 '13 at 13:53