pygtkspellcheck-3.0/ 0000775 0001750 0001750 00000000000 12013730753 016205 5 ustar cjenkins cjenkins 0000000 0000000 pygtkspellcheck-3.0/README.md 0000664 0001750 0001750 00000003236 12013730013 017455 0 ustar cjenkins cjenkins 0000000 0000000 # About
PyGtkSpellCheck is a spellchecking library written in pure Python for Gtk based
on [Enchant](http://www.abisource.com/projects/enchant/).
It supports both Gtk's Python bindings,
[PyGObject](https://live.gnome.org/PyGObject/) and
[PyGtk](http://www.pygtk.org/), and for both Python
2 and 3 with automatic switching and binding autodetection. For automatic
translation of the user interface it can use GEdit's translation files.
# Features
* Localized names of the available languages.
* Supports word, line and multiline ignore regexes.
* Support for ignore custom tags on Gtk's TextBuffer.
* Enable and disable of spellchecking with preferences memory.
* Support for hotswap of Gtk's TextBuffers.
* PyGObject and PyGtk compatible with automatic detection.
* Python 2 and 3 support.
* As Enchant, support for Hunspell (LibreOffice) and Aspell (GNU) dictionaries.
# Documentation
You can find the documentation at http://pygtkspellcheck.readthedocs.org/ .
# Homepage
You can find the project page at http://koehlma.github.com/projects/pygtkspellcheck.html .
# License
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 3 of the License, 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 .
pygtkspellcheck-3.0/PKG-INFO 0000664 0001750 0001750 00000002267 12013730753 017311 0 ustar cjenkins cjenkins 0000000 0000000 Metadata-Version: 1.1
Name: pygtkspellcheck
Version: 3.0
Summary: A simple but quite powerful Python spell checking library for GtkTextViews based on Enchant.
Home-page: http://koehlma.github.com/projects/pygtkspellcheck.html
Author: Maximilian Köhl & Carlos Jenkins
Author-email: linuxmaxi@googlemail.com & carlos@jenkins.co.cr
License: GPLv3+
Download-URL: https://github.com/koehlma/pygtkspellcheck/tarball/master
Description: It supports both Gtk's Python bindings, PyGObject andPyGtk, and for both Python 2 and 3 with automatic switchingand binding autodetection. For automatic translation of theuser interface it can use GEdit's translation files.
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: X11 Applications :: Gnome
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development :: Localization
pygtkspellcheck-3.0/src/ 0000775 0001750 0001750 00000000000 12013730753 016774 5 ustar cjenkins cjenkins 0000000 0000000 pygtkspellcheck-3.0/src/gtkspellcheck/ 0000775 0001750 0001750 00000000000 12013730753 021617 5 ustar cjenkins cjenkins 0000000 0000000 pygtkspellcheck-3.0/src/gtkspellcheck/oxt_import.py 0000664 0001750 0001750 00000020752 12004224443 024375 0 ustar cjenkins cjenkins 0000000 0000000 # -*- coding:utf-8 -*-
#
# Copyright (C) 2012, Carlos Jenkins
#
# 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 3 of the License, 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 .
"""
Uncompress, read and install LibreOffice .oxt dictionaries extensions.
This module extracts the .dic and .aff (Hunspell) dictionaries from all the
.oxt extensions found on some directory.
Extensions like the ones found here:
http://extensions.services.openoffice.org/dictionary
"""
import os
import xml.dom.minidom
import shutil
import logging
import gettext
from zipfile import ZipFile, BadZipfile
# Expose
__all__ = ['deflate_oxt']
logger = logging.getLogger(__name__)
_ = gettext.translation('pygtkspellcheck', fallback=True).gettext
def deflate_oxt(oxt_path, extract_path, override=False, move_path=None):
"""
Uncompress, read and install LibreOffice ``.oxt`` dictionaries extensions.
:param oxt_path: path to a directory containing the ``.oxt`` extensions.
:param extract_path: path to extract Hunspell dictionaries files.
:param override: override files.
:param move_path: Optional path to move the ``.oxt`` files after processing.
:rtype: None
This function extracts the Hunspell dictionaries (``.dic`` and ``.aff``
files) from all the ``.oxt`` extensions found on ``oxt_path`` directory to
the ``extract_path`` directory.
Extensions like the ones found here:
http://extensions.services.openoffice.org/dictionary
In detail, this functions does the following:
1. Find all the ``.oxt`` extension files within ``oxt_path``
2. Open (unzip) each extension.
3. Find the dictionary definition file within (*dictionaries.xcu*)
4. Parse the dictionary definition file and locate the dictionaries files.
5. Uncompress those files to ``extract_path``.
By default file overriding is disabled, set ``override`` parameter to True
if you want to enable it. As and additional option, each processed extension
can be moved to ``move_path``.
"""
# Get the real, absolute and normalized path
oxt_path = os.path.normpath(os.path.abspath(os.path.realpath(oxt_path)))
# Check that the input directory exists
if not os.path.isdir(oxt_path):
return
# Create extract directory if not exists
if not os.path.exists(extract_path):
os.makedirs(extract_path)
# Check that the extract path is a directory
if not os.path.isdir(extract_path):
logger.error(_('Extract path is not a directory.'))
return
# Get all .oxt extension at given path
oxt_files = [extension for extension in os.listdir(oxt_path) if extension.lower().endswith('.oxt')]
for extension_name in oxt_files:
extension_path = os.path.join(oxt_path, extension_name)
try:
with ZipFile(extension_path, 'r') as extension_file:
# List of files within the extension file
files_within = extension_file.namelist()
# Find the dictionaries registry
registry = 'dictionaries.xcu'
if not registry in files_within:
for file_path in files_within:
if file_path.lower().endswith(registry):
registry = file_path
if registry in files_within:
try:
# Find within the registry the entry for dictionaries
registry_content = extension_file.read(registry)
dom = xml.dom.minidom.parseString(registry_content)
dic_locations = _find_dictionaries_location(dom)
if dic_locations:
for dic_location in dic_locations:
# Get the list of files considered dictionaries for current entry
dic_location = dic_location.replace('%origin%', os.path.dirname(registry))
dic_files = []
for dic_file in dic_location.split(' '):
if dic_file.startswith('/'):
dic_file = dic_file[1:]
dic_files.append(os.path.normpath(dic_file))
# Extract files if they exists within the extension file
for dic_file in dic_files:
if dic_file in files_within:
target = os.path.join(extract_path, os.path.basename(dic_file))
# Extract only if we are overriding or file doesn't exists
if (override and os.path.isfile(target)) or (not os.path.exists(target)):
# Extract a single file without caring about folder structure
with extension_file.open(dic_file) as source:
with file(target, 'wb') as destination:
shutil.copyfileobj(source, destination)
else:
logger.warning(_('\'{0}\' declared in registry but not found within the extension.').format(dic_file))
except Exception as inst:
logger.exception(_('Error while processing extension {0}.').format(extension_name))
pass
else:
logger.error(_('Extension \'{0}\' has no dictionary registry.').format(extension_name))
except BadZipfile:
logger.error(_('Extension \'{0}\' is not a valid zip file.').format(extension_name))
# Move the extension after processing if user requires it
if move_path is not None:
# Create move path if it doesn't exists
if not os.path.exists(move_path):
os.makedirs(move_path)
# Move to the given path only if it is a directory and target doesn't exists
if os.path.isdir(move_path):
if not os.path.exists(os.path.join(move_path, extension_name)) or override:
#print('Move from ', extension_path, ' to ', move_path)
shutil.move(extension_path, move_path)
else:
logger.warning(_('Unable to move extension, file with same name exists within move_path.'))
else:
logger.warning(_('Unable to move extension, move_path is not a directory.'))
def _find_dictionaries_location(dom):
"""Find the location of the dictionaries files in the extension XML registry"""
def _is_text_node(element):
return element.firstChild.nodeType == xml.dom.Node.TEXT_NODE
result = []
root = dom.getElementsByTagName('oor:component-data')[0]
for value in root.getElementsByTagName('value'):
if _is_text_node(value) and value.firstChild.data == 'DICT_SPELL':
dict_node = value.parentNode.parentNode
for prop in dict_node.getElementsByTagName('prop'):
if prop.hasAttribute('oor:name') and prop.getAttribute('oor:name') == 'Locations':
dict_value = prop.getElementsByTagName('value')[0]
# %origin%/es_CR.aff %origin%/es_CR.dic
if _is_text_node(dict_value):
result.append(dict_value.firstChild.data)
# %origin%/es_CR.aff%origin%/es_CR.dic
else:
for item in dict_value.getElementsByTagName('it'):
result.append(item.firstChild.data)
break
return result
pygtkspellcheck-3.0/src/gtkspellcheck/spellcheck.py 0000664 0001750 0001750 00000053264 12006755550 024324 0 ustar cjenkins cjenkins 0000000 0000000 # -*- coding:utf-8 -*-
#
# Copyright (C) 2012, Maximilian Köhl
# Copyright (C) 2012, Carlos Jenkins
#
# 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 3 of the License, 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 .
"""
A spellchecking library written in pure Python for Gtk based on Enchant. It
supports both Gtk's Python bindings, PyGObject and PyGtk, and for both Python 2
and 3 with automatic switching and binding autodetection. For automatic
translation of the user interface it can use GEdit's translation files.
"""
import enchant
import gettext
import logging
import re
import sys
from pylocales import code_to_name
# Public Objects
__all__ = ['SpellChecker']
# Logger
logger = logging.getLogger(__name__)
# Find which Gtk binding to use based on client's binding
if 'gi.repository.Gtk' in sys.modules:
gtk = sys.modules['gi.repository.Gtk']
_pygobject = True
elif 'gtk' in sys.modules:
gtk = sys.modules['gtk']
_pygobject = False
else:
logger.error('No Gtk module found. Spellcheck will be unusable.')
# Select base list class for Python3/2
try:
from collections import UserList
_list = UserList
except ImportError:
_list = list
# Select basestring for Python2/3
if sys.version_info.major == 3:
basestring = str
# Map between Gedit's translation and PyGtkSpellcheck's own
_GEDIT_MAP = {'Languages' : 'Languages',
'Ignore All' : 'Ignore _All',
'Suggestions' : 'Suggestions',
'(no suggestions)' : '(no suggested words)',
'Add "{word}" to Dictionary' : 'Add w_ord'}
# Translation
if gettext.find('gedit'):
_gedit = gettext.translation('gedit', fallback=True).gettext
_ = lambda message: _gedit(_GEDIT_MAP[message]).replace('_', '')
else:
_ = gettext.translation('pygtkspellcheck', fallback=True).gettext
class SpellChecker(object):
"""
Main spellchecking class, everything important happens here.
:param view: GtkTextView the SpellChecker should be attached to.
:param language: the language which should be used for spellchecking.
Use a combination of two letter lower-case ISO 639 language code with a
two letter upper-case ISO 3166 country code, for example en_US or de_DE.
:param prefix: a prefix for some internal GtkTextMarks.
:param collapse: enclose suggestions in its own menu.
:param params: dictionary with Enchant broker parameters that should be set
e.g. `enchant.myspell.dictionary.path`.
.. attribute:: languages
A list of supported languages.
.. function:: exists(language)
checks if a language exists
:param language: language to check
"""
FILTER_WORD = 'word'
FILTER_LINE = 'line'
FILTER_TEXT = 'text'
DEFAULT_FILTERS = {FILTER_WORD : [r'[0-9.,]+'],
FILTER_LINE : [r'(https?|ftp|file):((//)|(\\\\))+[\w\d:#@%/;$()~_?+-=\\.&]+',
r'[\w\d]+@[\w\d.]+'],
FILTER_TEXT : []}
class _LanguageList(_list):
def __init__(self, *args, **kwargs):
if sys.version_info.major == 3:
super().__init__(*args, **kwargs)
else:
_list.__init__(self, *args, **kwargs)
self.mapping = dict(self)
@classmethod
def from_broker(cls, broker):
return cls(sorted([(language, code_to_name(language))
for language in broker.list_languages()],
key=lambda language: language[1]))
def exists(self, language):
return language in self.mapping
class _Mark():
def __init__(self, buffer, name, start):
self._buffer = buffer
self._name = name
self._mark = self._buffer.create_mark(self._name, start, True)
@property
def iter(self):
return self._buffer.get_iter_at_mark(self._mark)
@property
def inside_word(self):
return self.iter.inside_word()
@property
def word(self):
start = self.iter
if not start.starts_word():
start.backward_word_start()
end = self.iter
if end.inside_word():
end.forward_word_end()
return start, end
def move(self, location):
self._buffer.move_mark(self._mark, location)
def __init__(self, view, language='en', prefix='gtkspellchecker', collapse=True, params={}):
self._view = view
self.collapse = collapse
self._view.connect('populate-popup', lambda entry, menu: self._extend_menu(menu))
self._view.connect('popup-menu', self._click_move_popup)
self._view.connect('button-press-event', self._click_move_button)
self._prefix = prefix
if _pygobject:
self._misspelled = gtk.TextTag.new('{prefix}-misspelled'.format(prefix=self._prefix))
else:
self._misspelled = gtk.TextTag('{prefix}-misspelled'.format(prefix=self._prefix))
self._misspelled.set_property('underline', 4)
self._broker = enchant.Broker()
for param, value in params: self._broker.set_param(param, value)
self.languages = SpellChecker._LanguageList.from_broker(self._broker)
self._language = language if self.languages.exists(language) else 'en'
self._dictionary = self._broker.request_dict(language)
self._deferred_check = False
self._filters = dict(SpellChecker.DEFAULT_FILTERS)
self._regexes = {SpellChecker.FILTER_WORD : re.compile('|'.join(self._filters[SpellChecker.FILTER_WORD])),
SpellChecker.FILTER_LINE : re.compile('|'.join(self._filters[SpellChecker.FILTER_LINE])),
SpellChecker.FILTER_TEXT : re.compile('|'.join(self._filters[SpellChecker.FILTER_TEXT]), re.MULTILINE)}
self._enabled = True
self.buffer_initialize()
@property
def language(self):
"""
The language used for spellchecking
"""
return self._language
@language.setter
def language(self, language):
if language != self._language and self.languages.exists(language):
self._language = language
self._dictionary = self._broker.request_dict(language)
self.recheck()
@property
def enabled(self):
"""
Enable or disable spellchecking
"""
return self._enabled
@enabled.setter
def enabled(self, enabled):
if enabled and not self._enabled:
self.enable()
elif not enabled and self._enabled:
self.disable()
def buffer_initialize(self):
"""
Initialize the GtkTextBuffer associated with the GtkTextView.
If you associate a new GtkTextBuffer with the GtkTextView call this method.
"""
self._buffer = self._view.get_buffer()
self._buffer.connect('insert-text', self._before_text_insert)
self._buffer.connect_after('insert-text', self._after_text_insert)
self._buffer.connect_after('delete-range', self._range_delete)
self._buffer.connect_after('mark-set', self._mark_set)
start = self._buffer.get_bounds()[0]
self._marks = {'insert-start' : SpellChecker._Mark(self._buffer, '{prefix}-insert-start'.format(prefix=self._prefix), start),
'insert-end' : SpellChecker._Mark(self._buffer, '{prefix}-insert-end'.format(prefix=self._prefix), start),
'click' : SpellChecker._Mark(self._buffer, '{prefix}-click'.format(prefix=self._prefix), start)}
self._table = self._buffer.get_tag_table()
self._table.add(self._misspelled)
self.ignored_tags = []
def tag_added(tag, *args):
if hasattr(tag, 'spell_check') and not getattr(tag, 'spell_check'):
self.ignored_tags.append(tag)
def tag_removed(tag, *args):
if tag in self.ignored_tags:
self.ignored_tags.remove(tag)
self._table.connect('tag-added', tag_added)
self._table.connect('tag-removed', tag_removed)
self._table.foreach(tag_added, None)
self.no_spell_check = self._table.lookup('no-spell-check')
if not self.no_spell_check:
if _pygobject:
self.no_spell_check = gtk.TextTag.new('no-spell-check')
else:
self.no_spell_check = gtk.TextTag('no-spell-check')
self._table.add(self.no_spell_check)
self.recheck()
def recheck(self):
"""
Rechecks the spelling of the whole text.
"""
start, end = self._buffer.get_bounds()
self.check_range(start, end, True)
def disable(self):
"""
Disable spellchecking.
"""
self._enabled = False
start, end = self._buffer.get_bounds()
self._buffer.remove_tag(self._misspelled, start, end)
def enable(self):
"""
Enable spellchecking.
"""
self._enabled = True
self.recheck()
def append_filter(self, regex, filter_type):
"""
Append a new filter to the filter list.
Filters are useful to ignore some misspelled words based on regular expressions.
:param regex: the regex used for filtering
:param filter_type: the type of the filter
Filter Types:
:const:`SpellChecker.FILTER_WORD`: The regex must match the whole word you want to filter.
The word separation is done by Pango's word separation algorythm so, for example, urls won't work here because they are split in many words.
:const:`SpellChecker.FILTER_LINE`: If the expression you want to match is a single line expression use this type.
It should not be an open end expression because then the rest of the line with the text you want to filter will become correct.
:const:`SpellChecker.FILTER_TEXT`: Use this if you want to filter multiline expressions.
The regex will be compiled with the `MULTILINE` flag.
Same with open end expressions apply here.
"""
self._filters[filter_type].append(regex)
if filter_type == SpellChecker.FILTER_TEXT:
self._regexes[filter_type] = re.compile('|'.join(self._filters[filter_type]), re.MULTILINE)
else:
self._regexes[filter_type] = re.compile('|'.join(self._filters[filter_type]))
def remove_filter(self, regex, filter_type):
"""
Remove a filter from the filter list.
:param regex: the regex which used for filtering
:param filter_type: the type of the filter
"""
self._filters[filter_type].remove(regex)
if filter_type == SpellChecker.FILTER_TEXT:
self._regexes[filter_type] = re.compile('|'.join(self._filters[filter_type]), re.MULTILINE)
else:
self._regexes[filter_type] = re.compile('|'.join(self._filters[filter_type]))
def append_ignore_tag(self, tag):
"""
Appends a tag to the list of ignored tags.
A string will be automatic resolved into a tag object.
:param tag: tag object or tag name
"""
if isinstance(tag, basestring):
tag = self._table.lookup(tag)
self.ignored_tags.append(tag)
def remove_ignore_tag(self, tag):
"""
Removes a tag from the list of ignored tags.
A string will be automatic resolved into a tag object.
:param tag: tag object or tag name
"""
if isinstance(tag, basestring):
tag = self._table.lookup(tag)
self.ignored_tags.remove(tag)
def add_to_dictionary(self, word):
"""
Adds a word to user's dictionary.
:param word: the word to add
"""
self._dictionary.add_to_pwl(word)
self.recheck()
def ignore_all(self, word):
"""
Ignores a word for the current session.
:param word: the word to ignore
"""
self._dictionary.add_to_session(word)
self.recheck()
def check_range(self, start, end, force_all=False):
"""
Checks a specified range between two GtkTextIters.
:param start: start iter - checking starts here
:param end: end iter - checking ends here
"""
if not self._enabled:
return
if end.inside_word(): end.forward_word_end()
if not start.starts_word() and (start.inside_word() or start.ends_word()): start.backward_word_start()
self._buffer.remove_tag(self._misspelled, start, end)
cursor = self._buffer.get_iter_at_mark(self._buffer.get_insert())
precursor = cursor.copy()
precursor.backward_char()
highlight = cursor.has_tag(self._misspelled) or precursor.has_tag(self._misspelled)
if not start.get_offset():
start.forward_word_end()
start.backward_word_start()
word_start = start.copy()
while word_start.compare(end) < 0:
word_end = word_start.copy()
word_end.forward_word_end()
in_word = (word_start.compare(cursor) < 0) and (cursor.compare(word_end) <= 0)
if in_word and not force_all:
if highlight:
self._check_word(word_start, word_end)
else:
self._deferred_check = True
else:
self._check_word(word_start, word_end)
self._deferred_check = False
word_end.forward_word_end()
word_end.backward_word_start()
if word_start.equal(word_end):
break
word_start = word_end.copy()
def _languages_menu(self):
def _set_language(item, code):
self.language = code
if _pygobject:
menu = gtk.Menu.new()
group = []
else:
menu = gtk.Menu()
group = gtk.RadioMenuItem()
connect = []
for code, name in self.languages:
if _pygobject:
item = gtk.RadioMenuItem.new_with_label(group, name)
group.append(item)
else:
item = gtk.RadioMenuItem(group, name)
if code == self.language:
item.set_active(True)
connect.append((item, code))
menu.append(item)
for item, code in connect:
item.connect('activate', _set_language, code)
return menu
def _suggestion_menu(self, word):
menu = []
suggestions = self._dictionary.suggest(word)
if not suggestions:
if _pygobject:
item = gtk.MenuItem.new()
label = gtk.Label.new('')
else:
item = gtk.MenuItem()
label = gtk.Label()
try:
label.set_halign(gtk.Align.LEFT)
except AttributeError:
label.set_alignment(0.0, 0.5)
label.set_markup('{text}'.format(text=_('(no suggestions)')))
item.add(label)
menu.append(item)
else:
for suggestion in suggestions:
if _pygobject:
item = gtk.MenuItem.new()
label = gtk.Label.new('')
else:
item = gtk.MenuItem()
label = gtk.Label()
label.set_markup('{text}'.format(text=suggestion))
try:
label.set_halign(gtk.Align.LEFT)
except AttributeError:
label.set_alignment(0.0, 0.5)
item.add(label)
item.connect('activate', self._replace_word, word, suggestion)
menu.append(item)
if _pygobject:
menu.append(gtk.SeparatorMenuItem.new())
item = gtk.MenuItem.new_with_label(_('Add "{word}" to Dictionary').format(word=word))
else:
menu.append(gtk.SeparatorMenuItem())
item = gtk.MenuItem(_('Add "{word}" to Dictionary').format(word=word))
item.connect('activate', lambda *args: self.add_to_dictionary(word))
menu.append(item)
if _pygobject:
item = gtk.MenuItem.new_with_label(_('Ignore All'))
else:
item = gtk.MenuItem(_('Ignore All'))
item.connect('activate', lambda *args: self.ignore_all(word))
menu.append(item)
return menu
def _extend_menu(self, menu):
if not self._enabled:
return
if _pygobject:
separator = gtk.SeparatorMenuItem.new()
else:
separator = gtk.SeparatorMenuItem()
separator.show()
menu.prepend(separator)
if _pygobject:
languages = gtk.MenuItem.new_with_label(_('Languages'))
else:
languages = gtk.MenuItem(_('Languages'))
languages.set_submenu(self._languages_menu())
languages.show_all()
menu.prepend(languages)
if self._marks['click'].inside_word:
start, end = self._marks['click'].word
if start.has_tag(self._misspelled):
word = self._buffer.get_text(start, end, False)
submenu_items = self._suggestion_menu(word)
if self.collapse:
if _pygobject:
suggestions = gtk.MenuItem.new_with_label(_('Suggestions'))
submenu = gtk.Menu.new()
else:
suggestions = gtk.MenuItem(_('Suggestions'))
submenu = gtk.Menu()
for i in submenu_items:
submenu.append(i)
suggestions.set_submenu(submenu)
suggestions.show_all()
menu.prepend(suggestions)
else:
submenu_items.reverse()
for i in submenu_items:
menu.prepend(i)
menu.show_all()
def _click_move_popup(self, *args):
self._marks['click'].move(self._buffer.get_iter_at_mark(self._buffer.get_insert()))
return False
def _click_move_button(self, widget, event):
if event.button == 3:
if self._deferred_check: self._check_deferred_range(True)
x, y = self._view.window_to_buffer_coords(2, int(event.x), int(event.y))
self._marks['click'].move(self._view.get_iter_at_location(x, y))
return False
def _before_text_insert(self, textbuffer, location, text, length):
self._marks['insert-start'].move(location)
def _after_text_insert(self, textbuffer, location, text, length):
start = self._marks['insert-start'].iter
self.check_range(start, location)
self._marks['insert-end'].move(location)
def _range_delete(self, textbuffer, start, end):
self.check_range(start, end)
def _mark_set(self, textbuffer, location, mark):
if mark == self._buffer.get_insert() and self._deferred_check:
self._check_deferred_range(False)
def _replace_word(self, item, old_word, new_word):
start, end = self._marks['click'].word
offset = start.get_offset()
self._buffer.begin_user_action()
self._buffer.delete(start, end)
self._buffer.insert(self._buffer.get_iter_at_offset(offset), new_word)
self._buffer.end_user_action()
self._dictionary.store_replacement(old_word, new_word)
def _check_deferred_range(self, force_all):
start = self._marks['insert-start'].iter
end = self._marks['insert-end'].iter
self.check_range(start, end, force_all)
def _check_word(self, start, end):
if start.has_tag(self.no_spell_check):
return
for tag in self.ignored_tags:
if start.has_tag(tag):
return
word = self._buffer.get_text(start, end, False).strip()
if len(self._filters[SpellChecker.FILTER_WORD]):
if self._regexes[SpellChecker.FILTER_WORD].match(word):
return
if len(self._filters[SpellChecker.FILTER_LINE]):
line_start = self._buffer.get_iter_at_line(start.get_line())
line_end = end.copy()
line_end.forward_to_line_end()
line = self._buffer.get_text(line_start, line_end, False)
for match in self._regexes[SpellChecker.FILTER_LINE].finditer(line):
if match.start() <= start.get_line_offset() <= match.end():
start = self._buffer.get_iter_at_line_offset(start.get_line(), match.start())
end = self._buffer.get_iter_at_line_offset(start.get_line(), match.end())
self._buffer.remove_tag(self._misspelled, start, end)
return
if len(self._filters[SpellChecker.FILTER_TEXT]):
text_start, text_end = self._buffer.get_bounds()
text = self._buffer.get_text(text_start, text_end, False)
for match in self._regexes[SpellChecker.FILTER_TEXT].finditer(text):
if match.start() <= start.get_offset() <= match.end():
start = self._buffer.get_iter_at_offset(match.start())
end = self._buffer.get_iter_at_offset(match.end())
self._buffer.remove_tag(self._misspelled, start, end)
return
if not self._dictionary.check(word):
self._buffer.apply_tag(self._misspelled, start, end)
pygtkspellcheck-3.0/src/gtkspellcheck/__init__.py 0000664 0001750 0001750 00000004731 12013730013 023722 0 ustar cjenkins cjenkins 0000000 0000000 # -*- coding:utf-8 -*-
#
# Copyright (C) 2012, Maximilian Köhl
# Copyright (C) 2012, Carlos Jenkins
#
# 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 3 of the License, 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 .
# Python 2/3 unicode
import sys
if sys.version_info.major == 3:
u = lambda x: x
else:
u = lambda x: x.decode('utf-8')
# Metadata
__version__ = '3.0'
__project__ = 'Python GTK Spellcheck'
__short_name__ = 'pygtkspellcheck'
__authors__ = u('Maximilian Köhl & Carlos Jenkins')
__emails__ = u('linuxmaxi@googlemail.com & carlos@jenkins.co.cr')
__website__ = 'http://koehlma.github.com/projects/pygtkspellcheck.html'
__download_url__ = 'https://github.com/koehlma/pygtkspellcheck/tarball/master'
__source__ = 'https://github.com/koehlma/pygtkspellcheck/'
__vcs__ = 'git://github.com/koehlma/pygtkspellcheck.git'
__copyright__ = u('2012, Maximilian Köhl & Carlos Jenkins')
__desc_short__ = 'A simple but quite powerful Python spell checking library for GtkTextViews based on Enchant.'
__desc_long__ = ('It supports both Gtk\'s Python bindings, PyGObject and'
'PyGtk, and for both Python 2 and 3 with automatic switching'
'and binding autodetection. For automatic translation of the'
'user interface it can use GEdit\'s translation files.')
__metadata__ = {'__version__' : __version__,
'__project__' : __project__,
'__short_name__' : __short_name__,
'__authors__' : __authors__,
'__emails__' : __emails__,
'__website__' : __website__,
'__download_url__' : __download_url__,
'__source__' : __source__,
'__vcs__' : __vcs__,
'__copyright__' : __copyright__,
'__desc_short__' : __desc_short__,
'__desc_long__' : __desc_long__}
# import SpellChecker class
from gtkspellcheck.spellcheck import SpellChecker pygtkspellcheck-3.0/src/pylocales/ 0000775 0001750 0001750 00000000000 12013730753 020767 5 ustar cjenkins cjenkins 0000000 0000000 pygtkspellcheck-3.0/src/pylocales/__init__.py 0000664 0001750 0001750 00000004422 12004224443 023074 0 ustar cjenkins cjenkins 0000000 0000000 # -*- coding:utf-8 -*-
#
# Copyright (C) 2012, Maximilian Köhl
#
# 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 3 of the License, 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 .
# Python 2/3 unicode
import sys
if sys.version_info.major == 3:
u = lambda x: x
else:
u = lambda x: x.decode('utf-8')
# Metadata
__version__ = '1.1'
__project__ = 'PyLocales'
__short_name__ = 'pylocales'
__authors__ = u('Maximilian Köhl & Carlos Jenkins')
__emails__ = u('linuxmaxi@googlemail.com & carlos@jenkins.co.cr')
__website__ = 'http://pygtkspellcheck.readthedocs.org/'
__source__ = 'https://github.com/koehlma/pygtkspellcheck/'
__vcs__ = 'git://github.com/koehlma/pygtkspellcheck.git'
__copyright__ = u('2012, Maximilian Köhl & Carlos Jenkins')
__desc_short__ = 'Query the ISO 639/3166 database about a country or a language.'
__desc_long__ = ('Query the ISO 639/3166 database about a country or a'
'language. The locales database contains ISO 639 languages'
'definitions and ISO 3166 countries definitions. This package'
'provides translation for countries and languages names if'
'iso-codes package is installed (Ubuntu/Debian).')
__metadata__ = {'__version__' : __version__,
'__project__' : __project__,
'__short_name__' : __short_name__,
'__authors__' : __authors__,
'__emails__' : __emails__,
'__website__' : __website__,
'__source__' : __source__,
'__vcs__' : __vcs__,
'__copyright__' : __copyright__,
'__desc_short__' : __desc_short__,
'__desc_long__' : __desc_long__}
# Should only import Public Objects
from pylocales.locales import *
pygtkspellcheck-3.0/src/pylocales/locales.py 0000664 0001750 0001750 00000011423 12004224443 022756 0 ustar cjenkins cjenkins 0000000 0000000 # -*- coding:utf-8 -*-
#
# Copyright (C) 2012, Maximilian Köhl
# Copyright (C) 2012, Carlos Jenkins
#
# 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 3 of the License, 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 .
"""
Query the ISO 639/3166 database about a country or a language. The locales
database contains ISO 639 languages definitions and ISO 3166 countries
definitions. This package provides translation for countries and languages names
if iso-codes package is installed (Ubuntu/Debian).
@see utils/locales/build.py to know the database tables and structure.
"""
import gettext
import logging
import os
import sqlite3
# Public Objects
__all__ = ['Country', 'Language', 'LanguageNotFound',
'CountryNotFound', 'code_to_name']
# Translation
_translator_language = gettext.translation('iso_639', fallback=True).gettext
_translator_country = gettext.translation('iso_3166', fallback=True).gettext
# Decides where the database is located. If an application provides an
# os.path.get_module_path monkey patch to determine the path where the module
# is located it uses this. If not it searches in the directory of this source
# code file.
__path__ = None
if hasattr(os.path, 'get_module_path'):
__path__ = os.path.get_module_path(__file__)
if not os.path.isfile(os.path.join(__path__, 'locales.db')):
__path__ = None
if __path__ is None:
__path__ = os.path.abspath(os.path.realpath(os.path.dirname(__file__)))
# Loading the Database
_database = sqlite3.connect(os.path.join(__path__, 'locales.db'))
logger = logging.getLogger(__name__)
# Exceptions
class LanguageNotFound(Exception):
"""
The specified language wasn't found in the database.
"""
class CountryNotFound(Exception):
"""
The specified country wasn't found in the database.
"""
class Country(object):
def __init__(self, rowid):
country = _database.execute('SELECT * FROM countries WHERE rowid == ?', (rowid,)).fetchone()
self.name = country[0]
self.official_name = country[1]
self.alpha_2 = country[2]
self.alpha_3 = country[3]
self.numeric = country[4]
self.translation = _translator_country(self.name)
@classmethod
def get_country(cls, code, codec):
country = _database.execute('SELECT rowid FROM countries WHERE %s == ?' % (codec), (code,)).fetchone()
if country:
return cls(country[0])
raise CountryNotFound('code: %s, codec: %s' % (code, codec))
@classmethod
def by_alpha_2(cls, code):
return Country.get_country(code, 'alpha_2')
@classmethod
def by_alpha_3(cls, code):
return Country.get_country(code, 'alpha_3')
@classmethod
def by_numeric(cls, code):
return Country.get_country(code, 'numeric')
class Language(object):
def __init__(self, rowid):
language = _database.execute('SELECT * FROM languages WHERE rowid == ?', (rowid,)).fetchone()
self.name = language[0]
self.iso_639_2B = language[1]
self.iso_639_2T = language[2]
self.iso_639_1 = language[3]
self.translation = _translator_language(self.name)
@classmethod
def get_language(cls, code, codec):
language = _database.execute('SELECT rowid FROM languages WHERE %s == ?' % (codec), (code,)).fetchone()
if language:
return cls(language[0])
raise LanguageNotFound('code: %s, codec: %s' % (code, codec))
@classmethod
def by_iso_639_2B(cls, code):
return Language.get_language(code, 'iso_639_2B')
@classmethod
def by_iso_639_2T(cls, code):
return Language.get_language(code, 'iso_639_2T')
@classmethod
def by_iso_639_1(cls, code):
return Language.get_language(code, 'iso_639_1')
def code_to_name(code, separator='_'):
"""
Get the natural name of a language based on it's code.
"""
logger.debug('requesting name for code "{}"'.format(code))
code = code.split(separator)
if len(code) > 1:
lang = Language.by_iso_639_1(code[0]).translation
country = Country.by_alpha_2(code[1]).translation
return '{lang} ({country})'.format(lang=lang, country=country)
else:
return Language.by_iso_639_1(code[0]).translation pygtkspellcheck-3.0/src/pylocales/locales.db 0000664 0001750 0001750 00000072000 12004224443 022711 0 ustar cjenkins cjenkins 0000000 0000000 SQLite format 3 @ -
7 7 _
tablelanguageslanguagesCREATE TABLE languages (name, iso_639_2B, iso_639_2T, iso_639_1)ftablecountriescountriesCREATE TABLE countries (name, official_name, alpha_2, alpha_3, numeric) s
` L 7
v ` F /
O ( _ ? z T 1 j I #
H ~@"wL"
h? _ H BermudaBMBMU060$/BeninRepublic of BeninBJBEN204 BelizeBZBLZ084'1BelgiumKingdom of BelgiumBEBEL056(3BelarusRepublic of BelarusBYBLR112 BarbadosBBBRB0527!KBangladeshPeople's Republic of BangladeshBDBGD050'1BahrainKingdom of BahrainBHBHR0480CBahamasCommonwealth of the BahamasBSBHS044.!9AzerbaijanRepublic of AzerbaijanAZAZE031(3AustriaRepublic of AustriaATAUT040 AustraliaAUAUS036
ArubaAWABW533(3ArmeniaRepublic of ArmeniaAMARM051)1ArgentinaArgentine RepublicARARG032!
3 Antigua and BarbudaAGATG028 ! AntarcticaAQATA010 AnguillaAIAIA660&1AngolaRepublic of AngolaAOAGO024,;AndorraPrincipality of AndorraADAND020) American SamoaASASM016<[AlgeriaPeople's Democratic Republic of AlgeriaDZDZA012(3AlbaniaRepublic of AlbaniaALALB008) Åland IslandsAXALA2488#KAfghanistanIslamic Republic of AfghanistanAFAFG004
9 :vH'^H Y 9 /- Christmas IslandCXCXR162-.AChinaPeople's Republic of ChinaCNCHN156$-/ChileRepublic of ChileCLCHL152",-ChadRepublic of ChadTDTCD148&+= Central African RepublicCFCAF140*) Cayman IslandsKYCYM136.)!9Cape VerdeRepublic of Cape VerdeCVCPV132( CanadaCACAN124*'5CameroonRepublic of CameroonCMCMR120)&3CambodiaKingdom of CambodiaKHKHM116(%3BurundiRepublic of BurundiBIBDI108$% Burkina FasoBFBFA854*#5BulgariaRepublic of BulgariaBGBGR100"/ Brunei DarussalamBNBRN096,!I British Indian Ocean TerritoryIOIOT0861 GBrazilFederative Republic of BrazilBRBRA076' Bouvet IslandBVBVT074*5BotswanaRepublic of BotswanaBWBWA072F9QBosnia and HerzegovinaRepublic of Bosnia and HerzegovinaBABIH070POOBonaire, Saint Eustatius and SabaBonaire, Saint Eustatius and SabaBQBES535KKIBolivia, Plurinational State ofPlurinational State of BoliviaBOBOL068%/BhutanKingdom of BhutanBTBTN064
> X#uQ1 fD h > (F3EstoniaRepublic of EstoniaEEEST233E EritreaERERI232