Example #1
0
def get_font(section='main', option='font', font_size_delta=0):
    """Get console font properties depending on OS and user options"""
    font = FONT_CACHE.get((section, option))

    if font is None:
        families = CONF.get(section, option+"/family", None)

        if families is None:
            return QFont()

        family = get_family(families)
        weight = QFont.Normal
        italic = CONF.get(section, option+'/italic', False)

        if CONF.get(section, option+'/bold', False):
            weight = QFont.Bold

        size = CONF.get(section, option+'/size', 9) + font_size_delta
        font = QFont(family, size, weight)
        font.setItalic(italic)
        FONT_CACHE[(section, option)] = font

    size = CONF.get(section, option+'/size', 9) + font_size_delta
    font.setPointSize(size)
    return font
Example #2
0
def get_font(section='main', option='font', font_size_delta=0):
    """Get console font properties depending on OS and user options"""
    font = FONT_CACHE.get((section, option))

    if font is None:
        families = CONF.get(section, option+"/family", None)

        if families is None:
            return QFont()

        family = get_family(families)
        weight = QFont.Normal
        italic = CONF.get(section, option+'/italic', False)

        if CONF.get(section, option+'/bold', False):
            weight = QFont.Bold

        size = CONF.get(section, option+'/size', 9) + font_size_delta
        font = QFont(family, size, weight)
        font.setItalic(italic)
        FONT_CACHE[(section, option)] = font

    size = CONF.get(section, option+'/size', 9) + font_size_delta
    font.setPointSize(size)
    return font
Example #3
0
 def set_option(self, option, value):
     """
     Set a plugin option in configuration file
     Use a SIGNAL to call it, e.g.:
     plugin.sig_option_changed.emit('show_all', checked)
     """
     CONF.set(self.CONF_SECTION, str(option), value)
Example #4
0
    def long_banner(self):
        """Banner for IPython widgets with pylab message"""
        from IPython.core.usage import default_gui_banner
        banner = default_gui_banner
        
        pylab_o = CONF.get('ipython_console', 'pylab', True)
        autoload_pylab_o = CONF.get('ipython_console', 'pylab/autoload', True)
        mpl_installed = programs.is_module_installed('matplotlib')
        if mpl_installed and (pylab_o and autoload_pylab_o):
            pylab_message = ("\nPopulating the interactive namespace from "
                             "numpy and matplotlib")
            banner = banner + pylab_message
        
        sympy_o = CONF.get('ipython_console', 'symbolic_math', True)
        if sympy_o:
            lines = """
These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
"""
            banner = banner + lines
        return banner
Example #5
0
    def long_banner(self):
        """Banner for IPython widgets with pylab message"""
        from IPython.core.usage import default_gui_banner
        banner = default_gui_banner
        
        pylab_o = CONF.get('ipython_console', 'pylab', True)
        autoload_pylab_o = CONF.get('ipython_console', 'pylab/autoload', True)
        mpl_installed = programs.is_module_installed('matplotlib')
        if mpl_installed and (pylab_o and autoload_pylab_o):
            pylab_message = ("\nPopulating the interactive namespace from "
                             "numpy and matplotlib")
            banner = banner + pylab_message
        
        sympy_o = CONF.get('ipython_console', 'symbolic_math', True)
        if sympy_o:
            lines = """
These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
"""
            banner = banner + lines
        return banner
Example #6
0
 def set_option(self, option, value):
     """
     Set a plugin option in configuration file
     Use a SIGNAL to call it, e.g.:
     plugin.sig_option_changed.emit('show_all', checked)
     """
     CONF.set(self.CONF_SECTION, str(option), value)
Example #7
0
def _get_run_configurations():
    history_count = CONF.get("run", "history", 20)
    try:
        return [
            (filename, options) for filename, options in CONF.get("run", "configurations", []) if osp.isfile(filename)
        ][:history_count]
    except ValueError:
        CONF.set("run", "configurations", [])
        return []
Example #8
0
 def update_margins(self):
     layout = self.layout()
     if self.default_margins is None:
         self.default_margins = layout.getContentsMargins()
     if CONF.get('main', 'use_custom_margin'):
         margin = CONF.get('main', 'custom_margin')
         layout.setContentsMargins(*[margin] * 4)
     else:
         layout.setContentsMargins(*self.default_margins)
Example #9
0
def _get_run_configurations():
    history_count = CONF.get('run', 'history', 20)
    try:
        return [(filename, options)
                for filename, options in CONF.get('run', 'configurations', [])
                if osp.isfile(filename)][:history_count]
    except ValueError:
        CONF.set('run', 'configurations', [])
        return []
Example #10
0
 def update_margins(self):
     layout = self.layout()
     if self.default_margins is None:
         self.default_margins = layout.getContentsMargins()
     if CONF.get('main', 'use_custom_margin'):
         margin = CONF.get('main', 'custom_margin')
         layout.setContentsMargins(*[margin]*4)
     else:
         layout.setContentsMargins(*self.default_margins)
