Permalink
Browse files

fix #3 and #4

  • Loading branch information...
1 parent 4eb3e8d commit 01501d32044a74c1930a02d62f324e7ed036752c @revolunet committed Feb 9, 2012
Showing with 47 additions and 12 deletions.
  1. +11 −2 Default.sublime-commands
  2. +36 −10 MarkdownPreview.py
@@ -1,7 +1,16 @@
[
{
- "caption": "Markdown Preview: Preview Current File",
+ "caption": "Markdown Preview: current file in browser",
"command": "markdown_preview",
- "args": {}
+ "args": {
+ "target": "browser"
+ }
+ },
+ {
+ "caption": "Markdown Preview: current file in Sublime Text",
+ "command": "markdown_preview",
+ "args": {
+ "target": "sublime"
+ }
}
]
View
@@ -3,22 +3,48 @@
import tempfile
import markdown
import os
-import sys
class MarkdownPreviewCommand(sublime_plugin.TextCommand):
""" preview file contents with python-markdown and your web browser"""
- def run(self, edit):
+
+ def getCSS(self):
+ css_filename = 'markdown.css'
+ # path via package manager
+ css_path = os.path.join(sublime.packages_path(), 'Markdown Preview', css_filename)
+ if not os.path.isfile(css_path):
+ # path via git repo
+ css_path = os.path.join(sublime.packages_path(), 'sublimetext-markdown-preview', css_filename)
+ if not os.path.isfile(css_path):
+ raise Exception("markdown.css file not found!")
+
+ return open(css_path, 'r').read()
+
+ def run(self, edit, target='browser'):
+ print edit, target
region = sublime.Region(0, self.view.size())
encoding = self.view.encoding()
if encoding == 'Undefined':
encoding = 'UTF-8'
contents = self.view.substr(region)
- tmp_html = tempfile.NamedTemporaryFile(delete=False, suffix='.html')
- html = markdown.markdown(contents)
- tmp_html.write('<meta charset="%s">' % self.view.encoding())
- styles = open(os.path.join(sublime.packages_path(), 'Markdown Preview', 'markdown.css'), 'r').read()
- tmp_html.write('<style>%s</style>' % styles)
- tmp_html.write(html.encode(encoding))
- tmp_html.close()
- webbrowser.open_new_tab(tmp_html.name)
+
+ # convert the markdown
+ markdown_html = markdown.markdown(contents)
+
+ # build the html
+ html_contents = u'<meta charset="%s">' % self.view.encoding()
+ styles = self.getCSS()
+ html_contents += '<style>%s</style>' % styles
+ html_contents += markdown_html
+
+ # output
+ if target == 'browser':
+ tmp_html = tempfile.NamedTemporaryFile(delete=False, suffix='.html')
+ tmp_html.write(html_contents.encode(encoding))
+ tmp_html.close()
+ webbrowser.open_new_tab(tmp_html.name)
+ elif target == 'sublime':
+ new_view = self.view.window().new_file()
+ new_edit = new_view.begin_edit()
+ new_view.insert(new_edit, 0, html_contents)
+ new_view.end_edit(new_edit)

0 comments on commit 01501d3

Please sign in to comment.