Example #1
0
    def test_4(self):
        # dock remembers its Enabled/Disabled state
        ruby = self.createFile('source.rb', RUBY_SOURCE)
        txt = self.createFile('file.txt', "asdf")

        dock = self.findDock('&Navigator')

        core.workspace().setCurrentDocument(ruby)

        self.retryUntilPassed(200,
                              lambda: self.assertTrue(dock.isVisible()))

        self.keyClicks('N', Qt.AltModifier)
        self.keyClick(Qt.Key_Escape)
        self.assertFalse(dock.isVisible())
        self.assertFalse(core.config()['Navigator']['Enabled'])

        core.workspace().setCurrentDocument(txt)
        core.workspace().setCurrentDocument(ruby)
        self.assertFalse(dock.isVisible())

        self.keyClicks('N', Qt.AltModifier)
        self.assertTrue(dock.isVisible())
        self.assertTrue(core.config()['Navigator']['Enabled'])

        core.workspace().setCurrentDocument(txt)
        core.workspace().setCurrentDocument(ruby)
        self.assertTrue(dock.isVisible())
Example #2
0
    def _onShowIndentationTriggered(self, checked):
        for document in core.workspace().documents():
            document.qutepart.drawWhiteSpaceAnyIndentation = checked
        core.config()['Qutepart']['WhiteSpaceVisibility']['AnyIndentation'] = checked
        core.config().flush()

        core.actionManager().action('mView/aShowTrailingWhitespaces').setEnabled(not checked)
Example #3
0
    def __init__(self):
        # if config file is old, add own settings
        if not 'Python' in core.config()['Modes']:
            core.config()['Modes']['Python'] = {'Enabled': 'whenOpened',
                                                'InterpreterPath': 'python -i'}

        _AbstractReplPlugin.__init__(self)
Example #4
0
    def test_previewCheck2b(self):
        """Check for double builds.
        """
        self._doBasicSphinxConfig()
        webViewContent, logContent = self._doBasicSphinxTest('rst')
        # After the inital ``_clear`` then a build with text, we expect to
        # see two builds.
        self.assertEqual(self._dock()._sphinxConverter._SphinxInvocationCount, 2)

        # Inserting a character when auto-save is enabled can cause a double
        # build: the save made in preparation for the first build also invokes
        # the second build.
        qp = core.workspace().currentDocument().qutepart
        core.config()['Sphinx']['BuildOnSave'] = False
        with self._WaitForHtmlReady(timeout=10000, numEmittedExpected=1):
            qp.lines[0] += ' '
        self.assertEqual(self._dock()._sphinxConverter._SphinxInvocationCount, 3)

        # Inserting a space at the end of the line can cause a double build,
        # since the StripTrailingWhitespace option deletes the space, then
        # the auto-save and build code restores it.
        #
        # However, double builds still only produce a single ``loadFinished``
        # signal.
        core.config()["Qutepart"]["StripTrailingWhitespace"] = True
        qp = core.workspace().currentDocument().qutepart
        with self._WaitForHtmlReady(timeout=10000, numEmittedExpected=1):
            qp.appendPlainText('\nTesting...')
        self.assertEqual(self._dock()._sphinxConverter._SphinxInvocationCount, 4)
Example #5
0
    def _onJavaScriptEnabledCheckbox(self, enabled):
        """Checkbox clicked, save and apply settings
        """
        core.config()['Preview']['JavaScriptEnabled'] = enabled
        core.config().flush()

        self._applyJavaScriptEnabled(enabled)
Example #6
0
    def test_previewCheck23(self):
        """If the document is modified externally, then build on save will be
        automatically enabled. Calling scheduledocumentprocessing will not
        trigger a rebuild.
        """
        self._doBasicSphinxConfig()
        core.config()['Sphinx']['BuildOnSave'] = False
        core.config().flush()
        self.codeText = """****
head
****

"""
        self.masterText = """.. toctree::

   code.rst"""
        codeDoc = self.createFile('code.rst', self.testText)
        masterDoc = self.createFile('index.rst', self.testText)
        self._assertHtmlReady(lambda: core.workspace().setCurrentDocument(codeDoc), timeout=10000)
        # Modify this file externally.
        with open("code.rst", 'a') as f:
            f.write(".. mytag::")
        self._assertHtmlReady(lambda: core.workspace().setCurrentDocument(masterDoc), timeout=10000)
        core.workspace().setCurrentDocument(codeDoc)

        # Modify this file internally, then wait for the typing timer to expire.
        qp = core.workspace().currentDocument().qutepart
        self.assertEmits(lambda: qp.appendPlainText('xxx'),
                         self._dock()._typingTimer.timeout, timeoutMs=1000)
        # The typing timer invokes _scheduleDocumentProcessing. Make sure
        # it completes by waiting until all events are processed.
        base._processPendingEvents()
        # Make sure the file wasn't saved.
        self.assertTrue(qp.document().isModified())
Example #7
0
 def _onDockShown(self):
     """Dock has been shown by a user. Change Enabled option
     """
     if not core.config()['Navigator']['Enabled']:
         core.config()['Navigator']['Enabled'] = True
         core.config().flush()
         self._scheduleDocumentProcessing()
Example #8
0
 def _readSettings(self):
     """Read settings from core configuration file
     """
     if not "HelloWorld" in core.config():
         core.config()["HelloWorld"] = {}
         core.config()["HelloWorld"]["VeryImportantOption"] = "the correct value"
     self._dock.label.setText('Option value: %s' % core.config()["HelloWorld"]["VeryImportantOption"])
Example #9
0
 def _saveSettings(self):
     """Flush main configuration file.
     """
     try:
         core.config().flush()
     except UserWarning as ex:
         core.mainWindow().appendMessage(unicode(ex))