Example #11
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.main = parent

        # Widgets
        self.pages_widget = QStackedWidget()
        self.contents_widget = QListWidget()
        self.button_reset = QPushButton(_('Reset to defaults'))

        bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Apply |
                                QDialogButtonBox.Cancel)
        self.apply_btn = bbox.button(QDialogButtonBox.Apply)

        # Widgets setup
        # Destroying the C++ object right after closing the dialog box,
        # otherwise it may be garbage-collected in another QThread
        # (e.g. the editor's analysis thread in Spyder), thus leading to
        # a segmentation fault on UNIX or an application crash on Windows
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowTitle(_('Preferences'))
        self.setWindowIcon(ima.icon('configure'))
        self.contents_widget.setMovement(QListView.Static)
        self.contents_widget.setSpacing(1)
        self.contents_widget.setCurrentRow(0)

        # Layout
        hsplitter = QSplitter()
        hsplitter.addWidget(self.contents_widget)
        hsplitter.addWidget(self.pages_widget)

        btnlayout = QHBoxLayout()
        btnlayout.addWidget(self.button_reset)
        btnlayout.addStretch(1)
        btnlayout.addWidget(bbox)

        vlayout = QVBoxLayout()
        vlayout.addWidget(hsplitter)
        vlayout.addLayout(btnlayout)

        self.setLayout(vlayout)

        # Signals and slots
        self.button_reset.clicked.connect(self.main.reset_spyder)
        self.pages_widget.currentChanged.connect(self.current_page_changed)
        self.contents_widget.currentRowChanged.connect(
                                             self.pages_widget.setCurrentIndex)
        bbox.accepted.connect(self.accept)
        bbox.rejected.connect(self.reject)
        bbox.clicked.connect(self.button_clicked)

        # Ensures that the config is present on spyder first run
        CONF.set('main', 'interface_language', load_lang_conf())
Example #12
0
 def external_editor(self, filename, goto=-1):
     """Edit in an external editor
     Recommended: SciTE (e.g. to go to line where an error did occur)"""
     editor_path = CONF.get("internal_console", "external_editor/path")
     goto_option = CONF.get("internal_console", "external_editor/gotoline")
     try:
         if goto > 0 and goto_option:
             Popen(r'%s "%s" %s%d' % (editor_path, filename, goto_option, goto))
         else:
             Popen(r'%s "%s"' % (editor_path, filename))
     except OSError:
         self.write_error("External editor was not found:" " %s\n" % editor_path)
Example #13
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.main = parent

        # Widgets
        self.pages_widget = QStackedWidget()
        self.contents_widget = QListWidget()
        self.button_reset = QPushButton(_('Reset to defaults'))

        bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Apply
                                | QDialogButtonBox.Cancel)
        self.apply_btn = bbox.button(QDialogButtonBox.Apply)

        # Widgets setup
        # Destroying the C++ object right after closing the dialog box,
        # otherwise it may be garbage-collected in another QThread
        # (e.g. the editor's analysis thread in Spyder), thus leading to
        # a segmentation fault on UNIX or an application crash on Windows
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowTitle(_('Preferences'))
        self.setWindowIcon(ima.icon('configure'))
        self.contents_widget.setMovement(QListView.Static)
        self.contents_widget.setSpacing(1)
        self.contents_widget.setCurrentRow(0)

        # Layout
        hsplitter = QSplitter()
        hsplitter.addWidget(self.contents_widget)
        hsplitter.addWidget(self.pages_widget)

        btnlayout = QHBoxLayout()
        btnlayout.addWidget(self.button_reset)
        btnlayout.addStretch(1)
        btnlayout.addWidget(bbox)

        vlayout = QVBoxLayout()
        vlayout.addWidget(hsplitter)
        vlayout.addLayout(btnlayout)

        self.setLayout(vlayout)

        # Signals and slots
        self.button_reset.clicked.connect(self.main.reset_spyder)
        self.pages_widget.currentChanged.connect(self.current_page_changed)
        self.contents_widget.currentRowChanged.connect(
            self.pages_widget.setCurrentIndex)
        bbox.accepted.connect(self.accept)
        bbox.rejected.connect(self.reject)
        bbox.clicked.connect(self.button_clicked)

        # Ensures that the config is present on spyder first run
        CONF.set('main', 'interface_language', load_lang_conf())
Example #14
0
 def external_editor(self, filename, goto=-1):
     """Edit in an external editor
     Recommended: SciTE (e.g. to go to line where an error did occur)"""
     editor_path = CONF.get('internal_console', 'external_editor/path')
     goto_option = CONF.get('internal_console', 'external_editor/gotoline')
     try:
         args = [filename]
         if goto > 0 and goto_option:
             args.append('%s%d'.format(goto_option, goto))
         programs.run_program(editor_path, args)
     except OSError:
         self.write_error("External editor was not found:"
                          " %s\n" % editor_path)
Example #15
0
 def external_editor(self, filename, goto=-1):
     """Edit in an external editor
     Recommended: SciTE (e.g. to go to line where an error did occur)"""
     editor_path = CONF.get('internal_console', 'external_editor/path')
     goto_option = CONF.get('internal_console', 'external_editor/gotoline')
     try:
         args = [filename]
         if goto > 0 and goto_option:
             args.append('%s%d'.format(goto_option, goto))
         programs.run_program(editor_path, args)
     except OSError:
         self.write_error("External editor was not found:"
                          " %s\n" % editor_path)
Example #16
0
 def external_editor(self, filename, goto=-1):
     """Edit in an external editor
     Recommended: SciTE (e.g. to go to line where an error did occur)"""
     editor_path = CONF.get('internal_console', 'external_editor/path')
     goto_option = CONF.get('internal_console', 'external_editor/gotoline')
     try:
         if goto > 0 and goto_option:
             Popen(r'%s "%s" %s%d' %
                   (editor_path, filename, goto_option, goto))
         else:
             Popen(r'%s "%s"' % (editor_path, filename))
     except OSError:
         self.write_error("External editor was not found:"
                          " %s\n" % editor_path)
Example #17
0
def set_font(font, section='main', option='font'):
    """Set font"""
    CONF.set(section, option+'/family', to_text_string(font.family()))
    CONF.set(section, option+'/size', float(font.pointSize()))
    CONF.set(section, option+'/italic', int(font.italic()))
    CONF.set(section, option+'/bold', int(font.bold()))
    FONT_CACHE[(section, option)] = font
Example #18
0
def set_font(font, section='main', option='font'):
    """Set font"""
    CONF.set(section, option+'/family', to_text_string(font.family()))
    CONF.set(section, option+'/size', float(font.pointSize()))
    CONF.set(section, option+'/italic', int(font.italic()))
    CONF.set(section, option+'/bold', int(font.bold()))
    FONT_CACHE[(section, option)] = font
Example #19
0
    def __init__(self, main=None, **kwds):
        """Bind widget to a QMainWindow instance"""
        super(SpyderPluginMixin, self).__init__(**kwds)
        assert self.CONF_SECTION is not None
        self.main = main
        self.default_margins = None
        self.plugin_actions = None
        self.dockwidget = None
        self.mainwindow = None
        self.ismaximized = False
        self.isvisible = False

        # NOTE: Don't use the default option of CONF.get to assign a
        # None shortcut to plugins that don't have one. That will mess
        # the creation of our Keyboard Shortcuts prefs page
        try:
            self.shortcut = CONF.get('shortcuts', '_/switch to %s' % \
                                     self.CONF_SECTION)
        except configparser.NoOptionError:
            self.shortcut = None

        # We decided to create our own toggle action instead of using
        # the one that comes with dockwidget because it's not possible
        # to raise and focus the plugin with it.
        self.toggle_view_action = None
Example #20
0
def test():
    from spyderlib.utils.qthelpers import qapplication

    app = qapplication()

    from spyderlib.plugins.variableexplorer import VariableExplorer

    settings = VariableExplorer.get_settings()

    shell = ExternalPythonShell(
        pythonexecutable=sys.executable,
        interact=True,
        stand_alone=settings,
        wdir=osp.dirname(__file__),
        mpl_backend=0,
        light_background=False,
    )

    from spyderlib.qt.QtGui import QFont
    from spyderlib.config.main import CONF

    font = QFont(CONF.get("console", "font/family")[0])
    font.setPointSize(10)
    shell.shell.set_font(font)

    shell.shell.toggle_wrap_mode(True)
    shell.start_shell(False)
    shell.show()
    sys.exit(app.exec_())
Example #21
0
def send_args_to_spyder(args):
    """
    Simple socket client used to send the args passed to the Spyder 
    executable to an already running instance.

    Args can be Python scripts or files with these extensions: .spydata, .mat,
    .npy, or .h5, which can be imported by the Variable Explorer.
    """
    port = CONF.get('main', 'open_files_port')

    # Wait ~50 secs for the server to be up
    # Taken from http://stackoverflow.com/a/4766598/438386
    for _x in range(200):
        try:
            for arg in args:
                client = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                                       socket.IPPROTO_TCP)
                client.connect(("127.0.0.1", port))
                if is_unicode(arg):
                    arg = arg.encode('utf-8')
                client.send(osp.abspath(arg))
                client.close()
        except socket.error:
            time.sleep(0.25)
            continue
        break
Example #22
0
    def __init__(self, main=None, **kwds):
        """Bind widget to a QMainWindow instance"""
        super(SpyderPluginMixin, self).__init__(**kwds)
        assert self.CONF_SECTION is not None
        self.PLUGIN_PATH = os.path.dirname(inspect.getfile(self.__class__))
        self.main = main
        self.default_margins = None
        self.plugin_actions = None
        self.dockwidget = None
        self.mainwindow = None
        self.ismaximized = False
        self.isvisible = False

        # NOTE: Don't use the default option of CONF.get to assign a
        # None shortcut to plugins that don't have one. That will mess
        # the creation of our Keyboard Shortcuts prefs page
        try:
            self.shortcut = CONF.get('shortcuts', '_/switch to %s' % \
                                     self.CONF_SECTION)
        except configparser.NoOptionError:
            self.shortcut = None

        # We decided to create our own toggle action instead of using
        # the one that comes with dockwidget because it's not possible
        # to raise and focus the plugin with it.
        self.toggle_view_action = None 
Example #23
0
def send_args_to_spyder(args):
    """
    Simple socket client used to send the args passed to the Spyder 
    executable to an already running instance.

    Args can be Python scripts or files with these extensions: .spydata, .mat,
    .npy, or .h5, which can be imported by the Variable Explorer.
    """
    port = CONF.get('main', 'open_files_port')

    # Wait ~50 secs for the server to be up
    # Taken from http://stackoverflow.com/a/4766598/438386
    for _x in range(200):
        try:
            for arg in args:
                client = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                                       socket.IPPROTO_TCP)
                client.connect(("127.0.0.1", port))
                if is_unicode(arg):
                    arg = arg.encode('utf-8')
                client.send(osp.abspath(arg))
                client.close()
        except socket.error:
            time.sleep(0.25)
            continue
        break
Example #24
0
    def setup_page(self):
        settings_group = QGroupBox(_("Settings"))
        hist_spin = self.create_spinbox(
                            _("History depth: "), _(" entries"),
                            'max_entries', min_=10, max_=10000, step=10,
                            tip=_("Set maximum line count"))

        sourcecode_group = QGroupBox(_("Source code"))
        wrap_mode_box = self.create_checkbox(_("Wrap lines"), 'wrap')
        go_to_eof_box = self.create_checkbox(
                        _("Scroll automatically to last entry"), 'go_to_eof')
        font_group = self.create_fontgroup(option=None,
                                    text=_("Font style"),
                                    fontfilters=QFontComboBox.MonospacedFonts)
        names = CONF.get('color_schemes', 'names')
        choices = list(zip(names, names))
        cs_combo = self.create_combobox(_("Syntax color scheme: "),
                                        choices, 'color_scheme_name')

        settings_layout = QVBoxLayout()
        settings_layout.addWidget(hist_spin)
        settings_group.setLayout(settings_layout)

        sourcecode_layout = QVBoxLayout()
        sourcecode_layout.addWidget(wrap_mode_box)
        sourcecode_layout.addWidget(go_to_eof_box)
        sourcecode_layout.addWidget(cs_combo)
        sourcecode_group.setLayout(sourcecode_layout)
        
        vlayout = QVBoxLayout()
        vlayout.addWidget(font_group)
        vlayout.addWidget(settings_group)
        vlayout.addWidget(sourcecode_group)
        vlayout.addStretch(1)
        self.setLayout(vlayout)
