Add ruby stuff
[emacs.git] / .emacs.d / elisp / local / ruby-hash-syntax.el
1 ;;; ruby-hash-syntax.el --- Toggle ruby hash syntax between classic and 1.9 styles
2
3 ;; Copyright (C) 2013 Steve Purcell
4
5 ;; Author: Steve Purcell <steve@sanityinc.com>
6 ;; Version: DEV
7 ;; URL: https://github.com/purcell/ruby-hash-syntax
8 ;; Keywords: languages
9
10 ;; This program is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; This program is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; Adapted from the method used by TextMate, this library provides
26 ;; a command `ruby-hash-syntax-toggle' which attempts to automatically
27 ;; convert the selected region of ruby code between 1.8 and 1.9 hash styles.
28
29 ;;; Code:
30
31 ;; Borrowed from https://github.com/textmate/ruby.tmbundle/blob/master/Commands/Convert%20Ruby%20hash%20to%201_9%20syntax.tmCommand
32
33 ;;;###autoload
34 (defun ruby-toggle-hash-syntax (beg end)
35 "Toggle syntax of ruby hash literal in region from BEG to END between ruby 1.8 and 1.9 styles."
36 (interactive "r")
37 (save-excursion
38 (let ((limit (copy-marker (max beg end))))
39 (goto-char (min beg end))
40 (cond
41 ((ruby-hash-syntax--code-has-pattern "=>" limit)
42 (ruby-hash-syntax--replace ":\\([a-zA-Z0-9_]+\\) *=> *" "\\1: " limit))
43 ((ruby-hash-syntax--code-has-pattern "\\w+:" limit)
44 (ruby-hash-syntax--replace "\\([a-zA-Z0-9_]+\\):\\( *\\(?:\"\\(?:\\\"\\|[^\"]\\)*\"\\|'\\(?:\\'\\|[^']\\)*'\\|[a-zA-Z0-9_]+([^)]*)\\|[^,]+\\)\\)" ":\\1 =>\\2" limit))))))
45
46 (defun ruby-hash-syntax--code-has-pattern (pat limit)
47 "A version of `search-forward' which skips over string literals.
48 Argument PAT is the search patter, while LIMIT is the maximum
49 search extent."
50 (let (found)
51 (save-excursion
52 (while (and (not found) (re-search-forward pat limit t))
53 (unless (elt (syntax-ppss) 3)
54 ;; If this isn't inside a string...
55 (setq found t))))
56 found))
57
58 (defun ruby-hash-syntax--replace (from to end)
59 "Replace FROM with TO up to END."
60 (while (re-search-forward from end t)
61 (replace-match to nil nil)))
62
63
64 (provide 'ruby-hash-syntax)
65 ;;; ruby-hash-syntax.el ends here