Example #10
0
    def _do_test(self, mode, autoDetect):
        def continueFunc(dialog):
            page = dialog._pageForItem["Editor/EOL"]
            
            if mode == r'\n':
                page.rbEolUnix.setChecked(True)
            elif mode == r'\r\n':
                page.rbEolWindows.setChecked(True)
            elif mode == r'\r':
                page.rbEolMac.setChecked(True)
            else:
                assert 0
            
            if page.cbAutoDetectEol.isChecked() != autoDetect:
                QTest.mouseClick(page.cbAutoDetectEol, Qt.LeftButton)
            
            self.assertEqual(not page.lReloadToReapply.isHidden(), autoDetect)
            
            QTest.keyClick(dialog, Qt.Key_Enter)
        
        self.openSettings(continueFunc)

        self.assertEqual(core.config()['Qutepart']['EOL']['Mode'], mode)
        self.assertEqual(core.config()['Qutepart']['EOL']['AutoDetect'], autoDetect)
        
        conv = {r'\n': '\n',
                r'\r\n': '\r\n',
                r'\r': '\r'}
        
        if not autoDetect:  # if autodetection is active - not applied
            self.assertEqual(core.workspace().currentDocument().qutepart.eol, conv[mode])
Example #11
0
    def _onShowAnyWhitespaceTriggered(self, checked):
        for document in core.workspace().documents():
            document.qutepart.drawAnyWhitespace = checked
        core.config()["Qutepart"]["WhiteSpaceVisibility"]["Any"] = checked
        core.config().flush()

        core.actionManager().action("mView/aShowIncorrectIndentation").setEnabled(not checked)
Example #12
0
 def onSphinxPath(self):
     """Set the Sphinx path to the current project path."""
     assert core.project().path()
     core.config()["Sphinx"]["ProjectPath"] = core.project().path()
     core.config().flush()
     if core.config()["Preview"]["Enabled"] and self._dock is not None:
         self._dock._scheduleDocumentProcessing()
Example #13
0
 def _onDockClosed(self):
     """Dock has been closed by a user. Change Enabled option
     """
     if core.config()['Navigator']['Enabled']:
         core.config()['Navigator']['Enabled'] = False
         core.config().flush()
         self._dock.setTags([])
Example #14
0
 def _writeSettings(self):
     """This method is never called.
     Just an example implementation
     """
     core.config()["HelloWorld"]["VeryImportantOption"] = "new value"
     # Don't forget to flush config!
     # if settings has been edited with main settings dialogue, it will be flushed automatically
     core.config().flush()
Example #15
0
 def _checkSettings(self):
     """Check if settings are present in the core configuration file,
     else create them.
     """
     if "PluginManager" not in core.config():
         core.config()["PluginManager"] = {}
     if "Plugins" not in core.config()["PluginManager"]:
         core.config()["PluginManager"]["Plugins"] = {}
Example #16
0
 def setSortMode(self, mode ):
     """Set current sort mode, resort documents"""
     if  self._sortMode != mode :
         self._sortMode = mode
         if mode != self.Custom:
             core.config().reload()
             core.config()["Workspace"]["FileSortMode"] = mode
             core.config().flush()
         self.sortDocuments()
Example #17
0
    def del_(self):
        """Uninstall the plugin
        """
        curPath = self.dock.currentPath()
        if curPath is not None:
            core.config()['FileBrowser']['LastPath'] = curPath
            core.config().flush()

        self.dock.del_()
Example #18
0
 def _togglePluginInConfig(self, name, state):
     """String Bool -> Bool
     Consumes a name of a plugin and a state, sets the setting to state.
     If no setting is available for the plugin, it gets created.
     Returns the setting (Bool)
     """
     if name not in core.config()["PluginManager"]["Plugins"]:
         core.config()["PluginManager"]["Plugins"][name] = {}
     core.config()["PluginManager"]["Plugins"][name]["Enabled"] = state
     return core.config()["PluginManager"]["Plugins"][name]["Enabled"]
Example #19
0
 def test_previewCheck25(self, _getmtime):
     """Check exception handling in date comparison code."""
     # Make getmtime fail.
     _getmtime.side_effect = OSError()
     # First, run Sphinx and generate some output.
     self._doBasicSphinxConfig()
     core.config()['Sphinx']['BuildOnSave'] = False
     core.config().flush()
     self.testText = 'Testing'
     webViewContent, logContent = self._doBasicSphinxTest('rst')
     self.assertIn('modification', webViewContent)
Example #20
0
 def iterLanguages(self):
     """Get list of available languages as tuple (name, file name globs, first line globs, icon path)
     """
     languageNames = sorted(core.config()["Associations"].iterkeys())
     for languageName in languageNames:
         params = core.config()["Associations"][languageName]
         QTreeWidgetItem([languageName])
         iconPath = ":/enkiicons/languages/%s.png" % languageName.lower()
         if not QFileInfo(iconPath).exists():
             iconPath = ":/enkiicons/transparent.png"
         yield (languageName, params["FileName"], params["FirstLine"], iconPath)
Example #21
0
def sphinxEnabledForFile(filePath):
    """Based on Sphinx settings under core.config()['Sphinx'], this function
    determines whether Sphinx can be applied to filePath. It can't know if
    Sphinx actually processes the file or not, since this is based on conf.py
    settings.
    """
    sphinxProjectPath = core.config()['Sphinx']['ProjectPath']
    return (filePath and
            core.config()['Sphinx']['Enabled'] and
            os.path.exists(core.config()['Sphinx']['ProjectPath']) and
            os.path.normcase(sphinxProjectPath) ==
            commonPrefix(filePath, sphinxProjectPath))
Example #22
0
def shouldPluginLoad(name):
    """String Dict -> Bool
    Consumes a name of a plugin and the enki configuration and
    checks in the settings if it should be loaded.
    If no setting is available for the plugin, it gets created.
    Returns the setting (Bool)
    """
    if name not in core.config()["PluginManager"]["Plugins"]:
        core.config()["PluginManager"]["Plugins"][name] = {}
    if "Enabled" not in core.config()["PluginManager"]["Plugins"][name]:
        core.config()["PluginManager"]["Plugins"][name]["Enabled"] = False
    return core.config()["PluginManager"]["Plugins"][name]["Enabled"]
Example #23
0
    def _onCurrentTemplateChanged(self):
        """Update text or show message to the user"""
        if self._getCurrentTemplatePath() == self._CUSTOM_TEMPLATE_PATH:
            QMessageBox.information(core.mainWindow(),
                                   'Custom templaes help',
                                   '<html>See <a href="https://github.com/hlamer/enki/wiki/Markdown-preview-templates">'
                                   'this</a> wiki page for information about custom templates')
            self._restorePreviousTemplate()

        core.config()['Preview']['Template'] = self._widget.cbTemplate.currentText()
        core.config().flush()
        self._scheduleDocumentProcessing()
Example #24
0
    def test_4(self):
        """ Settings are applied """
        doc = self.createFile('test.py', 'asdf\n\n')
        self.waitUntilPassed(2000, lambda: self.assertEqual(doc.qutepart.lintMarks,
                                                            {0: ('e', "F821 undefined name 'asdf'"),
                                                             1: ('w', 'W391 blank line at end of file')}))

        core.config().set('Lint/Python/IgnoredMessages', 'F821 W391')
        doc.qutepart.text += ' '
        doc.saveFile()

        self.waitUntilPassed(2000, lambda: self.assertEqual(doc.qutepart.lintMarks,
                                                            {1: ('w', 'W293 blank line contains whitespace')}))
Example #25
0
    def _onSettingsDialogAboutToExecute(self, dialog):
        """UI settings dialogue is about to execute.
        Add own options
        """
        from mitscheme import MitSchemeSettings
        widget = MitSchemeSettings(dialog)
        dialog.appendPage(u"Modes/MIT Scheme", widget, QIcon(':/enkiicons/languages/scheme.png'))

        # Options
        dialog.appendOption(ChoiseOption(dialog, core.config(), "Modes/Scheme/Enabled",
                                       {widget.rbWhenOpened: "whenOpened",
                                        widget.rbNever: "never",
                                        widget.rbAlways: "always"}))
        dialog.appendOption(TextOption(dialog, core.config(), "Modes/Scheme/InterpreterPath", widget.leInterpreterPath))
Example #26
0
    def _onSettingsDialogAboutToExecute(self, dialog):
        """UI settings dialogue is about to execute.
        Add own options
        """
        widget = SettingsWidget(dialog)

        dialog.appendPage("Navigator", widget, QIcon(':/enkiicons/goto.png'))

        # Options
        dialog.appendOption(TextOption(dialog, core.config(),
                                       "Navigator/CtagsPath", widget.leCtagsPath))
        dialog.appendOption(CheckableOption(dialog, core.config(),
                                            "Navigator/SortAlphabetically",
                                            widget.cbSortTagsAlphabetically))
Example #27
0
    def test_previewCheck3a(self):
        """Basic Sphinx with CodeChat test. Output directory is a absolute
        directory.
        """
        core.config()['CodeChat']['Enabled'] = True
        self._doBasicSphinxConfig()
        core.config()['Sphinx']['OutputPath'] = os.path.join(self.TEST_FILE_DIR, '_build', 'html')

        self.testText = """# ****
# head
# ****
#
# content"""
        webViewContent, logContent = self._doBasicSphinxTest('py')
        self.assertTrue('<p>content</p>' in webViewContent)
Example #28
0
    def __init__(self):
        """Create and install the plugin
        """
        QObject.__init__(self)
        
        if not 'Preview' in core.config():  # migration from old configs versions
            core.config()['Preview'] = {'Enabled': True,
                                        'JavaScriptEnabled' : True}

        self._dock = None
        self._saveAction = None
        self._dockInstalled = False
        core.workspace().currentDocumentChanged.connect(self._onDocumentChanged)
        core.workspace().languageChanged.connect(self._onDocumentChanged)
        core.mainWindow().stateRestored.connect(self._onMainWindowStateRestored)
Example #29
0
    def __init__(self):
        """Create and install the plugin
        """
        QObject.__init__(self)

        self._dock = None
        self._saveAction = None
        self._dockInstalled = False
        core.workspace().currentDocumentChanged.connect(self._onDocumentChanged)
        core.workspace().languageChanged.connect(self._onDocumentChanged)

        # Install our CodeChat page into the settings dialog.
        core.uiSettingsManager().aboutToExecute.connect(self._onSettingsDialogAboutToExecute)
        # Update preview dock when the settings dialog (which contains the
        # CodeChat enable checkbox) is changed.
        core.uiSettingsManager().dialogAccepted.connect(self._onDocumentChanged)

        # Provide a "Set Sphinx Path" menu item.
        core.uiSettingsManager().dialogAccepted.connect(self._setSphinxActionVisibility)
        self._sphinxAction = QAction('Set Sphinx path', self._dock)
        self._sphinxAction.setShortcut(QKeySequence('Alt+Shift+S'))
        core.actionManager().addAction('mTools/aSetSphinxPath',
                                       self._sphinxAction)
        self._sphinxAction.triggered.connect(self.onSphinxPath)
        # Only enable this command if the File browser has a valid path.
        self.onFileBrowserPathChanged()
        core.project().changed.connect(self.onFileBrowserPathChanged)

        # If user's config .json file lacks it, populate CodeChat's default
        # config keys and Sphinx's default config keys.
        c = core.config()
        c.setdefault('CodeChat', {})
        c.setdefault('CodeChat/Enabled', False)
        c.setdefault('Sphinx', {})
        c.setdefault('Sphinx/Enabled', False)
        c.setdefault('Sphinx/Executable', 'sphinx-build')
        c.setdefault('Sphinx/ProjectPath', '')
        c.setdefault('Sphinx/SourcePath', '.')
        c.setdefault('Sphinx/BuildOnSave', False)
        c.setdefault('Sphinx/OutputPath', os.path.join('_build',
                            'html'))
        c.setdefault('Sphinx/AdvancedMode', False)
        c.setdefault('Sphinx/Cmdline', ('sphinx-build -d ' +
             os.path.join('_build', 'doctrees') + ' . ' +
             os.path.join('_build', 'html')))
        core.config().flush()

        self._setSphinxActionVisibility()
Example #30
0
File: document.py Project: vi/enki
    def _applyQpartSettings(self):
        """Apply qutepart settings
        """
        conf = core.config()['Qutepart']
        self.qutepart.setFont(QFont(conf['Font']['Family'], conf['Font']['Size']))

        self.qutepart.indentUseTabs = conf['Indentation']['UseTabs']
        self.qutepart.indentWidth = conf['Indentation']['Width']

        if conf['Edge']['Enabled']:
            self.qutepart.lineLengthEdge = conf['Edge']['Column']
        else:
            self.qutepart.lineLengthEdge = None
        self.qutepart.lineLengthEdgeColor = QColor(conf['Edge']['Color'])

        self.qutepart.completionEnabled = conf['AutoCompletion']['Enabled']
        self.qutepart.completionThreshold = conf['AutoCompletion']['Threshold']

        self.qutepart.setLineWrapMode(QPlainTextEdit.WidgetWidth if conf['Wrap']['Enabled'] else QPlainTextEdit.NoWrap)
        if conf['Wrap']['Mode'] == 'WrapAtWord':
            self.qutepart.setWordWrapMode(QTextOption.WrapAtWordBoundaryOrAnywhere)
        elif conf['Wrap']['Mode'] == 'WrapAnywhere':
            self.qutepart.setWordWrapMode(QTextOption.WrapAnywhere)
        else:
            assert 'Invalid wrap mode', conf['Wrap']['Mode']

        # EOL is managed by _configureEolMode(). But, if autodetect is disabled, we may apply new value here
        if not conf['EOL']['AutoDetect']:
            self.qutepart.eol = self._EOL_CONVERTOR[conf['EOL']['Mode']]
Example #31
0
 def test_previewCheck17(self):
     """A complex test case that tests both the log parser regexp and
     the progress bar color when both warnings and errors are present.
     """
     core.config()['CodeChat']['Enabled'] = True
     self.testText = u'# .. ERROR::\n# `WARNING_'
     self._doBasicTest('py')
     ps = self._widget().prgStatus
     self.assertIn('red', ps.styleSheet())
     self.assertIn('Error(s): 2, warning(s): 2', ps.text())
Example #32
0
 def test_previewCheck10(self):
     """Empty input should generate an empty log.
     """
     core.config()['CodeChat']['Enabled'] = True
     self.testText = u''
     self._doBasicTest('py')
     self.assertEqual(self._logText(), '')
     # do the same test for restructuredText
     self._doBasicTest('rst')
     self.assertEqual(self._logText(), '')
Example #33
0
 def test_previewCheck11(self):
     """Unicode should display correctly in log window too.
     """
     core.config()['CodeChat']['Enabled'] = True
     self.testText = u'# .. Енки::'
     self._doBasicTest('py')
     self.assertTrue(u'Енки' in self._logText())
     self.testText = u'.. Енки::'
     self._doBasicTest('rst')
     self.assertTrue(u'Енки' in self._logText())
Example #34
0
    def __init__(self, dialog):
        # Initialize the dialog, loading in the literate programming settings
        # GUI.
        QWidget.__init__(self, dialog)
        uic.loadUi(
            os.path.join(os.path.dirname(__file__), 'Sphinx_Settings.ui'),
            self)

        # Make links gray when they are disabled
        palette = self.palette()
        palette.setColor(QPalette.Disabled, QPalette.Link,
                         palette.color(QPalette.Disabled, QPalette.Text))
        self.lbSphinxReference.setPalette(palette)

        palette = self.palette()
        palette.setColor(QPalette.Active, QPalette.WindowText,
                         palette.color(QPalette.Normal, QPalette.Link))
        self.lbSphinxEnableAdvMode.setPalette(palette)

        # Clicking on advanced mode label triggers either advanced mode or
        # normal mode.
        self.lbSphinxEnableAdvMode.mousePressEvent = self.on_ToggleSphinxSettingModeClicked

        # Update misc pieces of the GUI that can't be stored in the .ui file.
        self._updateSphinxSettingMode()

        # Add this GUI to the settings dialog box.
        dialog.appendPage("Sphinx", self)
        # Next, have the setting UI auto-update the corresponding CodeChat and
        # config entries.
        dialog.appendOption(
            CheckableOption(dialog, core.config(), "Sphinx/Enabled",
                            self.gbSphinxProject))
        dialog.appendOption(
            ChoiseOption(dialog, core.config(), "Sphinx/BuildOnSave", {
                self.rbBuildOnlyOnSave: True,
                self.rbBuildOnFileChange: False
            }))
        dialog.appendOption(
            TextOption(dialog, core.config(), "Sphinx/ProjectPath",
                       self.leSphinxProjectPath))
        dialog.appendOption(
            TextOption(dialog, core.config(), "Sphinx/SourcePath",
                       self.leSphinxSourcePath))
        dialog.appendOption(
            TextOption(dialog, core.config(), "Sphinx/OutputPath",
                       self.leSphinxOutputPath))
        dialog.appendOption(
            TextOption(dialog, core.config(), "Sphinx/Executable",
                       self.leSphinxExecutable))
        dialog.appendOption(
            TextOption(dialog, core.config(), "Sphinx/Cmdline",
                       self.leSphinxCmdline))

        # Run this after the appendOption calls, since these fields must be set
        # up before _updateleValidateSphinxExecutable can run.
        self._updateleValidateSphinxExecutable()