Example #25
0
 def __init__(self, fname=None):
     self.args = None
     self.args_enabled = None
     self.wdir = None
     self.wdir_enabled = None
     self.current = None
     self.systerm = None
     self.interact = None
     self.show_kill_warning = None
     self.post_mortem = None
     self.python_args = None
     self.python_args_enabled = None
     self.set(CONF.get("run", "defaultconfiguration", default={}))
     if fname is not None and CONF.get("run", WDIR_USE_SCRIPT_DIR_OPTION, True):
         self.wdir = osp.dirname(fname)
         self.wdir_enabled = True
Example #26
0
    def __init__(self, parent, history_filename, profile=False):
        """
        parent : specifies the parent widget
        """
        ConsoleBaseWidget.__init__(self, parent)
        SaveHistoryMixin.__init__(self)

        # Prompt position: tuple (line, index)
        self.current_prompt_pos = None
        self.new_input_line = True

        # History
        self.histidx = None
        self.hist_wholeline = False
        assert is_text_string(history_filename)
        self.history_filename = history_filename
        self.history = self.load_history()

        # Session
        self.historylog_filename = CONF.get('main', 'historylog_filename',
                                            get_conf_path('history.log'))

        # Context menu
        self.menu = None
        self.setup_context_menu()

        # Simple profiling test
        self.profile = profile

        # Buffer to increase performance of write/flush operations
        self.__buffer = []
        self.__timestamp = 0.0
        self.__flushtimer = QTimer(self)
        self.__flushtimer.setSingleShot(True)
        self.__flushtimer.timeout.connect(self.flush)

        # Give focus to widget
        self.setFocus()

        # Completion
        completion_size = CONF.get('shell_appearance', 'completion/size')
        completion_font = get_font('console')
        self.completion_widget.setup_appearance(completion_size,
                                                completion_font)
        # Cursor width
        self.setCursorWidth(CONF.get('shell_appearance', 'cursor/width'))
Example #27
0
 def __init__(self, fname=None):
     self.args = None
     self.args_enabled = None
     self.wdir = None
     self.wdir_enabled = None
     self.current = None
     self.systerm = None
     self.interact = None
     self.show_kill_warning = None
     self.post_mortem = None
     self.python_args = None
     self.python_args_enabled = None
     self.set(CONF.get('run', 'defaultconfiguration', default={}))
     if fname is not None and\
        CONF.get('run', WDIR_USE_SCRIPT_DIR_OPTION, True):
         self.wdir = osp.dirname(fname)
         self.wdir_enabled = True
Example #28
0
 def set_default_color_scheme(self, name='Spyder'):
     """Set default color scheme (only once)"""
     color_scheme_name = self.get_option('color_scheme_name', None)
     if color_scheme_name is None:
         names = CONF.get("color_schemes", "names")
         if name not in names:
             name = names[0]
         self.set_option('color_scheme_name', name)
Example #29
0
 def set_default_color_scheme(self, name='Spyder'):
     """Set default color scheme (only once)"""
     color_scheme_name = self.get_option('color_scheme_name', None)
     if color_scheme_name is None:
         names = CONF.get("color_schemes", "names")
         if name not in names:
             name = names[0]
         self.set_option('color_scheme_name', name)
Example #30
0
    def __init__(self, parent, history_filename, profile=False):
        """
        parent : specifies the parent widget
        """
        ConsoleBaseWidget.__init__(self, parent)
        SaveHistoryMixin.__init__(self)
                
        # Prompt position: tuple (line, index)
        self.current_prompt_pos = None
        self.new_input_line = True
        
        # History
        self.histidx = None
        self.hist_wholeline = False
        assert is_text_string(history_filename)
        self.history_filename = history_filename
        self.history = self.load_history()
        
        # Session
        self.historylog_filename = CONF.get('main', 'historylog_filename',
                                            get_conf_path('history.log'))
        
        # Context menu
        self.menu = None
        self.setup_context_menu()

        # Simple profiling test
        self.profile = profile
        
        # Buffer to increase performance of write/flush operations
        self.__buffer = []
        self.__timestamp = 0.0
        self.__flushtimer = QTimer(self)
        self.__flushtimer.setSingleShot(True)
        self.__flushtimer.timeout.connect(self.flush)

        # Give focus to widget
        self.setFocus()
        
        # Completion
        completion_size = CONF.get('shell_appearance', 'completion/size')
        completion_font = get_font('console')
        self.completion_widget.setup_appearance(completion_size,
                                                completion_font)
        # Cursor width
        self.setCursorWidth( CONF.get('shell_appearance', 'cursor/width') )
