Skip to content

Instantly share code, notes, and snippets.

@PhilHudson
Created April 14, 2015 19:30
Show Gist options
  • Save PhilHudson/cf882c673599221d42b2 to your computer and use it in GitHub Desktop.
Save PhilHudson/cf882c673599221d42b2 to your computer and use it in GitHub Desktop.
Shell-escape a string in Elisp
(defun ph/shell-escaper (matched-text)
"Return replacement text for MATCHED-TEXT when shell-escaping.
See `ph/shell-escape'."
(cond
;; Already escaped?
((string= matched-text "\\'")
"’")
;; Leading?
((string= matched-text "'")
"’")
((string-match "\\(.\\)'" matched-text)
(concat
(match-string 1 matched-text)
"’"))
;; TODO whitespace, *, ?, {, }, (, ), [, ]
(t
matched-text)))
(defun ph/shell-escape (string)
"Make STRING safe to pass to a shell command."
(replace-regexp-in-string
".?'"
#'ph/shell-escaper
(replace-regexp-in-string "\n" " " string)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment