Skip to content

Commit

Permalink
Complete refactoring (PythonConsole plugin as example)
Browse files Browse the repository at this point in the history
  • Loading branch information
bittner committed Jan 11, 2015
1 parent 9a6ce4d commit 15cce67
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 233 deletions.
4 changes: 2 additions & 2 deletions README.rst
Expand Up @@ -27,12 +27,12 @@ Installation
``git checkout gedit-3.12``).

:gedit-3.8: 3.8 <= gedit < to 3.12
:gedit-3.12: gedit >= 3.12
:gedit-3.14: gedit >= 3.12

- Put ``reST.plugin`` file in gedit's plugins directory.
The standard one should be ``~/.local/share/gedit/plugins/``. Alternatively,
the global directory is something like ``/usr/lib/gedit/plugins/`` or
``/usr/lib/i386-linux-gnu/gedit/plugins/``.
``/usr/lib/<architecture>-linux-gnu/gedit/plugins/``.

- Copy the whole ``reST`` folder into the same directory.

Expand Down
6 changes: 4 additions & 2 deletions reST.plugin
@@ -1,8 +1,10 @@
[Plugin]
Loader=python3
Module=reST
IAge=3
Name=reStructuredText Preview
Description=Preview panel for reStructuredText (.rst)
Authors=Christophe Kibleur <kib2@free.fr>;Matěj Cepl <mcepl@cepl.eu>;Peter Bittner <django@bittner.it>;François Poirotte
Copyright=Copyright © 2008 Christophe Kibleur <kib2@free.fr>
Authors=Peter Bittner <django@bittner.it>;Christophe Kibleur <kib2@free.fr>;Matěj Cepl <mcepl@cepl.eu>;François Poirotte
Copyright=Copyright © 2015 Peter Bittner
Website=https://github.com/bittner/gedit-reST-plugin
Version=3.14.0
250 changes: 21 additions & 229 deletions reST/__init__.py
@@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-

# restPlugin - HTML preview of reST formatted text in gedit
# __init__.py - HTML preview for reStructuredText (.rst) plugin
#
# Copyright (C) 2007 - Christophe Kibleur
# Copyright (C) 2015 - Peter Bittner
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
Expand All @@ -15,248 +15,40 @@
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# along with this program; if not, see <http://www.gnu.org/licenses/>.

from docutils.core import publish_parts
from gi.repository import Gedit, GObject, Gtk, WebKit
from gettext import gettext as _
#from makeTable import toRSTtable
#import RegisterPygment
import os
from gi.repository import GObject, Gtk, Gedit, Peas, PeasGtk, WebKit

from .restructuredtext import RestructuredtextHtmlPanel
# from .config import RestructuredtextConfigWidget

# Menu item example, insert a new item in the Tools menu
ui_str = """<ui>
<menubar name="MenuBar">
<menu name="ToolsMenu" action="Tools">
<separator/>
<placeholder name="ToolsOps_6">
<menuitem name="preview" action="preview"/>
</placeholder>
<placeholder name="ToolsOps_6">
<menuitem name="table" action="table"/>
</placeholder>
<placeholder name="ToolsOps_6">
<menuitem name="sourcecode" action="sourcecode"/>
</placeholder>
<placeholder name="ToolsOps_6">
<menuitem name="--> HTML" action="--> HTML"/>
</placeholder>
<placeholder name="ToolsOps_6">
<menuitem name="--> LaTeX" action="--> LaTeX"/>
</placeholder>
<placeholder name="ToolsOps_6">
<menuitem name="--> LibreOffice" action="--> LibreOffice"/>
</placeholder>
<separator/>
</menu>
</menubar>
</ui>
"""

class ReStructuredTextPlugin(GObject.Object, Gedit.WindowActivatable, PeasGtk.Configurable):
__gtype_name__ = "ReStructuredTextPlugin"

class restPlugin(GObject.Object, Gedit.WindowActivatable):
__gtype_name__ = "reStructuredTextPlugin"
window = GObject.property(type=Gedit.Window)

def __init__(self):
GObject.Object.__init__(self)