Example #31
0
    def shellwidget_config(self):
        """
        Generate a Config instance for shell widgets using our config
        system
        
        This lets us create each widget with its own config (as opposed to
        IPythonQtConsoleApp, where all widgets have the same config)
        """
        # ---- IPython config ----
        try:
            profile_path = osp.join(get_ipython_dir(), 'profile_default')
            full_ip_cfg = load_pyconfig_files(['ipython_qtconsole_config.py'],
                                              profile_path)
            
            # From the full config we only select the IPythonWidget section
            # because the others have no effect here.
            ip_cfg = Config({'IPythonWidget': full_ip_cfg.IPythonWidget})
        except:
            ip_cfg = Config()
       
        # ---- Spyder config ----
        spy_cfg = Config()
        
        # Make the pager widget a rich one (i.e a QTextEdit)
        spy_cfg.IPythonWidget.kind = 'rich'
        
        # Gui completion widget
        completion_type_o = CONF.get('ipython_console', 'completion_type')
        completions = {0: "droplist", 1: "ncurses", 2: "plain"}
        spy_cfg.IPythonWidget.gui_completion = completions[completion_type_o]

        # Pager
        pager_o = self.get_option('use_pager')
        if pager_o:
            spy_cfg.IPythonWidget.paging = 'inside'
        else:
            spy_cfg.IPythonWidget.paging = 'none'
        
        # Calltips
        calltips_o = self.get_option('show_calltips')
        spy_cfg.IPythonWidget.enable_calltips = calltips_o

        # Buffer size
        buffer_size_o = self.get_option('buffer_size')
        spy_cfg.IPythonWidget.buffer_size = buffer_size_o
        
        # Prompts
        in_prompt_o = self.get_option('in_prompt')
        out_prompt_o = self.get_option('out_prompt')
        if in_prompt_o:
            spy_cfg.IPythonWidget.in_prompt = in_prompt_o
        if out_prompt_o:
            spy_cfg.IPythonWidget.out_prompt = out_prompt_o
        
        # Merge IPython and Spyder configs. Spyder prefs will have prevalence
        # over IPython ones
        ip_cfg._merge(spy_cfg)
        return ip_cfg
Example #32
0
    def shellwidget_config(self):
        """
        Generate a Config instance for shell widgets using our config
        system
        
        This lets us create each widget with its own config (as opposed to
        IPythonQtConsoleApp, where all widgets have the same config)
        """
        # ---- IPython config ----
        try:
            profile_path = osp.join(get_ipython_dir(), 'profile_default')
            full_ip_cfg = load_pyconfig_files(['ipython_qtconsole_config.py'],
                                              profile_path)
            
            # From the full config we only select the IPythonWidget section
            # because the others have no effect here.
            ip_cfg = Config({'IPythonWidget': full_ip_cfg.IPythonWidget})
        except:
            ip_cfg = Config()
       
        # ---- Spyder config ----
        spy_cfg = Config()
        
        # Make the pager widget a rich one (i.e a QTextEdit)
        spy_cfg.IPythonWidget.kind = 'rich'
        
        # Gui completion widget
        completion_type_o = CONF.get('ipython_console', 'completion_type')
        completions = {0: "droplist", 1: "ncurses", 2: "plain"}
        spy_cfg.IPythonWidget.gui_completion = completions[completion_type_o]

        # Pager
        pager_o = self.get_option('use_pager')
        if pager_o:
            spy_cfg.IPythonWidget.paging = 'inside'
        else:
            spy_cfg.IPythonWidget.paging = 'none'
        
        # Calltips
        calltips_o = self.get_option('show_calltips')
        spy_cfg.IPythonWidget.enable_calltips = calltips_o

        # Buffer size
        buffer_size_o = self.get_option('buffer_size')
        spy_cfg.IPythonWidget.buffer_size = buffer_size_o
        
        # Prompts
        in_prompt_o = self.get_option('in_prompt')
        out_prompt_o = self.get_option('out_prompt')
        if in_prompt_o:
            spy_cfg.IPythonWidget.in_prompt = in_prompt_o
        if out_prompt_o:
            spy_cfg.IPythonWidget.out_prompt = out_prompt_o
        
        # Merge IPython and Spyder configs. Spyder prefs will have prevalence
        # over IPython ones
        ip_cfg._merge(spy_cfg)
        return ip_cfg
Example #33
0
def set_font(font, section, option=None):
    """Set font"""
    if option is None:
        option = 'font'
    else:
        option += '/font'
    CONF.set(section, option + '/family', to_text_string(font.family()))
    CONF.set(section, option + '/size', float(font.pointSize()))
    CONF.set(section, option + '/italic', int(font.italic()))
    CONF.set(section, option + '/bold', int(font.bold()))
    FONT_CACHE[(section, option)] = font
Example #34
0
def set_font(font, section, option=None):
    """Set font"""
    if option is None:
        option = 'font'
    else:
        option += '/font'
    CONF.set(section, option+'/family', to_text_string(font.family()))
    CONF.set(section, option+'/size', float(font.pointSize()))
    CONF.set(section, option+'/italic', int(font.italic()))
    CONF.set(section, option+'/bold', int(font.bold()))
    FONT_CACHE[(section, option)] = font
Example #35
0
 def get_settings():
     """
     Return Variable Explorer settings dictionary
     (i.e. namespace browser settings according to Spyder's configuration file)
     """
     settings = {}
     #        CONF.load_from_ini() # necessary only when called from another process
     for name in REMOTE_SETTINGS:
         settings[name] = CONF.get(VariableExplorer.CONF_SECTION, name)
     return settings
Example #36
0
 def _banner_default(self):
     """
     Reimplement banner creation to let the user decide if he wants a
     banner or not
     """
     banner_o = CONF.get('ipython_console', 'show_banner', True)
     if banner_o:
         return self.long_banner()
     else:
         return self.short_banner()
Example #37
0
 def _banner_default(self):
     """
     Reimplement banner creation to let the user decide if he wants a
     banner or not
     """
     banner_o = CONF.get('ipython_console', 'show_banner', True)
     if banner_o:
         return self.long_banner()
     else:
         return self.short_banner()
