Search code examples
emacselispparedit

Swap parentheses and square brackets in Emacs Paredit


How can I define a command in paredit mode that swaps parentheses and square brackets?


Solution

  • So the task is to turn this, for example:

    (blah
     (a (b)
        c))
    

    into this:

    (blah
     [a (b)
        c])
    

    With paredit mode, move to start of the expression (a ..) and then:

    C-M-SPC [ <right> M-s
    

    Without paredit, but still wanting to maintain balanced parens during transitions, move to a and then press C-M-SPC multiple times until error and then (assuming that CUA mode is on):

    C-x <timeout> <right> <backspace> <backspace> [ ] <left> C-v
    

    Well that is complex, so let's stick with paredit mode version, and try to make a command out of it. Keyboard Macro Editor tells you the names of commands being used, so you would be able to come up with at least the following code:

    (defun my-switch-to-square ()
      "Change (..) to [..]."
      (interactive)
      (mark-sexp --)
      (paredit-open-square --)
      (right-char --)
      (paredit-splice-sexp --))
    

    -- indicates part of code we have not yet decided. After you read documentation of each function in the code, you learn what arguments to pass, and that there is no need to call mark-sexp. After rewriting docstring and adding a call to left-char, the code you end up with would be:

    (defun my-switch-to-square ()
      "Change |(..) to |[..]. | is point position."
      (interactive)
      (paredit-open-square 1)
      (right-char 1)
      (paredit-splice-sexp)
      (left-char 1))