self.restplugin_dir = os.path.dirname(os.path.abspath(__file__))
css_file = os.path.join(self.restplugin_dir, 'restmain.css')
with open(css_file, 'r') as styles:
self.START_HTML = """<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Language" content="English">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
%s
</style>
</head>
<body>""" % styles.read()
self.END_HTML = """</body>
</html>
"""
self.html_window = None

def do_activate(self):
## TODO : Maybe have to check the filetype ?

# Store data in the window object
windowdata = dict()
self.window.reStPreviewData = windowdata

scrolled_window = Gtk.ScrolledWindow()
scrolled_window.set_property("hscrollbar-policy",
Gtk.PolicyType.AUTOMATIC)
scrolled_window.set_property("vscrollbar-policy",
Gtk.PolicyType.AUTOMATIC)
scrolled_window.set_property("shadow-type",
Gtk.ShadowType.IN)

html_view = WebKit.WebView()
html_view.load_string("%s\n<p>reStructuredText Viewer</p>\n%s" %
(self.START_HTML, self.END_HTML), 'text/html', 'utf8', '')

#scrolled_window.set_hadjustment(html_view.get_hadjustment())
#scrolled_window.set_vadjustment(html_view.get_vadjustment())
scrolled_window.add(html_view)
scrolled_window.show_all()

self.html_window = RestructuredtextHtmlPanel()
self.html_window.update_view()
bottom = self.window.get_bottom_panel()
bottom.add_titled(scrolled_window, "rest-preview", "reStructuredText Preview")
windowdata["bottom_panel"] = scrolled_window
windowdata["html_doc"] = html_view

manager = self.window.get_ui_manager()

## Added later
self._action_group = Gtk.ActionGroup("reStPluginActions")
self._action_group.add_actions([("preview", None, _("reStructuredText Preview"),
"<Control><Shift>R", _("reStructuredText Preview"),
self.on_update_preview),
("table", None, _("Create table"),
None, _("Create a reStructuredText table"),
self.on_create_table),
("sourcecode", None, _("Paste Code"),
None, _("Paste source code"),
self.on_paste_code),
("--> HTML", None, _("--> HTML"),
None, _("Save as HTML document"),
self.on_html),
("--> LaTeX", None, _("--> LaTeX"),
None, _("Save as LaTeX document"),
self.on_latex),
("--> LibreOffice", None, _("--> LibreOffice"),
None, _("Save as LibreOffice ODF"),
self.on_libreoffice),
])

# Insert the action group
manager.insert_action_group(self._action_group, -1)

# Merge the UI
self._ui_id = manager.add_ui_from_string(ui_str)
bottom.add_titled(self.html_window, "GeditReStructuredTextPanel", _('reStructuredText Preview'))

def do_deactivate(self):
# Retrieve the data of the window object
windowdata = self.window.reStPreviewData

# Remove the menu action
if 'ui_id' in windowdata:
manager = self.window.get_ui_manager()
manager.remove_ui(windowdata["ui_id"])
manager.remove_action_group(windowdata["action_group"])

# Remove the bottom panel
self.html_window.clear_view()
bottom = self.window.get_bottom_panel()
bottom.remove(windowdata["bottom_panel"])

def getSelection(self):
view = self.window.get_active_view()
if not view:
return

doc = view.get_buffer()

start = doc.get_start_iter()
end = doc.get_end_iter()

if doc.get_selection_bounds():
start = doc.get_iter_at_mark(doc.get_insert())
end = doc.get_iter_at_mark(doc.get_selection_bound())

text = doc.get_text(start, end)

# Menu activate handlers
def on_update_preview(self, window):
# Retrieve the data of the window object
windowdata = self.window.reStPreviewData

view = self.window.get_active_view()
if not view:
return

doc = view.get_buffer()
bottom.remove(self.html_window)

start = doc.get_start_iter()
end = doc.get_end_iter()
def do_update_state(self):
pass

if doc.get_selection_bounds():
start = doc.get_iter_at_mark(doc.get_insert())
end = doc.get_iter_at_mark(doc.get_selection_bound())