Example #38
0
    def get_settings():
        """
        Return Variable Explorer settings dictionary
        (i.e. namespace browser settings according to Spyder's configuration file)
        """
        settings = {}
#        CONF.load_from_ini() # necessary only when called from another process
        for name in REMOTE_SETTINGS:
            settings[name] = CONF.get(VariableExplorer.CONF_SECTION, name)
        return settings
Example #39
0
    def __init__(self,
                 parent=None,
                 namespace=None,
                 commands=[],
                 message=None,
                 max_line_count=300,
                 font=None,
                 exitfunc=None,
                 profile=False,
                 multithreaded=True,
                 light_background=True):
        PythonShellWidget.__init__(self, parent,
                                   get_conf_path('history_internal.py'),
                                   profile)

        self.set_light_background(light_background)
        self.multithreaded = multithreaded
        self.setMaximumBlockCount(max_line_count)

        # For compatibility with ExtPythonShellWidget
        self.is_ipykernel = False

        if font is not None:
            self.set_font(font)

        # Allow raw_input support:
        self.input_loop = None
        self.input_mode = False

        # KeyboardInterrupt support
        self.interrupted = False  # used only for not-multithreaded mode
        self.sig_keyboard_interrupt.connect(self.keyboard_interrupt)

        # Code completion / calltips
        getcfg = lambda option: CONF.get('internal_console', option)
        case_sensitive = getcfg('codecompletion/case_sensitive')
        self.set_codecompletion_case(case_sensitive)

        # keyboard events management
        self.eventqueue = []

        # Init interpreter
        self.exitfunc = exitfunc
        self.commands = commands
        self.message = message
        self.interpreter = None
        self.start_interpreter(namespace)

        # Clear status bar
        self.status.emit('')

        # Embedded shell -- requires the monitor (which installs the
        # 'open_in_spyder' function in builtins)
        if hasattr(builtins, 'open_in_spyder'):
            self.go_to_error.connect(self.open_with_external_spyder)
Example #40
0
    def __init__(
        self,
        parent=None,
        namespace=None,
        commands=[],
        message=None,
        max_line_count=300,
        font=None,
        exitfunc=None,
        profile=False,
        multithreaded=True,
        light_background=True,
    ):
        PythonShellWidget.__init__(self, parent, get_conf_path("history_internal.py"), profile)

        self.set_light_background(light_background)
        self.multithreaded = multithreaded
        self.setMaximumBlockCount(max_line_count)

        # For compatibility with ExtPythonShellWidget
        self.is_ipykernel = False

        if font is not None:
            self.set_font(font)

        # Allow raw_input support:
        self.input_loop = None
        self.input_mode = False

        # KeyboardInterrupt support
        self.interrupted = False  # used only for not-multithreaded mode
        self.sig_keyboard_interrupt.connect(self.keyboard_interrupt)

        # Code completion / calltips
        getcfg = lambda option: CONF.get("internal_console", option)
        case_sensitive = getcfg("codecompletion/case_sensitive")
        self.set_codecompletion_case(case_sensitive)

        # keyboard events management
        self.eventqueue = []

        # Init interpreter
        self.exitfunc = exitfunc
        self.commands = commands
        self.message = message
        self.interpreter = None
        self.start_interpreter(namespace)

        # Clear status bar
        self.status.emit("")

        # Embedded shell -- requires the monitor (which installs the
        # 'open_in_spyder' function in builtins)
        if hasattr(builtins, "open_in_spyder"):
            self.go_to_error.connect(self.open_with_external_spyder)
Example #41
0
 def save_historylog(self):
     """Save current history log (all text in console)"""
     title = _("Save history log")
     self.redirect_stdio.emit(False)
     filename, _selfilter = getsavefilename(self, title,
                 self.historylog_filename, "%s (*.log)" % _("History logs"))
     self.redirect_stdio.emit(True)
     if filename:
         filename = osp.normpath(filename)
         try:
             encoding.write(to_text_string(self.get_text_with_eol()),
                            filename)
             self.historylog_filename = filename
             CONF.set('main', 'historylog_filename', filename)
         except EnvironmentError as error:
             QMessageBox.critical(self, title,
                                  _("<b>Unable to save file '%s'</b>"
                                    "<br><br>Error message:<br>%s"
                                    ) % (osp.basename(filename),
                                         to_text_string(error)))
Example #42
0
 def set_spyder_breakpoints(self):
     self.clear_all_breaks()
     #------Really deleting all breakpoints:
     for bp in bdb.Breakpoint.bpbynumber:
         if bp:
             bp.deleteMe()
     bdb.Breakpoint.next = 1
     bdb.Breakpoint.bplist = {}
     bdb.Breakpoint.bpbynumber = [None]
     #------
     from spyderlib.config.main import CONF
     CONF.load_from_ini()
     if CONF.get('run', 'breakpoints/enabled', True):
         breakpoints = CONF.get('run', 'breakpoints', {})
         i = 0
         for fname, data in list(breakpoints.items()):
             for linenumber, condition in data:
                 i += 1
                 self.set_break(self.canonic(fname), linenumber,
                                cond=condition)
Example #43
0
def icon(name, resample=False):
    theme =  CONF.get('main', 'icon_theme')
    if theme == 'spyder 3':
        if not _resource['loaded']:
            qta.load_font('spyder', 'spyder.ttf', 'spyder-charmap.json', directory=_resource['directory'])
            _resource['loaded'] = True
        args, kwargs = _qtaargs[name]
        return qta.icon(*args, **kwargs)
    elif theme == 'spyder 2':
        icon = get_icon(name + '.png', resample=resample)
        return icon if icon is not None else QIcon()
