Swap parentheses and square brackets in Emacs Paredit

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


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

     (a (b)

    into this:

     [a (b)

    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 [..]."
      (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."
      (paredit-open-square 1)
      (right-char 1)
      (left-char 1))