text = doc.get_text(start, end, False)
html = publish_parts(text, writer_name="html")["html_body"]

p = windowdata["bottom_panel"].get_placement()

html_doc = windowdata["html_doc"]
html_doc.load_string("%s\n%s\n%s" % (self.START_HTML, html, self.END_HTML),
'text/html', 'utf8', '')

windowdata["bottom_panel"].set_placement(p)

def on_latex(self, action):
command = 'python3 {dir}/to_tex.py' \
' "{file}.rst" "{file}.tex"'
doc = self.window.get_active_document()
filename = doc.get_uri_for_display()[:-4]
os.system(command.format(dir=self.restplugin_dir, file=filename))

def on_html(self, action):
command = 'python3 {dir}/to_html.py' \
' --stylesheet={dir}/restmain.css' \
' --language=en' \
' "{file}.rst" "{file}.html"'
doc = self.window.get_active_document()
filename = doc.get_uri_for_display()[:-4]
os.system(command.format(dir=self.restplugin_dir, file=filename))

def on_libreoffice(self, action):
command = 'python3 {dir}/to_odt.py' \
' --add-syntax-highlighting' \
' --stylesheet={dir}/default.odt' \
' "{file}.rst" "{file}.odt"'
doc = self.window.get_active_document()
filename = doc.get_uri_for_display()[:-4]
os.system(command.format(dir=self.restplugin_dir, file=filename))

def on_paste_code(self, action):
doc = self.window.get_active_document()

if not doc:
return

lines = Gtk.clipboard_get().wait_for_text().split('\n')
to_copy = "\n".join([line for line in lines[1:]])
doc.insert_at_cursor('..sourcecode:: ChoosenLanguage\n\n %s\n' % lines[0])
doc.insert_at_cursor(to_copy + '\n\n')

def on_create_table(self, action):
view = self.window.get_active_view()

if not view:
return

indent = view.get_indent()

doc = view.get_buffer()
#print('language=%s' %s doc.get_language())

start = doc.get_start_iter()
end = doc.get_end_iter()

if doc.get_selection_bounds():
start = doc.get_iter_at_mark(doc.get_insert())
end = doc.get_iter_at_mark(doc.get_selection_bound())

text = doc.get_text(start, end)
doc.delete(start, end)

lines = text.split("\n")
labels = lines[0].split(',')
rows = [row.strip().split(',') for row in lines[1:]]
# def do_create_configure_widget(self):
# config_widget = PythonConsoleConfigWidget(self.plugin_info.get_data_dir())
#
# return config_widget.configure_widget()

# doc.insert_at_cursor(toRSTtable([labels] + rows))
# ex:et:ts=4:
File renamed without changes.
63 changes: 63 additions & 0 deletions reST/restructuredtext.py
@@ -0,0 +1,63 @@
# -*- coding: utf-8 -*-

# restructuredtext.py - reStructuredText HTML preview panel
#
# Copyright (C) 2015 - Peter Bittner
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.

from gi.repository import Gtk, WebKit
from os.path import abspath, dirname, join


class RestructuredtextHtmlPanel(Gtk.ScrolledWindow):
"""
A Gtk panel displaying HTML rendered from ``.rst`` source code.
"""

START_HTML = """<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Language" content="English">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
%s
</style>
</head>
<body>"""

END_HTML = """</body>
</html>
"""

def __init__(self, styles_filename='restructuredtext.css'):
Gtk.ScrolledWindow.__init__(self) # TODO: replace by super()

module_dir = dirname(abspath(__file__))
css_file = join(module_dir, styles_filename)
with open(css_file, 'r') as styles:
self.START_HTML = self.START_HTML % styles.read()

self.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
self.set_shadow_type(Gtk.ShadowType.NONE)
self.view = WebKit.WebView()
self.add(self.view)
self.view.show()

def update_view(self):
self.view.load_string("%s\n<p>reStructuredText Viewer</p>\n%s" %
(self.START_HTML, self.END_HTML), 'text/html', 'utf8', '')

def clear_view(self):
self.view.load_string("", 'text/html', 'utf8', '')

0 comments on commit 15cce67

Please sign in to comment.