Example #44
0
 def save_historylog(self):
     """Save current history log (all text in console)"""
     title = _("Save history log")
     self.redirect_stdio.emit(False)
     filename, _selfilter = getsavefilename(self, title,
                 self.historylog_filename, "%s (*.log)" % _("History logs"))
     self.redirect_stdio.emit(True)
     if filename:
         filename = osp.normpath(filename)
         try:
             encoding.write(to_text_string(self.get_text_with_eol()),
                            filename)
             self.historylog_filename = filename
             CONF.set('main', 'historylog_filename', filename)
         except EnvironmentError as error:
             QMessageBox.critical(self, title,
                                  _("<b>Unable to save file '%s'</b>"
                                    "<br><br>Error message:<br>%s"
                                    ) % (osp.basename(filename),
                                         to_text_string(error)))
Example #45
0
 def set_spyder_breakpoints(self):
     self.clear_all_breaks()
     #------Really deleting all breakpoints:
     for bp in bdb.Breakpoint.bpbynumber:
         if bp:
             bp.deleteMe()
     bdb.Breakpoint.next = 1
     bdb.Breakpoint.bplist = {}
     bdb.Breakpoint.bpbynumber = [None]
     #------
     from spyderlib.config.main import CONF
     CONF.load_from_ini()
     if CONF.get('run', 'breakpoints/enabled', True):
         breakpoints = CONF.get('run', 'breakpoints', {})
         i = 0
         for fname, data in list(breakpoints.items()):
             for linenumber, condition in data:
                 i += 1
                 self.set_break(self.canonic(fname), linenumber,
                                cond=condition)
Example #46
0
def get_font(section, option=None):
    """Get console font properties depending on OS and user options"""
    font = FONT_CACHE.get((section, option))
    if font is None:
        if option is None:
            option = 'font'
        else:
            option += '/font'
        families = CONF.get(section, option+"/family", None)
        if families is None:
            return QFont()
        family = get_family(families)
        weight = QFont.Normal
        italic = CONF.get(section, option+'/italic', False)
        if CONF.get(section, option+'/bold', False):
            weight = QFont.Bold
        size = CONF.get(section, option+'/size', 9)
        font = QFont(family, size, weight)
        font.setItalic(italic)
        FONT_CACHE[(section, option)] = font
    return font
Example #47
0
def get_font(section, option=None):
    """Get console font properties depending on OS and user options"""
    font = FONT_CACHE.get((section, option))
    if font is None:
        if option is None:
            option = 'font'
        else:
            option += '/font'
        families = CONF.get(section, option + "/family", None)
        if families is None:
            return QFont()
        family = get_family(families)
        weight = QFont.Normal
        italic = CONF.get(section, option + '/italic', False)
        if CONF.get(section, option + '/bold', False):
            weight = QFont.Bold
        size = CONF.get(section, option + '/size', 9)
        font = QFont(family, size, weight)
        font.setItalic(italic)
        FONT_CACHE[(section, option)] = font
    return font
Example #48
0
def icon(name, resample=False):
    theme = CONF.get('main', 'icon_theme')
    if theme == 'spyder 3':
        if not _resource['loaded']:
            qta.load_font('spyder',
                          'spyder.ttf',
                          'spyder-charmap.json',
                          directory=_resource['directory'])
            _resource['loaded'] = True
        args, kwargs = _qtaargs[name]
        return qta.icon(*args, **kwargs)
    elif theme == 'spyder 2':
        icon = get_icon(name + '.png', resample=resample)
        return icon if icon is not None else QIcon()
Example #49
0
def remove_deprecated_shortcuts(data):
    """Remove deprecated shortcuts (shortcuts in CONF but not registered)"""
    section = 'shortcuts'
    options = [('%s/%s' % (context, name)).lower() for (context, name) in data]
    for option, _ in CONF.items(section, raw=CONF.raw):
        if option not in options:
            CONF.remove_option(section, option)
            if len(CONF.items(section, raw=CONF.raw)) == 0:
                CONF.remove_section(section)
Example #50
0
def remove_deprecated_shortcuts(data):
    """Remove deprecated shortcuts (shortcuts in CONF but not registered)"""
    section = 'shortcuts'
    options = [('%s/%s' % (context, name)).lower() for (context, name) in data]
    for option, _ in CONF.items(section, raw=CONF.raw):
        if option not in options:
            CONF.remove_option(section, option)
            if len(CONF.items(section, raw=CONF.raw)) == 0:
                CONF.remove_section(section)
Example #51
0
def set_color_scheme(name, color_scheme, replace=True):
    """Set syntax color scheme"""
    section = "color_schemes"
    names = CONF.get("color_schemes", "names", [])
    for key in sh.COLOR_SCHEME_KEYS:
        option = "%s/%s" % (name, key)
        value = CONF.get(section, option, default=None)
        if value is None or replace or name not in names:
            CONF.set(section, option, color_scheme[key])
    names.append(to_text_string(name))
    CONF.set(section, "names", sorted(list(set(names))))
Example #52
0
def set_color_scheme(name, color_scheme, replace=True):
    """Set syntax color scheme"""
    section = "color_schemes"
    names = CONF.get("color_schemes", "names", [])
    for key in sh.COLOR_SCHEME_KEYS:
        option = "%s/%s" % (name, key)
        value = CONF.get(section, option, default=None)
        if value is None or replace or name not in names:
            CONF.set(section, option, color_scheme[key])
    names.append(to_text_string(name))
    CONF.set(section, "names", sorted(list(set(names))))
