File: __init__.py

package info (click to toggle)
retext 8.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,780 kB
  • sloc: python: 5,363; xml: 149; makefile: 20; sh: 8
file content (198 lines) | stat: -rw-r--r-- 6,386 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# vim: ts=4:sw=4:expandtab

# This file is part of ReText
# Copyright: 2012-2025 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 <http://www.gnu.org/licenses/>.

from os.path import abspath, dirname, expanduser, join

import markups
import markups.common
from PyQt6.QtCore import QByteArray, QLocale, QSettings
from PyQt6.QtGui import QFont, QFontDatabase

app_version = "8.1.0"

settings = QSettings('ReText project', 'ReText')

if not str(settings.fileName()).endswith('.conf'):
    # We are on Windows probably
    settings = QSettings(QSettings.Format.IniFormat, QSettings.Scope.UserScope,
        'ReText project', 'ReText')

cache = QSettings('ReText project', 'cache')

if not str(cache.fileName()).endswith('.conf'):
    # We are on Windows probably
    cache = QSettings(QSettings.Format.IniFormat, QSettings.Scope.UserScope,
        'ReText project', 'cache')


packageDir = abspath(dirname(__file__))

def getBundledIcon(iconName):
    return join(packageDir, 'icons', iconName + '.png')


configOptions = {
    'appStyleSheet': '',
    'autoSave': False,
    'defaultCodec': '',
    'defaultMarkup': markups.MarkdownMarkup.name,
    'defaultPreviewState': 'editor',
    'detectEncoding': True,
    'directoryPath': expanduser("~"),
    'documentStatsEnabled': False,
    'editorFont': '',
    'font': '',
    'handleWebLinks': False,
    'hideToolBar': False,
    'highlightCurrentLine': 'disabled',
    'iconTheme': '',
    'lineNumbersEnabled': False,
    'markdownDefaultFileExtension': '.mkd',
    'openFilesInExistingWindow': True,
    'openLastFilesOnStartup': False,
    'orderedListMode': 'increment',
    'paperSize': '',
    'pygmentsStyle': 'default',
    'recentDocumentsCount': 10,
    'relativeLineNumbers': False,
    'restDefaultFileExtension': '.rst',
    'rightMargin': 0,
    'rightMarginWrap': False,
    'saveWindowGeometry': False,
    'showDirectoryTree': False,
    'spellCheck': False,
    'spellCheckLocale': '',
    'styleSheet': '',
    'syncScroll': True,
    'tabBarAutoHide': False,
    'tabInsertsSpaces': True,
    'tabWidth': 4,
    'uiLanguage': QLocale.system().name(),
    'useFakeVim': False,
    'useWebEngine': False,
    'wideCursor': False,
    'windowTitleFullPath': False,
}

cacheOptions = {
    'lastFileList': [],
    'lastTabIndex': 0,
    'recentFileList': [],
    'splitterState': QByteArray(),
    'webEngineZoomFactor': 1.0,
    'windowGeometry': QByteArray(),
}

def readFromSettings(key, keytype, settings, default=None):
    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):
    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):
    if value == default:
        settings.remove(key)
    else:
        settings.setValue(key, value)

def writeListToSettings(key, value, settings):
    if len(value) > 1:
        settings.setValue(key, value)
    elif len(value) == 1:
        settings.setValue(key, value[0])
    else:
        settings.remove(key)

def getSettingsFilePath():
    return settings.fileName()


class ReTextSettings:

    def __init__(self, settings, defaults):
        # We have to do this to go around the custom __setattr__ method
        object.__setattr__(self, "settings", settings)
        object.__setattr__(self, "defaults", defaults)
        for option in defaults:
            default = defaults[option]
            if isinstance(default, list):
                object.__setattr__(self, option, readListFromSettings(
                    option, settings=settings))
            else:
                object.__setattr__(self, option, readFromSettings(
                    option, type(default), default=default, settings=settings))

    def __setattr__(self, option, value):
        if option not in self.defaults:
            raise AttributeError('Unknown attribute')
        default = self.defaults[option]
        if isinstance(default, list):
            object.__setattr__(self, option, value.copy())
            writeListToSettings(option, value, settings=self.settings)
        else:
            object.__setattr__(self, option, value)
            writeToSettings(option, value, default=default, settings=self.settings)

    def getPreviewFont(self):
        font = QFont()
        if self.font:
            font.fromString(self.font)
        return font

    def getEditorFont(self):
        font = QFontDatabase.systemFont(QFontDatabase.SystemFont.FixedFont)
        if self.editorFont:
            font.fromString(self.editorFont)
        return font

def moveSettingsToCache():
    # Moves the non-editable config options to the cache file
    # This is here for backwards compatibility
    for option in cacheOptions:
        if not cache.contains(option):
            default = cacheOptions[option]
            if isinstance(default, list):
                value = readListFromSettings(option, settings)
                writeListToSettings(option, value, cache)
            else:
                value = readFromSettings(option, type(default), settings, default)
                writeToSettings(option, value, default, cache)
        settings.remove(option)

moveSettingsToCache()
globalSettings = ReTextSettings(settings, configOptions)
globalCache = ReTextSettings(cache, cacheOptions)

markups.common.PYGMENTS_STYLE = globalSettings.pygmentsStyle