Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions jsonian-tests.el
Original file line number Diff line number Diff line change
Expand Up @@ -858,5 +858,24 @@ If START and END are provided, they are set as point and mark."
(should (eq major-mode 'jsonian-mode))
(remove-hook 'jsonian-edit-string-hook hook-fn))))

(ert-deftest jsonian-special-chars ()
"Test `jsonian--intern-special-chars' and `jsonian--unintern-special-chars' translate properly"
(with-temp-buffer
(mapc (lambda (testcase)
(let ((raw (car testcase))
(escaped (cdr testcase)))
(insert escaped)
(jsonian--unintern-special-chars (current-buffer))
(should (equal (buffer-string) raw))
(jsonian--intern-special-chars (current-buffer))
(should (equal (buffer-string) escaped))
(delete-region (point-min) (point-max))))
'(("\t" . "\\t")
("\n" . "\\n")
("\"" . "\\\"")
("\\" . "\\\\")
("\\\n" . "\\\\\\n"))))
nil)

(provide 'jsonian-tests)
;;; jsonian-tests.el ends here
23 changes: 13 additions & 10 deletions jsonian.el
Original file line number Diff line number Diff line change
Expand Up @@ -1136,10 +1136,13 @@ BUFFER defaults to the current buffer."

(defun jsonian--intern-special-chars (buffer)
"Translates whitespace operators to their ansi equivalents in BUFFER.
This means replacing '\n' with '\\n', '\t' with '\\t'."
This means replacing '\n' with '\\n', '\t' with '\\t', and escaping quotes and backslashes"
(with-current-buffer buffer
(save-excursion
(goto-char (point-min))
(while (search-forward "\\" nil t)
(replace-match "\\\\\\\\"))
(goto-char (point-min))
(while (search-forward "\n" nil t)
(replace-match "\\\\n"))
(goto-char (point-min))
Expand All @@ -1151,18 +1154,18 @@ This means replacing '\n' with '\\n', '\t' with '\\t'."

(defun jsonian--unintern-special-chars (buffer)
"Translate special characters to their unescaped equivalents in BUFFER.
This means replacing '\\n' with '\n' and '\\t' with '\t'."
This means replacing '\\n' with '\n' and '\\t' with '\t' and unescaping escaped characters."
(with-current-buffer buffer
(save-excursion
(goto-char (point-min))
(while (search-forward "\\n" nil t)
(replace-match "\n"))
(goto-char (point-min))
(while (search-forward "\\t" nil t)
(replace-match "\t"))
(goto-char (point-min))
(while (search-forward "\\\"" nil t)
(replace-match "\"")))))
(while (search-forward "\\" nil t)
(let ((c (char-after)))
(delete-region (1- (point)) (1+ (point)))
(insert
(cond
((eql c ?t) ?\t)
((eql c ?n) ?\n)
(t c))))))))

(defun jsonian-edit-mode-return ()
"Jump back from `json-edit-string', actualizing the change made."
Expand Down