Example #35
0
 def test_previewCheck8a(self):
     """Start with Sphinx disabled, make sure rst file will be rendered by
     docutils.core.publish_string. Then enable Sphinx, force document refresh
     by calling scheduleDucomentProcessing. Make sure now Sphinx kicks in.
     """
     self._doBasicSphinxConfig()
     core.config()['Sphinx']['Enabled'] = False
     self.testText = ''
     self._doBasicSphinxTest('rst')
     self.assertEqual(self._plainText(), '')
     self.assertEqual(self._logText(), '')
Example #36
0
    def test_previewCheck25(self):
        """If the file to be previewed is older than the source, an error
        should appear."""
        # First, run Sphinx and generate some output.
        self._doBasicSphinxConfig()
        core.config()['Sphinx']['BuildOnSave'] = False
        core.config().flush()
        self.testText = 'Testing'
        webEngineViewContent, logContent = self._doBasicSphinxTest('rst')
        self.assertTrue('Testing' in webEngineViewContent)

        # Now, exclude this from the build and re-run.
        conf = os.path.join(self.TEST_FILE_DIR, 'conf.py')
        with open(conf, 'a') as f:
            f.write('\n\nexclude_patterns = ["code.rst"]')
        # Run Sphinx again.
        qp = core.workspace().currentDocument().qutepart
        self._assertHtmlReady(lambda: qp.appendPlainText('xxx'), timeout=10000)
        webEngineViewContent, logContent = (self._html(), self._logText())
        self.assertIn('is older than the source file', webEngineViewContent)
Example #37
0
    def test_markdown_templates(self):
        core.config()['Preview']['Template'] = 'WhiteOnBlack'
        self._dock()._restorePreviousTemplate()
        self._assertHtmlReady(lambda: self.createFile('test.md', 'foo'), numEmittedExpected=2)
        combo = self._widget().cbTemplate
        self.assertEqual(combo.currentText(), 'WhiteOnBlack')
        self.assertNotIn('body {color: white; background: black;}', self._plainText())
        self.assertIn('body {color: white; background: black;}', self._html())

        self._assertHtmlReady(lambda: combo.setCurrentIndex(combo.findText('Default')),
                              numEmittedExpected=1)
        self.assertFalse('body {color: white; background: black;}' in self._plainText())
        self.assertFalse('body {color: white; background: black;}' in self._html())
        self.assertEqual(core.config()['Preview']['Template'], 'Default')

        self._assertHtmlReady(lambda: combo.setCurrentIndex(combo.findText('WhiteOnBlack')),
                              numEmittedExpected=1)
        self.assertEqual(combo.currentText(), 'WhiteOnBlack')
        self.assertFalse('body {color: white; background: black;}' in self._plainText())
        self.assertTrue('body {color: white; background: black;}' in self._html())
Example #38
0
    def _onSettingsDialogAboutToExecute(self, dialog):
        """UI settings dialogue is about to execute.
        Add own options
        """
        page = SettingsPage(dialog)
        dialog.appendPage("Hello World", page, QIcon(':/enkiicons/help.png'))

        # Options
        dialog.appendOption(
            TextOption(dialog, core.config(), "HelloWorld/VeryImportantOption",
                       page.edit))
Example #39
0
    def __init__(self):
        """Create and install the plugin
        """
        QObject.__init__(self)

        if not 'Preview' in core.config(
        ):  # migration from old configs versions
            core.config()['Preview'] = {
                'Enabled': True,
                'JavaScriptEnabled': True
            }

        self._dock = None
        self._saveAction = None
        self._dockInstalled = False
        core.workspace().currentDocumentChanged.connect(
            self._onDocumentChanged)
        core.workspace().languageChanged.connect(self._onDocumentChanged)
        core.mainWindow().stateRestored.connect(
            self._onMainWindowStateRestored)
Example #40
0
    def test_previewCheck21(self):
        """When user hit ok button in setting window, the project will get
        rebuild.
        """
        core.config()['CodeChat']['Enabled'] = True
        self._doBasicSphinxConfig()

        self.testText = """# ****
# head
# ****
#
# :doc:`missing.file`"""
        webEngineViewContent, logContent = self._doBasicSphinxTest('py')
        self.assertTrue('<span class="xref doc">missing.file</span>' in webEngineViewContent)
        self.assertTrue('unknown document: missing.file' in logContent)
        core.config()['Sphinx']['Enabled'] = False
        core.uiSettingsManager().dialogAccepted.emit()
        self._assertHtmlReady(lambda: None, timeout=10000,
                              numEmittedExpected=1)
        self.assertTrue('Unknown interpreted text role "doc"' in self._logText())
Example #41
0
    def test_previewCheck20a(self):
        core.config()['CodeChat']['Enabled'] = True
        self._doBasicSphinxConfig()

        self.testText = """# ****
# head
# ****
#
# content"""
        webEngineViewContent, logContent = self._doBasicSphinxTest('py')
        self.assertTrue(os.path.isfile(os.path.join(self.TEST_FILE_DIR, 'CodeChat.css')))
Example #42
0
 def test_previewCheck9(self):
     """Uninterpretable reStructuredText syntax in source code will generate
        errors and be displayed in the output log window."""
     core.config()['CodeChat']['Enabled'] = True
     self.testText = '# .. wrong::'
     self._doBasicTest('py')
     self.assertTrue("""Unknown directive type "wrong".""" in self._logText())
     # do the same test for restructuredText
     self.testText = '.. wrong::'
     self._doBasicTest('rst', numEmittedExpected=2)
     self.assertTrue("""Unknown directive type "wrong".""" in self._logText())
