Skip to content

Instantly share code, notes, and snippets.

@ebello
Created December 13, 2011 16:08
Show Gist options
  • Save ebello/1472704 to your computer and use it in GitHub Desktop.
Save ebello/1472704 to your computer and use it in GitHub Desktop.
TextMate: Convert HTML document to Entities
1. Show Bundle Editor in TextMate
2. Create new command under HTML called "Convert Selection to Entities"
3. Paste code in command.rb, and set the following options:
- Save: Nothing
- Input: Selected Text or Document
- Output: Replace Selected Text
- Activation: Key Equivalent: command+&
- Scope Selector: text.html
#!/usr/bin/env ruby
$KCODE = 'U'
def encode (text)
text.gsub(/[^\x00-\x7F]|["'<>&]/) do |ch|
sprintf("&#%d;", ch.unpack("U")[0])
end
end
STDIN.read.scan(/(?x)
( <\?(?:[^?]*|\?(?!>))*\?>
| <!-- (?m:.*?) -->
| <\/? (?i:a|abbr|address|area|article|aside|audio|b|base|bdo|big|blockquote|body|br|button|canvas|caption|cite|code|col|colgroup|command|datalist|dd|del|details|dfn|div|dl|dt|em|embed|fieldset|figure|figcaption|footer|form|h1|h2|h3|h4|h5|h6|head|header|hgroup|hr|html|i|iframe|img|input|ins|kbd||keygen|label|legend|li|link|map|mark|menu|meta|meter|nav|noscript|object|ol|optgroup|option|output|p|param|pre|progress|q|rp|rt|ruby|s|samp|section|script|select|small|source|span|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|u|ul|var|video|wbr)\b
(?:[^>"']|"[^"]*"|'[^']*')*
>
| &(?:[a-zA-Z0-9]+|\#[0-9]+|\#x[0-9a-fA-F]+);
)
|([^<&]+|[<&])
/x) do |tag, text|
print tag.to_s, encode(text.to_s)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment