Repeated calls to format ignore the ~t option - lisp

I have this:
(defun promptread (prompt)
(format *query-io* "~10t~a:" prompt)
(force-output *query-io*)
(read-line *query-io*))
(defun prompt-cd ()
(make-cd
(promptread "Artist")
(promptread "Album")
(promptread "Rating")
(promptread "Like [y/n]")))
It works, however the format ~10t only affects the first call to promptread inside make-cd; the others are left-aligned without this padding.
Why would this be?
REPL:
CL-USER> (addcds)
Artist:Dixie
Album:Funny
Rating:22
The first promptread is indented because of the format with ~10t but not the others, which use the same exact format call.

The problem is that after force-output and readline, the cursor is not known to formatto be at position 0. Thus absolute tabulation will fail. If you start the format string with ~&, you will see this as an additional newline will be outputted anyway.
To solve the problem use the # modifier to get relative tabulation:
(format *query-io* "~10#t~a:" prompt)

Related

Lisp string formatting with named parameters

Is there a way in Lisp to format a string using named parameters?
Perhaps something with association lists like
(format t "All for ~(who)a and ~(who)a for all!~%" ((who . "one")))
in order to print "All for one and one for all".
Similar to this python question, or this scala one, or even c++, but in Lisp.
If this functionality isn't in the language, does anyone have any cool functions or macros that could accomplish the same thing?
Use CL-INTERPOL.
(cl-interpol:enable-interpol-syntax)
String interpolation
For simple cases, you don't need FORMAT:
(lambda (who) #?"All for $(who) and $(who) for all!")
Then:
(funcall * "one")
=> "All for one and one for all!"
Interpret format directives
If you need to format, you can do:
(setf cl-interpol:*interpolate-format-directives* t)
For example, this expression:
(let ((who "one"))
(princ #?"All for ~A(who) and ~S(who) for all!~%"))
... prints:
All for one and "one" for all!
If you are curious, the above reads as:
(LET ((WHO "one"))
(PRINC
(WITH-OUTPUT-TO-STRING (#:G1177)
(WRITE-STRING "All for " #:G1177)
(FORMAT #:G1177 "~A" (PROGN WHO))
(WRITE-STRING " and " #:G1177)
(FORMAT #:G1177 "~S" (PROGN WHO))
(WRITE-STRING " for all!" #:G1177))))
Alternate reader function
Previously, I globally set *interpolate-format-directives*, which interprets format directive in all interpolated strings.
If you want to control precisely when format directives are interpolated, you can't just bind the variable temporarily in your code, because the magic happens at read-time. Instead, you have to use a custom reader function.
(set-dispatch-macro-character
#\#
#\F
(lambda (&rest args)
(let ((cl-interpol:*interpolate-format-directives* t))
(apply #'cl-interpol:interpol-reader args))))
If I reset the special variable to its default value NIL, then strings where directives are formatted are prefixed with #F, whereas normal interpolated ones use the #? syntax. If you want to change readtables, have a look at named readtables.

Emacs24 and python-mode: indention in docstrings

I have the following code/text:
def f():
"""
Return nothing.
.. NOTE::
First note line
second note line
In Emacs23 (23.4.1) I was able to press TAB in the last line ("second note line"; nomatter how this line was indented) and it was aligned correctly like this:
def f():
"""
Return nothing.
.. NOTE::
First note line
second note line
I.e., it uses the previous line and indents the following line in the same way.
Now in Emacs24 (24.3.1) this does not work anymore and it is aligned like this:
def f():
"""
Return nothing.
.. NOTE::
First note line
second note line
I.e. it aligns the multi-line string block, but does not depend on the previous line.
It affects only docstrings; code is indented as I want. I am using python-mode. How can I change this, so that pressing TAB aligns the block correctly?
Python mode has changed quite a bit between Emacs 23 and 24. There is no configuration that would allow you to do what you want.
But, Emacs is quite flexible and you can advise the (python-indent-context) function to make it return a different result that will lead to the behavior you want. The function (python-indent-context) returns a character at which the indentation is measured and used for indenting the current line. By default, when inside a string, it returns the point where the beginning of the string resides. Thus, your line will be indented to the indentation of the start of the string. We can easily modify it to return a point in the previous non-empty line instead, for instance like this:
(defun python-fake-indent-context (orig-fun &rest args)
(let ((res (apply orig-fun args))) ; Get the original result
(pcase res
(`(:inside-string . ,start) ; When inside a string
`(:inside-string . ,(save-excursion ; Find a point in previous non-empty line
(beginning-of-line)
(backward-sexp)
(point))))
(_ res)))) ; Otherwise, return the result as is
;; Add the advice
(advice-add 'python-indent-context :around #'python-fake-indent-context)
The same effect can be achieved using the old defadvice for older Emacs:
(defadvice python-indent-context (after python-fake-indent-context)
(pcase ad-return-value
(`(:inside-string . ,start) ; When inside a string
(setq ad-return-value ; Set return value
`(:inside-string . ,(save-excursion ; Find a point in previous non-empty line
(beginning-of-line)
(backward-sexp)
(point)))))))
(ad-activate 'python-indent-context)
What about editing the section de-stringified in a separate buffer? That would allow python-mode with all its facilities.
Here a first draft - original string will be stored in kill-ring:
(defun temp-edit-docstring ()
"Edit docstring in python-mode. "
(interactive "*")
(let ((orig (point))
(pps (parse-partial-sexp (point-min) (point))))
(when (nth 3 pps)
(let* (;; relative position in string
(relpos (- orig (+ 2 (nth 8 pps))))
(beg (progn (goto-char (nth 8 pps))
(skip-chars-forward (char-to-string (char-after)))(push-mark)(point)))
(end (progn (goto-char (nth 8 pps))
(forward-sexp)
(skip-chars-backward (char-to-string (char-before)))
(point)))
(docstring (buffer-substring beg end)))
(kill-region beg end)
(set-buffer (get-buffer-create "Edit docstring"))
(erase-buffer)
(switch-to-buffer (current-buffer))
(insert docstring)
(python-mode)
(goto-char relpos)))))
When ready, copy the contents back into original buffer.
Which remains to be implemented still.

print only text discarding text properties

I have the following function to print the line where point is to the *scratch* buffer,
(defun print-line ()
(print (thing-at-point 'line) (get-buffer "*scratch*")))
but it prints even the fontified info like this
#(" OFFICE
" 0 2 (fontified t org ...
How to discard the printing of the fontified info.
To expand on Daimrod's mention of buffer-substring-no-properties...
M-x apropos RET no-properties RET
buffer-substring-no-properties
Function: Return the characters of part of the buffer, without the
text properties.
field-string-no-properties
Function: Return the contents of the field around POS, without text
properties.
insert-buffer-substring-no-properties
Function: Insert before point a substring of BUFFER, without text
properties.
match-string-no-properties
Function: Return string of text matched by last search, without text
properties.
minibuffer-contents-no-properties
Function: Return the user input in a minibuffer as a string, without
text-properties.
substring-no-properties
Function: Return a substring of STRING, without text properties.
You can read about text properties in the manual:
M-: (info "(elisp) Text Properties") RET
I needed something similar for eredis when manipulating strings from an org-table. You can use `set-text-properties' to get rid of them when displaying the string.
(defun strip-text-properties(txt)
(set-text-properties 0 (length txt) nil txt)
txt)
(defun print-line ()
(print (strip-text-properties
(thing-at-point 'line))
(get-buffer "*scratch*")))
I've tried some things but it's weird, I don't really understand how text properties work.
For example:
(type-of (thing-at-point 'line)) => string
As you've said if one tries to print it, the properties are printed as well, but if one tries to insert it:
(insert (format "%s" (thing-at-point 'line)))
Only the string is printed, not the properties.
So it seems to me that those properties are just bound to the string but you can manipulate the string as usual:
(lenght (thing-at-point 'line))
(substring (thing-at-point 'line) 0 2)
However, if all you want is the line, and the line only you can use buffer-substring-no-properties:
(defun print-line ()
(print (buffer-substring-no-properties (point-at-bol) (point-at-eol))))

Treating the values from a list of slots and strings

I want to do a macro in common lisp which is supposed to take in one of its arguments a list made of slots and strings. Here is the prototype :
(defclass time-info ()
((name :initarg name)
(calls :initarg calls)
(second :initarg second)
(consing :initarg consing)
(gc-run-time :initarg gc-run-time)))
(defun print-table (output arg-list time-info-list) ())
The idea is to print a table based on the arg-list which defines its structure. Here is an example of a call to the function:
(print-table *trace-output*
'("|" name "||" calls "|" second "\")
my-time-info-list)
This print a table in ascII on the trace output. The problem, is that I don't know how to explicitely get the elements of the list to use them in the different parts of my macro.
I have no idea how to do this yet, but I'm sure it can be done. Maybe you can help me :)
I would base this on format. The idea is to build a format string
from your arg-list.
I define a helper function for that:
(defun make-format-string-and-args (arg-list)
(let ((symbols ()))
(values (apply #'concatenate 'string
(mapcar (lambda (arg)
(ctypecase arg
(string
(cl-ppcre:regex-replace-all "~" arg "~~"))
(symbol
(push arg symbols)
"~a")))
arg-list))
(nreverse symbols))))
Note that ~ must be doubled in format strings in order to escape them.
The printing macro itself then just produces a mapcar of format:
(defmacro print-table (stream arg-list time-info-list)
(let ((time-info (gensym)))
(multiple-value-bind (format-string arguments)
(make-format-string-and-args arg-list)
`(mapcar (lambda (,time-info)
(format ,stream ,format-string
,#(mapcar (lambda (arg)
(list arg time-info))
arguments)))
,time-info-list)))
You can then call it like this:
(print-table *trace-output*
("|" name "||" calls "|" second "\\")
my-time-info-list)
Please note the following errors in your code:
You need to escape \ in strings.
Second is already a function name exported from the common-lisp
package. You should not clobber that with a generic function.
You need to be more precise with your requirements. Macros and Functions are different things. Arrays and Lists are also different.
We need to iterate over the TIME-INFO-LIST. So that's the first DOLIST.
The table has a description for a line. Each item in the description is either a slot-name or a string. So we iterate over the description. That's the second DOLIST. A string is just printed. A symbol is a slot-name, where we retrieve the slot-value from the current time-info instance.
(defun print-table (stream line-format-description time-info-list)
(dolist (time-info time-info-list)
(terpri stream)
(dolist (slot-or-string line-format-description)
(princ (etypecase slot-or-string
(string slot-or-string)
(symbol (slot-value time-info slot-or-string)))
stream))))
Test:
> (print-table *standard-output*
'("|" name "||" calls "|" second "\\")
(list (make-instance 'time-info
:name "foo"
:calls 100
:second 10)
(make-instance 'time-info
:name "bar"
:calls 20
:second 20)))
|foo||100|10\
|bar||20|20\
First, you probably don't want the quote there, if you're using a macro (you do want it there if you're using a function, however). Second, do you want any padding between your separators and your values? Third, you're probably better off with a function, rather than a macro.
You also seem to be using "array" and "list" interchangeably. They're quite different things in Common Lisp. There are operations that work on generic sequences, but typically you would use one way of iterating over a list and another to iterate over an array.

Why might the Emacs "downcase" function refuse to do downcasing?

I'm trying to write simple Emacs function to convert ids between C style ones and camelCase ones (i.e. c_style <-> cStyle). But for some reason, Emacs built in downcase function leaves the word intact. M-x downcase-word works fine so I completely lost. Any ideas are welcome.
(defun toggle-id-style ()
"Toggle between C-style ids and camel Case ones (i.e. c_style_id -> cStyleId and back)."
(interactive)
(save-excursion
(progn
(re-search-forward "[^A-Za-z0-9_]" nil t)
(let ((end (point))
(case-fold-search nil))
(progn
(re-search-backward "[^A-Za-z0-9_]" nil t)
(let* ((cstyle (if (string-match "_" (buffer-substring-no-properties (point) end)) t nil))
(regexp (if cstyle "_\\(\\w+\\)" "\\([A-Z][a-z0-9]+\\)") )
(func (if cstyle 'capitalize (lambda (s) (concat "_" (downcase s) ) ))))
(progn
(while (re-search-forward regexp end t)
(replace-match (funcall func (match-string 1)) nil nil)))))))))
;;M-x replace-regexp _\(\w+\) -> \,(capitalize \1) ;; c_style -> cStyle
;;M-x replace-regexp \([A-Z][a-z0-9]+\) -> _\,(downcase \1) ;;cStyle -> c_style
It works fine if I convert c_style but when I'm trying to convert cStyle I got c_Style as result. Yes, I've checked that this is due to downcase behaviour.
Your problem is the second argument to replace-match. From the documentation:
If second arg fixedcase is non-nil, do not alter case of replacement text.
Otherwise maybe capitalize the whole text, or maybe just word initials,
based on the replaced text.
If the replaced text has only capital letters
and has at least one multiletter word, convert newtext to all caps.
Otherwise if all words are capitalized in the replaced text,
capitalize each word in newtext.
You're passing nil for the fixedcase argument, which causes replace-match to capitalize the replacement when the text being replaced is capitalized. Pass t instead and this bit of the code will work.
I have two general comments about your code.
All of your uses of progn are unnecessary. The body of save-excursion is an implicit progn and so are the bodies of let and let*.
You search forwards and then backwards to try to find the bounds of the symbol underneath point. Emacs already has a thingatpt library to find things at or near the point. In your case you can just call (bounds-of-thing-at-point 'symbol) which returns a cons cell (START . END) giving the start and end positions of the symbol that was found.
I think you need the second arg of replace-match to be t instead of nil.