Example #43
0
    def _onSettingsDialogAboutToExecute(self, dialog):
        """UI settings dialogue is about to execute.
        Add own options
        """
        page = SettingsPage(dialog)
        dialog.appendPage(u"Autosave", page)

        # Options
        dialog.appendOption(
            CheckableOption(dialog, core.config(), "Autosave/Active",
                            page.checkbox))
Example #44
0
    def test_previewCheck2a(self):
        """Basic Sphinx test. Output directory is an absolute directory
        """
        self._doBasicSphinxConfig()
        core.config()['Sphinx']['OutputPath'] = os.path.join(self.TEST_FILE_DIR, '_build', 'html')
        self.testText = """****
head
****

content"""
        webEngineViewContent, logContent = self._doBasicSphinxTest('rst')
Example #45
0
    def test_markdown_templates_help(self):
        core.config()['Preview']['Template'] = 'WhiteOnBlack'
        document = self.createFile('test.md', 'foo')

        combo = self._widget().cbTemplate

        def inDialog(dialog):
            self.assertEqual(dialog.windowTitle(), 'Custom templaes help')
            dialog.accept()

        self.openDialog(lambda: combo.setCurrentIndex(combo.count() - 1), inDialog)
Example #46
0
 def _openTerm(self):
     """Handler for main menu action
     """
     term = core.config()["OpenTerm"]["defaultTerm"]
     cwd = path.dirname(core.workspace().currentDocument().filePath())
     try:
         subprocess.Popen(term, cwd=cwd)
     except:
         QMessageBox.information(
             core.mainWindow(), "OpenTerm error",
             "Enki was unable to open '{0}' terminal".format(term))
Example #47
0
    def _onSettingsDialogAboutToExecute(self, dialog):
        """UI settings dialogue is about to execute.
        Add own options
        """
        fontWidget = _SettingsPageWidget('Font.ui', dialog)
        indentWidget = _SettingsPageWidget('Indentation.ui', dialog)
        complWidget = _SettingsPageWidget('Autocompletion.ui', dialog)
        eolWidget = _SettingsPageWidget('Eol.ui', dialog)
        edgeWidget = _SettingsPageWidget('Edge.ui', dialog)
        wrapWidget = _SettingsPageWidget('Wrap.ui', dialog)

        dialog.appendPage(u"Editor/Font", fontWidget)
        dialog.appendPage(u"Editor/Indentation", indentWidget)
        dialog.appendPage(u"Editor/Autocompletion", complWidget)
        dialog.appendPage(u"Editor/EOL", eolWidget)
        dialog.appendPage(u"Editor/Edge", edgeWidget)
        dialog.appendPage(u"Editor/Wrap", wrapWidget)

        cfg = core.config()
        options = \
        (
            FontOption(dialog, cfg, "Qutepart/Font/Family", "Qutepart/Font/Size",
                       fontWidget.lFont, fontWidget.pbFont),

            ChoiseOption(dialog, cfg, "Qutepart/Indentation/UseTabs",
                         {indentWidget.rbIndentationSpaces : False,
                          indentWidget.rbIndentationTabs: True}),
            NumericOption(dialog, cfg, "Qutepart/Indentation/Width", indentWidget.sIndentationWidth),
            CheckableOption(dialog, cfg, "Qutepart/Indentation/AutoDetect", indentWidget.cbAutodetectIndent),

            ChoiseOption(dialog, cfg, "Qutepart/EOL/Mode",
                         {eolWidget.rbEolUnix: r'\n',
                          eolWidget.rbEolWindows: r'\r\n',
                          eolWidget.rbEolMac: r'\r'}),
            CheckableOption(dialog, cfg, "Qutepart/EOL/AutoDetect", eolWidget.cbAutoDetectEol),

            CheckableOption(dialog, cfg, "Qutepart/Edge/Enabled", edgeWidget.gbEdgeEnabled),
            NumericOption(dialog, cfg, "Qutepart/Edge/Column", edgeWidget.sEdgeColumnNumber),
            ColorOption(dialog, cfg, "Qutepart/Edge/Color", edgeWidget.tbEdgeColor),

            CheckableOption(dialog, cfg, "Qutepart/AutoCompletion/Enabled", complWidget.gbAutoCompletion),
            NumericOption(dialog, cfg, "Qutepart/AutoCompletion/Threshold", complWidget.sThreshold),

            CheckableOption(dialog, cfg, "Qutepart/Wrap/Enabled", wrapWidget.gbWrapEnabled),
            ChoiseOption(dialog, cfg, "Qutepart/Wrap/Mode",
                         {wrapWidget.rbWrapAtWord : "WrapAtWord",
                          wrapWidget.rbWrapAnywhere: "WrapAnywhere"}),
        )

        for option in options:
            dialog.appendOption(option)

        eolWidget.lReloadToReapply.setVisible(
            eolWidget.cbAutoDetectEol.isChecked())
Example #48
0
    def __init__(self, parent, *args):
        QToolBar.__init__(self, parent, *args)

        self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum))
        self._dock = parent

        closeIcon = self.style().standardIcon(QStyle.SP_DockWidgetCloseButton)
        if not closeIcon.availableSizes():
            # SP_DockWidgetCloseButton is missing on Fedora. Why??? Using fallback
            closeIcon = self.style().standardIcon(QStyle.SP_DialogCloseButton)

        self.aClose = QToolBar.addAction(self, closeIcon, "")

        self.setMovable(False)
        self.setFloatable(False)

        self.aClose.triggered.connect(self._dock.close)

        textHeight = QFontMetrics(self.font()).height()
        self.setIconSize(QSize(int(textHeight * 0.8), int(textHeight * 0.8)))

        # a fake spacer widget
        self._spacer = QWidget(self)
        self._spacer.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.MinimumExpanding))
        self.addWidget(self._spacer)

        self.setStyleSheet('QToolBar{spacing:0px; margin:0px}')

        # The pinned/unpinned control.
        self.tbUnPinned = QToolButton()
        icon = QIcon()
        # To do: Replace with my own image and put in resources.
        icon.addPixmap(QPixmap(os.path.join(os.path.dirname(__file__), 'unpinned.png')), QIcon.Normal, QIcon.On)
        icon.addPixmap(QPixmap(os.path.join(os.path.dirname(__file__), 'pinned.png')), QIcon.Normal, QIcon.Off)
        self.tbUnPinned.setIcon(icon)
        self.tbUnPinned.setCheckable(True)
        self._configName = parent.windowTitle() + " pinned"
        if self._configName in core.config():
            self.tbUnPinned.setChecked(not core.config()[self._configName])
        self.tbUnPinned.toggled.connect(self.on_tbUnPinned_toggled)
        self.addWidget(self.tbUnPinned)
