ReText-7.0.1/ 0000755 0001750 0001750 00000000000 13123552576 013605 5 ustar dmitry dmitry 0000000 0000000 ReText-7.0.1/ReText/ 0000755 0001750 0001750 00000000000 13123552576 015020 5 ustar dmitry dmitry 0000000 0000000 ReText-7.0.1/ReText/__init__.py 0000644 0001750 0001750 00000011645 13123552555 017135 0 ustar dmitry dmitry 0000000 0000000 # vim: ts=8:sts=8:sw=8:noexpandtab
# This file is part of ReText
# Copyright: 2012-2017 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
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 = "7.0.1"
settings = QSettings('ReText project', 'ReText')
if not str(settings.fileName()).endswith('.conf'):
# We are on Windows probably
settings = QSettings(QSettings.IniFormat, QSettings.UserScope,
'ReText project', 'ReText')
datadirs = []
def initializeDataDirs():
assert not datadirs
if '__file__' in locals():
datadirs.append(dirname(dirname(__file__)))
dataLocations = QStandardPaths.standardLocations(QStandardPaths.GenericDataLocation)
datadirs.extend(join(d, 'retext') for d in dataLocations)
if sys.platform == "win32":
# Windows compatibility: Add "PythonXXX\share\" path
datadirs.append(join(dirname(sys.executable), 'share', 'retext'))
# For virtualenvs
datadirs.append(join(dirname(dirname(sys.executable)), 'share', 'retext'))
_iconPath = None
def getBundledIcon(iconName):
global _iconPath
if _iconPath is None:
for dir in ['icons'] + datadirs:
_iconPath = join(dir, 'icons')
if exists(_iconPath):
break
return join(_iconPath, iconName + '.png')
configOptions = {
'appStyleSheet': '',
'autoSave': False,
'defaultCodec': '',
'defaultMarkup': markups.MarkdownMarkup.name,
'detectEncoding': True,
'editorFont': QFont(),
'font': QFont(),
'handleWebLinks': False,
'hideToolBar': False,
'highlightCurrentLine': False,
'iconTheme': '',
'lastTabIndex': 0,
'lineNumbersEnabled': False,
'livePreviewByDefault': False,
'markdownDefaultFileExtension': '.mkd',
'openLastFilesOnStartup': False,
'pygmentsStyle': 'default',
'restDefaultFileExtension': '.rst',
'rightMargin': 0,
'saveWindowGeometry': False,
'spellCheck': False,
'spellCheckLocale': '',
'styleSheet': '',
'syncScroll': True,
'tabBarAutoHide': False,
'tabInsertsSpaces': True,
'tabWidth': 4,
'uiLanguage': QLocale.system().name(),
'useFakeVim': False,
'useWebEngine': 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)
def chooseMonospaceFont():
font = QFont('monospace')
font.setStyleHint(QFont.TypeWriter)
return font
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])
def __getattribute__(self, option):
value = object.__getattribute__(self, option)
# Choose a font just-in-time, because when the settings are
# loaded it is too early to work on Windows
if option == 'editorFont' and not value.family():
value = chooseMonospaceFont()
return value
globalSettings = ReTextSettings()
markups.common.PYGMENTS_STYLE = globalSettings.pygmentsStyle
ReText-7.0.1/ReText/fakevimeditor.py 0000644 0001750 0001750 00000021206 13075110262 020210 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.__handler.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-7.0.1/ReText/config.py 0000644 0001750 0001750 00000015032 13123552555 016635 0 ustar dmitry dmitry 0000000 0000000 # This file is part of ReText
# Copyright: 2013-2017 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, getBundledIcon
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('Automatically open last documents on startup'), 'openLastFilesOnStartup'),
(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('Enable synchronized scrolling for Markdown'), 'syncScroll'),
# (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('Draw vertical line 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(getBundledIcon('document-new')):
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()
tab.editBox.viewport().update()
self.parent.updateStyleSheet()
ReText-7.0.1/ReText/tablemode.py 0000644 0001750 0001750 00000015226 13047642057 017333 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 is 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)
def handleReturn(cursor, markupClass, newRow):
if markupClass not in (MarkdownMarkup, ReStructuredTextMarkup):
return False
positionInBlock = cursor.positionInBlock()
cursor.select(QTextCursor.BlockUnderCursor)
oldLine = cursor.selectedText().lstrip('\u2029')
if not ('| ' in oldLine or ' |' in oldLine):
cursor.setPosition(cursor.block().position() + positionInBlock)
return False
indent = 0
while oldLine[indent] in ' \t':
indent += 1
indentChars, oldLine = oldLine[:indent], oldLine[indent:]
newLine = ''.join('|' if c in '+|' else ' ' for c in oldLine).rstrip()
cursor.movePosition(QTextCursor.EndOfBlock)
if newRow and markupClass == MarkdownMarkup:
sepLine = ''.join(c if c in ' |' else '-' for c in oldLine)
cursor.insertText('\n' + indentChars + sepLine)
elif newRow:
sepLine = ''.join('+' if c in '+|' else '-' for c in oldLine)
cursor.insertText('\n' + indentChars + sepLine)
cursor.insertText('\n' + indentChars + newLine)
positionInBlock = min(positionInBlock, len(indentChars + newLine))
cursor.setPosition(cursor.block().position() + positionInBlock)
return True
ReText-7.0.1/ReText/preview.py 0000644 0001750 0001750 00000005603 13047642057 017056 0 ustar dmitry dmitry 0000000 0000000 # vim: ts=8:sts=8:sw=8:noexpandtab
#
# This file is part of ReText
# Copyright: 2017 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 PyQt5.QtCore import QDir
from PyQt5.QtGui import QDesktopServices
from PyQt5.QtWidgets import QTextBrowser
from ReText import globalSettings
class ReTextPreview(QTextBrowser):
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 disconnectExternalSignals(self):
pass
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():
fileToOpen = QDir.current().filePath(url)
if self.tab.openSourceFile(fileToOpen):
return
if globalSettings.handleWebLinks and isLocalHtml:
self.setSource(link)
else:
QDesktopServices.openUrl(link)
class ReTextWebPreview:
"""This is a common class shared between WebKit and WebEngine
based previews."""
def __init__(self, editBox):
self.editBox = editBox
self.settings().setDefaultTextEncoding('utf-8')
# Events relevant to sync scrolling
self.editBox.cursorPositionChanged.connect(self._handleCursorPositionChanged)
self.editBox.verticalScrollBar().valueChanged.connect(self.syncscroll.handleEditorScrolled)
self.editBox.resized.connect(self._handleEditorResized)
# Scroll the preview when the mouse wheel is used to scroll
# beyond the beginning/end of the editor
self.editBox.scrollLimitReached.connect(self._handleWheelEvent)
def disconnectExternalSignals(self):
self.editBox.cursorPositionChanged.disconnect(self._handleCursorPositionChanged)
self.editBox.verticalScrollBar().valueChanged.disconnect(self.syncscroll.handleEditorScrolled)
self.editBox.resized.disconnect(self._handleEditorResized)
self.editBox.scrollLimitReached.disconnect(self._handleWheelEvent)
def _handleCursorPositionChanged(self):
editorCursorPosition = self.editBox.verticalScrollBar().value() + \
self.editBox.cursorRect().top()
self.syncscroll.handleCursorPositionChanged(editorCursorPosition)
def _handleEditorResized(self, rect):
self.syncscroll.handleEditorResized(rect.height())
ReText-7.0.1/ReText/syncscroll.py 0000644 0001750 0001750 00000015023 13047642057 017565 0 ustar dmitry dmitry 0000000 0000000 # This file is part of ReText
# Copyright: 2016 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 .
from PyQt5.QtCore import QPoint
class SyncScroll:
def __init__(self, previewFrame,
editorPositionToSourceLineFunc,
sourceLineToEditorPositionFunc):
self.posmap = {}
self.frame = previewFrame
self.editorPositionToSourceLine = editorPositionToSourceLineFunc
self.sourceLineToEditorPosition = sourceLineToEditorPositionFunc
self.previewPositionBeforeLoad = QPoint()
self.contentIsLoading = False
self.editorViewportHeight = 0
self.editorViewportOffset = 0
self.editorCursorPosition = 0
self.frame.contentsSizeChanged.connect(self._handlePreviewResized)
self.frame.loadStarted.connect(self._handleLoadStarted)
self.frame.loadFinished.connect(self._handleLoadFinished)
def isActive(self):
return bool(self.posmap)
def handleEditorResized(self, editorViewportHeight):
self.editorViewportHeight = editorViewportHeight
self._updatePreviewScrollPosition()
def handleEditorScrolled(self, editorViewportOffset):
self.editorViewportOffset = editorViewportOffset
return self._updatePreviewScrollPosition()
def handleCursorPositionChanged(self, editorCursorPosition):
self.editorCursorPosition = editorCursorPosition
return self._updatePreviewScrollPosition()
def _handleLoadStarted(self):
# Store the current scroll position so it can be restored when the new
# content is presented
self.previewPositionBeforeLoad = self.frame.scrollPosition()
self.contentIsLoading = True
def _handleLoadFinished(self):
self.frame.setScrollPosition(self.previewPositionBeforeLoad)
self.contentIsLoading = False
self._recalculatePositionMap()
def _handlePreviewResized(self):
self._recalculatePositionMap()
self._updatePreviewScrollPosition()
def _linearScale(self, fromValue, fromMin, fromMax, toMin, toMax):
fromRange = fromMax - fromMin
toRange = toMax - toMin
toValue = toMin
if fromRange:
toValue += ((fromValue - fromMin) * toRange) / float(fromRange)
return toValue
def _updatePreviewScrollPosition(self):
if not self.posmap:
# Loading new content resets the scroll position to the top. If we
# don't have a posmap to calculate the new best position, then
# restore the position stored at the beginning of the load.
if self.contentIsLoading:
self.frame.setScrollPosition(self.previewPositionBeforeLoad)
return
textedit_pixel_to_scroll_to = self.editorCursorPosition
if textedit_pixel_to_scroll_to < self.editorViewportOffset:
textedit_pixel_to_scroll_to = self.editorViewportOffset
last_viewport_pixel = self.editorViewportOffset + self.editorViewportHeight
if textedit_pixel_to_scroll_to > last_viewport_pixel:
textedit_pixel_to_scroll_to = last_viewport_pixel
line_to_scroll_to = self.editorPositionToSourceLine(textedit_pixel_to_scroll_to)
# Do a binary search through the posmap to find the nearest line above
# and below the line to scroll to for which the rendered position is
# known.
posmap_lines = [0] + sorted(self.posmap.keys())
min_index = 0
max_index = len(posmap_lines) - 1
while max_index - min_index > 1:
current_index = int((min_index + max_index) / 2)
if posmap_lines[current_index] > line_to_scroll_to:
max_index = current_index
else:
min_index = current_index
# number of nearest line above and below for which we have a position
min_line = posmap_lines[min_index]
max_line = posmap_lines[max_index]
min_textedit_pos = self.sourceLineToEditorPosition(min_line)
max_textedit_pos = self.sourceLineToEditorPosition(max_line)
# rendered pixel position of nearest line above and below
min_preview_pos = self.posmap[min_line]
max_preview_pos = self.posmap[max_line]
# calculate rendered pixel position of line corresponding to cursor
# (0 == top of document)
preview_pixel_to_scroll_to = self._linearScale(textedit_pixel_to_scroll_to,
min_textedit_pos, max_textedit_pos,
min_preview_pos, max_preview_pos)
distance_to_top_of_viewport = textedit_pixel_to_scroll_to - self.editorViewportOffset
preview_scroll_offset = preview_pixel_to_scroll_to - distance_to_top_of_viewport
pos = self.frame.scrollPosition()
pos.setY(preview_scroll_offset)
self.frame.setScrollPosition(pos)
def _setPositionMap(self, posmap):
self.posmap = posmap
if posmap:
self.posmap[0] = 0
def _recalculatePositionMap(self):
if hasattr(self.frame, 'getPositionMap'):
# For WebEngine the update has to be asynchronous
self.frame.getPositionMap(self._setPositionMap)
return
# Create a list of input line positions mapped to vertical pixel positions in the preview
self.posmap = {}
elements = self.frame.findAllElements('[data-posmap]')
if elements:
# If there are posmap attributes, then build a posmap
# dictionary from them that will be used whenever the
# cursor is moved.
for el in elements:
value = el.attribute('data-posmap', 'invalid')
bottom = el.geometry().bottom()
# Ignore data-posmap entries that do not have integer values
try:
self.posmap[int(value)] = bottom
except ValueError:
pass
self.posmap[0] = 0
ReText-7.0.1/ReText/window.py 0000644 0001750 0001750 00000127307 13123552555 016710 0 ustar dmitry dmitry 0000000 0000000 # vim: ts=8:sts=8:sw=8:noexpandtab
#
# This file is part of ReText
# Copyright: 2012-2017 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
import warnings
from ReText import (getBundledIcon, app_version, globalSettings,
readListFromSettings, writeListToSettings, datadirs)
from ReText.tab import (ReTextTab, ReTextWebKitPreview, ReTextWebEnginePreview,
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
try:
import enchant
except ImportError:
enchant = None
from PyQt5.QtCore import QDir, QFile, QFileInfo, QFileSystemWatcher, \
QIODevice, QLocale, QTextCodec, QTextStream, QTimer, QUrl, Qt
from PyQt5.QtGui import QColor, QDesktopServices, QIcon, \
QKeySequence, QPalette, QTextDocument, QTextDocumentWriter
from PyQt5.QtWidgets import QAction, QActionGroup, QApplication, QCheckBox, \
QComboBox, QDesktopWidget, QDialog, QFileDialog, QFontDialog, QInputDialog, \
QLineEdit, QMainWindow, QMenu, 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 sys.platform.startswith('darwin'):
# https://github.com/retext-project/retext/issues/198
searchPaths = QIcon.themeSearchPaths()
searchPaths.append('/opt/local/share/icons')
searchPaths.append('/usr/local/share/icons')
QIcon.setThemeSearchPaths(searchPaths)
if globalSettings.iconTheme:
QIcon.setThemeName(globalSettings.iconTheme)
if QIcon.themeName() in ('hicolor', ''):
if not QFile.exists(getBundledIcon('document-new')):
QIcon.setThemeName(get_icon_theme())
if QFile.exists(getBundledIcon('retext')):
self.setWindowIcon(QIcon(getBundledIcon('retext')))
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(getBundledIcon('document-preview')))
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 editing 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 is not None:
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)
if ReTextWebKitPreview is None:
globalSettings.useWebKit = False
self.actionWebKit.setEnabled(False)
self.actionWebKit.setChecked(globalSettings.useWebKit)
self.actionWebEngine = self.act(self.tr('Use WebEngine (Chromium) renderer'),
trigbool=self.enableWebEngine)
if ReTextWebEnginePreview is None:
globalSettings.useWebEngine = False
self.actionWebEngine.setChecked(globalSettings.useWebEngine)
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.actionReplace = self.act(self.tr('Replace'), 'edit-find-replace',
lambda: self.find(replace=True))
self.actionReplaceAll = self.act(self.tr('Replace all'), trig=self.replaceAll)
menuReplace = QMenu()
menuReplace.addAction(self.actionReplaceAll)
self.actionReplace.setMenu(menuReplace)
self.actionCloseSearch = self.act(self.tr('Close'), 'window-close',
lambda: self.searchBar.setVisible(False))
self.actionCloseSearch.setPriority(QAction.LowPriority)
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!')
if len(availableMarkups) > 1:
self.chooseGroup = QActionGroup(self)
markupActions = []
for markup in availableMarkups:
markupAction = self.act(markup.name, trigbool=self.markupFunction(markup))
if markup.name == globalSettings.defaultMarkup:
markupAction.setChecked(True)
self.chooseGroup.addAction(markupAction)
markupActions.append(markupAction)
self.actionBold = self.act(self.tr('Bold'), shct=QKeySequence.Bold,
trig=lambda: self.insertFormatting('bold'))
self.actionItalic = self.act(self.tr('Italic'), shct=QKeySequence.Italic,
trig=lambda: self.insertFormatting('italic'))
self.actionUnderline = self.act(self.tr('Underline'), shct=QKeySequence.Underline,
trig=lambda: self.insertFormatting('underline'))
self.usefulTags = ('header', 'italic', 'bold', 'underline', 'numbering',
'bullets', 'image', 'link', 'inline code', 'code block', 'blockquote')
self.usefulChars = ('deg', 'divide', 'dollar', 'hellip', 'laquo', 'larr',
'lsquo', 'mdash', 'middot', 'minus', 'nbsp', 'ndash', 'raquo',
'rarr', 'rsquo', 'times')
self.formattingBox = QComboBox(self.editBar)
self.formattingBox.addItem(self.tr('Formatting'))
self.formattingBox.addItems(self.usefulTags)
self.formattingBox.activated[str].connect(self.insertFormatting)
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 = self.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.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 is not None:
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)
if ReTextWebKitPreview is not None or ReTextWebEnginePreview is None:
menuEdit.addAction(self.actionWebKit)
else:
menuEdit.addAction(self.actionWebEngine)
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)
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.formattingBox)
self.editBar.addWidget(self.symbolBox)
self.searchEdit = QLineEdit(self.searchBar)
self.searchEdit.setPlaceholderText(self.tr('Search'))
self.searchEdit.returnPressed.connect(self.find)
self.replaceEdit = QLineEdit(self.searchBar)
self.replaceEdit.setPlaceholderText(self.tr('Replace with'))
self.replaceEdit.returnPressed.connect(self.find)
self.csBox = QCheckBox(self.tr('Case sensitively'), self.searchBar)
self.searchBar.addWidget(self.searchEdit)
self.searchBar.addWidget(self.replaceEdit)
self.searchBar.addSeparator()
self.searchBar.addWidget(self.csBox)
self.searchBar.addAction(self.actionFindPrev)
self.searchBar.addAction(self.actionFind)
self.searchBar.addAction(self.actionReplace)
self.searchBar.addAction(self.actionCloseSearch)
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 is not None:
self.sl = globalSettings.spellCheckLocale
try:
enchant.Dict(self.sl or None)
except enchant.errors.Error as e:
warnings.warn(str(e), RuntimeWarning)
globalSettings.spellCheck = False
if globalSettings.spellCheck:
self.actionEnableSC.setChecked(True)
self.fileSystemWatcher = QFileSystemWatcher()
self.fileSystemWatcher.fileChanged.connect(self.fileChanged)
def restoreLastOpenedFiles(self):
for file in readListFromSettings("lastFileList"):
self.openFileWrapper(file)
# Show the tab of last opened file
lastTabIndex = globalSettings.lastTabIndex
if lastTabIndex >= 0 and lastTabIndex < self.tabWidget.count():
self.tabWidget.setCurrentIndex(lastTabIndex)
def iterateTabs(self):
for i in range(self.tabWidget.count()):
yield self.tabWidget.widget(i)
def updateStyleSheet(self):
if globalSettings.styleSheet:
sheetfile = QFile(globalSettings.styleSheet)
sheetfile.open(QIODevice.ReadOnly)
self.ss = QTextStream(sheetfile).readAll()
sheetfile.close()
else:
palette = QApplication.palette()
self.ss = 'html { color: %s; }\n' % palette.color(QPalette.WindowText).name()
self.ss += 'td, th { border: 1px solid #c3c3c3; padding: 0 3px 0 3px; }\n'
self.ss += 'table { border-collapse: collapse; }\n'
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
if hasattr(self.tabWidget, 'setTabBarAutoHide'):
self.tabWidget.setTabBarAutoHide(globalSettings.tabBarAutoHide)
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(getBundledIcon(name)))
def printError(self):
import traceback
print('Exception occurred while parsing document:', file=sys.stderr)
traceback.print_exc()
def tabFileNameChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
filename of the current tab has changed.
'''
if tab == self.currentTab:
if tab.fileName:
self.setWindowTitle("")
self.setWindowFilePath(tab.fileName)
self.tabWidget.setTabText(self.ind, tab.getBaseName())
self.tabWidget.setTabToolTip(self.ind, tab.fileName)
QDir.setCurrent(QFileInfo(tab.fileName).dir().path())
else:
self.setWindowFilePath('')
self.setWindowTitle(self.tr('New document') + '[*]')
canReload = bool(tab.fileName) and not self.autoSaveActive(tab)
self.actionSetEncoding.setEnabled(canReload)
self.actionReload.setEnabled(canReload)
def tabActiveMarkupChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
active markup class of the current tab has changed.
'''
if tab == self.currentTab:
markupClass = tab.getActiveMarkupClass()
dtMarkdown = (markupClass == markups.MarkdownMarkup)
dtMkdOrReST = dtMarkdown or (markupClass == markups.ReStructuredTextMarkup)
self.formattingBox.setEnabled(dtMarkdown)
self.symbolBox.setEnabled(dtMarkdown)
self.actionUnderline.setEnabled(dtMarkdown)
self.actionBold.setEnabled(dtMkdOrReST)
self.actionItalic.setEnabled(dtMkdOrReST)
def tabModificationStateChanged(self, tab):
'''
Perform all UI state changes that need to be done when the
modification state of the current tab has changed.
'''
if tab == self.currentTab:
changed = tab.editBox.document().isModified()
if self.autoSaveActive(tab):
changed = False
self.actionSave.setEnabled(changed)
self.setWindowModified(changed)
def createTab(self, fileName):
self.currentTab = ReTextTab(self, fileName,
previewState=int(globalSettings.livePreviewByDefault))
self.currentTab.fileNameChanged.connect(lambda: self.tabFileNameChanged(self.currentTab))
self.currentTab.modificationStateChanged.connect(lambda: self.tabModificationStateChanged(self.currentTab))
self.currentTab.activeMarkupChanged.connect(lambda: self.tabActiveMarkupChanged(self.currentTab))
self.tabWidget.addTab(self.currentTab, self.tr("New document"))
self.currentTab.updateBoxesVisibility()
def closeTab(self, ind):
if self.maybeSave(ind):
if self.tabWidget.count() == 1:
self.createTab("")
closedTab = self.tabWidget.widget(ind)
if closedTab.fileName:
self.fileSystemWatcher.removePath(closedTab.fileName)
self.tabWidget.removeTab(ind)
closedTab.deleteLater()
def changeIndex(self, ind):
'''
This function is called when a different tab is selected.
It changes the state of the window to mirror the current state
of the newly selected tab. Future changes to this state will be
done in response to signals emitted by the tab, to which the
window was subscribed when the tab was created. The window is
subscribed to all tabs like this, but only the active tab will
logically generate these signals.
Aside from the above this function also calls the handlers for
the other changes that are implied by a tab switch: filename
change, modification state change and active markup change.
'''
self.currentTab = self.tabWidget.currentWidget()
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
editBox.setFocus(Qt.OtherFocusReason)
self.tabFileNameChanged(self.currentTab)
self.tabModificationStateChanged(self.currentTab)
self.tabActiveMarkupChanged(self.currentTab)
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.triggerPreviewUpdate()
def preview(self, viewmode):
self.currentTab.previewState = viewmode * 2
self.actionLivePreview.setChecked(False)
self.editBar.setDisabled(viewmode)
self.currentTab.updateBoxesVisibility()
self.currentTab.triggerPreviewUpdate()
def enableLivePreview(self, livemode):
self.currentTab.previewState = int(livemode)
self.actionPreview.setChecked(livemode)
self.editBar.setEnabled(True)
self.currentTab.updateBoxesVisibility()
self.currentTab.triggerPreviewUpdate()
def enableWebKit(self, enable):
globalSettings.useWebKit = enable
globalSettings.useWebEngine = False
for tab in self.iterateTabs():
tab.rebuildPreviewBox()
def enableWebEngine(self, enable):
globalSettings.useWebKit = False
globalSettings.useWebEngine = enable
for tab in self.iterateTabs():
tab.rebuildPreviewBox()
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.editBox.installFakeVimHandler()
else:
FakeVimMode.exit(self)
def enableSpellCheck(self, yes):
try:
dict = enchant.Dict(self.sl or None)
except enchant.errors.Error as e:
QMessageBox.warning(self, '', str(e))
self.actionEnableSC.setChecked(False)
yes = False
self.setAllDictionaries(dict if yes else None)
globalSettings.spellCheck = yes
def setAllDictionaries(self, dictionary):
for tab in self.iterateTabs():
hl = tab.highlighter
hl.dictionary = dictionary
hl.rehighlight()
def changeLocale(self):
localedlg = LocaleDialog(self, defaultText=self.sl)
if localedlg.exec() != QDialog.Accepted:
return
sl = localedlg.localeEdit.text()
try:
enchant.Dict(sl or None)
except enchant.errors.Error as e:
QMessageBox.warning(self, '', str(e))
else:
self.sl = sl or None
self.enableSpellCheck(self.actionEnableSC.isChecked())
if localedlg.checkBox.isChecked():
globalSettings.spellCheckLocale = sl
def searchBarVisibilityChanged(self, visible):
self.actionSearch.setChecked(visible)
if visible:
self.searchEdit.setFocus(Qt.ShortcutFocusReason)
def find(self, back=False, replace=False):
flags = QTextDocument.FindFlags()
if back:
flags |= QTextDocument.FindBackward
if self.csBox.isChecked():
flags |= QTextDocument.FindCaseSensitively
text = self.searchEdit.text()
replaceText = self.replaceEdit.text() if replace else None
found = self.currentTab.find(text, flags, replaceText=replaceText)
self.setSearchEditColor(found)
def replaceAll(self):
text = self.searchEdit.text()
replaceText = self.replaceEdit.text()
found = self.currentTab.replaceAll(text, replaceText)
self.setSearchEditColor(found)
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 moveToTopOfRecentFileList(self, fileName):
if fileName:
files = readListFromSettings("recentFileList")
if fileName in files:
files.remove(fileName)
files.insert(0, fileName)
if len(files) > 10:
del files[10:]
writeListToSettings("recentFileList", files)
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.getActiveMarkupClass()
for action in self.extensionActions:
if markupClass is None:
action[0].setEnabled(False)
continue
mimetype = action[1]
if mimetype is None:
enabled = True
elif markupClass == markups.MarkdownMarkup:
enabled = (mimetype in ("text/x-retext-markdown", "text/x-markdown", "text/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"), QDir.currentPath(),
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.readTextFromFile(fileName)
self.moveToTopOfRecentFileList(self.currentTab.fileName)
def showEncodingDialog(self):
if not self.maybeSave(self.ind):
return
codecsSet = set(bytes(QTextCodec.codecForName(alias).name())
for alias in QTextCodec.availableCodecs())
encoding, ok = QInputDialog.getItem(self, '',
self.tr('Select file encoding from the list:'),
[bytes(b).decode() for b in sorted(codecsSet)],
0, False)
if ok:
self.currentTab.readTextFromFile(None, 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()
def saveFile(self, dlg=False):
fileNameToSave = self.currentTab.fileName
if (not fileNameToSave) or dlg:
markupClass = self.currentTab.getActiveMarkupClass()
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
fileNameToSave = QFileDialog.getSaveFileName(self,
self.tr("Save file"), "", defaultExt)[0]
if fileNameToSave:
if not QFileInfo(fileNameToSave).suffix():
fileNameToSave += ext
# Make sure we don't overwrite a file opened in other tab
for tab in self.iterateTabs():
if tab is not self.currentTab and tab.fileName == fileNameToSave:
QMessageBox.warning(self, "",
self.tr("Cannot save to file which is open in another tab!"))
return False
self.actionSetEncoding.setDisabled(self.autoSaveActive())
if fileNameToSave:
if self.currentTab.saveTextToFile(fileNameToSave):
self.moveToTopOfRecentFileList(self.currentTab.fileName)
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.getDocumentForExport(includeStyleSheet=False,
webenv=True)
except Exception:
return self.printError()
htmlFile = QFile(fileName)
result = htmlFile.open(QIODevice.WriteOnly)
if not result:
QMessageBox.warning(self, '',
self.tr("Cannot save to file because it is read-only!"))
return
html = QTextStream(htmlFile)
if globalSettings.defaultCodec:
html.setCodec(globalSettings.defaultCodec)
html << htmltext
htmlFile.close()
def textDocument(self, title, htmltext):
td = QTextDocument()
td.setMetaInformation(QTextDocument.DocumentTitle, title)
if self.ss:
td.setDefaultStyleSheet(self.ss)
td.setHtml(htmltext)
td.setDefaultFont(globalSettings.font)
return td
def saveOdf(self):
title, htmltext, _ = self.currentTab.getDocumentForExport(includeStyleSheet=True,
webenv=False)
try:
document = self.textDocument(title, htmltext)
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, title, htmltext, preview):
if globalSettings.useWebKit:
return preview
try:
return self.textDocument(title, htmltext)
except Exception:
self.printError()
def standardPrinter(self, title):
printer = QPrinter(QPrinter.HighResolution)
printer.setDocName(title)
printer.setCreator('ReText %s' % app_version)
return printer
def savePdf(self):
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"
title, htmltext, preview = self.currentTab.getDocumentForExport(includeStyleSheet=True,
webenv=False)
printer = self.standardPrinter(title)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName(fileName)
document = self.getDocumentForPrint(title, htmltext, preview)
if document != None:
document.print(printer)
def printFile(self):
title, htmltext, preview = self.currentTab.getDocumentForExport(includeStyleSheet=True,
webenv=False)
printer = self.standardPrinter(title)
dlg = QPrintDialog(printer, self)
dlg.setWindowTitle(self.tr("Print document"))
if (dlg.exec() == QDialog.Accepted):
document = self.getDocumentForPrint(title, htmltext, preview)
if document != None:
document.print(printer)
def printPreview(self):
title, htmltext, preview = self.currentTab.getDocumentForExport(includeStyleSheet=True,
webenv=False)
document = self.getDocumentForPrint(title, htmltext, preview)
if document is None:
return
printer = self.standardPrinter(title)
preview = QPrintPreviewDialog(printer, self)
preview.paintRequested.connect(document.print)
preview.exec()
def runExtensionCommand(self, command, filefilter, defaultext):
import shlex
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
else:
fileName = 'out' + defaultext
basename = '.%s.retext-temp' % self.currentTab.getBaseName()
if html:
tmpname = basename+'.html'
self.saveHtml(tmpname)
else:
tmpname = basename + self.currentTab.getActiveMarkupClass().default_extension
self.currentTab.writeTextToFile(tmpname)
command = command.replace('%of', shlex.quote(fileName))
command = command.replace('%html' if html else '%if', shlex.quote(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()
def autoSaveActive(self, tab=None):
tab = tab if tab else self.currentTab
return bool(self.autoSaveEnabled and tab.fileName and
QFileInfo(tab.fileName).isWritable())
def clipboardDataChanged(self):
mimeData = QApplication.instance().clipboard().mimeData()
if mimeData is not None:
self.actionPaste.setEnabled(mimeData.hasText() or mimeData.hasImage())
def insertFormatting(self, formatting):
cursor = self.currentTab.editBox.textCursor()
text = cursor.selectedText()
moveCursorTo = None
def c(cursor):
nonlocal moveCursorTo
moveCursorTo = cursor.position()
def ensurenl(cursor):
if not cursor.atBlockStart():
cursor.insertText('\n\n')
toinsert = {
'header': (ensurenl, '# ', text),
'italic': ('*', text, c, '*'),
'bold': ('**', text, c, '**'),
'underline': ('', text, c, ''),
'numbering': (ensurenl, ' 1. ', text),
'bullets': (ensurenl, ' * ', text),
'image': (', ')'),
'link': ('[', text or self.tr('Link text'), c, '](', self.tr('URL'), ')'),
'inline code': ('`', text, c, '`'),
'code block': (ensurenl, ' ', text),
'blockquote': (ensurenl, '> ', text),
}
if formatting not in toinsert:
return
cursor.beginEditBlock()
for token in toinsert[formatting]:
if callable(token):
token(cursor)
else:
cursor.insertText(token)
cursor.endEditBlock()
self.formattingBox.setCurrentIndex(0)
# Bring back the focus on the editor
self.currentTab.editBox.setFocus(Qt.OtherFocusReason)
if moveCursorTo:
cursor.setPosition(moveCursorTo)
self.currentTab.editBox.setTextCursor(cursor)
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()
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()
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)
if self.autoSaveActive(tab):
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()
if globalSettings.openLastFilesOnStartup:
files = [tab.fileName for tab in self.iterateTabs()]
writeListToSettings("lastFileList", files)
globalSettings.lastTabIndex = self.tabWidget.currentIndex()
closeevent.accept()
def viewHtml(self):
htmlDlg = HtmlDialog(self)
try:
_, htmltext, _ = self.currentTab.getDocumentForExport(includeStyleSheet=False,
webenv=False)
except Exception:
return self.printError()
winTitle = self.currentTab.getBaseName()
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):
globalSettings.defaultMarkup = markupClass.name
for tab in self.iterateTabs():
if not tab.fileName:
tab.updateActiveMarkupClass()
ReText-7.0.1/ReText/xsettings.py 0000644 0001750 0001750 00000015456 13113344366 017430 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
c.free.argtypes = [ctypes.c_void_p]
c.free.restype = None
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-7.0.1/ReText/converterprocess.py 0000644 0001750 0001750 00000014227 13047421537 021003 0 ustar dmitry dmitry 0000000 0000000 #!/usr/bin/env python3
import markups
import multiprocessing as mp
import pickle
import signal
import struct
import traceback
import weakref
try:
from socket import socketpair
except ImportError:
# Windows compatibility: socket.socketpair backport for Python < 3.5
from backports.socketpair import socketpair
from PyQt5.QtCore import pyqtSignal, QObject, QSocketNotifier
def recvall(sock, remaining):
alldata = bytearray()
while remaining > 0:
data = sock.recv(remaining)
if len(data) == 0:
raise EOFError('Received 0 bytes from socket while more bytes were expected. Did the sender process exit unexpectedly?')
alldata.extend(data)
remaining -= len(data)
return alldata
def receiveObject(sock):
sizeBuf = recvall(sock, 4)
size = struct.unpack('I', sizeBuf)[0]
message = recvall(sock, size)
obj = pickle.loads(message)
return obj
def sendObject(sock, obj):
message = pickle.dumps(obj)
sizeBuf = struct.pack('I', len(message))
sock.sendall(sizeBuf)
sock.sendall(message)
class ConversionError(Exception):
pass
class MarkupNotAvailableError(Exception):
pass
def _indent(text, prefix):
return ''.join(('%s%s\n' % (prefix, line) for line in text.splitlines()))
def _converter_process_func(conn_parent, conn_child):
conn_parent.close()
# Ignore ctrl-C. The main application will also receive the signal and
# determine if the application should be stopped or not.
signal.signal(signal.SIGINT, signal.SIG_IGN)
current_markup = None
while True:
job = receiveObject(conn_child)
if job['command'] == 'quit':
break
elif job['command'] == 'convert':
try:
if (not current_markup or
current_markup.name != job['markup_name'] or
current_markup.filename != job['filename']):
markup_class = markups.find_markup_class_by_name(job['markup_name'])
if not markup_class.available():
raise MarkupNotAvailableError('The specified markup was not available')
current_markup = markup_class(job['filename'])
current_markup.requested_extensions = job['requested_extensions']
converted = current_markup.convert(job['text'])
result = ('ok', converted)
except MarkupNotAvailableError as e:
result = ('markupnotavailableerror', e.args)
except Exception:
result = ('conversionerror',
'The background markup conversion process received this exception:\n%s' %
_indent(traceback.format_exc(), ' '))
try:
sendObject(conn_child, result)
except BrokenPipeError:
# Continue despite the broken pipe because we expect that a
# 'quit' command will have been sent. If it has been then we
# should terminate without any error messages. If no command
# was queued we will get an EOFError from the read, giving us a
# second chance to show that something went wrong by exiting
# with a traceback.
continue
class ConverterProcess(QObject):
conversionDone = pyqtSignal()
def __init__(self):
super(QObject, self).__init__()
conn_parent, conn_child = socketpair()
# TODO: figure out which of the two sockets should be set to
# inheritable and which should be passed to the child
if hasattr(conn_child, 'set_inheritable'):
conn_child.set_inheritable(True)
# Use a local variable for child so that we can talk to the child in
# on_finalize without needing a reference to self
child = mp.Process(target=_converter_process_func, args=(conn_parent, conn_child))
child.daemon = True
child.start()
self.child = child
conn_child.close()
self.conn = conn_parent
self.busy = False
self.notificationPending = False
self.conversionNotifier = QSocketNotifier(self.conn.fileno(),
QSocketNotifier.Read)
self.conversionNotifier.activated.connect(self._conversionNotifierActivated)
def on_finalize(conn):
sendObject(conn_parent, {'command':'quit'})
conn_parent.close()
child.join()
weakref.finalize(self, on_finalize, conn_parent)
def _conversionNotifierActivated(self):
# The ready-for-read signal on the socket may be triggered multiple
# times, but we only send a single notification to the client as soon
# as the results of the conversion are starting to come in. This makes
# it easy for clients to avoid multiple calls to get_result for the
# same conversion.
if self.notificationPending:
self.notificationPending = False
# Set the socket to blocking before waking up any interested parties,
# because it has been set to unblocking by QSocketNotifier
self.conn.setblocking(True)
self.conversionDone.emit()
def start_conversion(self, markup_name, filename, requested_extensions, text):
if self.busy:
raise RuntimeError('Already converting')
sendObject(self.conn, {'command': 'convert',
'markup_name' : markup_name,
'filename' : filename,
'requested_extensions' : requested_extensions,
'text' : text})
self.busy = True
self.notificationPending = True
def get_result(self):
if not self.busy:
raise RuntimeError('No ongoing conversion')
self.busy = False
status, result = receiveObject(self.conn)
if status == 'markupnotavailableerror':
raise MarkupNotAvailableError(result)
elif status == 'conversionerror':
raise ConversionError(result)
return result
def stop(self):
sendObject(self.conn, {'command': 'quit'})
self.conn.close()
ReText-7.0.1/ReText/webenginepreview.py 0000644 0001750 0001750 00000010024 13117307332 020723 0 ustar dmitry dmitry 0000000 0000000 # vim: ts=4:sw=4:expandtab
# This file is part of ReText
# Copyright: 2017 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.preview import ReTextWebPreview
from ReText.syncscroll import SyncScroll
from PyQt5.QtGui import QDesktopServices, QGuiApplication
from PyQt5.QtWebEngineWidgets import QWebEnginePage, QWebEngineView, QWebEngineSettings
class ReTextWebEnginePage(QWebEnginePage):
def __init__(self, parent, tab):
QWebEnginePage.__init__(self, parent)
self.tab = tab
def setScrollPosition(self, pos):
self.runJavaScript("window.scrollTo(%s, %s);" % (pos.x(), pos.y()))
def getPositionMap(self, callback):
def resultCallback(result):
if result:
return callback({int(a): b for a, b in result.items()})
script = """
var elements = document.querySelectorAll('[data-posmap]');
var result = {};
var bodyTop = document.body.getBoundingClientRect().top;
for (var i = 0; i < elements.length; ++i) {
var element = elements[i];
value = element.getAttribute('data-posmap');
bottom = element.getBoundingClientRect().bottom - bodyTop;
result[value] = bottom;
}
result;
"""
self.runJavaScript(script, resultCallback)
def javaScriptConsoleMessage(self, level, message, lineNumber, sourceId):
print("level=%r message=%r lineNumber=%r sourceId=%r" % (level, message, lineNumber, sourceId))
def acceptNavigationRequest(self, url, type, isMainFrame):
if url.isLocalFile():
localFile = url.toLocalFile()
if localFile == self.tab.fileName:
self.tab.startPendingConversion()
return False
if self.tab.openSourceFile(localFile):
return False
if globalSettings.handleWebLinks:
return True
QDesktopServices.openUrl(url)
return False
class ReTextWebEnginePreview(ReTextWebPreview, QWebEngineView):
def __init__(self, tab,
editorPositionToSourceLineFunc,
sourceLineToEditorPositionFunc):
QWebEngineView.__init__(self, parent=tab)
webPage = ReTextWebEnginePage(self, tab)
self.setPage(webPage)
self.syncscroll = SyncScroll(webPage,
editorPositionToSourceLineFunc,
sourceLineToEditorPositionFunc)
ReTextWebPreview.__init__(self, tab.editBox)
settings = self.settings()
settings.setAttribute(QWebEngineSettings.LocalContentCanAccessFileUrls,
False)
def updateFontSettings(self):
settings = self.settings()
settings.setFontFamily(QWebEngineSettings.StandardFont,
globalSettings.font.family())
settings.setFontSize(QWebEngineSettings.DefaultFontSize,
globalSettings.font.pointSize())
def setHtml(self, html, baseUrl):
# A hack to prevent WebEngine from stealing the focus
self.setEnabled(False)
QWebEngineView.setHtml(self, html, baseUrl)
self.setEnabled(True)
def _handleWheelEvent(self, event):
# Only pass wheelEvents on to the preview if syncscroll is
# controlling the position of the preview
if self.syncscroll.isActive():
QGuiApplication.sendEvent(self.focusProxy(), event)
ReText-7.0.1/ReText/dialogs.py 0000644 0001750 0001750 00000004267 13047421537 017022 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=None):
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)
if defaultText:
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-7.0.1/ReText/mdx_posmap.py 0000644 0001750 0001750 00000006540 13047421537 017543 0 ustar dmitry dmitry 0000000 0000000 '''
Position Map Extension for Python-Markdown
==========================================
This extension adds data-posmap attributes to the generated HTML elements that
can be used to relate HTML elements to the corresponding lines in the markdown
input file.
Note: the line number stored in the data-posmap attribute corresponds to the
empty line *after* the markdown block that the HTML was generated from.
Copyright 2016 [Maurice van der Pot](griffon26@kfk4ever.com)
License: [BSD](http://www.opensource.org/licenses/bsd-license.php)
'''
from __future__ import unicode_literals
import re
from markdown.blockprocessors import BlockProcessor
from markdown.extensions import Extension
from markdown.preprocessors import Preprocessor
from markdown.util import etree, HTML_PLACEHOLDER_RE
class PosMapExtension(Extension):
""" Position Map Extension for Python-Markdown. """
def extendMarkdown(self, md, md_globals):
""" Insert the PosMapExtension blockprocessor before any other
extensions to make sure our own markers, inserted by the
preprocessor, are removed before any other extensions get confused
by them.
"""
md.preprocessors.add('posmap_mark', PosMapMarkPreprocessor(md), '_begin')
md.preprocessors.add('posmap_clean', PosMapCleanPreprocessor(md), '_end')
md.parser.blockprocessors.add('posmap', PosMapBlockProcessor(md.parser), '_begin')
class PosMapMarkPreprocessor(Preprocessor):
""" PosMapMarkPreprocessor - insert $posmapmarker$linenr entries at each empty line """
def run(self, lines):
new_text = []
for i, line in enumerate(lines):
new_text.append(line)
if line == '':
new_text.append('$posmapmarker$%d' % i)
new_text.append('')
return new_text
class PosMapCleanPreprocessor(Preprocessor):
""" PosMapCleanPreprocessor - remove $posmapmarker$linenr entries that
accidentally ended up in the htmlStash. This could have happened
because they were inside html tags or a fenced code block
"""
POSMAP_MARKER_RE = re.compile('\$posmapmarker\$\d+\n\n')
def run(self, lines):
for i in range(self.markdown.htmlStash.html_counter):
html, safe = self.markdown.htmlStash.rawHtmlBlocks[i]
html = re.sub(self.POSMAP_MARKER_RE, '', html)
self.markdown.htmlStash.rawHtmlBlocks[i] = (html, safe)
return lines
class PosMapBlockProcessor(BlockProcessor):
""" PosMapBlockProcessor - remove each marker and add a data-posmap
attribute to the previous HTML element
"""
def test(self, parent, block):
return block.startswith('$posmapmarker$')
def run(self, parent, blocks):
block = blocks.pop(0)
line_nr = block.split('$')[2]
last_child = self.lastChild(parent)
if last_child != None:
# Avoid setting the attribute on HTML placeholders, because it
# would interfere with later replacement with literal HTML
# fragments. In this case just add an empty
with the attribute.
if last_child.text and re.match(HTML_PLACEHOLDER_RE, last_child.text):
last_child = etree.SubElement(parent, 'p')
last_child.set('data-posmap', line_nr)
def makeExtension(*args, **kwargs):
return PosMapExtension(*args, **kwargs)
ReText-7.0.1/ReText/highlighter.py 0000644 0001750 0001750 00000015443 13047642057 017676 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-]+:)(`.+?`)')
reReSTLinks = re.compile('(`.+?<)(.+?)(>`__?)')
reReSTLinkRefs = re.compile(r'\.\. _`?(.*?)`?: (.*)')
reReSTFldLists = re.compile('^ *:(.*?):')
reTextileHdrs = re.compile(r'^h[1-6][()<>=]*\.\s.+')
reTextileQuot = re.compile(r'^bq\.\s.+')
reMkdCodeSpans = re.compile('`[^`]*`')
reMkdMathSpans = re.compile(r'\\[\(\[].*?\\[\)\]]')
reReSTCodeSpan = re.compile('``.+?``')
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,
'codeSpans': QColor(0x50, 0x50, 0x50),
'markdownLinks': QColor(0, 0, 0x90),
'blockquotes': Qt.darkGray,
'restDirectives': Qt.darkMagenta,
'restRoles': Qt.darkRed,
'whitespaceOnEnd': QColor(0xe1, 0xe1, 0xa5, 0x80)
}
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 Formatter:
def __init__(self, funcs=None):
self._funcs = funcs or []
def __or__(self, other):
result = Formatter(self._funcs.copy())
if isinstance(other, Formatter):
result._funcs.extend(other._funcs)
elif isinstance(other, QFont.Weight):
result._funcs.append(lambda f: f.setFontWeight(other))
return result
def format(self, charFormat):
for func in self._funcs:
func(charFormat)
NF = Formatter()
ITAL = Formatter([lambda f: f.setFontItalic(True)])
UNDL = Formatter([lambda f: f.setFontUnderline(True)])
def FG(colorName):
color = colorScheme[colorName]
func = lambda f: f.setForeground(color)
return Formatter([func])
class ReTextHighlighter(QSyntaxHighlighter):
dictionary = None
docType = None
def highlightBlock(self, text):
patterns = (
# regex, color,
(reHtmlTags, FG('htmlTags') | QFont.Bold), # 0
(reHtmlSymbols, FG('htmlSymbols') | QFont.Bold), # 1
(reHtmlStrings, FG('htmlStrings') | QFont.Bold), # 2
(reHtmlComments, FG('htmlComments')), # 3
(reAsterisks, ITAL), # 4
(reUnderline, ITAL), # 5
(reDblAsterisks, NF | QFont.Bold), # 6
(reDblUnderline, NF | QFont.Bold), # 7
(reTrpAsterisks, ITAL | QFont.Bold), # 8
(reTrpUnderline, ITAL | QFont.Bold), # 9
(reMkdHeaders, NF | QFont.Black), # 10
(reMkdLinksImgs, FG('markdownLinks')), # 11
(reMkdLinkRefs, ITAL | UNDL), # 12
(reBlockQuotes, FG('blockquotes')), # 13
(reReSTDirects, FG('restDirectives') | QFont.Bold), # 14
(reReSTRoles, NF, FG('restRoles') | QFont.Bold, FG('htmlStrings')), # 15
(reTextileHdrs, NF | QFont.Black), # 16
(reTextileQuot, FG('blockquotes')), # 17
(reAsterisks, NF | QFont.Bold), # 18
(reDblUnderline, ITAL), # 19
(reMkdCodeSpans, FG('codeSpans')), # 20
(reReSTCodeSpan, FG('codeSpans')), # 21
(reReSTLinks, NF, NF, ITAL | UNDL, NF), # 22
(reReSTLinkRefs, NF, FG('markdownLinks'), ITAL | UNDL), # 23
(reReSTFldLists, NF, FG('restDirectives')), # 24
(reMkdMathSpans, FG('codeSpans')), # 25
)
patternsDict = {
'Markdown': (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 20, 25),
'reStructuredText': (4, 6, 14, 15, 21, 22, 23, 24),
'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]
for match in pattern[0].finditer(text):
for i, formatter in enumerate(pattern[1:]):
charFormat = QTextCharFormat()
formatter.format(charFormat)
self.setFormat(match.start(i), match.end(i) - match.start(i), 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-7.0.1/ReText/webkitpreview.py 0000644 0001750 0001750 00000005024 13047642057 020261 0 ustar dmitry dmitry 0000000 0000000 # vim: ts=8:sts=8:sw=8:noexpandtab
#
# This file is part of ReText
# Copyright: 2015-2017 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.syncscroll import SyncScroll
from ReText.preview import ReTextWebPreview
from PyQt5.QtGui import QDesktopServices
from PyQt5.QtWebKit import QWebSettings
from PyQt5.QtWebKitWidgets import QWebPage, QWebView
class ReTextWebKitPreview(ReTextWebPreview, QWebView):
def __init__(self, tab,
editorPositionToSourceLineFunc,
sourceLineToEditorPositionFunc):
QWebView.__init__(self)
self.tab = tab
self.syncscroll = SyncScroll(self.page().mainFrame(),
editorPositionToSourceLineFunc,
sourceLineToEditorPositionFunc)
ReTextWebPreview.__init__(self, tab.editBox)
self.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
self.page().linkClicked.connect(self._handleLinkClicked)
self.settings().setAttribute(QWebSettings.LocalContentCanAccessFileUrls, False)
# Avoid caching of CSS
self.settings().setObjectCacheCapacities(0,0,0)
def updateFontSettings(self):
settings = self.settings()
settings.setFontFamily(QWebSettings.StandardFont,
globalSettings.font.family())
settings.setFontSize(QWebSettings.DefaultFontSize,
globalSettings.font.pointSize())
def _handleWheelEvent(self, event):
# Only pass wheelEvents on to the preview if syncscroll is
# controlling the position of the preview
if self.syncscroll.isActive():
self.wheelEvent(event)
def _handleLinkClicked(self, url):
if url.isLocalFile():
localFile = url.toLocalFile()
if localFile == self.tab.fileName and url.hasFragment():
self.page().mainFrame().scrollToAnchor(url.fragment())
return
if self.tab.openSourceFile(localFile):
return
if globalSettings.handleWebLinks:
self.load(url)
else:
QDesktopServices.openUrl(url)
ReText-7.0.1/ReText/tab.py 0000644 0001750 0001750 00000036400 13123551102 016123 0 ustar dmitry dmitry 0000000 0000000 # vim: ts=8:sts=8:sw=8:noexpandtab
#
# This file is part of ReText
# Copyright: 2015-2017 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 os.path import exists, splitext
from markups import get_markup_for_file_name, find_markup_class_by_name
from markups.common import MODULE_HOME_PAGE
from ReText import app_version, globalSettings, converterprocess
from ReText.editor import ReTextEdit
from ReText.highlighter import ReTextHighlighter
from ReText.preview import ReTextPreview
try:
import enchant
except ImportError:
enchant = None
from PyQt5.QtCore import pyqtSignal, Qt, QDir, QFile, QFileInfo, QPoint, QTextStream, QTimer, QUrl
from PyQt5.QtGui import QTextCursor, QTextDocument
from PyQt5.QtWidgets import QTextEdit, QSplitter
try:
from ReText.webkitpreview import ReTextWebKitPreview
except ImportError:
ReTextWebKitPreview = None
try:
from ReText.webenginepreview import ReTextWebEnginePreview
except ImportError:
ReTextWebEnginePreview = None
PreviewDisabled, PreviewLive, PreviewNormal = range(3)
class ReTextTab(QSplitter):
fileNameChanged = pyqtSignal()
modificationStateChanged = pyqtSignal()
activeMarkupChanged = pyqtSignal()
# Make _fileName a read-only property to make sure that any
# modification happens through the proper functions. These functions
# will make sure that the fileNameChanged signal is emitted when
# applicable.
@property
def fileName(self):
return self._fileName
def __init__(self, parent, fileName, previewState=PreviewDisabled):
super(QSplitter, self).__init__(Qt.Horizontal, parent=parent)
self.p = parent
self._fileName = fileName
self.editBox = ReTextEdit(self)
self.previewBox = self.createPreviewBox(self.editBox)
self.activeMarkupClass = None
self.markup = None
self.converted = None
self.previewState = previewState
self.previewOutdated = False
self.conversionPending = False
self.converterProcess = converterprocess.ConverterProcess()
self.converterProcess.conversionDone.connect(self.updatePreviewBox)
textDocument = self.editBox.document()
self.highlighter = ReTextHighlighter(textDocument)
if enchant is not None and parent.actionEnableSC.isChecked():
self.highlighter.dictionary = enchant.Dict(parent.sl or None)
# Rehighlighting is tied to the change in markup class that
# happens at the end of this function
self.editBox.textChanged.connect(self.triggerPreviewUpdate)
self.editBox.undoAvailable.connect(parent.actionUndo.setEnabled)
self.editBox.redoAvailable.connect(parent.actionRedo.setEnabled)
self.editBox.copyAvailable.connect(parent.actionCopy.setEnabled)
# 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)
self.addWidget(widget)
self.setSizes((50, 50))
self.setChildrenCollapsible(False)
textDocument.modificationChanged.connect(self.handleModificationChanged)
self.updateActiveMarkupClass()
def handleModificationChanged(self):
self.modificationStateChanged.emit()
def createPreviewBox(self, editBox):
# Use closures to avoid a hard reference from ReTextWebKitPreview
# to self, which would keep the tab and its resources alive
# even after other references to it have disappeared.
def editorPositionToSourceLine(editorPosition):
viewportPosition = editorPosition - editBox.verticalScrollBar().value()
sourceLine = editBox.cursorForPosition(QPoint(0,viewportPosition)).blockNumber()
return sourceLine
def sourceLineToEditorPosition(sourceLine):
doc = editBox.document()
block = doc.findBlockByNumber(sourceLine)
rect = doc.documentLayout().blockBoundingRect(block)
return rect.top()
if ReTextWebKitPreview and globalSettings.useWebKit:
preview = ReTextWebKitPreview(self,
editorPositionToSourceLine,
sourceLineToEditorPosition)
elif ReTextWebEnginePreview and globalSettings.useWebEngine:
preview = ReTextWebEnginePreview(self,
editorPositionToSourceLine,
sourceLineToEditorPosition)
else:
preview = ReTextPreview(self)
return preview
def getActiveMarkupClass(self):
'''
Return the currently active markup class for this tab.
No objects should be created of this class, it should
only be used to retrieve markup class specific information.
'''
return self.activeMarkupClass
def updateActiveMarkupClass(self):
'''
Update the active markup class based on the default class and
the current filename. If the active markup class changes, the
highlighter is rerun on the input text, the markup object of
this tab is replaced with one of the new class and the
activeMarkupChanged signal is emitted.
'''
previousMarkupClass = self.activeMarkupClass
self.activeMarkupClass = find_markup_class_by_name(globalSettings.defaultMarkup)
if self._fileName:
markupClass = get_markup_for_file_name(
self._fileName, return_class=True)
if markupClass:
self.activeMarkupClass = markupClass
if self.activeMarkupClass != previousMarkupClass:
self.highlighter.docType = self.activeMarkupClass.name if self.activeMarkupClass else None
self.highlighter.rehighlight()
self.activeMarkupChanged.emit()
self.triggerPreviewUpdate()
def getDocumentTitleFromConverted(self, converted):
if converted:
try:
return converted.get_document_title()
except Exception:
self.p.printError()
return self.getBaseName()
def getBaseName(self):
if self._fileName:
fileinfo = QFileInfo(self._fileName)
basename = fileinfo.completeBaseName()
return (basename if basename else fileinfo.fileName())
return self.tr("New document")
def getHtmlFromConverted(self, converted, includeStyleSheet=True, webenv=False):
if converted is None:
markupClass = self.getActiveMarkupClass()
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
headers = ''
if includeStyleSheet:
headers += '\n'
baseName = self.getBaseName()
cssFileName = baseName + '.css'
if QFile.exists(cssFileName):
headers += ('\n'
% cssFileName)
headers += ('\n' % app_version)
return converted.get_whole_html(
custom_headers=headers, include_stylesheet=includeStyleSheet,
fallback_title=baseName, webenv=webenv)
def getDocumentForExport(self, includeStyleSheet, webenv):
markupClass = self.getActiveMarkupClass()
if markupClass and markupClass.available():
exportMarkup = markupClass(filename=self._fileName)
text = self.editBox.toPlainText()
converted = exportMarkup.convert(text)
else:
converted = None
return (self.getDocumentTitleFromConverted(converted),
self.getHtmlFromConverted(converted, includeStyleSheet=includeStyleSheet, webenv=webenv),
self.previewBox)
def updatePreviewBox(self):
self.conversionPending = False
try:
self.converted = self.converterProcess.get_result()
except converterprocess.MarkupNotAvailableError:
self.converted = None
except converterprocess.ConversionError:
return self.p.printError()
if isinstance(self.previewBox, QTextEdit):
scrollbar = self.previewBox.verticalScrollBar()
scrollbarValue = scrollbar.value()
distToBottom = scrollbar.maximum() - scrollbarValue
try:
html = self.getHtmlFromConverted(self.converted)
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:
self.previewBox.updateFontSettings()
# Always provide a baseUrl otherwise QWebView will
# refuse to show images or other external objects
if self._fileName:
baseUrl = QUrl.fromLocalFile(self._fileName)
else:
baseUrl = QUrl.fromLocalFile(QDir.currentPath())
self.previewBox.setHtml(html, baseUrl)
if self.previewOutdated:
self.triggerPreviewUpdate()
def triggerPreviewUpdate(self):
self.previewOutdated = True
if not self.conversionPending:
self.conversionPending = True
QTimer.singleShot(500, self.startPendingConversion)
def startPendingConversion(self):
self.previewOutdated = False
requested_extensions = ['ReText.mdx_posmap'] if globalSettings.syncScroll else []
self.converterProcess.start_conversion(self.getActiveMarkupClass().name,
self.fileName,
requested_extensions,
self.editBox.toPlainText())
def updateBoxesVisibility(self):
self.editBox.setVisible(self.previewState < PreviewNormal)
self.previewBox.setVisible(self.previewState > PreviewDisabled)
def rebuildPreviewBox(self):
self.previewBox.disconnectExternalSignals()
self.previewBox.setParent(None)
self.previewBox.deleteLater()
self.previewBox = self.createPreviewBox(self.editBox)
self.previewBox.setMinimumWidth(125)
self.addWidget(self.previewBox)
self.setSizes((50, 50))
self.triggerPreviewUpdate()
self.updateBoxesVisibility()
def detectFileEncoding(self, fileName):
'''
Detect content encoding of specific file.
It will return None if it can't determine the encoding.
'''
try:
import chardet
except ImportError:
return
with open(fileName, 'rb') as inputFile:
raw = inputFile.read(2048)
result = chardet.detect(raw)
if result['confidence'] > 0.9:
if result['encoding'].lower() == 'ascii':
# UTF-8 files can be falsely detected as ASCII files if they
# don't contain non-ASCII characters in first 2048 bytes.
# We map ASCII to UTF-8 to avoid such situations.
return 'utf-8'
return result['encoding']
def readTextFromFile(self, fileName=None, encoding=None):
previousFileName = self._fileName
if fileName:
self._fileName = fileName
# Only try to detect encoding if it is not specified
if encoding is None and globalSettings.detectEncoding:
encoding = self.detectFileEncoding(self._fileName)
# TODO: why do we open the file twice: for detecting encoding
# and for actual read? Can we open it just once?
openfile = QFile(self._fileName)
openfile.open(QFile.ReadOnly)
stream = QTextStream(openfile)
encoding = encoding or globalSettings.defaultCodec
if encoding:
stream.setCodec(encoding)
# If encoding is specified or detected, we should save the file with
# the same encoding
self.editBox.document().setProperty("encoding", encoding)
text = stream.readAll()
openfile.close()
self.editBox.setPlainText(text)
self.editBox.document().setModified(False)
if previousFileName != self._fileName:
self.updateActiveMarkupClass()
self.fileNameChanged.emit()
def writeTextToFile(self, fileName=None):
# Just writes the text to file, without any changes to tab object
# Used directly for i.e. export extensions
# Get text from the cursor to avoid tweaking special characters,
# see https://bugreports.qt.io/browse/QTBUG-57552 and
# https://github.com/retext-project/retext/issues/216
cursor = self.editBox.textCursor()
cursor.select(QTextCursor.Document)
text = cursor.selectedText().replace('\u2029', '\n')
savefile = QFile(fileName or self._fileName)
result = savefile.open(QFile.WriteOnly)
if result:
savestream = QTextStream(savefile)
# Save the file with original encoding
encoding = self.editBox.document().property("encoding")
if encoding is not None:
savestream.setCodec(encoding)
savestream << text
savefile.close()
return result
def saveTextToFile(self, fileName=None):
# Sets fileName as tab fileName and writes the text to that file
if self._fileName:
self.p.fileSystemWatcher.removePath(self._fileName)
result = self.writeTextToFile(fileName)
if result:
self.editBox.document().setModified(False)
self.p.fileSystemWatcher.addPath(fileName or self._fileName)
if fileName and self._fileName != fileName:
self._fileName = fileName
self.updateActiveMarkupClass()
self.fileNameChanged.emit()
return result
def find(self, text, flags, replaceText=None, wrap=False):
cursor = self.editBox.textCursor()
if wrap and flags & QTextDocument.FindBackward:
cursor.movePosition(QTextCursor.End)
elif wrap:
cursor.movePosition(QTextCursor.Start)
if replaceText is not None and cursor.selectedText() == text:
newCursor = cursor
else:
newCursor = self.editBox.document().find(text, cursor, flags)
if not newCursor.isNull():
if replaceText is not None:
newCursor.insertText(replaceText)
newCursor.movePosition(QTextCursor.Left, QTextCursor.MoveAnchor, len(replaceText))
newCursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, len(replaceText))
self.editBox.setTextCursor(newCursor)
return True
if not wrap:
return self.find(text, flags, replaceText, True)
return False
def replaceAll(self, text, replaceText):
cursor = self.editBox.textCursor()
cursor.beginEditBlock()
cursor.movePosition(QTextCursor.Start)
flags = QTextDocument.FindFlags()
cursor = lastCursor = self.editBox.document().find(text, cursor, flags)
while not cursor.isNull():
cursor.insertText(replaceText)
lastCursor = cursor
cursor = self.editBox.document().find(text, cursor, flags)
if not lastCursor.isNull():
lastCursor.movePosition(QTextCursor.Left, QTextCursor.MoveAnchor, len(replaceText))
lastCursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, len(replaceText))
self.editBox.setTextCursor(lastCursor)
self.editBox.textCursor().endEditBlock()
return not lastCursor.isNull()
def openSourceFile(self, fileToOpen):
"""Finds and opens the source file for link target fileToOpen.
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 paths like [test](../test) or [test](folder/test) are also possible.
"""
if self.fileName:
currentExt = splitext(self.fileName)[1]
basename, ext = splitext(fileToOpen)
if ext in ('.html', '') and exists(basename + currentExt):
self.p.openFileWrapper(basename + currentExt)
return basename + currentExt
if exists(fileToOpen) and get_markup_for_file_name(fileToOpen, return_class=True):
self.p.openFileWrapper(fileToOpen)
return fileToOpen
ReText-7.0.1/ReText/icontheme.py 0000644 0001750 0001750 00000003212 13047642057 017342 0 ustar dmitry dmitry 0000000 0000000 # This file is part of ReText
# Copyright: 2015-2016 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 import require_version
require_version('Gtk', '3.0')
from gi.repository import Gtk
except (ImportError, ValueError):
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-7.0.1/ReText/editor.py 0000644 0001750 0001750 00000034135 13123552555 016663 0 ustar dmitry dmitry 0000000 0000000 # vim: ts=8:sts=8:sw=8:noexpandtab
#
# This file is part of ReText
# Copyright: 2012-2017 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 os
import re
import weakref
from markups import MarkdownMarkup, ReStructuredTextMarkup, TextileMarkup
from ReText import globalSettings, tablemode, readFromSettings
from PyQt5.QtCore import pyqtSignal, QFileInfo, QRect, QSize, Qt
from PyQt5.QtGui import QColor, QImage, QKeyEvent, QMouseEvent, QPainter, \
QPalette, QTextCursor, QTextFormat, QWheelEvent
from PyQt5.QtWidgets import QFileDialog, QLabel, QTextEdit, QWidget
try:
from ReText.fakevimeditor import ReTextFakeVimHandler
except ImportError:
ReTextFakeVimHandler = None
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):
resized = pyqtSignal(QRect)
scrollLimitReached = pyqtSignal(QWheelEvent)
def __init__(self, parent):
QTextEdit.__init__(self)
self.tab = weakref.proxy(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)
if globalSettings.useFakeVim:
self.installFakeVimHandler()
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 wheelEvent(self, event):
QTextEdit.wheelEvent(self, event)
if event.angleDelta().y() < 0:
scrollBarLimit = self.verticalScrollBar().maximum()
else:
scrollBarLimit = self.verticalScrollBar().minimum()
if self.verticalScrollBar().value() == scrollBarLimit:
self.scrollLimitReached.emit(event)
def scrollContentsBy(self, dx, dy):
QTextEdit.scrollContentsBy(self, dx, dy)
self.lineNumberArea.update()
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 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:
markupClass = self.tab.getActiveMarkupClass()
if event.modifiers() & Qt.ControlModifier:
cursor.insertText('\n')
self.ensureCursorVisible()
elif self.tableModeEnabled and tablemode.handleReturn(cursor, markupClass,
newRow=(event.modifiers() & Qt.ShiftModifier)):
self.setTextCursor(cursor)
self.ensureCursorVisible()
else:
if event.modifiers() & Qt.ShiftModifier and markupClass == MarkdownMarkup:
# Insert Markdown-style line break
cursor.insertText(' ')
self.handleReturn(cursor)
else:
if event.text() and self.tableModeEnabled:
cursor.beginEditBlock()
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
if pos == length:
cursor.removeSelectedText()
# Reset the cursor
cursor = self.textCursor()
cursor.insertText(('\n' + text[:pos]) if pos < length else '\n')
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.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0)
def resizeEvent(self, event):
QTextEdit.resizeEvent(self, event)
rect = self.contentsRect()
self.resized.emit(rect)
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.getActiveMarkupClass()
cursorPosition = self.backupCursorPositionOnLine()
tablemode.adjustTableToChanges(self.document(), pos, added - removed, markupClass)
self.restoreCursorPositionOnLine(cursorPosition)
self.lineNumberArea.update()
def canInsertFromMimeData(self, mimeData):
return mimeData.hasText() or mimeData.hasImage()
def findNextImageName(self, filenames):
highestNumber = 0
for filename in filenames:
m = re.match(r'image(\d+).png', filename, re.IGNORECASE)
if m:
number = int(m.group(1))
highestNumber = max(number, highestNumber)
return 'image%04d.png' % (highestNumber + 1)
def getImageFilenameAndLink(self):
if self.tab.fileName:
saveDir = os.path.dirname(self.tab.fileName)
else:
saveDir = os.getcwd()
imageFileName = self.findNextImageName(os.listdir(saveDir))
chosenFileName = QFileDialog.getSaveFileName(self,
self.tr('Save image'),
os.path.join(saveDir, imageFileName),
self.tr('Images (*.png *.jpg)'))[0]
if chosenFileName:
# Use relative links for named documents
if self.tab.fileName:
link = os.path.relpath(chosenFileName, saveDir)
else:
link = chosenFileName
else:
link = None
return chosenFileName, link
def insertFromMimeData(self, mimeData):
if mimeData.hasImage():
fileName, link = self.getImageFilenameAndLink()
if fileName:
image = QImage(mimeData.imageData())
image.save(fileName)
markupClass = self.tab.getActiveMarkupClass()
if markupClass == MarkdownMarkup:
imageText = '' % (QFileInfo(link).baseName(), link)
elif markupClass == ReStructuredTextMarkup:
imageText = '.. image:: %s' % link
elif markupClass == TextileMarkup:
imageText = '!%s!' % link
self.textCursor().insertText(imageText)
else:
QTextEdit.insertFromMimeData(self, mimeData)
def installFakeVimHandler(self):
if ReTextFakeVimHandler:
fakeVimEditor = ReTextFakeVimHandler(self, self.parent)
fakeVimEditor.setSaveAction(self.parent.actionSave)
fakeVimEditor.setQuitAction(self.parent.actionQuit)
self.parent.actionFakeVimMode.triggered.connect(fakeVimEditor.remove)
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 not globalSettings.lineNumbersEnabled:
return QWidget.paintEvent(self, event)
painter = QPainter(self)
painter.fillRect(event.rect(), colorValues['lineNumberArea'])
cursor = QTextCursor(self.editor.document())
cursor.movePosition(QTextCursor.Start)
atEnd = False
while not atEnd:
rect = self.editor.cursorRect(cursor)
block = cursor.block()
if block.isVisible():
number = str(cursor.blockNumber() + 1)
painter.setPen(colorValues['lineNumberAreaText'])
painter.drawText(0, rect.top(), self.width() - 2,
self.fontMetrics().height(), Qt.AlignRight, number)
cursor.movePosition(QTextCursor.EndOfBlock)
atEnd = cursor.atEnd()
if not atEnd:
cursor.movePosition(QTextCursor.NextBlock)
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)
self.setCursor(Qt.IBeamCursor)
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)
def enterEvent(self, event):
palette = self.palette()
windowColor = QColor(colorValues['infoArea'])
windowColor.setAlpha(0x20)
palette.setColor(QPalette.Window, windowColor)
textColor = palette.color(QPalette.WindowText)
textColor.setAlpha(0x20)
palette.setColor(QPalette.WindowText, textColor)
self.setPalette(palette)
def leaveEvent(self, event):
palette = self.palette()
palette.setColor(QPalette.Window, colorValues['infoArea'])
palette.setColor(QPalette.WindowText,
self.editor.palette().color(QPalette.WindowText))
self.setPalette(palette)
def mousePressEvent(self, event):
pos = self.mapToParent(event.pos())
pos.setX(pos.x() - self.editor.lineNumberAreaWidth())
newEvent = QMouseEvent(event.type(), pos,
event.button(), event.buttons(),
event.modifiers())
self.editor.mousePressEvent(newEvent)
mouseReleaseEvent = mousePressEvent
mouseDoubleClickEvent = mousePressEvent
mouseMoveEvent = mousePressEvent
ReText-7.0.1/data/ 0000755 0001750 0001750 00000000000 13123552576 014516 5 ustar dmitry dmitry 0000000 0000000 ReText-7.0.1/data/me.mitya57.ReText.desktop 0000644 0001750 0001750 00000003500 13055264264 021216 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[nl]=Eenvoudige teksteditor voor Markdown en 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/markdown;text/x-rst;
Keywords=Text;Editor;Markdown;reStructuredText;
ReText-7.0.1/data/me.mitya57.ReText.appdata.xml 0000644 0001750 0001750 00000006036 13047421540 021756 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 編輯器
ReText is a text editor for plain text markup languages, such as Markdown and reStructuredText.
It supports tabs, live text preview, synchronized scrolling (for Markdown) and syntax highlighting.
ReText can export to HTML, ODT and PDF formats. It is also possible to write custom export extensions.
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-7.0.1/LICENSE_GPL 0000644 0001750 0001750 00000105755 12722556646 015337 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-7.0.1/configuration.md 0000644 0001750 0001750 00000013641 13123552555 017000 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)
`openLastFilesOnStartup` | boolean | whether to automatically open last documents on startup (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
`detectEncoding` | boolean | whether to automatically detect files encoding; needs chardet package (default: true)
`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
`syncScroll` | boolean | whether to enable synchronized scrolling for Markdown (default: true)
`tabBarAutoHide` | boolean | whether to hide the tabs bar when only one tab is open (default: false)
`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)
`useWebEngine` | boolean | whether to use the WebEngine (Chromium) as HTML previewer (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`, `lastFileList`, `lastTabIndex` 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
`codeSpans` | code spans, i.e. `` `code` `` in Markdown
`restDirectives` | reStructuredText directives, i.e. `.. math::`
`restRoles` | reStructuredText roles, i.e. `:math:`
`whitespaceOnEnd` | whitespace at line endings
ReText-7.0.1/PKG-INFO 0000644 0001750 0001750 00000002262 13123552576 014704 0 ustar dmitry dmitry 0000000 0000000 Metadata-Version: 1.1
Name: ReText
Version: 7.0.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(>=2.0)
Requires: pyenchant
Requires: Pygments
Requires: PyQt5
ReText-7.0.1/locale/ 0000755 0001750 0001750 00000000000 13123552576 015044 5 ustar dmitry dmitry 0000000 0000000 ReText-7.0.1/locale/retext_ca.qm 0000644 0001750 0001750 00000014422 13123552566 017363 0 ustar dmitry dmitry 0000000 0000000