Example #53
0
def test():
    import os.path as osp
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    shell = ExternalSystemShell(wdir=osp.dirname(__file__),
                                light_background=False)

    from spyderlib.qt.QtGui import QFont
    from spyderlib.config.main import CONF
    font = QFont(CONF.get('console', 'font/family')[0])
    font.setPointSize(10)
    shell.shell.set_font(font)

    shell.shell.toggle_wrap_mode(True)
    shell.start_shell(False)
    shell.show()
    sys.exit(app.exec_())
Example #54
0
def test():
    import os.path as osp
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()
    shell = ExternalSystemShell(wdir=osp.dirname(__file__),
                                light_background=False)

    from spyderlib.qt.QtGui import QFont
    from spyderlib.config.main import CONF
    font = QFont(CONF.get('console', 'font/family')[0])
    font.setPointSize(10)
    shell.shell.set_font(font)

    shell.shell.toggle_wrap_mode(True)
    shell.start_shell(False)
    shell.show()
    sys.exit(app.exec_())
Example #55
0
 def set(self, options):
     self.args = options.get("args", "")
     self.args_enabled = options.get("args/enabled", False)
     if CONF.get("run", WDIR_USE_FIXED_DIR_OPTION, False):
         default_wdir = CONF.get("run", WDIR_FIXED_DIR_OPTION, getcwd())
         self.wdir = options.get("workdir", default_wdir)
         self.wdir_enabled = True
     else:
         self.wdir = options.get("workdir", getcwd())
         self.wdir_enabled = options.get("workdir/enabled", False)
     self.current = options.get("current", CONF.get("run", CURRENT_INTERPRETER_OPTION, True))
     self.systerm = options.get("systerm", CONF.get("run", SYSTERM_INTERPRETER_OPTION, False))
     self.interact = options.get("interact", CONF.get("run", "interact", False))
     self.show_kill_warning = options.get("show_kill_warning", CONF.get("run", "show_kill_warning", False))
     self.post_mortem = options.get("post_mortem", CONF.get("run", "post_mortem", False))
     self.python_args = options.get("python_args", "")
     self.python_args_enabled = options.get("python_args/enabled", False)
Example #56
0
    def load_history(self):
        """Load history from a .py file in user home directory"""
        if osp.isfile(self.history_filename):
            rawhistory, _ = encoding.readlines(self.history_filename)
            rawhistory = [line.replace('\n', '') for line in rawhistory]
            if rawhistory[1] != self.INITHISTORY[1]:
                rawhistory[1] = self.INITHISTORY[1]
        else:
            rawhistory = self.INITHISTORY
        history = [line for line in rawhistory \
                   if line and not line.startswith('#')]

        # Truncating history to X entries:
        while len(history) >= CONF.get('historylog', 'max_entries'):
            del history[0]
            while rawhistory[0].startswith('#'):
                del rawhistory[0]
            del rawhistory[0]
        # Saving truncated history:
        encoding.writelines(rawhistory, self.history_filename)
        return history
Example #57
0
    def load_history(self):
        """Load history from a .py file in user home directory"""
        if osp.isfile(self.history_filename):
            rawhistory, _ = encoding.readlines(self.history_filename)
            rawhistory = [line.replace('\n', '') for line in rawhistory]
            if rawhistory[1] != self.INITHISTORY[1]:
                rawhistory[1] = self.INITHISTORY[1]
        else:
            rawhistory = self.INITHISTORY
        history = [line for line in rawhistory \
                   if line and not line.startswith('#')]

        # Truncating history to X entries:
        while len(history) >= CONF.get('historylog', 'max_entries'):
            del history[0]
            while rawhistory[0].startswith('#'):
                del rawhistory[0]
            del rawhistory[0]
        # Saving truncated history:
        encoding.writelines(rawhistory, self.history_filename)
        return history
Example #58
0
 def set(self, options):
     self.args = options.get('args', '')
     self.args_enabled = options.get('args/enabled', False)
     if CONF.get('run', WDIR_USE_FIXED_DIR_OPTION, False):
         default_wdir = CONF.get('run', WDIR_FIXED_DIR_OPTION, getcwd())
         self.wdir = options.get('workdir', default_wdir)
         self.wdir_enabled = True
     else:
         self.wdir = options.get('workdir', getcwd())
         self.wdir_enabled = options.get('workdir/enabled', False)
     self.current = options.get(
         'current', CONF.get('run', CURRENT_INTERPRETER_OPTION, True))
     self.systerm = options.get(
         'systerm', CONF.get('run', SYSTERM_INTERPRETER_OPTION, False))
     self.interact = options.get('interact',
                                 CONF.get('run', 'interact', False))
     self.show_kill_warning = options.get(
         'show_kill_warning', CONF.get('run', 'show_kill_warning', False))
     self.post_mortem = options.get('post_mortem',
                                    CONF.get('run', 'post_mortem', False))
     self.python_args = options.get('python_args', '')
     self.python_args_enabled = options.get('python_args/enabled', False)
Example #59
0
def test():
    from spyderlib.utils.qthelpers import qapplication
    app = qapplication()

    from spyderlib.plugins.variableexplorer import VariableExplorer
    settings = VariableExplorer.get_settings()

    shell = ExternalPythonShell(pythonexecutable=sys.executable,
                                interact=True,
                                stand_alone=settings,
                                wdir=osp.dirname(__file__),
                                mpl_backend=0,
                                light_background=False)

    from spyderlib.qt.QtGui import QFont
    from spyderlib.config.main import CONF
    font = QFont(CONF.get('console', 'font/family')[0])
    font.setPointSize(10)
    shell.shell.set_font(font)

    shell.shell.toggle_wrap_mode(True)
    shell.start_shell(False)
    shell.show()
    sys.exit(app.exec_())