Sublime Forum

How to automatically add "end" to code blocks?

#1

Love Sublime 2. Thank you!

Working in Ruby on Rails.

How can I have it automatically add “end” when starting a block such as begin, do, if, etc? I gather there is a plug-in, but didn’t find it.

Thanks!

0 Likes

#2

Just make a snippet.

0 Likes

#3

I haven’t found a way to have blocks automatically balanced, but I came up with a pretty good key binding that gets 90% of the way there. It will automatically insert “end” when you press “command+enter” after typing syntax that should be closed with “end” (“class”, “module”, “def”, “do”, “if” and “begin”). The one drawback is that it doesn’t detect if there’s already a balanced “end”, so doing it twice will create an extra “end”. This really isn’t a big deal if you’re paying attention though.

Just add the following to the array in “Packages/Ruby/Default.sublime-keymap”:

  { "keys": "command+enter"],
    "command": "insert_snippet",
    "args": {"contents": "\n\t$0\nend"},
    "context": 
      { "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
      { "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
      {
        "key": "preceding_text",
        "operator": "regex_contains",
        "operand": "^\\s*((class|module|def) .+|(.+ )?begin|.+ do( .+)?|if .+)$",
        "match_all": true
      },
      { "key": "following_text", "operator": "regex_match", "operand": "^$", "match_all": true }
    ]
  }
0 Likes

#4

I have found these snippets by Michael Hartl to be very friendly:
github.com/mhartl/rails_tutorial_snippets

0 Likes