Example #49
0
    def _convertSphinx(self, filePath):
        # Run the builder.
        errString = self._runHtmlBuilder()

        # Look for the HTML output.
        #
        # Get an absolute path to the output path, which could be relative.
        outputPath = core.config()['Sphinx']['OutputPath']
        projectPath = core.config()['Sphinx']['ProjectPath']
        if not os.path.isabs(outputPath):
            outputPath = os.path.join(projectPath, outputPath)
        # Create an htmlPath as OutputPath + remainder of filePath.
        htmlPath = os.path.join(outputPath + filePath[len(projectPath):])
        html_file_suffix = '.html'
        try:
            with codecs.open(os.path.join(projectPath, 'sphinx-enki-info.txt')) as f:
                hfs = f.read()
                # If the file is empty, then html_file_suffix wasn't defined
                # or is None. In this case, use the default extension.
                # Otherwise, use the extension read from the file.
                if hfs:
                    html_file_suffix = hfs
        except:
            errString = "Warning: assuming .html extension. Use " + \
                "the conf.py template to set the extension.\n" + errString
            pass
        # First place to look: file.html. For example, look for foo.py
        # in foo.py.html.
        htmlFile = htmlPath + html_file_suffix
        # Second place to look: file without extension.html. For
        # example, look for foo.html for foo.rst.
        htmlFileAlter = os.path.splitext(htmlPath)[0] + html_file_suffix
        # Check that the output file produced by Sphinx is newer than
        # the source file it was built from.
        if os.path.exists(htmlFile):
            return _checkModificationTime(filePath, htmlFile, errString)
        elif os.path.exists(htmlFileAlter):
            return _checkModificationTime(filePath, htmlFileAlter, errString)
        else:
            return ('No preview for this type of file.<br>Expected ' +
                    htmlFile + " or " + htmlFileAlter, errString, QUrl())
Example #50
0
    def _onSettingsDialogAboutToExecute(self, dialog):
        """UI settings dialogue is about to execute.
        Add own options
        """
        from .repl import SettingsWidget
        widget = SettingsWidget(dialog)

        dialog.appendPage("REPL/%s" % self._FULL_NAME, widget, self._icon())

        # Options
        dialog.appendOption(
            ChoiseOption(
                dialog, core.config(), "Modes/%s/Enabled" % self._LANGUAGE, {
                    widget.rbWhenOpened: "whenOpened",
                    widget.rbNever: "never",
                    widget.rbAlways: "always"
                }))
        dialog.appendOption(
            TextOption(dialog, core.config(),
                       "Modes/%s/InterpreterPath" % self._LANGUAGE,
                       widget.leInterpreterPath))
Example #51
0
 def _onSettingsDialogAboutToExecute(self, dialog):
     """UI settings dialogue is about to execute.
     Add own option
     """
     dialog.appendOption(
         ChoiseOption(
             dialog, core.config(), "Workspace/FileSortMode", {
                 dialog.rbOpeningOrder: "OpeningOrder",
                 dialog.rbFileName: "FileName",
                 dialog.rbUri: "URL",
                 dialog.rbSuffix: "Suffixes"
             }))
Example #52
0
    def test_1(self):
        # Ctags path are configurable
        def continueFunc(dialog):
            page = dialog._pageForItem["Navigator"]

            page.leCtagsPath.setText('new ctags path')

            QTest.keyClick(dialog, Qt.Key_Enter)

        self.openSettings(continueFunc)

        self.assertEqual(core.config()['Navigator']['CtagsPath'], 'new ctags path')
Example #53
0
    def _doTest(self, incorrect, anyIndent):
        incorrectAction = core.actionManager().action('mView/aShowIncorrectIndentation')
        anyIndentAction = core.actionManager().action('mView/aShowAnyWhitespaces')

        if anyIndentAction.isChecked() != anyIndent:
            anyIndentAction.trigger()

        if not anyIndent:
            if incorrectAction.isChecked() != incorrect:
                incorrectAction.trigger()

        self.assertEqual(core.config()['Qutepart']['WhiteSpaceVisibility']['Any'], anyIndent)
        self.assertEqual(core.workspace().currentDocument().qutepart.drawAnyWhitespace,
                         anyIndent)

        if not anyIndent:
            self.assertEqual(core.config()['Qutepart']['WhiteSpaceVisibility']['Incorrect'], incorrect)
            self.assertEqual(core.workspace().currentDocument().qutepart.drawIncorrectIndentation,
                             incorrect)

        self.assertEqual(incorrectAction.isEnabled(), not anyIndent)
Example #54
0
    def _doTest(self, enabled, atWord, lineWrapMode, wordWrapMode, wordWrapText):
        def continueFunc(dialog):
            page = dialog._pageForItem["Editor/Long Lines"]

            page.gbWrapEnabled.setChecked(enabled)
            if atWord:
                page.rbWrapAtWord.setChecked(True)
            else:
                page.rbWrapAnywhere.setChecked(True)

            QTest.keyClick(dialog, Qt.Key_Enter)

        self.openSettings(continueFunc)

        self.assertEqual(core.config()['Qutepart']['Wrap']['Enabled'], enabled)
        self.assertEqual(core.config()['Qutepart']['Wrap']['Mode'], wordWrapText)

        self.assertEqual(core.workspace().currentDocument().qutepart.lineWrapMode(),
                         lineWrapMode)
        self.assertEqual(core.workspace().currentDocument().qutepart.wordWrapMode(),
                         wordWrapMode)
