Why order of quote character "'" in relation to '#1=' matters in circular lists? - lisp

I am experimenting with circular lists and have written a flawed graph viewer. So when I try to draw 2 different graphs
(graph-viewer:graph '#1=(1 2 3 #1#) "a")
(graph-viewer:graph #1='(1 2 3 #1#) "b")
I get who different pictures with the latter version having a quote symbol included in the graph.

You need to think how the reader does its job.
When it sees #1=, it knows to store whatever comes next and re-use it on #1# - think about it as a "binding" for the "variable 1".
When it sees '<blah>, it reads it as (quote <blah>).
Thus, when it sees '#1=(1 2 3 #1#), it reads it as
(quote (1 2 3 *))
^ |
| |
+------+
(quote is outside of "binding of 1")
while #1='(1 2 3 #1#) is read as
(quote (1 2 3 *))
^ |
| |
+-------------+
(quote is inside the "binding of 1").
The "arrow" in the pics above is the reference, i.e., * points along the arrow.

Related

org--agenda-prefix-format %? does not work

Currently, I have my global TODO list shown as follows thanks to erikstokes:
(org-agenda-prefix-format " %i %?-12(concat \"[ \"(org-format-outline-path (list (nth 1 (org-get-outline-path)))) \" ]\") ")))
which outputs:
for org layout:
However, as you can see, for Task A, even though there is nothing in the project, it still shows up on the list.
describe-variable for org-agenda-prefix-format says :
If the first character after `%' is a question mark, the entire field
will only be included if the corresponding value applies to the current
entry. This is useful for fields which should have fixed width when
present, but zero width when absent.
So I feel like by using %?, [ ] shouldn't be there for Task A, yet it still shows up.
The problem is that the field is never empty: it will always contain at least the left and right square brackets plus the white space to bring it to a width of 12.
The solution is to write a function that returns either an empty string or the bracketed project and use that in the format:
(defun foo ()
(let ((x (nth 1 (org-get-outline-path))))
(if x
(concat "[ " (org-format-outline-path (list x)) " ]")
"")))
(setq org-agenda-prefix-format " %i %?-12(foo) "

How to increment a serie of number on the same row in a configuration file?

Let say I have a configuration file, and each lines contains space separated values. On on the column I have only zeros. Example:
... # there is more configuration before the interesting stuff:
0 0 file /dev/stdin 224.0.68.54:12131
0 0 file /dev/stdin 224.0.68.55:12102
0 0 file /dev/stdin 224.0.68.49:12333
0 0 file /dev/stdin 224.0.68.60:12184
0 0 file /dev/stdin 224.0.68.62:12888
0 0 file /dev/stdin 224.0.68.77:12001
0 0 file /dev/stdin 224.0.68.33:12973
Now I want to increment the second column with its index.
that is I want this result:
0 0 file /dev/stdin 224.0.68.54:12131
0 1 file /dev/stdin 224.0.68.55:12102
0 2 file /dev/stdin 224.0.68.49:12333
0 3 file /dev/stdin 224.0.68.60:12184
0 4 file /dev/stdin 224.0.68.62:12888
0 5 file /dev/stdin 224.0.68.77:12001
0 6 file /dev/stdin 224.0.68.33:12973
How to to that in emacs lisp? Or any other Emacsen way of doing thing please?
You can use the possibility to search and replace by an evaluated expression:
put the point on the first line to process
M-x query-replace-regexp RET
searched string: ^0 \([0-9]+\)
replace with: \,(format "0 %s" (+ \#1 \#))
The meaning is:
search a number preceded by a single zero at the beginning of the line
replace by the result of the evaluation where \#1 is the first matched group (like \1 but converted to number) and \# is the number of replacements already done (begins at 0 for the first replacement). The expression is evaluated for each match.
If the first number is not always a zero, I would use:
searched string: ^\([0-9]+\) \([0-9]+\)
replace with: \,(format "%s %s" \#1 (+ \#2 \#))
You can use a macro with a counter to do that. You start defining a macro with F3 and end the definition with F4. While defining the macro, hitting F3 again will insert the value of the counter and increment it. After defining the macro, run it by hitting F4.
So in your case, move point to the beginning of the first interesting line, hit F3 C-f C-f C-d F3 C-n C-a F4 (i.e. remove the second zero, insert the counter, and move to the beginning of the next line). Then hit F4 as many times as needed to change all the lines.
If you need to change the value of the counter, use M-x kmacro-set-counter.
Similarly to Jonathan Leech-Pepin's answer, you can also use the non-cua rectangle editing commands (albeit in two steps instead of one).
Set mark and point to the corners of the column rectangle
C-xrk to delete the rectangle.
C-uC-xrN to insert a number sequence in its place.
Also see related question:
emacs string-insert-rectangle vector of numbers?
Something you could do using org-mode (I'm not sure of how will you use the result, but this can be one way of doing it)
| N | X | file | stream | ip |
|---+---+------+------------+-------------------|
| 0 | 0 | file | /dev/stdin | 224.0.68.54:12131 |
| 0 | 1 | file | /dev/stdin | 224.0.68.55:12102 |
| 0 | 2 | file | /dev/stdin | 224.0.68.49:12333 |
| 0 | 3 | file | /dev/stdin | 224.0.68.60:12184 |
| 0 | 4 | file | /dev/stdin | 224.0.68.62:12888 |
| 0 | 5 | file | /dev/stdin | 224.0.68.77:12001 |
| 0 | 6 | file | /dev/stdin | 224.0.68.33:12973 |
#+TBLFM: $2=##-2
Some explanation, or rather, how to get your original data and transform it into this table:
Copy your data into file config.org
Create the table by basic string replacement commands. (Just copy the text as you have it now, select all of it and then C-c |)
The #+TBLFM: part is the "formula" for this table, it means the following: assign to every cell in the second column the ordinal of it's row minus 2 (they start counting rows at 1, and this table has a header row).
Whenever you C-c C-c on the formula, it will re-apply it to the table (so you can append more rows as you modify the document, reapplying the formula will automatically update the table.)
You can use cua-set-rectangle-mark.
Evaluate:
(cua-mode 't)
Then in the buffer you can use M-x cua-set-rectangle-mark at the second column then extend the rectangle down to the end of the list.
Then use M-n (sequence), the defaults of Start (0):, Increment (1): and Format (%d): all provide what you need in this case.
Here a very easy way to do this (using the same technique as Seki's answer but easier):
Select all the lines you want the increment to appear in, then issue
M-x replace-regexp "^0 0" "0 \#"
or in more detail:
M-x replace-regexp RET
Searched string: ^0 0
Replace with: 0 \#
This will give you the desired result, because \# replaces to the number of replacements done.
I run into this problem all the time, and I don't enjoy setting up complicated rectangles or macros. So I created an elisp function to do it for me in a single command. I call it...*drumroll*...the downcrementer
Placing your cursor on the second 0 in your example and running M-x downcrementer will sequentially increment all the numbers in the column in one shot.
(defun downcrementer--bounds-of-num-at-point ()
(interactive)
(let (num-start num-end)
(save-excursion
(skip-chars-backward "0-9")
(setq num-start (point)))
(save-excursion
(skip-chars-forward "0-9")
(setq num-end (point)))
(list num-start num-end)))
(defun downcrementer (&optional prefix-arg)
(interactive "P")
(let ((current-number (string-to-number
(apply #'buffer-substring-no-properties
(downcrementer--bounds-of-num-at-point))))
(stride 1)
(orig-truncate-lines truncate-lines))
(when prefix-arg
(setq stride (string-to-number (read-string "Enter stride: "))))
;; Prevent wrapping from causing next-line to go to the wrong place
(toggle-truncate-lines t)
(next-line)
(let ((first-column (current-column)))
(while (thing-at-point 'number t)
(save-excursion
(apply #'delete-region (downcrementer--bounds-of-num-at-point))
(setq current-number (+ current-number stride))
(insert (number-to-string current-number)))
(next-line)
(move-to-column first-column))
(previous-line)
(move-to-column first-column))
;; Restore original truncate-line setting
(toggle-truncate-lines orig-truncate-lines)))

Having a table as result of an org-babel code block in Perl

I have a very simple example to illustrate the problem. Consider the following code block in Perl, in an org-mode file:
#+begin_src perl :results table
return qw(1 2 3);
#+end_src
It produces the following result:
#+results:
| 1\n2\n3\n |
which is not totally satisfactory since I was expecting a full org-table.
For instance, in Python the following code:
#+begin_src python :results table
return (1, 2, 3)
#+end_src
produces this result:
#+results:
| 1 | 2 | 3 |
So that's apparently working in Python but not in Perl. Am I doing something wrong? Is this a known bug?
Since I felt a little masochistic this morning I decided to take a shot at hacking a little lisp again. I cooked up a small fix which works for your example but I can't promise it will work more complex ones. So here it comes:
org-babel defines a wrapper for each language. The perl one did not produce something babel detects as a list so I modified it. In order to not make everything formated as a table I had to check if the result was printable as a table:
(setq org-babel-perl-wrapper-method
"
sub main {
%s
}
#r = main;
open(o, \">%s\");
if ($#r > 0) {
print o \"(\",join(\", \",#r), \")\",\"\\n\"
} else {
print o join(\"\\n\", #r), \"\\n\"
}")
You can modify this further to fit your needs if you want to.
The next thing is that the perl-evaluate method in babel does not run the output through further formating so I modified the evaluate method taking the new parts from the python-evaluate code:
(defun org-babel-perl-table-or-string (results)
"Convert RESULTS into an appropriate elisp value.
If the results look like a list or tuple, then convert them into an
Emacs-lisp table, otherwise return the results as a string."
(org-babel-script-escape results))
(defun org-babel-perl-evaluate (session body &optional result-type)
"Pass BODY to the Perl process in SESSION.
If RESULT-TYPE equals 'output then return a list of the outputs
of the statements in BODY, if RESULT-TYPE equals 'value then
return the value of the last statement in BODY, as elisp."
(when session (error "Sessions are not supported for Perl."))
((lambda (raw)
(if (or (member "code" result-params)
(member "pp" result-params)
(and (member "output" result-params)
(not (member "table" result-params))))
raw
(org-babel-perl-table-or-string (org-babel-trim raw))))
(case result-type
(output (org-babel-eval org-babel-perl-command body))
(value (let ((tmp-file (org-babel-temp-file "perl-")))
(org-babel-eval
org-babel-perl-command
(format org-babel-perl-wrapper-method body
(org-babel-process-file-name tmp-file 'noquote)))
(org-babel-eval-read-file tmp-file))))))
The new parts are org-babel-perl-table-or-string and the part in org-babel-perl-evaluate between the empty lines (plus 1 closing parenthesis at the end).
So what this now does is let perl print lists similar to the way python prints them and put the printed results through org-babel's formating procedures.
Now to the result:
A List:
#+begin_src perl :results value
return qw(1 2 3);
#+end_src
#+results:
| 1 | 2 | 3 |
A scalar:
#+begin_src perl :results value
return "Hello test 123";
#+end_src
#+results:
: Hello test 123
Ways you can use this code:
Place it in scratch and M-x eval-buffer for testing
Place it in a elsip src block at the beginning of your org-document
Place it in your .emacs after babel is loaded
Modify ob-perl.el in your lisp/org folder (might need to recompile org-mode afertwards)
I didn't not tested this much further than the output examples I gave you so if it misbehaves for other examples feel free to complain.

when to quote symbol in Emacs Lisp

I've beginning learning programming with Emacs Lisp. I'm so confused by symbol quotation.
For example:
(progn
(setq a '(1 2))
(prin1 a)
(add-to-list 'a 3)
(prin1 a)
(setcar a 4)
(prin1 a)
(push 5 a)
""
)
why the "add-to-list" function need a quoted symbol as its first argument, while the "setcar" and "push" function need no argument quotation?
Here's a diagram that represents the symbol a and its value after (setq a '(1 2)). The boxes are elementary data structures (symbols and conses) and the arrows are pointers (where a piece of data references another). (I'm simplifying a little.)
symbol cons cons
+-------+----------+ +------+------+ +------+------+
|name: |variable: | |car: |cdr: | |car: |cdr: |
| a | | | | 1 | | | | 2 | nil |
+-------+----|-----+ +------+--|---+ +------+------+
| ​↑ | ↑
+-------------+ +-------+
The expression '(1 2) builds the two conses on the right, which make up a two-element list. The expression (setq a '(1 2)) creates the symbol a if it doesn't exist, then makes its “variable slot” (the part that contains the value of the symbol) point to the newly created list. setq is a built-in macro, and (setq a '(1 2)) is shorthand for (set 'a '(1 2)). The first argument of set is the symbol to modify and the second argument is the value to set the symbol's variable slot to.
(add-to-list 'a 3) is equivalent to (set 'a (cons 3 a)) here, because 3 is not in the list. This expression does four things:
Create a new cons cell.
Set the new cons cell's car field to 3.
Set the new cons cell's cdr field to the former (and still current) value of a (i.e. copy the contents of a's variable slot).
Set the variable slot of a to the new cons cell.
After that call, the data structures involved look like this:
symbol cons cons cons
+-------+----------+ +------+--|---+ +------+------+ +------+------+
|name: |variable: | |car: |cdr: | |car: |cdr: | |car: |cdr: |
| a | | | | 3 | | | | 1 | | | | 2 | nil |
+-------+----|-----+ +------+--|---+ +------+--|---+ +------+------+
| ​↑ | ↑ | ↑
+-------------+ +-------+ +-------+
The call to setcar doesn't create any new data structure, and doesn't act on the symbol a but on its value, which is the cons cell whose car currently contains 3. After (setcar a 4), the data structures look like this:
symbol cons cons cons
+-------+----------+ +------+--|---+ +------+------+ +------+------+
|name: |variable: | |car: |cdr: | |car: |cdr: | |car: |cdr: |
| a | | | | 4 | | | | 1 | | | | 2 | nil |
+-------+----|-----+ +------+--|---+ +------+--|---+ +------+------+
| ​↑ | ↑ | ↑
+-------------+ +-------+ +-------+
push is a macro; here, (push 5 a) is equivalent to (set 'a (cons 5 a)).
setq and push are macros (setq is a “special form”, which as far as we're concerned here means a macro whose definition is built into the interpreter and not provided in Lisp). Macros receive their arguments unevaluated and can choose to expand them or not. set, setcar and add-to-list are functions, which receive their arguments evaluated. Evaluating a symbol returns the contents of its variable slot, e.g. after the initial (setq a '(1 2)) the value of the symbol a is the cons cell whose car contains 1.
If you're still confused, I suggest experimenting with (setq b a) and seeing for yourself which of the expressions modify b when you act on a (the ones that act on the symbol a) and which don't (the ones that act on the value of the symbol a).
Functions evaluate their arguments before execution, so quote when you need to pass an actual symbol (as pointer to some data structure, for example) and don't quote when it's a variable value.
add-to-list performs in-place mutation of its first argument, so it needs a quoted symbol.
push is not a function, but a macro; that is why it's able to accept unquoted arguments without evaluation. Builtin forms, like setcar, also do not have that limitation.
The other answers given so far clarify the use of quote and the difference between functions, on the one hand, and macros and special forms on the other hand.
However, they do not get to another part of the question: why is add-to-list as it is? Why does it require its first argument to be a symbol? That's a separate question from whether or not it evaluates the argument. It's the real question behind the design of add-to-list.
One could imagine that add-to-list evaluated its args, and expected the value of the first arg to be a list, and then added the value of the second arg to that list as an element and returned the result (new list or same list). That would let you do (add-to-list foo 'shoe) to add the symbol shoe to the list that is the value of foo -- say (1 2 buckle) --, to give (1 2 buckle shoe).
The point is that such a function would not be very useful. Why? Because the list value isn't necessarily accessible. The variable foo might be thought of as a way to access it -- a "handle" or "pointer" to it. But that is not true of the list that the function returns. That returned list can be composed of new list structure, and there is typically nothing (no variable) pointing to that list. The function add-to-list never sees the symbol (variable) foo -- it has no way of knowing that the list value it receives as first argument is bound to foo. If add-to-list were designed that way then you would still need to assign its returned result to your list variable.
IOW, add-to-list evaluates its args because it is a function, but that doesn't explain much. It expects a symbol as the value of its first arg. And it expects the value of that variable (symbol) to be a list. It adds the value of its second arg to the list (possibly changing the list structure), and it sets the value of the variable that is the value of its first arg to that list.
Bottom line: It needs a symbol as arg because its job is to assign a new value to that symbol (the new value being the same list value or the same value with the new list element added at the front).
And yes, another way to go would be to use a macro or special form, as in push. It's the same idea: push wants a symbol as its second arg. The difference is that push does not evaluate its args so the symbol need not be quoted. But in both cases (in Emacs Lisp) the code needs to get hold of a symbol in order to set its value to the augmented list.

What's the corresponding standard function of atoi in clisp?

In visual lisp, you can use (atoi "123") to convert "123" to 123. It seems there is no "atoi" like function in clisp ?
any suggestion is appreciated !
Now i want to convert '(1 2 3 20 30) to "1 2 3 20 30", then what's the best way to do it ?
parse-interger can convert string to integer, and how to convert integer to string ? Do i need to use format function ?
(map 'list #'(lambda (x) (format nil "~D" x)) '(1 2 3)) => ("1" "2" "3")
But i donot know how to cnovert it to "1 2 3" as haskell does:
concat $ intersperse " " ["1","2","3","4","5"] => "1 2 3 4 5"
Sincerely!
In Common Lisp, you can use the read-from-string function for this purpose:
> (read-from-string "123")
123 ;
3
As you can see, the primary return value is the object read, which in this case happens to be an integer. The second value—the position—is harder to explain, but here it indicates the next would-be character in the string that would need to be read next on a subsequent call to a reading function consuming the same input.
Note that read-from-string is obviously not tailored just for reading integers. For that, you can turn to the parse-integer function. Its interface is similar to read-from-string:
> (parse-integer "123")
123 ;
3
Given that you were asking for an analogue to atoi, the parse-integer function is the more appropriate choice.
Addressing the second part of your question, post-editing, you can interleave (or "intersperse") a string with the format function. This example hard-codes a single space character as the separating string, using the format iteration control directives ~{ (start), ~} (end), and ~^ (terminate if remaining input is empty):
> (format nil "Interleaved: ~{~S~^ ~}." '(1 2 3))
"Interleaved: 1 2 3."
Loosely translated, the format string says,
For each item in the input list (~{), print the item by its normal conversion (~S). If no items remain, stop the iteration (~^). Otherwise, print a space, and then repeat the process with the next item (~}).
If you want to avoid hard-coding the single space there, and accept the separator string as a separately-supplied value, there are a few ways to do that. It's not clear whether you require that much flexibility here.