ReText-5.3.1/ 0000755 0001750 0001750 00000000000 12701277415 013603 5 ustar dmitry dmitry 0000000 0000000 ReText-5.3.1/ReText/ 0000755 0001750 0001750 00000000000 12701277415 015016 5 ustar dmitry dmitry 0000000 0000000 ReText-5.3.1/ReText/__init__.py 0000644 0001750 0001750 00000010235 12701277312 017124 0 ustar dmitry dmitry 0000000 0000000 # This file is part of ReText
# Copyright: 2012-2014 Dmitry Shachnev
#
# 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 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 .
import markups
import markups.common
from os.path import dirname, exists, join
from PyQt5.QtCore import QByteArray, QLocale, QSettings, QStandardPaths
from PyQt5.QtGui import QFont
app_version = "5.3.1"
settings = QSettings('ReText project', 'ReText')
print('Using configuration file:', settings.fileName())
if not str(settings.fileName()).endswith('.conf'):
# We are on Windows probably
settings = QSettings(QSettings.IniFormat, QSettings.UserScope,
'ReText project', 'ReText')
try:
import enchant
import enchant.errors
except ImportError:
enchant_available = False
enchant = None
else:
enchant_available = True
try:
enchant.Dict()
except enchant.errors.Error:
enchant_available = False
datadirs = QStandardPaths.standardLocations(QStandardPaths.GenericDataLocation)
datadirs = [join(d, 'retext') for d in datadirs]
if '__file__' in locals():
datadirs = [dirname(dirname(__file__))] + datadirs
icon_path = 'icons/'
for dir in datadirs:
if exists(join(dir, 'icons')):
icon_path = join(dir, 'icons/')
break
configOptions = {
'appStyleSheet': '',
'autoSave': False,
'defaultCodec': '',
'defaultMarkup': '',
'editorFont': QFont('monospace'),
'font': QFont(),
'handleWebLinks': False,
'hideToolBar': False,
'highlightCurrentLine': False,
'iconTheme': '',
'lineNumbersEnabled': False,
'livePreviewByDefault': False,
'markdownDefaultFileExtension': '.mkd',
'pygmentsStyle': 'default',
'restDefaultFileExtension': '.rst',
'rightMargin': 0,
'saveWindowGeometry': False,
'spellCheck': False,
'spellCheckLocale': '',
'styleSheet': '',
'tabInsertsSpaces': True,
'tabWidth': 4,
'uiLanguage': QLocale.system().name(),
'useFakeVim': False,
'useWebKit': False,
'windowGeometry': QByteArray(),
}
def readFromSettings(key, keytype, settings=settings, default=None):
if isinstance(default, QFont):
family = readFromSettings(key, str, settings, default.family())
size = readFromSettings(key + 'Size', int, settings, 0)
return QFont(family, size)
if not settings.contains(key):
return default
try:
value = settings.value(key, type=keytype)
if isinstance(value, keytype):
return value
return keytype(value)
except TypeError as error:
# Type mismatch
print('Warning: '+str(error))
# Return an instance of keytype
return default if (default is not None) else keytype()
def readListFromSettings(key, settings=settings):
if not settings.contains(key):
return []
value = settings.value(key)
if isinstance(value, str):
return [value]
else:
return value
def writeToSettings(key, value, default, settings=settings):
if isinstance(value, QFont):
writeToSettings(key, value.family(), '', settings)
writeToSettings(key + 'Size', max(value.pointSize(), 0), 0, settings)
elif value == default:
settings.remove(key)
else:
settings.setValue(key, value)
def writeListToSettings(key, value, settings=settings):
if len(value) > 1:
settings.setValue(key, value)
elif len(value) == 1:
settings.setValue(key, value[0])
else:
settings.remove(key)
class ReTextSettings(object):
def __init__(self):
for option in configOptions:
value = configOptions[option]
object.__setattr__(self, option, readFromSettings(
option, type(value), default=value))
def __setattr__(self, option, value):
if not option in configOptions:
raise AttributeError('Unknown attribute')
object.__setattr__(self, option, value)
writeToSettings(option, value, configOptions[option])
globalSettings = ReTextSettings()
markups.common.PYGMENTS_STYLE = globalSettings.pygmentsStyle
ReText-5.3.1/ReText/fakevimeditor.py 0000644 0001750 0001750 00000021205 12700242644 020214 0 ustar dmitry dmitry 0000000 0000000 # This file is part of ReText
# Copyright: 2014 Lukas Holecek
#
# 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 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 .
from FakeVim import FakeVimProxy, FakeVimHandler, FAKEVIM_PYQT_VERSION, \
MessageError
if FAKEVIM_PYQT_VERSION != 5:
raise ImportError("FakeVim must be compiled with Qt 5")
from PyQt5.QtCore import QDir, QRegExp, QObject, Qt
from PyQt5.QtGui import QPainter, QPen, QTextCursor
from PyQt5.QtWidgets import QWidget, QLabel, QLineEdit, \
QMessageBox, QStatusBar, QTextEdit
class FakeVimMode:
@staticmethod
def init(window):
window.setStatusBar(StatusBar())
@staticmethod
def exit(window):
window.statusBar().deleteLater()
class Proxy (FakeVimProxy):
""" Used by FakeVim to modify or retrieve editor state. """
def __init__(self, window, editor, handler):
super(Proxy, self).__init__(handler.handler())
self.__handler = handler
self.__window = window
self.__editor = editor
self.__statusMessage = ""
self.__statusData = ""
self.__cursorPosition = -1
self.__cursorAnchor = -1
self.__eventFilter = None
self.__lastSavePath = ""
def showMessage(self, messageLevel, message):
self.__handler.handler().showMessage(messageLevel, message)
def needSave(self):
return self.__editor.document().isModified()
def maybeCloseEditor(self):
if self.needSave():
self.showMessage( MessageError,
self.tr("No write since last change (add ! to override)") )
self.__updateStatusBar()
return False
return True
def commandQuit(self):
self.__handler.quit()
def commandWrite(self):
self.__handler.save()
return not self.needSave()
def handleExCommand(self, cmd):
if cmd.matches("q", "quit"):
if cmd.hasBang or self.maybeCloseEditor():
self.commandQuit()
elif cmd.matches("w", "write"):
self.commandWrite()
elif cmd.cmd == "wq":
self.commandWrite() and self.commandQuit()
else:
return False
return True
def enableBlockSelection(self, cursor):
self.__handler.setBlockSelection(True)
self.__editor.setTextCursor(cursor)
def disableBlockSelection(self):
self.__handler.setBlockSelection(False)
def blockSelection(self):
self.__handler.setBlockSelection(True)
return self.__editor.textCursor()
def hasBlockSelection(self):
return self.__editor.hasBlockSelection()
def commandBufferChanged(self, msg, cursorPosition, cursorAnchor, messageLevel, eventFilter):
# Give focus back to editor if closing command line.
if self.__cursorPosition != -1 and cursorPosition == -1:
self.__editor.setFocus()
self.__cursorPosition = cursorPosition
self.__cursorAnchor = cursorAnchor
self.__statusMessage = msg
self.__updateStatusBar();
self.__eventFilter = eventFilter
def statusDataChanged(self, msg):
self.__statusData = msg
self.__updateStatusBar()
def extraInformationChanged(self, msg):
QMessageBox.information(self.__window, self.tr("Information"), msg)
def highlightMatches(self, pattern):
self.__handler.highlightMatches(pattern)
def __updateStatusBar(self):
self.__window.statusBar().setStatus(
self.__statusMessage, self.__statusData,
self.__cursorPosition, self.__cursorAnchor, self.__eventFilter)
class BlockSelection (QWidget):
def __init__(self, editor):
super(BlockSelection, self).__init__(editor.viewport())
self.__editor = editor
self.__lineWidth = 4
def updateSelection(self, tc):
# block selection rectagle
rect = self.__editor.cursorRect(tc)
w = rect.width()
tc2 = QTextCursor(tc)
tc2.setPosition(tc.anchor())
rect = rect.united( self.__editor.cursorRect(tc2) )
x = self.__lineWidth / 2
rect.adjust(-x, -x, x - w, x)
QWidget.setGeometry(self, rect)
def paintEvent(self, paintEvent):
painter = QPainter(self)
painter.setClipRect(paintEvent.rect())
color = self.__editor.palette().text()
painter.setPen(QPen(color, self.__lineWidth))
painter.drawRect(self.rect())
class ReTextFakeVimHandler (QObject):
""" Editor widget driven by FakeVim. """
def __init__(self, editor, window):
super(ReTextFakeVimHandler, self).__init__(window)
self.__window = window
self.__editor = editor
self.__blockSelection = BlockSelection(self.__editor)
self.__blockSelection.hide()
self.__searchSelections = []
fm = self.__editor.fontMetrics()
self.__cursorWidth = fm.averageCharWidth()
self.__oldCursorWidth = self.__editor.cursorWidth()
self.__editor.setCursorWidth(self.__cursorWidth)
self.__handler = FakeVimHandler(self.__editor, self)
self.__proxy = Proxy(self.__window, self.__editor, self)
self.__handler.installEventFilter()
self.__handler.setupWidget()
self.__handler.handleCommand(
'source {home}/.vimrc'.format(home = QDir.homePath()))
self.__saveAction = None
self.__quitAction = None
# Update selections if cursor changes because of current line can be highlighted.
self.__editor.cursorPositionChanged.connect(self.__updateSelections)
def remove(self):
self.__editor.setOverwriteMode(False)
self.__editor.setCursorWidth(self.__oldCursorWidth)
self.__blockSelection.deleteLater()
self.__updateSelections([])
self.deleteLater()
def handler(self):
return self.__handler
def setBlockSelection(self, enabled):
self.__editor.setCursorWidth(self.__cursorWidth)
self.__blockSelection.setVisible(enabled)
if enabled:
self.__blockSelection.updateSelection(self.__editor.textCursor())
# Shift text cursor into the block selection.
tc = self.__editor.textCursor()
if self.__columnForPosition(tc.anchor()) < self.__columnForPosition(tc.position()):
self.__editor.setCursorWidth(-self.__cursorWidth)
def setSaveAction(self, saveAction):
self.__saveAction = saveAction
def setQuitAction(self, quitAction):
self.__quitAction = quitAction
def save(self):
if self.__saveAction:
self.__saveAction.trigger()
def quit(self):
if self.__quitAction:
self.__quitAction.trigger()
def hasBlockSelection(self):
return self.__BlockSelection.isVisible()
def highlightMatches(self, pattern):
cur = self.__editor.textCursor()
re = QRegExp(pattern)
cur = self.__editor.document().find(re)
a = cur.position()
searchSelections = []
while not cur.isNull():
if cur.hasSelection():
selection = QTextEdit.ExtraSelection()
selection.format.setBackground(Qt.yellow)
selection.format.setForeground(Qt.black)
selection.cursor = cur
searchSelections.append(selection)
else:
cur.movePosition(QTextCursor.NextCharacter)
cur = self.__editor.document().find(re, cur)
b = cur.position()
if a == b:
cur.movePosition(QTextCursor.NextCharacter)
cur = self.__editor.document().find(re, cur)
b = cur.position()
if (a == b):
break
a = b
self.__updateSelections(searchSelections)
def __updateSelections(self, searchSelections = None):
oldSelections = self.__editor.extraSelections()
for selection in self.__searchSelections:
for i in range(len(oldSelections) - 1, 0, -1):
if selection.cursor == oldSelections[i].cursor:
oldSelections.pop(i)
break
if searchSelections != None:
self.__searchSelections = searchSelections
self.__editor.setExtraSelections(oldSelections + self.__searchSelections)
def __columnForPosition(self, position):
return position - self.__editor.document().findBlock(position).position()
class StatusBar (QStatusBar):
def __init__(self):
super(StatusBar, self).__init__()
self.__statusMessageLabel = QLabel(self)
self.__statusDataLabel = QLabel(self)
self.__commandLine = QLineEdit(self)
self.addPermanentWidget(self.__statusMessageLabel, 1)
self.addPermanentWidget(self.__commandLine, 1)
self.addPermanentWidget(self.__statusDataLabel)
self.__commandLine.hide()
def setStatus(self, statusMessage, statusData, cursorPosition, cursorAnchor, eventFilter):
commandMode = cursorPosition != -1
self.__commandLine.setVisible(commandMode)
self.__statusMessageLabel.setVisible(not commandMode)
if commandMode:
self.__commandLine.installEventFilter(eventFilter)
self.__commandLine.setFocus()
self.__commandLine.setText(statusMessage)
self.__commandLine.setSelection(cursorPosition, cursorAnchor - cursorPosition)
else:
self.__statusMessageLabel.setText(statusMessage)
self.__statusDataLabel.setText(statusData)
ReText-5.3.1/ReText/config.py 0000644 0001750 0001750 00000014522 12701276155 016641 0 ustar dmitry dmitry 0000000 0000000 # This file is part of ReText
# Copyright: 2013-2015 Dmitry Shachnev
#
# 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 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 .
import sys
from ReText import globalSettings, icon_path
from ReText.icontheme import get_icon_theme
from markups.common import CONFIGURATION_DIR
from os.path import join
from PyQt5.QtCore import QFile, QFileInfo, QUrl, Qt
from PyQt5.QtGui import QDesktopServices, QIcon
from PyQt5.QtWidgets import QCheckBox, QDialog, QDialogButtonBox, \
QFileDialog, QGridLayout, QLabel, QLineEdit, QPushButton, QSpinBox
MKD_EXTS_FILE = join(CONFIGURATION_DIR, 'markdown-extensions.txt')
class FileSelectButton(QPushButton):
def __init__(self, parent, fileName):
QPushButton.__init__(self, parent)
self.fileName = fileName
self.defaultText = self.tr('(none)')
self.updateButtonText()
self.clicked.connect(self.processClick)
def processClick(self):
startDir = (QFileInfo(self.fileName).absolutePath()
if self.fileName else '')
self.fileName = QFileDialog.getOpenFileName(
self, self.tr('Select file to open'), startDir)[0]
self.updateButtonText()
def updateButtonText(self):
if self.fileName:
self.setText(QFileInfo(self.fileName).fileName())
else:
self.setText(self.defaultText)
class ConfigDialog(QDialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
self.parent = parent
self.initConfigOptions()
self.layout = QGridLayout(self)
buttonBox = QDialogButtonBox(self)
buttonBox.setStandardButtons(QDialogButtonBox.Ok |
QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.saveSettings)
buttonBox.rejected.connect(self.close)
self.initWidgets()
self.layout.addWidget(buttonBox, len(self.options), 0, 1, 2)
def initConfigOptions(self):
# options is a tuple containing (displayname, name) tuples
self.options = (
(self.tr('Behavior'), None),
(self.tr('Automatically save documents'), 'autoSave'),
(self.tr('Restore window geometry'), 'saveWindowGeometry'),
(self.tr('Use live preview by default'), 'livePreviewByDefault'),
(self.tr('Open external links in ReText window'), 'handleWebLinks'),
(self.tr('Markdown syntax extensions (comma-separated)'), 'markdownExtensions'),
(None, 'markdownExtensions'),
# (self.tr('Default Markdown file extension'), 'markdownDefaultFileExtension'),
# (self.tr('Default reStructuredText file extension'), 'restDefaultFileExtension'),
(self.tr('Editor'), None),
(self.tr('Highlight current line'), 'highlightCurrentLine'),
(self.tr('Show line numbers'), 'lineNumbersEnabled'),
(self.tr('Tab key inserts spaces'), 'tabInsertsSpaces'),
(self.tr('Tabulation width'), 'tabWidth'),
(self.tr('Display right margin at column'), 'rightMargin'),
(self.tr('Interface'), None),
(self.tr('Icon theme name'), 'iconTheme'),
(self.tr('Stylesheet file'), 'styleSheet', True),
)
def initWidgets(self):
self.configurators = {}
for index, option in enumerate(self.options):
displayname, name = option[:2]
fileselector = option[2] if len(option) > 2 else False
if name is None:
header = QLabel('
%s
' % displayname, self)
self.layout.addWidget(header, index, 0, 1, 2, Qt.AlignHCenter)
continue
if displayname:
label = QLabel(displayname + ':', self)
if name == 'markdownExtensions':
if displayname:
url = QUrl('https://github.com/retext-project/retext/wiki/Markdown-extensions')
helpButton = QPushButton(self.tr('Help'), self)
helpButton.clicked.connect(lambda: QDesktopServices.openUrl(url))
self.layout.addWidget(label, index, 0)
self.layout.addWidget(helpButton, index, 1)
continue
try:
extsFile = open(MKD_EXTS_FILE)
value = extsFile.read().rstrip().replace(extsFile.newlines, ', ')
extsFile.close()
except Exception:
value = ''
self.configurators[name] = QLineEdit(self)
self.configurators[name].setText(value)
self.layout.addWidget(self.configurators[name], index, 0, 1, 2)
continue
value = getattr(globalSettings, name)
if isinstance(value, bool):
self.configurators[name] = QCheckBox(self)
self.configurators[name].setChecked(value)
elif isinstance(value, int):
self.configurators[name] = QSpinBox(self)
if name == 'tabWidth':
self.configurators[name].setRange(1, 10)
else:
self.configurators[name].setMaximum(200)
self.configurators[name].setValue(value)
elif isinstance(value, str) and fileselector:
self.configurators[name] = FileSelectButton(self, value)
elif isinstance(value, str):
self.configurators[name] = QLineEdit(self)
self.configurators[name].setText(value)
self.layout.addWidget(label, index, 0)
self.layout.addWidget(self.configurators[name], index, 1, Qt.AlignRight)
def saveSettings(self):
for option in self.options:
name = option[1]
if name is None or name == 'markdownExtensions':
continue
configurator = self.configurators[name]
if isinstance(configurator, QCheckBox):
value = configurator.isChecked()
elif isinstance(configurator, QSpinBox):
value = configurator.value()
elif isinstance(configurator, QLineEdit):
value = configurator.text()
elif isinstance(configurator, FileSelectButton):
value = configurator.fileName
setattr(globalSettings, name, value)
self.applySettings()
self.close()
def applySettings(self):
QIcon.setThemeName(globalSettings.iconTheme)
if QIcon.themeName() in ('hicolor', ''):
if not QFile.exists(icon_path + 'document-new.png'):
QIcon.setThemeName(get_icon_theme())
try:
extsFile = open(MKD_EXTS_FILE, 'w')
for ext in self.configurators['markdownExtensions'].text().split(','):
if ext.strip():
extsFile.write(ext.strip() + '\n')
extsFile.close()
except Exception as e:
print(e, file=sys.stderr)
for tab in self.parent.iterateTabs():
tab.editBox.updateFont()
self.parent.updateStyleSheet()
ReText-5.3.1/ReText/tablemode.py 0000644 0001750 0001750 00000013100 12701272775 017323 0 ustar dmitry dmitry 0000000 0000000 # This file is part of ReText
# Copyright: 2014 Maurice van der Pot
#
# 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 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 .
import sys
from markups import MarkdownMarkup, ReStructuredTextMarkup
from PyQt5.QtGui import QTextCursor
LARGER_THAN_ANYTHING = sys.maxsize
class Row:
def __init__(self, block=None, text=None, separatorline=False, paddingchar=' '):
self.block = block
self.text = text
self.separatorline = separatorline
self.paddingchar = paddingchar
def __repr__(self):
return "" % (self.text, self.separatorline, self.paddingchar)
def _getTableLines(doc, pos, markupClass):
startblock = doc.findBlock(pos)
editedlineindex = 0
offset = pos - startblock.position()
rows = [ Row(block = startblock,
text = startblock.text()) ]
block = startblock.previous()
while any(c in block.text() for c in '+|'):
rows.insert(0, Row(block = block,
text = block.text()))
editedlineindex += 1
block = block.previous()
block = startblock.next()
while any(c in block.text() for c in '+|'):
rows.append(Row(block = block,
text = block.text()))
block = block.next()
if markupClass == MarkdownMarkup:
for i, row in enumerate(rows):
if i == 1:
row.separatorline = True
row.paddingchar = '-'
elif markupClass == ReStructuredTextMarkup:
for i, row in enumerate(rows):
if i & 1 == 0: # i is even
row.separatorline = True
row.paddingchar = '=' if (i == 2) else '-'
row.text = row.text.replace('+', '|')
return rows, editedlineindex, offset
def _sortaUndoEdit(rows, editedlineindex, editsize):
aftertext = rows[editedlineindex].text
if editsize < 0:
beforetext = ' ' * -editsize + aftertext
else:
beforetext = aftertext[editsize:]
rows[editedlineindex].text = beforetext
def _determineRoomInCell(row, edge, shrinking, startposition=0):
if edge >= len(row.text) or row.text[edge] != '|':
room = LARGER_THAN_ANYTHING
else:
clearance = 0
cellwidth = 0
afterContent = True
for i in range(edge - 1, startposition - 1, -1):
if row.text[i] == '|':
break
else:
if row.text[i] == row.paddingchar and afterContent:
clearance += 1
else:
afterContent = False
cellwidth += 1
if row.separatorline:
if shrinking:
# do not shrink separator cells below 3
room = max(0, cellwidth - 3)
else:
# start expanding the cell if only the space for a right-align marker is left
room = max(0, cellwidth - 1)
else:
room = clearance
return room
def _performShift(row, rowShift, edge, shift):
editlist = []
if len(row.text) > edge and row.text[edge] == '|' and rowShift != shift:
editsize = -(rowShift - shift)
rowShift = shift
# Insert one position further to the left on separator lines, because
# there may be a space (for esthetical reasons) or an alignment marker
# on the last position before the edge and that should stay next to the
# edge.
if row.separatorline:
edge -= 1
editlist.append((edge, editsize))
return editlist, rowShift
def _determineNextEdge(rows, rowShifts, offset):
nextedge = None
for row, rowShift in zip(rows, rowShifts):
if rowShift != 0:
edge = row.text.find('|', offset)
if edge != -1 and (nextedge == None or edge < nextedge):
nextedge = edge
return nextedge
def _determineEditLists(rows, editedlineindex, offset, editsize):
rowShifts = [0 for _ in rows]
rowShifts[editedlineindex] = editsize
editLists = [[] for _ in rows]
currentedge = _determineNextEdge(rows, rowShifts, offset)
firstEdge = True
while currentedge:
if editsize < 0:
leastLeftShift = min((-rowShift + _determineRoomInCell(row, currentedge, True)
for row, rowShift in zip(rows, rowShifts)))
shift = max(editsize, -leastLeftShift)
else:
if firstEdge:
room = _determineRoomInCell(rows[editedlineindex], currentedge, False, offset)
shift = max(0, editsize - room)
for i, row in enumerate(rows):
editList, newRowShift = _performShift(row, rowShifts[i], currentedge, shift)
rowShifts[i] = newRowShift
editLists[i].extend(editList)
currentedge = _determineNextEdge(rows, rowShifts, currentedge + 1)
firstEdge = False
return editLists
def _performEdits(cursor, rows, editLists, linewithoffset, offset):
cursor.joinPreviousEditBlock()
for i, (row, editList) in enumerate(zip(rows, editLists)):
for editpos, editsize in sorted(editList, reverse=True):
if i == linewithoffset:
editpos += offset
cursor.setPosition(row.block.position() + editpos)
if editsize > 0:
cursor.insertText(editsize * row.paddingchar)
else:
for _ in range(-editsize):
cursor.deletePreviousChar()
cursor.endEditBlock()
def adjustTableToChanges(doc, pos, editsize, markupClass):
if markupClass in (MarkdownMarkup, ReStructuredTextMarkup):
rows, editedlineindex, offset = _getTableLines(doc, pos, markupClass)
_sortaUndoEdit(rows, editedlineindex, editsize)
editLists = _determineEditLists(rows, editedlineindex, offset, editsize)
cursor = QTextCursor(doc)
_performEdits(cursor, rows, editLists, editedlineindex, editsize)
ReText-5.3.1/ReText/window.py 0000644 0001750 0001750 00000117120 12701276155 016701 0 ustar dmitry dmitry 0000000 0000000 # This file is part of ReText
# Copyright: 2012-2015 Dmitry Shachnev
#
# 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 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 .
import markups
import sys
from subprocess import Popen
from ReText import icon_path, app_version, globalSettings, readListFromSettings, \
writeListToSettings, writeToSettings, datadirs, enchant, enchant_available
from ReText.tab import ReTextTab, PreviewNormal, PreviewLive
from ReText.dialogs import HtmlDialog, LocaleDialog
from ReText.config import ConfigDialog
from ReText.icontheme import get_icon_theme
try:
from ReText.fakevimeditor import ReTextFakeVimHandler, FakeVimMode
except ImportError:
ReTextFakeVimHandler = None
from PyQt5.QtCore import QDir, QFile, QFileInfo, QFileSystemWatcher, \
QIODevice, QLocale, QRect, QTextCodec, QTextStream, QTimer, QUrl, Qt
from PyQt5.QtGui import QColor, QDesktopServices, QIcon, \
QKeySequence, QPalette, QTextCursor, QTextDocument, QTextDocumentWriter
from PyQt5.QtWidgets import QAction, QActionGroup, QApplication, QCheckBox, \
QComboBox, QDesktopWidget, QDialog, QFileDialog, QFontDialog, QInputDialog, \
QLineEdit, QMainWindow, QMenu, QMenuBar, QMessageBox, QTabWidget, QToolBar
from PyQt5.QtPrintSupport import QPrintDialog, QPrintPreviewDialog, QPrinter
class ReTextWindow(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.resize(950, 700)
screenRect = QDesktopWidget().screenGeometry()
if globalSettings.windowGeometry:
self.restoreGeometry(globalSettings.windowGeometry)
else:
self.move((screenRect.width()-self.width())/2, (screenRect.height()-self.height())/2)
if not screenRect.contains(self.geometry()):
self.showMaximized()
if globalSettings.iconTheme:
QIcon.setThemeName(globalSettings.iconTheme)
if QIcon.themeName() in ('hicolor', ''):
if not QFile.exists(icon_path + 'document-new.png'):
QIcon.setThemeName(get_icon_theme())
if QFile.exists(icon_path+'retext.png'):
self.setWindowIcon(QIcon(icon_path+'retext.png'))
elif QFile.exists('/usr/share/pixmaps/retext.png'):
self.setWindowIcon(QIcon('/usr/share/pixmaps/retext.png'))
else:
self.setWindowIcon(QIcon.fromTheme('retext',
QIcon.fromTheme('accessories-text-editor')))
self.tabWidget = QTabWidget(self)
self.initTabWidget()
self.setCentralWidget(self.tabWidget)
self.tabWidget.currentChanged.connect(self.changeIndex)
self.tabWidget.tabCloseRequested.connect(self.closeTab)
toolBar = QToolBar(self.tr('File toolbar'), self)
self.addToolBar(Qt.TopToolBarArea, toolBar)
self.editBar = QToolBar(self.tr('Edit toolbar'), self)
self.addToolBar(Qt.TopToolBarArea, self.editBar)
self.searchBar = QToolBar(self.tr('Search toolbar'), self)
self.addToolBar(Qt.BottomToolBarArea, self.searchBar)
toolBar.setVisible(not globalSettings.hideToolBar)
self.editBar.setVisible(not globalSettings.hideToolBar)
self.actionNew = self.act(self.tr('New'), 'document-new',
self.createNew, shct=QKeySequence.New)
self.actionNew.setPriority(QAction.LowPriority)
self.actionOpen = self.act(self.tr('Open'), 'document-open',
self.openFile, shct=QKeySequence.Open)
self.actionOpen.setPriority(QAction.LowPriority)
self.actionSetEncoding = self.act(self.tr('Set encoding'),
trig=self.showEncodingDialog)
self.actionSetEncoding.setEnabled(False)
self.actionReload = self.act(self.tr('Reload'), 'view-refresh',
lambda: self.currentTab.readTextFromFile())
self.actionReload.setEnabled(False)
self.actionSave = self.act(self.tr('Save'), 'document-save',
self.saveFile, shct=QKeySequence.Save)
self.actionSave.setEnabled(False)
self.actionSave.setPriority(QAction.LowPriority)
self.actionSaveAs = self.act(self.tr('Save as'), 'document-save-as',
self.saveFileAs, shct=QKeySequence.SaveAs)
self.actionNextTab = self.act(self.tr('Next tab'), 'go-next',
lambda: self.switchTab(1), shct=Qt.CTRL+Qt.Key_PageDown)
self.actionPrevTab = self.act(self.tr('Previous tab'), 'go-previous',
lambda: self.switchTab(-1), shct=Qt.CTRL+Qt.Key_PageUp)
self.actionPrint = self.act(self.tr('Print'), 'document-print',
self.printFile, shct=QKeySequence.Print)
self.actionPrint.setPriority(QAction.LowPriority)
self.actionPrintPreview = self.act(self.tr('Print preview'), 'document-print-preview',
self.printPreview)
self.actionViewHtml = self.act(self.tr('View HTML code'), 'text-html', self.viewHtml)
self.actionChangeEditorFont = self.act(self.tr('Change editor font'),
trig=self.changeEditorFont)
self.actionChangePreviewFont = self.act(self.tr('Change preview font'),
trig=self.changePreviewFont)
self.actionSearch = self.act(self.tr('Find text'), 'edit-find', shct=QKeySequence.Find)
self.actionSearch.setCheckable(True)
self.actionSearch.triggered[bool].connect(self.searchBar.setVisible)
self.searchBar.visibilityChanged.connect(self.searchBarVisibilityChanged)
self.actionPreview = self.act(self.tr('Preview'), shct=Qt.CTRL+Qt.Key_E,
trigbool=self.preview)
if QIcon.hasThemeIcon('document-preview'):
self.actionPreview.setIcon(QIcon.fromTheme('document-preview'))
elif QIcon.hasThemeIcon('preview-file'):
self.actionPreview.setIcon(QIcon.fromTheme('preview-file'))
elif QIcon.hasThemeIcon('x-office-document'):
self.actionPreview.setIcon(QIcon.fromTheme('x-office-document'))
else:
self.actionPreview.setIcon(QIcon(icon_path+'document-preview.png'))
self.actionLivePreview = self.act(self.tr('Live preview'), shct=Qt.CTRL+Qt.Key_L,
trigbool=self.enableLivePreview)
menuPreview = QMenu()
menuPreview.addAction(self.actionLivePreview)
self.actionPreview.setMenu(menuPreview)
self.actionTableMode = self.act(self.tr('Table mode'), shct=Qt.CTRL+Qt.Key_T,
trigbool=lambda x: self.currentTab.editBox.enableTableMode(x))
if ReTextFakeVimHandler:
self.actionFakeVimMode = self.act(self.tr('FakeVim mode'),
shct=Qt.CTRL+Qt.ALT+Qt.Key_V, trigbool=self.enableFakeVimMode)
if globalSettings.useFakeVim:
self.actionFakeVimMode.setChecked(True)
self.enableFakeVimMode(True)
self.actionFullScreen = self.act(self.tr('Fullscreen mode'), 'view-fullscreen',
shct=Qt.Key_F11, trigbool=self.enableFullScreen)
self.actionFullScreen.setPriority(QAction.LowPriority)
self.actionConfig = self.act(self.tr('Preferences'), icon='preferences-system',
trig=self.openConfigDialog)
self.actionConfig.setMenuRole(QAction.PreferencesRole)
self.actionSaveHtml = self.act('HTML', 'text-html', self.saveFileHtml)
self.actionPdf = self.act('PDF', 'application-pdf', self.savePdf)
self.actionOdf = self.act('ODT', 'x-office-document', self.saveOdf)
self.getExportExtensionsList()
self.actionQuit = self.act(self.tr('Quit'), 'application-exit', shct=QKeySequence.Quit)
self.actionQuit.setMenuRole(QAction.QuitRole)
self.actionQuit.triggered.connect(self.close)
self.actionUndo = self.act(self.tr('Undo'), 'edit-undo',
lambda: self.currentTab.editBox.undo(), shct=QKeySequence.Undo)
self.actionRedo = self.act(self.tr('Redo'), 'edit-redo',
lambda: self.currentTab.editBox.redo(), shct=QKeySequence.Redo)
self.actionCopy = self.act(self.tr('Copy'), 'edit-copy',
lambda: self.currentTab.editBox.copy(), shct=QKeySequence.Copy)
self.actionCut = self.act(self.tr('Cut'), 'edit-cut',
lambda: self.currentTab.editBox.cut(), shct=QKeySequence.Cut)
self.actionPaste = self.act(self.tr('Paste'), 'edit-paste',
lambda: self.currentTab.editBox.paste(), shct=QKeySequence.Paste)
self.actionUndo.setEnabled(False)
self.actionRedo.setEnabled(False)
self.actionCopy.setEnabled(False)
self.actionCut.setEnabled(False)
qApp = QApplication.instance()
qApp.clipboard().dataChanged.connect(self.clipboardDataChanged)
self.clipboardDataChanged()
if enchant_available:
self.actionEnableSC = self.act(self.tr('Enable'), trigbool=self.enableSpellCheck)
self.actionSetLocale = self.act(self.tr('Set locale'), trig=self.changeLocale)
self.actionWebKit = self.act(self.tr('Use WebKit renderer'), trigbool=self.enableWebKit)
self.actionWebKit.setChecked(globalSettings.useWebKit)
self.actionShow = self.act(self.tr('Show directory'), 'system-file-manager', self.showInDir)
self.actionFind = self.act(self.tr('Next'), 'go-next', self.find,
shct=QKeySequence.FindNext)
self.actionFindPrev = self.act(self.tr('Previous'), 'go-previous',
lambda: self.find(back=True), shct=QKeySequence.FindPrevious)
self.actionHelp = self.act(self.tr('Get help online'), 'help-contents', self.openHelp)
self.aboutWindowTitle = self.tr('About ReText')
self.actionAbout = self.act(self.aboutWindowTitle, 'help-about', self.aboutDialog)
self.actionAbout.setMenuRole(QAction.AboutRole)
self.actionAboutQt = self.act(self.tr('About Qt'))
self.actionAboutQt.setMenuRole(QAction.AboutQtRole)
self.actionAboutQt.triggered.connect(qApp.aboutQt)
availableMarkups = markups.get_available_markups()
if not availableMarkups:
print('Warning: no markups are available!')
self.defaultMarkup = availableMarkups[0] if availableMarkups else None
if globalSettings.defaultMarkup:
mc = markups.find_markup_class_by_name(globalSettings.defaultMarkup)
if mc and mc.available():
self.defaultMarkup = mc
if len(availableMarkups) > 1:
self.chooseGroup = QActionGroup(self)
markupActions = []
for markup in availableMarkups:
markupAction = self.act(markup.name, trigbool=self.markupFunction(markup))
if markup == self.defaultMarkup:
markupAction.setChecked(True)
self.chooseGroup.addAction(markupAction)
markupActions.append(markupAction)
self.actionBold = self.act(self.tr('Bold'), shct=QKeySequence.Bold,
trig=lambda: self.insertChars('**'))
self.actionItalic = self.act(self.tr('Italic'), shct=QKeySequence.Italic,
trig=lambda: self.insertChars('*'))
self.actionUnderline = self.act(self.tr('Underline'), shct=QKeySequence.Underline,
trig=lambda: self.insertTag('u'))
self.usefulTags = ('a', 'big', 'center', 'img', 's', 'small', 'span',
'table', 'td', 'tr', 'u')
self.usefulChars = ('deg', 'divide', 'dollar', 'hellip', 'laquo', 'larr',
'lsquo', 'mdash', 'middot', 'minus', 'nbsp', 'ndash', 'raquo',
'rarr', 'rsquo', 'times')
self.tagsBox = QComboBox(self.editBar)
self.tagsBox.addItem(self.tr('Tags'))
self.tagsBox.addItems(self.usefulTags)
self.tagsBox.activated.connect(self.insertTag)
self.symbolBox = QComboBox(self.editBar)
self.symbolBox.addItem(self.tr('Symbols'))
self.symbolBox.addItems(self.usefulChars)
self.symbolBox.activated.connect(self.insertSymbol)
self.updateStyleSheet()
menubar = QMenuBar(self)
menubar.setGeometry(QRect(0, 0, 800, 25))
self.setMenuBar(menubar)
menuFile = menubar.addMenu(self.tr('File'))
menuEdit = menubar.addMenu(self.tr('Edit'))
menuHelp = menubar.addMenu(self.tr('Help'))
menuFile.addAction(self.actionNew)
menuFile.addAction(self.actionOpen)
self.menuRecentFiles = menuFile.addMenu(self.tr('Open recent'))
self.menuRecentFiles.aboutToShow.connect(self.updateRecentFiles)
menuFile.addMenu(self.menuRecentFiles)
menuFile.addAction(self.actionShow)
menuFile.addAction(self.actionSetEncoding)
menuFile.addAction(self.actionReload)
menuFile.addSeparator()
menuFile.addAction(self.actionSave)
menuFile.addAction(self.actionSaveAs)
menuFile.addSeparator()
menuFile.addAction(self.actionNextTab)
menuFile.addAction(self.actionPrevTab)
menuFile.addSeparator()
menuExport = menuFile.addMenu(self.tr('Export'))
menuExport.addAction(self.actionSaveHtml)
menuExport.addAction(self.actionOdf)
menuExport.addAction(self.actionPdf)
if self.extensionActions:
menuExport.addSeparator()
for action, mimetype in self.extensionActions:
menuExport.addAction(action)
menuExport.aboutToShow.connect(self.updateExtensionsVisibility)
menuFile.addAction(self.actionPrint)
menuFile.addAction(self.actionPrintPreview)
menuFile.addSeparator()
menuFile.addAction(self.actionQuit)
menuEdit.addAction(self.actionUndo)
menuEdit.addAction(self.actionRedo)
menuEdit.addSeparator()
menuEdit.addAction(self.actionCut)
menuEdit.addAction(self.actionCopy)
menuEdit.addAction(self.actionPaste)
menuEdit.addSeparator()
if enchant_available:
menuSC = menuEdit.addMenu(self.tr('Spell check'))
menuSC.addAction(self.actionEnableSC)
menuSC.addAction(self.actionSetLocale)
menuEdit.addAction(self.actionSearch)
menuEdit.addAction(self.actionChangeEditorFont)
menuEdit.addAction(self.actionChangePreviewFont)
menuEdit.addSeparator()
if len(availableMarkups) > 1:
self.menuMode = menuEdit.addMenu(self.tr('Default markup'))
for markupAction in markupActions:
self.menuMode.addAction(markupAction)
menuFormat = menuEdit.addMenu(self.tr('Formatting'))
menuFormat.addAction(self.actionBold)
menuFormat.addAction(self.actionItalic)
menuFormat.addAction(self.actionUnderline)
menuEdit.addAction(self.actionWebKit)
menuEdit.addSeparator()
menuEdit.addAction(self.actionViewHtml)
menuEdit.addAction(self.actionPreview)
menuEdit.addAction(self.actionTableMode)
if ReTextFakeVimHandler:
menuEdit.addAction(self.actionFakeVimMode)
menuEdit.addSeparator()
menuEdit.addAction(self.actionFullScreen)
menuEdit.addAction(self.actionConfig)
menuHelp.addAction(self.actionHelp)
menuHelp.addSeparator()
menuHelp.addAction(self.actionAbout)
menuHelp.addAction(self.actionAboutQt)
menubar.addMenu(menuFile)
menubar.addMenu(menuEdit)
menubar.addMenu(menuHelp)
toolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
toolBar.addAction(self.actionNew)
toolBar.addSeparator()
toolBar.addAction(self.actionOpen)
toolBar.addAction(self.actionSave)
toolBar.addAction(self.actionPrint)
toolBar.addSeparator()
toolBar.addAction(self.actionPreview)
toolBar.addAction(self.actionFullScreen)
self.editBar.addAction(self.actionUndo)
self.editBar.addAction(self.actionRedo)
self.editBar.addSeparator()
self.editBar.addAction(self.actionCut)
self.editBar.addAction(self.actionCopy)
self.editBar.addAction(self.actionPaste)
self.editBar.addSeparator()
self.editBar.addWidget(self.tagsBox)
self.editBar.addWidget(self.symbolBox)
self.searchEdit = QLineEdit(self.searchBar)
self.searchEdit.setPlaceholderText(self.tr('Search'))
self.searchEdit.returnPressed.connect(self.find)
self.csBox = QCheckBox(self.tr('Case sensitively'), self.searchBar)
self.searchBar.addWidget(self.searchEdit)
self.searchBar.addSeparator()
self.searchBar.addWidget(self.csBox)
self.searchBar.addAction(self.actionFindPrev)
self.searchBar.addAction(self.actionFind)
self.searchBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
self.searchBar.setVisible(False)
self.autoSaveEnabled = globalSettings.autoSave
if self.autoSaveEnabled:
timer = QTimer(self)
timer.start(60000)
timer.timeout.connect(self.saveAll)
self.ind = None
if enchant_available:
self.sl = globalSettings.spellCheckLocale
if self.sl:
try:
enchant.Dict(self.sl)
except Exception as e:
print(e, file=sys.stderr)
self.sl = None
if globalSettings.spellCheck:
self.actionEnableSC.setChecked(True)
self.enableSpellCheck(True)
self.fileSystemWatcher = QFileSystemWatcher()
self.fileSystemWatcher.fileChanged.connect(self.fileChanged)
def iterateTabs(self):
for i in range(self.tabWidget.count()):
yield self.tabWidget.widget(i).tab
def updateStyleSheet(self):
if globalSettings.styleSheet:
sheetfile = QFile(globalSettings.styleSheet)
sheetfile.open(QIODevice.ReadOnly)
self.ss = QTextStream(sheetfile).readAll()
sheetfile.close()
else:
self.ss = ''
def initTabWidget(self):
def dragEnterEvent(e):
e.acceptProposedAction()
def dropEvent(e):
fn = bytes(e.mimeData().data('text/plain')).decode().rstrip()
if fn.startswith('file:'):
fn = QUrl(fn).toLocalFile()
self.openFileWrapper(fn)
self.tabWidget.setTabsClosable(True)
self.tabWidget.setAcceptDrops(True)
self.tabWidget.setMovable(True)
self.tabWidget.dragEnterEvent = dragEnterEvent
self.tabWidget.dropEvent = dropEvent
def act(self, name, icon=None, trig=None, trigbool=None, shct=None):
if not isinstance(shct, QKeySequence):
shct = QKeySequence(shct)
if icon:
action = QAction(self.actIcon(icon), name, self)
else:
action = QAction(name, self)
if trig:
action.triggered.connect(trig)
elif trigbool:
action.setCheckable(True)
action.triggered[bool].connect(trigbool)
if shct:
action.setShortcut(shct)
return action
def actIcon(self, name):
return QIcon.fromTheme(name, QIcon(icon_path+name+'.png'))
def printError(self):
import traceback
print('Exception occured while parsing document:', file=sys.stderr)
traceback.print_exc()
def createTab(self, fileName):
self.currentTab = ReTextTab(self, fileName,
previewState=int(globalSettings.livePreviewByDefault))
self.tabWidget.addTab(self.currentTab.getSplitter(), self.tr("New document"))
def closeTab(self, ind):
if self.maybeSave(ind):
if self.tabWidget.count() == 1:
self.createTab("")
currentWidget = self.tabWidget.widget(ind)
if currentWidget.tab.fileName:
self.fileSystemWatcher.removePath(currentWidget.tab.fileName)
del currentWidget.tab
self.tabWidget.removeTab(ind)
def docTypeChanged(self):
markupClass = self.currentTab.getMarkupClass()
if type(self.currentTab.markup) != markupClass:
self.currentTab.setMarkupClass(markupClass)
self.currentTab.updatePreviewBox()
dtMarkdown = (markupClass == markups.MarkdownMarkup)
dtMkdOrReST = dtMarkdown or (markupClass == markups.ReStructuredTextMarkup)
self.tagsBox.setEnabled(dtMarkdown)
self.symbolBox.setEnabled(dtMarkdown)
self.actionUnderline.setEnabled(dtMarkdown)
self.actionBold.setEnabled(dtMkdOrReST)
self.actionItalic.setEnabled(dtMkdOrReST)
canReload = bool(self.currentTab.fileName) and not self.autoSaveActive()
self.actionSetEncoding.setEnabled(canReload)
self.actionReload.setEnabled(canReload)
def changeIndex(self, ind):
self.currentTab = self.tabWidget.currentWidget().tab
editBox = self.currentTab.editBox
previewState = self.currentTab.previewState
self.actionUndo.setEnabled(editBox.document().isUndoAvailable())
self.actionRedo.setEnabled(editBox.document().isRedoAvailable())
self.actionCopy.setEnabled(editBox.textCursor().hasSelection())
self.actionCut.setEnabled(editBox.textCursor().hasSelection())
self.actionPreview.setChecked(previewState >= PreviewLive)
self.actionLivePreview.setChecked(previewState == PreviewLive)
self.actionTableMode.setChecked(editBox.tableModeEnabled)
self.editBar.setEnabled(previewState < PreviewNormal)
self.ind = ind
if self.currentTab.fileName:
self.setCurrentFile()
else:
self.setWindowTitle(self.tr('New document') + '[*]')
self.docTypeChanged()
self.modificationChanged(editBox.document().isModified())
editBox.setFocus(Qt.OtherFocusReason)
def changeEditorFont(self):
font, ok = QFontDialog.getFont(globalSettings.editorFont, self)
if ok:
globalSettings.editorFont = font
for tab in self.iterateTabs():
tab.editBox.updateFont()
def changePreviewFont(self):
font, ok = QFontDialog.getFont(globalSettings.font, self)
if ok:
globalSettings.font = font
for tab in self.iterateTabs():
tab.updatePreviewBox()
def preview(self, viewmode):
self.currentTab.previewState = viewmode * 2
self.actionLivePreview.setChecked(False)
self.editBar.setDisabled(viewmode)
self.currentTab.updateBoxesVisibility()
if viewmode:
self.currentTab.updatePreviewBox()
def enableLivePreview(self, livemode):
self.currentTab.previewState = int(livemode)
self.actionPreview.setChecked(livemode)
self.editBar.setEnabled(True)
self.currentTab.updateBoxesVisibility()
if livemode:
self.currentTab.updatePreviewBox()
def enableWebKit(self, enable):
globalSettings.useWebKit = enable
for i in range(self.tabWidget.count()):
splitter = self.tabWidget.widget(i)
tab = splitter.tab
tab.previewBox.setParent(None)
tab.previewBox.deleteLater()
tab.previewBox = tab.createPreviewBox()
tab.previewBox.setMinimumWidth(125)
splitter.addWidget(tab.previewBox)
splitter.setSizes((50, 50))
tab.updatePreviewBox()
tab.updateBoxesVisibility()
def enableCopy(self, copymode):
self.actionCopy.setEnabled(copymode)
self.actionCut.setEnabled(copymode)
def enableFullScreen(self, yes):
if yes:
self.showFullScreen()
else:
self.showNormal()
def openConfigDialog(self):
dlg = ConfigDialog(self)
dlg.setWindowTitle(self.tr('Preferences'))
dlg.show()
def enableFakeVimMode(self, yes):
globalSettings.useFakeVim = yes
if yes:
FakeVimMode.init(self)
for tab in self.iterateTabs():
tab.installFakeVimHandler()
else:
FakeVimMode.exit(self)
def enableSpellCheck(self, yes):
if yes:
if self.sl:
self.setAllDictionaries(enchant.Dict(self.sl))
else:
self.setAllDictionaries(enchant.Dict())
else:
self.setAllDictionaries(None)
globalSettings.spellCheck = yes
def setAllDictionaries(self, dictionary):
for tab in self.iterateTabs():
hl = tab.highlighter
hl.dictionary = dictionary
hl.rehighlight()
def changeLocale(self):
if self.sl:
localedlg = LocaleDialog(self, defaultText=self.sl)
else:
localedlg = LocaleDialog(self)
if localedlg.exec() != QDialog.Accepted:
return
sl = localedlg.localeEdit.text()
setdefault = localedlg.checkBox.isChecked()
if sl:
try:
sl = str(sl)
enchant.Dict(sl)
except Exception as e:
QMessageBox.warning(self, '', str(e))
else:
self.sl = sl
self.enableSpellCheck(self.actionEnableSC.isChecked())
else:
self.sl = None
self.enableSpellCheck(self.actionEnableSC.isChecked())
if setdefault:
globalSettings.spellCheckLocale = sl
def searchBarVisibilityChanged(self, visible):
self.actionSearch.setChecked(visible)
if visible:
self.searchEdit.setFocus(Qt.ShortcutFocusReason)
def find(self, back=False):
flags = QTextDocument.FindFlags()
if back:
flags |= QTextDocument.FindBackward
if self.csBox.isChecked():
flags |= QTextDocument.FindCaseSensitively
text = self.searchEdit.text()
editBox = self.currentTab.editBox
cursor = editBox.textCursor()
newCursor = editBox.document().find(text, cursor, flags)
if not newCursor.isNull():
editBox.setTextCursor(newCursor)
return self.setSearchEditColor(True)
cursor.movePosition(QTextCursor.End if back else QTextCursor.Start)
newCursor = editBox.document().find(text, cursor, flags)
if not newCursor.isNull():
editBox.setTextCursor(newCursor)
return self.setSearchEditColor(True)
self.setSearchEditColor(False)
def setSearchEditColor(self, found):
palette = self.searchEdit.palette()
palette.setColor(QPalette.Active, QPalette.Base,
Qt.white if found else QColor(255, 102, 102))
self.searchEdit.setPalette(palette)
def showInDir(self):
if self.currentTab.fileName:
path = QFileInfo(self.currentTab.fileName).path()
QDesktopServices.openUrl(QUrl.fromLocalFile(path))
else:
QMessageBox.warning(self, '', self.tr("Please, save the file somewhere."))
def setCurrentFile(self):
self.setWindowTitle("")
self.tabWidget.setTabText(self.ind, self.currentTab.getDocumentTitle(baseName=True))
self.setWindowFilePath(self.currentTab.fileName)
files = readListFromSettings("recentFileList")
while self.currentTab.fileName in files:
files.remove(self.currentTab.fileName)
files.insert(0, self.currentTab.fileName)
if len(files) > 10:
del files[10:]
writeListToSettings("recentFileList", files)
QDir.setCurrent(QFileInfo(self.currentTab.fileName).dir().path())
self.docTypeChanged()
def createNew(self, text=None):
self.createTab("")
self.ind = self.tabWidget.count()-1
self.tabWidget.setCurrentIndex(self.ind)
if text:
self.currentTab.editBox.textCursor().insertText(text)
def switchTab(self, shift=1):
self.tabWidget.setCurrentIndex((self.ind + shift) % self.tabWidget.count())
def updateRecentFiles(self):
self.menuRecentFiles.clear()
self.recentFilesActions = []
filesOld = readListFromSettings("recentFileList")
files = []
for f in filesOld:
if QFile.exists(f):
files.append(f)
self.recentFilesActions.append(self.act(f, trig=self.openFunction(f)))
writeListToSettings("recentFileList", files)
for action in self.recentFilesActions:
self.menuRecentFiles.addAction(action)
def markupFunction(self, markup):
return lambda: self.setDefaultMarkup(markup)
def openFunction(self, fileName):
return lambda: self.openFileWrapper(fileName)
def extensionFunction(self, data):
return lambda: \
self.runExtensionCommand(data['Exec'], data['FileFilter'], data['DefaultExtension'])
def getExportExtensionsList(self):
extensions = []
for extsprefix in datadirs:
extsdir = QDir(extsprefix+'/export-extensions/')
if extsdir.exists():
for fileInfo in extsdir.entryInfoList(['*.desktop', '*.ini'],
QDir.Files | QDir.Readable):
extensions.append(self.readExtension(fileInfo.filePath()))
locale = QLocale.system().name()
self.extensionActions = []
for extension in extensions:
try:
if ('Name[%s]' % locale) in extension:
name = extension['Name[%s]' % locale]
elif ('Name[%s]' % locale.split('_')[0]) in extension:
name = extension['Name[%s]' % locale.split('_')[0]]
else:
name = extension['Name']
data = {}
for prop in ('FileFilter', 'DefaultExtension', 'Exec'):
if 'X-ReText-'+prop in extension:
data[prop] = extension['X-ReText-'+prop]
elif prop in extension:
data[prop] = extension[prop]
else:
data[prop] = ''
action = self.act(name, trig=self.extensionFunction(data))
if 'Icon' in extension:
action.setIcon(self.actIcon(extension['Icon']))
mimetype = extension['MimeType'] if 'MimeType' in extension else None
except KeyError:
print('Failed to parse extension: Name is required', file=sys.stderr)
else:
self.extensionActions.append((action, mimetype))
def updateExtensionsVisibility(self):
markupClass = self.currentTab.getMarkupClass()
for action in self.extensionActions:
if markupClass is None:
action[0].setEnabled(False)
continue
mimetype = action[1]
if mimetype == None:
enabled = True
elif markupClass == markups.MarkdownMarkup:
enabled = (mimetype in ("text/x-retext-markdown", "text/x-markdown"))
elif markupClass == markups.ReStructuredTextMarkup:
enabled = (mimetype in ("text/x-retext-rst", "text/x-rst"))
else:
enabled = False
action[0].setEnabled(enabled)
def readExtension(self, fileName):
extFile = QFile(fileName)
extFile.open(QIODevice.ReadOnly)
extension = {}
stream = QTextStream(extFile)
while not stream.atEnd():
line = stream.readLine()
if '=' in line:
index = line.index('=')
extension[line[:index].rstrip()] = line[index+1:].lstrip()
extFile.close()
return extension
def openFile(self):
supportedExtensions = ['.txt']
for markup in markups.get_all_markups():
supportedExtensions += markup.file_extensions
fileFilter = ' (' + str.join(' ', ['*'+ext for ext in supportedExtensions]) + ');;'
fileNames = QFileDialog.getOpenFileNames(self,
self.tr("Select one or several files to open"), "",
self.tr("Supported files") + fileFilter + self.tr("All files (*)"))
for fileName in fileNames[0]:
self.openFileWrapper(fileName)
def openFileWrapper(self, fileName):
if not fileName:
return
fileName = QFileInfo(fileName).canonicalFilePath()
exists = False
for i, tab in enumerate(self.iterateTabs()):
if tab.fileName == fileName:
exists = True
ex = i
if exists:
self.tabWidget.setCurrentIndex(ex)
elif QFile.exists(fileName):
noEmptyTab = (
(self.ind is None) or
self.currentTab.fileName or
self.currentTab.editBox.toPlainText() or
self.currentTab.editBox.document().isModified()
)
if noEmptyTab:
self.createTab(fileName)
self.ind = self.tabWidget.count()-1
self.tabWidget.setCurrentIndex(self.ind)
if fileName:
self.fileSystemWatcher.addPath(fileName)
self.currentTab.fileName = fileName
self.currentTab.readTextFromFile()
editBox = self.currentTab.editBox
self.setCurrentFile()
self.setWindowModified(editBox.document().isModified())
def showEncodingDialog(self):
if not self.maybeSave(self.ind):
return
encoding, ok = QInputDialog.getItem(self, '',
self.tr('Select file encoding from the list:'),
[bytes(b).decode() for b in QTextCodec.availableCodecs()],
0, False)
if ok:
self.currentTab.readTextFromFile(encoding)
def saveFileAs(self):
self.saveFile(dlg=True)
def saveAll(self):
for tab in self.iterateTabs():
if tab.fileName and QFileInfo(tab.fileName).isWritable():
tab.saveTextToFile()
tab.editBox.document().setModified(False)
def saveFile(self, dlg=False):
if (not self.currentTab.fileName) or dlg:
markupClass = self.currentTab.getMarkupClass()
if (markupClass is None) or not hasattr(markupClass, 'default_extension'):
defaultExt = self.tr("Plain text (*.txt)")
ext = ".txt"
else:
defaultExt = self.tr('%s files',
'Example of final string: Markdown files') \
% markupClass.name + ' (' + str.join(' ',
('*'+extension for extension in markupClass.file_extensions)) + ')'
if markupClass == markups.MarkdownMarkup:
ext = globalSettings.markdownDefaultFileExtension
elif markupClass == markups.ReStructuredTextMarkup:
ext = globalSettings.restDefaultFileExtension
else:
ext = markupClass.default_extension
newFileName = QFileDialog.getSaveFileName(self,
self.tr("Save file"), "", defaultExt)[0]
if newFileName:
if not QFileInfo(newFileName).suffix():
newFileName += ext
if self.currentTab.fileName:
self.fileSystemWatcher.removePath(self.currentTab.fileName)
self.currentTab.fileName = newFileName
self.actionSetEncoding.setDisabled(self.autoSaveActive())
if self.currentTab.fileName:
if self.currentTab.saveTextToFile():
self.setCurrentFile()
self.currentTab.editBox.document().setModified(False)
self.setWindowModified(False)
return True
else:
QMessageBox.warning(self, '',
self.tr("Cannot save to file because it is read-only!"))
return False
def saveHtml(self, fileName):
if not QFileInfo(fileName).suffix():
fileName += ".html"
try:
htmltext = self.currentTab.getHtml(includeStyleSheet=False,
includeMeta=True, webenv=True)
except Exception:
return self.printError()
htmlFile = QFile(fileName)
htmlFile.open(QIODevice.WriteOnly)
html = QTextStream(htmlFile)
if globalSettings.defaultCodec:
html.setCodec(globalSettings.defaultCodec)
html << htmltext
htmlFile.close()
def textDocument(self):
td = QTextDocument()
td.setMetaInformation(QTextDocument.DocumentTitle,
self.currentTab.getDocumentTitle())
if self.ss:
td.setDefaultStyleSheet(self.ss)
td.setHtml(self.currentTab.getHtml())
td.setDefaultFont(globalSettings.font)
return td
def saveOdf(self):
try:
document = self.textDocument()
except Exception:
return self.printError()
fileName = QFileDialog.getSaveFileName(self,
self.tr("Export document to ODT"), "",
self.tr("OpenDocument text files (*.odt)"))[0]
if not QFileInfo(fileName).suffix():
fileName += ".odt"
writer = QTextDocumentWriter(fileName)
writer.setFormat(b"odf")
writer.write(document)
def saveFileHtml(self):
fileName = QFileDialog.getSaveFileName(self,
self.tr("Save file"), "",
self.tr("HTML files (*.html *.htm)"))[0]
if fileName:
self.saveHtml(fileName)
def getDocumentForPrint(self):
if globalSettings.useWebKit:
return self.currentTab.previewBox
try:
return self.textDocument()
except Exception:
self.printError()
def standardPrinter(self):
printer = QPrinter(QPrinter.HighResolution)
printer.setDocName(self.currentTab.getDocumentTitle())
printer.setCreator('ReText %s' % app_version)
return printer
def savePdf(self):
self.currentTab.updatePreviewBox()
fileName = QFileDialog.getSaveFileName(self,
self.tr("Export document to PDF"),
"", self.tr("PDF files (*.pdf)"))[0]
if fileName:
if not QFileInfo(fileName).suffix():
fileName += ".pdf"
printer = self.standardPrinter()
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName(fileName)
document = self.getDocumentForPrint()
if document != None:
document.print(printer)
def printFile(self):
self.currentTab.updatePreviewBox()
printer = self.standardPrinter()
dlg = QPrintDialog(printer, self)
dlg.setWindowTitle(self.tr("Print document"))
if (dlg.exec() == QDialog.Accepted):
document = self.getDocumentForPrint()
if document != None:
document.print(printer)
def printPreview(self):
document = self.getDocumentForPrint()
if document == None:
return
printer = self.standardPrinter()
preview = QPrintPreviewDialog(printer, self)
preview.paintRequested.connect(document.print)
preview.exec()
def runExtensionCommand(self, command, filefilter, defaultext):
of = ('%of' in command)
html = ('%html' in command)
if of:
if defaultext and not filefilter:
filefilter = '*'+defaultext
fileName = QFileDialog.getSaveFileName(self,
self.tr('Export document'), '', filefilter)[0]
if not fileName:
return
if defaultext and not QFileInfo(fileName).suffix():
fileName += defaultext
basename = '.%s.retext-temp' % self.currentTab.getDocumentTitle(baseName=True)
if html:
tmpname = basename+'.html'
self.saveHtml(tmpname)
else:
tmpname = basename + self.currentTab.getMarkupClass().default_extension
self.currentTab.saveTextToFile(fileName=tmpname, addToWatcher=False)
command = command.replace('%of', '"out'+defaultext+'"')
command = command.replace('%html' if html else '%if', '"'+tmpname+'"')
try:
Popen(str(command), shell=True).wait()
except Exception as error:
errorstr = str(error)
QMessageBox.warning(self, '', self.tr('Failed to execute the command:')
+ '\n' + errorstr)
QFile(tmpname).remove()
if of:
QFile('out'+defaultext).rename(fileName)
def autoSaveActive(self, ind=None):
tab = self.currentTab if ind is None else self.tabWidget.widget(ind).tab
return (self.autoSaveEnabled and tab.fileName and
QFileInfo(tab.fileName).isWritable())
def modificationChanged(self, changed):
if self.autoSaveActive():
changed = False
self.actionSave.setEnabled(changed)
self.setWindowModified(changed)
def clipboardDataChanged(self):
mimeData = QApplication.instance().clipboard().mimeData()
if mimeData is not None:
self.actionPaste.setEnabled(mimeData.hasText())
def insertChars(self, chars):
tc = self.currentTab.editBox.textCursor()
if tc.hasSelection():
selection = tc.selectedText()
if selection.startswith(chars) and selection.endswith(chars):
if len(selection) > 2*len(chars):
selection = selection[len(chars):-len(chars)]
tc.insertText(selection)
else:
tc.insertText(chars+tc.selectedText()+chars)
else:
tc.insertText(chars)
def insertTag(self, ut):
if not ut:
return
if isinstance(ut, int):
ut = self.usefulTags[ut - 1]
arg = ' style=""' if ut == 'span' else ''
tc = self.currentTab.editBox.textCursor()
if ut == 'img':
toinsert = ('')
elif ut == 'a':
toinsert = ('' + tc.selectedText() + '')
else:
toinsert = '<'+ut+arg+'>'+tc.selectedText()+''+ut+'>'
tc.insertText(toinsert)
self.tagsBox.setCurrentIndex(0)
def insertSymbol(self, num):
if num:
self.currentTab.editBox.insertPlainText('&'+self.usefulChars[num-1]+';')
self.symbolBox.setCurrentIndex(0)
def fileChanged(self, fileName):
ind = None
for testind, tab in enumerate(self.iterateTabs()):
if tab.fileName == fileName:
ind = testind
if ind is None:
self.fileSystemWatcher.removePath(fileName)
self.tabWidget.setCurrentIndex(ind)
if not QFile.exists(fileName):
self.currentTab.editBox.document().setModified(True)
QMessageBox.warning(self, '', self.tr(
'This file has been deleted by other application.\n'
'Please make sure you save the file before exit.'))
elif not self.currentTab.editBox.document().isModified():
# File was not modified in ReText, reload silently
self.currentTab.readTextFromFile()
self.currentTab.updatePreviewBox()
else:
text = self.tr(
'This document has been modified by other application.\n'
'Do you want to reload the file (this will discard all '
'your changes)?\n')
if self.autoSaveEnabled:
text += self.tr(
'If you choose to not reload the file, auto save mode will '
'be disabled for this session to prevent data loss.')
messageBox = QMessageBox(QMessageBox.Warning, '', text)
reloadButton = messageBox.addButton(self.tr('Reload'), QMessageBox.YesRole)
messageBox.addButton(QMessageBox.Cancel)
messageBox.exec()
if messageBox.clickedButton() is reloadButton:
self.currentTab.readTextFromFile()
self.currentTab.updatePreviewBox()
else:
self.autoSaveEnabled = False
self.currentTab.editBox.document().setModified(True)
if fileName not in self.fileSystemWatcher.files():
# https://github.com/retext-project/retext/issues/137
self.fileSystemWatcher.addPath(fileName)
def maybeSave(self, ind):
tab = self.tabWidget.widget(ind).tab
if self.autoSaveActive(ind):
tab.saveTextToFile()
return True
if not tab.editBox.document().isModified():
return True
self.tabWidget.setCurrentIndex(ind)
ret = QMessageBox.warning(self, '',
self.tr("The document has been modified.\nDo you want to save your changes?"),
QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
if ret == QMessageBox.Save:
return self.saveFile(False)
elif ret == QMessageBox.Cancel:
return False
return True
def closeEvent(self, closeevent):
for ind in range(self.tabWidget.count()):
if not self.maybeSave(ind):
return closeevent.ignore()
if globalSettings.saveWindowGeometry and not self.isMaximized():
globalSettings.windowGeometry = self.saveGeometry()
closeevent.accept()
def viewHtml(self):
htmlDlg = HtmlDialog(self)
try:
htmltext = self.currentTab.getHtml(includeStyleSheet=False,
includeTitle=False)
except Exception:
return self.printError()
winTitle = self.currentTab.getDocumentTitle(baseName=True)
htmlDlg.setWindowTitle(winTitle+" ("+self.tr("HTML code")+")")
htmlDlg.textEdit.setPlainText(htmltext.rstrip())
htmlDlg.hl.rehighlight()
htmlDlg.show()
htmlDlg.raise_()
htmlDlg.activateWindow()
def openHelp(self):
QDesktopServices.openUrl(QUrl('https://github.com/retext-project/retext/wiki'))
def aboutDialog(self):
QMessageBox.about(self, self.aboutWindowTitle,
'
')
def setDefaultMarkup(self, markupClass):
self.defaultMarkup = markupClass
defaultName = markups.get_available_markups()[0].name
writeToSettings('defaultMarkup', markupClass.name, defaultName)
for tab in self.iterateTabs():
if not tab.fileName:
tab.setMarkupClass(markupClass)
tab.updatePreviewBox()
self.docTypeChanged()
ReText-5.3.1/ReText/xsettings.py 0000644 0001750 0001750 00000015362 12700242644 017422 0 ustar dmitry dmitry 0000000 0000000 # This file is part of ReText
# Copyright: 2015 Dmitry Shachnev
#
# 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 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 .
# This is implementation of XSettings specification, described at
#
import ctypes
import ctypes.util
import struct
class _xcb_reply_t(ctypes.Structure):
# this can be used instead of xcb_intern_atom_reply_t,
# xcb_get_selection_owner_reply_t, etc
_fields_ = [('response_type', ctypes.c_uint8),
('pad0', ctypes.c_uint8),
('sequence', ctypes.c_uint16),
('length', ctypes.c_uint32),
('payload', ctypes.c_uint32)]
class _xcb_cookie_t(ctypes.Structure):
# this can be used instead of xcb_intern_atom_cookie_t,
# xcb_get_selection_owner_cookie_t, etc
_fields_ = [('sequence', ctypes.c_uint)]
_xcb_error_messages = [
None,
'XCB error: socket, pipe and other stream error',
'XCB connection closed: extension unsupported',
'XCB connection closed: insufficient memory',
'XCB connection closed: request length exceeded',
'XCB connection closed: DISPLAY parse error',
'XCB connection closed: invalid screen'
]
class XSettingsError(RuntimeError):
pass
class XSettingsParseError(XSettingsError):
pass
def get_raw_xsettings(display=0):
# initialize the libraries
xcb_library_name = ctypes.util.find_library('xcb')
if xcb_library_name is None:
raise XSettingsError('Xcb library not found')
xcb = ctypes.CDLL(xcb_library_name)
c_library_name = ctypes.util.find_library('c')
if c_library_name is None:
raise XSettingsError('C library not found')
c = ctypes.CDLL(c_library_name)
# set some args and return types
xcb.xcb_connect.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_int)]
xcb.xcb_connect.restype = ctypes.c_void_p
xcb.xcb_connection_has_error.argtypes = [ctypes.c_void_p]
xcb.xcb_connection_has_error.restype = ctypes.c_int
xcb.xcb_disconnect.argtypes = [ctypes.c_void_p]
xcb.xcb_disconnect.restype = None
xcb.xcb_intern_atom.argtypes = [ctypes.c_void_p, ctypes.c_uint8, ctypes.c_uint16, ctypes.c_char_p]
xcb.xcb_intern_atom.restype = _xcb_cookie_t
xcb.xcb_intern_atom_reply.argtypes = [ctypes.c_void_p, _xcb_cookie_t, ctypes.c_void_p]
xcb.xcb_intern_atom_reply.restype = ctypes.POINTER(_xcb_reply_t)
xcb.xcb_get_selection_owner.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
xcb.xcb_get_selection_owner.restype = _xcb_cookie_t
xcb.xcb_get_selection_owner_reply.argtypes = [ctypes.c_void_p, _xcb_cookie_t, ctypes.c_void_p]
xcb.xcb_get_selection_owner_reply.restype = ctypes.POINTER(_xcb_reply_t)
xcb.xcb_get_property.argtypes = [ctypes.c_void_p, ctypes.c_uint8, ctypes.c_uint32, ctypes.c_uint32,
ctypes.c_uint32, ctypes.c_uint32]
xcb.xcb_get_property.restype = _xcb_cookie_t
xcb.xcb_get_property_reply.argtypes = [ctypes.c_void_p, _xcb_cookie_t, ctypes.c_void_p]
xcb.xcb_get_property_reply.restype = ctypes.c_void_p
xcb.xcb_get_property_value_length.argtypes = [ctypes.c_void_p]
xcb.xcb_get_property_value_length.restype = ctypes.c_int
xcb.xcb_get_property_value.argtypes = [ctypes.c_void_p]
xcb.xcb_get_property_value.restype = ctypes.c_void_p
# open the connection
connection = xcb.xcb_connect(None, None)
error = xcb.xcb_connection_has_error(connection)
if error:
raise XSettingsError(_xcb_error_messages[error])
# get selection atom cookie
buffer = ('_XSETTINGS_S%d' % display).encode()
cookie = xcb.xcb_intern_atom(connection, 0, len(buffer), buffer)
# get selection atom reply
reply = xcb.xcb_intern_atom_reply(connection, cookie, None)
selection_atom = reply.contents.payload
c.free(reply)
# get selection owner cookie
cookie = xcb.xcb_get_selection_owner(connection, selection_atom)
# get selection owner reply
reply = xcb.xcb_get_selection_owner_reply(connection, cookie, None)
window = reply.contents.payload
c.free(reply)
# get settings atom cookie
buffer = b'_XSETTINGS_SETTINGS'
cookie = xcb.xcb_intern_atom(connection, 0, len(buffer), buffer)
# get settings atom reply
reply = xcb.xcb_intern_atom_reply(connection, cookie, None)
settings_atom = reply.contents.payload
c.free(reply)
# get property cookie
cookie = xcb.xcb_get_property(connection, 0, window, settings_atom, 0, 0, 0x2000)
# get property reply
reply = xcb.xcb_get_property_reply(connection, cookie, None)
if reply is not None:
length = xcb.xcb_get_property_value_length(reply)
pointer = xcb.xcb_get_property_value(reply) if length else None
result = ctypes.string_at(pointer, length)
c.free(reply)
# close the connection
xcb.xcb_disconnect(connection)
# handle possible errors
if reply is None or not length:
raise XSettingsError('XSettings not available')
return result
def parse_xsettings(raw_xsettings):
if len(raw_xsettings) < 12:
raise XSettingsParseError('length < 12')
if raw_xsettings[0] not in (0, 1):
raise XSettingsParseError('wrong order byte: %d' % raw_xsettings[0])
byte_order = '<>'[raw_xsettings[0]]
settings_count = struct.unpack(byte_order + 'I', raw_xsettings[8:12])[0]
TypeInteger, TypeString, TypeColor = range(3)
result = {}
raw_xsettings = raw_xsettings[12:]
offset = 0
for i in range(settings_count):
setting_type = raw_xsettings[offset]
offset += 2
name_length = struct.unpack(byte_order + 'H', raw_xsettings[offset:offset + 2])[0]
offset += 2
name = raw_xsettings[offset:offset + name_length]
offset += name_length
if offset & 3:
offset += 4 - (offset & 3)
offset += 4 # skip last-change-serial
if setting_type == TypeInteger:
value = struct.unpack(byte_order + 'I', raw_xsettings[offset:offset + 4])[0]
offset += 4
elif setting_type == TypeString:
value_length = struct.unpack(byte_order + 'I', raw_xsettings[offset:offset + 4])[0]
offset += 4
value = raw_xsettings[offset:offset + value_length]
offset += value_length
if offset & 3:
offset += 4 - (offset & 3)
elif setting_type == TypeColor:
value = struct.unpack(byte_order + 'HHHH', raw_xsettings[offset:offset + 8])
offset += 8
else:
raise XSettingsParseError('Wrong setting type: %d' % setting_type)
result[name] = value
return result
def get_xsettings(display=0):
raw_xsettings = get_raw_xsettings(display)
return parse_xsettings(raw_xsettings)
ReText-5.3.1/ReText/dialogs.py 0000644 0001750 0001750 00000004242 12701272775 017020 0 ustar dmitry dmitry 0000000 0000000 # This file is part of ReText
# Copyright: 2012-2015 Dmitry Shachnev
#
# 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 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 .
from ReText import globalSettings
from ReText.highlighter import ReTextHighlighter
from PyQt5.QtWidgets import QCheckBox, QDialog, QDialogButtonBox, \
QLabel, QLineEdit, QTextEdit, QVBoxLayout
class HtmlDialog(QDialog):
def __init__(self, parent=None):
QDialog.__init__(self, parent)
self.resize(700, 600)
verticalLayout = QVBoxLayout(self)
self.textEdit = QTextEdit(self)
self.textEdit.setReadOnly(True)
self.textEdit.setFont(globalSettings.editorFont)
self.hl = ReTextHighlighter(self.textEdit.document())
self.hl.docType = 'html'
verticalLayout.addWidget(self.textEdit)
buttonBox = QDialogButtonBox(self)
buttonBox.setStandardButtons(QDialogButtonBox.Close)
buttonBox.rejected.connect(self.close)
verticalLayout.addWidget(buttonBox)
class LocaleDialog(QDialog):
def __init__(self, parent, defaultText=""):
QDialog.__init__(self, parent)
verticalLayout = QVBoxLayout(self)
self.label = QLabel(self)
self.label.setText(self.tr('Enter locale name (example: en_US)'))
verticalLayout.addWidget(self.label)
self.localeEdit = QLineEdit(self)
self.localeEdit.setText(defaultText)
verticalLayout.addWidget(self.localeEdit)
self.checkBox = QCheckBox(self.tr('Set as default'), self)
verticalLayout.addWidget(self.checkBox)
buttonBox = QDialogButtonBox(self)
buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
verticalLayout.addWidget(buttonBox)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
ReText-5.3.1/ReText/highlighter.py 0000644 0001750 0001750 00000012711 12700242644 017663 0 ustar dmitry dmitry 0000000 0000000 # This file is part of ReText
# Copyright: 2012-2015 Dmitry Shachnev
#
# 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 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 .
from ReText import settings
import re
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor, QFont, QSyntaxHighlighter, QTextCharFormat
reHtmlTags = re.compile('<[^<>@]*>')
reHtmlSymbols = re.compile(r'?\w+;')
reHtmlStrings = re.compile('"[^"<]*"(?=[^<]*>)')
reHtmlComments = re.compile('')
reAsterisks = re.compile(r'(?.+')
reReSTDirects = re.compile(r'\.\. [a-z]+::')
reReSTRoles = re.compile(':[a-z]+:')
reTextileHdrs = re.compile(r'^h[1-6][()<>=]*\.\s.+')
reTextileQuot = re.compile(r'^bq\.\s.+')
reWords = re.compile('[^_\\W]+', flags=re.UNICODE)
reSpacesOnEnd = re.compile(r'\s+$', flags=re.UNICODE)
defaultColorScheme = {
'htmlTags': Qt.darkMagenta,
'htmlSymbols': Qt.darkCyan,
'htmlStrings': Qt.darkYellow,
'htmlComments': Qt.gray,
'markdownLinks': Qt.blue,
'blockquotes': Qt.darkGray,
'restDirectives': Qt.darkMagenta,
'restRoles': Qt.darkRed,
'whitespaceOnEnd': QColor(0xf0, 0xf0, 0xd2)
}
colorScheme = {}
def updateColorScheme(settings=settings):
settings.beginGroup('ColorScheme')
for key in defaultColorScheme:
if settings.contains(key):
colorScheme[key] = settings.value(key, type=QColor)
else:
colorScheme[key] = defaultColorScheme[key]
settings.endGroup()
updateColorScheme()
class ReTextHighlighter(QSyntaxHighlighter):
dictionary = None
docType = None
def highlightBlock(self, text):
patterns = (
# regex, color, font style, italic, underline
(reHtmlTags, 'htmlTags', QFont.Bold), # 0
(reHtmlSymbols, 'htmlSymbols', QFont.Bold), # 1
(reHtmlStrings, 'htmlStrings', QFont.Bold), # 2
(reHtmlComments, 'htmlComments', QFont.Normal), # 3
(reAsterisks, None, QFont.Normal, True), # 4
(reUnderline, None, QFont.Normal, True), # 5
(reDblAsterisks, None, QFont.Bold), # 6
(reDblUnderline, None, QFont.Bold), # 7
(reTrpAsterisks, None, QFont.Bold, True), # 8
(reTrpUnderline, None, QFont.Bold, True), # 9
(reMkdHeaders, None, QFont.Black), # 10
(reMkdLinksImgs, 'markdownLinks', QFont.Normal), # 11
(reMkdLinkRefs, None, QFont.Normal, True, True), # 12
(reBlockQuotes, 'blockquotes', QFont.Normal), # 13
(reReSTDirects, 'restDirectives', QFont.Bold), # 14
(reReSTRoles, 'restRoles', QFont.Bold), # 15
(reTextileHdrs, None, QFont.Black), # 16
(reTextileQuot, 'blockquotes', QFont.Normal), # 17
(reAsterisks, None, QFont.Bold), # 18
(reDblUnderline, None, QFont.Normal, True), # 19
)
patternsDict = {
'Markdown': (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13),
'reStructuredText': (4, 6, 14, 15),
'Textile': (0, 5, 6, 16, 17, 18, 19),
'html': (0, 1, 2, 3)
}
# Syntax highlighter
if self.docType in patternsDict:
for number in patternsDict[self.docType]:
pattern = patterns[number]
charFormat = QTextCharFormat()
charFormat.setFontWeight(pattern[2])
if pattern[1] != None:
charFormat.setForeground(colorScheme[pattern[1]])
if len(pattern) >= 4:
charFormat.setFontItalic(pattern[3])
if len(pattern) >= 5:
charFormat.setFontUnderline(pattern[4])
for match in pattern[0].finditer(text):
self.setFormat(match.start(), match.end() - match.start(), charFormat)
for match in reSpacesOnEnd.finditer(text):
charFormat = QTextCharFormat()
charFormat.setBackground(colorScheme['whitespaceOnEnd'])
self.setFormat(match.start(), match.end() - match.start(), charFormat)
# Spell checker
if self.dictionary:
charFormat = QTextCharFormat()
charFormat.setUnderlineColor(Qt.red)
charFormat.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)
for match in reWords.finditer(text):
finalFormat = QTextCharFormat()
finalFormat.merge(charFormat)
finalFormat.merge(self.format(match.start()))
if not self.dictionary.check(match.group(0)):
self.setFormat(match.start(), match.end() - match.start(), finalFormat)
ReText-5.3.1/ReText/tab.py 0000644 0001750 0001750 00000022661 12701275717 016150 0 ustar dmitry dmitry 0000000 0000000 # This file is part of ReText
# Copyright: 2015 Dmitry Shachnev
#
# 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 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 .
from markups import get_markup_for_file_name
from markups.common import MODULE_HOME_PAGE
from ReText import app_version, enchant, enchant_available, globalSettings
from ReText.editor import ReTextEdit
from ReText.highlighter import ReTextHighlighter
try:
from ReText.fakevimeditor import ReTextFakeVimHandler
except ImportError:
ReTextFakeVimHandler = None
from PyQt5.QtCore import Qt, QDir, QFile, QFileInfo, QObject, QTextStream, QTimer, QUrl
from PyQt5.QtGui import QDesktopServices
from PyQt5.QtWidgets import QTextBrowser, QTextEdit, QSplitter
from PyQt5.QtWebKit import QWebSettings
from PyQt5.QtWebKitWidgets import QWebPage, QWebView
PreviewDisabled, PreviewLive, PreviewNormal = range(3)
class ReTextTab(QObject):
def __init__(self, parent, fileName, previewState=PreviewDisabled):
QObject.__init__(self, parent)
self.p = parent
self.fileName = fileName
self.editBox = ReTextEdit(self)
self.previewBox = self.createPreviewBox()
self.markup = self.getMarkup()
self.previewState = previewState
self.previewBlocked = False
textDocument = self.editBox.document()
self.highlighter = ReTextHighlighter(textDocument)
if enchant_available and parent.actionEnableSC.isChecked():
self.highlighter.dictionary = enchant.Dict(parent.sl or None)
self.highlighter.rehighlight()
self.highlighter.docType = self.markup.name
self.editBox.textChanged.connect(self.updateLivePreviewBox)
self.editBox.undoAvailable.connect(parent.actionUndo.setEnabled)
self.editBox.redoAvailable.connect(parent.actionRedo.setEnabled)
self.editBox.copyAvailable.connect(parent.actionCopy.setEnabled)
textDocument.modificationChanged.connect(parent.modificationChanged)
self.updateBoxesVisibility()
def createWebView(self):
webView = QWebView()
if not globalSettings.handleWebLinks:
webView.page().setLinkDelegationPolicy(QWebPage.DelegateExternalLinks)
webView.page().linkClicked.connect(QDesktopServices.openUrl)
settings = webView.settings()
settings.setAttribute(QWebSettings.LocalContentCanAccessFileUrls, False)
settings.setDefaultTextEncoding('utf-8')
return webView
def createPreviewBox(self):
if globalSettings.useWebKit:
return self.createWebView()
browser = ReTextPreview(self)
return browser
def getSplitter(self):
splitter = QSplitter(Qt.Horizontal)
# Give both boxes a minimum size so the minimumSizeHint will be
# ignored when splitter.setSizes is called below
for widget in self.editBox, self.previewBox:
widget.setMinimumWidth(125)
splitter.addWidget(widget)
splitter.setSizes((50, 50))
splitter.setChildrenCollapsible(False)
splitter.tab = self
return splitter
def getMarkupClass(self):
if self.fileName:
markupClass = get_markup_for_file_name(
self.fileName, return_class=True)
if markupClass:
return markupClass
return self.p.defaultMarkup
def getMarkup(self):
markupClass = self.getMarkupClass()
if markupClass and markupClass.available():
return markupClass(filename=self.fileName)
def getDocumentTitle(self, baseName=False):
if self.markup and not baseName:
text = self.editBox.toPlainText()
try:
return self.markup.get_document_title(text)
except Exception:
self.p.printError()
if self.fileName:
fileinfo = QFileInfo(self.fileName)
basename = fileinfo.completeBaseName()
return (basename if basename else fileinfo.fileName())
return self.tr("New document")
def getHtml(self, includeStyleSheet=True, includeTitle=True,
includeMeta=False, webenv=False):
if self.markup is None:
markupClass = self.getMarkupClass()
errMsg = self.tr('Could not parse file contents, check if '
'you have the necessary module '
'installed!')
try:
errMsg %= markupClass.attributes[MODULE_HOME_PAGE]
except (AttributeError, KeyError):
# Remove the link if markupClass doesn't have the needed attribute
errMsg = errMsg.replace('', '').replace('', '')
return '
%s
' % errMsg
text = self.editBox.toPlainText()
headers = ''
if includeStyleSheet:
headers += '\n'
cssFileName = self.getDocumentTitle(baseName=True) + '.css'
if QFile(cssFileName).exists():
headers += ('\n'
% cssFileName)
if includeMeta:
headers += ('\n'
% app_version)
fallbackTitle = self.getDocumentTitle() if includeTitle else ''
return self.markup.get_whole_html(text,
custom_headers=headers, include_stylesheet=includeStyleSheet,
fallback_title=fallbackTitle, webenv=webenv)
def updatePreviewBox(self):
self.previewBlocked = False
if isinstance(self.previewBox, QTextEdit):
scrollbar = self.previewBox.verticalScrollBar()
scrollbarValue = scrollbar.value()
distToBottom = scrollbar.maximum() - scrollbarValue
else:
frame = self.previewBox.page().mainFrame()
scrollpos = frame.scrollPosition()
try:
html = self.getHtml()
except Exception:
return self.p.printError()
if isinstance(self.previewBox, QTextEdit):
self.previewBox.setHtml(html)
self.previewBox.document().setDefaultFont(globalSettings.font)
# If scrollbar was at bottom (and that was not the same as top),
# set it to bottom again
if scrollbarValue:
newValue = scrollbar.maximum() - distToBottom
scrollbar.setValue(newValue)
else:
settings = self.previewBox.settings()
settings.setFontFamily(QWebSettings.StandardFont,
globalSettings.font.family())
settings.setFontSize(QWebSettings.DefaultFontSize,
globalSettings.font.pointSize())
self.previewBox.setHtml(html, QUrl.fromLocalFile(self.fileName))
frame.setScrollPosition(scrollpos)
def updateLivePreviewBox(self):
if self.previewState == PreviewLive and not self.previewBlocked:
self.previewBlocked = True
QTimer.singleShot(1000, self.updatePreviewBox)
def updateBoxesVisibility(self):
self.editBox.setVisible(self.previewState < PreviewNormal)
self.previewBox.setVisible(self.previewState > PreviewDisabled)
def setMarkupClass(self, markupClass):
self.markup = None
if markupClass and markupClass.available:
self.markup = markupClass(filename=self.fileName)
self.highlighter.docType = markupClass.name if markupClass else None
self.highlighter.rehighlight()
def readTextFromFile(self, encoding=None):
openfile = QFile(self.fileName)
openfile.open(QFile.ReadOnly)
stream = QTextStream(openfile)
encoding = encoding or globalSettings.defaultCodec
if encoding:
stream.setCodec(encoding)
text = stream.readAll()
openfile.close()
markupClass = get_markup_for_file_name(self.fileName, return_class=True)
self.setMarkupClass(markupClass)
modified = bool(encoding) and (self.editBox.toPlainText() != text)
self.editBox.setPlainText(text)
self.editBox.document().setModified(modified)
def saveTextToFile(self, fileName=None, addToWatcher=True):
if fileName is None:
fileName = self.fileName
self.p.fileSystemWatcher.removePath(fileName)
savefile = QFile(fileName)
result = savefile.open(QFile.WriteOnly)
if result:
savestream = QTextStream(savefile)
if globalSettings.defaultCodec:
savestream.setCodec(globalSettings.defaultCodec)
savestream << self.editBox.toPlainText()
savefile.close()
if result and addToWatcher:
self.p.fileSystemWatcher.addPath(fileName)
return result
def installFakeVimHandler(self):
if ReTextFakeVimHandler:
fakeVimEditor = ReTextFakeVimHandler(self.editBox, self)
fakeVimEditor.setSaveAction(self.actionSave)
fakeVimEditor.setQuitAction(self.actionQuit)
# TODO: action is bool, really call remove?
self.p.actionFakeVimMode.triggered.connect(fakeVimEditor.remove)
class ReTextPreview(QTextBrowser):
"""
When links like [test](test) are clicked, the file test.md is opened.
It has to be located next to the current opened file.
Relative pathes like [test](../test) or [test](folder/test) are also possible.
"""
def __init__(self, tab):
QTextBrowser.__init__(self)
self.tab = tab
# if set to True, links to other files will unsuccessfully be opened as anchors
self.setOpenLinks(False)
self.anchorClicked.connect(self.openInternal)
def openInternal(self, link):
url = link.url()
isLocalHtml = (link.scheme() in ('file', '') and url.endswith('.html'))
if url.startswith('#'):
self.scrollToAnchor(url[1:])
elif link.isRelative() and get_markup_for_file_name(url, return_class=True):
fileToOpen = QDir.current().filePath(url)
if not QFileInfo(fileToOpen).completeSuffix() and self.fileName:
fileToOpen += '.' + QFileInfo(self.tab.fileName).completeSuffix()
self.tab.p.openFileWrapper(fileToOpen)
elif globalSettings.handleWebLinks and isLocalHtml:
self.setSource(link)
else:
QDesktopServices.openUrl(link)
ReText-5.3.1/ReText/icontheme.py 0000644 0001750 0001750 00000003066 12701272775 017354 0 ustar dmitry dmitry 0000000 0000000 # This file is part of ReText
# Copyright: 2015 Dmitry Shachnev
#
# 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 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 .
def get_from_xsettings():
from ReText.xsettings import get_xsettings, XSettingsError
try:
xsettings = get_xsettings()
except XSettingsError:
return
if b'Net/IconThemeName' in xsettings:
return xsettings[b'Net/IconThemeName'].decode()
if b'Net/FallbackIconTheme' in xsettings:
return xsettings[b'Net/FallbackIconTheme'].decode()
def get_from_gsettings():
try:
from gi.repository import Gio
except ImportError:
return
schema = 'org.gnome.desktop.interface'
if schema in Gio.Settings.list_schemas():
settings = Gio.Settings.new(schema)
return settings.get_string('icon-theme')
def get_from_gtk():
try:
from gi.repository import Gtk
except ImportError:
return
settings = Gtk.Settings.get_default()
return settings.get_property('gtk-icon-theme-name')
def get_icon_theme():
return (get_from_xsettings()
or get_from_gsettings()
or get_from_gtk())
ReText-5.3.1/ReText/editor.py 0000644 0001750 0001750 00000024262 12701275717 016667 0 ustar dmitry dmitry 0000000 0000000 # This file is part of ReText
# Copyright: 2012-2015 Dmitry Shachnev
#
# 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 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 .
from markups import MarkdownMarkup
from ReText import globalSettings, tablemode, readFromSettings
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtGui import QColor, QKeyEvent, QPainter, QPalette, QTextCursor, QTextFormat
from PyQt5.QtWidgets import QLabel, QTextEdit, QWidget
colors = {
'marginLine': QColor(0xdc, 0xd2, 0xdc),
'currentLineHighlight': QColor(0xff, 0xff, 0xc8),
'infoArea': QColor(0xaa, 0xff, 0x55, 0xaa),
'lineNumberArea': Qt.cyan,
'lineNumberAreaText': Qt.darkCyan
}
colorValues = {
colorName: readFromSettings(
'ColorScheme/' + colorName, QColor, default=colors[colorName])
for colorName in colors
}
def documentIndentMore(document, cursor, globalSettings=globalSettings):
if cursor.hasSelection():
block = document.findBlock(cursor.selectionStart())
end = document.findBlock(cursor.selectionEnd()).next()
cursor.beginEditBlock()
while block != end:
cursor.setPosition(block.position())
if globalSettings.tabInsertsSpaces:
cursor.insertText(' ' * globalSettings.tabWidth)
else:
cursor.insertText('\t')
block = block.next()
cursor.endEditBlock()
else:
indent = globalSettings.tabWidth - (cursor.positionInBlock()
% globalSettings.tabWidth)
if globalSettings.tabInsertsSpaces:
cursor.insertText(' ' * indent)
else:
cursor.insertText('\t')
def documentIndentLess(document, cursor, globalSettings=globalSettings):
if cursor.hasSelection():
block = document.findBlock(cursor.selectionStart())
end = document.findBlock(cursor.selectionEnd()).next()
else:
block = document.findBlock(cursor.position())
end = block.next()
cursor.beginEditBlock()
while block != end:
cursor.setPosition(block.position())
if document.characterAt(cursor.position()) == '\t':
cursor.deleteChar()
else:
pos = 0
while document.characterAt(cursor.position()) == ' ' \
and pos < globalSettings.tabWidth:
pos += 1
cursor.deleteChar()
block = block.next()
cursor.endEditBlock()
class ReTextEdit(QTextEdit):
def __init__(self, parent):
QTextEdit.__init__(self)
self.tab = parent
self.parent = parent.p
self.undoRedoActive = False
self.tableModeEnabled = False
self.setAcceptRichText(False)
self.lineNumberArea = LineNumberArea(self)
self.infoArea = InfoArea(self)
self.updateFont()
self.document().blockCountChanged.connect(self.updateLineNumberAreaWidth)
self.cursorPositionChanged.connect(self.highlightCurrentLine)
self.document().contentsChange.connect(self.contentsChange)
def updateFont(self):
self.setFont(globalSettings.editorFont)
metrics = self.fontMetrics()
self.marginx = (self.document().documentMargin()
+ metrics.width(' ' * globalSettings.rightMargin))
self.setTabStopWidth(globalSettings.tabWidth * self.fontMetrics().width(' '))
self.updateLineNumberAreaWidth()
self.infoArea.updateTextAndGeometry()
def paintEvent(self, event):
if not globalSettings.rightMargin:
return QTextEdit.paintEvent(self, event)
painter = QPainter(self.viewport())
painter.setPen(colorValues['marginLine'])
y1 = self.rect().topLeft().y()
y2 = self.rect().bottomLeft().y()
painter.drawLine(self.marginx, y1, self.marginx, y2)
QTextEdit.paintEvent(self, event)
def scrollContentsBy(self, dx, dy):
QTextEdit.scrollContentsBy(self, dx, dy)
self.lineNumberArea.update()
def lineNumberAreaPaintEvent(self, event):
painter = QPainter(self.lineNumberArea)
painter.fillRect(event.rect(), colorValues['lineNumberArea'])
cursor = QTextCursor(self.document())
cursor.movePosition(QTextCursor.Start)
atEnd = False
while not atEnd:
rect = self.cursorRect(cursor)
block = cursor.block()
if block.isVisible():
number = str(cursor.blockNumber() + 1)
painter.setPen(colorValues['lineNumberAreaText'])
painter.drawText(0, rect.top(), self.lineNumberArea.width()-2,
self.fontMetrics().height(), Qt.AlignRight, number)
cursor.movePosition(QTextCursor.EndOfBlock)
atEnd = cursor.atEnd()
if not atEnd:
cursor.movePosition(QTextCursor.NextBlock)
def contextMenuEvent(self, event):
text = self.toPlainText()
dictionary = self.tab.highlighter.dictionary
if (dictionary is None) or not text:
return QTextEdit.contextMenuEvent(self, event)
oldcursor = self.textCursor()
cursor = self.cursorForPosition(event.pos())
pos = cursor.positionInBlock()
if pos == len(text): pos -= 1
curchar = text[pos]
isalpha = curchar.isalpha()
cursor.select(QTextCursor.WordUnderCursor)
if not isalpha or (oldcursor.hasSelection() and
oldcursor.selectedText() != cursor.selectedText()):
return QTextEdit.contextMenuEvent(self, event)
self.setTextCursor(cursor)
word = cursor.selectedText()
if not word or dictionary.check(word):
self.setTextCursor(oldcursor)
return QTextEdit.contextMenuEvent(self, event)
suggestions = dictionary.suggest(word)
actions = [self.parent.act(sug, trig=self.fixWord(sug)) for sug in suggestions]
menu = self.createStandardContextMenu()
menu.insertSeparator(menu.actions()[0])
for action in actions[::-1]:
menu.insertAction(menu.actions()[0], action)
menu.exec(event.globalPos())
def fixWord(self, correctword):
return lambda: self.insertPlainText(correctword)
def keyPressEvent(self, event):
key = event.key()
cursor = self.textCursor()
if event.text() and self.tableModeEnabled:
cursor.beginEditBlock()
if key == Qt.Key_Backspace and event.modifiers() & Qt.GroupSwitchModifier:
# Workaround for https://bugreports.qt.io/browse/QTBUG-49771
event = QKeyEvent(event.type(), event.key(),
event.modifiers() ^ Qt.GroupSwitchModifier)
if key == Qt.Key_Tab:
documentIndentMore(self.document(), cursor)
elif key == Qt.Key_Backtab:
documentIndentLess(self.document(), cursor)
elif key == Qt.Key_Return and not cursor.hasSelection():
if event.modifiers() & Qt.ShiftModifier:
# Insert Markdown-style line break
markupClass = self.tab.getMarkupClass()
if markupClass and markupClass == MarkdownMarkup:
cursor.insertText(' ')
if event.modifiers() & Qt.ControlModifier:
cursor.insertText('\n')
self.ensureCursorVisible()
else:
self.handleReturn(cursor)
else:
QTextEdit.keyPressEvent(self, event)
if event.text() and self.tableModeEnabled:
cursor.endEditBlock()
def handleReturn(self, cursor):
# Select text between the cursor and the line start
cursor.movePosition(QTextCursor.StartOfBlock, QTextCursor.KeepAnchor)
text = cursor.selectedText()
length = len(text)
pos = 0
while pos < length and (text[pos] in (' ', '\t')
or text[pos:pos+2] in ('* ', '- ')):
pos += 1
# Reset the cursor
cursor = self.textCursor()
cursor.insertText('\n'+text[:pos])
self.ensureCursorVisible()
def lineNumberAreaWidth(self):
if not globalSettings.lineNumbersEnabled:
return 0
cursor = QTextCursor(self.document())
cursor.movePosition(QTextCursor.End)
digits = len(str(cursor.blockNumber() + 1))
return 5 + self.fontMetrics().width('9') * digits
def updateLineNumberAreaWidth(self, blockcount=0):
self.lineNumberArea.update()
self.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0)
def resizeEvent(self, event):
QTextEdit.resizeEvent(self, event)
rect = self.contentsRect()
self.lineNumberArea.setGeometry(rect.left(), rect.top(),
self.lineNumberAreaWidth(), rect.height())
self.infoArea.updateTextAndGeometry()
def highlightCurrentLine(self):
if not globalSettings.highlightCurrentLine:
return self.setExtraSelections([])
selection = QTextEdit.ExtraSelection();
selection.format.setBackground(colorValues['currentLineHighlight'])
selection.format.setProperty(QTextFormat.FullWidthSelection, True)
selection.cursor = self.textCursor()
selection.cursor.clearSelection()
self.setExtraSelections([selection])
def enableTableMode(self, enable):
self.tableModeEnabled = enable
def backupCursorPositionOnLine(self):
return self.textCursor().positionInBlock()
def restoreCursorPositionOnLine(self, positionOnLine):
cursor = self.textCursor()
cursor.setPosition(cursor.block().position() + positionOnLine)
self.setTextCursor(cursor)
def contentsChange(self, pos, removed, added):
if self.tableModeEnabled:
markupClass = self.tab.getMarkupClass()
cursorPosition = self.backupCursorPositionOnLine()
tablemode.adjustTableToChanges(self.document(), pos, added - removed, markupClass)
self.restoreCursorPositionOnLine(cursorPosition)
class LineNumberArea(QWidget):
def __init__(self, editor):
QWidget.__init__(self, editor)
self.editor = editor
def sizeHint(self):
return QSize(self.editor.lineNumberAreaWidth(), 0)
def paintEvent(self, event):
if globalSettings.lineNumbersEnabled:
return self.editor.lineNumberAreaPaintEvent(event)
class InfoArea(QLabel):
def __init__(self, editor):
QWidget.__init__(self, editor)
self.editor = editor
self.editor.cursorPositionChanged.connect(self.updateTextAndGeometry)
self.updateTextAndGeometry()
self.setAutoFillBackground(True)
palette = self.palette()
palette.setColor(QPalette.Window, colorValues['infoArea'])
self.setPalette(palette)
def updateTextAndGeometry(self):
text = self.getText()
self.setText(text)
viewport = self.editor.viewport()
metrics = self.fontMetrics()
width = metrics.width(text)
height = metrics.height()
self.resize(width, height)
rightSide = viewport.width() + self.editor.lineNumberAreaWidth()
self.move(rightSide - width, viewport.height() - height)
self.setVisible(not globalSettings.useFakeVim)
def getText(self):
template = '%d : %d'
cursor = self.editor.textCursor()
block = cursor.blockNumber() + 1
position = cursor.positionInBlock()
return template % (block, position)
ReText-5.3.1/data/ 0000755 0001750 0001750 00000000000 12701277415 014514 5 ustar dmitry dmitry 0000000 0000000 ReText-5.3.1/data/me.mitya57.ReText.desktop 0000644 0001750 0001750 00000003375 12700242644 021223 0 ustar dmitry dmitry 0000000 0000000 [Desktop Entry]
Version=1.0
Name=ReText
Comment=Simple text editor for Markdown and reStructuredText
Comment[ca]=Editor de Markdown i reStructuredText senzill alhora que potent
Comment[cs]=Jednoduchý editor pro Markdown a reStructuredText
Comment[cy]=Golygydd testun syml ar gyfer Markdown a reStructuredText
Comment[da]=Enkel editor til Markdown og reStructuredText
Comment[de]=Einfacher Texteditor für Markdown und reStructuredText
Comment[es]=Editor básico de texto para Markdown y reStructuredText
Comment[et]=Lihtne tekstiredaktor Markdown ning reStructuredText süntaksitele
Comment[eu]=Markdown et reStructuredText-erako editore sinple
Comment[fr]=Éditeur de texte simple pour Markdown et reStructuredText
Comment[hu]=Egyszerű Markdown és reStructuredText szövegszerkesztő
Comment[it]=Semplice editor di testo per Markdown e reStructuredText
Comment[ja]=MarkdownとreStructuredTextのためのシンプルで強力なエディタ
Comment[pl]=Prosty edytor Markdown i reStructuredText
Comment[pt_BR]=Editor simples para Markdown e reStructuredText
Comment[ru]=Простой редактор для Markdown и reStructuredText
Comment[sr]=Једноставан уређивач за Markdown и reStructuredText
Comment[sr@latin]=Jednostavan uređivač za Markdown i reStructuredText
Comment[uk]=Простий текстовий редактор для Markdown та reStructuredText
Comment[sk]=Jednoduchý textový editor pre Markdown a reStructuredText
Comment[zh_CN]=支持 Markdown 和 reStructuredText 语法的简易文本编辑器
Comment[zh_TW]=簡單高效的 Markdown 與 reStructuredText 編輯器
Categories=Office;WordProcessor;
Exec=retext %F
Type=Application
Icon=retext
MimeType=text/x-markdown;text/x-rst;
Keywords=Text;Editor;Markdown;reStructuredText;
ReText-5.3.1/data/me.mitya57.ReText.appdata.xml 0000644 0001750 0001750 00000005261 12700242644 021757 0 ustar dmitry dmitry 0000000 0000000
me.mitya57.ReText.desktopReTextSimple text editor for Markdown and reStructuredTextEditor de Markdown i reStructuredText senzill alhora que potentJednoduchý editor pro Markdown a reStructuredTextGolygydd testun syml ar gyfer Markdown a reStructuredTextEnkel editor til Markdown og reStructuredTextEinfacher Texteditor für Markdown und reStructuredTextEditor básico de texto para Markdown y reStructuredTextLihtne tekstiredaktor Markdown ning reStructuredText süntaksiteleMarkdown et reStructuredText-erako editore sinpleÉditeur de texte simple pour Markdown et reStructuredTextEgyszerű Markdown és reStructuredText szövegszerkesztőSemplice editor di testo per Markdown e reStructuredTextMarkdownとreStructuredTextのためのシンプルで強力なエディタProsty edytor Markdown i reStructuredTextEditor simples para Markdown e reStructuredTextПростой редактор для Markdown и reStructuredTextЈедноставан уређивач за Markdown и reStructuredTextJednostavan uređivač za Markdown i reStructuredTextПростий текстовий редактор для Markdown та reStructuredTextJednoduchý textový editor pre Markdown a reStructuredText支持 Markdown 和 reStructuredText 语法的简易文本编辑器簡單高效的 Markdown 與 reStructuredText 編輯器https://github.com/retext-project/retextCC0GPL-2.0+retexthttps://a.fsdn.com/con/app/proj/retext/screenshots/retext-kde5.pngDmitry Shachnevmitya57_AT_gmail.com
ReText-5.3.1/LICENSE_GPL 0000644 0001750 0001750 00000105755 12556404212 015322 0 ustar dmitry dmitry 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
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 .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
ReText-5.3.1/configuration.md 0000644 0001750 0001750 00000012351 12701276155 016776 0 ustar dmitry dmitry 0000000 0000000 ReText stores all of its configuration in a text file. A path to that
file is printed to stdout during ReText startup.
Possible configuration options
==============================
Configuration options that you can set to improve your experience:
option name | type | description
----------- | ---- | -----------
`appStyleSheet` | file path | file containing a Qt stylesheet file
`autoSave` | boolean | whether to automatically save documents (default: false)
`defaultCodec` | string | name of encoding to use by default (default: use system encoding)
`defaultMarkup` | string | name of markup to use for unknown files
`editorFont` | string | font to use for editor: name (default: `monospace`)
`editorFontSize` | integer | font to use for editor: font size
`font` | string | font to use for previews: name
`fontSize` | integer | font to use for previews: font size
`handleWebLinks` | boolean | whether to use ReText preview area to open external links (default: false)
`hideToolBar` | boolean | whether to hide the toolbars from the UI (default: false)
`highlightCurrentLine` | boolean | whether to highlight current line in editor (default: false)
`iconTheme` | string | name of the system icon theme to use (see below)
`lineNumbersEnabled` | boolean | whether to show column with line numbers in editor (default: false)
`livePreviewByDefault` | boolean | whether new tabs and windows should open in live preview mode (default: false)
`markdownDefaultFileExtension` | string | default file extension for Markdown files (default: `.mkd`)
`pygmentsStyle` | string | name of Pygments syntax highlighting style to use (default: `default`)
`restDefaultFileExtension` | string | default file extension for reStructuredText files (default: `.rst`)
`rightMargin` | integer | enable drawing of vertical line on defined position (or 0 to disable)
`saveWindowGeometry` | boolean | whether to restore window geometry from previous session (default: false)
`spellCheck` | boolean | whether to enable spell checking
`spellCheckLocale` | string | short name of spell check locale to use (examples: `en_US`, `ru`, `pt_BR`)
`styleSheet` | file path | CSS file to use in preview area
`tabInsertsSpaces` | boolean | whether Tab key should insert spaces instead of tabs (default: true)
`tabWidth` | integer | the width of tab character (default: 4)
`uiLanguage` | string | short name of locale to use for interface (examples: `en_US, `ru, `pt_BR`)
`useFakeVim` | boolean | whether to use the FakeVim editor, if available (default: false)
`useWebKit` | boolean | whether to use the WebKit instead of QTextEdit as HTML previewer (default: false)
If the type is 'file path', then the value should be an absolute path
to a file.
These options can be set internally by ReText and should never be set
manually: `recentFileList` and `windowGeometry`.
Icon themes
===========
If ReText starts and does not show icons, go to Preferences dialog
and fill the "icon theme" field with the icon theme being used.
By default Qt (the toolkit used by ReText) can correctly detect icon
theme only on KDE and on a fixed list of Gtk+-based environments (when
the gtk platformtheme is used).
If you don't know name of your icon theme, look at the names of
subdirectories in `/usr/share/icons/` directory.
Color scheme setting
====================
It is possible to configure ReText highlighter to use custom colors set,
by providing these colors in a separate section in the configuration file.
The example of such section is:
[ColorScheme]
htmlTags=green
htmlSymbols=#ff8800
htmlComments=#abc
Color names for the text editor:
color name | main setting | description
---------- | ------------ | -----------
`marginLine` | `rightMargin` | the vertical right margin line
`currentLineHighlight` | `highlightCurrentLine` | highlighting of the text line being edited
`infoArea` | | the info box in the bottom-right corner
`lineNumberArea` | `lineNumbersEnabled` | the line numbers area background
`lineNumberAreaText` | `lineNumbersEnabled` | the line numbers area foreground
Color names for the highlighter:
color name | description
---------- | -----------
`htmlTags` | HTML tags, i.e. ``
`htmlStrings` | string properties inside HTML tags, i.e. `"baz"` inside ``
`htmlSymbols` | HTML symbols, i.e. `&bar;`
`htmlComments` | HTML comments, i.e. ``
`markdownLinks` | Markdown links and images text, i.e. `foo` inside `[foo](http://example.com)`
`blockquotes` | blockquotes, i.e. `> quote` in Markdown
`restDirectives` | reStructuredText directives, i.e. `.. math::`
`restRoles` | reStructuredText roles, i.e. `:math:`
`whitespaceOnEnd` | whitespace at line endings
ReText-5.3.1/PKG-INFO 0000644 0001750 0001750 00000002233 12701277415 014700 0 ustar dmitry dmitry 0000000 0000000 Metadata-Version: 1.1
Name: ReText
Version: 5.3.1
Summary: Simple editor for Markdown and reStructuredText
Home-page: https://github.com/retext-project/retext
Author: Dmitry Shachnev
Author-email: mitya57@gmail.com
License: GPL 2+
Description: ReText is simple text editor that supports Markdown and reStructuredText
markup languages. It is written in Python using PyQt libraries.
It supports live preview, tabs, math formulas, export to various formats
including PDF and HTML.
For more details, please go to the `home page`_ or to the `wiki`_.
.. _`home page`: https://github.com/retext-project/retext
.. _`wiki`: https://github.com/retext-project/retext/wiki
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: X11 Applications :: Qt
Classifier: License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Text Editors
Classifier: Topic :: Text Processing :: Markup
Requires: docutils
Requires: Markdown
Requires: Markups
Requires: pyenchant
Requires: Pygments
ReText-5.3.1/locale/ 0000755 0001750 0001750 00000000000 12701277415 015042 5 ustar dmitry dmitry 0000000 0000000 ReText-5.3.1/locale/retext_ca.qm 0000644 0001750 0001750 00000014521 12701277414 017361 0 ustar dmitry dmitry 0000000 0000000