Example #55
0
    def test_previewCheck5(self):
        """Basic Sphinx test: with Sphinx and codechat disabled, no preview
           window results are generated."""
        self._doBasicSphinxConfig()
        core.config()['Sphinx']['Enabled'] = False
        self.testText = """****
head
****

content"""
        self._doBasicSphinxTest('rst')
        self.assertNotIn('<h1>head', self._html())
Example #56
0
 def test_previewCheck8(self):
     """Start with a short code file, make sure the preview window isn't
        opened, then enable the CodeChat module and refresh Enki.
        The preview window should now be opened."""
     self.testText = 'test'
     self.createFile('file.py', self.testText)
     with self.assertRaisesRegex(AssertionError, 'Dock Previe&w not found'):
         self._dock()
     core.config()['CodeChat']['Enabled'] = True
     core.uiSettingsManager().dialogAccepted.emit()
     self._doBasicTest('py')
     assert 'test' in self._html()
Example #57
0
    def test_saveAndBuildWhitespace1(self):
        """See if whitespace is preserved on the current line
           when auto build and save is enabled."""
        # Get Sphinx auto-save-and-build plus strip trailing whitespace set up.
        self._doBasicSphinxConfig()
        core.config()['Sphinx']['BuildOnSave'] = False
        core.config()["Qutepart"]["StripTrailingWhitespace"] = True
        self.testText = "testing "
        webEngineViewContent, logContent = self._doBasicSphinxTest('rst')

        # Move to the end of the document and add a space on the next line,
        # which should be preserved through the auto-save. The space at the
        # end of the first line should be removed.
        qp = core.workspace().currentDocument().qutepart
        # The format is line, column. This goes to the next line ???
        qp.cursorPosition = 0, len(self.testText)
        with self._WaitForHtmlReady(timeout=5000, numEmittedExpected=1):
            qp.appendPlainText(' ')
            self.assertTrue(qp.document().isModified())
        self.assertEqual(qp.text, "testing\n ")
        self.assertFalse(qp.document().isModified())
Example #58
0
    def _configureEolMode(self, originalText):
        """Detect end of line mode automatically and apply detected mode
        """
        modes = set()
        for line in originalText.splitlines(True):
            if line.endswith('\r\n'):
                modes.add('\r\n')
            elif line.endswith('\n'):
                modes.add('\n')
            elif line.endswith('\r'):
                modes.add('\r')

        if len(modes) == 1:  # exactly one
            detectedMode = modes.pop()
        else:
            detectedMode = None

        default = self._EOL_CONVERTOR[core.config()["Qutepart"]["EOL"]["Mode"]]

        if len(modes) > 1:
            message = "%s contains mix of End Of Line symbols. It will be saved with '%s'" % \
                (self.filePath(), repr(default))
            core.mainWindow().appendMessage(message)
            self.qutepart.eol = default
            self.qutepart.document().setModified(True)
        elif core.config()["Qutepart"]["EOL"]["AutoDetect"]:
            if detectedMode is not None:
                self.qutepart.eol = detectedMode
            else:  # empty set, not detected
                self.qutepart.eol = default
        else:  # no mix, no autodetect. Force EOL
            if detectedMode is not None and \
                    detectedMode != default:
                message = "%s: End Of Line mode is '%s', but file will be saved with '%s'. " \
                          "EOL autodetection is disabled in the settings" % \
                    (self.fileName(), repr(detectedMode), repr(default))
                core.mainWindow().appendMessage(message)
                self.qutepart.document().setModified(True)

            self.qutepart.eol = default
Example #59
0
    def _scheduleDocumentProcessing(self):
        """Start document processing with the thread.
        """
        self._typingTimer.stop()

        document = core.workspace().currentDocument()
        if document is not None and \
           document.qutepart.language() in _QUTEPART_TO_CTAGS_LANG_MAP:
            ctagsLang = _QUTEPART_TO_CTAGS_LANG_MAP[
                document.qutepart.language()]
            self._thread.process(
                ctagsLang, document.qutepart.text,
                core.config()['Navigator']['SortAlphabetically'])
Example #60
0
    def test_previewCheck23(self):
        """If the document is modified externally, then build on save will be
        automatically enabled. Calling scheduledocumentprocessing will not
        trigger a rebuild.
        """
        self._doBasicSphinxConfig()
        core.config()['Sphinx']['BuildOnSave'] = False
        core.config().flush()
        self.codeText = """****
head
****

"""
        self.masterText = """.. toctree::

   code.rst"""
        codeDoc = self.createFile('code.rst', self.testText)
        masterDoc = self.createFile('index.rst', self.testText)
        self._assertHtmlReady(
            lambda: core.workspace().setCurrentDocument(codeDoc),
            timeout=10000)
        # Modify this file externally.
        with open("code.rst", 'a') as f:
            f.write(".. mytag::")
        self._assertHtmlReady(
            lambda: core.workspace().setCurrentDocument(masterDoc),
            timeout=10000)
        core.workspace().setCurrentDocument(codeDoc)

        # Modify this file internally, then wait for the typing timer to expire.
        qp = core.workspace().currentDocument().qutepart
        self.assertEmits(lambda: qp.appendPlainText('xxx'),
                         self._dock()._typingTimer.timeout,
                         timeoutMs=1000)
        # The typing timer invokes _scheduleDocumentProcessing. Make sure
        # it completes by waiting until all events are processed.
        base._processPendingEvents()
        # Make sure the file wasn't saved.
        self.assertTrue(qp.document().isModified())