Created
November 23, 2012 16:09
-
-
Save nakamuray/4136278 to your computer and use it in GitHub Desktop.
reST リアルタイムでレンダリングする vim script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
python <<EOPython | |
import vim | |
class InstantReST(object): | |
from multiprocessing import Queue | |
queue = Queue() | |
process = None | |
last_rst = None | |
@staticmethod | |
def _process_main(queue): | |
import os, sys | |
# XXX: ignore docutils' warnings | |
sys.stderr = open(os.devnull, 'w') | |
import docutils.core | |
import docutils.writers.html4css1 | |
import threading | |
from gi.repository import GLib | |
from gi.repository import Gtk | |
from gi.repository import WebKit | |
GLib.threads_init() | |
w = Gtk.Window() | |
w.set_size_request(640, 480) | |
webview = WebKit.WebView() | |
w.add(webview) | |
w.connect('destroy', lambda *_: Gtk.main_quit()) | |
w.show_all() | |
def q_watcher(): | |
while True: | |
rst = queue.get() | |
html = docutils.core.publish_string(rst, writer=docutils.writers.html4css1.Writer()) | |
# load string in main thread | |
GLib.idle_add(webview.load_string, html, 'text/html', 'UTF-8', '') | |
threading.Thread(target=q_watcher).start() | |
Gtk.main() | |
@classmethod | |
def start_webview_process(cls): | |
from multiprocessing import Process | |
cls.process = Process(target=cls._process_main, args=(cls.queue, )) | |
cls.process.start() | |
@classmethod | |
def view_rst(cls, rst): | |
if cls.process is None or not cls.process.is_alive(): | |
# FIXME: by unknown reason, second process can't get from queue | |
cls.start_webview_process() | |
cls.queue.put(rst) | |
@classmethod | |
def update_view(cls): | |
rst = '\n'.join(vim.current.buffer[:]) | |
if rst != cls.last_rst: | |
cls.last_rst = rst | |
cls.view_rst(rst) | |
@classmethod | |
def stop_view(cls): | |
if cls.process is not None: | |
# FIXME: process doesn't exit | |
cls.process.terminate() | |
EOPython | |
autocmd CursorMoved,CursorMovedI,CursorHold,CursorHoldI *.rst silent python InstantReST.update_view() | |
autocmd BufWinEnter *.rst silent python InstantReST.update_view() | |
autocmd BufWinLeave *.rst silent python InstantReST.stop_view() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment