def add_history(self, filename): """ Add new history tab Slot for add_history signal emitted by shell instance """ filename = encoding.to_unicode_from_fs(filename) if filename in self.filenames: return editor = codeeditor.CodeEditor(self) if osp.splitext(filename)[1] == '.py': language = 'py' icon = ima.icon('python') else: language = 'bat' icon = ima.icon('cmdprompt') editor.setup_editor(linenumbers=False, language=language, scrollflagarea=False) editor.focus_changed.connect(lambda: self.focus_changed.emit()) editor.setReadOnly(True) color_scheme = get_color_scheme(self.get_option('color_scheme_name')) editor.set_font( self.get_plugin_font(), color_scheme ) editor.toggle_wrap_mode( self.get_option('wrap') ) text, _ = encoding.read(filename) editor.set_text(text) editor.set_cursor_position('eof') self.editors.append(editor) self.filenames.append(filename) self.icons.append(icon) index = self.tabwidget.addTab(editor, osp.basename(filename)) self.find_widget.set_editor(editor) self.tabwidget.setTabToolTip(index, filename) self.tabwidget.setTabIcon(index, icon) self.tabwidget.setCurrentIndex(index)
def add_history(self, filename): """ Add new history tab Slot for SIGNAL('add_history(QString)') emitted by shell instance """ filename = encoding.to_unicode_from_fs(filename) if filename in self.filenames: return editor = codeeditor.CodeEditor(self) if osp.splitext(filename)[1] == ".py": language = "py" icon = get_icon("python.png") else: language = "bat" icon = get_icon("cmdprompt.png") editor.setup_editor(linenumbers=False, language=language, scrollflagarea=False) self.connect(editor, SIGNAL("focus_changed()"), lambda: self.emit(SIGNAL("focus_changed()"))) editor.setReadOnly(True) color_scheme = get_color_scheme(self.get_option("color_scheme_name")) editor.set_font(self.get_plugin_font(), color_scheme) editor.toggle_wrap_mode(self.get_option("wrap")) text, _ = encoding.read(filename) editor.set_text(text) editor.set_cursor_position("eof") self.editors.append(editor) self.filenames.append(filename) self.icons.append(icon) index = self.tabwidget.addTab(editor, osp.basename(filename)) self.find_widget.set_editor(editor) self.tabwidget.setTabToolTip(index, filename) self.tabwidget.setTabIcon(index, icon) self.tabwidget.setCurrentIndex(index)
def get_home_dir(): """ Return user home directory """ try: # expanduser() returns a raw byte string which needs to be # decoded with the codec that the OS is using to represent file paths. path = encoding.to_unicode_from_fs(osp.expanduser('~')) except: path = '' for env_var in ('HOME', 'USERPROFILE', 'TMP'): if osp.isdir(path): break # os.environ.get() returns a raw byte string which needs to be # decoded with the codec that the OS is using to represent environment # variables. path = encoding.to_unicode_from_fs(os.environ.get(env_var, '')) if path: return path else: raise RuntimeError('Please define environment variable $HOME')
def patched(): """ Return user home directory """ import os.path as osp from spyderlib.utils import encoding for env_var in ('APPDATA', 'USERPROFILE', 'HOME', 'TMP'): # os.environ.get() returns a raw byte string which needs to be # decoded with the codec that the OS is using to represent environment # variables. path = encoding.to_unicode_from_fs(os.environ.get(env_var, '')) if osp.isdir(path): break if path: return path try: # expanduser() returns a raw byte string which needs to be # decoded with the codec that the OS is using to represent file paths. path = encoding.to_unicode_from_fs(osp.expanduser('~')) return path except: raise RuntimeError('Please define environment variable $HOME')
def get_pylint_version(): """Return pylint version""" global PYLINT_PATH if PYLINT_PATH is None: return process = subprocess.Popen(['pylint', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=osp.dirname(PYLINT_PATH), shell=True if os.name == 'nt' else False) lines = to_unicode_from_fs(process.stdout.read()).splitlines() if lines: match = re.match('(pylint|pylint-script.py) ([0-9\.]*)', lines[0]) if match is not None: return match.groups()[1]
def get_pylint_version(): """Return pylint version""" if PYLINT_PATH is None: return cwd = osp.dirname(PYLINT_PATH) args = ['--version'] if os.name == 'nt': cmd = ' '.join([PYLINT] + args) process = programs.run_shell_command(cmd, cwd=cwd) else: process = programs.run_program(PYLINT, args, cwd=cwd) lines = to_unicode_from_fs(process.stdout.read()).splitlines() if lines: regex = '({0}*|pylint-script.py) ([0-9\.]*)'.format(PYLINT) match = re.match(regex, lines[0]) if match is not None: return match.groups()[1]
def get_pylint_version(): """Return pylint version""" global PYLINT_PATH if PYLINT_PATH is None: return process = subprocess.Popen( [PYLINT, "--version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=osp.dirname(PYLINT_PATH), shell=True if os.name == "nt" else False, ) lines = to_unicode_from_fs(process.stdout.read()).splitlines() if lines: regex = "({0}*|pylint-script.py) ([0-9\.]*)".format(PYLINT) match = re.match(regex, lines[0]) if match is not None: return match.groups()[1]
def _convert(fname): fname = os.path.abspath(encoding.to_unicode_from_fs(fname)) if os.name == 'nt' and len(fname) >= 2 and fname[1] == ':': fname = fname[0].upper() + fname[1:] return fname
import inspect import os import os.path as osp import re import subprocess import sys import tempfile # Local imports from spyderlib.utils import encoding from spyderlib.py3compat import PY2, is_text_string if os.name == 'nt': TEMPDIR = tempfile.gettempdir() + osp.sep + 'spyder' else: username = encoding.to_unicode_from_fs(os.environ.get('USER')) TEMPDIR = tempfile.gettempdir() + osp.sep + 'spyder-' + username def is_program_installed(basename): """Return program absolute path if installed in PATH Otherwise, return None""" for path in os.environ["PATH"].split(os.pathsep): abspath = osp.join(path, basename) if osp.isfile(abspath): return abspath def find_program(basename): """Find program in PATH and return absolute path Try adding .exe or .bat to basename on Windows platforms
def _convert(fname): fname = os.path.abspath(encoding.to_unicode_from_fs(fname)) if os.name == 'nt' and len(fname) >= 2 and fname[1] == ':': fname = fname[0].upper()+fname[1:] return fname
import os import os.path as osp import re import subprocess import sys import tempfile # Local imports from spyderlib.utils import encoding from spyderlib.py3compat import PY2, is_text_string if os.name == 'nt': TEMPDIR = tempfile.gettempdir() + osp.sep + 'spyder' else: username = encoding.to_unicode_from_fs(os.environ.get('USER')) TEMPDIR = tempfile.gettempdir() + osp.sep + 'spyder-' + username def is_program_installed(basename): """Return program absolute path if installed in PATH Otherwise, return None""" for path in os.environ["PATH"].split(os.pathsep): abspath = osp.join(path, basename) if osp.isfile(abspath): return abspath def find_program(basename): """Find program in PATH and return absolute path Try adding .exe or .bat to basename on Windows platforms
def sphinxify(docstring, context, buildername='html'): """ Runs Sphinx on a docstring and outputs the processed documentation. Parameters ---------- docstring : str a ReST-formatted docstring context : dict Variables to be passed to the layout template to control how its rendered (through the Sphinx variable *html_context*). buildername: str It can be either `html` or `text`. Returns ------- An Sphinx-processed string, in either HTML or plain text format, depending on the value of `buildername` """ srcdir = mkdtemp() srcdir = encoding.to_unicode_from_fs(srcdir) base_name = osp.join(srcdir, 'docstring') rst_name = base_name + '.rst' if buildername == 'html': suffix = '.html' else: suffix = '.txt' output_name = base_name + suffix # This is needed so users can type \\ on latex eqnarray envs inside raw # docstrings if context['right_sphinx_version'] and context['math_on']: docstring = docstring.replace('\\\\', '\\\\\\\\') # Add a class to several characters on the argspec. This way we can # highlight them using css, in a similar way to what IPython does. # NOTE: Before doing this, we escape common html chars so that they # don't interfere with the rest of html present in the page argspec = escape(context['argspec']) for char in ['=', ',', '(', ')', '*', '**']: argspec = argspec.replace(char, '<span class="argspec-highlight">' + char + '</span>') context['argspec'] = argspec doc_file = codecs.open(rst_name, 'w', encoding='utf-8') doc_file.write(docstring) doc_file.close() temp_confdir = False if temp_confdir: # TODO: This may be inefficient. Find a faster way to do it. confdir = mkdtemp() confdir = encoding.to_unicode_from_fs(confdir) generate_configuration(confdir) else: confdir = osp.join(get_module_source_path('spyderlib.utils.inspector')) confoverrides = {'html_context': context} doctreedir = osp.join(srcdir, 'doctrees') sphinx_app = Sphinx(srcdir, confdir, srcdir, doctreedir, buildername, confoverrides, status=None, warning=None, freshenv=True, warningiserror=False, tags=None) try: sphinx_app.build(None, [rst_name]) except SystemMessage: output = _("It was not possible to generate rich text help for this " "object.</br>" "Please see it in plain text.") return warning(output) # TODO: Investigate if this is necessary/important for us if osp.exists(output_name): output = codecs.open(output_name, 'r', encoding='utf-8').read() output = output.replace('<pre>', '<pre class="literal-block">') else: output = _("It was not possible to generate rich text help for this " "object.</br>" "Please see it in plain text.") return warning(output) if temp_confdir: shutil.rmtree(confdir, ignore_errors=True) shutil.rmtree(srcdir, ignore_errors=True) return output
def sphinxify(docstring, context, buildername='html'): """ Runs Sphinx on a docstring and outputs the processed documentation. Parameters ---------- docstring : str a ReST-formatted docstring context : dict Variables to be passed to the layout template to control how its rendered (through the Sphinx variable *html_context*). buildername: str It can be either `html` or `text`. Returns ------- An Sphinx-processed string, in either HTML or plain text format, depending on the value of `buildername` """ srcdir = mkdtemp() srcdir = encoding.to_unicode_from_fs(srcdir) base_name = osp.join(srcdir, 'docstring') rst_name = base_name + '.rst' if buildername == 'html': suffix = '.html' else: suffix = '.txt' output_name = base_name + suffix # This is needed so users can type \\ on latex eqnarray envs inside raw # docstrings if context['right_sphinx_version'] and context['math_on']: docstring = docstring.replace('\\\\', '\\\\\\\\') # Add a class to several characters on the argspec. This way we can # highlight them using css, in a similar way to what IPython does. argspec = context['argspec'] for char in ['=', ',', '(', ')', '*', '**']: argspec = argspec.replace(char, '<span class="argspec-highlight">' + char + '</span>') context['argspec'] = argspec doc_file = codecs.open(rst_name, 'w', encoding='utf-8') doc_file.write(docstring) doc_file.close() temp_confdir = False if temp_confdir: # TODO: This may be inefficient. Find a faster way to do it. confdir = mkdtemp() confdir = encoding.to_unicode_from_fs(confdir) generate_configuration(confdir) else: confdir = osp.join(get_module_source_path('spyderlib.utils.inspector')) confoverrides = {'html_context': context} doctreedir = osp.join(srcdir, 'doctrees') sphinx_app = Sphinx(srcdir, confdir, srcdir, doctreedir, buildername, confoverrides, status=None, warning=None, freshenv=True, warningiserror=False, tags=None) try: sphinx_app.build(None, [rst_name]) except SystemMessage: output = _("It was not possible to generate rich text help for this " "object.</br>" "Please see it in plain text.") return warning(output) # TODO: Investigate if this is necessary/important for us if osp.exists(output_name): output = codecs.open(output_name, 'r', encoding='utf-8').read() output = output.replace('<pre>', '<pre class="literal-block">') else: output = _("It was not possible to generate rich text help for this " "object.</br>" "Please see it in plain text.") return warning(output) if temp_confdir: shutil.rmtree(confdir, ignore_errors=True) shutil.rmtree(srcdir, ignore_errors=True) return output