Search code examples
elisp

Need to extend elisp function


All,

I must suck at eLisp. Banged this first function out in no time.

(defun sort-lines-reverse (beg end)
  "sort lines in reverse order"
   (interactive
   (if (use-region-p)
       (list (region-beginning) (region-end))
     (list (point-min) (point-max))))
   (if (and beg end)
       (sort-lines 1 beg end))
   )

works perfectly. Hosed this next one

(defun sort-numeric-fields-reverse (field beg end)
  "sort numeric fields in reverse order"
  (interactive
   (if (use-region-p)
       (list (read-number "Field number: " 1) (region-beginning) (region-end))
     (list (read-number "Field number: " 1) (point-min) (point-max)))
   (message "calling if")
   (if (and beg end)
       ((message "inside if")
        (sort-numeric-fields field beg end)
        (reverse-region beg end))
     )
   ))

No runs no hits no errors. Don't see a single message displayed in messages. I do get my field number prompt.

A snippet of randomly generated test data if one so wishes.

8       412086510
8       744308263
8       1482781895
8       995992436
1       1021762533
1       897682569
1       963686690
1       166565707
1       2096612583
1       829723388
1       587753131
1       264251710
32      139885828
32      781244288

Adding insult to injury in my KDE Neon environment the C-M-x to bring up the lisp debugger doesn't do squat.

The only real difference between these two functions is in this one I have to prompt for a field number. Inside the if I run 2 functions instead of one. After getting the first one to work the second should have been a cakewalk.

Help would be appreciated.


Solution

  • Two issues:

    • missing ) at the end of interactive, after (if (use-region-p) ...
    • missing progn in (if (and beg end)... (progn is superfluous because if has been replaced by when.)

    Corrected version:

    (defun sort-numeric-fields-reverse (field beg end)
      "sort numeric fields in reverse order"
      (interactive
       (if (use-region-p)
           (list (read-number "Field number: " 1) (region-beginning) (region-end))
         (list (read-number "Field number: " 1) (point-min) (point-max))))
      (message "calling if")
      (when (and beg end)
        (message "inside if")
        (sort-numeric-fields field beg end)
        (reverse-region beg end)))
    

    EDIT: Code changed: if-progn replaced with when according to hint from @phils.

    Hint: using an adequate editor makes the typing easy and gives you control over parentheses.