repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
spyder-ide/spyder | spyder/preferences/shortcuts.py | ShortcutsTable.focusInEvent | def focusInEvent(self, e):
"""Qt Override."""
super(ShortcutsTable, self).focusInEvent(e)
self.selectRow(self.currentIndex().row()) | python | def focusInEvent(self, e):
"""Qt Override."""
super(ShortcutsTable, self).focusInEvent(e)
self.selectRow(self.currentIndex().row()) | [
"def",
"focusInEvent",
"(",
"self",
",",
"e",
")",
":",
"super",
"(",
"ShortcutsTable",
",",
"self",
")",
".",
"focusInEvent",
"(",
"e",
")",
"self",
".",
"selectRow",
"(",
"self",
".",
"currentIndex",
"(",
")",
".",
"row",
"(",
")",
")"
] | Qt Override. | [
"Qt",
"Override",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/shortcuts.py#L719-L722 | train |
spyder-ide/spyder | spyder/preferences/shortcuts.py | ShortcutsTable.adjust_cells | def adjust_cells(self):
"""Adjust column size based on contents."""
self.resizeColumnsToContents()
fm = self.horizontalHeader().fontMetrics()
names = [fm.width(s.name + ' '*9) for s in self.source_model.shortcuts]
self.setColumnWidth(NAME, max(names))
self.horizontalHeader().setStretchLastSection(True) | python | def adjust_cells(self):
"""Adjust column size based on contents."""
self.resizeColumnsToContents()
fm = self.horizontalHeader().fontMetrics()
names = [fm.width(s.name + ' '*9) for s in self.source_model.shortcuts]
self.setColumnWidth(NAME, max(names))
self.horizontalHeader().setStretchLastSection(True) | [
"def",
"adjust_cells",
"(",
"self",
")",
":",
"self",
".",
"resizeColumnsToContents",
"(",
")",
"fm",
"=",
"self",
".",
"horizontalHeader",
"(",
")",
".",
"fontMetrics",
"(",
")",
"names",
"=",
"[",
"fm",
".",
"width",
"(",
"s",
".",
"name",
"+",
"' '",
"*",
"9",
")",
"for",
"s",
"in",
"self",
".",
"source_model",
".",
"shortcuts",
"]",
"self",
".",
"setColumnWidth",
"(",
"NAME",
",",
"max",
"(",
"names",
")",
")",
"self",
".",
"horizontalHeader",
"(",
")",
".",
"setStretchLastSection",
"(",
"True",
")"
] | Adjust column size based on contents. | [
"Adjust",
"column",
"size",
"based",
"on",
"contents",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/shortcuts.py#L729-L735 | train |
spyder-ide/spyder | spyder/preferences/shortcuts.py | ShortcutsTable.load_shortcuts | def load_shortcuts(self):
"""Load shortcuts and assign to table model."""
shortcuts = []
for context, name, keystr in iter_shortcuts():
shortcut = Shortcut(context, name, keystr)
shortcuts.append(shortcut)
shortcuts = sorted(shortcuts, key=lambda x: x.context+x.name)
# Store the original order of shortcuts
for i, shortcut in enumerate(shortcuts):
shortcut.index = i
self.source_model.shortcuts = shortcuts
self.source_model.scores = [0]*len(shortcuts)
self.source_model.rich_text = [s.name for s in shortcuts]
self.source_model.reset()
self.adjust_cells()
self.sortByColumn(CONTEXT, Qt.AscendingOrder) | python | def load_shortcuts(self):
"""Load shortcuts and assign to table model."""
shortcuts = []
for context, name, keystr in iter_shortcuts():
shortcut = Shortcut(context, name, keystr)
shortcuts.append(shortcut)
shortcuts = sorted(shortcuts, key=lambda x: x.context+x.name)
# Store the original order of shortcuts
for i, shortcut in enumerate(shortcuts):
shortcut.index = i
self.source_model.shortcuts = shortcuts
self.source_model.scores = [0]*len(shortcuts)
self.source_model.rich_text = [s.name for s in shortcuts]
self.source_model.reset()
self.adjust_cells()
self.sortByColumn(CONTEXT, Qt.AscendingOrder) | [
"def",
"load_shortcuts",
"(",
"self",
")",
":",
"shortcuts",
"=",
"[",
"]",
"for",
"context",
",",
"name",
",",
"keystr",
"in",
"iter_shortcuts",
"(",
")",
":",
"shortcut",
"=",
"Shortcut",
"(",
"context",
",",
"name",
",",
"keystr",
")",
"shortcuts",
".",
"append",
"(",
"shortcut",
")",
"shortcuts",
"=",
"sorted",
"(",
"shortcuts",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"context",
"+",
"x",
".",
"name",
")",
"# Store the original order of shortcuts\r",
"for",
"i",
",",
"shortcut",
"in",
"enumerate",
"(",
"shortcuts",
")",
":",
"shortcut",
".",
"index",
"=",
"i",
"self",
".",
"source_model",
".",
"shortcuts",
"=",
"shortcuts",
"self",
".",
"source_model",
".",
"scores",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"shortcuts",
")",
"self",
".",
"source_model",
".",
"rich_text",
"=",
"[",
"s",
".",
"name",
"for",
"s",
"in",
"shortcuts",
"]",
"self",
".",
"source_model",
".",
"reset",
"(",
")",
"self",
".",
"adjust_cells",
"(",
")",
"self",
".",
"sortByColumn",
"(",
"CONTEXT",
",",
"Qt",
".",
"AscendingOrder",
")"
] | Load shortcuts and assign to table model. | [
"Load",
"shortcuts",
"and",
"assign",
"to",
"table",
"model",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/shortcuts.py#L737-L752 | train |
spyder-ide/spyder | spyder/preferences/shortcuts.py | ShortcutsTable.check_shortcuts | def check_shortcuts(self):
"""Check shortcuts for conflicts."""
conflicts = []
for index, sh1 in enumerate(self.source_model.shortcuts):
if index == len(self.source_model.shortcuts)-1:
break
if str(sh1.key) == '':
continue
for sh2 in self.source_model.shortcuts[index+1:]:
if sh2 is sh1:
continue
if str(sh2.key) == str(sh1.key) \
and (sh1.context == sh2.context or sh1.context == '_' or
sh2.context == '_'):
conflicts.append((sh1, sh2))
if conflicts:
self.parent().show_this_page.emit()
cstr = "\n".join(['%s <---> %s' % (sh1, sh2)
for sh1, sh2 in conflicts])
QMessageBox.warning(self, _("Conflicts"),
_("The following conflicts have been "
"detected:")+"\n"+cstr, QMessageBox.Ok) | python | def check_shortcuts(self):
"""Check shortcuts for conflicts."""
conflicts = []
for index, sh1 in enumerate(self.source_model.shortcuts):
if index == len(self.source_model.shortcuts)-1:
break
if str(sh1.key) == '':
continue
for sh2 in self.source_model.shortcuts[index+1:]:
if sh2 is sh1:
continue
if str(sh2.key) == str(sh1.key) \
and (sh1.context == sh2.context or sh1.context == '_' or
sh2.context == '_'):
conflicts.append((sh1, sh2))
if conflicts:
self.parent().show_this_page.emit()
cstr = "\n".join(['%s <---> %s' % (sh1, sh2)
for sh1, sh2 in conflicts])
QMessageBox.warning(self, _("Conflicts"),
_("The following conflicts have been "
"detected:")+"\n"+cstr, QMessageBox.Ok) | [
"def",
"check_shortcuts",
"(",
"self",
")",
":",
"conflicts",
"=",
"[",
"]",
"for",
"index",
",",
"sh1",
"in",
"enumerate",
"(",
"self",
".",
"source_model",
".",
"shortcuts",
")",
":",
"if",
"index",
"==",
"len",
"(",
"self",
".",
"source_model",
".",
"shortcuts",
")",
"-",
"1",
":",
"break",
"if",
"str",
"(",
"sh1",
".",
"key",
")",
"==",
"''",
":",
"continue",
"for",
"sh2",
"in",
"self",
".",
"source_model",
".",
"shortcuts",
"[",
"index",
"+",
"1",
":",
"]",
":",
"if",
"sh2",
"is",
"sh1",
":",
"continue",
"if",
"str",
"(",
"sh2",
".",
"key",
")",
"==",
"str",
"(",
"sh1",
".",
"key",
")",
"and",
"(",
"sh1",
".",
"context",
"==",
"sh2",
".",
"context",
"or",
"sh1",
".",
"context",
"==",
"'_'",
"or",
"sh2",
".",
"context",
"==",
"'_'",
")",
":",
"conflicts",
".",
"append",
"(",
"(",
"sh1",
",",
"sh2",
")",
")",
"if",
"conflicts",
":",
"self",
".",
"parent",
"(",
")",
".",
"show_this_page",
".",
"emit",
"(",
")",
"cstr",
"=",
"\"\\n\"",
".",
"join",
"(",
"[",
"'%s <---> %s'",
"%",
"(",
"sh1",
",",
"sh2",
")",
"for",
"sh1",
",",
"sh2",
"in",
"conflicts",
"]",
")",
"QMessageBox",
".",
"warning",
"(",
"self",
",",
"_",
"(",
"\"Conflicts\"",
")",
",",
"_",
"(",
"\"The following conflicts have been \"",
"\"detected:\"",
")",
"+",
"\"\\n\"",
"+",
"cstr",
",",
"QMessageBox",
".",
"Ok",
")"
] | Check shortcuts for conflicts. | [
"Check",
"shortcuts",
"for",
"conflicts",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/shortcuts.py#L754-L775 | train |
spyder-ide/spyder | spyder/preferences/shortcuts.py | ShortcutsTable.save_shortcuts | def save_shortcuts(self):
"""Save shortcuts from table model."""
self.check_shortcuts()
for shortcut in self.source_model.shortcuts:
shortcut.save() | python | def save_shortcuts(self):
"""Save shortcuts from table model."""
self.check_shortcuts()
for shortcut in self.source_model.shortcuts:
shortcut.save() | [
"def",
"save_shortcuts",
"(",
"self",
")",
":",
"self",
".",
"check_shortcuts",
"(",
")",
"for",
"shortcut",
"in",
"self",
".",
"source_model",
".",
"shortcuts",
":",
"shortcut",
".",
"save",
"(",
")"
] | Save shortcuts from table model. | [
"Save",
"shortcuts",
"from",
"table",
"model",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/shortcuts.py#L777-L781 | train |
spyder-ide/spyder | spyder/preferences/shortcuts.py | ShortcutsTable.show_editor | def show_editor(self):
"""Create, setup and display the shortcut editor dialog."""
index = self.proxy_model.mapToSource(self.currentIndex())
row, column = index.row(), index.column()
shortcuts = self.source_model.shortcuts
context = shortcuts[row].context
name = shortcuts[row].name
sequence_index = self.source_model.index(row, SEQUENCE)
sequence = sequence_index.data()
dialog = ShortcutEditor(self, context, name, sequence, shortcuts)
if dialog.exec_():
new_sequence = dialog.new_sequence
self.source_model.setData(sequence_index, new_sequence) | python | def show_editor(self):
"""Create, setup and display the shortcut editor dialog."""
index = self.proxy_model.mapToSource(self.currentIndex())
row, column = index.row(), index.column()
shortcuts = self.source_model.shortcuts
context = shortcuts[row].context
name = shortcuts[row].name
sequence_index = self.source_model.index(row, SEQUENCE)
sequence = sequence_index.data()
dialog = ShortcutEditor(self, context, name, sequence, shortcuts)
if dialog.exec_():
new_sequence = dialog.new_sequence
self.source_model.setData(sequence_index, new_sequence) | [
"def",
"show_editor",
"(",
"self",
")",
":",
"index",
"=",
"self",
".",
"proxy_model",
".",
"mapToSource",
"(",
"self",
".",
"currentIndex",
"(",
")",
")",
"row",
",",
"column",
"=",
"index",
".",
"row",
"(",
")",
",",
"index",
".",
"column",
"(",
")",
"shortcuts",
"=",
"self",
".",
"source_model",
".",
"shortcuts",
"context",
"=",
"shortcuts",
"[",
"row",
"]",
".",
"context",
"name",
"=",
"shortcuts",
"[",
"row",
"]",
".",
"name",
"sequence_index",
"=",
"self",
".",
"source_model",
".",
"index",
"(",
"row",
",",
"SEQUENCE",
")",
"sequence",
"=",
"sequence_index",
".",
"data",
"(",
")",
"dialog",
"=",
"ShortcutEditor",
"(",
"self",
",",
"context",
",",
"name",
",",
"sequence",
",",
"shortcuts",
")",
"if",
"dialog",
".",
"exec_",
"(",
")",
":",
"new_sequence",
"=",
"dialog",
".",
"new_sequence",
"self",
".",
"source_model",
".",
"setData",
"(",
"sequence_index",
",",
"new_sequence",
")"
] | Create, setup and display the shortcut editor dialog. | [
"Create",
"setup",
"and",
"display",
"the",
"shortcut",
"editor",
"dialog",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/shortcuts.py#L783-L798 | train |
spyder-ide/spyder | spyder/preferences/shortcuts.py | ShortcutsTable.set_regex | def set_regex(self, regex=None, reset=False):
"""Update the regex text for the shortcut finder."""
if reset:
text = ''
else:
text = self.finder.text().replace(' ', '').lower()
self.proxy_model.set_filter(text)
self.source_model.update_search_letters(text)
self.sortByColumn(SEARCH_SCORE, Qt.AscendingOrder)
if self.last_regex != regex:
self.selectRow(0)
self.last_regex = regex | python | def set_regex(self, regex=None, reset=False):
"""Update the regex text for the shortcut finder."""
if reset:
text = ''
else:
text = self.finder.text().replace(' ', '').lower()
self.proxy_model.set_filter(text)
self.source_model.update_search_letters(text)
self.sortByColumn(SEARCH_SCORE, Qt.AscendingOrder)
if self.last_regex != regex:
self.selectRow(0)
self.last_regex = regex | [
"def",
"set_regex",
"(",
"self",
",",
"regex",
"=",
"None",
",",
"reset",
"=",
"False",
")",
":",
"if",
"reset",
":",
"text",
"=",
"''",
"else",
":",
"text",
"=",
"self",
".",
"finder",
".",
"text",
"(",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
".",
"lower",
"(",
")",
"self",
".",
"proxy_model",
".",
"set_filter",
"(",
"text",
")",
"self",
".",
"source_model",
".",
"update_search_letters",
"(",
"text",
")",
"self",
".",
"sortByColumn",
"(",
"SEARCH_SCORE",
",",
"Qt",
".",
"AscendingOrder",
")",
"if",
"self",
".",
"last_regex",
"!=",
"regex",
":",
"self",
".",
"selectRow",
"(",
"0",
")",
"self",
".",
"last_regex",
"=",
"regex"
] | Update the regex text for the shortcut finder. | [
"Update",
"the",
"regex",
"text",
"for",
"the",
"shortcut",
"finder",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/shortcuts.py#L800-L813 | train |
spyder-ide/spyder | spyder/preferences/shortcuts.py | ShortcutsTable.next_row | def next_row(self):
"""Move to next row from currently selected row."""
row = self.currentIndex().row()
rows = self.proxy_model.rowCount()
if row + 1 == rows:
row = -1
self.selectRow(row + 1) | python | def next_row(self):
"""Move to next row from currently selected row."""
row = self.currentIndex().row()
rows = self.proxy_model.rowCount()
if row + 1 == rows:
row = -1
self.selectRow(row + 1) | [
"def",
"next_row",
"(",
"self",
")",
":",
"row",
"=",
"self",
".",
"currentIndex",
"(",
")",
".",
"row",
"(",
")",
"rows",
"=",
"self",
".",
"proxy_model",
".",
"rowCount",
"(",
")",
"if",
"row",
"+",
"1",
"==",
"rows",
":",
"row",
"=",
"-",
"1",
"self",
".",
"selectRow",
"(",
"row",
"+",
"1",
")"
] | Move to next row from currently selected row. | [
"Move",
"to",
"next",
"row",
"from",
"currently",
"selected",
"row",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/shortcuts.py#L815-L821 | train |
spyder-ide/spyder | spyder/preferences/shortcuts.py | ShortcutsTable.previous_row | def previous_row(self):
"""Move to previous row from currently selected row."""
row = self.currentIndex().row()
rows = self.proxy_model.rowCount()
if row == 0:
row = rows
self.selectRow(row - 1) | python | def previous_row(self):
"""Move to previous row from currently selected row."""
row = self.currentIndex().row()
rows = self.proxy_model.rowCount()
if row == 0:
row = rows
self.selectRow(row - 1) | [
"def",
"previous_row",
"(",
"self",
")",
":",
"row",
"=",
"self",
".",
"currentIndex",
"(",
")",
".",
"row",
"(",
")",
"rows",
"=",
"self",
".",
"proxy_model",
".",
"rowCount",
"(",
")",
"if",
"row",
"==",
"0",
":",
"row",
"=",
"rows",
"self",
".",
"selectRow",
"(",
"row",
"-",
"1",
")"
] | Move to previous row from currently selected row. | [
"Move",
"to",
"previous",
"row",
"from",
"currently",
"selected",
"row",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/shortcuts.py#L823-L829 | train |
spyder-ide/spyder | spyder/preferences/shortcuts.py | ShortcutsTable.keyPressEvent | def keyPressEvent(self, event):
"""Qt Override."""
key = event.key()
if key in [Qt.Key_Enter, Qt.Key_Return]:
self.show_editor()
elif key in [Qt.Key_Tab]:
self.finder.setFocus()
elif key in [Qt.Key_Backtab]:
self.parent().reset_btn.setFocus()
elif key in [Qt.Key_Up, Qt.Key_Down, Qt.Key_Left, Qt.Key_Right]:
super(ShortcutsTable, self).keyPressEvent(event)
elif key not in [Qt.Key_Escape, Qt.Key_Space]:
text = event.text()
if text:
if re.search(VALID_FINDER_CHARS, text) is not None:
self.finder.setFocus()
self.finder.set_text(text)
elif key in [Qt.Key_Escape]:
self.finder.keyPressEvent(event) | python | def keyPressEvent(self, event):
"""Qt Override."""
key = event.key()
if key in [Qt.Key_Enter, Qt.Key_Return]:
self.show_editor()
elif key in [Qt.Key_Tab]:
self.finder.setFocus()
elif key in [Qt.Key_Backtab]:
self.parent().reset_btn.setFocus()
elif key in [Qt.Key_Up, Qt.Key_Down, Qt.Key_Left, Qt.Key_Right]:
super(ShortcutsTable, self).keyPressEvent(event)
elif key not in [Qt.Key_Escape, Qt.Key_Space]:
text = event.text()
if text:
if re.search(VALID_FINDER_CHARS, text) is not None:
self.finder.setFocus()
self.finder.set_text(text)
elif key in [Qt.Key_Escape]:
self.finder.keyPressEvent(event) | [
"def",
"keyPressEvent",
"(",
"self",
",",
"event",
")",
":",
"key",
"=",
"event",
".",
"key",
"(",
")",
"if",
"key",
"in",
"[",
"Qt",
".",
"Key_Enter",
",",
"Qt",
".",
"Key_Return",
"]",
":",
"self",
".",
"show_editor",
"(",
")",
"elif",
"key",
"in",
"[",
"Qt",
".",
"Key_Tab",
"]",
":",
"self",
".",
"finder",
".",
"setFocus",
"(",
")",
"elif",
"key",
"in",
"[",
"Qt",
".",
"Key_Backtab",
"]",
":",
"self",
".",
"parent",
"(",
")",
".",
"reset_btn",
".",
"setFocus",
"(",
")",
"elif",
"key",
"in",
"[",
"Qt",
".",
"Key_Up",
",",
"Qt",
".",
"Key_Down",
",",
"Qt",
".",
"Key_Left",
",",
"Qt",
".",
"Key_Right",
"]",
":",
"super",
"(",
"ShortcutsTable",
",",
"self",
")",
".",
"keyPressEvent",
"(",
"event",
")",
"elif",
"key",
"not",
"in",
"[",
"Qt",
".",
"Key_Escape",
",",
"Qt",
".",
"Key_Space",
"]",
":",
"text",
"=",
"event",
".",
"text",
"(",
")",
"if",
"text",
":",
"if",
"re",
".",
"search",
"(",
"VALID_FINDER_CHARS",
",",
"text",
")",
"is",
"not",
"None",
":",
"self",
".",
"finder",
".",
"setFocus",
"(",
")",
"self",
".",
"finder",
".",
"set_text",
"(",
"text",
")",
"elif",
"key",
"in",
"[",
"Qt",
".",
"Key_Escape",
"]",
":",
"self",
".",
"finder",
".",
"keyPressEvent",
"(",
"event",
")"
] | Qt Override. | [
"Qt",
"Override",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/shortcuts.py#L831-L849 | train |
spyder-ide/spyder | spyder/preferences/shortcuts.py | ShortcutsConfigPage.reset_to_default | def reset_to_default(self):
"""Reset to default values of the shortcuts making a confirmation."""
reset = QMessageBox.warning(self, _("Shortcuts reset"),
_("Do you want to reset "
"to default values?"),
QMessageBox.Yes | QMessageBox.No)
if reset == QMessageBox.No:
return
reset_shortcuts()
self.main.apply_shortcuts()
self.table.load_shortcuts()
self.load_from_conf()
self.set_modified(False) | python | def reset_to_default(self):
"""Reset to default values of the shortcuts making a confirmation."""
reset = QMessageBox.warning(self, _("Shortcuts reset"),
_("Do you want to reset "
"to default values?"),
QMessageBox.Yes | QMessageBox.No)
if reset == QMessageBox.No:
return
reset_shortcuts()
self.main.apply_shortcuts()
self.table.load_shortcuts()
self.load_from_conf()
self.set_modified(False) | [
"def",
"reset_to_default",
"(",
"self",
")",
":",
"reset",
"=",
"QMessageBox",
".",
"warning",
"(",
"self",
",",
"_",
"(",
"\"Shortcuts reset\"",
")",
",",
"_",
"(",
"\"Do you want to reset \"",
"\"to default values?\"",
")",
",",
"QMessageBox",
".",
"Yes",
"|",
"QMessageBox",
".",
"No",
")",
"if",
"reset",
"==",
"QMessageBox",
".",
"No",
":",
"return",
"reset_shortcuts",
"(",
")",
"self",
".",
"main",
".",
"apply_shortcuts",
"(",
")",
"self",
".",
"table",
".",
"load_shortcuts",
"(",
")",
"self",
".",
"load_from_conf",
"(",
")",
"self",
".",
"set_modified",
"(",
"False",
")"
] | Reset to default values of the shortcuts making a confirmation. | [
"Reset",
"to",
"default",
"values",
"of",
"the",
"shortcuts",
"making",
"a",
"confirmation",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/shortcuts.py#L895-L907 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | get_color_scheme | def get_color_scheme(name):
"""Get a color scheme from config using its name"""
name = name.lower()
scheme = {}
for key in COLOR_SCHEME_KEYS:
try:
scheme[key] = CONF.get('appearance', name+'/'+key)
except:
scheme[key] = CONF.get('appearance', 'spyder/'+key)
return scheme | python | def get_color_scheme(name):
"""Get a color scheme from config using its name"""
name = name.lower()
scheme = {}
for key in COLOR_SCHEME_KEYS:
try:
scheme[key] = CONF.get('appearance', name+'/'+key)
except:
scheme[key] = CONF.get('appearance', 'spyder/'+key)
return scheme | [
"def",
"get_color_scheme",
"(",
"name",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"scheme",
"=",
"{",
"}",
"for",
"key",
"in",
"COLOR_SCHEME_KEYS",
":",
"try",
":",
"scheme",
"[",
"key",
"]",
"=",
"CONF",
".",
"get",
"(",
"'appearance'",
",",
"name",
"+",
"'/'",
"+",
"key",
")",
"except",
":",
"scheme",
"[",
"key",
"]",
"=",
"CONF",
".",
"get",
"(",
"'appearance'",
",",
"'spyder/'",
"+",
"key",
")",
"return",
"scheme"
] | Get a color scheme from config using its name | [
"Get",
"a",
"color",
"scheme",
"from",
"config",
"using",
"its",
"name"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L88-L97 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | make_python_patterns | def make_python_patterns(additional_keywords=[], additional_builtins=[]):
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kwlist = keyword.kwlist + additional_keywords
builtinlist = [str(name) for name in dir(builtins)
if not name.startswith('_')] + additional_builtins
repeated = set(kwlist) & set(builtinlist)
for repeated_element in repeated:
kwlist.remove(repeated_element)
kw = r"\b" + any("keyword", kwlist) + r"\b"
builtin = r"([^.'\"\\#]\b|^)" + any("builtin", builtinlist) + r"\b"
comment = any("comment", [r"#[^\n]*"])
instance = any("instance", [r"\bself\b",
r"\bcls\b",
(r"^\s*@([a-zA-Z_][a-zA-Z0-9_]*)"
r"(\.[a-zA-Z_][a-zA-Z0-9_]*)*")])
number_regex = [r"\b[+-]?[0-9]+[lLjJ]?\b",
r"\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b",
r"\b[+-]?0[oO][0-7]+[lL]?\b",
r"\b[+-]?0[bB][01]+[lL]?\b",
r"\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?[jJ]?\b"]
if PY3:
prefix = "r|u|R|U|f|F|fr|Fr|fR|FR|rf|rF|Rf|RF|b|B|br|Br|bR|BR|rb|rB|Rb|RB"
else:
prefix = "r|u|ur|R|U|UR|Ur|uR|b|B|br|Br|bR|BR"
sqstring = r"(\b(%s))?'[^'\\\n]*(\\.[^'\\\n]*)*'?" % prefix
dqstring = r'(\b(%s))?"[^"\\\n]*(\\.[^"\\\n]*)*"?' % prefix
uf_sqstring = r"(\b(%s))?'[^'\\\n]*(\\.[^'\\\n]*)*(\\)$(?!')$" % prefix
uf_dqstring = r'(\b(%s))?"[^"\\\n]*(\\.[^"\\\n]*)*(\\)$(?!")$' % prefix
sq3string = r"(\b(%s))?'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?" % prefix
dq3string = r'(\b(%s))?"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?' % prefix
uf_sq3string = r"(\b(%s))?'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(\\)?(?!''')$" \
% prefix
uf_dq3string = r'(\b(%s))?"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(\\)?(?!""")$' \
% prefix
# Needed to achieve correct highlighting in Python 3.6+
# See issue 7324
if PY36_OR_MORE:
# Based on
# https://github.com/python/cpython/blob/
# 81950495ba2c36056e0ce48fd37d514816c26747/Lib/tokenize.py#L117
# In order: Hexnumber, Binnumber, Octnumber, Decnumber,
# Pointfloat + Exponent, Expfloat, Imagnumber
number_regex = [
r"\b[+-]?0[xX](?:_?[0-9A-Fa-f])+[lL]?\b",
r"\b[+-]?0[bB](?:_?[01])+[lL]?\b",
r"\b[+-]?0[oO](?:_?[0-7])+[lL]?\b",
r"\b[+-]?(?:0(?:_?0)*|[1-9](?:_?[0-9])*)[lL]?\b",
r"\b((\.[0-9](?:_?[0-9])*')|\.[0-9](?:_?[0-9])*)"
"([eE][+-]?[0-9](?:_?[0-9])*)?[jJ]?\b",
r"\b[0-9](?:_?[0-9])*([eE][+-]?[0-9](?:_?[0-9])*)?[jJ]?\b",
r"\b[0-9](?:_?[0-9])*[jJ]\b"]
number = any("number", number_regex)
string = any("string", [sq3string, dq3string, sqstring, dqstring])
ufstring1 = any("uf_sqstring", [uf_sqstring])
ufstring2 = any("uf_dqstring", [uf_dqstring])
ufstring3 = any("uf_sq3string", [uf_sq3string])
ufstring4 = any("uf_dq3string", [uf_dq3string])
return "|".join([instance, kw, builtin, comment,
ufstring1, ufstring2, ufstring3, ufstring4, string,
number, any("SYNC", [r"\n"])]) | python | def make_python_patterns(additional_keywords=[], additional_builtins=[]):
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kwlist = keyword.kwlist + additional_keywords
builtinlist = [str(name) for name in dir(builtins)
if not name.startswith('_')] + additional_builtins
repeated = set(kwlist) & set(builtinlist)
for repeated_element in repeated:
kwlist.remove(repeated_element)
kw = r"\b" + any("keyword", kwlist) + r"\b"
builtin = r"([^.'\"\\#]\b|^)" + any("builtin", builtinlist) + r"\b"
comment = any("comment", [r"#[^\n]*"])
instance = any("instance", [r"\bself\b",
r"\bcls\b",
(r"^\s*@([a-zA-Z_][a-zA-Z0-9_]*)"
r"(\.[a-zA-Z_][a-zA-Z0-9_]*)*")])
number_regex = [r"\b[+-]?[0-9]+[lLjJ]?\b",
r"\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b",
r"\b[+-]?0[oO][0-7]+[lL]?\b",
r"\b[+-]?0[bB][01]+[lL]?\b",
r"\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?[jJ]?\b"]
if PY3:
prefix = "r|u|R|U|f|F|fr|Fr|fR|FR|rf|rF|Rf|RF|b|B|br|Br|bR|BR|rb|rB|Rb|RB"
else:
prefix = "r|u|ur|R|U|UR|Ur|uR|b|B|br|Br|bR|BR"
sqstring = r"(\b(%s))?'[^'\\\n]*(\\.[^'\\\n]*)*'?" % prefix
dqstring = r'(\b(%s))?"[^"\\\n]*(\\.[^"\\\n]*)*"?' % prefix
uf_sqstring = r"(\b(%s))?'[^'\\\n]*(\\.[^'\\\n]*)*(\\)$(?!')$" % prefix
uf_dqstring = r'(\b(%s))?"[^"\\\n]*(\\.[^"\\\n]*)*(\\)$(?!")$' % prefix
sq3string = r"(\b(%s))?'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?" % prefix
dq3string = r'(\b(%s))?"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?' % prefix
uf_sq3string = r"(\b(%s))?'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(\\)?(?!''')$" \
% prefix
uf_dq3string = r'(\b(%s))?"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(\\)?(?!""")$' \
% prefix
# Needed to achieve correct highlighting in Python 3.6+
# See issue 7324
if PY36_OR_MORE:
# Based on
# https://github.com/python/cpython/blob/
# 81950495ba2c36056e0ce48fd37d514816c26747/Lib/tokenize.py#L117
# In order: Hexnumber, Binnumber, Octnumber, Decnumber,
# Pointfloat + Exponent, Expfloat, Imagnumber
number_regex = [
r"\b[+-]?0[xX](?:_?[0-9A-Fa-f])+[lL]?\b",
r"\b[+-]?0[bB](?:_?[01])+[lL]?\b",
r"\b[+-]?0[oO](?:_?[0-7])+[lL]?\b",
r"\b[+-]?(?:0(?:_?0)*|[1-9](?:_?[0-9])*)[lL]?\b",
r"\b((\.[0-9](?:_?[0-9])*')|\.[0-9](?:_?[0-9])*)"
"([eE][+-]?[0-9](?:_?[0-9])*)?[jJ]?\b",
r"\b[0-9](?:_?[0-9])*([eE][+-]?[0-9](?:_?[0-9])*)?[jJ]?\b",
r"\b[0-9](?:_?[0-9])*[jJ]\b"]
number = any("number", number_regex)
string = any("string", [sq3string, dq3string, sqstring, dqstring])
ufstring1 = any("uf_sqstring", [uf_sqstring])
ufstring2 = any("uf_dqstring", [uf_dqstring])
ufstring3 = any("uf_sq3string", [uf_sq3string])
ufstring4 = any("uf_dq3string", [uf_dq3string])
return "|".join([instance, kw, builtin, comment,
ufstring1, ufstring2, ufstring3, ufstring4, string,
number, any("SYNC", [r"\n"])]) | [
"def",
"make_python_patterns",
"(",
"additional_keywords",
"=",
"[",
"]",
",",
"additional_builtins",
"=",
"[",
"]",
")",
":",
"kwlist",
"=",
"keyword",
".",
"kwlist",
"+",
"additional_keywords",
"builtinlist",
"=",
"[",
"str",
"(",
"name",
")",
"for",
"name",
"in",
"dir",
"(",
"builtins",
")",
"if",
"not",
"name",
".",
"startswith",
"(",
"'_'",
")",
"]",
"+",
"additional_builtins",
"repeated",
"=",
"set",
"(",
"kwlist",
")",
"&",
"set",
"(",
"builtinlist",
")",
"for",
"repeated_element",
"in",
"repeated",
":",
"kwlist",
".",
"remove",
"(",
"repeated_element",
")",
"kw",
"=",
"r\"\\b\"",
"+",
"any",
"(",
"\"keyword\"",
",",
"kwlist",
")",
"+",
"r\"\\b\"",
"builtin",
"=",
"r\"([^.'\\\"\\\\#]\\b|^)\"",
"+",
"any",
"(",
"\"builtin\"",
",",
"builtinlist",
")",
"+",
"r\"\\b\"",
"comment",
"=",
"any",
"(",
"\"comment\"",
",",
"[",
"r\"#[^\\n]*\"",
"]",
")",
"instance",
"=",
"any",
"(",
"\"instance\"",
",",
"[",
"r\"\\bself\\b\"",
",",
"r\"\\bcls\\b\"",
",",
"(",
"r\"^\\s*@([a-zA-Z_][a-zA-Z0-9_]*)\"",
"r\"(\\.[a-zA-Z_][a-zA-Z0-9_]*)*\"",
")",
"]",
")",
"number_regex",
"=",
"[",
"r\"\\b[+-]?[0-9]+[lLjJ]?\\b\"",
",",
"r\"\\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\\b\"",
",",
"r\"\\b[+-]?0[oO][0-7]+[lL]?\\b\"",
",",
"r\"\\b[+-]?0[bB][01]+[lL]?\\b\"",
",",
"r\"\\b[+-]?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?[jJ]?\\b\"",
"]",
"if",
"PY3",
":",
"prefix",
"=",
"\"r|u|R|U|f|F|fr|Fr|fR|FR|rf|rF|Rf|RF|b|B|br|Br|bR|BR|rb|rB|Rb|RB\"",
"else",
":",
"prefix",
"=",
"\"r|u|ur|R|U|UR|Ur|uR|b|B|br|Br|bR|BR\"",
"sqstring",
"=",
"r\"(\\b(%s))?'[^'\\\\\\n]*(\\\\.[^'\\\\\\n]*)*'?\"",
"%",
"prefix",
"dqstring",
"=",
"r'(\\b(%s))?\"[^\"\\\\\\n]*(\\\\.[^\"\\\\\\n]*)*\"?'",
"%",
"prefix",
"uf_sqstring",
"=",
"r\"(\\b(%s))?'[^'\\\\\\n]*(\\\\.[^'\\\\\\n]*)*(\\\\)$(?!')$\"",
"%",
"prefix",
"uf_dqstring",
"=",
"r'(\\b(%s))?\"[^\"\\\\\\n]*(\\\\.[^\"\\\\\\n]*)*(\\\\)$(?!\")$'",
"%",
"prefix",
"sq3string",
"=",
"r\"(\\b(%s))?'''[^'\\\\]*((\\\\.|'(?!''))[^'\\\\]*)*(''')?\"",
"%",
"prefix",
"dq3string",
"=",
"r'(\\b(%s))?\"\"\"[^\"\\\\]*((\\\\.|\"(?!\"\"))[^\"\\\\]*)*(\"\"\")?'",
"%",
"prefix",
"uf_sq3string",
"=",
"r\"(\\b(%s))?'''[^'\\\\]*((\\\\.|'(?!''))[^'\\\\]*)*(\\\\)?(?!''')$\"",
"",
"%",
"prefix",
"uf_dq3string",
"=",
"r'(\\b(%s))?\"\"\"[^\"\\\\]*((\\\\.|\"(?!\"\"))[^\"\\\\]*)*(\\\\)?(?!\"\"\")$'",
"%",
"prefix",
"# Needed to achieve correct highlighting in Python 3.6+\r",
"# See issue 7324\r",
"if",
"PY36_OR_MORE",
":",
"# Based on\r",
"# https://github.com/python/cpython/blob/\r",
"# 81950495ba2c36056e0ce48fd37d514816c26747/Lib/tokenize.py#L117\r",
"# In order: Hexnumber, Binnumber, Octnumber, Decnumber,\r",
"# Pointfloat + Exponent, Expfloat, Imagnumber\r",
"number_regex",
"=",
"[",
"r\"\\b[+-]?0[xX](?:_?[0-9A-Fa-f])+[lL]?\\b\"",
",",
"r\"\\b[+-]?0[bB](?:_?[01])+[lL]?\\b\"",
",",
"r\"\\b[+-]?0[oO](?:_?[0-7])+[lL]?\\b\"",
",",
"r\"\\b[+-]?(?:0(?:_?0)*|[1-9](?:_?[0-9])*)[lL]?\\b\"",
",",
"r\"\\b((\\.[0-9](?:_?[0-9])*')|\\.[0-9](?:_?[0-9])*)\"",
"\"([eE][+-]?[0-9](?:_?[0-9])*)?[jJ]?\\b\"",
",",
"r\"\\b[0-9](?:_?[0-9])*([eE][+-]?[0-9](?:_?[0-9])*)?[jJ]?\\b\"",
",",
"r\"\\b[0-9](?:_?[0-9])*[jJ]\\b\"",
"]",
"number",
"=",
"any",
"(",
"\"number\"",
",",
"number_regex",
")",
"string",
"=",
"any",
"(",
"\"string\"",
",",
"[",
"sq3string",
",",
"dq3string",
",",
"sqstring",
",",
"dqstring",
"]",
")",
"ufstring1",
"=",
"any",
"(",
"\"uf_sqstring\"",
",",
"[",
"uf_sqstring",
"]",
")",
"ufstring2",
"=",
"any",
"(",
"\"uf_dqstring\"",
",",
"[",
"uf_dqstring",
"]",
")",
"ufstring3",
"=",
"any",
"(",
"\"uf_sq3string\"",
",",
"[",
"uf_sq3string",
"]",
")",
"ufstring4",
"=",
"any",
"(",
"\"uf_dq3string\"",
",",
"[",
"uf_dq3string",
"]",
")",
"return",
"\"|\"",
".",
"join",
"(",
"[",
"instance",
",",
"kw",
",",
"builtin",
",",
"comment",
",",
"ufstring1",
",",
"ufstring2",
",",
"ufstring3",
",",
"ufstring4",
",",
"string",
",",
"number",
",",
"any",
"(",
"\"SYNC\"",
",",
"[",
"r\"\\n\"",
"]",
")",
"]",
")"
] | Strongly inspired from idlelib.ColorDelegator.make_pat | [
"Strongly",
"inspired",
"from",
"idlelib",
".",
"ColorDelegator",
".",
"make_pat"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L329-L389 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | get_code_cell_name | def get_code_cell_name(text):
"""Returns a code cell name from a code cell comment."""
name = text.strip().lstrip("#% ")
if name.startswith("<codecell>"):
name = name[10:].lstrip()
elif name.startswith("In["):
name = name[2:]
if name.endswith("]:"):
name = name[:-1]
name = name.strip()
return name | python | def get_code_cell_name(text):
"""Returns a code cell name from a code cell comment."""
name = text.strip().lstrip("#% ")
if name.startswith("<codecell>"):
name = name[10:].lstrip()
elif name.startswith("In["):
name = name[2:]
if name.endswith("]:"):
name = name[:-1]
name = name.strip()
return name | [
"def",
"get_code_cell_name",
"(",
"text",
")",
":",
"name",
"=",
"text",
".",
"strip",
"(",
")",
".",
"lstrip",
"(",
"\"#% \"",
")",
"if",
"name",
".",
"startswith",
"(",
"\"<codecell>\"",
")",
":",
"name",
"=",
"name",
"[",
"10",
":",
"]",
".",
"lstrip",
"(",
")",
"elif",
"name",
".",
"startswith",
"(",
"\"In[\"",
")",
":",
"name",
"=",
"name",
"[",
"2",
":",
"]",
"if",
"name",
".",
"endswith",
"(",
"\"]:\"",
")",
":",
"name",
"=",
"name",
"[",
":",
"-",
"1",
"]",
"name",
"=",
"name",
".",
"strip",
"(",
")",
"return",
"name"
] | Returns a code cell name from a code cell comment. | [
"Returns",
"a",
"code",
"cell",
"name",
"from",
"a",
"code",
"cell",
"comment",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L392-L402 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | make_generic_c_patterns | def make_generic_c_patterns(keywords, builtins,
instance=None, define=None, comment=None):
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kw = r"\b" + any("keyword", keywords.split()) + r"\b"
builtin = r"\b" + any("builtin", builtins.split()+C_TYPES.split()) + r"\b"
if comment is None:
comment = any("comment", [r"//[^\n]*", r"\/\*(.*?)\*\/"])
comment_start = any("comment_start", [r"\/\*"])
comment_end = any("comment_end", [r"\*\/"])
if instance is None:
instance = any("instance", [r"\bthis\b"])
number = any("number",
[r"\b[+-]?[0-9]+[lL]?\b",
r"\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b",
r"\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"])
sqstring = r"(\b[rRuU])?'[^'\\\n]*(\\.[^'\\\n]*)*'?"
dqstring = r'(\b[rRuU])?"[^"\\\n]*(\\.[^"\\\n]*)*"?'
string = any("string", [sqstring, dqstring])
if define is None:
define = any("define", [r"#[^\n]*"])
return "|".join([instance, kw, comment, string, number,
comment_start, comment_end, builtin,
define, any("SYNC", [r"\n"])]) | python | def make_generic_c_patterns(keywords, builtins,
instance=None, define=None, comment=None):
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kw = r"\b" + any("keyword", keywords.split()) + r"\b"
builtin = r"\b" + any("builtin", builtins.split()+C_TYPES.split()) + r"\b"
if comment is None:
comment = any("comment", [r"//[^\n]*", r"\/\*(.*?)\*\/"])
comment_start = any("comment_start", [r"\/\*"])
comment_end = any("comment_end", [r"\*\/"])
if instance is None:
instance = any("instance", [r"\bthis\b"])
number = any("number",
[r"\b[+-]?[0-9]+[lL]?\b",
r"\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b",
r"\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"])
sqstring = r"(\b[rRuU])?'[^'\\\n]*(\\.[^'\\\n]*)*'?"
dqstring = r'(\b[rRuU])?"[^"\\\n]*(\\.[^"\\\n]*)*"?'
string = any("string", [sqstring, dqstring])
if define is None:
define = any("define", [r"#[^\n]*"])
return "|".join([instance, kw, comment, string, number,
comment_start, comment_end, builtin,
define, any("SYNC", [r"\n"])]) | [
"def",
"make_generic_c_patterns",
"(",
"keywords",
",",
"builtins",
",",
"instance",
"=",
"None",
",",
"define",
"=",
"None",
",",
"comment",
"=",
"None",
")",
":",
"kw",
"=",
"r\"\\b\"",
"+",
"any",
"(",
"\"keyword\"",
",",
"keywords",
".",
"split",
"(",
")",
")",
"+",
"r\"\\b\"",
"builtin",
"=",
"r\"\\b\"",
"+",
"any",
"(",
"\"builtin\"",
",",
"builtins",
".",
"split",
"(",
")",
"+",
"C_TYPES",
".",
"split",
"(",
")",
")",
"+",
"r\"\\b\"",
"if",
"comment",
"is",
"None",
":",
"comment",
"=",
"any",
"(",
"\"comment\"",
",",
"[",
"r\"//[^\\n]*\"",
",",
"r\"\\/\\*(.*?)\\*\\/\"",
"]",
")",
"comment_start",
"=",
"any",
"(",
"\"comment_start\"",
",",
"[",
"r\"\\/\\*\"",
"]",
")",
"comment_end",
"=",
"any",
"(",
"\"comment_end\"",
",",
"[",
"r\"\\*\\/\"",
"]",
")",
"if",
"instance",
"is",
"None",
":",
"instance",
"=",
"any",
"(",
"\"instance\"",
",",
"[",
"r\"\\bthis\\b\"",
"]",
")",
"number",
"=",
"any",
"(",
"\"number\"",
",",
"[",
"r\"\\b[+-]?[0-9]+[lL]?\\b\"",
",",
"r\"\\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\\b\"",
",",
"r\"\\b[+-]?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b\"",
"]",
")",
"sqstring",
"=",
"r\"(\\b[rRuU])?'[^'\\\\\\n]*(\\\\.[^'\\\\\\n]*)*'?\"",
"dqstring",
"=",
"r'(\\b[rRuU])?\"[^\"\\\\\\n]*(\\\\.[^\"\\\\\\n]*)*\"?'",
"string",
"=",
"any",
"(",
"\"string\"",
",",
"[",
"sqstring",
",",
"dqstring",
"]",
")",
"if",
"define",
"is",
"None",
":",
"define",
"=",
"any",
"(",
"\"define\"",
",",
"[",
"r\"#[^\\n]*\"",
"]",
")",
"return",
"\"|\"",
".",
"join",
"(",
"[",
"instance",
",",
"kw",
",",
"comment",
",",
"string",
",",
"number",
",",
"comment_start",
",",
"comment_end",
",",
"builtin",
",",
"define",
",",
"any",
"(",
"\"SYNC\"",
",",
"[",
"r\"\\n\"",
"]",
")",
"]",
")"
] | Strongly inspired from idlelib.ColorDelegator.make_pat | [
"Strongly",
"inspired",
"from",
"idlelib",
".",
"ColorDelegator",
".",
"make_pat"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L607-L629 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | make_fortran_patterns | def make_fortran_patterns():
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kwstr = 'access action advance allocatable allocate apostrophe assign assignment associate asynchronous backspace bind blank blockdata call case character class close common complex contains continue cycle data deallocate decimal delim default dimension direct do dowhile double doubleprecision else elseif elsewhere encoding end endassociate endblockdata enddo endfile endforall endfunction endif endinterface endmodule endprogram endselect endsubroutine endtype endwhere entry eor equivalence err errmsg exist exit external file flush fmt forall form format formatted function go goto id if implicit in include inout integer inquire intent interface intrinsic iomsg iolength iostat kind len logical module name named namelist nextrec nml none nullify number only open opened operator optional out pad parameter pass pause pending pointer pos position precision print private program protected public quote read readwrite real rec recl recursive result return rewind save select selectcase selecttype sequential sign size stat status stop stream subroutine target then to type unformatted unit use value volatile wait where while write'
bistr1 = 'abs achar acos acosd adjustl adjustr aimag aimax0 aimin0 aint ajmax0 ajmin0 akmax0 akmin0 all allocated alog alog10 amax0 amax1 amin0 amin1 amod anint any asin asind associated atan atan2 atan2d atand bitest bitl bitlr bitrl bjtest bit_size bktest break btest cabs ccos cdabs cdcos cdexp cdlog cdsin cdsqrt ceiling cexp char clog cmplx conjg cos cosd cosh count cpu_time cshift csin csqrt dabs dacos dacosd dasin dasind datan datan2 datan2d datand date date_and_time dble dcmplx dconjg dcos dcosd dcosh dcotan ddim dexp dfloat dflotk dfloti dflotj digits dim dimag dint dlog dlog10 dmax1 dmin1 dmod dnint dot_product dprod dreal dsign dsin dsind dsinh dsqrt dtan dtand dtanh eoshift epsilon errsns exp exponent float floati floatj floatk floor fraction free huge iabs iachar iand ibclr ibits ibset ichar idate idim idint idnint ieor ifix iiabs iiand iibclr iibits iibset iidim iidint iidnnt iieor iifix iint iior iiqint iiqnnt iishft iishftc iisign ilen imax0 imax1 imin0 imin1 imod index inint inot int int1 int2 int4 int8 iqint iqnint ior ishft ishftc isign isnan izext jiand jibclr jibits jibset jidim jidint jidnnt jieor jifix jint jior jiqint jiqnnt jishft jishftc jisign jmax0 jmax1 jmin0 jmin1 jmod jnint jnot jzext kiabs kiand kibclr kibits kibset kidim kidint kidnnt kieor kifix kind kint kior kishft kishftc kisign kmax0 kmax1 kmin0 kmin1 kmod knint knot kzext lbound leadz len len_trim lenlge lge lgt lle llt log log10 logical lshift malloc matmul max max0 max1 maxexponent maxloc maxval merge min min0 min1 minexponent minloc minval mod modulo mvbits nearest nint not nworkers number_of_processors pack popcnt poppar precision present product radix random random_number random_seed range real repeat reshape rrspacing rshift scale scan secnds selected_int_kind selected_real_kind set_exponent shape sign sin sind sinh size sizeof sngl snglq spacing spread sqrt sum system_clock tan tand tanh tiny transfer transpose trim ubound unpack verify'
bistr2 = 'cdabs cdcos cdexp cdlog cdsin cdsqrt cotan cotand dcmplx dconjg dcotan dcotand decode dimag dll_export dll_import doublecomplex dreal dvchk encode find flen flush getarg getcharqq getcl getdat getenv gettim hfix ibchng identifier imag int1 int2 int4 intc intrup invalop iostat_msg isha ishc ishl jfix lacfar locking locnear map nargs nbreak ndperr ndpexc offset ovefl peekcharqq precfill prompt qabs qacos qacosd qasin qasind qatan qatand qatan2 qcmplx qconjg qcos qcosd qcosh qdim qexp qext qextd qfloat qimag qlog qlog10 qmax1 qmin1 qmod qreal qsign qsin qsind qsinh qsqrt qtan qtand qtanh ran rand randu rewrite segment setdat settim system timer undfl unlock union val virtual volatile zabs zcos zexp zlog zsin zsqrt'
kw = r"\b" + any("keyword", kwstr.split()) + r"\b"
builtin = r"\b" + any("builtin", bistr1.split()+bistr2.split()) + r"\b"
comment = any("comment", [r"\![^\n]*"])
number = any("number",
[r"\b[+-]?[0-9]+[lL]?\b",
r"\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b",
r"\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"])
sqstring = r"(\b[rRuU])?'[^'\\\n]*(\\.[^'\\\n]*)*'?"
dqstring = r'(\b[rRuU])?"[^"\\\n]*(\\.[^"\\\n]*)*"?'
string = any("string", [sqstring, dqstring])
return "|".join([kw, comment, string, number, builtin,
any("SYNC", [r"\n"])]) | python | def make_fortran_patterns():
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kwstr = 'access action advance allocatable allocate apostrophe assign assignment associate asynchronous backspace bind blank blockdata call case character class close common complex contains continue cycle data deallocate decimal delim default dimension direct do dowhile double doubleprecision else elseif elsewhere encoding end endassociate endblockdata enddo endfile endforall endfunction endif endinterface endmodule endprogram endselect endsubroutine endtype endwhere entry eor equivalence err errmsg exist exit external file flush fmt forall form format formatted function go goto id if implicit in include inout integer inquire intent interface intrinsic iomsg iolength iostat kind len logical module name named namelist nextrec nml none nullify number only open opened operator optional out pad parameter pass pause pending pointer pos position precision print private program protected public quote read readwrite real rec recl recursive result return rewind save select selectcase selecttype sequential sign size stat status stop stream subroutine target then to type unformatted unit use value volatile wait where while write'
bistr1 = 'abs achar acos acosd adjustl adjustr aimag aimax0 aimin0 aint ajmax0 ajmin0 akmax0 akmin0 all allocated alog alog10 amax0 amax1 amin0 amin1 amod anint any asin asind associated atan atan2 atan2d atand bitest bitl bitlr bitrl bjtest bit_size bktest break btest cabs ccos cdabs cdcos cdexp cdlog cdsin cdsqrt ceiling cexp char clog cmplx conjg cos cosd cosh count cpu_time cshift csin csqrt dabs dacos dacosd dasin dasind datan datan2 datan2d datand date date_and_time dble dcmplx dconjg dcos dcosd dcosh dcotan ddim dexp dfloat dflotk dfloti dflotj digits dim dimag dint dlog dlog10 dmax1 dmin1 dmod dnint dot_product dprod dreal dsign dsin dsind dsinh dsqrt dtan dtand dtanh eoshift epsilon errsns exp exponent float floati floatj floatk floor fraction free huge iabs iachar iand ibclr ibits ibset ichar idate idim idint idnint ieor ifix iiabs iiand iibclr iibits iibset iidim iidint iidnnt iieor iifix iint iior iiqint iiqnnt iishft iishftc iisign ilen imax0 imax1 imin0 imin1 imod index inint inot int int1 int2 int4 int8 iqint iqnint ior ishft ishftc isign isnan izext jiand jibclr jibits jibset jidim jidint jidnnt jieor jifix jint jior jiqint jiqnnt jishft jishftc jisign jmax0 jmax1 jmin0 jmin1 jmod jnint jnot jzext kiabs kiand kibclr kibits kibset kidim kidint kidnnt kieor kifix kind kint kior kishft kishftc kisign kmax0 kmax1 kmin0 kmin1 kmod knint knot kzext lbound leadz len len_trim lenlge lge lgt lle llt log log10 logical lshift malloc matmul max max0 max1 maxexponent maxloc maxval merge min min0 min1 minexponent minloc minval mod modulo mvbits nearest nint not nworkers number_of_processors pack popcnt poppar precision present product radix random random_number random_seed range real repeat reshape rrspacing rshift scale scan secnds selected_int_kind selected_real_kind set_exponent shape sign sin sind sinh size sizeof sngl snglq spacing spread sqrt sum system_clock tan tand tanh tiny transfer transpose trim ubound unpack verify'
bistr2 = 'cdabs cdcos cdexp cdlog cdsin cdsqrt cotan cotand dcmplx dconjg dcotan dcotand decode dimag dll_export dll_import doublecomplex dreal dvchk encode find flen flush getarg getcharqq getcl getdat getenv gettim hfix ibchng identifier imag int1 int2 int4 intc intrup invalop iostat_msg isha ishc ishl jfix lacfar locking locnear map nargs nbreak ndperr ndpexc offset ovefl peekcharqq precfill prompt qabs qacos qacosd qasin qasind qatan qatand qatan2 qcmplx qconjg qcos qcosd qcosh qdim qexp qext qextd qfloat qimag qlog qlog10 qmax1 qmin1 qmod qreal qsign qsin qsind qsinh qsqrt qtan qtand qtanh ran rand randu rewrite segment setdat settim system timer undfl unlock union val virtual volatile zabs zcos zexp zlog zsin zsqrt'
kw = r"\b" + any("keyword", kwstr.split()) + r"\b"
builtin = r"\b" + any("builtin", bistr1.split()+bistr2.split()) + r"\b"
comment = any("comment", [r"\![^\n]*"])
number = any("number",
[r"\b[+-]?[0-9]+[lL]?\b",
r"\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b",
r"\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"])
sqstring = r"(\b[rRuU])?'[^'\\\n]*(\\.[^'\\\n]*)*'?"
dqstring = r'(\b[rRuU])?"[^"\\\n]*(\\.[^"\\\n]*)*"?'
string = any("string", [sqstring, dqstring])
return "|".join([kw, comment, string, number, builtin,
any("SYNC", [r"\n"])]) | [
"def",
"make_fortran_patterns",
"(",
")",
":",
"kwstr",
"=",
"'access action advance allocatable allocate apostrophe assign assignment associate asynchronous backspace bind blank blockdata call case character class close common complex contains continue cycle data deallocate decimal delim default dimension direct do dowhile double doubleprecision else elseif elsewhere encoding end endassociate endblockdata enddo endfile endforall endfunction endif endinterface endmodule endprogram endselect endsubroutine endtype endwhere entry eor equivalence err errmsg exist exit external file flush fmt forall form format formatted function go goto id if implicit in include inout integer inquire intent interface intrinsic iomsg iolength iostat kind len logical module name named namelist nextrec nml none nullify number only open opened operator optional out pad parameter pass pause pending pointer pos position precision print private program protected public quote read readwrite real rec recl recursive result return rewind save select selectcase selecttype sequential sign size stat status stop stream subroutine target then to type unformatted unit use value volatile wait where while write'",
"bistr1",
"=",
"'abs achar acos acosd adjustl adjustr aimag aimax0 aimin0 aint ajmax0 ajmin0 akmax0 akmin0 all allocated alog alog10 amax0 amax1 amin0 amin1 amod anint any asin asind associated atan atan2 atan2d atand bitest bitl bitlr bitrl bjtest bit_size bktest break btest cabs ccos cdabs cdcos cdexp cdlog cdsin cdsqrt ceiling cexp char clog cmplx conjg cos cosd cosh count cpu_time cshift csin csqrt dabs dacos dacosd dasin dasind datan datan2 datan2d datand date date_and_time dble dcmplx dconjg dcos dcosd dcosh dcotan ddim dexp dfloat dflotk dfloti dflotj digits dim dimag dint dlog dlog10 dmax1 dmin1 dmod dnint dot_product dprod dreal dsign dsin dsind dsinh dsqrt dtan dtand dtanh eoshift epsilon errsns exp exponent float floati floatj floatk floor fraction free huge iabs iachar iand ibclr ibits ibset ichar idate idim idint idnint ieor ifix iiabs iiand iibclr iibits iibset iidim iidint iidnnt iieor iifix iint iior iiqint iiqnnt iishft iishftc iisign ilen imax0 imax1 imin0 imin1 imod index inint inot int int1 int2 int4 int8 iqint iqnint ior ishft ishftc isign isnan izext jiand jibclr jibits jibset jidim jidint jidnnt jieor jifix jint jior jiqint jiqnnt jishft jishftc jisign jmax0 jmax1 jmin0 jmin1 jmod jnint jnot jzext kiabs kiand kibclr kibits kibset kidim kidint kidnnt kieor kifix kind kint kior kishft kishftc kisign kmax0 kmax1 kmin0 kmin1 kmod knint knot kzext lbound leadz len len_trim lenlge lge lgt lle llt log log10 logical lshift malloc matmul max max0 max1 maxexponent maxloc maxval merge min min0 min1 minexponent minloc minval mod modulo mvbits nearest nint not nworkers number_of_processors pack popcnt poppar precision present product radix random random_number random_seed range real repeat reshape rrspacing rshift scale scan secnds selected_int_kind selected_real_kind set_exponent shape sign sin sind sinh size sizeof sngl snglq spacing spread sqrt sum system_clock tan tand tanh tiny transfer transpose trim ubound unpack verify'",
"bistr2",
"=",
"'cdabs cdcos cdexp cdlog cdsin cdsqrt cotan cotand dcmplx dconjg dcotan dcotand decode dimag dll_export dll_import doublecomplex dreal dvchk encode find flen flush getarg getcharqq getcl getdat getenv gettim hfix ibchng identifier imag int1 int2 int4 intc intrup invalop iostat_msg isha ishc ishl jfix lacfar locking locnear map nargs nbreak ndperr ndpexc offset ovefl peekcharqq precfill prompt qabs qacos qacosd qasin qasind qatan qatand qatan2 qcmplx qconjg qcos qcosd qcosh qdim qexp qext qextd qfloat qimag qlog qlog10 qmax1 qmin1 qmod qreal qsign qsin qsind qsinh qsqrt qtan qtand qtanh ran rand randu rewrite segment setdat settim system timer undfl unlock union val virtual volatile zabs zcos zexp zlog zsin zsqrt'",
"kw",
"=",
"r\"\\b\"",
"+",
"any",
"(",
"\"keyword\"",
",",
"kwstr",
".",
"split",
"(",
")",
")",
"+",
"r\"\\b\"",
"builtin",
"=",
"r\"\\b\"",
"+",
"any",
"(",
"\"builtin\"",
",",
"bistr1",
".",
"split",
"(",
")",
"+",
"bistr2",
".",
"split",
"(",
")",
")",
"+",
"r\"\\b\"",
"comment",
"=",
"any",
"(",
"\"comment\"",
",",
"[",
"r\"\\![^\\n]*\"",
"]",
")",
"number",
"=",
"any",
"(",
"\"number\"",
",",
"[",
"r\"\\b[+-]?[0-9]+[lL]?\\b\"",
",",
"r\"\\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\\b\"",
",",
"r\"\\b[+-]?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b\"",
"]",
")",
"sqstring",
"=",
"r\"(\\b[rRuU])?'[^'\\\\\\n]*(\\\\.[^'\\\\\\n]*)*'?\"",
"dqstring",
"=",
"r'(\\b[rRuU])?\"[^\"\\\\\\n]*(\\\\.[^\"\\\\\\n]*)*\"?'",
"string",
"=",
"any",
"(",
"\"string\"",
",",
"[",
"sqstring",
",",
"dqstring",
"]",
")",
"return",
"\"|\"",
".",
"join",
"(",
"[",
"kw",
",",
"comment",
",",
"string",
",",
"number",
",",
"builtin",
",",
"any",
"(",
"\"SYNC\"",
",",
"[",
"r\"\\n\"",
"]",
")",
"]",
")"
] | Strongly inspired from idlelib.ColorDelegator.make_pat | [
"Strongly",
"inspired",
"from",
"idlelib",
".",
"ColorDelegator",
".",
"make_pat"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L705-L721 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | make_nsis_patterns | def make_nsis_patterns():
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kwstr1 = 'Abort AddBrandingImage AddSize AllowRootDirInstall AllowSkipFiles AutoCloseWindow BGFont BGGradient BrandingText BringToFront Call CallInstDLL Caption ClearErrors CompletedText ComponentText CopyFiles CRCCheck CreateDirectory CreateFont CreateShortCut Delete DeleteINISec DeleteINIStr DeleteRegKey DeleteRegValue DetailPrint DetailsButtonText DirText DirVar DirVerify EnableWindow EnumRegKey EnumRegValue Exec ExecShell ExecWait Exch ExpandEnvStrings File FileBufSize FileClose FileErrorText FileOpen FileRead FileReadByte FileSeek FileWrite FileWriteByte FindClose FindFirst FindNext FindWindow FlushINI Function FunctionEnd GetCurInstType GetCurrentAddress GetDlgItem GetDLLVersion GetDLLVersionLocal GetErrorLevel GetFileTime GetFileTimeLocal GetFullPathName GetFunctionAddress GetInstDirError GetLabelAddress GetTempFileName Goto HideWindow ChangeUI CheckBitmap Icon IfAbort IfErrors IfFileExists IfRebootFlag IfSilent InitPluginsDir InstallButtonText InstallColors InstallDir InstallDirRegKey InstProgressFlags InstType InstTypeGetText InstTypeSetText IntCmp IntCmpU IntFmt IntOp IsWindow LangString LicenseBkColor LicenseData LicenseForceSelection LicenseLangString LicenseText LoadLanguageFile LogSet LogText MessageBox MiscButtonText Name OutFile Page PageCallbacks PageEx PageExEnd Pop Push Quit ReadEnvStr ReadINIStr ReadRegDWORD ReadRegStr Reboot RegDLL Rename ReserveFile Return RMDir SearchPath Section SectionEnd SectionGetFlags SectionGetInstTypes SectionGetSize SectionGetText SectionIn SectionSetFlags SectionSetInstTypes SectionSetSize SectionSetText SendMessage SetAutoClose SetBrandingImage SetCompress SetCompressor SetCompressorDictSize SetCtlColors SetCurInstType SetDatablockOptimize SetDateSave SetDetailsPrint SetDetailsView SetErrorLevel SetErrors SetFileAttributes SetFont SetOutPath SetOverwrite SetPluginUnload SetRebootFlag SetShellVarContext SetSilent ShowInstDetails ShowUninstDetails ShowWindow SilentInstall SilentUnInstall Sleep SpaceTexts StrCmp StrCpy StrLen SubCaption SubSection SubSectionEnd UninstallButtonText UninstallCaption UninstallIcon UninstallSubCaption UninstallText UninstPage UnRegDLL Var VIAddVersionKey VIProductVersion WindowIcon WriteINIStr WriteRegBin WriteRegDWORD WriteRegExpandStr WriteRegStr WriteUninstaller XPStyle'
kwstr2 = 'all alwaysoff ARCHIVE auto both bzip2 components current custom details directory false FILE_ATTRIBUTE_ARCHIVE FILE_ATTRIBUTE_HIDDEN FILE_ATTRIBUTE_NORMAL FILE_ATTRIBUTE_OFFLINE FILE_ATTRIBUTE_READONLY FILE_ATTRIBUTE_SYSTEM FILE_ATTRIBUTE_TEMPORARY force grey HIDDEN hide IDABORT IDCANCEL IDIGNORE IDNO IDOK IDRETRY IDYES ifdiff ifnewer instfiles instfiles lastused leave left level license listonly lzma manual MB_ABORTRETRYIGNORE MB_DEFBUTTON1 MB_DEFBUTTON2 MB_DEFBUTTON3 MB_DEFBUTTON4 MB_ICONEXCLAMATION MB_ICONINFORMATION MB_ICONQUESTION MB_ICONSTOP MB_OK MB_OKCANCEL MB_RETRYCANCEL MB_RIGHT MB_SETFOREGROUND MB_TOPMOST MB_YESNO MB_YESNOCANCEL nevershow none NORMAL off OFFLINE on READONLY right RO show silent silentlog SYSTEM TEMPORARY text textonly true try uninstConfirm windows zlib'
kwstr3 = 'MUI_ABORTWARNING MUI_ABORTWARNING_CANCEL_DEFAULT MUI_ABORTWARNING_TEXT MUI_BGCOLOR MUI_COMPONENTSPAGE_CHECKBITMAP MUI_COMPONENTSPAGE_NODESC MUI_COMPONENTSPAGE_SMALLDESC MUI_COMPONENTSPAGE_TEXT_COMPLIST MUI_COMPONENTSPAGE_TEXT_DESCRIPTION_INFO MUI_COMPONENTSPAGE_TEXT_DESCRIPTION_TITLE MUI_COMPONENTSPAGE_TEXT_INSTTYPE MUI_COMPONENTSPAGE_TEXT_TOP MUI_CUSTOMFUNCTION_ABORT MUI_CUSTOMFUNCTION_GUIINIT MUI_CUSTOMFUNCTION_UNABORT MUI_CUSTOMFUNCTION_UNGUIINIT MUI_DESCRIPTION_TEXT MUI_DIRECTORYPAGE_BGCOLOR MUI_DIRECTORYPAGE_TEXT_DESTINATION MUI_DIRECTORYPAGE_TEXT_TOP MUI_DIRECTORYPAGE_VARIABLE MUI_DIRECTORYPAGE_VERIFYONLEAVE MUI_FINISHPAGE_BUTTON MUI_FINISHPAGE_CANCEL_ENABLED MUI_FINISHPAGE_LINK MUI_FINISHPAGE_LINK_COLOR MUI_FINISHPAGE_LINK_LOCATION MUI_FINISHPAGE_NOAUTOCLOSE MUI_FINISHPAGE_NOREBOOTSUPPORT MUI_FINISHPAGE_REBOOTLATER_DEFAULT MUI_FINISHPAGE_RUN MUI_FINISHPAGE_RUN_FUNCTION MUI_FINISHPAGE_RUN_NOTCHECKED MUI_FINISHPAGE_RUN_PARAMETERS MUI_FINISHPAGE_RUN_TEXT MUI_FINISHPAGE_SHOWREADME MUI_FINISHPAGE_SHOWREADME_FUNCTION MUI_FINISHPAGE_SHOWREADME_NOTCHECKED MUI_FINISHPAGE_SHOWREADME_TEXT MUI_FINISHPAGE_TEXT MUI_FINISHPAGE_TEXT_LARGE MUI_FINISHPAGE_TEXT_REBOOT MUI_FINISHPAGE_TEXT_REBOOTLATER MUI_FINISHPAGE_TEXT_REBOOTNOW MUI_FINISHPAGE_TITLE MUI_FINISHPAGE_TITLE_3LINES MUI_FUNCTION_DESCRIPTION_BEGIN MUI_FUNCTION_DESCRIPTION_END MUI_HEADER_TEXT MUI_HEADER_TRANSPARENT_TEXT MUI_HEADERIMAGE MUI_HEADERIMAGE_BITMAP MUI_HEADERIMAGE_BITMAP_NOSTRETCH MUI_HEADERIMAGE_BITMAP_RTL MUI_HEADERIMAGE_BITMAP_RTL_NOSTRETCH MUI_HEADERIMAGE_RIGHT MUI_HEADERIMAGE_UNBITMAP MUI_HEADERIMAGE_UNBITMAP_NOSTRETCH MUI_HEADERIMAGE_UNBITMAP_RTL MUI_HEADERIMAGE_UNBITMAP_RTL_NOSTRETCH MUI_HWND MUI_ICON MUI_INSTALLCOLORS MUI_INSTALLOPTIONS_DISPLAY MUI_INSTALLOPTIONS_DISPLAY_RETURN MUI_INSTALLOPTIONS_EXTRACT MUI_INSTALLOPTIONS_EXTRACT_AS MUI_INSTALLOPTIONS_INITDIALOG MUI_INSTALLOPTIONS_READ MUI_INSTALLOPTIONS_SHOW MUI_INSTALLOPTIONS_SHOW_RETURN MUI_INSTALLOPTIONS_WRITE MUI_INSTFILESPAGE_ABORTHEADER_SUBTEXT MUI_INSTFILESPAGE_ABORTHEADER_TEXT MUI_INSTFILESPAGE_COLORS MUI_INSTFILESPAGE_FINISHHEADER_SUBTEXT MUI_INSTFILESPAGE_FINISHHEADER_TEXT MUI_INSTFILESPAGE_PROGRESSBAR MUI_LANGDLL_ALLLANGUAGES MUI_LANGDLL_ALWAYSSHOW MUI_LANGDLL_DISPLAY MUI_LANGDLL_INFO MUI_LANGDLL_REGISTRY_KEY MUI_LANGDLL_REGISTRY_ROOT MUI_LANGDLL_REGISTRY_VALUENAME MUI_LANGDLL_WINDOWTITLE MUI_LANGUAGE MUI_LICENSEPAGE_BGCOLOR MUI_LICENSEPAGE_BUTTON MUI_LICENSEPAGE_CHECKBOX MUI_LICENSEPAGE_CHECKBOX_TEXT MUI_LICENSEPAGE_RADIOBUTTONS MUI_LICENSEPAGE_RADIOBUTTONS_TEXT_ACCEPT MUI_LICENSEPAGE_RADIOBUTTONS_TEXT_DECLINE MUI_LICENSEPAGE_TEXT_BOTTOM MUI_LICENSEPAGE_TEXT_TOP MUI_PAGE_COMPONENTS MUI_PAGE_CUSTOMFUNCTION_LEAVE MUI_PAGE_CUSTOMFUNCTION_PRE MUI_PAGE_CUSTOMFUNCTION_SHOW MUI_PAGE_DIRECTORY MUI_PAGE_FINISH MUI_PAGE_HEADER_SUBTEXT MUI_PAGE_HEADER_TEXT MUI_PAGE_INSTFILES MUI_PAGE_LICENSE MUI_PAGE_STARTMENU MUI_PAGE_WELCOME MUI_RESERVEFILE_INSTALLOPTIONS MUI_RESERVEFILE_LANGDLL MUI_SPECIALINI MUI_STARTMENU_GETFOLDER MUI_STARTMENU_WRITE_BEGIN MUI_STARTMENU_WRITE_END MUI_STARTMENUPAGE_BGCOLOR MUI_STARTMENUPAGE_DEFAULTFOLDER MUI_STARTMENUPAGE_NODISABLE MUI_STARTMENUPAGE_REGISTRY_KEY MUI_STARTMENUPAGE_REGISTRY_ROOT MUI_STARTMENUPAGE_REGISTRY_VALUENAME MUI_STARTMENUPAGE_TEXT_CHECKBOX MUI_STARTMENUPAGE_TEXT_TOP MUI_UI MUI_UI_COMPONENTSPAGE_NODESC MUI_UI_COMPONENTSPAGE_SMALLDESC MUI_UI_HEADERIMAGE MUI_UI_HEADERIMAGE_RIGHT MUI_UNABORTWARNING MUI_UNABORTWARNING_CANCEL_DEFAULT MUI_UNABORTWARNING_TEXT MUI_UNCONFIRMPAGE_TEXT_LOCATION MUI_UNCONFIRMPAGE_TEXT_TOP MUI_UNFINISHPAGE_NOAUTOCLOSE MUI_UNFUNCTION_DESCRIPTION_BEGIN MUI_UNFUNCTION_DESCRIPTION_END MUI_UNGETLANGUAGE MUI_UNICON MUI_UNPAGE_COMPONENTS MUI_UNPAGE_CONFIRM MUI_UNPAGE_DIRECTORY MUI_UNPAGE_FINISH MUI_UNPAGE_INSTFILES MUI_UNPAGE_LICENSE MUI_UNPAGE_WELCOME MUI_UNWELCOMEFINISHPAGE_BITMAP MUI_UNWELCOMEFINISHPAGE_BITMAP_NOSTRETCH MUI_UNWELCOMEFINISHPAGE_INI MUI_WELCOMEFINISHPAGE_BITMAP MUI_WELCOMEFINISHPAGE_BITMAP_NOSTRETCH MUI_WELCOMEFINISHPAGE_CUSTOMFUNCTION_INIT MUI_WELCOMEFINISHPAGE_INI MUI_WELCOMEPAGE_TEXT MUI_WELCOMEPAGE_TITLE MUI_WELCOMEPAGE_TITLE_3LINES'
bistr = 'addincludedir addplugindir AndIf cd define echo else endif error execute If ifdef ifmacrodef ifmacrondef ifndef include insertmacro macro macroend onGUIEnd onGUIInit onInit onInstFailed onInstSuccess onMouseOverSection onRebootFailed onSelChange onUserAbort onVerifyInstDir OrIf packhdr system undef verbose warning'
instance = any("instance", [r'\$\{.*?\}', r'\$[A-Za-z0-9\_]*'])
define = any("define", [r"\![^\n]*"])
comment = any("comment", [r"\;[^\n]*", r"\#[^\n]*", r"\/\*(.*?)\*\/"])
return make_generic_c_patterns(kwstr1+' '+kwstr2+' '+kwstr3, bistr,
instance=instance, define=define,
comment=comment) | python | def make_nsis_patterns():
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kwstr1 = 'Abort AddBrandingImage AddSize AllowRootDirInstall AllowSkipFiles AutoCloseWindow BGFont BGGradient BrandingText BringToFront Call CallInstDLL Caption ClearErrors CompletedText ComponentText CopyFiles CRCCheck CreateDirectory CreateFont CreateShortCut Delete DeleteINISec DeleteINIStr DeleteRegKey DeleteRegValue DetailPrint DetailsButtonText DirText DirVar DirVerify EnableWindow EnumRegKey EnumRegValue Exec ExecShell ExecWait Exch ExpandEnvStrings File FileBufSize FileClose FileErrorText FileOpen FileRead FileReadByte FileSeek FileWrite FileWriteByte FindClose FindFirst FindNext FindWindow FlushINI Function FunctionEnd GetCurInstType GetCurrentAddress GetDlgItem GetDLLVersion GetDLLVersionLocal GetErrorLevel GetFileTime GetFileTimeLocal GetFullPathName GetFunctionAddress GetInstDirError GetLabelAddress GetTempFileName Goto HideWindow ChangeUI CheckBitmap Icon IfAbort IfErrors IfFileExists IfRebootFlag IfSilent InitPluginsDir InstallButtonText InstallColors InstallDir InstallDirRegKey InstProgressFlags InstType InstTypeGetText InstTypeSetText IntCmp IntCmpU IntFmt IntOp IsWindow LangString LicenseBkColor LicenseData LicenseForceSelection LicenseLangString LicenseText LoadLanguageFile LogSet LogText MessageBox MiscButtonText Name OutFile Page PageCallbacks PageEx PageExEnd Pop Push Quit ReadEnvStr ReadINIStr ReadRegDWORD ReadRegStr Reboot RegDLL Rename ReserveFile Return RMDir SearchPath Section SectionEnd SectionGetFlags SectionGetInstTypes SectionGetSize SectionGetText SectionIn SectionSetFlags SectionSetInstTypes SectionSetSize SectionSetText SendMessage SetAutoClose SetBrandingImage SetCompress SetCompressor SetCompressorDictSize SetCtlColors SetCurInstType SetDatablockOptimize SetDateSave SetDetailsPrint SetDetailsView SetErrorLevel SetErrors SetFileAttributes SetFont SetOutPath SetOverwrite SetPluginUnload SetRebootFlag SetShellVarContext SetSilent ShowInstDetails ShowUninstDetails ShowWindow SilentInstall SilentUnInstall Sleep SpaceTexts StrCmp StrCpy StrLen SubCaption SubSection SubSectionEnd UninstallButtonText UninstallCaption UninstallIcon UninstallSubCaption UninstallText UninstPage UnRegDLL Var VIAddVersionKey VIProductVersion WindowIcon WriteINIStr WriteRegBin WriteRegDWORD WriteRegExpandStr WriteRegStr WriteUninstaller XPStyle'
kwstr2 = 'all alwaysoff ARCHIVE auto both bzip2 components current custom details directory false FILE_ATTRIBUTE_ARCHIVE FILE_ATTRIBUTE_HIDDEN FILE_ATTRIBUTE_NORMAL FILE_ATTRIBUTE_OFFLINE FILE_ATTRIBUTE_READONLY FILE_ATTRIBUTE_SYSTEM FILE_ATTRIBUTE_TEMPORARY force grey HIDDEN hide IDABORT IDCANCEL IDIGNORE IDNO IDOK IDRETRY IDYES ifdiff ifnewer instfiles instfiles lastused leave left level license listonly lzma manual MB_ABORTRETRYIGNORE MB_DEFBUTTON1 MB_DEFBUTTON2 MB_DEFBUTTON3 MB_DEFBUTTON4 MB_ICONEXCLAMATION MB_ICONINFORMATION MB_ICONQUESTION MB_ICONSTOP MB_OK MB_OKCANCEL MB_RETRYCANCEL MB_RIGHT MB_SETFOREGROUND MB_TOPMOST MB_YESNO MB_YESNOCANCEL nevershow none NORMAL off OFFLINE on READONLY right RO show silent silentlog SYSTEM TEMPORARY text textonly true try uninstConfirm windows zlib'
kwstr3 = 'MUI_ABORTWARNING MUI_ABORTWARNING_CANCEL_DEFAULT MUI_ABORTWARNING_TEXT MUI_BGCOLOR MUI_COMPONENTSPAGE_CHECKBITMAP MUI_COMPONENTSPAGE_NODESC MUI_COMPONENTSPAGE_SMALLDESC MUI_COMPONENTSPAGE_TEXT_COMPLIST MUI_COMPONENTSPAGE_TEXT_DESCRIPTION_INFO MUI_COMPONENTSPAGE_TEXT_DESCRIPTION_TITLE MUI_COMPONENTSPAGE_TEXT_INSTTYPE MUI_COMPONENTSPAGE_TEXT_TOP MUI_CUSTOMFUNCTION_ABORT MUI_CUSTOMFUNCTION_GUIINIT MUI_CUSTOMFUNCTION_UNABORT MUI_CUSTOMFUNCTION_UNGUIINIT MUI_DESCRIPTION_TEXT MUI_DIRECTORYPAGE_BGCOLOR MUI_DIRECTORYPAGE_TEXT_DESTINATION MUI_DIRECTORYPAGE_TEXT_TOP MUI_DIRECTORYPAGE_VARIABLE MUI_DIRECTORYPAGE_VERIFYONLEAVE MUI_FINISHPAGE_BUTTON MUI_FINISHPAGE_CANCEL_ENABLED MUI_FINISHPAGE_LINK MUI_FINISHPAGE_LINK_COLOR MUI_FINISHPAGE_LINK_LOCATION MUI_FINISHPAGE_NOAUTOCLOSE MUI_FINISHPAGE_NOREBOOTSUPPORT MUI_FINISHPAGE_REBOOTLATER_DEFAULT MUI_FINISHPAGE_RUN MUI_FINISHPAGE_RUN_FUNCTION MUI_FINISHPAGE_RUN_NOTCHECKED MUI_FINISHPAGE_RUN_PARAMETERS MUI_FINISHPAGE_RUN_TEXT MUI_FINISHPAGE_SHOWREADME MUI_FINISHPAGE_SHOWREADME_FUNCTION MUI_FINISHPAGE_SHOWREADME_NOTCHECKED MUI_FINISHPAGE_SHOWREADME_TEXT MUI_FINISHPAGE_TEXT MUI_FINISHPAGE_TEXT_LARGE MUI_FINISHPAGE_TEXT_REBOOT MUI_FINISHPAGE_TEXT_REBOOTLATER MUI_FINISHPAGE_TEXT_REBOOTNOW MUI_FINISHPAGE_TITLE MUI_FINISHPAGE_TITLE_3LINES MUI_FUNCTION_DESCRIPTION_BEGIN MUI_FUNCTION_DESCRIPTION_END MUI_HEADER_TEXT MUI_HEADER_TRANSPARENT_TEXT MUI_HEADERIMAGE MUI_HEADERIMAGE_BITMAP MUI_HEADERIMAGE_BITMAP_NOSTRETCH MUI_HEADERIMAGE_BITMAP_RTL MUI_HEADERIMAGE_BITMAP_RTL_NOSTRETCH MUI_HEADERIMAGE_RIGHT MUI_HEADERIMAGE_UNBITMAP MUI_HEADERIMAGE_UNBITMAP_NOSTRETCH MUI_HEADERIMAGE_UNBITMAP_RTL MUI_HEADERIMAGE_UNBITMAP_RTL_NOSTRETCH MUI_HWND MUI_ICON MUI_INSTALLCOLORS MUI_INSTALLOPTIONS_DISPLAY MUI_INSTALLOPTIONS_DISPLAY_RETURN MUI_INSTALLOPTIONS_EXTRACT MUI_INSTALLOPTIONS_EXTRACT_AS MUI_INSTALLOPTIONS_INITDIALOG MUI_INSTALLOPTIONS_READ MUI_INSTALLOPTIONS_SHOW MUI_INSTALLOPTIONS_SHOW_RETURN MUI_INSTALLOPTIONS_WRITE MUI_INSTFILESPAGE_ABORTHEADER_SUBTEXT MUI_INSTFILESPAGE_ABORTHEADER_TEXT MUI_INSTFILESPAGE_COLORS MUI_INSTFILESPAGE_FINISHHEADER_SUBTEXT MUI_INSTFILESPAGE_FINISHHEADER_TEXT MUI_INSTFILESPAGE_PROGRESSBAR MUI_LANGDLL_ALLLANGUAGES MUI_LANGDLL_ALWAYSSHOW MUI_LANGDLL_DISPLAY MUI_LANGDLL_INFO MUI_LANGDLL_REGISTRY_KEY MUI_LANGDLL_REGISTRY_ROOT MUI_LANGDLL_REGISTRY_VALUENAME MUI_LANGDLL_WINDOWTITLE MUI_LANGUAGE MUI_LICENSEPAGE_BGCOLOR MUI_LICENSEPAGE_BUTTON MUI_LICENSEPAGE_CHECKBOX MUI_LICENSEPAGE_CHECKBOX_TEXT MUI_LICENSEPAGE_RADIOBUTTONS MUI_LICENSEPAGE_RADIOBUTTONS_TEXT_ACCEPT MUI_LICENSEPAGE_RADIOBUTTONS_TEXT_DECLINE MUI_LICENSEPAGE_TEXT_BOTTOM MUI_LICENSEPAGE_TEXT_TOP MUI_PAGE_COMPONENTS MUI_PAGE_CUSTOMFUNCTION_LEAVE MUI_PAGE_CUSTOMFUNCTION_PRE MUI_PAGE_CUSTOMFUNCTION_SHOW MUI_PAGE_DIRECTORY MUI_PAGE_FINISH MUI_PAGE_HEADER_SUBTEXT MUI_PAGE_HEADER_TEXT MUI_PAGE_INSTFILES MUI_PAGE_LICENSE MUI_PAGE_STARTMENU MUI_PAGE_WELCOME MUI_RESERVEFILE_INSTALLOPTIONS MUI_RESERVEFILE_LANGDLL MUI_SPECIALINI MUI_STARTMENU_GETFOLDER MUI_STARTMENU_WRITE_BEGIN MUI_STARTMENU_WRITE_END MUI_STARTMENUPAGE_BGCOLOR MUI_STARTMENUPAGE_DEFAULTFOLDER MUI_STARTMENUPAGE_NODISABLE MUI_STARTMENUPAGE_REGISTRY_KEY MUI_STARTMENUPAGE_REGISTRY_ROOT MUI_STARTMENUPAGE_REGISTRY_VALUENAME MUI_STARTMENUPAGE_TEXT_CHECKBOX MUI_STARTMENUPAGE_TEXT_TOP MUI_UI MUI_UI_COMPONENTSPAGE_NODESC MUI_UI_COMPONENTSPAGE_SMALLDESC MUI_UI_HEADERIMAGE MUI_UI_HEADERIMAGE_RIGHT MUI_UNABORTWARNING MUI_UNABORTWARNING_CANCEL_DEFAULT MUI_UNABORTWARNING_TEXT MUI_UNCONFIRMPAGE_TEXT_LOCATION MUI_UNCONFIRMPAGE_TEXT_TOP MUI_UNFINISHPAGE_NOAUTOCLOSE MUI_UNFUNCTION_DESCRIPTION_BEGIN MUI_UNFUNCTION_DESCRIPTION_END MUI_UNGETLANGUAGE MUI_UNICON MUI_UNPAGE_COMPONENTS MUI_UNPAGE_CONFIRM MUI_UNPAGE_DIRECTORY MUI_UNPAGE_FINISH MUI_UNPAGE_INSTFILES MUI_UNPAGE_LICENSE MUI_UNPAGE_WELCOME MUI_UNWELCOMEFINISHPAGE_BITMAP MUI_UNWELCOMEFINISHPAGE_BITMAP_NOSTRETCH MUI_UNWELCOMEFINISHPAGE_INI MUI_WELCOMEFINISHPAGE_BITMAP MUI_WELCOMEFINISHPAGE_BITMAP_NOSTRETCH MUI_WELCOMEFINISHPAGE_CUSTOMFUNCTION_INIT MUI_WELCOMEFINISHPAGE_INI MUI_WELCOMEPAGE_TEXT MUI_WELCOMEPAGE_TITLE MUI_WELCOMEPAGE_TITLE_3LINES'
bistr = 'addincludedir addplugindir AndIf cd define echo else endif error execute If ifdef ifmacrodef ifmacrondef ifndef include insertmacro macro macroend onGUIEnd onGUIInit onInit onInstFailed onInstSuccess onMouseOverSection onRebootFailed onSelChange onUserAbort onVerifyInstDir OrIf packhdr system undef verbose warning'
instance = any("instance", [r'\$\{.*?\}', r'\$[A-Za-z0-9\_]*'])
define = any("define", [r"\![^\n]*"])
comment = any("comment", [r"\;[^\n]*", r"\#[^\n]*", r"\/\*(.*?)\*\/"])
return make_generic_c_patterns(kwstr1+' '+kwstr2+' '+kwstr3, bistr,
instance=instance, define=define,
comment=comment) | [
"def",
"make_nsis_patterns",
"(",
")",
":",
"kwstr1",
"=",
"'Abort AddBrandingImage AddSize AllowRootDirInstall AllowSkipFiles AutoCloseWindow BGFont BGGradient BrandingText BringToFront Call CallInstDLL Caption ClearErrors CompletedText ComponentText CopyFiles CRCCheck CreateDirectory CreateFont CreateShortCut Delete DeleteINISec DeleteINIStr DeleteRegKey DeleteRegValue DetailPrint DetailsButtonText DirText DirVar DirVerify EnableWindow EnumRegKey EnumRegValue Exec ExecShell ExecWait Exch ExpandEnvStrings File FileBufSize FileClose FileErrorText FileOpen FileRead FileReadByte FileSeek FileWrite FileWriteByte FindClose FindFirst FindNext FindWindow FlushINI Function FunctionEnd GetCurInstType GetCurrentAddress GetDlgItem GetDLLVersion GetDLLVersionLocal GetErrorLevel GetFileTime GetFileTimeLocal GetFullPathName GetFunctionAddress GetInstDirError GetLabelAddress GetTempFileName Goto HideWindow ChangeUI CheckBitmap Icon IfAbort IfErrors IfFileExists IfRebootFlag IfSilent InitPluginsDir InstallButtonText InstallColors InstallDir InstallDirRegKey InstProgressFlags InstType InstTypeGetText InstTypeSetText IntCmp IntCmpU IntFmt IntOp IsWindow LangString LicenseBkColor LicenseData LicenseForceSelection LicenseLangString LicenseText LoadLanguageFile LogSet LogText MessageBox MiscButtonText Name OutFile Page PageCallbacks PageEx PageExEnd Pop Push Quit ReadEnvStr ReadINIStr ReadRegDWORD ReadRegStr Reboot RegDLL Rename ReserveFile Return RMDir SearchPath Section SectionEnd SectionGetFlags SectionGetInstTypes SectionGetSize SectionGetText SectionIn SectionSetFlags SectionSetInstTypes SectionSetSize SectionSetText SendMessage SetAutoClose SetBrandingImage SetCompress SetCompressor SetCompressorDictSize SetCtlColors SetCurInstType SetDatablockOptimize SetDateSave SetDetailsPrint SetDetailsView SetErrorLevel SetErrors SetFileAttributes SetFont SetOutPath SetOverwrite SetPluginUnload SetRebootFlag SetShellVarContext SetSilent ShowInstDetails ShowUninstDetails ShowWindow SilentInstall SilentUnInstall Sleep SpaceTexts StrCmp StrCpy StrLen SubCaption SubSection SubSectionEnd UninstallButtonText UninstallCaption UninstallIcon UninstallSubCaption UninstallText UninstPage UnRegDLL Var VIAddVersionKey VIProductVersion WindowIcon WriteINIStr WriteRegBin WriteRegDWORD WriteRegExpandStr WriteRegStr WriteUninstaller XPStyle'",
"kwstr2",
"=",
"'all alwaysoff ARCHIVE auto both bzip2 components current custom details directory false FILE_ATTRIBUTE_ARCHIVE FILE_ATTRIBUTE_HIDDEN FILE_ATTRIBUTE_NORMAL FILE_ATTRIBUTE_OFFLINE FILE_ATTRIBUTE_READONLY FILE_ATTRIBUTE_SYSTEM FILE_ATTRIBUTE_TEMPORARY force grey HIDDEN hide IDABORT IDCANCEL IDIGNORE IDNO IDOK IDRETRY IDYES ifdiff ifnewer instfiles instfiles lastused leave left level license listonly lzma manual MB_ABORTRETRYIGNORE MB_DEFBUTTON1 MB_DEFBUTTON2 MB_DEFBUTTON3 MB_DEFBUTTON4 MB_ICONEXCLAMATION MB_ICONINFORMATION MB_ICONQUESTION MB_ICONSTOP MB_OK MB_OKCANCEL MB_RETRYCANCEL MB_RIGHT MB_SETFOREGROUND MB_TOPMOST MB_YESNO MB_YESNOCANCEL nevershow none NORMAL off OFFLINE on READONLY right RO show silent silentlog SYSTEM TEMPORARY text textonly true try uninstConfirm windows zlib'",
"kwstr3",
"=",
"'MUI_ABORTWARNING MUI_ABORTWARNING_CANCEL_DEFAULT MUI_ABORTWARNING_TEXT MUI_BGCOLOR MUI_COMPONENTSPAGE_CHECKBITMAP MUI_COMPONENTSPAGE_NODESC MUI_COMPONENTSPAGE_SMALLDESC MUI_COMPONENTSPAGE_TEXT_COMPLIST MUI_COMPONENTSPAGE_TEXT_DESCRIPTION_INFO MUI_COMPONENTSPAGE_TEXT_DESCRIPTION_TITLE MUI_COMPONENTSPAGE_TEXT_INSTTYPE MUI_COMPONENTSPAGE_TEXT_TOP MUI_CUSTOMFUNCTION_ABORT MUI_CUSTOMFUNCTION_GUIINIT MUI_CUSTOMFUNCTION_UNABORT MUI_CUSTOMFUNCTION_UNGUIINIT MUI_DESCRIPTION_TEXT MUI_DIRECTORYPAGE_BGCOLOR MUI_DIRECTORYPAGE_TEXT_DESTINATION MUI_DIRECTORYPAGE_TEXT_TOP MUI_DIRECTORYPAGE_VARIABLE MUI_DIRECTORYPAGE_VERIFYONLEAVE MUI_FINISHPAGE_BUTTON MUI_FINISHPAGE_CANCEL_ENABLED MUI_FINISHPAGE_LINK MUI_FINISHPAGE_LINK_COLOR MUI_FINISHPAGE_LINK_LOCATION MUI_FINISHPAGE_NOAUTOCLOSE MUI_FINISHPAGE_NOREBOOTSUPPORT MUI_FINISHPAGE_REBOOTLATER_DEFAULT MUI_FINISHPAGE_RUN MUI_FINISHPAGE_RUN_FUNCTION MUI_FINISHPAGE_RUN_NOTCHECKED MUI_FINISHPAGE_RUN_PARAMETERS MUI_FINISHPAGE_RUN_TEXT MUI_FINISHPAGE_SHOWREADME MUI_FINISHPAGE_SHOWREADME_FUNCTION MUI_FINISHPAGE_SHOWREADME_NOTCHECKED MUI_FINISHPAGE_SHOWREADME_TEXT MUI_FINISHPAGE_TEXT MUI_FINISHPAGE_TEXT_LARGE MUI_FINISHPAGE_TEXT_REBOOT MUI_FINISHPAGE_TEXT_REBOOTLATER MUI_FINISHPAGE_TEXT_REBOOTNOW MUI_FINISHPAGE_TITLE MUI_FINISHPAGE_TITLE_3LINES MUI_FUNCTION_DESCRIPTION_BEGIN MUI_FUNCTION_DESCRIPTION_END MUI_HEADER_TEXT MUI_HEADER_TRANSPARENT_TEXT MUI_HEADERIMAGE MUI_HEADERIMAGE_BITMAP MUI_HEADERIMAGE_BITMAP_NOSTRETCH MUI_HEADERIMAGE_BITMAP_RTL MUI_HEADERIMAGE_BITMAP_RTL_NOSTRETCH MUI_HEADERIMAGE_RIGHT MUI_HEADERIMAGE_UNBITMAP MUI_HEADERIMAGE_UNBITMAP_NOSTRETCH MUI_HEADERIMAGE_UNBITMAP_RTL MUI_HEADERIMAGE_UNBITMAP_RTL_NOSTRETCH MUI_HWND MUI_ICON MUI_INSTALLCOLORS MUI_INSTALLOPTIONS_DISPLAY MUI_INSTALLOPTIONS_DISPLAY_RETURN MUI_INSTALLOPTIONS_EXTRACT MUI_INSTALLOPTIONS_EXTRACT_AS MUI_INSTALLOPTIONS_INITDIALOG MUI_INSTALLOPTIONS_READ MUI_INSTALLOPTIONS_SHOW MUI_INSTALLOPTIONS_SHOW_RETURN MUI_INSTALLOPTIONS_WRITE MUI_INSTFILESPAGE_ABORTHEADER_SUBTEXT MUI_INSTFILESPAGE_ABORTHEADER_TEXT MUI_INSTFILESPAGE_COLORS MUI_INSTFILESPAGE_FINISHHEADER_SUBTEXT MUI_INSTFILESPAGE_FINISHHEADER_TEXT MUI_INSTFILESPAGE_PROGRESSBAR MUI_LANGDLL_ALLLANGUAGES MUI_LANGDLL_ALWAYSSHOW MUI_LANGDLL_DISPLAY MUI_LANGDLL_INFO MUI_LANGDLL_REGISTRY_KEY MUI_LANGDLL_REGISTRY_ROOT MUI_LANGDLL_REGISTRY_VALUENAME MUI_LANGDLL_WINDOWTITLE MUI_LANGUAGE MUI_LICENSEPAGE_BGCOLOR MUI_LICENSEPAGE_BUTTON MUI_LICENSEPAGE_CHECKBOX MUI_LICENSEPAGE_CHECKBOX_TEXT MUI_LICENSEPAGE_RADIOBUTTONS MUI_LICENSEPAGE_RADIOBUTTONS_TEXT_ACCEPT MUI_LICENSEPAGE_RADIOBUTTONS_TEXT_DECLINE MUI_LICENSEPAGE_TEXT_BOTTOM MUI_LICENSEPAGE_TEXT_TOP MUI_PAGE_COMPONENTS MUI_PAGE_CUSTOMFUNCTION_LEAVE MUI_PAGE_CUSTOMFUNCTION_PRE MUI_PAGE_CUSTOMFUNCTION_SHOW MUI_PAGE_DIRECTORY MUI_PAGE_FINISH MUI_PAGE_HEADER_SUBTEXT MUI_PAGE_HEADER_TEXT MUI_PAGE_INSTFILES MUI_PAGE_LICENSE MUI_PAGE_STARTMENU MUI_PAGE_WELCOME MUI_RESERVEFILE_INSTALLOPTIONS MUI_RESERVEFILE_LANGDLL MUI_SPECIALINI MUI_STARTMENU_GETFOLDER MUI_STARTMENU_WRITE_BEGIN MUI_STARTMENU_WRITE_END MUI_STARTMENUPAGE_BGCOLOR MUI_STARTMENUPAGE_DEFAULTFOLDER MUI_STARTMENUPAGE_NODISABLE MUI_STARTMENUPAGE_REGISTRY_KEY MUI_STARTMENUPAGE_REGISTRY_ROOT MUI_STARTMENUPAGE_REGISTRY_VALUENAME MUI_STARTMENUPAGE_TEXT_CHECKBOX MUI_STARTMENUPAGE_TEXT_TOP MUI_UI MUI_UI_COMPONENTSPAGE_NODESC MUI_UI_COMPONENTSPAGE_SMALLDESC MUI_UI_HEADERIMAGE MUI_UI_HEADERIMAGE_RIGHT MUI_UNABORTWARNING MUI_UNABORTWARNING_CANCEL_DEFAULT MUI_UNABORTWARNING_TEXT MUI_UNCONFIRMPAGE_TEXT_LOCATION MUI_UNCONFIRMPAGE_TEXT_TOP MUI_UNFINISHPAGE_NOAUTOCLOSE MUI_UNFUNCTION_DESCRIPTION_BEGIN MUI_UNFUNCTION_DESCRIPTION_END MUI_UNGETLANGUAGE MUI_UNICON MUI_UNPAGE_COMPONENTS MUI_UNPAGE_CONFIRM MUI_UNPAGE_DIRECTORY MUI_UNPAGE_FINISH MUI_UNPAGE_INSTFILES MUI_UNPAGE_LICENSE MUI_UNPAGE_WELCOME MUI_UNWELCOMEFINISHPAGE_BITMAP MUI_UNWELCOMEFINISHPAGE_BITMAP_NOSTRETCH MUI_UNWELCOMEFINISHPAGE_INI MUI_WELCOMEFINISHPAGE_BITMAP MUI_WELCOMEFINISHPAGE_BITMAP_NOSTRETCH MUI_WELCOMEFINISHPAGE_CUSTOMFUNCTION_INIT MUI_WELCOMEFINISHPAGE_INI MUI_WELCOMEPAGE_TEXT MUI_WELCOMEPAGE_TITLE MUI_WELCOMEPAGE_TITLE_3LINES'",
"bistr",
"=",
"'addincludedir addplugindir AndIf cd define echo else endif error execute If ifdef ifmacrodef ifmacrondef ifndef include insertmacro macro macroend onGUIEnd onGUIInit onInit onInstFailed onInstSuccess onMouseOverSection onRebootFailed onSelChange onUserAbort onVerifyInstDir OrIf packhdr system undef verbose warning'",
"instance",
"=",
"any",
"(",
"\"instance\"",
",",
"[",
"r'\\$\\{.*?\\}'",
",",
"r'\\$[A-Za-z0-9\\_]*'",
"]",
")",
"define",
"=",
"any",
"(",
"\"define\"",
",",
"[",
"r\"\\![^\\n]*\"",
"]",
")",
"comment",
"=",
"any",
"(",
"\"comment\"",
",",
"[",
"r\"\\;[^\\n]*\"",
",",
"r\"\\#[^\\n]*\"",
",",
"r\"\\/\\*(.*?)\\*\\/\"",
"]",
")",
"return",
"make_generic_c_patterns",
"(",
"kwstr1",
"+",
"' '",
"+",
"kwstr2",
"+",
"' '",
"+",
"kwstr3",
",",
"bistr",
",",
"instance",
"=",
"instance",
",",
"define",
"=",
"define",
",",
"comment",
"=",
"comment",
")"
] | Strongly inspired from idlelib.ColorDelegator.make_pat | [
"Strongly",
"inspired",
"from",
"idlelib",
".",
"ColorDelegator",
".",
"make_pat"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L829-L840 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | make_gettext_patterns | def make_gettext_patterns():
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kwstr = 'msgid msgstr'
kw = r"\b" + any("keyword", kwstr.split()) + r"\b"
fuzzy = any("builtin", [r"#,[^\n]*"])
links = any("normal", [r"#:[^\n]*"])
comment = any("comment", [r"#[^\n]*"])
number = any("number",
[r"\b[+-]?[0-9]+[lL]?\b",
r"\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b",
r"\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"])
sqstring = r"(\b[rRuU])?'[^'\\\n]*(\\.[^'\\\n]*)*'?"
dqstring = r'(\b[rRuU])?"[^"\\\n]*(\\.[^"\\\n]*)*"?'
string = any("string", [sqstring, dqstring])
return "|".join([kw, string, number, fuzzy, links, comment,
any("SYNC", [r"\n"])]) | python | def make_gettext_patterns():
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kwstr = 'msgid msgstr'
kw = r"\b" + any("keyword", kwstr.split()) + r"\b"
fuzzy = any("builtin", [r"#,[^\n]*"])
links = any("normal", [r"#:[^\n]*"])
comment = any("comment", [r"#[^\n]*"])
number = any("number",
[r"\b[+-]?[0-9]+[lL]?\b",
r"\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b",
r"\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"])
sqstring = r"(\b[rRuU])?'[^'\\\n]*(\\.[^'\\\n]*)*'?"
dqstring = r'(\b[rRuU])?"[^"\\\n]*(\\.[^"\\\n]*)*"?'
string = any("string", [sqstring, dqstring])
return "|".join([kw, string, number, fuzzy, links, comment,
any("SYNC", [r"\n"])]) | [
"def",
"make_gettext_patterns",
"(",
")",
":",
"kwstr",
"=",
"'msgid msgstr'",
"kw",
"=",
"r\"\\b\"",
"+",
"any",
"(",
"\"keyword\"",
",",
"kwstr",
".",
"split",
"(",
")",
")",
"+",
"r\"\\b\"",
"fuzzy",
"=",
"any",
"(",
"\"builtin\"",
",",
"[",
"r\"#,[^\\n]*\"",
"]",
")",
"links",
"=",
"any",
"(",
"\"normal\"",
",",
"[",
"r\"#:[^\\n]*\"",
"]",
")",
"comment",
"=",
"any",
"(",
"\"comment\"",
",",
"[",
"r\"#[^\\n]*\"",
"]",
")",
"number",
"=",
"any",
"(",
"\"number\"",
",",
"[",
"r\"\\b[+-]?[0-9]+[lL]?\\b\"",
",",
"r\"\\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\\b\"",
",",
"r\"\\b[+-]?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b\"",
"]",
")",
"sqstring",
"=",
"r\"(\\b[rRuU])?'[^'\\\\\\n]*(\\\\.[^'\\\\\\n]*)*'?\"",
"dqstring",
"=",
"r'(\\b[rRuU])?\"[^\"\\\\\\n]*(\\\\.[^\"\\\\\\n]*)*\"?'",
"string",
"=",
"any",
"(",
"\"string\"",
",",
"[",
"sqstring",
",",
"dqstring",
"]",
")",
"return",
"\"|\"",
".",
"join",
"(",
"[",
"kw",
",",
"string",
",",
"number",
",",
"fuzzy",
",",
"links",
",",
"comment",
",",
"any",
"(",
"\"SYNC\"",
",",
"[",
"r\"\\n\"",
"]",
")",
"]",
")"
] | Strongly inspired from idlelib.ColorDelegator.make_pat | [
"Strongly",
"inspired",
"from",
"idlelib",
".",
"ColorDelegator",
".",
"make_pat"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L852-L867 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | make_yaml_patterns | def make_yaml_patterns():
"Strongly inspired from sublime highlighter "
kw = any("keyword", [r":|>|-|\||\[|\]|[A-Za-z][\w\s\-\_ ]+(?=:)"])
links = any("normal", [r"#:[^\n]*"])
comment = any("comment", [r"#[^\n]*"])
number = any("number",
[r"\b[+-]?[0-9]+[lL]?\b",
r"\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b",
r"\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"])
sqstring = r"(\b[rRuU])?'[^'\\\n]*(\\.[^'\\\n]*)*'?"
dqstring = r'(\b[rRuU])?"[^"\\\n]*(\\.[^"\\\n]*)*"?'
string = any("string", [sqstring, dqstring])
return "|".join([kw, string, number, links, comment,
any("SYNC", [r"\n"])]) | python | def make_yaml_patterns():
"Strongly inspired from sublime highlighter "
kw = any("keyword", [r":|>|-|\||\[|\]|[A-Za-z][\w\s\-\_ ]+(?=:)"])
links = any("normal", [r"#:[^\n]*"])
comment = any("comment", [r"#[^\n]*"])
number = any("number",
[r"\b[+-]?[0-9]+[lL]?\b",
r"\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b",
r"\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"])
sqstring = r"(\b[rRuU])?'[^'\\\n]*(\\.[^'\\\n]*)*'?"
dqstring = r'(\b[rRuU])?"[^"\\\n]*(\\.[^"\\\n]*)*"?'
string = any("string", [sqstring, dqstring])
return "|".join([kw, string, number, links, comment,
any("SYNC", [r"\n"])]) | [
"def",
"make_yaml_patterns",
"(",
")",
":",
"kw",
"=",
"any",
"(",
"\"keyword\"",
",",
"[",
"r\":|>|-|\\||\\[|\\]|[A-Za-z][\\w\\s\\-\\_ ]+(?=:)\"",
"]",
")",
"links",
"=",
"any",
"(",
"\"normal\"",
",",
"[",
"r\"#:[^\\n]*\"",
"]",
")",
"comment",
"=",
"any",
"(",
"\"comment\"",
",",
"[",
"r\"#[^\\n]*\"",
"]",
")",
"number",
"=",
"any",
"(",
"\"number\"",
",",
"[",
"r\"\\b[+-]?[0-9]+[lL]?\\b\"",
",",
"r\"\\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\\b\"",
",",
"r\"\\b[+-]?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b\"",
"]",
")",
"sqstring",
"=",
"r\"(\\b[rRuU])?'[^'\\\\\\n]*(\\\\.[^'\\\\\\n]*)*'?\"",
"dqstring",
"=",
"r'(\\b[rRuU])?\"[^\"\\\\\\n]*(\\\\.[^\"\\\\\\n]*)*\"?'",
"string",
"=",
"any",
"(",
"\"string\"",
",",
"[",
"sqstring",
",",
"dqstring",
"]",
")",
"return",
"\"|\"",
".",
"join",
"(",
"[",
"kw",
",",
"string",
",",
"number",
",",
"links",
",",
"comment",
",",
"any",
"(",
"\"SYNC\"",
",",
"[",
"r\"\\n\"",
"]",
")",
"]",
")"
] | Strongly inspired from sublime highlighter | [
"Strongly",
"inspired",
"from",
"sublime",
"highlighter"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L878-L891 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | make_html_patterns | def make_html_patterns():
"""Strongly inspired from idlelib.ColorDelegator.make_pat """
tags = any("builtin", [r"<", r"[\?/]?>", r"(?<=<).*?(?=[ >])"])
keywords = any("keyword", [r" [\w:-]*?(?==)"])
string = any("string", [r'".*?"'])
comment = any("comment", [r"<!--.*?-->"])
multiline_comment_start = any("multiline_comment_start", [r"<!--"])
multiline_comment_end = any("multiline_comment_end", [r"-->"])
return "|".join([comment, multiline_comment_start,
multiline_comment_end, tags, keywords, string]) | python | def make_html_patterns():
"""Strongly inspired from idlelib.ColorDelegator.make_pat """
tags = any("builtin", [r"<", r"[\?/]?>", r"(?<=<).*?(?=[ >])"])
keywords = any("keyword", [r" [\w:-]*?(?==)"])
string = any("string", [r'".*?"'])
comment = any("comment", [r"<!--.*?-->"])
multiline_comment_start = any("multiline_comment_start", [r"<!--"])
multiline_comment_end = any("multiline_comment_end", [r"-->"])
return "|".join([comment, multiline_comment_start,
multiline_comment_end, tags, keywords, string]) | [
"def",
"make_html_patterns",
"(",
")",
":",
"tags",
"=",
"any",
"(",
"\"builtin\"",
",",
"[",
"r\"<\"",
",",
"r\"[\\?/]?>\"",
",",
"r\"(?<=<).*?(?=[ >])\"",
"]",
")",
"keywords",
"=",
"any",
"(",
"\"keyword\"",
",",
"[",
"r\" [\\w:-]*?(?==)\"",
"]",
")",
"string",
"=",
"any",
"(",
"\"string\"",
",",
"[",
"r'\".*?\"'",
"]",
")",
"comment",
"=",
"any",
"(",
"\"comment\"",
",",
"[",
"r\"<!--.*?-->\"",
"]",
")",
"multiline_comment_start",
"=",
"any",
"(",
"\"multiline_comment_start\"",
",",
"[",
"r\"<!--\"",
"]",
")",
"multiline_comment_end",
"=",
"any",
"(",
"\"multiline_comment_end\"",
",",
"[",
"r\"-->\"",
"]",
")",
"return",
"\"|\"",
".",
"join",
"(",
"[",
"comment",
",",
"multiline_comment_start",
",",
"multiline_comment_end",
",",
"tags",
",",
"keywords",
",",
"string",
"]",
")"
] | Strongly inspired from idlelib.ColorDelegator.make_pat | [
"Strongly",
"inspired",
"from",
"idlelib",
".",
"ColorDelegator",
".",
"make_pat"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L962-L971 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | guess_pygments_highlighter | def guess_pygments_highlighter(filename):
"""Factory to generate syntax highlighter for the given filename.
If a syntax highlighter is not available for a particular file, this
function will attempt to generate one based on the lexers in Pygments. If
Pygments is not available or does not have an appropriate lexer, TextSH
will be returned instead.
"""
try:
from pygments.lexers import get_lexer_for_filename, get_lexer_by_name
except Exception:
return TextSH
root, ext = os.path.splitext(filename)
if ext in custom_extension_lexer_mapping:
try:
lexer = get_lexer_by_name(custom_extension_lexer_mapping[ext])
except Exception:
return TextSH
else:
try:
lexer = get_lexer_for_filename(filename)
except Exception:
return TextSH
class GuessedPygmentsSH(PygmentsSH):
_lexer = lexer
return GuessedPygmentsSH | python | def guess_pygments_highlighter(filename):
"""Factory to generate syntax highlighter for the given filename.
If a syntax highlighter is not available for a particular file, this
function will attempt to generate one based on the lexers in Pygments. If
Pygments is not available or does not have an appropriate lexer, TextSH
will be returned instead.
"""
try:
from pygments.lexers import get_lexer_for_filename, get_lexer_by_name
except Exception:
return TextSH
root, ext = os.path.splitext(filename)
if ext in custom_extension_lexer_mapping:
try:
lexer = get_lexer_by_name(custom_extension_lexer_mapping[ext])
except Exception:
return TextSH
else:
try:
lexer = get_lexer_for_filename(filename)
except Exception:
return TextSH
class GuessedPygmentsSH(PygmentsSH):
_lexer = lexer
return GuessedPygmentsSH | [
"def",
"guess_pygments_highlighter",
"(",
"filename",
")",
":",
"try",
":",
"from",
"pygments",
".",
"lexers",
"import",
"get_lexer_for_filename",
",",
"get_lexer_by_name",
"except",
"Exception",
":",
"return",
"TextSH",
"root",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"ext",
"in",
"custom_extension_lexer_mapping",
":",
"try",
":",
"lexer",
"=",
"get_lexer_by_name",
"(",
"custom_extension_lexer_mapping",
"[",
"ext",
"]",
")",
"except",
"Exception",
":",
"return",
"TextSH",
"else",
":",
"try",
":",
"lexer",
"=",
"get_lexer_for_filename",
"(",
"filename",
")",
"except",
"Exception",
":",
"return",
"TextSH",
"class",
"GuessedPygmentsSH",
"(",
"PygmentsSH",
")",
":",
"_lexer",
"=",
"lexer",
"return",
"GuessedPygmentsSH"
] | Factory to generate syntax highlighter for the given filename.
If a syntax highlighter is not available for a particular file, this
function will attempt to generate one based on the lexers in Pygments. If
Pygments is not available or does not have an appropriate lexer, TextSH
will be returned instead. | [
"Factory",
"to",
"generate",
"syntax",
"highlighter",
"for",
"the",
"given",
"filename",
".",
"If",
"a",
"syntax",
"highlighter",
"is",
"not",
"available",
"for",
"a",
"particular",
"file",
"this",
"function",
"will",
"attempt",
"to",
"generate",
"one",
"based",
"on",
"the",
"lexers",
"in",
"Pygments",
".",
"If",
"Pygments",
"is",
"not",
"available",
"or",
"does",
"not",
"have",
"an",
"appropriate",
"lexer",
"TextSH",
"will",
"be",
"returned",
"instead",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L1233-L1259 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | BaseSH.highlightBlock | def highlightBlock(self, text):
"""
Highlights a block of text. Please do not override, this method.
Instead you should implement
:func:`spyder.utils.syntaxhighplighters.SyntaxHighlighter.highlight_block`.
:param text: text to highlight.
"""
self.highlight_block(text)
# Process blocks for fold detection
current_block = self.currentBlock()
previous_block = self._find_prev_non_blank_block(current_block)
if self.editor:
if self.fold_detector is not None:
self.fold_detector._editor = weakref.ref(self.editor)
self.fold_detector.process_block(
current_block, previous_block, text) | python | def highlightBlock(self, text):
"""
Highlights a block of text. Please do not override, this method.
Instead you should implement
:func:`spyder.utils.syntaxhighplighters.SyntaxHighlighter.highlight_block`.
:param text: text to highlight.
"""
self.highlight_block(text)
# Process blocks for fold detection
current_block = self.currentBlock()
previous_block = self._find_prev_non_blank_block(current_block)
if self.editor:
if self.fold_detector is not None:
self.fold_detector._editor = weakref.ref(self.editor)
self.fold_detector.process_block(
current_block, previous_block, text) | [
"def",
"highlightBlock",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"highlight_block",
"(",
"text",
")",
"# Process blocks for fold detection\r",
"current_block",
"=",
"self",
".",
"currentBlock",
"(",
")",
"previous_block",
"=",
"self",
".",
"_find_prev_non_blank_block",
"(",
"current_block",
")",
"if",
"self",
".",
"editor",
":",
"if",
"self",
".",
"fold_detector",
"is",
"not",
"None",
":",
"self",
".",
"fold_detector",
".",
"_editor",
"=",
"weakref",
".",
"ref",
"(",
"self",
".",
"editor",
")",
"self",
".",
"fold_detector",
".",
"process_block",
"(",
"current_block",
",",
"previous_block",
",",
"text",
")"
] | Highlights a block of text. Please do not override, this method.
Instead you should implement
:func:`spyder.utils.syntaxhighplighters.SyntaxHighlighter.highlight_block`.
:param text: text to highlight. | [
"Highlights",
"a",
"block",
"of",
"text",
".",
"Please",
"do",
"not",
"override",
"this",
"method",
".",
"Instead",
"you",
"should",
"implement",
":",
"func",
":",
"spyder",
".",
"utils",
".",
"syntaxhighplighters",
".",
"SyntaxHighlighter",
".",
"highlight_block",
".",
":",
"param",
"text",
":",
"text",
"to",
"highlight",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L219-L236 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | BaseSH.highlight_spaces | def highlight_spaces(self, text, offset=0):
"""
Make blank space less apparent by setting the foreground alpha.
This only has an effect when 'Show blank space' is turned on.
Derived classes could call this function at the end of
highlightBlock().
"""
flags_text = self.document().defaultTextOption().flags()
show_blanks = flags_text & QTextOption.ShowTabsAndSpaces
if show_blanks:
format_leading = self.formats.get("leading", None)
format_trailing = self.formats.get("trailing", None)
match = self.BLANKPROG.search(text, offset)
while match:
start, end = match.span()
start = max([0, start+offset])
end = max([0, end+offset])
# Format trailing spaces at the end of the line.
if end == len(text) and format_trailing is not None:
self.setFormat(start, end, format_trailing)
# Format leading spaces, e.g. indentation.
if start == 0 and format_leading is not None:
self.setFormat(start, end, format_leading)
format = self.format(start)
color_foreground = format.foreground().color()
alpha_new = self.BLANK_ALPHA_FACTOR * color_foreground.alphaF()
color_foreground.setAlphaF(alpha_new)
self.setFormat(start, end-start, color_foreground)
match = self.BLANKPROG.search(text, match.end()) | python | def highlight_spaces(self, text, offset=0):
"""
Make blank space less apparent by setting the foreground alpha.
This only has an effect when 'Show blank space' is turned on.
Derived classes could call this function at the end of
highlightBlock().
"""
flags_text = self.document().defaultTextOption().flags()
show_blanks = flags_text & QTextOption.ShowTabsAndSpaces
if show_blanks:
format_leading = self.formats.get("leading", None)
format_trailing = self.formats.get("trailing", None)
match = self.BLANKPROG.search(text, offset)
while match:
start, end = match.span()
start = max([0, start+offset])
end = max([0, end+offset])
# Format trailing spaces at the end of the line.
if end == len(text) and format_trailing is not None:
self.setFormat(start, end, format_trailing)
# Format leading spaces, e.g. indentation.
if start == 0 and format_leading is not None:
self.setFormat(start, end, format_leading)
format = self.format(start)
color_foreground = format.foreground().color()
alpha_new = self.BLANK_ALPHA_FACTOR * color_foreground.alphaF()
color_foreground.setAlphaF(alpha_new)
self.setFormat(start, end-start, color_foreground)
match = self.BLANKPROG.search(text, match.end()) | [
"def",
"highlight_spaces",
"(",
"self",
",",
"text",
",",
"offset",
"=",
"0",
")",
":",
"flags_text",
"=",
"self",
".",
"document",
"(",
")",
".",
"defaultTextOption",
"(",
")",
".",
"flags",
"(",
")",
"show_blanks",
"=",
"flags_text",
"&",
"QTextOption",
".",
"ShowTabsAndSpaces",
"if",
"show_blanks",
":",
"format_leading",
"=",
"self",
".",
"formats",
".",
"get",
"(",
"\"leading\"",
",",
"None",
")",
"format_trailing",
"=",
"self",
".",
"formats",
".",
"get",
"(",
"\"trailing\"",
",",
"None",
")",
"match",
"=",
"self",
".",
"BLANKPROG",
".",
"search",
"(",
"text",
",",
"offset",
")",
"while",
"match",
":",
"start",
",",
"end",
"=",
"match",
".",
"span",
"(",
")",
"start",
"=",
"max",
"(",
"[",
"0",
",",
"start",
"+",
"offset",
"]",
")",
"end",
"=",
"max",
"(",
"[",
"0",
",",
"end",
"+",
"offset",
"]",
")",
"# Format trailing spaces at the end of the line. \r",
"if",
"end",
"==",
"len",
"(",
"text",
")",
"and",
"format_trailing",
"is",
"not",
"None",
":",
"self",
".",
"setFormat",
"(",
"start",
",",
"end",
",",
"format_trailing",
")",
"# Format leading spaces, e.g. indentation.\r",
"if",
"start",
"==",
"0",
"and",
"format_leading",
"is",
"not",
"None",
":",
"self",
".",
"setFormat",
"(",
"start",
",",
"end",
",",
"format_leading",
")",
"format",
"=",
"self",
".",
"format",
"(",
"start",
")",
"color_foreground",
"=",
"format",
".",
"foreground",
"(",
")",
".",
"color",
"(",
")",
"alpha_new",
"=",
"self",
".",
"BLANK_ALPHA_FACTOR",
"*",
"color_foreground",
".",
"alphaF",
"(",
")",
"color_foreground",
".",
"setAlphaF",
"(",
"alpha_new",
")",
"self",
".",
"setFormat",
"(",
"start",
",",
"end",
"-",
"start",
",",
"color_foreground",
")",
"match",
"=",
"self",
".",
"BLANKPROG",
".",
"search",
"(",
"text",
",",
"match",
".",
"end",
"(",
")",
")"
] | Make blank space less apparent by setting the foreground alpha.
This only has an effect when 'Show blank space' is turned on.
Derived classes could call this function at the end of
highlightBlock(). | [
"Make",
"blank",
"space",
"less",
"apparent",
"by",
"setting",
"the",
"foreground",
"alpha",
".",
"This",
"only",
"has",
"an",
"effect",
"when",
"Show",
"blank",
"space",
"is",
"turned",
"on",
".",
"Derived",
"classes",
"could",
"call",
"this",
"function",
"at",
"the",
"end",
"of",
"highlightBlock",
"()",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L247-L275 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | PythonSH.highlight_block | def highlight_block(self, text):
"""Implement specific highlight for Python."""
text = to_text_string(text)
prev_state = tbh.get_state(self.currentBlock().previous())
if prev_state == self.INSIDE_DQ3STRING:
offset = -4
text = r'""" '+text
elif prev_state == self.INSIDE_SQ3STRING:
offset = -4
text = r"''' "+text
elif prev_state == self.INSIDE_DQSTRING:
offset = -2
text = r'" '+text
elif prev_state == self.INSIDE_SQSTRING:
offset = -2
text = r"' "+text
else:
offset = 0
prev_state = self.NORMAL
oedata = None
import_stmt = None
self.setFormat(0, len(text), self.formats["normal"])
state = self.NORMAL
match = self.PROG.search(text)
while match:
for key, value in list(match.groupdict().items()):
if value:
start, end = match.span(key)
start = max([0, start+offset])
end = max([0, end+offset])
if key == "uf_sq3string":
self.setFormat(start, end-start,
self.formats["string"])
state = self.INSIDE_SQ3STRING
elif key == "uf_dq3string":
self.setFormat(start, end-start,
self.formats["string"])
state = self.INSIDE_DQ3STRING
elif key == "uf_sqstring":
self.setFormat(start, end-start,
self.formats["string"])
state = self.INSIDE_SQSTRING
elif key == "uf_dqstring":
self.setFormat(start, end-start,
self.formats["string"])
state = self.INSIDE_DQSTRING
else:
self.setFormat(start, end-start, self.formats[key])
if key == "comment":
if text.lstrip().startswith(self.cell_separators):
self.found_cell_separators = True
oedata = OutlineExplorerData()
oedata.text = to_text_string(text).strip()
# cell_head: string contaning the first group
# of '%'s in the cell header
cell_head = re.search(r"%+|$",
text.lstrip()).group()
if cell_head == '':
oedata.cell_level = 0
else:
oedata.cell_level = len(cell_head) - 2
oedata.fold_level = start
oedata.def_type = OutlineExplorerData.CELL
oedata.def_name = get_code_cell_name(text)
elif self.OECOMMENT.match(text.lstrip()):
oedata = OutlineExplorerData()
oedata.text = to_text_string(text).strip()
oedata.fold_level = start
oedata.def_type = OutlineExplorerData.COMMENT
oedata.def_name = text.strip()
elif key == "keyword":
if value in ("def", "class"):
match1 = self.IDPROG.match(text, end)
if match1:
start1, end1 = match1.span(1)
self.setFormat(start1, end1-start1,
self.formats["definition"])
oedata = OutlineExplorerData()
oedata.text = to_text_string(text)
oedata.fold_level = (len(text)
- len(text.lstrip()))
oedata.def_type = self.DEF_TYPES[
to_text_string(value)]
oedata.def_name = text[start1:end1]
oedata.color = self.formats["definition"]
elif value in ("elif", "else", "except", "finally",
"for", "if", "try", "while",
"with"):
if text.lstrip().startswith(value):
oedata = OutlineExplorerData()
oedata.text = to_text_string(text).strip()
oedata.fold_level = start
oedata.def_type = \
OutlineExplorerData.STATEMENT
oedata.def_name = text.strip()
elif value == "import":
import_stmt = text.strip()
# color all the "as" words on same line, except
# if in a comment; cheap approximation to the
# truth
if '#' in text:
endpos = text.index('#')
else:
endpos = len(text)
while True:
match1 = self.ASPROG.match(text, end,
endpos)
if not match1:
break
start, end = match1.span(1)
self.setFormat(start, end-start,
self.formats["keyword"])
match = self.PROG.search(text, match.end())
tbh.set_state(self.currentBlock(), state)
# Use normal format for indentation and trailing spaces.
self.formats['leading'] = self.formats['normal']
self.formats['trailing'] = self.formats['normal']
self.highlight_spaces(text, offset)
if oedata is not None:
block_nb = self.currentBlock().blockNumber()
self.outlineexplorer_data[block_nb] = oedata
self.outlineexplorer_data['found_cell_separators'] = self.found_cell_separators
if import_stmt is not None:
block_nb = self.currentBlock().blockNumber()
self.import_statements[block_nb] = import_stmt | python | def highlight_block(self, text):
"""Implement specific highlight for Python."""
text = to_text_string(text)
prev_state = tbh.get_state(self.currentBlock().previous())
if prev_state == self.INSIDE_DQ3STRING:
offset = -4
text = r'""" '+text
elif prev_state == self.INSIDE_SQ3STRING:
offset = -4
text = r"''' "+text
elif prev_state == self.INSIDE_DQSTRING:
offset = -2
text = r'" '+text
elif prev_state == self.INSIDE_SQSTRING:
offset = -2
text = r"' "+text
else:
offset = 0
prev_state = self.NORMAL
oedata = None
import_stmt = None
self.setFormat(0, len(text), self.formats["normal"])
state = self.NORMAL
match = self.PROG.search(text)
while match:
for key, value in list(match.groupdict().items()):
if value:
start, end = match.span(key)
start = max([0, start+offset])
end = max([0, end+offset])
if key == "uf_sq3string":
self.setFormat(start, end-start,
self.formats["string"])
state = self.INSIDE_SQ3STRING
elif key == "uf_dq3string":
self.setFormat(start, end-start,
self.formats["string"])
state = self.INSIDE_DQ3STRING
elif key == "uf_sqstring":
self.setFormat(start, end-start,
self.formats["string"])
state = self.INSIDE_SQSTRING
elif key == "uf_dqstring":
self.setFormat(start, end-start,
self.formats["string"])
state = self.INSIDE_DQSTRING
else:
self.setFormat(start, end-start, self.formats[key])
if key == "comment":
if text.lstrip().startswith(self.cell_separators):
self.found_cell_separators = True
oedata = OutlineExplorerData()
oedata.text = to_text_string(text).strip()
# cell_head: string contaning the first group
# of '%'s in the cell header
cell_head = re.search(r"%+|$",
text.lstrip()).group()
if cell_head == '':
oedata.cell_level = 0
else:
oedata.cell_level = len(cell_head) - 2
oedata.fold_level = start
oedata.def_type = OutlineExplorerData.CELL
oedata.def_name = get_code_cell_name(text)
elif self.OECOMMENT.match(text.lstrip()):
oedata = OutlineExplorerData()
oedata.text = to_text_string(text).strip()
oedata.fold_level = start
oedata.def_type = OutlineExplorerData.COMMENT
oedata.def_name = text.strip()
elif key == "keyword":
if value in ("def", "class"):
match1 = self.IDPROG.match(text, end)
if match1:
start1, end1 = match1.span(1)
self.setFormat(start1, end1-start1,
self.formats["definition"])
oedata = OutlineExplorerData()
oedata.text = to_text_string(text)
oedata.fold_level = (len(text)
- len(text.lstrip()))
oedata.def_type = self.DEF_TYPES[
to_text_string(value)]
oedata.def_name = text[start1:end1]
oedata.color = self.formats["definition"]
elif value in ("elif", "else", "except", "finally",
"for", "if", "try", "while",
"with"):
if text.lstrip().startswith(value):
oedata = OutlineExplorerData()
oedata.text = to_text_string(text).strip()
oedata.fold_level = start
oedata.def_type = \
OutlineExplorerData.STATEMENT
oedata.def_name = text.strip()
elif value == "import":
import_stmt = text.strip()
# color all the "as" words on same line, except
# if in a comment; cheap approximation to the
# truth
if '#' in text:
endpos = text.index('#')
else:
endpos = len(text)
while True:
match1 = self.ASPROG.match(text, end,
endpos)
if not match1:
break
start, end = match1.span(1)
self.setFormat(start, end-start,
self.formats["keyword"])
match = self.PROG.search(text, match.end())
tbh.set_state(self.currentBlock(), state)
# Use normal format for indentation and trailing spaces.
self.formats['leading'] = self.formats['normal']
self.formats['trailing'] = self.formats['normal']
self.highlight_spaces(text, offset)
if oedata is not None:
block_nb = self.currentBlock().blockNumber()
self.outlineexplorer_data[block_nb] = oedata
self.outlineexplorer_data['found_cell_separators'] = self.found_cell_separators
if import_stmt is not None:
block_nb = self.currentBlock().blockNumber()
self.import_statements[block_nb] = import_stmt | [
"def",
"highlight_block",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"to_text_string",
"(",
"text",
")",
"prev_state",
"=",
"tbh",
".",
"get_state",
"(",
"self",
".",
"currentBlock",
"(",
")",
".",
"previous",
"(",
")",
")",
"if",
"prev_state",
"==",
"self",
".",
"INSIDE_DQ3STRING",
":",
"offset",
"=",
"-",
"4",
"text",
"=",
"r'\"\"\" '",
"+",
"text",
"elif",
"prev_state",
"==",
"self",
".",
"INSIDE_SQ3STRING",
":",
"offset",
"=",
"-",
"4",
"text",
"=",
"r\"''' \"",
"+",
"text",
"elif",
"prev_state",
"==",
"self",
".",
"INSIDE_DQSTRING",
":",
"offset",
"=",
"-",
"2",
"text",
"=",
"r'\" '",
"+",
"text",
"elif",
"prev_state",
"==",
"self",
".",
"INSIDE_SQSTRING",
":",
"offset",
"=",
"-",
"2",
"text",
"=",
"r\"' \"",
"+",
"text",
"else",
":",
"offset",
"=",
"0",
"prev_state",
"=",
"self",
".",
"NORMAL",
"oedata",
"=",
"None",
"import_stmt",
"=",
"None",
"self",
".",
"setFormat",
"(",
"0",
",",
"len",
"(",
"text",
")",
",",
"self",
".",
"formats",
"[",
"\"normal\"",
"]",
")",
"state",
"=",
"self",
".",
"NORMAL",
"match",
"=",
"self",
".",
"PROG",
".",
"search",
"(",
"text",
")",
"while",
"match",
":",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"match",
".",
"groupdict",
"(",
")",
".",
"items",
"(",
")",
")",
":",
"if",
"value",
":",
"start",
",",
"end",
"=",
"match",
".",
"span",
"(",
"key",
")",
"start",
"=",
"max",
"(",
"[",
"0",
",",
"start",
"+",
"offset",
"]",
")",
"end",
"=",
"max",
"(",
"[",
"0",
",",
"end",
"+",
"offset",
"]",
")",
"if",
"key",
"==",
"\"uf_sq3string\"",
":",
"self",
".",
"setFormat",
"(",
"start",
",",
"end",
"-",
"start",
",",
"self",
".",
"formats",
"[",
"\"string\"",
"]",
")",
"state",
"=",
"self",
".",
"INSIDE_SQ3STRING",
"elif",
"key",
"==",
"\"uf_dq3string\"",
":",
"self",
".",
"setFormat",
"(",
"start",
",",
"end",
"-",
"start",
",",
"self",
".",
"formats",
"[",
"\"string\"",
"]",
")",
"state",
"=",
"self",
".",
"INSIDE_DQ3STRING",
"elif",
"key",
"==",
"\"uf_sqstring\"",
":",
"self",
".",
"setFormat",
"(",
"start",
",",
"end",
"-",
"start",
",",
"self",
".",
"formats",
"[",
"\"string\"",
"]",
")",
"state",
"=",
"self",
".",
"INSIDE_SQSTRING",
"elif",
"key",
"==",
"\"uf_dqstring\"",
":",
"self",
".",
"setFormat",
"(",
"start",
",",
"end",
"-",
"start",
",",
"self",
".",
"formats",
"[",
"\"string\"",
"]",
")",
"state",
"=",
"self",
".",
"INSIDE_DQSTRING",
"else",
":",
"self",
".",
"setFormat",
"(",
"start",
",",
"end",
"-",
"start",
",",
"self",
".",
"formats",
"[",
"key",
"]",
")",
"if",
"key",
"==",
"\"comment\"",
":",
"if",
"text",
".",
"lstrip",
"(",
")",
".",
"startswith",
"(",
"self",
".",
"cell_separators",
")",
":",
"self",
".",
"found_cell_separators",
"=",
"True",
"oedata",
"=",
"OutlineExplorerData",
"(",
")",
"oedata",
".",
"text",
"=",
"to_text_string",
"(",
"text",
")",
".",
"strip",
"(",
")",
"# cell_head: string contaning the first group\r",
"# of '%'s in the cell header\r",
"cell_head",
"=",
"re",
".",
"search",
"(",
"r\"%+|$\"",
",",
"text",
".",
"lstrip",
"(",
")",
")",
".",
"group",
"(",
")",
"if",
"cell_head",
"==",
"''",
":",
"oedata",
".",
"cell_level",
"=",
"0",
"else",
":",
"oedata",
".",
"cell_level",
"=",
"len",
"(",
"cell_head",
")",
"-",
"2",
"oedata",
".",
"fold_level",
"=",
"start",
"oedata",
".",
"def_type",
"=",
"OutlineExplorerData",
".",
"CELL",
"oedata",
".",
"def_name",
"=",
"get_code_cell_name",
"(",
"text",
")",
"elif",
"self",
".",
"OECOMMENT",
".",
"match",
"(",
"text",
".",
"lstrip",
"(",
")",
")",
":",
"oedata",
"=",
"OutlineExplorerData",
"(",
")",
"oedata",
".",
"text",
"=",
"to_text_string",
"(",
"text",
")",
".",
"strip",
"(",
")",
"oedata",
".",
"fold_level",
"=",
"start",
"oedata",
".",
"def_type",
"=",
"OutlineExplorerData",
".",
"COMMENT",
"oedata",
".",
"def_name",
"=",
"text",
".",
"strip",
"(",
")",
"elif",
"key",
"==",
"\"keyword\"",
":",
"if",
"value",
"in",
"(",
"\"def\"",
",",
"\"class\"",
")",
":",
"match1",
"=",
"self",
".",
"IDPROG",
".",
"match",
"(",
"text",
",",
"end",
")",
"if",
"match1",
":",
"start1",
",",
"end1",
"=",
"match1",
".",
"span",
"(",
"1",
")",
"self",
".",
"setFormat",
"(",
"start1",
",",
"end1",
"-",
"start1",
",",
"self",
".",
"formats",
"[",
"\"definition\"",
"]",
")",
"oedata",
"=",
"OutlineExplorerData",
"(",
")",
"oedata",
".",
"text",
"=",
"to_text_string",
"(",
"text",
")",
"oedata",
".",
"fold_level",
"=",
"(",
"len",
"(",
"text",
")",
"-",
"len",
"(",
"text",
".",
"lstrip",
"(",
")",
")",
")",
"oedata",
".",
"def_type",
"=",
"self",
".",
"DEF_TYPES",
"[",
"to_text_string",
"(",
"value",
")",
"]",
"oedata",
".",
"def_name",
"=",
"text",
"[",
"start1",
":",
"end1",
"]",
"oedata",
".",
"color",
"=",
"self",
".",
"formats",
"[",
"\"definition\"",
"]",
"elif",
"value",
"in",
"(",
"\"elif\"",
",",
"\"else\"",
",",
"\"except\"",
",",
"\"finally\"",
",",
"\"for\"",
",",
"\"if\"",
",",
"\"try\"",
",",
"\"while\"",
",",
"\"with\"",
")",
":",
"if",
"text",
".",
"lstrip",
"(",
")",
".",
"startswith",
"(",
"value",
")",
":",
"oedata",
"=",
"OutlineExplorerData",
"(",
")",
"oedata",
".",
"text",
"=",
"to_text_string",
"(",
"text",
")",
".",
"strip",
"(",
")",
"oedata",
".",
"fold_level",
"=",
"start",
"oedata",
".",
"def_type",
"=",
"OutlineExplorerData",
".",
"STATEMENT",
"oedata",
".",
"def_name",
"=",
"text",
".",
"strip",
"(",
")",
"elif",
"value",
"==",
"\"import\"",
":",
"import_stmt",
"=",
"text",
".",
"strip",
"(",
")",
"# color all the \"as\" words on same line, except\r",
"# if in a comment; cheap approximation to the\r",
"# truth\r",
"if",
"'#'",
"in",
"text",
":",
"endpos",
"=",
"text",
".",
"index",
"(",
"'#'",
")",
"else",
":",
"endpos",
"=",
"len",
"(",
"text",
")",
"while",
"True",
":",
"match1",
"=",
"self",
".",
"ASPROG",
".",
"match",
"(",
"text",
",",
"end",
",",
"endpos",
")",
"if",
"not",
"match1",
":",
"break",
"start",
",",
"end",
"=",
"match1",
".",
"span",
"(",
"1",
")",
"self",
".",
"setFormat",
"(",
"start",
",",
"end",
"-",
"start",
",",
"self",
".",
"formats",
"[",
"\"keyword\"",
"]",
")",
"match",
"=",
"self",
".",
"PROG",
".",
"search",
"(",
"text",
",",
"match",
".",
"end",
"(",
")",
")",
"tbh",
".",
"set_state",
"(",
"self",
".",
"currentBlock",
"(",
")",
",",
"state",
")",
"# Use normal format for indentation and trailing spaces.\r",
"self",
".",
"formats",
"[",
"'leading'",
"]",
"=",
"self",
".",
"formats",
"[",
"'normal'",
"]",
"self",
".",
"formats",
"[",
"'trailing'",
"]",
"=",
"self",
".",
"formats",
"[",
"'normal'",
"]",
"self",
".",
"highlight_spaces",
"(",
"text",
",",
"offset",
")",
"if",
"oedata",
"is",
"not",
"None",
":",
"block_nb",
"=",
"self",
".",
"currentBlock",
"(",
")",
".",
"blockNumber",
"(",
")",
"self",
".",
"outlineexplorer_data",
"[",
"block_nb",
"]",
"=",
"oedata",
"self",
".",
"outlineexplorer_data",
"[",
"'found_cell_separators'",
"]",
"=",
"self",
".",
"found_cell_separators",
"if",
"import_stmt",
"is",
"not",
"None",
":",
"block_nb",
"=",
"self",
".",
"currentBlock",
"(",
")",
".",
"blockNumber",
"(",
")",
"self",
".",
"import_statements",
"[",
"block_nb",
"]",
"=",
"import_stmt"
] | Implement specific highlight for Python. | [
"Implement",
"specific",
"highlight",
"for",
"Python",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L426-L557 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | CppSH.highlight_block | def highlight_block(self, text):
"""Implement highlight specific for C/C++."""
text = to_text_string(text)
inside_comment = tbh.get_state(self.currentBlock().previous()) == self.INSIDE_COMMENT
self.setFormat(0, len(text),
self.formats["comment" if inside_comment else "normal"])
match = self.PROG.search(text)
index = 0
while match:
for key, value in list(match.groupdict().items()):
if value:
start, end = match.span(key)
index += end-start
if key == "comment_start":
inside_comment = True
self.setFormat(start, len(text)-start,
self.formats["comment"])
elif key == "comment_end":
inside_comment = False
self.setFormat(start, end-start,
self.formats["comment"])
elif inside_comment:
self.setFormat(start, end-start,
self.formats["comment"])
elif key == "define":
self.setFormat(start, end-start,
self.formats["number"])
else:
self.setFormat(start, end-start, self.formats[key])
match = self.PROG.search(text, match.end())
self.highlight_spaces(text)
last_state = self.INSIDE_COMMENT if inside_comment else self.NORMAL
tbh.set_state(self.currentBlock(), last_state) | python | def highlight_block(self, text):
"""Implement highlight specific for C/C++."""
text = to_text_string(text)
inside_comment = tbh.get_state(self.currentBlock().previous()) == self.INSIDE_COMMENT
self.setFormat(0, len(text),
self.formats["comment" if inside_comment else "normal"])
match = self.PROG.search(text)
index = 0
while match:
for key, value in list(match.groupdict().items()):
if value:
start, end = match.span(key)
index += end-start
if key == "comment_start":
inside_comment = True
self.setFormat(start, len(text)-start,
self.formats["comment"])
elif key == "comment_end":
inside_comment = False
self.setFormat(start, end-start,
self.formats["comment"])
elif inside_comment:
self.setFormat(start, end-start,
self.formats["comment"])
elif key == "define":
self.setFormat(start, end-start,
self.formats["number"])
else:
self.setFormat(start, end-start, self.formats[key])
match = self.PROG.search(text, match.end())
self.highlight_spaces(text)
last_state = self.INSIDE_COMMENT if inside_comment else self.NORMAL
tbh.set_state(self.currentBlock(), last_state) | [
"def",
"highlight_block",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"to_text_string",
"(",
"text",
")",
"inside_comment",
"=",
"tbh",
".",
"get_state",
"(",
"self",
".",
"currentBlock",
"(",
")",
".",
"previous",
"(",
")",
")",
"==",
"self",
".",
"INSIDE_COMMENT",
"self",
".",
"setFormat",
"(",
"0",
",",
"len",
"(",
"text",
")",
",",
"self",
".",
"formats",
"[",
"\"comment\"",
"if",
"inside_comment",
"else",
"\"normal\"",
"]",
")",
"match",
"=",
"self",
".",
"PROG",
".",
"search",
"(",
"text",
")",
"index",
"=",
"0",
"while",
"match",
":",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"match",
".",
"groupdict",
"(",
")",
".",
"items",
"(",
")",
")",
":",
"if",
"value",
":",
"start",
",",
"end",
"=",
"match",
".",
"span",
"(",
"key",
")",
"index",
"+=",
"end",
"-",
"start",
"if",
"key",
"==",
"\"comment_start\"",
":",
"inside_comment",
"=",
"True",
"self",
".",
"setFormat",
"(",
"start",
",",
"len",
"(",
"text",
")",
"-",
"start",
",",
"self",
".",
"formats",
"[",
"\"comment\"",
"]",
")",
"elif",
"key",
"==",
"\"comment_end\"",
":",
"inside_comment",
"=",
"False",
"self",
".",
"setFormat",
"(",
"start",
",",
"end",
"-",
"start",
",",
"self",
".",
"formats",
"[",
"\"comment\"",
"]",
")",
"elif",
"inside_comment",
":",
"self",
".",
"setFormat",
"(",
"start",
",",
"end",
"-",
"start",
",",
"self",
".",
"formats",
"[",
"\"comment\"",
"]",
")",
"elif",
"key",
"==",
"\"define\"",
":",
"self",
".",
"setFormat",
"(",
"start",
",",
"end",
"-",
"start",
",",
"self",
".",
"formats",
"[",
"\"number\"",
"]",
")",
"else",
":",
"self",
".",
"setFormat",
"(",
"start",
",",
"end",
"-",
"start",
",",
"self",
".",
"formats",
"[",
"key",
"]",
")",
"match",
"=",
"self",
".",
"PROG",
".",
"search",
"(",
"text",
",",
"match",
".",
"end",
"(",
")",
")",
"self",
".",
"highlight_spaces",
"(",
"text",
")",
"last_state",
"=",
"self",
".",
"INSIDE_COMMENT",
"if",
"inside_comment",
"else",
"self",
".",
"NORMAL",
"tbh",
".",
"set_state",
"(",
"self",
".",
"currentBlock",
"(",
")",
",",
"last_state",
")"
] | Implement highlight specific for C/C++. | [
"Implement",
"highlight",
"specific",
"for",
"C",
"/",
"C",
"++",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L644-L680 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | FortranSH.highlight_block | def highlight_block(self, text):
"""Implement highlight specific for Fortran."""
text = to_text_string(text)
self.setFormat(0, len(text), self.formats["normal"])
match = self.PROG.search(text)
index = 0
while match:
for key, value in list(match.groupdict().items()):
if value:
start, end = match.span(key)
index += end-start
self.setFormat(start, end-start, self.formats[key])
if value.lower() in ("subroutine", "module", "function"):
match1 = self.IDPROG.match(text, end)
if match1:
start1, end1 = match1.span(1)
self.setFormat(start1, end1-start1,
self.formats["definition"])
match = self.PROG.search(text, match.end())
self.highlight_spaces(text) | python | def highlight_block(self, text):
"""Implement highlight specific for Fortran."""
text = to_text_string(text)
self.setFormat(0, len(text), self.formats["normal"])
match = self.PROG.search(text)
index = 0
while match:
for key, value in list(match.groupdict().items()):
if value:
start, end = match.span(key)
index += end-start
self.setFormat(start, end-start, self.formats[key])
if value.lower() in ("subroutine", "module", "function"):
match1 = self.IDPROG.match(text, end)
if match1:
start1, end1 = match1.span(1)
self.setFormat(start1, end1-start1,
self.formats["definition"])
match = self.PROG.search(text, match.end())
self.highlight_spaces(text) | [
"def",
"highlight_block",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"to_text_string",
"(",
"text",
")",
"self",
".",
"setFormat",
"(",
"0",
",",
"len",
"(",
"text",
")",
",",
"self",
".",
"formats",
"[",
"\"normal\"",
"]",
")",
"match",
"=",
"self",
".",
"PROG",
".",
"search",
"(",
"text",
")",
"index",
"=",
"0",
"while",
"match",
":",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"match",
".",
"groupdict",
"(",
")",
".",
"items",
"(",
")",
")",
":",
"if",
"value",
":",
"start",
",",
"end",
"=",
"match",
".",
"span",
"(",
"key",
")",
"index",
"+=",
"end",
"-",
"start",
"self",
".",
"setFormat",
"(",
"start",
",",
"end",
"-",
"start",
",",
"self",
".",
"formats",
"[",
"key",
"]",
")",
"if",
"value",
".",
"lower",
"(",
")",
"in",
"(",
"\"subroutine\"",
",",
"\"module\"",
",",
"\"function\"",
")",
":",
"match1",
"=",
"self",
".",
"IDPROG",
".",
"match",
"(",
"text",
",",
"end",
")",
"if",
"match1",
":",
"start1",
",",
"end1",
"=",
"match1",
".",
"span",
"(",
"1",
")",
"self",
".",
"setFormat",
"(",
"start1",
",",
"end1",
"-",
"start1",
",",
"self",
".",
"formats",
"[",
"\"definition\"",
"]",
")",
"match",
"=",
"self",
".",
"PROG",
".",
"search",
"(",
"text",
",",
"match",
".",
"end",
"(",
")",
")",
"self",
".",
"highlight_spaces",
"(",
"text",
")"
] | Implement highlight specific for Fortran. | [
"Implement",
"highlight",
"specific",
"for",
"Fortran",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L733-L755 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | Fortran77SH.highlight_block | def highlight_block(self, text):
"""Implement highlight specific for Fortran77."""
text = to_text_string(text)
if text.startswith(("c", "C")):
self.setFormat(0, len(text), self.formats["comment"])
self.highlight_spaces(text)
else:
FortranSH.highlight_block(self, text)
self.setFormat(0, 5, self.formats["comment"])
self.setFormat(73, max([73, len(text)]),
self.formats["comment"]) | python | def highlight_block(self, text):
"""Implement highlight specific for Fortran77."""
text = to_text_string(text)
if text.startswith(("c", "C")):
self.setFormat(0, len(text), self.formats["comment"])
self.highlight_spaces(text)
else:
FortranSH.highlight_block(self, text)
self.setFormat(0, 5, self.formats["comment"])
self.setFormat(73, max([73, len(text)]),
self.formats["comment"]) | [
"def",
"highlight_block",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"to_text_string",
"(",
"text",
")",
"if",
"text",
".",
"startswith",
"(",
"(",
"\"c\"",
",",
"\"C\"",
")",
")",
":",
"self",
".",
"setFormat",
"(",
"0",
",",
"len",
"(",
"text",
")",
",",
"self",
".",
"formats",
"[",
"\"comment\"",
"]",
")",
"self",
".",
"highlight_spaces",
"(",
"text",
")",
"else",
":",
"FortranSH",
".",
"highlight_block",
"(",
"self",
",",
"text",
")",
"self",
".",
"setFormat",
"(",
"0",
",",
"5",
",",
"self",
".",
"formats",
"[",
"\"comment\"",
"]",
")",
"self",
".",
"setFormat",
"(",
"73",
",",
"max",
"(",
"[",
"73",
",",
"len",
"(",
"text",
")",
"]",
")",
",",
"self",
".",
"formats",
"[",
"\"comment\"",
"]",
")"
] | Implement highlight specific for Fortran77. | [
"Implement",
"highlight",
"specific",
"for",
"Fortran77",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L759-L769 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | DiffSH.highlight_block | def highlight_block(self, text):
"""Implement highlight specific Diff/Patch files."""
text = to_text_string(text)
if text.startswith("+++"):
self.setFormat(0, len(text), self.formats["keyword"])
elif text.startswith("---"):
self.setFormat(0, len(text), self.formats["keyword"])
elif text.startswith("+"):
self.setFormat(0, len(text), self.formats["string"])
elif text.startswith("-"):
self.setFormat(0, len(text), self.formats["number"])
elif text.startswith("@"):
self.setFormat(0, len(text), self.formats["builtin"])
self.highlight_spaces(text) | python | def highlight_block(self, text):
"""Implement highlight specific Diff/Patch files."""
text = to_text_string(text)
if text.startswith("+++"):
self.setFormat(0, len(text), self.formats["keyword"])
elif text.startswith("---"):
self.setFormat(0, len(text), self.formats["keyword"])
elif text.startswith("+"):
self.setFormat(0, len(text), self.formats["string"])
elif text.startswith("-"):
self.setFormat(0, len(text), self.formats["number"])
elif text.startswith("@"):
self.setFormat(0, len(text), self.formats["builtin"])
self.highlight_spaces(text) | [
"def",
"highlight_block",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"to_text_string",
"(",
"text",
")",
"if",
"text",
".",
"startswith",
"(",
"\"+++\"",
")",
":",
"self",
".",
"setFormat",
"(",
"0",
",",
"len",
"(",
"text",
")",
",",
"self",
".",
"formats",
"[",
"\"keyword\"",
"]",
")",
"elif",
"text",
".",
"startswith",
"(",
"\"---\"",
")",
":",
"self",
".",
"setFormat",
"(",
"0",
",",
"len",
"(",
"text",
")",
",",
"self",
".",
"formats",
"[",
"\"keyword\"",
"]",
")",
"elif",
"text",
".",
"startswith",
"(",
"\"+\"",
")",
":",
"self",
".",
"setFormat",
"(",
"0",
",",
"len",
"(",
"text",
")",
",",
"self",
".",
"formats",
"[",
"\"string\"",
"]",
")",
"elif",
"text",
".",
"startswith",
"(",
"\"-\"",
")",
":",
"self",
".",
"setFormat",
"(",
"0",
",",
"len",
"(",
"text",
")",
",",
"self",
".",
"formats",
"[",
"\"number\"",
"]",
")",
"elif",
"text",
".",
"startswith",
"(",
"\"@\"",
")",
":",
"self",
".",
"setFormat",
"(",
"0",
",",
"len",
"(",
"text",
")",
",",
"self",
".",
"formats",
"[",
"\"builtin\"",
"]",
")",
"self",
".",
"highlight_spaces",
"(",
"text",
")"
] | Implement highlight specific Diff/Patch files. | [
"Implement",
"highlight",
"specific",
"Diff",
"/",
"Patch",
"files",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L809-L823 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | BaseWebSH.highlight_block | def highlight_block(self, text):
"""Implement highlight specific for CSS and HTML."""
text = to_text_string(text)
previous_state = tbh.get_state(self.currentBlock().previous())
if previous_state == self.COMMENT:
self.setFormat(0, len(text), self.formats["comment"])
else:
previous_state = self.NORMAL
self.setFormat(0, len(text), self.formats["normal"])
tbh.set_state(self.currentBlock(), previous_state)
match = self.PROG.search(text)
match_count = 0
n_characters = len(text)
# There should never be more matches than characters in the text.
while match and match_count < n_characters:
match_dict = match.groupdict()
for key, value in list(match_dict.items()):
if value:
start, end = match.span(key)
if previous_state == self.COMMENT:
if key == "multiline_comment_end":
tbh.set_state(self.currentBlock(), self.NORMAL)
self.setFormat(end, len(text),
self.formats["normal"])
else:
tbh.set_state(self.currentBlock(), self.COMMENT)
self.setFormat(0, len(text),
self.formats["comment"])
else:
if key == "multiline_comment_start":
tbh.set_state(self.currentBlock(), self.COMMENT)
self.setFormat(start, len(text),
self.formats["comment"])
else:
tbh.set_state(self.currentBlock(), self.NORMAL)
try:
self.setFormat(start, end-start,
self.formats[key])
except KeyError:
# happens with unmatched end-of-comment;
# see issue 1462
pass
match = self.PROG.search(text, match.end())
match_count += 1
self.highlight_spaces(text) | python | def highlight_block(self, text):
"""Implement highlight specific for CSS and HTML."""
text = to_text_string(text)
previous_state = tbh.get_state(self.currentBlock().previous())
if previous_state == self.COMMENT:
self.setFormat(0, len(text), self.formats["comment"])
else:
previous_state = self.NORMAL
self.setFormat(0, len(text), self.formats["normal"])
tbh.set_state(self.currentBlock(), previous_state)
match = self.PROG.search(text)
match_count = 0
n_characters = len(text)
# There should never be more matches than characters in the text.
while match and match_count < n_characters:
match_dict = match.groupdict()
for key, value in list(match_dict.items()):
if value:
start, end = match.span(key)
if previous_state == self.COMMENT:
if key == "multiline_comment_end":
tbh.set_state(self.currentBlock(), self.NORMAL)
self.setFormat(end, len(text),
self.formats["normal"])
else:
tbh.set_state(self.currentBlock(), self.COMMENT)
self.setFormat(0, len(text),
self.formats["comment"])
else:
if key == "multiline_comment_start":
tbh.set_state(self.currentBlock(), self.COMMENT)
self.setFormat(start, len(text),
self.formats["comment"])
else:
tbh.set_state(self.currentBlock(), self.NORMAL)
try:
self.setFormat(start, end-start,
self.formats[key])
except KeyError:
# happens with unmatched end-of-comment;
# see issue 1462
pass
match = self.PROG.search(text, match.end())
match_count += 1
self.highlight_spaces(text) | [
"def",
"highlight_block",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"to_text_string",
"(",
"text",
")",
"previous_state",
"=",
"tbh",
".",
"get_state",
"(",
"self",
".",
"currentBlock",
"(",
")",
".",
"previous",
"(",
")",
")",
"if",
"previous_state",
"==",
"self",
".",
"COMMENT",
":",
"self",
".",
"setFormat",
"(",
"0",
",",
"len",
"(",
"text",
")",
",",
"self",
".",
"formats",
"[",
"\"comment\"",
"]",
")",
"else",
":",
"previous_state",
"=",
"self",
".",
"NORMAL",
"self",
".",
"setFormat",
"(",
"0",
",",
"len",
"(",
"text",
")",
",",
"self",
".",
"formats",
"[",
"\"normal\"",
"]",
")",
"tbh",
".",
"set_state",
"(",
"self",
".",
"currentBlock",
"(",
")",
",",
"previous_state",
")",
"match",
"=",
"self",
".",
"PROG",
".",
"search",
"(",
"text",
")",
"match_count",
"=",
"0",
"n_characters",
"=",
"len",
"(",
"text",
")",
"# There should never be more matches than characters in the text.\r",
"while",
"match",
"and",
"match_count",
"<",
"n_characters",
":",
"match_dict",
"=",
"match",
".",
"groupdict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"match_dict",
".",
"items",
"(",
")",
")",
":",
"if",
"value",
":",
"start",
",",
"end",
"=",
"match",
".",
"span",
"(",
"key",
")",
"if",
"previous_state",
"==",
"self",
".",
"COMMENT",
":",
"if",
"key",
"==",
"\"multiline_comment_end\"",
":",
"tbh",
".",
"set_state",
"(",
"self",
".",
"currentBlock",
"(",
")",
",",
"self",
".",
"NORMAL",
")",
"self",
".",
"setFormat",
"(",
"end",
",",
"len",
"(",
"text",
")",
",",
"self",
".",
"formats",
"[",
"\"normal\"",
"]",
")",
"else",
":",
"tbh",
".",
"set_state",
"(",
"self",
".",
"currentBlock",
"(",
")",
",",
"self",
".",
"COMMENT",
")",
"self",
".",
"setFormat",
"(",
"0",
",",
"len",
"(",
"text",
")",
",",
"self",
".",
"formats",
"[",
"\"comment\"",
"]",
")",
"else",
":",
"if",
"key",
"==",
"\"multiline_comment_start\"",
":",
"tbh",
".",
"set_state",
"(",
"self",
".",
"currentBlock",
"(",
")",
",",
"self",
".",
"COMMENT",
")",
"self",
".",
"setFormat",
"(",
"start",
",",
"len",
"(",
"text",
")",
",",
"self",
".",
"formats",
"[",
"\"comment\"",
"]",
")",
"else",
":",
"tbh",
".",
"set_state",
"(",
"self",
".",
"currentBlock",
"(",
")",
",",
"self",
".",
"NORMAL",
")",
"try",
":",
"self",
".",
"setFormat",
"(",
"start",
",",
"end",
"-",
"start",
",",
"self",
".",
"formats",
"[",
"key",
"]",
")",
"except",
"KeyError",
":",
"# happens with unmatched end-of-comment;\r",
"# see issue 1462\r",
"pass",
"match",
"=",
"self",
".",
"PROG",
".",
"search",
"(",
"text",
",",
"match",
".",
"end",
"(",
")",
")",
"match_count",
"+=",
"1",
"self",
".",
"highlight_spaces",
"(",
"text",
")"
] | Implement highlight specific for CSS and HTML. | [
"Implement",
"highlight",
"specific",
"for",
"CSS",
"and",
"HTML",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L911-L960 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | PygmentsSH.make_charlist | def make_charlist(self):
"""Parses the complete text and stores format for each character."""
def worker_output(worker, output, error):
"""Worker finished callback."""
self._charlist = output
if error is None and output:
self._allow_highlight = True
self.rehighlight()
self._allow_highlight = False
text = to_text_string(self.document().toPlainText())
tokens = self._lexer.get_tokens(text)
# Before starting a new worker process make sure to end previous
# incarnations
self._worker_manager.terminate_all()
worker = self._worker_manager.create_python_worker(
self._make_charlist,
tokens,
self._tokmap,
self.formats,
)
worker.sig_finished.connect(worker_output)
worker.start() | python | def make_charlist(self):
"""Parses the complete text and stores format for each character."""
def worker_output(worker, output, error):
"""Worker finished callback."""
self._charlist = output
if error is None and output:
self._allow_highlight = True
self.rehighlight()
self._allow_highlight = False
text = to_text_string(self.document().toPlainText())
tokens = self._lexer.get_tokens(text)
# Before starting a new worker process make sure to end previous
# incarnations
self._worker_manager.terminate_all()
worker = self._worker_manager.create_python_worker(
self._make_charlist,
tokens,
self._tokmap,
self.formats,
)
worker.sig_finished.connect(worker_output)
worker.start() | [
"def",
"make_charlist",
"(",
"self",
")",
":",
"def",
"worker_output",
"(",
"worker",
",",
"output",
",",
"error",
")",
":",
"\"\"\"Worker finished callback.\"\"\"",
"self",
".",
"_charlist",
"=",
"output",
"if",
"error",
"is",
"None",
"and",
"output",
":",
"self",
".",
"_allow_highlight",
"=",
"True",
"self",
".",
"rehighlight",
"(",
")",
"self",
".",
"_allow_highlight",
"=",
"False",
"text",
"=",
"to_text_string",
"(",
"self",
".",
"document",
"(",
")",
".",
"toPlainText",
"(",
")",
")",
"tokens",
"=",
"self",
".",
"_lexer",
".",
"get_tokens",
"(",
"text",
")",
"# Before starting a new worker process make sure to end previous\r",
"# incarnations\r",
"self",
".",
"_worker_manager",
".",
"terminate_all",
"(",
")",
"worker",
"=",
"self",
".",
"_worker_manager",
".",
"create_python_worker",
"(",
"self",
".",
"_make_charlist",
",",
"tokens",
",",
"self",
".",
"_tokmap",
",",
"self",
".",
"formats",
",",
")",
"worker",
".",
"sig_finished",
".",
"connect",
"(",
"worker_output",
")",
"worker",
".",
"start",
"(",
")"
] | Parses the complete text and stores format for each character. | [
"Parses",
"the",
"complete",
"text",
"and",
"stores",
"format",
"for",
"each",
"character",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L1161-L1186 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | PygmentsSH._make_charlist | def _make_charlist(self, tokens, tokmap, formats):
"""
Parses the complete text and stores format for each character.
Uses the attached lexer to parse into a list of tokens and Pygments
token types. Then breaks tokens into individual letters, each with a
Spyder token type attached. Stores this list as self._charlist.
It's attached to the contentsChange signal of the parent QTextDocument
so that the charlist is updated whenever the document changes.
"""
def _get_fmt(typ):
"""Get the Spyder format code for the given Pygments token type."""
# Exact matches first
if typ in tokmap:
return tokmap[typ]
# Partial (parent-> child) matches
for key, val in tokmap.items():
if typ in key: # Checks if typ is a subtype of key.
return val
return 'normal'
charlist = []
for typ, token in tokens:
fmt = formats[_get_fmt(typ)]
for letter in token:
charlist.append((fmt, letter))
return charlist | python | def _make_charlist(self, tokens, tokmap, formats):
"""
Parses the complete text and stores format for each character.
Uses the attached lexer to parse into a list of tokens and Pygments
token types. Then breaks tokens into individual letters, each with a
Spyder token type attached. Stores this list as self._charlist.
It's attached to the contentsChange signal of the parent QTextDocument
so that the charlist is updated whenever the document changes.
"""
def _get_fmt(typ):
"""Get the Spyder format code for the given Pygments token type."""
# Exact matches first
if typ in tokmap:
return tokmap[typ]
# Partial (parent-> child) matches
for key, val in tokmap.items():
if typ in key: # Checks if typ is a subtype of key.
return val
return 'normal'
charlist = []
for typ, token in tokens:
fmt = formats[_get_fmt(typ)]
for letter in token:
charlist.append((fmt, letter))
return charlist | [
"def",
"_make_charlist",
"(",
"self",
",",
"tokens",
",",
"tokmap",
",",
"formats",
")",
":",
"def",
"_get_fmt",
"(",
"typ",
")",
":",
"\"\"\"Get the Spyder format code for the given Pygments token type.\"\"\"",
"# Exact matches first\r",
"if",
"typ",
"in",
"tokmap",
":",
"return",
"tokmap",
"[",
"typ",
"]",
"# Partial (parent-> child) matches\r",
"for",
"key",
",",
"val",
"in",
"tokmap",
".",
"items",
"(",
")",
":",
"if",
"typ",
"in",
"key",
":",
"# Checks if typ is a subtype of key.\r",
"return",
"val",
"return",
"'normal'",
"charlist",
"=",
"[",
"]",
"for",
"typ",
",",
"token",
"in",
"tokens",
":",
"fmt",
"=",
"formats",
"[",
"_get_fmt",
"(",
"typ",
")",
"]",
"for",
"letter",
"in",
"token",
":",
"charlist",
".",
"append",
"(",
"(",
"fmt",
",",
"letter",
")",
")",
"return",
"charlist"
] | Parses the complete text and stores format for each character.
Uses the attached lexer to parse into a list of tokens and Pygments
token types. Then breaks tokens into individual letters, each with a
Spyder token type attached. Stores this list as self._charlist.
It's attached to the contentsChange signal of the parent QTextDocument
so that the charlist is updated whenever the document changes. | [
"Parses",
"the",
"complete",
"text",
"and",
"stores",
"format",
"for",
"each",
"character",
".",
"Uses",
"the",
"attached",
"lexer",
"to",
"parse",
"into",
"a",
"list",
"of",
"tokens",
"and",
"Pygments",
"token",
"types",
".",
"Then",
"breaks",
"tokens",
"into",
"individual",
"letters",
"each",
"with",
"a",
"Spyder",
"token",
"type",
"attached",
".",
"Stores",
"this",
"list",
"as",
"self",
".",
"_charlist",
".",
"It",
"s",
"attached",
"to",
"the",
"contentsChange",
"signal",
"of",
"the",
"parent",
"QTextDocument",
"so",
"that",
"the",
"charlist",
"is",
"updated",
"whenever",
"the",
"document",
"changes",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L1188-L1218 | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | PygmentsSH.highlightBlock | def highlightBlock(self, text):
""" Actually highlight the block"""
# Note that an undefined blockstate is equal to -1, so the first block
# will have the correct behaviour of starting at 0.
if self._allow_highlight:
start = self.previousBlockState() + 1
end = start + len(text)
for i, (fmt, letter) in enumerate(self._charlist[start:end]):
self.setFormat(i, 1, fmt)
self.setCurrentBlockState(end)
self.highlight_spaces(text) | python | def highlightBlock(self, text):
""" Actually highlight the block"""
# Note that an undefined blockstate is equal to -1, so the first block
# will have the correct behaviour of starting at 0.
if self._allow_highlight:
start = self.previousBlockState() + 1
end = start + len(text)
for i, (fmt, letter) in enumerate(self._charlist[start:end]):
self.setFormat(i, 1, fmt)
self.setCurrentBlockState(end)
self.highlight_spaces(text) | [
"def",
"highlightBlock",
"(",
"self",
",",
"text",
")",
":",
"# Note that an undefined blockstate is equal to -1, so the first block\r",
"# will have the correct behaviour of starting at 0.\r",
"if",
"self",
".",
"_allow_highlight",
":",
"start",
"=",
"self",
".",
"previousBlockState",
"(",
")",
"+",
"1",
"end",
"=",
"start",
"+",
"len",
"(",
"text",
")",
"for",
"i",
",",
"(",
"fmt",
",",
"letter",
")",
"in",
"enumerate",
"(",
"self",
".",
"_charlist",
"[",
"start",
":",
"end",
"]",
")",
":",
"self",
".",
"setFormat",
"(",
"i",
",",
"1",
",",
"fmt",
")",
"self",
".",
"setCurrentBlockState",
"(",
"end",
")",
"self",
".",
"highlight_spaces",
"(",
"text",
")"
] | Actually highlight the block | [
"Actually",
"highlight",
"the",
"block"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L1220-L1230 | train |
spyder-ide/spyder | spyder/utils/introspection/module_completion.py | get_submodules | def get_submodules(mod):
"""Get all submodules of a given module"""
def catch_exceptions(module):
pass
try:
m = __import__(mod)
submodules = [mod]
submods = pkgutil.walk_packages(m.__path__, m.__name__ + '.',
catch_exceptions)
for sm in submods:
sm_name = sm[1]
submodules.append(sm_name)
except ImportError:
return []
except:
return [mod]
return submodules | python | def get_submodules(mod):
"""Get all submodules of a given module"""
def catch_exceptions(module):
pass
try:
m = __import__(mod)
submodules = [mod]
submods = pkgutil.walk_packages(m.__path__, m.__name__ + '.',
catch_exceptions)
for sm in submods:
sm_name = sm[1]
submodules.append(sm_name)
except ImportError:
return []
except:
return [mod]
return submodules | [
"def",
"get_submodules",
"(",
"mod",
")",
":",
"def",
"catch_exceptions",
"(",
"module",
")",
":",
"pass",
"try",
":",
"m",
"=",
"__import__",
"(",
"mod",
")",
"submodules",
"=",
"[",
"mod",
"]",
"submods",
"=",
"pkgutil",
".",
"walk_packages",
"(",
"m",
".",
"__path__",
",",
"m",
".",
"__name__",
"+",
"'.'",
",",
"catch_exceptions",
")",
"for",
"sm",
"in",
"submods",
":",
"sm_name",
"=",
"sm",
"[",
"1",
"]",
"submodules",
".",
"append",
"(",
"sm_name",
")",
"except",
"ImportError",
":",
"return",
"[",
"]",
"except",
":",
"return",
"[",
"mod",
"]",
"return",
"submodules"
] | Get all submodules of a given module | [
"Get",
"all",
"submodules",
"of",
"a",
"given",
"module"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/module_completion.py#L34-L51 | train |
spyder-ide/spyder | spyder/utils/introspection/module_completion.py | get_preferred_submodules | def get_preferred_submodules():
"""
Get all submodules of the main scientific modules and others of our
interest
"""
# Path to the modules database
modules_path = get_conf_path('db')
# Modules database
modules_db = PickleShareDB(modules_path)
if 'submodules' in modules_db:
return modules_db['submodules']
submodules = []
for m in PREFERRED_MODULES:
submods = get_submodules(m)
submodules += submods
modules_db['submodules'] = submodules
return submodules | python | def get_preferred_submodules():
"""
Get all submodules of the main scientific modules and others of our
interest
"""
# Path to the modules database
modules_path = get_conf_path('db')
# Modules database
modules_db = PickleShareDB(modules_path)
if 'submodules' in modules_db:
return modules_db['submodules']
submodules = []
for m in PREFERRED_MODULES:
submods = get_submodules(m)
submodules += submods
modules_db['submodules'] = submodules
return submodules | [
"def",
"get_preferred_submodules",
"(",
")",
":",
"# Path to the modules database\r",
"modules_path",
"=",
"get_conf_path",
"(",
"'db'",
")",
"# Modules database\r",
"modules_db",
"=",
"PickleShareDB",
"(",
"modules_path",
")",
"if",
"'submodules'",
"in",
"modules_db",
":",
"return",
"modules_db",
"[",
"'submodules'",
"]",
"submodules",
"=",
"[",
"]",
"for",
"m",
"in",
"PREFERRED_MODULES",
":",
"submods",
"=",
"get_submodules",
"(",
"m",
")",
"submodules",
"+=",
"submods",
"modules_db",
"[",
"'submodules'",
"]",
"=",
"submodules",
"return",
"submodules"
] | Get all submodules of the main scientific modules and others of our
interest | [
"Get",
"all",
"submodules",
"of",
"the",
"main",
"scientific",
"modules",
"and",
"others",
"of",
"our",
"interest"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/module_completion.py#L54-L75 | train |
spyder-ide/spyder | spyder/config/base.py | is_stable_version | def is_stable_version(version):
"""
Return true if version is stable, i.e. with letters in the final component.
Stable version examples: ``1.2``, ``1.3.4``, ``1.0.5``.
Non-stable version examples: ``1.3.4beta``, ``0.1.0rc1``, ``3.0.0dev0``.
"""
if not isinstance(version, tuple):
version = version.split('.')
last_part = version[-1]
if not re.search(r'[a-zA-Z]', last_part):
return True
else:
return False | python | def is_stable_version(version):
"""
Return true if version is stable, i.e. with letters in the final component.
Stable version examples: ``1.2``, ``1.3.4``, ``1.0.5``.
Non-stable version examples: ``1.3.4beta``, ``0.1.0rc1``, ``3.0.0dev0``.
"""
if not isinstance(version, tuple):
version = version.split('.')
last_part = version[-1]
if not re.search(r'[a-zA-Z]', last_part):
return True
else:
return False | [
"def",
"is_stable_version",
"(",
"version",
")",
":",
"if",
"not",
"isinstance",
"(",
"version",
",",
"tuple",
")",
":",
"version",
"=",
"version",
".",
"split",
"(",
"'.'",
")",
"last_part",
"=",
"version",
"[",
"-",
"1",
"]",
"if",
"not",
"re",
".",
"search",
"(",
"r'[a-zA-Z]'",
",",
"last_part",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | Return true if version is stable, i.e. with letters in the final component.
Stable version examples: ``1.2``, ``1.3.4``, ``1.0.5``.
Non-stable version examples: ``1.3.4beta``, ``0.1.0rc1``, ``3.0.0dev0``. | [
"Return",
"true",
"if",
"version",
"is",
"stable",
"i",
".",
"e",
".",
"with",
"letters",
"in",
"the",
"final",
"component",
".",
"Stable",
"version",
"examples",
":",
"1",
".",
"2",
"1",
".",
"3",
".",
"4",
"1",
".",
"0",
".",
"5",
".",
"Non",
"-",
"stable",
"version",
"examples",
":",
"1",
".",
"3",
".",
"4beta",
"0",
".",
"1",
".",
"0rc1",
"3",
".",
"0",
".",
"0dev0",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L60-L74 | train |
spyder-ide/spyder | spyder/config/base.py | use_dev_config_dir | def use_dev_config_dir(use_dev_config_dir=USE_DEV_CONFIG_DIR):
"""Return whether the dev configuration directory should used."""
if use_dev_config_dir is not None:
if use_dev_config_dir.lower() in {'false', '0'}:
use_dev_config_dir = False
else:
use_dev_config_dir = DEV or not is_stable_version(__version__)
return use_dev_config_dir | python | def use_dev_config_dir(use_dev_config_dir=USE_DEV_CONFIG_DIR):
"""Return whether the dev configuration directory should used."""
if use_dev_config_dir is not None:
if use_dev_config_dir.lower() in {'false', '0'}:
use_dev_config_dir = False
else:
use_dev_config_dir = DEV or not is_stable_version(__version__)
return use_dev_config_dir | [
"def",
"use_dev_config_dir",
"(",
"use_dev_config_dir",
"=",
"USE_DEV_CONFIG_DIR",
")",
":",
"if",
"use_dev_config_dir",
"is",
"not",
"None",
":",
"if",
"use_dev_config_dir",
".",
"lower",
"(",
")",
"in",
"{",
"'false'",
",",
"'0'",
"}",
":",
"use_dev_config_dir",
"=",
"False",
"else",
":",
"use_dev_config_dir",
"=",
"DEV",
"or",
"not",
"is_stable_version",
"(",
"__version__",
")",
"return",
"use_dev_config_dir"
] | Return whether the dev configuration directory should used. | [
"Return",
"whether",
"the",
"dev",
"configuration",
"directory",
"should",
"used",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L77-L84 | train |
spyder-ide/spyder | spyder/config/base.py | debug_print | def debug_print(*message):
"""Output debug messages to stdout"""
warnings.warn("debug_print is deprecated; use the logging module instead.")
if get_debug_level():
ss = STDOUT
if PY3:
# This is needed after restarting and using debug_print
for m in message:
ss.buffer.write(str(m).encode('utf-8'))
print('', file=ss)
else:
print(*message, file=ss) | python | def debug_print(*message):
"""Output debug messages to stdout"""
warnings.warn("debug_print is deprecated; use the logging module instead.")
if get_debug_level():
ss = STDOUT
if PY3:
# This is needed after restarting and using debug_print
for m in message:
ss.buffer.write(str(m).encode('utf-8'))
print('', file=ss)
else:
print(*message, file=ss) | [
"def",
"debug_print",
"(",
"*",
"message",
")",
":",
"warnings",
".",
"warn",
"(",
"\"debug_print is deprecated; use the logging module instead.\"",
")",
"if",
"get_debug_level",
"(",
")",
":",
"ss",
"=",
"STDOUT",
"if",
"PY3",
":",
"# This is needed after restarting and using debug_print\r",
"for",
"m",
"in",
"message",
":",
"ss",
".",
"buffer",
".",
"write",
"(",
"str",
"(",
"m",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"print",
"(",
"''",
",",
"file",
"=",
"ss",
")",
"else",
":",
"print",
"(",
"*",
"message",
",",
"file",
"=",
"ss",
")"
] | Output debug messages to stdout | [
"Output",
"debug",
"messages",
"to",
"stdout"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L102-L113 | train |
spyder-ide/spyder | spyder/config/base.py | get_home_dir | 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 Exception:
path = ''
if osp.isdir(path):
return path
else:
# Get home from alternative locations
for env_var in ('HOME', 'USERPROFILE', '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):
return path
else:
path = ''
if not path:
raise RuntimeError('Please set the environment variable HOME to '
'your user/home directory path so Spyder can '
'start properly.') | python | 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 Exception:
path = ''
if osp.isdir(path):
return path
else:
# Get home from alternative locations
for env_var in ('HOME', 'USERPROFILE', '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):
return path
else:
path = ''
if not path:
raise RuntimeError('Please set the environment variable HOME to '
'your user/home directory path so Spyder can '
'start properly.') | [
"def",
"get_home_dir",
"(",
")",
":",
"try",
":",
"# expanduser() returns a raw byte string which needs to be\r",
"# decoded with the codec that the OS is using to represent\r",
"# file paths.\r",
"path",
"=",
"encoding",
".",
"to_unicode_from_fs",
"(",
"osp",
".",
"expanduser",
"(",
"'~'",
")",
")",
"except",
"Exception",
":",
"path",
"=",
"''",
"if",
"osp",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"path",
"else",
":",
"# Get home from alternative locations\r",
"for",
"env_var",
"in",
"(",
"'HOME'",
",",
"'USERPROFILE'",
",",
"'TMP'",
")",
":",
"# os.environ.get() returns a raw byte string which needs to be\r",
"# decoded with the codec that the OS is using to represent\r",
"# environment variables.\r",
"path",
"=",
"encoding",
".",
"to_unicode_from_fs",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"env_var",
",",
"''",
")",
")",
"if",
"osp",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"path",
"else",
":",
"path",
"=",
"''",
"if",
"not",
"path",
":",
"raise",
"RuntimeError",
"(",
"'Please set the environment variable HOME to '",
"'your user/home directory path so Spyder can '",
"'start properly.'",
")"
] | Return user home directory | [
"Return",
"user",
"home",
"directory"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L145-L174 | train |
spyder-ide/spyder | spyder/config/base.py | get_clean_conf_dir | def get_clean_conf_dir():
"""
Return the path to a temp clean configuration dir, for tests and safe mode.
"""
if sys.platform.startswith("win"):
current_user = ''
else:
current_user = '-' + str(getpass.getuser())
conf_dir = osp.join(str(tempfile.gettempdir()),
'pytest-spyder{0!s}'.format(current_user),
SUBFOLDER)
return conf_dir | python | def get_clean_conf_dir():
"""
Return the path to a temp clean configuration dir, for tests and safe mode.
"""
if sys.platform.startswith("win"):
current_user = ''
else:
current_user = '-' + str(getpass.getuser())
conf_dir = osp.join(str(tempfile.gettempdir()),
'pytest-spyder{0!s}'.format(current_user),
SUBFOLDER)
return conf_dir | [
"def",
"get_clean_conf_dir",
"(",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"current_user",
"=",
"''",
"else",
":",
"current_user",
"=",
"'-'",
"+",
"str",
"(",
"getpass",
".",
"getuser",
"(",
")",
")",
"conf_dir",
"=",
"osp",
".",
"join",
"(",
"str",
"(",
"tempfile",
".",
"gettempdir",
"(",
")",
")",
",",
"'pytest-spyder{0!s}'",
".",
"format",
"(",
"current_user",
")",
",",
"SUBFOLDER",
")",
"return",
"conf_dir"
] | Return the path to a temp clean configuration dir, for tests and safe mode. | [
"Return",
"the",
"path",
"to",
"a",
"temp",
"clean",
"configuration",
"dir",
"for",
"tests",
"and",
"safe",
"mode",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L177-L189 | train |
spyder-ide/spyder | spyder/config/base.py | get_conf_path | def get_conf_path(filename=None):
"""Return absolute path to the config file with the specified filename."""
# Define conf_dir
if running_under_pytest() or SAFE_MODE:
# Use clean config dir if running tests or the user requests it.
conf_dir = get_clean_conf_dir()
elif sys.platform.startswith('linux'):
# This makes us follow the XDG standard to save our settings
# on Linux, as it was requested on Issue 2629
xdg_config_home = os.environ.get('XDG_CONFIG_HOME', '')
if not xdg_config_home:
xdg_config_home = osp.join(get_home_dir(), '.config')
if not osp.isdir(xdg_config_home):
os.makedirs(xdg_config_home)
conf_dir = osp.join(xdg_config_home, SUBFOLDER)
else:
conf_dir = osp.join(get_home_dir(), SUBFOLDER)
# Create conf_dir
if not osp.isdir(conf_dir):
if running_under_pytest() or SAFE_MODE:
os.makedirs(conf_dir)
else:
os.mkdir(conf_dir)
if filename is None:
return conf_dir
else:
return osp.join(conf_dir, filename) | python | def get_conf_path(filename=None):
"""Return absolute path to the config file with the specified filename."""
# Define conf_dir
if running_under_pytest() or SAFE_MODE:
# Use clean config dir if running tests or the user requests it.
conf_dir = get_clean_conf_dir()
elif sys.platform.startswith('linux'):
# This makes us follow the XDG standard to save our settings
# on Linux, as it was requested on Issue 2629
xdg_config_home = os.environ.get('XDG_CONFIG_HOME', '')
if not xdg_config_home:
xdg_config_home = osp.join(get_home_dir(), '.config')
if not osp.isdir(xdg_config_home):
os.makedirs(xdg_config_home)
conf_dir = osp.join(xdg_config_home, SUBFOLDER)
else:
conf_dir = osp.join(get_home_dir(), SUBFOLDER)
# Create conf_dir
if not osp.isdir(conf_dir):
if running_under_pytest() or SAFE_MODE:
os.makedirs(conf_dir)
else:
os.mkdir(conf_dir)
if filename is None:
return conf_dir
else:
return osp.join(conf_dir, filename) | [
"def",
"get_conf_path",
"(",
"filename",
"=",
"None",
")",
":",
"# Define conf_dir\r",
"if",
"running_under_pytest",
"(",
")",
"or",
"SAFE_MODE",
":",
"# Use clean config dir if running tests or the user requests it.\r",
"conf_dir",
"=",
"get_clean_conf_dir",
"(",
")",
"elif",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'linux'",
")",
":",
"# This makes us follow the XDG standard to save our settings\r",
"# on Linux, as it was requested on Issue 2629\r",
"xdg_config_home",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'XDG_CONFIG_HOME'",
",",
"''",
")",
"if",
"not",
"xdg_config_home",
":",
"xdg_config_home",
"=",
"osp",
".",
"join",
"(",
"get_home_dir",
"(",
")",
",",
"'.config'",
")",
"if",
"not",
"osp",
".",
"isdir",
"(",
"xdg_config_home",
")",
":",
"os",
".",
"makedirs",
"(",
"xdg_config_home",
")",
"conf_dir",
"=",
"osp",
".",
"join",
"(",
"xdg_config_home",
",",
"SUBFOLDER",
")",
"else",
":",
"conf_dir",
"=",
"osp",
".",
"join",
"(",
"get_home_dir",
"(",
")",
",",
"SUBFOLDER",
")",
"# Create conf_dir\r",
"if",
"not",
"osp",
".",
"isdir",
"(",
"conf_dir",
")",
":",
"if",
"running_under_pytest",
"(",
")",
"or",
"SAFE_MODE",
":",
"os",
".",
"makedirs",
"(",
"conf_dir",
")",
"else",
":",
"os",
".",
"mkdir",
"(",
"conf_dir",
")",
"if",
"filename",
"is",
"None",
":",
"return",
"conf_dir",
"else",
":",
"return",
"osp",
".",
"join",
"(",
"conf_dir",
",",
"filename",
")"
] | Return absolute path to the config file with the specified filename. | [
"Return",
"absolute",
"path",
"to",
"the",
"config",
"file",
"with",
"the",
"specified",
"filename",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L192-L219 | train |
spyder-ide/spyder | spyder/config/base.py | get_module_path | def get_module_path(modname):
"""Return module *modname* base path"""
return osp.abspath(osp.dirname(sys.modules[modname].__file__)) | python | def get_module_path(modname):
"""Return module *modname* base path"""
return osp.abspath(osp.dirname(sys.modules[modname].__file__)) | [
"def",
"get_module_path",
"(",
"modname",
")",
":",
"return",
"osp",
".",
"abspath",
"(",
"osp",
".",
"dirname",
"(",
"sys",
".",
"modules",
"[",
"modname",
"]",
".",
"__file__",
")",
")"
] | Return module *modname* base path | [
"Return",
"module",
"*",
"modname",
"*",
"base",
"path"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L222-L224 | train |
spyder-ide/spyder | spyder/config/base.py | get_module_data_path | def get_module_data_path(modname, relpath=None, attr_name='DATAPATH'):
"""Return module *modname* data path
Note: relpath is ignored if module has an attribute named *attr_name*
Handles py2exe/cx_Freeze distributions"""
datapath = getattr(sys.modules[modname], attr_name, '')
if datapath:
return datapath
else:
datapath = get_module_path(modname)
parentdir = osp.join(datapath, osp.pardir)
if osp.isfile(parentdir):
# Parent directory is not a directory but the 'library.zip' file:
# this is either a py2exe or a cx_Freeze distribution
datapath = osp.abspath(osp.join(osp.join(parentdir, osp.pardir),
modname))
if relpath is not None:
datapath = osp.abspath(osp.join(datapath, relpath))
return datapath | python | def get_module_data_path(modname, relpath=None, attr_name='DATAPATH'):
"""Return module *modname* data path
Note: relpath is ignored if module has an attribute named *attr_name*
Handles py2exe/cx_Freeze distributions"""
datapath = getattr(sys.modules[modname], attr_name, '')
if datapath:
return datapath
else:
datapath = get_module_path(modname)
parentdir = osp.join(datapath, osp.pardir)
if osp.isfile(parentdir):
# Parent directory is not a directory but the 'library.zip' file:
# this is either a py2exe or a cx_Freeze distribution
datapath = osp.abspath(osp.join(osp.join(parentdir, osp.pardir),
modname))
if relpath is not None:
datapath = osp.abspath(osp.join(datapath, relpath))
return datapath | [
"def",
"get_module_data_path",
"(",
"modname",
",",
"relpath",
"=",
"None",
",",
"attr_name",
"=",
"'DATAPATH'",
")",
":",
"datapath",
"=",
"getattr",
"(",
"sys",
".",
"modules",
"[",
"modname",
"]",
",",
"attr_name",
",",
"''",
")",
"if",
"datapath",
":",
"return",
"datapath",
"else",
":",
"datapath",
"=",
"get_module_path",
"(",
"modname",
")",
"parentdir",
"=",
"osp",
".",
"join",
"(",
"datapath",
",",
"osp",
".",
"pardir",
")",
"if",
"osp",
".",
"isfile",
"(",
"parentdir",
")",
":",
"# Parent directory is not a directory but the 'library.zip' file:\r",
"# this is either a py2exe or a cx_Freeze distribution\r",
"datapath",
"=",
"osp",
".",
"abspath",
"(",
"osp",
".",
"join",
"(",
"osp",
".",
"join",
"(",
"parentdir",
",",
"osp",
".",
"pardir",
")",
",",
"modname",
")",
")",
"if",
"relpath",
"is",
"not",
"None",
":",
"datapath",
"=",
"osp",
".",
"abspath",
"(",
"osp",
".",
"join",
"(",
"datapath",
",",
"relpath",
")",
")",
"return",
"datapath"
] | Return module *modname* data path
Note: relpath is ignored if module has an attribute named *attr_name*
Handles py2exe/cx_Freeze distributions | [
"Return",
"module",
"*",
"modname",
"*",
"data",
"path",
"Note",
":",
"relpath",
"is",
"ignored",
"if",
"module",
"has",
"an",
"attribute",
"named",
"*",
"attr_name",
"*",
"Handles",
"py2exe",
"/",
"cx_Freeze",
"distributions"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L227-L245 | train |
spyder-ide/spyder | spyder/config/base.py | get_module_source_path | def get_module_source_path(modname, basename=None):
"""Return module *modname* source path
If *basename* is specified, return *modname.basename* path where
*modname* is a package containing the module *basename*
*basename* is a filename (not a module name), so it must include the
file extension: .py or .pyw
Handles py2exe/cx_Freeze distributions"""
srcpath = get_module_path(modname)
parentdir = osp.join(srcpath, osp.pardir)
if osp.isfile(parentdir):
# Parent directory is not a directory but the 'library.zip' file:
# this is either a py2exe or a cx_Freeze distribution
srcpath = osp.abspath(osp.join(osp.join(parentdir, osp.pardir),
modname))
if basename is not None:
srcpath = osp.abspath(osp.join(srcpath, basename))
return srcpath | python | def get_module_source_path(modname, basename=None):
"""Return module *modname* source path
If *basename* is specified, return *modname.basename* path where
*modname* is a package containing the module *basename*
*basename* is a filename (not a module name), so it must include the
file extension: .py or .pyw
Handles py2exe/cx_Freeze distributions"""
srcpath = get_module_path(modname)
parentdir = osp.join(srcpath, osp.pardir)
if osp.isfile(parentdir):
# Parent directory is not a directory but the 'library.zip' file:
# this is either a py2exe or a cx_Freeze distribution
srcpath = osp.abspath(osp.join(osp.join(parentdir, osp.pardir),
modname))
if basename is not None:
srcpath = osp.abspath(osp.join(srcpath, basename))
return srcpath | [
"def",
"get_module_source_path",
"(",
"modname",
",",
"basename",
"=",
"None",
")",
":",
"srcpath",
"=",
"get_module_path",
"(",
"modname",
")",
"parentdir",
"=",
"osp",
".",
"join",
"(",
"srcpath",
",",
"osp",
".",
"pardir",
")",
"if",
"osp",
".",
"isfile",
"(",
"parentdir",
")",
":",
"# Parent directory is not a directory but the 'library.zip' file:\r",
"# this is either a py2exe or a cx_Freeze distribution\r",
"srcpath",
"=",
"osp",
".",
"abspath",
"(",
"osp",
".",
"join",
"(",
"osp",
".",
"join",
"(",
"parentdir",
",",
"osp",
".",
"pardir",
")",
",",
"modname",
")",
")",
"if",
"basename",
"is",
"not",
"None",
":",
"srcpath",
"=",
"osp",
".",
"abspath",
"(",
"osp",
".",
"join",
"(",
"srcpath",
",",
"basename",
")",
")",
"return",
"srcpath"
] | Return module *modname* source path
If *basename* is specified, return *modname.basename* path where
*modname* is a package containing the module *basename*
*basename* is a filename (not a module name), so it must include the
file extension: .py or .pyw
Handles py2exe/cx_Freeze distributions | [
"Return",
"module",
"*",
"modname",
"*",
"source",
"path",
"If",
"*",
"basename",
"*",
"is",
"specified",
"return",
"*",
"modname",
".",
"basename",
"*",
"path",
"where",
"*",
"modname",
"*",
"is",
"a",
"package",
"containing",
"the",
"module",
"*",
"basename",
"*",
"*",
"basename",
"*",
"is",
"a",
"filename",
"(",
"not",
"a",
"module",
"name",
")",
"so",
"it",
"must",
"include",
"the",
"file",
"extension",
":",
".",
"py",
"or",
".",
"pyw",
"Handles",
"py2exe",
"/",
"cx_Freeze",
"distributions"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L248-L266 | train |
spyder-ide/spyder | spyder/config/base.py | get_image_path | def get_image_path(name, default="not_found.png"):
"""Return image absolute path"""
for img_path in IMG_PATH:
full_path = osp.join(img_path, name)
if osp.isfile(full_path):
return osp.abspath(full_path)
if default is not None:
img_path = osp.join(get_module_path('spyder'), 'images')
return osp.abspath(osp.join(img_path, default)) | python | def get_image_path(name, default="not_found.png"):
"""Return image absolute path"""
for img_path in IMG_PATH:
full_path = osp.join(img_path, name)
if osp.isfile(full_path):
return osp.abspath(full_path)
if default is not None:
img_path = osp.join(get_module_path('spyder'), 'images')
return osp.abspath(osp.join(img_path, default)) | [
"def",
"get_image_path",
"(",
"name",
",",
"default",
"=",
"\"not_found.png\"",
")",
":",
"for",
"img_path",
"in",
"IMG_PATH",
":",
"full_path",
"=",
"osp",
".",
"join",
"(",
"img_path",
",",
"name",
")",
"if",
"osp",
".",
"isfile",
"(",
"full_path",
")",
":",
"return",
"osp",
".",
"abspath",
"(",
"full_path",
")",
"if",
"default",
"is",
"not",
"None",
":",
"img_path",
"=",
"osp",
".",
"join",
"(",
"get_module_path",
"(",
"'spyder'",
")",
",",
"'images'",
")",
"return",
"osp",
".",
"abspath",
"(",
"osp",
".",
"join",
"(",
"img_path",
",",
"default",
")",
")"
] | Return image absolute path | [
"Return",
"image",
"absolute",
"path"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L289-L297 | train |
spyder-ide/spyder | spyder/config/base.py | get_available_translations | def get_available_translations():
"""
List available translations for spyder based on the folders found in the
locale folder. This function checks if LANGUAGE_CODES contain the same
information that is found in the 'locale' folder to ensure that when a new
language is added, LANGUAGE_CODES is updated.
"""
locale_path = get_module_data_path("spyder", relpath="locale",
attr_name='LOCALEPATH')
listdir = os.listdir(locale_path)
langs = [d for d in listdir if osp.isdir(osp.join(locale_path, d))]
langs = [DEFAULT_LANGUAGE] + langs
# Remove disabled languages
langs = list( set(langs) - set(DISABLED_LANGUAGES) )
# Check that there is a language code available in case a new translation
# is added, to ensure LANGUAGE_CODES is updated.
for lang in langs:
if lang not in LANGUAGE_CODES:
error = ('Update LANGUAGE_CODES (inside config/base.py) if a new '
'translation has been added to Spyder')
print(error) # spyder: test-skip
return ['en']
return langs | python | def get_available_translations():
"""
List available translations for spyder based on the folders found in the
locale folder. This function checks if LANGUAGE_CODES contain the same
information that is found in the 'locale' folder to ensure that when a new
language is added, LANGUAGE_CODES is updated.
"""
locale_path = get_module_data_path("spyder", relpath="locale",
attr_name='LOCALEPATH')
listdir = os.listdir(locale_path)
langs = [d for d in listdir if osp.isdir(osp.join(locale_path, d))]
langs = [DEFAULT_LANGUAGE] + langs
# Remove disabled languages
langs = list( set(langs) - set(DISABLED_LANGUAGES) )
# Check that there is a language code available in case a new translation
# is added, to ensure LANGUAGE_CODES is updated.
for lang in langs:
if lang not in LANGUAGE_CODES:
error = ('Update LANGUAGE_CODES (inside config/base.py) if a new '
'translation has been added to Spyder')
print(error) # spyder: test-skip
return ['en']
return langs | [
"def",
"get_available_translations",
"(",
")",
":",
"locale_path",
"=",
"get_module_data_path",
"(",
"\"spyder\"",
",",
"relpath",
"=",
"\"locale\"",
",",
"attr_name",
"=",
"'LOCALEPATH'",
")",
"listdir",
"=",
"os",
".",
"listdir",
"(",
"locale_path",
")",
"langs",
"=",
"[",
"d",
"for",
"d",
"in",
"listdir",
"if",
"osp",
".",
"isdir",
"(",
"osp",
".",
"join",
"(",
"locale_path",
",",
"d",
")",
")",
"]",
"langs",
"=",
"[",
"DEFAULT_LANGUAGE",
"]",
"+",
"langs",
"# Remove disabled languages\r",
"langs",
"=",
"list",
"(",
"set",
"(",
"langs",
")",
"-",
"set",
"(",
"DISABLED_LANGUAGES",
")",
")",
"# Check that there is a language code available in case a new translation\r",
"# is added, to ensure LANGUAGE_CODES is updated.\r",
"for",
"lang",
"in",
"langs",
":",
"if",
"lang",
"not",
"in",
"LANGUAGE_CODES",
":",
"error",
"=",
"(",
"'Update LANGUAGE_CODES (inside config/base.py) if a new '",
"'translation has been added to Spyder'",
")",
"print",
"(",
"error",
")",
"# spyder: test-skip\r",
"return",
"[",
"'en'",
"]",
"return",
"langs"
] | List available translations for spyder based on the folders found in the
locale folder. This function checks if LANGUAGE_CODES contain the same
information that is found in the 'locale' folder to ensure that when a new
language is added, LANGUAGE_CODES is updated. | [
"List",
"available",
"translations",
"for",
"spyder",
"based",
"on",
"the",
"folders",
"found",
"in",
"the",
"locale",
"folder",
".",
"This",
"function",
"checks",
"if",
"LANGUAGE_CODES",
"contain",
"the",
"same",
"information",
"that",
"is",
"found",
"in",
"the",
"locale",
"folder",
"to",
"ensure",
"that",
"when",
"a",
"new",
"language",
"is",
"added",
"LANGUAGE_CODES",
"is",
"updated",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L322-L346 | train |
spyder-ide/spyder | spyder/config/base.py | get_interface_language | def get_interface_language():
"""
If Spyder has a translation available for the locale language, it will
return the version provided by Spyder adjusted for language subdifferences,
otherwise it will return DEFAULT_LANGUAGE.
Example:
1.) Spyder provides ('en', 'de', 'fr', 'es' 'hu' and 'pt_BR'), if the
locale is either 'en_US' or 'en' or 'en_UK', this function will return 'en'
2.) Spyder provides ('en', 'de', 'fr', 'es' 'hu' and 'pt_BR'), if the
locale is either 'pt' or 'pt_BR', this function will return 'pt_BR'
"""
# Solves issue #3627
try:
locale_language = locale.getdefaultlocale()[0]
except ValueError:
locale_language = DEFAULT_LANGUAGE
# Tests expect English as the interface language
if running_under_pytest():
locale_language = DEFAULT_LANGUAGE
language = DEFAULT_LANGUAGE
if locale_language is not None:
spyder_languages = get_available_translations()
for lang in spyder_languages:
if locale_language == lang:
language = locale_language
break
elif locale_language.startswith(lang) or \
lang.startswith(locale_language):
language = lang
break
return language | python | def get_interface_language():
"""
If Spyder has a translation available for the locale language, it will
return the version provided by Spyder adjusted for language subdifferences,
otherwise it will return DEFAULT_LANGUAGE.
Example:
1.) Spyder provides ('en', 'de', 'fr', 'es' 'hu' and 'pt_BR'), if the
locale is either 'en_US' or 'en' or 'en_UK', this function will return 'en'
2.) Spyder provides ('en', 'de', 'fr', 'es' 'hu' and 'pt_BR'), if the
locale is either 'pt' or 'pt_BR', this function will return 'pt_BR'
"""
# Solves issue #3627
try:
locale_language = locale.getdefaultlocale()[0]
except ValueError:
locale_language = DEFAULT_LANGUAGE
# Tests expect English as the interface language
if running_under_pytest():
locale_language = DEFAULT_LANGUAGE
language = DEFAULT_LANGUAGE
if locale_language is not None:
spyder_languages = get_available_translations()
for lang in spyder_languages:
if locale_language == lang:
language = locale_language
break
elif locale_language.startswith(lang) or \
lang.startswith(locale_language):
language = lang
break
return language | [
"def",
"get_interface_language",
"(",
")",
":",
"# Solves issue #3627\r",
"try",
":",
"locale_language",
"=",
"locale",
".",
"getdefaultlocale",
"(",
")",
"[",
"0",
"]",
"except",
"ValueError",
":",
"locale_language",
"=",
"DEFAULT_LANGUAGE",
"# Tests expect English as the interface language\r",
"if",
"running_under_pytest",
"(",
")",
":",
"locale_language",
"=",
"DEFAULT_LANGUAGE",
"language",
"=",
"DEFAULT_LANGUAGE",
"if",
"locale_language",
"is",
"not",
"None",
":",
"spyder_languages",
"=",
"get_available_translations",
"(",
")",
"for",
"lang",
"in",
"spyder_languages",
":",
"if",
"locale_language",
"==",
"lang",
":",
"language",
"=",
"locale_language",
"break",
"elif",
"locale_language",
".",
"startswith",
"(",
"lang",
")",
"or",
"lang",
".",
"startswith",
"(",
"locale_language",
")",
":",
"language",
"=",
"lang",
"break",
"return",
"language"
] | If Spyder has a translation available for the locale language, it will
return the version provided by Spyder adjusted for language subdifferences,
otherwise it will return DEFAULT_LANGUAGE.
Example:
1.) Spyder provides ('en', 'de', 'fr', 'es' 'hu' and 'pt_BR'), if the
locale is either 'en_US' or 'en' or 'en_UK', this function will return 'en'
2.) Spyder provides ('en', 'de', 'fr', 'es' 'hu' and 'pt_BR'), if the
locale is either 'pt' or 'pt_BR', this function will return 'pt_BR' | [
"If",
"Spyder",
"has",
"a",
"translation",
"available",
"for",
"the",
"locale",
"language",
"it",
"will",
"return",
"the",
"version",
"provided",
"by",
"Spyder",
"adjusted",
"for",
"language",
"subdifferences",
"otherwise",
"it",
"will",
"return",
"DEFAULT_LANGUAGE",
".",
"Example",
":",
"1",
".",
")",
"Spyder",
"provides",
"(",
"en",
"de",
"fr",
"es",
"hu",
"and",
"pt_BR",
")",
"if",
"the",
"locale",
"is",
"either",
"en_US",
"or",
"en",
"or",
"en_UK",
"this",
"function",
"will",
"return",
"en",
"2",
".",
")",
"Spyder",
"provides",
"(",
"en",
"de",
"fr",
"es",
"hu",
"and",
"pt_BR",
")",
"if",
"the",
"locale",
"is",
"either",
"pt",
"or",
"pt_BR",
"this",
"function",
"will",
"return",
"pt_BR"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L349-L386 | train |
spyder-ide/spyder | spyder/config/base.py | load_lang_conf | def load_lang_conf():
"""
Load language setting from language config file if it exists, otherwise
try to use the local settings if Spyder provides a translation, or
return the default if no translation provided.
"""
if osp.isfile(LANG_FILE):
with open(LANG_FILE, 'r') as f:
lang = f.read()
else:
lang = get_interface_language()
save_lang_conf(lang)
# Save language again if it's been disabled
if lang.strip('\n') in DISABLED_LANGUAGES:
lang = DEFAULT_LANGUAGE
save_lang_conf(lang)
return lang | python | def load_lang_conf():
"""
Load language setting from language config file if it exists, otherwise
try to use the local settings if Spyder provides a translation, or
return the default if no translation provided.
"""
if osp.isfile(LANG_FILE):
with open(LANG_FILE, 'r') as f:
lang = f.read()
else:
lang = get_interface_language()
save_lang_conf(lang)
# Save language again if it's been disabled
if lang.strip('\n') in DISABLED_LANGUAGES:
lang = DEFAULT_LANGUAGE
save_lang_conf(lang)
return lang | [
"def",
"load_lang_conf",
"(",
")",
":",
"if",
"osp",
".",
"isfile",
"(",
"LANG_FILE",
")",
":",
"with",
"open",
"(",
"LANG_FILE",
",",
"'r'",
")",
"as",
"f",
":",
"lang",
"=",
"f",
".",
"read",
"(",
")",
"else",
":",
"lang",
"=",
"get_interface_language",
"(",
")",
"save_lang_conf",
"(",
"lang",
")",
"# Save language again if it's been disabled\r",
"if",
"lang",
".",
"strip",
"(",
"'\\n'",
")",
"in",
"DISABLED_LANGUAGES",
":",
"lang",
"=",
"DEFAULT_LANGUAGE",
"save_lang_conf",
"(",
"lang",
")",
"return",
"lang"
] | Load language setting from language config file if it exists, otherwise
try to use the local settings if Spyder provides a translation, or
return the default if no translation provided. | [
"Load",
"language",
"setting",
"from",
"language",
"config",
"file",
"if",
"it",
"exists",
"otherwise",
"try",
"to",
"use",
"the",
"local",
"settings",
"if",
"Spyder",
"provides",
"a",
"translation",
"or",
"return",
"the",
"default",
"if",
"no",
"translation",
"provided",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L401-L419 | train |
spyder-ide/spyder | spyder/config/base.py | get_translation | def get_translation(modname, dirname=None):
"""Return translation callback for module *modname*"""
if dirname is None:
dirname = modname
def translate_dumb(x):
"""Dumb function to not use translations."""
if not is_unicode(x):
return to_text_string(x, "utf-8")
return x
locale_path = get_module_data_path(dirname, relpath="locale",
attr_name='LOCALEPATH')
# If LANG is defined in Ubuntu, a warning message is displayed,
# so in Unix systems we define the LANGUAGE variable.
language = load_lang_conf()
if os.name == 'nt':
# Trying to set LANG on Windows can fail when Spyder is
# run with admin privileges.
# Fixes issue 6886
try:
os.environ["LANG"] = language # Works on Windows
except Exception:
return translate_dumb
else:
os.environ["LANGUAGE"] = language # Works on Linux
import gettext
try:
_trans = gettext.translation(modname, locale_path, codeset="utf-8")
lgettext = _trans.lgettext
def translate_gettext(x):
if not PY3 and is_unicode(x):
x = x.encode("utf-8")
y = lgettext(x)
if is_text_string(y) and PY3:
return y
else:
return to_text_string(y, "utf-8")
return translate_gettext
except Exception:
return translate_dumb | python | def get_translation(modname, dirname=None):
"""Return translation callback for module *modname*"""
if dirname is None:
dirname = modname
def translate_dumb(x):
"""Dumb function to not use translations."""
if not is_unicode(x):
return to_text_string(x, "utf-8")
return x
locale_path = get_module_data_path(dirname, relpath="locale",
attr_name='LOCALEPATH')
# If LANG is defined in Ubuntu, a warning message is displayed,
# so in Unix systems we define the LANGUAGE variable.
language = load_lang_conf()
if os.name == 'nt':
# Trying to set LANG on Windows can fail when Spyder is
# run with admin privileges.
# Fixes issue 6886
try:
os.environ["LANG"] = language # Works on Windows
except Exception:
return translate_dumb
else:
os.environ["LANGUAGE"] = language # Works on Linux
import gettext
try:
_trans = gettext.translation(modname, locale_path, codeset="utf-8")
lgettext = _trans.lgettext
def translate_gettext(x):
if not PY3 and is_unicode(x):
x = x.encode("utf-8")
y = lgettext(x)
if is_text_string(y) and PY3:
return y
else:
return to_text_string(y, "utf-8")
return translate_gettext
except Exception:
return translate_dumb | [
"def",
"get_translation",
"(",
"modname",
",",
"dirname",
"=",
"None",
")",
":",
"if",
"dirname",
"is",
"None",
":",
"dirname",
"=",
"modname",
"def",
"translate_dumb",
"(",
"x",
")",
":",
"\"\"\"Dumb function to not use translations.\"\"\"",
"if",
"not",
"is_unicode",
"(",
"x",
")",
":",
"return",
"to_text_string",
"(",
"x",
",",
"\"utf-8\"",
")",
"return",
"x",
"locale_path",
"=",
"get_module_data_path",
"(",
"dirname",
",",
"relpath",
"=",
"\"locale\"",
",",
"attr_name",
"=",
"'LOCALEPATH'",
")",
"# If LANG is defined in Ubuntu, a warning message is displayed,\r",
"# so in Unix systems we define the LANGUAGE variable.\r",
"language",
"=",
"load_lang_conf",
"(",
")",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"# Trying to set LANG on Windows can fail when Spyder is\r",
"# run with admin privileges.\r",
"# Fixes issue 6886\r",
"try",
":",
"os",
".",
"environ",
"[",
"\"LANG\"",
"]",
"=",
"language",
"# Works on Windows\r",
"except",
"Exception",
":",
"return",
"translate_dumb",
"else",
":",
"os",
".",
"environ",
"[",
"\"LANGUAGE\"",
"]",
"=",
"language",
"# Works on Linux\r",
"import",
"gettext",
"try",
":",
"_trans",
"=",
"gettext",
".",
"translation",
"(",
"modname",
",",
"locale_path",
",",
"codeset",
"=",
"\"utf-8\"",
")",
"lgettext",
"=",
"_trans",
".",
"lgettext",
"def",
"translate_gettext",
"(",
"x",
")",
":",
"if",
"not",
"PY3",
"and",
"is_unicode",
"(",
"x",
")",
":",
"x",
"=",
"x",
".",
"encode",
"(",
"\"utf-8\"",
")",
"y",
"=",
"lgettext",
"(",
"x",
")",
"if",
"is_text_string",
"(",
"y",
")",
"and",
"PY3",
":",
"return",
"y",
"else",
":",
"return",
"to_text_string",
"(",
"y",
",",
"\"utf-8\"",
")",
"return",
"translate_gettext",
"except",
"Exception",
":",
"return",
"translate_dumb"
] | Return translation callback for module *modname* | [
"Return",
"translation",
"callback",
"for",
"module",
"*",
"modname",
"*"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L422-L464 | train |
spyder-ide/spyder | spyder/config/base.py | reset_config_files | def reset_config_files():
"""Remove all config files"""
print("*** Reset Spyder settings to defaults ***", file=STDERR)
for fname in SAVED_CONFIG_FILES:
cfg_fname = get_conf_path(fname)
if osp.isfile(cfg_fname) or osp.islink(cfg_fname):
os.remove(cfg_fname)
elif osp.isdir(cfg_fname):
shutil.rmtree(cfg_fname)
else:
continue
print("removing:", cfg_fname, file=STDERR) | python | def reset_config_files():
"""Remove all config files"""
print("*** Reset Spyder settings to defaults ***", file=STDERR)
for fname in SAVED_CONFIG_FILES:
cfg_fname = get_conf_path(fname)
if osp.isfile(cfg_fname) or osp.islink(cfg_fname):
os.remove(cfg_fname)
elif osp.isdir(cfg_fname):
shutil.rmtree(cfg_fname)
else:
continue
print("removing:", cfg_fname, file=STDERR) | [
"def",
"reset_config_files",
"(",
")",
":",
"print",
"(",
"\"*** Reset Spyder settings to defaults ***\"",
",",
"file",
"=",
"STDERR",
")",
"for",
"fname",
"in",
"SAVED_CONFIG_FILES",
":",
"cfg_fname",
"=",
"get_conf_path",
"(",
"fname",
")",
"if",
"osp",
".",
"isfile",
"(",
"cfg_fname",
")",
"or",
"osp",
".",
"islink",
"(",
"cfg_fname",
")",
":",
"os",
".",
"remove",
"(",
"cfg_fname",
")",
"elif",
"osp",
".",
"isdir",
"(",
"cfg_fname",
")",
":",
"shutil",
".",
"rmtree",
"(",
"cfg_fname",
")",
"else",
":",
"continue",
"print",
"(",
"\"removing:\"",
",",
"cfg_fname",
",",
"file",
"=",
"STDERR",
")"
] | Remove all config files | [
"Remove",
"all",
"config",
"files"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L512-L523 | train |
spyder-ide/spyder | spyder/plugins/explorer/plugin.py | Explorer.register_plugin | def register_plugin(self):
"""Register plugin in Spyder's main window"""
ipyconsole = self.main.ipyconsole
treewidget = self.fileexplorer.treewidget
self.main.add_dockwidget(self)
self.fileexplorer.sig_open_file.connect(self.main.open_file)
self.register_widget_shortcuts(treewidget)
treewidget.sig_edit.connect(self.main.editor.load)
treewidget.sig_removed.connect(self.main.editor.removed)
treewidget.sig_removed_tree.connect(self.main.editor.removed_tree)
treewidget.sig_renamed.connect(self.main.editor.renamed)
treewidget.sig_renamed_tree.connect(self.main.editor.renamed_tree)
treewidget.sig_create_module.connect(self.main.editor.new)
treewidget.sig_new_file.connect(lambda t: self.main.editor.new(text=t))
treewidget.sig_open_interpreter.connect(
ipyconsole.create_client_from_path)
treewidget.redirect_stdio.connect(
self.main.redirect_internalshell_stdio)
treewidget.sig_run.connect(
lambda fname:
ipyconsole.run_script(fname, osp.dirname(fname), '', False, False,
False, True))
treewidget.sig_open_dir.connect(
lambda dirname:
self.main.workingdirectory.chdir(dirname,
refresh_explorer=False,
refresh_console=True))
self.main.editor.open_dir.connect(self.chdir)
# Signal "set_explorer_cwd(QString)" will refresh only the
# contents of path passed by the signal in explorer:
self.main.workingdirectory.set_explorer_cwd.connect(
lambda directory: self.refresh_plugin(new_path=directory,
force_current=True)) | python | def register_plugin(self):
"""Register plugin in Spyder's main window"""
ipyconsole = self.main.ipyconsole
treewidget = self.fileexplorer.treewidget
self.main.add_dockwidget(self)
self.fileexplorer.sig_open_file.connect(self.main.open_file)
self.register_widget_shortcuts(treewidget)
treewidget.sig_edit.connect(self.main.editor.load)
treewidget.sig_removed.connect(self.main.editor.removed)
treewidget.sig_removed_tree.connect(self.main.editor.removed_tree)
treewidget.sig_renamed.connect(self.main.editor.renamed)
treewidget.sig_renamed_tree.connect(self.main.editor.renamed_tree)
treewidget.sig_create_module.connect(self.main.editor.new)
treewidget.sig_new_file.connect(lambda t: self.main.editor.new(text=t))
treewidget.sig_open_interpreter.connect(
ipyconsole.create_client_from_path)
treewidget.redirect_stdio.connect(
self.main.redirect_internalshell_stdio)
treewidget.sig_run.connect(
lambda fname:
ipyconsole.run_script(fname, osp.dirname(fname), '', False, False,
False, True))
treewidget.sig_open_dir.connect(
lambda dirname:
self.main.workingdirectory.chdir(dirname,
refresh_explorer=False,
refresh_console=True))
self.main.editor.open_dir.connect(self.chdir)
# Signal "set_explorer_cwd(QString)" will refresh only the
# contents of path passed by the signal in explorer:
self.main.workingdirectory.set_explorer_cwd.connect(
lambda directory: self.refresh_plugin(new_path=directory,
force_current=True)) | [
"def",
"register_plugin",
"(",
"self",
")",
":",
"ipyconsole",
"=",
"self",
".",
"main",
".",
"ipyconsole",
"treewidget",
"=",
"self",
".",
"fileexplorer",
".",
"treewidget",
"self",
".",
"main",
".",
"add_dockwidget",
"(",
"self",
")",
"self",
".",
"fileexplorer",
".",
"sig_open_file",
".",
"connect",
"(",
"self",
".",
"main",
".",
"open_file",
")",
"self",
".",
"register_widget_shortcuts",
"(",
"treewidget",
")",
"treewidget",
".",
"sig_edit",
".",
"connect",
"(",
"self",
".",
"main",
".",
"editor",
".",
"load",
")",
"treewidget",
".",
"sig_removed",
".",
"connect",
"(",
"self",
".",
"main",
".",
"editor",
".",
"removed",
")",
"treewidget",
".",
"sig_removed_tree",
".",
"connect",
"(",
"self",
".",
"main",
".",
"editor",
".",
"removed_tree",
")",
"treewidget",
".",
"sig_renamed",
".",
"connect",
"(",
"self",
".",
"main",
".",
"editor",
".",
"renamed",
")",
"treewidget",
".",
"sig_renamed_tree",
".",
"connect",
"(",
"self",
".",
"main",
".",
"editor",
".",
"renamed_tree",
")",
"treewidget",
".",
"sig_create_module",
".",
"connect",
"(",
"self",
".",
"main",
".",
"editor",
".",
"new",
")",
"treewidget",
".",
"sig_new_file",
".",
"connect",
"(",
"lambda",
"t",
":",
"self",
".",
"main",
".",
"editor",
".",
"new",
"(",
"text",
"=",
"t",
")",
")",
"treewidget",
".",
"sig_open_interpreter",
".",
"connect",
"(",
"ipyconsole",
".",
"create_client_from_path",
")",
"treewidget",
".",
"redirect_stdio",
".",
"connect",
"(",
"self",
".",
"main",
".",
"redirect_internalshell_stdio",
")",
"treewidget",
".",
"sig_run",
".",
"connect",
"(",
"lambda",
"fname",
":",
"ipyconsole",
".",
"run_script",
"(",
"fname",
",",
"osp",
".",
"dirname",
"(",
"fname",
")",
",",
"''",
",",
"False",
",",
"False",
",",
"False",
",",
"True",
")",
")",
"treewidget",
".",
"sig_open_dir",
".",
"connect",
"(",
"lambda",
"dirname",
":",
"self",
".",
"main",
".",
"workingdirectory",
".",
"chdir",
"(",
"dirname",
",",
"refresh_explorer",
"=",
"False",
",",
"refresh_console",
"=",
"True",
")",
")",
"self",
".",
"main",
".",
"editor",
".",
"open_dir",
".",
"connect",
"(",
"self",
".",
"chdir",
")",
"# Signal \"set_explorer_cwd(QString)\" will refresh only the\r",
"# contents of path passed by the signal in explorer:\r",
"self",
".",
"main",
".",
"workingdirectory",
".",
"set_explorer_cwd",
".",
"connect",
"(",
"lambda",
"directory",
":",
"self",
".",
"refresh_plugin",
"(",
"new_path",
"=",
"directory",
",",
"force_current",
"=",
"True",
")",
")"
] | Register plugin in Spyder's main window | [
"Register",
"plugin",
"in",
"Spyder",
"s",
"main",
"window"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/explorer/plugin.py#L70-L106 | train |
spyder-ide/spyder | spyder/plugins/explorer/plugin.py | Explorer.refresh_plugin | def refresh_plugin(self, new_path=None, force_current=True):
"""Refresh explorer widget"""
self.fileexplorer.treewidget.update_history(new_path)
self.fileexplorer.treewidget.refresh(new_path,
force_current=force_current) | python | def refresh_plugin(self, new_path=None, force_current=True):
"""Refresh explorer widget"""
self.fileexplorer.treewidget.update_history(new_path)
self.fileexplorer.treewidget.refresh(new_path,
force_current=force_current) | [
"def",
"refresh_plugin",
"(",
"self",
",",
"new_path",
"=",
"None",
",",
"force_current",
"=",
"True",
")",
":",
"self",
".",
"fileexplorer",
".",
"treewidget",
".",
"update_history",
"(",
"new_path",
")",
"self",
".",
"fileexplorer",
".",
"treewidget",
".",
"refresh",
"(",
"new_path",
",",
"force_current",
"=",
"force_current",
")"
] | Refresh explorer widget | [
"Refresh",
"explorer",
"widget"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/explorer/plugin.py#L108-L112 | train |
spyder-ide/spyder | spyder/py3compat.py | is_type_text_string | def is_type_text_string(obj):
"""Return True if `obj` is type text string, False if it is anything else,
like an instance of a class that extends the basestring class."""
if PY2:
# Python 2
return type(obj) in [str, unicode]
else:
# Python 3
return type(obj) in [str, bytes] | python | def is_type_text_string(obj):
"""Return True if `obj` is type text string, False if it is anything else,
like an instance of a class that extends the basestring class."""
if PY2:
# Python 2
return type(obj) in [str, unicode]
else:
# Python 3
return type(obj) in [str, bytes] | [
"def",
"is_type_text_string",
"(",
"obj",
")",
":",
"if",
"PY2",
":",
"# Python 2\r",
"return",
"type",
"(",
"obj",
")",
"in",
"[",
"str",
",",
"unicode",
"]",
"else",
":",
"# Python 3\r",
"return",
"type",
"(",
"obj",
")",
"in",
"[",
"str",
",",
"bytes",
"]"
] | Return True if `obj` is type text string, False if it is anything else,
like an instance of a class that extends the basestring class. | [
"Return",
"True",
"if",
"obj",
"is",
"type",
"text",
"string",
"False",
"if",
"it",
"is",
"anything",
"else",
"like",
"an",
"instance",
"of",
"a",
"class",
"that",
"extends",
"the",
"basestring",
"class",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/py3compat.py#L87-L95 | train |
spyder-ide/spyder | spyder/py3compat.py | to_binary_string | def to_binary_string(obj, encoding=None):
"""Convert `obj` to binary string (bytes in Python 3, str in Python 2)"""
if PY2:
# Python 2
if encoding is None:
return str(obj)
else:
return obj.encode(encoding)
else:
# Python 3
return bytes(obj, 'utf-8' if encoding is None else encoding) | python | def to_binary_string(obj, encoding=None):
"""Convert `obj` to binary string (bytes in Python 3, str in Python 2)"""
if PY2:
# Python 2
if encoding is None:
return str(obj)
else:
return obj.encode(encoding)
else:
# Python 3
return bytes(obj, 'utf-8' if encoding is None else encoding) | [
"def",
"to_binary_string",
"(",
"obj",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"PY2",
":",
"# Python 2\r",
"if",
"encoding",
"is",
"None",
":",
"return",
"str",
"(",
"obj",
")",
"else",
":",
"return",
"obj",
".",
"encode",
"(",
"encoding",
")",
"else",
":",
"# Python 3\r",
"return",
"bytes",
"(",
"obj",
",",
"'utf-8'",
"if",
"encoding",
"is",
"None",
"else",
"encoding",
")"
] | Convert `obj` to binary string (bytes in Python 3, str in Python 2) | [
"Convert",
"obj",
"to",
"binary",
"string",
"(",
"bytes",
"in",
"Python",
"3",
"str",
"in",
"Python",
"2",
")"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/py3compat.py#L150-L160 | train |
spyder-ide/spyder | spyder/plugins/onlinehelp/onlinehelp.py | OnlineHelp.save_history | def save_history(self):
"""Save history to a text file in user home directory"""
open(self.LOG_PATH, 'w').write("\n".join( \
[to_text_string(self.pydocbrowser.url_combo.itemText(index))
for index in range(self.pydocbrowser.url_combo.count())])) | python | def save_history(self):
"""Save history to a text file in user home directory"""
open(self.LOG_PATH, 'w').write("\n".join( \
[to_text_string(self.pydocbrowser.url_combo.itemText(index))
for index in range(self.pydocbrowser.url_combo.count())])) | [
"def",
"save_history",
"(",
"self",
")",
":",
"open",
"(",
"self",
".",
"LOG_PATH",
",",
"'w'",
")",
".",
"write",
"(",
"\"\\n\"",
".",
"join",
"(",
"[",
"to_text_string",
"(",
"self",
".",
"pydocbrowser",
".",
"url_combo",
".",
"itemText",
"(",
"index",
")",
")",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"pydocbrowser",
".",
"url_combo",
".",
"count",
"(",
")",
")",
"]",
")",
")"
] | Save history to a text file in user home directory | [
"Save",
"history",
"to",
"a",
"text",
"file",
"in",
"user",
"home",
"directory"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/onlinehelp/onlinehelp.py#L57-L61 | train |
spyder-ide/spyder | spyder/plugins/onlinehelp/onlinehelp.py | OnlineHelp.visibility_changed | def visibility_changed(self, enable):
"""DockWidget visibility has changed"""
super(SpyderPluginWidget, self).visibility_changed(enable)
if enable and not self.pydocbrowser.is_server_running():
self.pydocbrowser.initialize() | python | def visibility_changed(self, enable):
"""DockWidget visibility has changed"""
super(SpyderPluginWidget, self).visibility_changed(enable)
if enable and not self.pydocbrowser.is_server_running():
self.pydocbrowser.initialize() | [
"def",
"visibility_changed",
"(",
"self",
",",
"enable",
")",
":",
"super",
"(",
"SpyderPluginWidget",
",",
"self",
")",
".",
"visibility_changed",
"(",
"enable",
")",
"if",
"enable",
"and",
"not",
"self",
".",
"pydocbrowser",
".",
"is_server_running",
"(",
")",
":",
"self",
".",
"pydocbrowser",
".",
"initialize",
"(",
")"
] | DockWidget visibility has changed | [
"DockWidget",
"visibility",
"has",
"changed"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/onlinehelp/onlinehelp.py#L64-L68 | train |
spyder-ide/spyder | spyder/plugins/onlinehelp/onlinehelp.py | OnlineHelp.get_focus_widget | def get_focus_widget(self):
"""
Return the widget to give focus to when
this plugin's dockwidget is raised on top-level
"""
self.pydocbrowser.url_combo.lineEdit().selectAll()
return self.pydocbrowser.url_combo | python | def get_focus_widget(self):
"""
Return the widget to give focus to when
this plugin's dockwidget is raised on top-level
"""
self.pydocbrowser.url_combo.lineEdit().selectAll()
return self.pydocbrowser.url_combo | [
"def",
"get_focus_widget",
"(",
"self",
")",
":",
"self",
".",
"pydocbrowser",
".",
"url_combo",
".",
"lineEdit",
"(",
")",
".",
"selectAll",
"(",
")",
"return",
"self",
".",
"pydocbrowser",
".",
"url_combo"
] | Return the widget to give focus to when
this plugin's dockwidget is raised on top-level | [
"Return",
"the",
"widget",
"to",
"give",
"focus",
"to",
"when",
"this",
"plugin",
"s",
"dockwidget",
"is",
"raised",
"on",
"top",
"-",
"level"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/onlinehelp/onlinehelp.py#L75-L81 | train |
spyder-ide/spyder | spyder/plugins/onlinehelp/onlinehelp.py | OnlineHelp.closing_plugin | def closing_plugin(self, cancelable=False):
"""Perform actions before parent main window is closed"""
self.save_history()
self.set_option('zoom_factor',
self.pydocbrowser.webview.get_zoom_factor())
return True | python | def closing_plugin(self, cancelable=False):
"""Perform actions before parent main window is closed"""
self.save_history()
self.set_option('zoom_factor',
self.pydocbrowser.webview.get_zoom_factor())
return True | [
"def",
"closing_plugin",
"(",
"self",
",",
"cancelable",
"=",
"False",
")",
":",
"self",
".",
"save_history",
"(",
")",
"self",
".",
"set_option",
"(",
"'zoom_factor'",
",",
"self",
".",
"pydocbrowser",
".",
"webview",
".",
"get_zoom_factor",
"(",
")",
")",
"return",
"True"
] | Perform actions before parent main window is closed | [
"Perform",
"actions",
"before",
"parent",
"main",
"window",
"is",
"closed"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/onlinehelp/onlinehelp.py#L83-L88 | train |
spyder-ide/spyder | spyder/widgets/pathmanager.py | PathManager.synchronize | def synchronize(self):
"""
Synchronize Spyder's path list with PYTHONPATH environment variable
Only apply to: current user, on Windows platforms
"""
answer = QMessageBox.question(self, _("Synchronize"),
_("This will synchronize Spyder's path list with "
"<b>PYTHONPATH</b> environment variable for current user, "
"allowing you to run your Python modules outside Spyder "
"without having to configure sys.path. "
"<br>Do you want to clear contents of PYTHONPATH before "
"adding Spyder's path list?"),
QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
if answer == QMessageBox.Cancel:
return
elif answer == QMessageBox.Yes:
remove = True
else:
remove = False
from spyder.utils.environ import (get_user_env, set_user_env,
listdict2envdict)
env = get_user_env()
if remove:
ppath = self.active_pathlist+self.ro_pathlist
else:
ppath = env.get('PYTHONPATH', [])
if not isinstance(ppath, list):
ppath = [ppath]
ppath = [path for path in ppath
if path not in (self.active_pathlist+self.ro_pathlist)]
ppath.extend(self.active_pathlist+self.ro_pathlist)
env['PYTHONPATH'] = ppath
set_user_env(listdict2envdict(env), parent=self) | python | def synchronize(self):
"""
Synchronize Spyder's path list with PYTHONPATH environment variable
Only apply to: current user, on Windows platforms
"""
answer = QMessageBox.question(self, _("Synchronize"),
_("This will synchronize Spyder's path list with "
"<b>PYTHONPATH</b> environment variable for current user, "
"allowing you to run your Python modules outside Spyder "
"without having to configure sys.path. "
"<br>Do you want to clear contents of PYTHONPATH before "
"adding Spyder's path list?"),
QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
if answer == QMessageBox.Cancel:
return
elif answer == QMessageBox.Yes:
remove = True
else:
remove = False
from spyder.utils.environ import (get_user_env, set_user_env,
listdict2envdict)
env = get_user_env()
if remove:
ppath = self.active_pathlist+self.ro_pathlist
else:
ppath = env.get('PYTHONPATH', [])
if not isinstance(ppath, list):
ppath = [ppath]
ppath = [path for path in ppath
if path not in (self.active_pathlist+self.ro_pathlist)]
ppath.extend(self.active_pathlist+self.ro_pathlist)
env['PYTHONPATH'] = ppath
set_user_env(listdict2envdict(env), parent=self) | [
"def",
"synchronize",
"(",
"self",
")",
":",
"answer",
"=",
"QMessageBox",
".",
"question",
"(",
"self",
",",
"_",
"(",
"\"Synchronize\"",
")",
",",
"_",
"(",
"\"This will synchronize Spyder's path list with \"",
"\"<b>PYTHONPATH</b> environment variable for current user, \"",
"\"allowing you to run your Python modules outside Spyder \"",
"\"without having to configure sys.path. \"",
"\"<br>Do you want to clear contents of PYTHONPATH before \"",
"\"adding Spyder's path list?\"",
")",
",",
"QMessageBox",
".",
"Yes",
"|",
"QMessageBox",
".",
"No",
"|",
"QMessageBox",
".",
"Cancel",
")",
"if",
"answer",
"==",
"QMessageBox",
".",
"Cancel",
":",
"return",
"elif",
"answer",
"==",
"QMessageBox",
".",
"Yes",
":",
"remove",
"=",
"True",
"else",
":",
"remove",
"=",
"False",
"from",
"spyder",
".",
"utils",
".",
"environ",
"import",
"(",
"get_user_env",
",",
"set_user_env",
",",
"listdict2envdict",
")",
"env",
"=",
"get_user_env",
"(",
")",
"if",
"remove",
":",
"ppath",
"=",
"self",
".",
"active_pathlist",
"+",
"self",
".",
"ro_pathlist",
"else",
":",
"ppath",
"=",
"env",
".",
"get",
"(",
"'PYTHONPATH'",
",",
"[",
"]",
")",
"if",
"not",
"isinstance",
"(",
"ppath",
",",
"list",
")",
":",
"ppath",
"=",
"[",
"ppath",
"]",
"ppath",
"=",
"[",
"path",
"for",
"path",
"in",
"ppath",
"if",
"path",
"not",
"in",
"(",
"self",
".",
"active_pathlist",
"+",
"self",
".",
"ro_pathlist",
")",
"]",
"ppath",
".",
"extend",
"(",
"self",
".",
"active_pathlist",
"+",
"self",
".",
"ro_pathlist",
")",
"env",
"[",
"'PYTHONPATH'",
"]",
"=",
"ppath",
"set_user_env",
"(",
"listdict2envdict",
"(",
"env",
")",
",",
"parent",
"=",
"self",
")"
] | Synchronize Spyder's path list with PYTHONPATH environment variable
Only apply to: current user, on Windows platforms | [
"Synchronize",
"Spyder",
"s",
"path",
"list",
"with",
"PYTHONPATH",
"environment",
"variable",
"Only",
"apply",
"to",
":",
"current",
"user",
"on",
"Windows",
"platforms"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/pathmanager.py#L151-L183 | train |
spyder-ide/spyder | spyder/widgets/pathmanager.py | PathManager.update_list | def update_list(self):
"""Update path list"""
self.listwidget.clear()
for name in self.pathlist+self.ro_pathlist:
item = QListWidgetItem(name)
item.setIcon(ima.icon('DirClosedIcon'))
if name in self.ro_pathlist:
item.setFlags(Qt.NoItemFlags | Qt.ItemIsUserCheckable)
item.setCheckState(Qt.Checked)
elif name in self.not_active_pathlist:
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
item.setCheckState(Qt.Unchecked)
else:
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
item.setCheckState(Qt.Checked)
self.listwidget.addItem(item)
self.refresh() | python | def update_list(self):
"""Update path list"""
self.listwidget.clear()
for name in self.pathlist+self.ro_pathlist:
item = QListWidgetItem(name)
item.setIcon(ima.icon('DirClosedIcon'))
if name in self.ro_pathlist:
item.setFlags(Qt.NoItemFlags | Qt.ItemIsUserCheckable)
item.setCheckState(Qt.Checked)
elif name in self.not_active_pathlist:
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
item.setCheckState(Qt.Unchecked)
else:
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
item.setCheckState(Qt.Checked)
self.listwidget.addItem(item)
self.refresh() | [
"def",
"update_list",
"(",
"self",
")",
":",
"self",
".",
"listwidget",
".",
"clear",
"(",
")",
"for",
"name",
"in",
"self",
".",
"pathlist",
"+",
"self",
".",
"ro_pathlist",
":",
"item",
"=",
"QListWidgetItem",
"(",
"name",
")",
"item",
".",
"setIcon",
"(",
"ima",
".",
"icon",
"(",
"'DirClosedIcon'",
")",
")",
"if",
"name",
"in",
"self",
".",
"ro_pathlist",
":",
"item",
".",
"setFlags",
"(",
"Qt",
".",
"NoItemFlags",
"|",
"Qt",
".",
"ItemIsUserCheckable",
")",
"item",
".",
"setCheckState",
"(",
"Qt",
".",
"Checked",
")",
"elif",
"name",
"in",
"self",
".",
"not_active_pathlist",
":",
"item",
".",
"setFlags",
"(",
"item",
".",
"flags",
"(",
")",
"|",
"Qt",
".",
"ItemIsUserCheckable",
")",
"item",
".",
"setCheckState",
"(",
"Qt",
".",
"Unchecked",
")",
"else",
":",
"item",
".",
"setFlags",
"(",
"item",
".",
"flags",
"(",
")",
"|",
"Qt",
".",
"ItemIsUserCheckable",
")",
"item",
".",
"setCheckState",
"(",
"Qt",
".",
"Checked",
")",
"self",
".",
"listwidget",
".",
"addItem",
"(",
"item",
")",
"self",
".",
"refresh",
"(",
")"
] | Update path list | [
"Update",
"path",
"list"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/pathmanager.py#L204-L220 | train |
spyder-ide/spyder | spyder/widgets/pathmanager.py | PathManager.refresh | def refresh(self, row=None):
"""Refresh widget"""
for widget in self.selection_widgets:
widget.setEnabled(self.listwidget.currentItem() is not None)
not_empty = self.listwidget.count() > 0
if self.sync_button is not None:
self.sync_button.setEnabled(not_empty) | python | def refresh(self, row=None):
"""Refresh widget"""
for widget in self.selection_widgets:
widget.setEnabled(self.listwidget.currentItem() is not None)
not_empty = self.listwidget.count() > 0
if self.sync_button is not None:
self.sync_button.setEnabled(not_empty) | [
"def",
"refresh",
"(",
"self",
",",
"row",
"=",
"None",
")",
":",
"for",
"widget",
"in",
"self",
".",
"selection_widgets",
":",
"widget",
".",
"setEnabled",
"(",
"self",
".",
"listwidget",
".",
"currentItem",
"(",
")",
"is",
"not",
"None",
")",
"not_empty",
"=",
"self",
".",
"listwidget",
".",
"count",
"(",
")",
">",
"0",
"if",
"self",
".",
"sync_button",
"is",
"not",
"None",
":",
"self",
".",
"sync_button",
".",
"setEnabled",
"(",
"not_empty",
")"
] | Refresh widget | [
"Refresh",
"widget"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/pathmanager.py#L222-L228 | train |
spyder-ide/spyder | spyder/widgets/tabs.py | EditTabNamePopup.eventFilter | def eventFilter(self, widget, event):
"""Catch clicks outside the object and ESC key press."""
if ((event.type() == QEvent.MouseButtonPress and
not self.geometry().contains(event.globalPos())) or
(event.type() == QEvent.KeyPress and
event.key() == Qt.Key_Escape)):
# Exits editing
self.hide()
self.setFocus(False)
return True
# Event is not interessant, raise to parent
return QLineEdit.eventFilter(self, widget, event) | python | def eventFilter(self, widget, event):
"""Catch clicks outside the object and ESC key press."""
if ((event.type() == QEvent.MouseButtonPress and
not self.geometry().contains(event.globalPos())) or
(event.type() == QEvent.KeyPress and
event.key() == Qt.Key_Escape)):
# Exits editing
self.hide()
self.setFocus(False)
return True
# Event is not interessant, raise to parent
return QLineEdit.eventFilter(self, widget, event) | [
"def",
"eventFilter",
"(",
"self",
",",
"widget",
",",
"event",
")",
":",
"if",
"(",
"(",
"event",
".",
"type",
"(",
")",
"==",
"QEvent",
".",
"MouseButtonPress",
"and",
"not",
"self",
".",
"geometry",
"(",
")",
".",
"contains",
"(",
"event",
".",
"globalPos",
"(",
")",
")",
")",
"or",
"(",
"event",
".",
"type",
"(",
")",
"==",
"QEvent",
".",
"KeyPress",
"and",
"event",
".",
"key",
"(",
")",
"==",
"Qt",
".",
"Key_Escape",
")",
")",
":",
"# Exits editing\r",
"self",
".",
"hide",
"(",
")",
"self",
".",
"setFocus",
"(",
"False",
")",
"return",
"True",
"# Event is not interessant, raise to parent\r",
"return",
"QLineEdit",
".",
"eventFilter",
"(",
"self",
",",
"widget",
",",
"event",
")"
] | Catch clicks outside the object and ESC key press. | [
"Catch",
"clicks",
"outside",
"the",
"object",
"and",
"ESC",
"key",
"press",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L77-L89 | train |
spyder-ide/spyder | spyder/widgets/tabs.py | EditTabNamePopup.edit_tab | def edit_tab(self, index):
"""Activate the edit tab."""
# Sets focus, shows cursor
self.setFocus(True)
# Updates tab index
self.tab_index = index
# Gets tab size and shrinks to avoid overlapping tab borders
rect = self.main.tabRect(index)
rect.adjust(1, 1, -2, -1)
# Sets size
self.setFixedSize(rect.size())
# Places on top of the tab
self.move(self.main.mapToGlobal(rect.topLeft()))
# Copies tab name and selects all
text = self.main.tabText(index)
text = text.replace(u'&', u'')
if self.split_char:
text = text.split(self.split_char)[self.split_index]
self.setText(text)
self.selectAll()
if not self.isVisible():
# Makes editor visible
self.show() | python | def edit_tab(self, index):
"""Activate the edit tab."""
# Sets focus, shows cursor
self.setFocus(True)
# Updates tab index
self.tab_index = index
# Gets tab size and shrinks to avoid overlapping tab borders
rect = self.main.tabRect(index)
rect.adjust(1, 1, -2, -1)
# Sets size
self.setFixedSize(rect.size())
# Places on top of the tab
self.move(self.main.mapToGlobal(rect.topLeft()))
# Copies tab name and selects all
text = self.main.tabText(index)
text = text.replace(u'&', u'')
if self.split_char:
text = text.split(self.split_char)[self.split_index]
self.setText(text)
self.selectAll()
if not self.isVisible():
# Makes editor visible
self.show() | [
"def",
"edit_tab",
"(",
"self",
",",
"index",
")",
":",
"# Sets focus, shows cursor\r",
"self",
".",
"setFocus",
"(",
"True",
")",
"# Updates tab index\r",
"self",
".",
"tab_index",
"=",
"index",
"# Gets tab size and shrinks to avoid overlapping tab borders\r",
"rect",
"=",
"self",
".",
"main",
".",
"tabRect",
"(",
"index",
")",
"rect",
".",
"adjust",
"(",
"1",
",",
"1",
",",
"-",
"2",
",",
"-",
"1",
")",
"# Sets size\r",
"self",
".",
"setFixedSize",
"(",
"rect",
".",
"size",
"(",
")",
")",
"# Places on top of the tab\r",
"self",
".",
"move",
"(",
"self",
".",
"main",
".",
"mapToGlobal",
"(",
"rect",
".",
"topLeft",
"(",
")",
")",
")",
"# Copies tab name and selects all\r",
"text",
"=",
"self",
".",
"main",
".",
"tabText",
"(",
"index",
")",
"text",
"=",
"text",
".",
"replace",
"(",
"u'&'",
",",
"u''",
")",
"if",
"self",
".",
"split_char",
":",
"text",
"=",
"text",
".",
"split",
"(",
"self",
".",
"split_char",
")",
"[",
"self",
".",
"split_index",
"]",
"self",
".",
"setText",
"(",
"text",
")",
"self",
".",
"selectAll",
"(",
")",
"if",
"not",
"self",
".",
"isVisible",
"(",
")",
":",
"# Makes editor visible\r",
"self",
".",
"show",
"(",
")"
] | Activate the edit tab. | [
"Activate",
"the",
"edit",
"tab",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L91-L121 | train |
spyder-ide/spyder | spyder/widgets/tabs.py | EditTabNamePopup.edit_finished | def edit_finished(self):
"""On clean exit, update tab name."""
# Hides editor
self.hide()
if isinstance(self.tab_index, int) and self.tab_index >= 0:
# We are editing a valid tab, update name
tab_text = to_text_string(self.text())
self.main.setTabText(self.tab_index, tab_text)
self.main.sig_change_name.emit(tab_text) | python | def edit_finished(self):
"""On clean exit, update tab name."""
# Hides editor
self.hide()
if isinstance(self.tab_index, int) and self.tab_index >= 0:
# We are editing a valid tab, update name
tab_text = to_text_string(self.text())
self.main.setTabText(self.tab_index, tab_text)
self.main.sig_change_name.emit(tab_text) | [
"def",
"edit_finished",
"(",
"self",
")",
":",
"# Hides editor\r",
"self",
".",
"hide",
"(",
")",
"if",
"isinstance",
"(",
"self",
".",
"tab_index",
",",
"int",
")",
"and",
"self",
".",
"tab_index",
">=",
"0",
":",
"# We are editing a valid tab, update name\r",
"tab_text",
"=",
"to_text_string",
"(",
"self",
".",
"text",
"(",
")",
")",
"self",
".",
"main",
".",
"setTabText",
"(",
"self",
".",
"tab_index",
",",
"tab_text",
")",
"self",
".",
"main",
".",
"sig_change_name",
".",
"emit",
"(",
"tab_text",
")"
] | On clean exit, update tab name. | [
"On",
"clean",
"exit",
"update",
"tab",
"name",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L123-L132 | train |
spyder-ide/spyder | spyder/widgets/tabs.py | TabBar.mousePressEvent | def mousePressEvent(self, event):
"""Reimplement Qt method"""
if event.button() == Qt.LeftButton:
self.__drag_start_pos = QPoint(event.pos())
QTabBar.mousePressEvent(self, event) | python | def mousePressEvent(self, event):
"""Reimplement Qt method"""
if event.button() == Qt.LeftButton:
self.__drag_start_pos = QPoint(event.pos())
QTabBar.mousePressEvent(self, event) | [
"def",
"mousePressEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"button",
"(",
")",
"==",
"Qt",
".",
"LeftButton",
":",
"self",
".",
"__drag_start_pos",
"=",
"QPoint",
"(",
"event",
".",
"pos",
"(",
")",
")",
"QTabBar",
".",
"mousePressEvent",
"(",
"self",
",",
"event",
")"
] | Reimplement Qt method | [
"Reimplement",
"Qt",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L164-L168 | train |
spyder-ide/spyder | spyder/widgets/tabs.py | TabBar.dragEnterEvent | def dragEnterEvent(self, event):
"""Override Qt method"""
mimeData = event.mimeData()
formats = list(mimeData.formats())
if "parent-id" in formats and \
int(mimeData.data("parent-id")) == id(self.ancestor):
event.acceptProposedAction()
QTabBar.dragEnterEvent(self, event) | python | def dragEnterEvent(self, event):
"""Override Qt method"""
mimeData = event.mimeData()
formats = list(mimeData.formats())
if "parent-id" in formats and \
int(mimeData.data("parent-id")) == id(self.ancestor):
event.acceptProposedAction()
QTabBar.dragEnterEvent(self, event) | [
"def",
"dragEnterEvent",
"(",
"self",
",",
"event",
")",
":",
"mimeData",
"=",
"event",
".",
"mimeData",
"(",
")",
"formats",
"=",
"list",
"(",
"mimeData",
".",
"formats",
"(",
")",
")",
"if",
"\"parent-id\"",
"in",
"formats",
"and",
"int",
"(",
"mimeData",
".",
"data",
"(",
"\"parent-id\"",
")",
")",
"==",
"id",
"(",
"self",
".",
"ancestor",
")",
":",
"event",
".",
"acceptProposedAction",
"(",
")",
"QTabBar",
".",
"dragEnterEvent",
"(",
"self",
",",
"event",
")"
] | Override Qt method | [
"Override",
"Qt",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L197-L206 | train |
spyder-ide/spyder | spyder/widgets/tabs.py | TabBar.dropEvent | def dropEvent(self, event):
"""Override Qt method"""
mimeData = event.mimeData()
index_from = int(mimeData.data("source-index"))
index_to = self.tabAt(event.pos())
if index_to == -1:
index_to = self.count()
if int(mimeData.data("tabbar-id")) != id(self):
tabwidget_from = to_text_string(mimeData.data("tabwidget-id"))
# We pass self object ID as a QString, because otherwise it would
# depend on the platform: long for 64bit, int for 32bit. Replacing
# by long all the time is not working on some 32bit platforms
# (see Issue 1094, Issue 1098)
self.sig_move_tab[(str, int, int)].emit(tabwidget_from, index_from,
index_to)
event.acceptProposedAction()
elif index_from != index_to:
self.sig_move_tab.emit(index_from, index_to)
event.acceptProposedAction()
QTabBar.dropEvent(self, event) | python | def dropEvent(self, event):
"""Override Qt method"""
mimeData = event.mimeData()
index_from = int(mimeData.data("source-index"))
index_to = self.tabAt(event.pos())
if index_to == -1:
index_to = self.count()
if int(mimeData.data("tabbar-id")) != id(self):
tabwidget_from = to_text_string(mimeData.data("tabwidget-id"))
# We pass self object ID as a QString, because otherwise it would
# depend on the platform: long for 64bit, int for 32bit. Replacing
# by long all the time is not working on some 32bit platforms
# (see Issue 1094, Issue 1098)
self.sig_move_tab[(str, int, int)].emit(tabwidget_from, index_from,
index_to)
event.acceptProposedAction()
elif index_from != index_to:
self.sig_move_tab.emit(index_from, index_to)
event.acceptProposedAction()
QTabBar.dropEvent(self, event) | [
"def",
"dropEvent",
"(",
"self",
",",
"event",
")",
":",
"mimeData",
"=",
"event",
".",
"mimeData",
"(",
")",
"index_from",
"=",
"int",
"(",
"mimeData",
".",
"data",
"(",
"\"source-index\"",
")",
")",
"index_to",
"=",
"self",
".",
"tabAt",
"(",
"event",
".",
"pos",
"(",
")",
")",
"if",
"index_to",
"==",
"-",
"1",
":",
"index_to",
"=",
"self",
".",
"count",
"(",
")",
"if",
"int",
"(",
"mimeData",
".",
"data",
"(",
"\"tabbar-id\"",
")",
")",
"!=",
"id",
"(",
"self",
")",
":",
"tabwidget_from",
"=",
"to_text_string",
"(",
"mimeData",
".",
"data",
"(",
"\"tabwidget-id\"",
")",
")",
"# We pass self object ID as a QString, because otherwise it would \r",
"# depend on the platform: long for 64bit, int for 32bit. Replacing \r",
"# by long all the time is not working on some 32bit platforms \r",
"# (see Issue 1094, Issue 1098)\r",
"self",
".",
"sig_move_tab",
"[",
"(",
"str",
",",
"int",
",",
"int",
")",
"]",
".",
"emit",
"(",
"tabwidget_from",
",",
"index_from",
",",
"index_to",
")",
"event",
".",
"acceptProposedAction",
"(",
")",
"elif",
"index_from",
"!=",
"index_to",
":",
"self",
".",
"sig_move_tab",
".",
"emit",
"(",
"index_from",
",",
"index_to",
")",
"event",
".",
"acceptProposedAction",
"(",
")",
"QTabBar",
".",
"dropEvent",
"(",
"self",
",",
"event",
")"
] | Override Qt method | [
"Override",
"Qt",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L208-L228 | train |
spyder-ide/spyder | spyder/widgets/tabs.py | TabBar.mouseDoubleClickEvent | def mouseDoubleClickEvent(self, event):
"""Override Qt method to trigger the tab name editor."""
if self.rename_tabs is True and \
event.buttons() == Qt.MouseButtons(Qt.LeftButton):
# Tab index
index = self.tabAt(event.pos())
if index >= 0:
# Tab is valid, call tab name editor
self.tab_name_editor.edit_tab(index)
else:
# Event is not interesting, raise to parent
QTabBar.mouseDoubleClickEvent(self, event) | python | def mouseDoubleClickEvent(self, event):
"""Override Qt method to trigger the tab name editor."""
if self.rename_tabs is True and \
event.buttons() == Qt.MouseButtons(Qt.LeftButton):
# Tab index
index = self.tabAt(event.pos())
if index >= 0:
# Tab is valid, call tab name editor
self.tab_name_editor.edit_tab(index)
else:
# Event is not interesting, raise to parent
QTabBar.mouseDoubleClickEvent(self, event) | [
"def",
"mouseDoubleClickEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"rename_tabs",
"is",
"True",
"and",
"event",
".",
"buttons",
"(",
")",
"==",
"Qt",
".",
"MouseButtons",
"(",
"Qt",
".",
"LeftButton",
")",
":",
"# Tab index\r",
"index",
"=",
"self",
".",
"tabAt",
"(",
"event",
".",
"pos",
"(",
")",
")",
"if",
"index",
">=",
"0",
":",
"# Tab is valid, call tab name editor\r",
"self",
".",
"tab_name_editor",
".",
"edit_tab",
"(",
"index",
")",
"else",
":",
"# Event is not interesting, raise to parent\r",
"QTabBar",
".",
"mouseDoubleClickEvent",
"(",
"self",
",",
"event",
")"
] | Override Qt method to trigger the tab name editor. | [
"Override",
"Qt",
"method",
"to",
"trigger",
"the",
"tab",
"name",
"editor",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L230-L241 | train |
spyder-ide/spyder | spyder/widgets/tabs.py | BaseTabs.update_browse_tabs_menu | def update_browse_tabs_menu(self):
"""Update browse tabs menu"""
self.browse_tabs_menu.clear()
names = []
dirnames = []
for index in range(self.count()):
if self.menu_use_tooltips:
text = to_text_string(self.tabToolTip(index))
else:
text = to_text_string(self.tabText(index))
names.append(text)
if osp.isfile(text):
# Testing if tab names are filenames
dirnames.append(osp.dirname(text))
offset = None
# If tab names are all filenames, removing common path:
if len(names) == len(dirnames):
common = get_common_path(dirnames)
if common is None:
offset = None
else:
offset = len(common)+1
if offset <= 3:
# Common path is not a path but a drive letter...
offset = None
for index, text in enumerate(names):
tab_action = create_action(self, text[offset:],
icon=self.tabIcon(index),
toggled=lambda state, index=index:
self.setCurrentIndex(index),
tip=self.tabToolTip(index))
tab_action.setChecked(index == self.currentIndex())
self.browse_tabs_menu.addAction(tab_action) | python | def update_browse_tabs_menu(self):
"""Update browse tabs menu"""
self.browse_tabs_menu.clear()
names = []
dirnames = []
for index in range(self.count()):
if self.menu_use_tooltips:
text = to_text_string(self.tabToolTip(index))
else:
text = to_text_string(self.tabText(index))
names.append(text)
if osp.isfile(text):
# Testing if tab names are filenames
dirnames.append(osp.dirname(text))
offset = None
# If tab names are all filenames, removing common path:
if len(names) == len(dirnames):
common = get_common_path(dirnames)
if common is None:
offset = None
else:
offset = len(common)+1
if offset <= 3:
# Common path is not a path but a drive letter...
offset = None
for index, text in enumerate(names):
tab_action = create_action(self, text[offset:],
icon=self.tabIcon(index),
toggled=lambda state, index=index:
self.setCurrentIndex(index),
tip=self.tabToolTip(index))
tab_action.setChecked(index == self.currentIndex())
self.browse_tabs_menu.addAction(tab_action) | [
"def",
"update_browse_tabs_menu",
"(",
"self",
")",
":",
"self",
".",
"browse_tabs_menu",
".",
"clear",
"(",
")",
"names",
"=",
"[",
"]",
"dirnames",
"=",
"[",
"]",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"count",
"(",
")",
")",
":",
"if",
"self",
".",
"menu_use_tooltips",
":",
"text",
"=",
"to_text_string",
"(",
"self",
".",
"tabToolTip",
"(",
"index",
")",
")",
"else",
":",
"text",
"=",
"to_text_string",
"(",
"self",
".",
"tabText",
"(",
"index",
")",
")",
"names",
".",
"append",
"(",
"text",
")",
"if",
"osp",
".",
"isfile",
"(",
"text",
")",
":",
"# Testing if tab names are filenames\r",
"dirnames",
".",
"append",
"(",
"osp",
".",
"dirname",
"(",
"text",
")",
")",
"offset",
"=",
"None",
"# If tab names are all filenames, removing common path:\r",
"if",
"len",
"(",
"names",
")",
"==",
"len",
"(",
"dirnames",
")",
":",
"common",
"=",
"get_common_path",
"(",
"dirnames",
")",
"if",
"common",
"is",
"None",
":",
"offset",
"=",
"None",
"else",
":",
"offset",
"=",
"len",
"(",
"common",
")",
"+",
"1",
"if",
"offset",
"<=",
"3",
":",
"# Common path is not a path but a drive letter...\r",
"offset",
"=",
"None",
"for",
"index",
",",
"text",
"in",
"enumerate",
"(",
"names",
")",
":",
"tab_action",
"=",
"create_action",
"(",
"self",
",",
"text",
"[",
"offset",
":",
"]",
",",
"icon",
"=",
"self",
".",
"tabIcon",
"(",
"index",
")",
",",
"toggled",
"=",
"lambda",
"state",
",",
"index",
"=",
"index",
":",
"self",
".",
"setCurrentIndex",
"(",
"index",
")",
",",
"tip",
"=",
"self",
".",
"tabToolTip",
"(",
"index",
")",
")",
"tab_action",
".",
"setChecked",
"(",
"index",
"==",
"self",
".",
"currentIndex",
"(",
")",
")",
"self",
".",
"browse_tabs_menu",
".",
"addAction",
"(",
"tab_action",
")"
] | Update browse tabs menu | [
"Update",
"browse",
"tabs",
"menu"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L288-L322 | train |
spyder-ide/spyder | spyder/widgets/tabs.py | BaseTabs.set_corner_widgets | def set_corner_widgets(self, corner_widgets):
"""
Set tabs corner widgets
corner_widgets: dictionary of (corner, widgets)
corner: Qt.TopLeftCorner or Qt.TopRightCorner
widgets: list of widgets (may contains integers to add spacings)
"""
assert isinstance(corner_widgets, dict)
assert all(key in (Qt.TopLeftCorner, Qt.TopRightCorner)
for key in corner_widgets)
self.corner_widgets.update(corner_widgets)
for corner, widgets in list(self.corner_widgets.items()):
cwidget = QWidget()
cwidget.hide()
prev_widget = self.cornerWidget(corner)
if prev_widget:
prev_widget.close()
self.setCornerWidget(cwidget, corner)
clayout = QHBoxLayout()
clayout.setContentsMargins(0, 0, 0, 0)
for widget in widgets:
if isinstance(widget, int):
clayout.addSpacing(widget)
else:
clayout.addWidget(widget)
cwidget.setLayout(clayout)
cwidget.show() | python | def set_corner_widgets(self, corner_widgets):
"""
Set tabs corner widgets
corner_widgets: dictionary of (corner, widgets)
corner: Qt.TopLeftCorner or Qt.TopRightCorner
widgets: list of widgets (may contains integers to add spacings)
"""
assert isinstance(corner_widgets, dict)
assert all(key in (Qt.TopLeftCorner, Qt.TopRightCorner)
for key in corner_widgets)
self.corner_widgets.update(corner_widgets)
for corner, widgets in list(self.corner_widgets.items()):
cwidget = QWidget()
cwidget.hide()
prev_widget = self.cornerWidget(corner)
if prev_widget:
prev_widget.close()
self.setCornerWidget(cwidget, corner)
clayout = QHBoxLayout()
clayout.setContentsMargins(0, 0, 0, 0)
for widget in widgets:
if isinstance(widget, int):
clayout.addSpacing(widget)
else:
clayout.addWidget(widget)
cwidget.setLayout(clayout)
cwidget.show() | [
"def",
"set_corner_widgets",
"(",
"self",
",",
"corner_widgets",
")",
":",
"assert",
"isinstance",
"(",
"corner_widgets",
",",
"dict",
")",
"assert",
"all",
"(",
"key",
"in",
"(",
"Qt",
".",
"TopLeftCorner",
",",
"Qt",
".",
"TopRightCorner",
")",
"for",
"key",
"in",
"corner_widgets",
")",
"self",
".",
"corner_widgets",
".",
"update",
"(",
"corner_widgets",
")",
"for",
"corner",
",",
"widgets",
"in",
"list",
"(",
"self",
".",
"corner_widgets",
".",
"items",
"(",
")",
")",
":",
"cwidget",
"=",
"QWidget",
"(",
")",
"cwidget",
".",
"hide",
"(",
")",
"prev_widget",
"=",
"self",
".",
"cornerWidget",
"(",
"corner",
")",
"if",
"prev_widget",
":",
"prev_widget",
".",
"close",
"(",
")",
"self",
".",
"setCornerWidget",
"(",
"cwidget",
",",
"corner",
")",
"clayout",
"=",
"QHBoxLayout",
"(",
")",
"clayout",
".",
"setContentsMargins",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"for",
"widget",
"in",
"widgets",
":",
"if",
"isinstance",
"(",
"widget",
",",
"int",
")",
":",
"clayout",
".",
"addSpacing",
"(",
"widget",
")",
"else",
":",
"clayout",
".",
"addWidget",
"(",
"widget",
")",
"cwidget",
".",
"setLayout",
"(",
"clayout",
")",
"cwidget",
".",
"show",
"(",
")"
] | Set tabs corner widgets
corner_widgets: dictionary of (corner, widgets)
corner: Qt.TopLeftCorner or Qt.TopRightCorner
widgets: list of widgets (may contains integers to add spacings) | [
"Set",
"tabs",
"corner",
"widgets",
"corner_widgets",
":",
"dictionary",
"of",
"(",
"corner",
"widgets",
")",
"corner",
":",
"Qt",
".",
"TopLeftCorner",
"or",
"Qt",
".",
"TopRightCorner",
"widgets",
":",
"list",
"of",
"widgets",
"(",
"may",
"contains",
"integers",
"to",
"add",
"spacings",
")"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L324-L350 | train |
spyder-ide/spyder | spyder/widgets/tabs.py | BaseTabs.contextMenuEvent | def contextMenuEvent(self, event):
"""Override Qt method"""
self.setCurrentIndex(self.tabBar().tabAt(event.pos()))
if self.menu:
self.menu.popup(event.globalPos()) | python | def contextMenuEvent(self, event):
"""Override Qt method"""
self.setCurrentIndex(self.tabBar().tabAt(event.pos()))
if self.menu:
self.menu.popup(event.globalPos()) | [
"def",
"contextMenuEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"setCurrentIndex",
"(",
"self",
".",
"tabBar",
"(",
")",
".",
"tabAt",
"(",
"event",
".",
"pos",
"(",
")",
")",
")",
"if",
"self",
".",
"menu",
":",
"self",
".",
"menu",
".",
"popup",
"(",
"event",
".",
"globalPos",
"(",
")",
")"
] | Override Qt method | [
"Override",
"Qt",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L356-L360 | train |
spyder-ide/spyder | spyder/widgets/tabs.py | BaseTabs.mousePressEvent | def mousePressEvent(self, event):
"""Override Qt method"""
if event.button() == Qt.MidButton:
index = self.tabBar().tabAt(event.pos())
if index >= 0:
self.sig_close_tab.emit(index)
event.accept()
return
QTabWidget.mousePressEvent(self, event) | python | def mousePressEvent(self, event):
"""Override Qt method"""
if event.button() == Qt.MidButton:
index = self.tabBar().tabAt(event.pos())
if index >= 0:
self.sig_close_tab.emit(index)
event.accept()
return
QTabWidget.mousePressEvent(self, event) | [
"def",
"mousePressEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"button",
"(",
")",
"==",
"Qt",
".",
"MidButton",
":",
"index",
"=",
"self",
".",
"tabBar",
"(",
")",
".",
"tabAt",
"(",
"event",
".",
"pos",
"(",
")",
")",
"if",
"index",
">=",
"0",
":",
"self",
".",
"sig_close_tab",
".",
"emit",
"(",
"index",
")",
"event",
".",
"accept",
"(",
")",
"return",
"QTabWidget",
".",
"mousePressEvent",
"(",
"self",
",",
"event",
")"
] | Override Qt method | [
"Override",
"Qt",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L362-L370 | train |
spyder-ide/spyder | spyder/widgets/tabs.py | BaseTabs.keyPressEvent | def keyPressEvent(self, event):
"""Override Qt method"""
ctrl = event.modifiers() & Qt.ControlModifier
key = event.key()
handled = False
if ctrl and self.count() > 0:
index = self.currentIndex()
if key == Qt.Key_PageUp:
if index > 0:
self.setCurrentIndex(index - 1)
else:
self.setCurrentIndex(self.count() - 1)
handled = True
elif key == Qt.Key_PageDown:
if index < self.count() - 1:
self.setCurrentIndex(index + 1)
else:
self.setCurrentIndex(0)
handled = True
if not handled:
QTabWidget.keyPressEvent(self, event) | python | def keyPressEvent(self, event):
"""Override Qt method"""
ctrl = event.modifiers() & Qt.ControlModifier
key = event.key()
handled = False
if ctrl and self.count() > 0:
index = self.currentIndex()
if key == Qt.Key_PageUp:
if index > 0:
self.setCurrentIndex(index - 1)
else:
self.setCurrentIndex(self.count() - 1)
handled = True
elif key == Qt.Key_PageDown:
if index < self.count() - 1:
self.setCurrentIndex(index + 1)
else:
self.setCurrentIndex(0)
handled = True
if not handled:
QTabWidget.keyPressEvent(self, event) | [
"def",
"keyPressEvent",
"(",
"self",
",",
"event",
")",
":",
"ctrl",
"=",
"event",
".",
"modifiers",
"(",
")",
"&",
"Qt",
".",
"ControlModifier",
"key",
"=",
"event",
".",
"key",
"(",
")",
"handled",
"=",
"False",
"if",
"ctrl",
"and",
"self",
".",
"count",
"(",
")",
">",
"0",
":",
"index",
"=",
"self",
".",
"currentIndex",
"(",
")",
"if",
"key",
"==",
"Qt",
".",
"Key_PageUp",
":",
"if",
"index",
">",
"0",
":",
"self",
".",
"setCurrentIndex",
"(",
"index",
"-",
"1",
")",
"else",
":",
"self",
".",
"setCurrentIndex",
"(",
"self",
".",
"count",
"(",
")",
"-",
"1",
")",
"handled",
"=",
"True",
"elif",
"key",
"==",
"Qt",
".",
"Key_PageDown",
":",
"if",
"index",
"<",
"self",
".",
"count",
"(",
")",
"-",
"1",
":",
"self",
".",
"setCurrentIndex",
"(",
"index",
"+",
"1",
")",
"else",
":",
"self",
".",
"setCurrentIndex",
"(",
"0",
")",
"handled",
"=",
"True",
"if",
"not",
"handled",
":",
"QTabWidget",
".",
"keyPressEvent",
"(",
"self",
",",
"event",
")"
] | Override Qt method | [
"Override",
"Qt",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L372-L392 | train |
spyder-ide/spyder | spyder/widgets/tabs.py | BaseTabs.tab_navigate | def tab_navigate(self, delta=1):
"""Ctrl+Tab"""
if delta > 0 and self.currentIndex() == self.count()-1:
index = delta-1
elif delta < 0 and self.currentIndex() == 0:
index = self.count()+delta
else:
index = self.currentIndex()+delta
self.setCurrentIndex(index) | python | def tab_navigate(self, delta=1):
"""Ctrl+Tab"""
if delta > 0 and self.currentIndex() == self.count()-1:
index = delta-1
elif delta < 0 and self.currentIndex() == 0:
index = self.count()+delta
else:
index = self.currentIndex()+delta
self.setCurrentIndex(index) | [
"def",
"tab_navigate",
"(",
"self",
",",
"delta",
"=",
"1",
")",
":",
"if",
"delta",
">",
"0",
"and",
"self",
".",
"currentIndex",
"(",
")",
"==",
"self",
".",
"count",
"(",
")",
"-",
"1",
":",
"index",
"=",
"delta",
"-",
"1",
"elif",
"delta",
"<",
"0",
"and",
"self",
".",
"currentIndex",
"(",
")",
"==",
"0",
":",
"index",
"=",
"self",
".",
"count",
"(",
")",
"+",
"delta",
"else",
":",
"index",
"=",
"self",
".",
"currentIndex",
"(",
")",
"+",
"delta",
"self",
".",
"setCurrentIndex",
"(",
"index",
")"
] | Ctrl+Tab | [
"Ctrl",
"+",
"Tab"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L394-L402 | train |
spyder-ide/spyder | spyder/widgets/tabs.py | BaseTabs.set_close_function | def set_close_function(self, func):
"""Setting Tabs close function
None -> tabs are not closable"""
state = func is not None
if state:
self.sig_close_tab.connect(func)
try:
# Assuming Qt >= 4.5
QTabWidget.setTabsClosable(self, state)
self.tabCloseRequested.connect(func)
except AttributeError:
# Workaround for Qt < 4.5
close_button = create_toolbutton(self, triggered=func,
icon=ima.icon('fileclose'),
tip=_("Close current tab"))
self.setCornerWidget(close_button if state else None) | python | def set_close_function(self, func):
"""Setting Tabs close function
None -> tabs are not closable"""
state = func is not None
if state:
self.sig_close_tab.connect(func)
try:
# Assuming Qt >= 4.5
QTabWidget.setTabsClosable(self, state)
self.tabCloseRequested.connect(func)
except AttributeError:
# Workaround for Qt < 4.5
close_button = create_toolbutton(self, triggered=func,
icon=ima.icon('fileclose'),
tip=_("Close current tab"))
self.setCornerWidget(close_button if state else None) | [
"def",
"set_close_function",
"(",
"self",
",",
"func",
")",
":",
"state",
"=",
"func",
"is",
"not",
"None",
"if",
"state",
":",
"self",
".",
"sig_close_tab",
".",
"connect",
"(",
"func",
")",
"try",
":",
"# Assuming Qt >= 4.5\r",
"QTabWidget",
".",
"setTabsClosable",
"(",
"self",
",",
"state",
")",
"self",
".",
"tabCloseRequested",
".",
"connect",
"(",
"func",
")",
"except",
"AttributeError",
":",
"# Workaround for Qt < 4.5\r",
"close_button",
"=",
"create_toolbutton",
"(",
"self",
",",
"triggered",
"=",
"func",
",",
"icon",
"=",
"ima",
".",
"icon",
"(",
"'fileclose'",
")",
",",
"tip",
"=",
"_",
"(",
"\"Close current tab\"",
")",
")",
"self",
".",
"setCornerWidget",
"(",
"close_button",
"if",
"state",
"else",
"None",
")"
] | Setting Tabs close function
None -> tabs are not closable | [
"Setting",
"Tabs",
"close",
"function",
"None",
"-",
">",
"tabs",
"are",
"not",
"closable"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L404-L419 | train |
spyder-ide/spyder | spyder/widgets/tabs.py | Tabs.move_tab | def move_tab(self, index_from, index_to):
"""Move tab inside a tabwidget"""
self.move_data.emit(index_from, index_to)
tip, text = self.tabToolTip(index_from), self.tabText(index_from)
icon, widget = self.tabIcon(index_from), self.widget(index_from)
current_widget = self.currentWidget()
self.removeTab(index_from)
self.insertTab(index_to, widget, icon, text)
self.setTabToolTip(index_to, tip)
self.setCurrentWidget(current_widget)
self.move_tab_finished.emit() | python | def move_tab(self, index_from, index_to):
"""Move tab inside a tabwidget"""
self.move_data.emit(index_from, index_to)
tip, text = self.tabToolTip(index_from), self.tabText(index_from)
icon, widget = self.tabIcon(index_from), self.widget(index_from)
current_widget = self.currentWidget()
self.removeTab(index_from)
self.insertTab(index_to, widget, icon, text)
self.setTabToolTip(index_to, tip)
self.setCurrentWidget(current_widget)
self.move_tab_finished.emit() | [
"def",
"move_tab",
"(",
"self",
",",
"index_from",
",",
"index_to",
")",
":",
"self",
".",
"move_data",
".",
"emit",
"(",
"index_from",
",",
"index_to",
")",
"tip",
",",
"text",
"=",
"self",
".",
"tabToolTip",
"(",
"index_from",
")",
",",
"self",
".",
"tabText",
"(",
"index_from",
")",
"icon",
",",
"widget",
"=",
"self",
".",
"tabIcon",
"(",
"index_from",
")",
",",
"self",
".",
"widget",
"(",
"index_from",
")",
"current_widget",
"=",
"self",
".",
"currentWidget",
"(",
")",
"self",
".",
"removeTab",
"(",
"index_from",
")",
"self",
".",
"insertTab",
"(",
"index_to",
",",
"widget",
",",
"icon",
",",
"text",
")",
"self",
".",
"setTabToolTip",
"(",
"index_to",
",",
"tip",
")",
"self",
".",
"setCurrentWidget",
"(",
"current_widget",
")",
"self",
".",
"move_tab_finished",
".",
"emit",
"(",
")"
] | Move tab inside a tabwidget | [
"Move",
"tab",
"inside",
"a",
"tabwidget"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L454-L467 | train |
spyder-ide/spyder | spyder/widgets/tabs.py | Tabs.move_tab_from_another_tabwidget | def move_tab_from_another_tabwidget(self, tabwidget_from,
index_from, index_to):
"""Move tab from a tabwidget to another"""
# We pass self object IDs as QString objs, because otherwise it would
# depend on the platform: long for 64bit, int for 32bit. Replacing
# by long all the time is not working on some 32bit platforms
# (see Issue 1094, Issue 1098)
self.sig_move_tab.emit(tabwidget_from, to_text_string(id(self)),
index_from, index_to) | python | def move_tab_from_another_tabwidget(self, tabwidget_from,
index_from, index_to):
"""Move tab from a tabwidget to another"""
# We pass self object IDs as QString objs, because otherwise it would
# depend on the platform: long for 64bit, int for 32bit. Replacing
# by long all the time is not working on some 32bit platforms
# (see Issue 1094, Issue 1098)
self.sig_move_tab.emit(tabwidget_from, to_text_string(id(self)),
index_from, index_to) | [
"def",
"move_tab_from_another_tabwidget",
"(",
"self",
",",
"tabwidget_from",
",",
"index_from",
",",
"index_to",
")",
":",
"# We pass self object IDs as QString objs, because otherwise it would \r",
"# depend on the platform: long for 64bit, int for 32bit. Replacing \r",
"# by long all the time is not working on some 32bit platforms \r",
"# (see Issue 1094, Issue 1098)\r",
"self",
".",
"sig_move_tab",
".",
"emit",
"(",
"tabwidget_from",
",",
"to_text_string",
"(",
"id",
"(",
"self",
")",
")",
",",
"index_from",
",",
"index_to",
")"
] | Move tab from a tabwidget to another | [
"Move",
"tab",
"from",
"a",
"tabwidget",
"to",
"another"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L470-L479 | train |
spyder-ide/spyder | spyder/preferences/runconfig.py | get_run_configuration | def get_run_configuration(fname):
"""Return script *fname* run configuration"""
configurations = _get_run_configurations()
for filename, options in configurations:
if fname == filename:
runconf = RunConfiguration()
runconf.set(options)
return runconf | python | def get_run_configuration(fname):
"""Return script *fname* run configuration"""
configurations = _get_run_configurations()
for filename, options in configurations:
if fname == filename:
runconf = RunConfiguration()
runconf.set(options)
return runconf | [
"def",
"get_run_configuration",
"(",
"fname",
")",
":",
"configurations",
"=",
"_get_run_configurations",
"(",
")",
"for",
"filename",
",",
"options",
"in",
"configurations",
":",
"if",
"fname",
"==",
"filename",
":",
"runconf",
"=",
"RunConfiguration",
"(",
")",
"runconf",
".",
"set",
"(",
"options",
")",
"return",
"runconf"
] | Return script *fname* run configuration | [
"Return",
"script",
"*",
"fname",
"*",
"run",
"configuration"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/runconfig.py#L150-L157 | train |
spyder-ide/spyder | spyder/preferences/runconfig.py | RunConfigOptions.select_directory | def select_directory(self):
"""Select directory"""
basedir = to_text_string(self.wd_edit.text())
if not osp.isdir(basedir):
basedir = getcwd_or_home()
directory = getexistingdirectory(self, _("Select directory"), basedir)
if directory:
self.wd_edit.setText(directory)
self.dir = directory | python | def select_directory(self):
"""Select directory"""
basedir = to_text_string(self.wd_edit.text())
if not osp.isdir(basedir):
basedir = getcwd_or_home()
directory = getexistingdirectory(self, _("Select directory"), basedir)
if directory:
self.wd_edit.setText(directory)
self.dir = directory | [
"def",
"select_directory",
"(",
"self",
")",
":",
"basedir",
"=",
"to_text_string",
"(",
"self",
".",
"wd_edit",
".",
"text",
"(",
")",
")",
"if",
"not",
"osp",
".",
"isdir",
"(",
"basedir",
")",
":",
"basedir",
"=",
"getcwd_or_home",
"(",
")",
"directory",
"=",
"getexistingdirectory",
"(",
"self",
",",
"_",
"(",
"\"Select directory\"",
")",
",",
"basedir",
")",
"if",
"directory",
":",
"self",
".",
"wd_edit",
".",
"setText",
"(",
"directory",
")",
"self",
".",
"dir",
"=",
"directory"
] | Select directory | [
"Select",
"directory"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/runconfig.py#L263-L271 | train |
spyder-ide/spyder | spyder/preferences/runconfig.py | BaseRunConfigDialog.add_widgets | def add_widgets(self, *widgets_or_spacings):
"""Add widgets/spacing to dialog vertical layout"""
layout = self.layout()
for widget_or_spacing in widgets_or_spacings:
if isinstance(widget_or_spacing, int):
layout.addSpacing(widget_or_spacing)
else:
layout.addWidget(widget_or_spacing) | python | def add_widgets(self, *widgets_or_spacings):
"""Add widgets/spacing to dialog vertical layout"""
layout = self.layout()
for widget_or_spacing in widgets_or_spacings:
if isinstance(widget_or_spacing, int):
layout.addSpacing(widget_or_spacing)
else:
layout.addWidget(widget_or_spacing) | [
"def",
"add_widgets",
"(",
"self",
",",
"*",
"widgets_or_spacings",
")",
":",
"layout",
"=",
"self",
".",
"layout",
"(",
")",
"for",
"widget_or_spacing",
"in",
"widgets_or_spacings",
":",
"if",
"isinstance",
"(",
"widget_or_spacing",
",",
"int",
")",
":",
"layout",
".",
"addSpacing",
"(",
"widget_or_spacing",
")",
"else",
":",
"layout",
".",
"addWidget",
"(",
"widget_or_spacing",
")"
] | Add widgets/spacing to dialog vertical layout | [
"Add",
"widgets",
"/",
"spacing",
"to",
"dialog",
"vertical",
"layout"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/runconfig.py#L342-L349 | train |
spyder-ide/spyder | spyder/preferences/runconfig.py | BaseRunConfigDialog.add_button_box | def add_button_box(self, stdbtns):
"""Create dialog button box and add it to the dialog layout"""
bbox = QDialogButtonBox(stdbtns)
run_btn = bbox.addButton(_("Run"), QDialogButtonBox.AcceptRole)
run_btn.clicked.connect(self.run_btn_clicked)
bbox.accepted.connect(self.accept)
bbox.rejected.connect(self.reject)
btnlayout = QHBoxLayout()
btnlayout.addStretch(1)
btnlayout.addWidget(bbox)
self.layout().addLayout(btnlayout) | python | def add_button_box(self, stdbtns):
"""Create dialog button box and add it to the dialog layout"""
bbox = QDialogButtonBox(stdbtns)
run_btn = bbox.addButton(_("Run"), QDialogButtonBox.AcceptRole)
run_btn.clicked.connect(self.run_btn_clicked)
bbox.accepted.connect(self.accept)
bbox.rejected.connect(self.reject)
btnlayout = QHBoxLayout()
btnlayout.addStretch(1)
btnlayout.addWidget(bbox)
self.layout().addLayout(btnlayout) | [
"def",
"add_button_box",
"(",
"self",
",",
"stdbtns",
")",
":",
"bbox",
"=",
"QDialogButtonBox",
"(",
"stdbtns",
")",
"run_btn",
"=",
"bbox",
".",
"addButton",
"(",
"_",
"(",
"\"Run\"",
")",
",",
"QDialogButtonBox",
".",
"AcceptRole",
")",
"run_btn",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"run_btn_clicked",
")",
"bbox",
".",
"accepted",
".",
"connect",
"(",
"self",
".",
"accept",
")",
"bbox",
".",
"rejected",
".",
"connect",
"(",
"self",
".",
"reject",
")",
"btnlayout",
"=",
"QHBoxLayout",
"(",
")",
"btnlayout",
".",
"addStretch",
"(",
"1",
")",
"btnlayout",
".",
"addWidget",
"(",
"bbox",
")",
"self",
".",
"layout",
"(",
")",
".",
"addLayout",
"(",
"btnlayout",
")"
] | Create dialog button box and add it to the dialog layout | [
"Create",
"dialog",
"button",
"box",
"and",
"add",
"it",
"to",
"the",
"dialog",
"layout"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/runconfig.py#L351-L361 | train |
spyder-ide/spyder | spyder/preferences/runconfig.py | RunConfigOneDialog.setup | def setup(self, fname):
"""Setup Run Configuration dialog with filename *fname*"""
self.filename = fname
self.runconfigoptions = RunConfigOptions(self)
self.runconfigoptions.set(RunConfiguration(fname).get())
self.add_widgets(self.runconfigoptions)
self.add_button_box(QDialogButtonBox.Cancel)
self.setWindowTitle(_("Run settings for %s") % osp.basename(fname)) | python | def setup(self, fname):
"""Setup Run Configuration dialog with filename *fname*"""
self.filename = fname
self.runconfigoptions = RunConfigOptions(self)
self.runconfigoptions.set(RunConfiguration(fname).get())
self.add_widgets(self.runconfigoptions)
self.add_button_box(QDialogButtonBox.Cancel)
self.setWindowTitle(_("Run settings for %s") % osp.basename(fname)) | [
"def",
"setup",
"(",
"self",
",",
"fname",
")",
":",
"self",
".",
"filename",
"=",
"fname",
"self",
".",
"runconfigoptions",
"=",
"RunConfigOptions",
"(",
"self",
")",
"self",
".",
"runconfigoptions",
".",
"set",
"(",
"RunConfiguration",
"(",
"fname",
")",
".",
"get",
"(",
")",
")",
"self",
".",
"add_widgets",
"(",
"self",
".",
"runconfigoptions",
")",
"self",
".",
"add_button_box",
"(",
"QDialogButtonBox",
".",
"Cancel",
")",
"self",
".",
"setWindowTitle",
"(",
"_",
"(",
"\"Run settings for %s\"",
")",
"%",
"osp",
".",
"basename",
"(",
"fname",
")",
")"
] | Setup Run Configuration dialog with filename *fname* | [
"Setup",
"Run",
"Configuration",
"dialog",
"with",
"filename",
"*",
"fname",
"*"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/runconfig.py#L387-L394 | train |
spyder-ide/spyder | spyder/preferences/runconfig.py | RunConfigOneDialog.accept | def accept(self):
"""Reimplement Qt method"""
if not self.runconfigoptions.is_valid():
return
configurations = _get_run_configurations()
configurations.insert(0, (self.filename, self.runconfigoptions.get()))
_set_run_configurations(configurations)
QDialog.accept(self) | python | def accept(self):
"""Reimplement Qt method"""
if not self.runconfigoptions.is_valid():
return
configurations = _get_run_configurations()
configurations.insert(0, (self.filename, self.runconfigoptions.get()))
_set_run_configurations(configurations)
QDialog.accept(self) | [
"def",
"accept",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"runconfigoptions",
".",
"is_valid",
"(",
")",
":",
"return",
"configurations",
"=",
"_get_run_configurations",
"(",
")",
"configurations",
".",
"insert",
"(",
"0",
",",
"(",
"self",
".",
"filename",
",",
"self",
".",
"runconfigoptions",
".",
"get",
"(",
")",
")",
")",
"_set_run_configurations",
"(",
"configurations",
")",
"QDialog",
".",
"accept",
"(",
"self",
")"
] | Reimplement Qt method | [
"Reimplement",
"Qt",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/runconfig.py#L397-L404 | train |
spyder-ide/spyder | spyder/preferences/runconfig.py | RunConfigDialog.setup | def setup(self, fname):
"""Setup Run Configuration dialog with filename *fname*"""
combo_label = QLabel(_("Select a run configuration:"))
self.combo = QComboBox()
self.combo.setMaxVisibleItems(20)
self.combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
self.combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
self.stack = QStackedWidget()
configurations = _get_run_configurations()
for index, (filename, options) in enumerate(configurations):
if fname == filename:
break
else:
# There is no run configuration for script *fname*:
# creating a temporary configuration that will be kept only if
# dialog changes are accepted by the user
configurations.insert(0, (fname, RunConfiguration(fname).get()))
index = 0
for filename, options in configurations:
widget = RunConfigOptions(self)
widget.set(options)
self.combo.addItem(filename)
self.stack.addWidget(widget)
self.combo.currentIndexChanged.connect(self.stack.setCurrentIndex)
self.combo.setCurrentIndex(index)
self.add_widgets(combo_label, self.combo, 10, self.stack)
self.add_button_box(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
self.setWindowTitle(_("Run configuration per file")) | python | def setup(self, fname):
"""Setup Run Configuration dialog with filename *fname*"""
combo_label = QLabel(_("Select a run configuration:"))
self.combo = QComboBox()
self.combo.setMaxVisibleItems(20)
self.combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
self.combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
self.stack = QStackedWidget()
configurations = _get_run_configurations()
for index, (filename, options) in enumerate(configurations):
if fname == filename:
break
else:
# There is no run configuration for script *fname*:
# creating a temporary configuration that will be kept only if
# dialog changes are accepted by the user
configurations.insert(0, (fname, RunConfiguration(fname).get()))
index = 0
for filename, options in configurations:
widget = RunConfigOptions(self)
widget.set(options)
self.combo.addItem(filename)
self.stack.addWidget(widget)
self.combo.currentIndexChanged.connect(self.stack.setCurrentIndex)
self.combo.setCurrentIndex(index)
self.add_widgets(combo_label, self.combo, 10, self.stack)
self.add_button_box(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
self.setWindowTitle(_("Run configuration per file")) | [
"def",
"setup",
"(",
"self",
",",
"fname",
")",
":",
"combo_label",
"=",
"QLabel",
"(",
"_",
"(",
"\"Select a run configuration:\"",
")",
")",
"self",
".",
"combo",
"=",
"QComboBox",
"(",
")",
"self",
".",
"combo",
".",
"setMaxVisibleItems",
"(",
"20",
")",
"self",
".",
"combo",
".",
"setSizeAdjustPolicy",
"(",
"QComboBox",
".",
"AdjustToMinimumContentsLength",
")",
"self",
".",
"combo",
".",
"setSizePolicy",
"(",
"QSizePolicy",
".",
"Expanding",
",",
"QSizePolicy",
".",
"Fixed",
")",
"self",
".",
"stack",
"=",
"QStackedWidget",
"(",
")",
"configurations",
"=",
"_get_run_configurations",
"(",
")",
"for",
"index",
",",
"(",
"filename",
",",
"options",
")",
"in",
"enumerate",
"(",
"configurations",
")",
":",
"if",
"fname",
"==",
"filename",
":",
"break",
"else",
":",
"# There is no run configuration for script *fname*:\r",
"# creating a temporary configuration that will be kept only if\r",
"# dialog changes are accepted by the user\r",
"configurations",
".",
"insert",
"(",
"0",
",",
"(",
"fname",
",",
"RunConfiguration",
"(",
"fname",
")",
".",
"get",
"(",
")",
")",
")",
"index",
"=",
"0",
"for",
"filename",
",",
"options",
"in",
"configurations",
":",
"widget",
"=",
"RunConfigOptions",
"(",
"self",
")",
"widget",
".",
"set",
"(",
"options",
")",
"self",
".",
"combo",
".",
"addItem",
"(",
"filename",
")",
"self",
".",
"stack",
".",
"addWidget",
"(",
"widget",
")",
"self",
".",
"combo",
".",
"currentIndexChanged",
".",
"connect",
"(",
"self",
".",
"stack",
".",
"setCurrentIndex",
")",
"self",
".",
"combo",
".",
"setCurrentIndex",
"(",
"index",
")",
"self",
".",
"add_widgets",
"(",
"combo_label",
",",
"self",
".",
"combo",
",",
"10",
",",
"self",
".",
"stack",
")",
"self",
".",
"add_button_box",
"(",
"QDialogButtonBox",
".",
"Ok",
"|",
"QDialogButtonBox",
".",
"Cancel",
")",
"self",
".",
"setWindowTitle",
"(",
"_",
"(",
"\"Run configuration per file\"",
")",
")"
] | Setup Run Configuration dialog with filename *fname* | [
"Setup",
"Run",
"Configuration",
"dialog",
"with",
"filename",
"*",
"fname",
"*"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/runconfig.py#L424-L455 | train |
spyder-ide/spyder | spyder/preferences/runconfig.py | RunConfigDialog.accept | def accept(self):
"""Reimplement Qt method"""
configurations = []
for index in range(self.stack.count()):
filename = to_text_string(self.combo.itemText(index))
runconfigoptions = self.stack.widget(index)
if index == self.stack.currentIndex() and\
not runconfigoptions.is_valid():
return
options = runconfigoptions.get()
configurations.append( (filename, options) )
_set_run_configurations(configurations)
QDialog.accept(self) | python | def accept(self):
"""Reimplement Qt method"""
configurations = []
for index in range(self.stack.count()):
filename = to_text_string(self.combo.itemText(index))
runconfigoptions = self.stack.widget(index)
if index == self.stack.currentIndex() and\
not runconfigoptions.is_valid():
return
options = runconfigoptions.get()
configurations.append( (filename, options) )
_set_run_configurations(configurations)
QDialog.accept(self) | [
"def",
"accept",
"(",
"self",
")",
":",
"configurations",
"=",
"[",
"]",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"stack",
".",
"count",
"(",
")",
")",
":",
"filename",
"=",
"to_text_string",
"(",
"self",
".",
"combo",
".",
"itemText",
"(",
"index",
")",
")",
"runconfigoptions",
"=",
"self",
".",
"stack",
".",
"widget",
"(",
"index",
")",
"if",
"index",
"==",
"self",
".",
"stack",
".",
"currentIndex",
"(",
")",
"and",
"not",
"runconfigoptions",
".",
"is_valid",
"(",
")",
":",
"return",
"options",
"=",
"runconfigoptions",
".",
"get",
"(",
")",
"configurations",
".",
"append",
"(",
"(",
"filename",
",",
"options",
")",
")",
"_set_run_configurations",
"(",
"configurations",
")",
"QDialog",
".",
"accept",
"(",
"self",
")"
] | Reimplement Qt method | [
"Reimplement",
"Qt",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/runconfig.py#L457-L469 | train |
spyder-ide/spyder | spyder/plugins/editor/panels/linenumber.py | LineNumberArea.paintEvent | def paintEvent(self, event):
"""Override Qt method.
Painting line number area
"""
painter = QPainter(self)
painter.fillRect(event.rect(), self.editor.sideareas_color)
# This is needed to make that the font size of line numbers
# be the same as the text one when zooming
# See Issue 2296 and 4811
font = self.editor.font()
font_height = self.editor.fontMetrics().height()
active_block = self.editor.textCursor().block()
active_line_number = active_block.blockNumber() + 1
def draw_pixmap(ytop, pixmap):
if not QT55_VERSION:
pixmap_height = pixmap.height()
else:
# scale pixmap height to device independent pixels
pixmap_height = pixmap.height() / pixmap.devicePixelRatio()
painter.drawPixmap(0, ytop + (font_height-pixmap_height) / 2,
pixmap)
for top, line_number, block in self.editor.visible_blocks:
if self._margin:
if line_number == active_line_number:
font.setWeight(font.Bold)
painter.setFont(font)
painter.setPen(self.editor.normal_color)
else:
font.setWeight(font.Normal)
painter.setFont(font)
painter.setPen(self.linenumbers_color)
painter.drawText(0, top, self.width(),
font_height,
Qt.AlignRight | Qt.AlignBottom,
to_text_string(line_number))
data = block.userData()
if self._markers_margin and data:
if data.code_analysis:
for source, code, severity, message in data.code_analysis:
error = severity == DiagnosticSeverity.ERROR
if error:
break
if error:
draw_pixmap(top, self.error_pixmap)
else:
draw_pixmap(top, self.warning_pixmap)
if data.todo:
draw_pixmap(top, self.todo_pixmap) | python | def paintEvent(self, event):
"""Override Qt method.
Painting line number area
"""
painter = QPainter(self)
painter.fillRect(event.rect(), self.editor.sideareas_color)
# This is needed to make that the font size of line numbers
# be the same as the text one when zooming
# See Issue 2296 and 4811
font = self.editor.font()
font_height = self.editor.fontMetrics().height()
active_block = self.editor.textCursor().block()
active_line_number = active_block.blockNumber() + 1
def draw_pixmap(ytop, pixmap):
if not QT55_VERSION:
pixmap_height = pixmap.height()
else:
# scale pixmap height to device independent pixels
pixmap_height = pixmap.height() / pixmap.devicePixelRatio()
painter.drawPixmap(0, ytop + (font_height-pixmap_height) / 2,
pixmap)
for top, line_number, block in self.editor.visible_blocks:
if self._margin:
if line_number == active_line_number:
font.setWeight(font.Bold)
painter.setFont(font)
painter.setPen(self.editor.normal_color)
else:
font.setWeight(font.Normal)
painter.setFont(font)
painter.setPen(self.linenumbers_color)
painter.drawText(0, top, self.width(),
font_height,
Qt.AlignRight | Qt.AlignBottom,
to_text_string(line_number))
data = block.userData()
if self._markers_margin and data:
if data.code_analysis:
for source, code, severity, message in data.code_analysis:
error = severity == DiagnosticSeverity.ERROR
if error:
break
if error:
draw_pixmap(top, self.error_pixmap)
else:
draw_pixmap(top, self.warning_pixmap)
if data.todo:
draw_pixmap(top, self.todo_pixmap) | [
"def",
"paintEvent",
"(",
"self",
",",
"event",
")",
":",
"painter",
"=",
"QPainter",
"(",
"self",
")",
"painter",
".",
"fillRect",
"(",
"event",
".",
"rect",
"(",
")",
",",
"self",
".",
"editor",
".",
"sideareas_color",
")",
"# This is needed to make that the font size of line numbers",
"# be the same as the text one when zooming",
"# See Issue 2296 and 4811",
"font",
"=",
"self",
".",
"editor",
".",
"font",
"(",
")",
"font_height",
"=",
"self",
".",
"editor",
".",
"fontMetrics",
"(",
")",
".",
"height",
"(",
")",
"active_block",
"=",
"self",
".",
"editor",
".",
"textCursor",
"(",
")",
".",
"block",
"(",
")",
"active_line_number",
"=",
"active_block",
".",
"blockNumber",
"(",
")",
"+",
"1",
"def",
"draw_pixmap",
"(",
"ytop",
",",
"pixmap",
")",
":",
"if",
"not",
"QT55_VERSION",
":",
"pixmap_height",
"=",
"pixmap",
".",
"height",
"(",
")",
"else",
":",
"# scale pixmap height to device independent pixels",
"pixmap_height",
"=",
"pixmap",
".",
"height",
"(",
")",
"/",
"pixmap",
".",
"devicePixelRatio",
"(",
")",
"painter",
".",
"drawPixmap",
"(",
"0",
",",
"ytop",
"+",
"(",
"font_height",
"-",
"pixmap_height",
")",
"/",
"2",
",",
"pixmap",
")",
"for",
"top",
",",
"line_number",
",",
"block",
"in",
"self",
".",
"editor",
".",
"visible_blocks",
":",
"if",
"self",
".",
"_margin",
":",
"if",
"line_number",
"==",
"active_line_number",
":",
"font",
".",
"setWeight",
"(",
"font",
".",
"Bold",
")",
"painter",
".",
"setFont",
"(",
"font",
")",
"painter",
".",
"setPen",
"(",
"self",
".",
"editor",
".",
"normal_color",
")",
"else",
":",
"font",
".",
"setWeight",
"(",
"font",
".",
"Normal",
")",
"painter",
".",
"setFont",
"(",
"font",
")",
"painter",
".",
"setPen",
"(",
"self",
".",
"linenumbers_color",
")",
"painter",
".",
"drawText",
"(",
"0",
",",
"top",
",",
"self",
".",
"width",
"(",
")",
",",
"font_height",
",",
"Qt",
".",
"AlignRight",
"|",
"Qt",
".",
"AlignBottom",
",",
"to_text_string",
"(",
"line_number",
")",
")",
"data",
"=",
"block",
".",
"userData",
"(",
")",
"if",
"self",
".",
"_markers_margin",
"and",
"data",
":",
"if",
"data",
".",
"code_analysis",
":",
"for",
"source",
",",
"code",
",",
"severity",
",",
"message",
"in",
"data",
".",
"code_analysis",
":",
"error",
"=",
"severity",
"==",
"DiagnosticSeverity",
".",
"ERROR",
"if",
"error",
":",
"break",
"if",
"error",
":",
"draw_pixmap",
"(",
"top",
",",
"self",
".",
"error_pixmap",
")",
"else",
":",
"draw_pixmap",
"(",
"top",
",",
"self",
".",
"warning_pixmap",
")",
"if",
"data",
".",
"todo",
":",
"draw_pixmap",
"(",
"top",
",",
"self",
".",
"todo_pixmap",
")"
] | Override Qt method.
Painting line number area | [
"Override",
"Qt",
"method",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/linenumber.py#L55-L108 | train |
spyder-ide/spyder | spyder/plugins/editor/panels/linenumber.py | LineNumberArea.mouseMoveEvent | def mouseMoveEvent(self, event):
"""Override Qt method.
Show code analisis, if left button pressed select lines.
"""
line_number = self.editor.get_linenumber_from_mouse_event(event)
block = self.editor.document().findBlockByNumber(line_number-1)
data = block.userData()
# this disables pyflakes messages if there is an active drag/selection
# operation
check = self._released == -1
if data and data.code_analysis and check:
self.editor.show_code_analysis_results(line_number,
data)
else:
self.editor.hide_tooltip()
if event.buttons() == Qt.LeftButton:
self._released = line_number
self.editor.select_lines(self._pressed, self._released) | python | def mouseMoveEvent(self, event):
"""Override Qt method.
Show code analisis, if left button pressed select lines.
"""
line_number = self.editor.get_linenumber_from_mouse_event(event)
block = self.editor.document().findBlockByNumber(line_number-1)
data = block.userData()
# this disables pyflakes messages if there is an active drag/selection
# operation
check = self._released == -1
if data and data.code_analysis and check:
self.editor.show_code_analysis_results(line_number,
data)
else:
self.editor.hide_tooltip()
if event.buttons() == Qt.LeftButton:
self._released = line_number
self.editor.select_lines(self._pressed, self._released) | [
"def",
"mouseMoveEvent",
"(",
"self",
",",
"event",
")",
":",
"line_number",
"=",
"self",
".",
"editor",
".",
"get_linenumber_from_mouse_event",
"(",
"event",
")",
"block",
"=",
"self",
".",
"editor",
".",
"document",
"(",
")",
".",
"findBlockByNumber",
"(",
"line_number",
"-",
"1",
")",
"data",
"=",
"block",
".",
"userData",
"(",
")",
"# this disables pyflakes messages if there is an active drag/selection",
"# operation",
"check",
"=",
"self",
".",
"_released",
"==",
"-",
"1",
"if",
"data",
"and",
"data",
".",
"code_analysis",
"and",
"check",
":",
"self",
".",
"editor",
".",
"show_code_analysis_results",
"(",
"line_number",
",",
"data",
")",
"else",
":",
"self",
".",
"editor",
".",
"hide_tooltip",
"(",
")",
"if",
"event",
".",
"buttons",
"(",
")",
"==",
"Qt",
".",
"LeftButton",
":",
"self",
".",
"_released",
"=",
"line_number",
"self",
".",
"editor",
".",
"select_lines",
"(",
"self",
".",
"_pressed",
",",
"self",
".",
"_released",
")"
] | Override Qt method.
Show code analisis, if left button pressed select lines. | [
"Override",
"Qt",
"method",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/linenumber.py#L114-L134 | train |
spyder-ide/spyder | spyder/plugins/editor/panels/linenumber.py | LineNumberArea.mousePressEvent | def mousePressEvent(self, event):
"""Override Qt method
Select line, and starts selection
"""
line_number = self.editor.get_linenumber_from_mouse_event(event)
self._pressed = line_number
self._released = line_number
self.editor.select_lines(self._pressed,
self._released) | python | def mousePressEvent(self, event):
"""Override Qt method
Select line, and starts selection
"""
line_number = self.editor.get_linenumber_from_mouse_event(event)
self._pressed = line_number
self._released = line_number
self.editor.select_lines(self._pressed,
self._released) | [
"def",
"mousePressEvent",
"(",
"self",
",",
"event",
")",
":",
"line_number",
"=",
"self",
".",
"editor",
".",
"get_linenumber_from_mouse_event",
"(",
"event",
")",
"self",
".",
"_pressed",
"=",
"line_number",
"self",
".",
"_released",
"=",
"line_number",
"self",
".",
"editor",
".",
"select_lines",
"(",
"self",
".",
"_pressed",
",",
"self",
".",
"_released",
")"
] | Override Qt method
Select line, and starts selection | [
"Override",
"Qt",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/linenumber.py#L136-L145 | train |
spyder-ide/spyder | spyder/plugins/editor/panels/linenumber.py | LineNumberArea.compute_width | def compute_width(self):
"""Compute and return line number area width"""
if not self._enabled:
return 0
digits = 1
maxb = max(1, self.editor.blockCount())
while maxb >= 10:
maxb /= 10
digits += 1
if self._margin:
margin = 3+self.editor.fontMetrics().width('9'*digits)
else:
margin = 0
return margin+self.get_markers_margin() | python | def compute_width(self):
"""Compute and return line number area width"""
if not self._enabled:
return 0
digits = 1
maxb = max(1, self.editor.blockCount())
while maxb >= 10:
maxb /= 10
digits += 1
if self._margin:
margin = 3+self.editor.fontMetrics().width('9'*digits)
else:
margin = 0
return margin+self.get_markers_margin() | [
"def",
"compute_width",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_enabled",
":",
"return",
"0",
"digits",
"=",
"1",
"maxb",
"=",
"max",
"(",
"1",
",",
"self",
".",
"editor",
".",
"blockCount",
"(",
")",
")",
"while",
"maxb",
">=",
"10",
":",
"maxb",
"/=",
"10",
"digits",
"+=",
"1",
"if",
"self",
".",
"_margin",
":",
"margin",
"=",
"3",
"+",
"self",
".",
"editor",
".",
"fontMetrics",
"(",
")",
".",
"width",
"(",
"'9'",
"*",
"digits",
")",
"else",
":",
"margin",
"=",
"0",
"return",
"margin",
"+",
"self",
".",
"get_markers_margin",
"(",
")"
] | Compute and return line number area width | [
"Compute",
"and",
"return",
"line",
"number",
"area",
"width"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/linenumber.py#L159-L172 | train |
spyder-ide/spyder | spyder/plugins/editor/panels/linenumber.py | LineNumberArea.setup_margins | def setup_margins(self, linenumbers=True, markers=True):
"""
Setup margin settings
(except font, now set in editor.set_font)
"""
self._margin = linenumbers
self._markers_margin = markers
self.set_enabled(linenumbers or markers) | python | def setup_margins(self, linenumbers=True, markers=True):
"""
Setup margin settings
(except font, now set in editor.set_font)
"""
self._margin = linenumbers
self._markers_margin = markers
self.set_enabled(linenumbers or markers) | [
"def",
"setup_margins",
"(",
"self",
",",
"linenumbers",
"=",
"True",
",",
"markers",
"=",
"True",
")",
":",
"self",
".",
"_margin",
"=",
"linenumbers",
"self",
".",
"_markers_margin",
"=",
"markers",
"self",
".",
"set_enabled",
"(",
"linenumbers",
"or",
"markers",
")"
] | Setup margin settings
(except font, now set in editor.set_font) | [
"Setup",
"margin",
"settings",
"(",
"except",
"font",
"now",
"set",
"in",
"editor",
".",
"set_font",
")"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/linenumber.py#L180-L187 | train |
spyder-ide/spyder | spyder/widgets/fileswitcher.py | process_python_symbol_data | def process_python_symbol_data(oedata):
"""Returns a list with line number, definition name, fold and token."""
symbol_list = []
for key in oedata:
val = oedata[key]
if val and key != 'found_cell_separators':
if val.is_class_or_function():
symbol_list.append((key, val.def_name, val.fold_level,
val.get_token()))
return sorted(symbol_list) | python | def process_python_symbol_data(oedata):
"""Returns a list with line number, definition name, fold and token."""
symbol_list = []
for key in oedata:
val = oedata[key]
if val and key != 'found_cell_separators':
if val.is_class_or_function():
symbol_list.append((key, val.def_name, val.fold_level,
val.get_token()))
return sorted(symbol_list) | [
"def",
"process_python_symbol_data",
"(",
"oedata",
")",
":",
"symbol_list",
"=",
"[",
"]",
"for",
"key",
"in",
"oedata",
":",
"val",
"=",
"oedata",
"[",
"key",
"]",
"if",
"val",
"and",
"key",
"!=",
"'found_cell_separators'",
":",
"if",
"val",
".",
"is_class_or_function",
"(",
")",
":",
"symbol_list",
".",
"append",
"(",
"(",
"key",
",",
"val",
".",
"def_name",
",",
"val",
".",
"fold_level",
",",
"val",
".",
"get_token",
"(",
")",
")",
")",
"return",
"sorted",
"(",
"symbol_list",
")"
] | Returns a list with line number, definition name, fold and token. | [
"Returns",
"a",
"list",
"with",
"line",
"number",
"definition",
"name",
"fold",
"and",
"token",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/fileswitcher.py#L32-L41 | train |
spyder-ide/spyder | spyder/widgets/fileswitcher.py | get_python_symbol_icons | def get_python_symbol_icons(oedata):
"""Return a list of icons for oedata of a python file."""
class_icon = ima.icon('class')
method_icon = ima.icon('method')
function_icon = ima.icon('function')
private_icon = ima.icon('private1')
super_private_icon = ima.icon('private2')
symbols = process_python_symbol_data(oedata)
# line - 1, name, fold level
fold_levels = sorted(list(set([s[2] for s in symbols])))
parents = [None]*len(symbols)
icons = [None]*len(symbols)
indexes = []
parent = None
for level in fold_levels:
for index, item in enumerate(symbols):
line, name, fold_level, token = item
if index in indexes:
continue
if fold_level == level:
indexes.append(index)
parent = item
else:
parents[index] = parent
for index, item in enumerate(symbols):
parent = parents[index]
if item[-1] == 'def':
icons[index] = function_icon
elif item[-1] == 'class':
icons[index] = class_icon
else:
icons[index] = QIcon()
if parent is not None:
if parent[-1] == 'class':
if item[-1] == 'def' and item[1].startswith('__'):
icons[index] = super_private_icon
elif item[-1] == 'def' and item[1].startswith('_'):
icons[index] = private_icon
else:
icons[index] = method_icon
return icons | python | def get_python_symbol_icons(oedata):
"""Return a list of icons for oedata of a python file."""
class_icon = ima.icon('class')
method_icon = ima.icon('method')
function_icon = ima.icon('function')
private_icon = ima.icon('private1')
super_private_icon = ima.icon('private2')
symbols = process_python_symbol_data(oedata)
# line - 1, name, fold level
fold_levels = sorted(list(set([s[2] for s in symbols])))
parents = [None]*len(symbols)
icons = [None]*len(symbols)
indexes = []
parent = None
for level in fold_levels:
for index, item in enumerate(symbols):
line, name, fold_level, token = item
if index in indexes:
continue
if fold_level == level:
indexes.append(index)
parent = item
else:
parents[index] = parent
for index, item in enumerate(symbols):
parent = parents[index]
if item[-1] == 'def':
icons[index] = function_icon
elif item[-1] == 'class':
icons[index] = class_icon
else:
icons[index] = QIcon()
if parent is not None:
if parent[-1] == 'class':
if item[-1] == 'def' and item[1].startswith('__'):
icons[index] = super_private_icon
elif item[-1] == 'def' and item[1].startswith('_'):
icons[index] = private_icon
else:
icons[index] = method_icon
return icons | [
"def",
"get_python_symbol_icons",
"(",
"oedata",
")",
":",
"class_icon",
"=",
"ima",
".",
"icon",
"(",
"'class'",
")",
"method_icon",
"=",
"ima",
".",
"icon",
"(",
"'method'",
")",
"function_icon",
"=",
"ima",
".",
"icon",
"(",
"'function'",
")",
"private_icon",
"=",
"ima",
".",
"icon",
"(",
"'private1'",
")",
"super_private_icon",
"=",
"ima",
".",
"icon",
"(",
"'private2'",
")",
"symbols",
"=",
"process_python_symbol_data",
"(",
"oedata",
")",
"# line - 1, name, fold level",
"fold_levels",
"=",
"sorted",
"(",
"list",
"(",
"set",
"(",
"[",
"s",
"[",
"2",
"]",
"for",
"s",
"in",
"symbols",
"]",
")",
")",
")",
"parents",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"symbols",
")",
"icons",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"symbols",
")",
"indexes",
"=",
"[",
"]",
"parent",
"=",
"None",
"for",
"level",
"in",
"fold_levels",
":",
"for",
"index",
",",
"item",
"in",
"enumerate",
"(",
"symbols",
")",
":",
"line",
",",
"name",
",",
"fold_level",
",",
"token",
"=",
"item",
"if",
"index",
"in",
"indexes",
":",
"continue",
"if",
"fold_level",
"==",
"level",
":",
"indexes",
".",
"append",
"(",
"index",
")",
"parent",
"=",
"item",
"else",
":",
"parents",
"[",
"index",
"]",
"=",
"parent",
"for",
"index",
",",
"item",
"in",
"enumerate",
"(",
"symbols",
")",
":",
"parent",
"=",
"parents",
"[",
"index",
"]",
"if",
"item",
"[",
"-",
"1",
"]",
"==",
"'def'",
":",
"icons",
"[",
"index",
"]",
"=",
"function_icon",
"elif",
"item",
"[",
"-",
"1",
"]",
"==",
"'class'",
":",
"icons",
"[",
"index",
"]",
"=",
"class_icon",
"else",
":",
"icons",
"[",
"index",
"]",
"=",
"QIcon",
"(",
")",
"if",
"parent",
"is",
"not",
"None",
":",
"if",
"parent",
"[",
"-",
"1",
"]",
"==",
"'class'",
":",
"if",
"item",
"[",
"-",
"1",
"]",
"==",
"'def'",
"and",
"item",
"[",
"1",
"]",
".",
"startswith",
"(",
"'__'",
")",
":",
"icons",
"[",
"index",
"]",
"=",
"super_private_icon",
"elif",
"item",
"[",
"-",
"1",
"]",
"==",
"'def'",
"and",
"item",
"[",
"1",
"]",
".",
"startswith",
"(",
"'_'",
")",
":",
"icons",
"[",
"index",
"]",
"=",
"private_icon",
"else",
":",
"icons",
"[",
"index",
"]",
"=",
"method_icon",
"return",
"icons"
] | Return a list of icons for oedata of a python file. | [
"Return",
"a",
"list",
"of",
"icons",
"for",
"oedata",
"of",
"a",
"python",
"file",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/fileswitcher.py#L44-L92 | train |
spyder-ide/spyder | spyder/widgets/fileswitcher.py | shorten_paths | def shorten_paths(path_list, is_unsaved):
"""
Takes a list of paths and tries to "intelligently" shorten them all. The
aim is to make it clear to the user where the paths differ, as that is
likely what they care about. Note that this operates on a list of paths
not on individual paths.
If the path ends in an actual file name, it will be trimmed off.
"""
# TODO: at the end, if the path is too long, should do a more dumb kind of
# shortening, but not completely dumb.
# Convert the path strings to a list of tokens and start building the
# new_path using the drive
path_list = path_list[:] # Make a local copy
new_path_list = []
for ii, (path, is_unsav) in enumerate(zip(path_list, is_unsaved)):
if is_unsav:
new_path_list.append(_('unsaved file'))
path_list[ii] = None
else:
drive, path = osp.splitdrive(osp.dirname(path))
new_path_list.append(drive + osp.sep)
path_list[ii] = [part for part in path.split(osp.sep) if part]
def recurse_level(level_idx):
sep = os.sep
# If toks are all empty we need not have recursed here
if not any(level_idx.values()):
return
# Firstly, find the longest common prefix for all in the level
# s = len of longest common prefix
sample_toks = list(level_idx.values())[0]
if not sample_toks:
s = 0
else:
for s, sample_val in enumerate(sample_toks):
if not all(len(toks) > s and toks[s] == sample_val
for toks in level_idx.values()):
break
# Shorten longest common prefix
if s == 0:
short_form = ''
else:
if s == 1:
short_form = sample_toks[0]
elif s == 2:
short_form = sample_toks[0] + sep + sample_toks[1]
else:
short_form = "..." + sep + sample_toks[s-1]
for idx in level_idx:
new_path_list[idx] += short_form + sep
level_idx[idx] = level_idx[idx][s:]
# Group the remaining bit after the common prefix, shorten, and recurse
while level_idx:
k, group = 0, level_idx # k is length of the group's common prefix
while True:
# Abort if we've gone beyond end of one or more in the group
prospective_group = {idx: toks for idx, toks
in group.items() if len(toks) == k}
if prospective_group:
if k == 0: # we spit out the group with no suffix
group = prospective_group
break
# Only keep going if all n still match on the kth token
_, sample_toks = next(iteritems(group))
prospective_group = {idx: toks for idx, toks
in group.items()
if toks[k] == sample_toks[k]}
if len(prospective_group) == len(group) or k == 0:
group = prospective_group
k += 1
else:
break
_, sample_toks = next(iteritems(group))
if k == 0:
short_form = ''
elif k == 1:
short_form = sample_toks[0]
elif k == 2:
short_form = sample_toks[0] + sep + sample_toks[1]
else: # k > 2
short_form = sample_toks[0] + "..." + sep + sample_toks[k-1]
for idx in group.keys():
new_path_list[idx] += short_form + (sep if k > 0 else '')
del level_idx[idx]
recurse_level({idx: toks[k:] for idx, toks in group.items()})
recurse_level({i: pl for i, pl in enumerate(path_list) if pl})
return [path.rstrip(os.sep) for path in new_path_list] | python | def shorten_paths(path_list, is_unsaved):
"""
Takes a list of paths and tries to "intelligently" shorten them all. The
aim is to make it clear to the user where the paths differ, as that is
likely what they care about. Note that this operates on a list of paths
not on individual paths.
If the path ends in an actual file name, it will be trimmed off.
"""
# TODO: at the end, if the path is too long, should do a more dumb kind of
# shortening, but not completely dumb.
# Convert the path strings to a list of tokens and start building the
# new_path using the drive
path_list = path_list[:] # Make a local copy
new_path_list = []
for ii, (path, is_unsav) in enumerate(zip(path_list, is_unsaved)):
if is_unsav:
new_path_list.append(_('unsaved file'))
path_list[ii] = None
else:
drive, path = osp.splitdrive(osp.dirname(path))
new_path_list.append(drive + osp.sep)
path_list[ii] = [part for part in path.split(osp.sep) if part]
def recurse_level(level_idx):
sep = os.sep
# If toks are all empty we need not have recursed here
if not any(level_idx.values()):
return
# Firstly, find the longest common prefix for all in the level
# s = len of longest common prefix
sample_toks = list(level_idx.values())[0]
if not sample_toks:
s = 0
else:
for s, sample_val in enumerate(sample_toks):
if not all(len(toks) > s and toks[s] == sample_val
for toks in level_idx.values()):
break
# Shorten longest common prefix
if s == 0:
short_form = ''
else:
if s == 1:
short_form = sample_toks[0]
elif s == 2:
short_form = sample_toks[0] + sep + sample_toks[1]
else:
short_form = "..." + sep + sample_toks[s-1]
for idx in level_idx:
new_path_list[idx] += short_form + sep
level_idx[idx] = level_idx[idx][s:]
# Group the remaining bit after the common prefix, shorten, and recurse
while level_idx:
k, group = 0, level_idx # k is length of the group's common prefix
while True:
# Abort if we've gone beyond end of one or more in the group
prospective_group = {idx: toks for idx, toks
in group.items() if len(toks) == k}
if prospective_group:
if k == 0: # we spit out the group with no suffix
group = prospective_group
break
# Only keep going if all n still match on the kth token
_, sample_toks = next(iteritems(group))
prospective_group = {idx: toks for idx, toks
in group.items()
if toks[k] == sample_toks[k]}
if len(prospective_group) == len(group) or k == 0:
group = prospective_group
k += 1
else:
break
_, sample_toks = next(iteritems(group))
if k == 0:
short_form = ''
elif k == 1:
short_form = sample_toks[0]
elif k == 2:
short_form = sample_toks[0] + sep + sample_toks[1]
else: # k > 2
short_form = sample_toks[0] + "..." + sep + sample_toks[k-1]
for idx in group.keys():
new_path_list[idx] += short_form + (sep if k > 0 else '')
del level_idx[idx]
recurse_level({idx: toks[k:] for idx, toks in group.items()})
recurse_level({i: pl for i, pl in enumerate(path_list) if pl})
return [path.rstrip(os.sep) for path in new_path_list] | [
"def",
"shorten_paths",
"(",
"path_list",
",",
"is_unsaved",
")",
":",
"# TODO: at the end, if the path is too long, should do a more dumb kind of",
"# shortening, but not completely dumb.",
"# Convert the path strings to a list of tokens and start building the",
"# new_path using the drive",
"path_list",
"=",
"path_list",
"[",
":",
"]",
"# Make a local copy",
"new_path_list",
"=",
"[",
"]",
"for",
"ii",
",",
"(",
"path",
",",
"is_unsav",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"path_list",
",",
"is_unsaved",
")",
")",
":",
"if",
"is_unsav",
":",
"new_path_list",
".",
"append",
"(",
"_",
"(",
"'unsaved file'",
")",
")",
"path_list",
"[",
"ii",
"]",
"=",
"None",
"else",
":",
"drive",
",",
"path",
"=",
"osp",
".",
"splitdrive",
"(",
"osp",
".",
"dirname",
"(",
"path",
")",
")",
"new_path_list",
".",
"append",
"(",
"drive",
"+",
"osp",
".",
"sep",
")",
"path_list",
"[",
"ii",
"]",
"=",
"[",
"part",
"for",
"part",
"in",
"path",
".",
"split",
"(",
"osp",
".",
"sep",
")",
"if",
"part",
"]",
"def",
"recurse_level",
"(",
"level_idx",
")",
":",
"sep",
"=",
"os",
".",
"sep",
"# If toks are all empty we need not have recursed here",
"if",
"not",
"any",
"(",
"level_idx",
".",
"values",
"(",
")",
")",
":",
"return",
"# Firstly, find the longest common prefix for all in the level",
"# s = len of longest common prefix",
"sample_toks",
"=",
"list",
"(",
"level_idx",
".",
"values",
"(",
")",
")",
"[",
"0",
"]",
"if",
"not",
"sample_toks",
":",
"s",
"=",
"0",
"else",
":",
"for",
"s",
",",
"sample_val",
"in",
"enumerate",
"(",
"sample_toks",
")",
":",
"if",
"not",
"all",
"(",
"len",
"(",
"toks",
")",
">",
"s",
"and",
"toks",
"[",
"s",
"]",
"==",
"sample_val",
"for",
"toks",
"in",
"level_idx",
".",
"values",
"(",
")",
")",
":",
"break",
"# Shorten longest common prefix",
"if",
"s",
"==",
"0",
":",
"short_form",
"=",
"''",
"else",
":",
"if",
"s",
"==",
"1",
":",
"short_form",
"=",
"sample_toks",
"[",
"0",
"]",
"elif",
"s",
"==",
"2",
":",
"short_form",
"=",
"sample_toks",
"[",
"0",
"]",
"+",
"sep",
"+",
"sample_toks",
"[",
"1",
"]",
"else",
":",
"short_form",
"=",
"\"...\"",
"+",
"sep",
"+",
"sample_toks",
"[",
"s",
"-",
"1",
"]",
"for",
"idx",
"in",
"level_idx",
":",
"new_path_list",
"[",
"idx",
"]",
"+=",
"short_form",
"+",
"sep",
"level_idx",
"[",
"idx",
"]",
"=",
"level_idx",
"[",
"idx",
"]",
"[",
"s",
":",
"]",
"# Group the remaining bit after the common prefix, shorten, and recurse",
"while",
"level_idx",
":",
"k",
",",
"group",
"=",
"0",
",",
"level_idx",
"# k is length of the group's common prefix",
"while",
"True",
":",
"# Abort if we've gone beyond end of one or more in the group",
"prospective_group",
"=",
"{",
"idx",
":",
"toks",
"for",
"idx",
",",
"toks",
"in",
"group",
".",
"items",
"(",
")",
"if",
"len",
"(",
"toks",
")",
"==",
"k",
"}",
"if",
"prospective_group",
":",
"if",
"k",
"==",
"0",
":",
"# we spit out the group with no suffix",
"group",
"=",
"prospective_group",
"break",
"# Only keep going if all n still match on the kth token",
"_",
",",
"sample_toks",
"=",
"next",
"(",
"iteritems",
"(",
"group",
")",
")",
"prospective_group",
"=",
"{",
"idx",
":",
"toks",
"for",
"idx",
",",
"toks",
"in",
"group",
".",
"items",
"(",
")",
"if",
"toks",
"[",
"k",
"]",
"==",
"sample_toks",
"[",
"k",
"]",
"}",
"if",
"len",
"(",
"prospective_group",
")",
"==",
"len",
"(",
"group",
")",
"or",
"k",
"==",
"0",
":",
"group",
"=",
"prospective_group",
"k",
"+=",
"1",
"else",
":",
"break",
"_",
",",
"sample_toks",
"=",
"next",
"(",
"iteritems",
"(",
"group",
")",
")",
"if",
"k",
"==",
"0",
":",
"short_form",
"=",
"''",
"elif",
"k",
"==",
"1",
":",
"short_form",
"=",
"sample_toks",
"[",
"0",
"]",
"elif",
"k",
"==",
"2",
":",
"short_form",
"=",
"sample_toks",
"[",
"0",
"]",
"+",
"sep",
"+",
"sample_toks",
"[",
"1",
"]",
"else",
":",
"# k > 2",
"short_form",
"=",
"sample_toks",
"[",
"0",
"]",
"+",
"\"...\"",
"+",
"sep",
"+",
"sample_toks",
"[",
"k",
"-",
"1",
"]",
"for",
"idx",
"in",
"group",
".",
"keys",
"(",
")",
":",
"new_path_list",
"[",
"idx",
"]",
"+=",
"short_form",
"+",
"(",
"sep",
"if",
"k",
">",
"0",
"else",
"''",
")",
"del",
"level_idx",
"[",
"idx",
"]",
"recurse_level",
"(",
"{",
"idx",
":",
"toks",
"[",
"k",
":",
"]",
"for",
"idx",
",",
"toks",
"in",
"group",
".",
"items",
"(",
")",
"}",
")",
"recurse_level",
"(",
"{",
"i",
":",
"pl",
"for",
"i",
",",
"pl",
"in",
"enumerate",
"(",
"path_list",
")",
"if",
"pl",
"}",
")",
"return",
"[",
"path",
".",
"rstrip",
"(",
"os",
".",
"sep",
")",
"for",
"path",
"in",
"new_path_list",
"]"
] | Takes a list of paths and tries to "intelligently" shorten them all. The
aim is to make it clear to the user where the paths differ, as that is
likely what they care about. Note that this operates on a list of paths
not on individual paths.
If the path ends in an actual file name, it will be trimmed off. | [
"Takes",
"a",
"list",
"of",
"paths",
"and",
"tries",
"to",
"intelligently",
"shorten",
"them",
"all",
".",
"The",
"aim",
"is",
"to",
"make",
"it",
"clear",
"to",
"the",
"user",
"where",
"the",
"paths",
"differ",
"as",
"that",
"is",
"likely",
"what",
"they",
"care",
"about",
".",
"Note",
"that",
"this",
"operates",
"on",
"a",
"list",
"of",
"paths",
"not",
"on",
"individual",
"paths",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/fileswitcher.py#L95-L190 | train |
spyder-ide/spyder | spyder/widgets/fileswitcher.py | FilesFilterLine.focusOutEvent | def focusOutEvent(self, event):
"""
Detect when the focus goes out of this widget.
This is used to make the file switcher leave focus on the
last selected file by the user.
"""
self.clicked_outside = True
return super(QLineEdit, self).focusOutEvent(event) | python | def focusOutEvent(self, event):
"""
Detect when the focus goes out of this widget.
This is used to make the file switcher leave focus on the
last selected file by the user.
"""
self.clicked_outside = True
return super(QLineEdit, self).focusOutEvent(event) | [
"def",
"focusOutEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"clicked_outside",
"=",
"True",
"return",
"super",
"(",
"QLineEdit",
",",
"self",
")",
".",
"focusOutEvent",
"(",
"event",
")"
] | Detect when the focus goes out of this widget.
This is used to make the file switcher leave focus on the
last selected file by the user. | [
"Detect",
"when",
"the",
"focus",
"goes",
"out",
"of",
"this",
"widget",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/fileswitcher.py#L218-L226 | train |
spyder-ide/spyder | spyder/widgets/fileswitcher.py | FileSwitcher.save_initial_state | def save_initial_state(self):
"""Save initial cursors and initial active widget."""
paths = self.paths
self.initial_widget = self.get_widget()
self.initial_cursors = {}
for i, editor in enumerate(self.widgets):
if editor is self.initial_widget:
self.initial_path = paths[i]
# This try is needed to make the fileswitcher work with
# plugins that does not have a textCursor.
try:
self.initial_cursors[paths[i]] = editor.textCursor()
except AttributeError:
pass | python | def save_initial_state(self):
"""Save initial cursors and initial active widget."""
paths = self.paths
self.initial_widget = self.get_widget()
self.initial_cursors = {}
for i, editor in enumerate(self.widgets):
if editor is self.initial_widget:
self.initial_path = paths[i]
# This try is needed to make the fileswitcher work with
# plugins that does not have a textCursor.
try:
self.initial_cursors[paths[i]] = editor.textCursor()
except AttributeError:
pass | [
"def",
"save_initial_state",
"(",
"self",
")",
":",
"paths",
"=",
"self",
".",
"paths",
"self",
".",
"initial_widget",
"=",
"self",
".",
"get_widget",
"(",
")",
"self",
".",
"initial_cursors",
"=",
"{",
"}",
"for",
"i",
",",
"editor",
"in",
"enumerate",
"(",
"self",
".",
"widgets",
")",
":",
"if",
"editor",
"is",
"self",
".",
"initial_widget",
":",
"self",
".",
"initial_path",
"=",
"paths",
"[",
"i",
"]",
"# This try is needed to make the fileswitcher work with ",
"# plugins that does not have a textCursor.",
"try",
":",
"self",
".",
"initial_cursors",
"[",
"paths",
"[",
"i",
"]",
"]",
"=",
"editor",
".",
"textCursor",
"(",
")",
"except",
"AttributeError",
":",
"pass"
] | Save initial cursors and initial active widget. | [
"Save",
"initial",
"cursors",
"and",
"initial",
"active",
"widget",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/fileswitcher.py#L380-L394 | train |
spyder-ide/spyder | spyder/widgets/fileswitcher.py | FileSwitcher.restore_initial_state | def restore_initial_state(self):
"""Restores initial cursors and initial active editor."""
self.list.clear()
self.is_visible = False
widgets = self.widgets_by_path
if not self.edit.clicked_outside:
for path in self.initial_cursors:
cursor = self.initial_cursors[path]
if path in widgets:
self.set_editor_cursor(widgets[path], cursor)
if self.initial_widget in self.paths_by_widget:
index = self.paths.index(self.initial_path)
self.sig_goto_file.emit(index) | python | def restore_initial_state(self):
"""Restores initial cursors and initial active editor."""
self.list.clear()
self.is_visible = False
widgets = self.widgets_by_path
if not self.edit.clicked_outside:
for path in self.initial_cursors:
cursor = self.initial_cursors[path]
if path in widgets:
self.set_editor_cursor(widgets[path], cursor)
if self.initial_widget in self.paths_by_widget:
index = self.paths.index(self.initial_path)
self.sig_goto_file.emit(index) | [
"def",
"restore_initial_state",
"(",
"self",
")",
":",
"self",
".",
"list",
".",
"clear",
"(",
")",
"self",
".",
"is_visible",
"=",
"False",
"widgets",
"=",
"self",
".",
"widgets_by_path",
"if",
"not",
"self",
".",
"edit",
".",
"clicked_outside",
":",
"for",
"path",
"in",
"self",
".",
"initial_cursors",
":",
"cursor",
"=",
"self",
".",
"initial_cursors",
"[",
"path",
"]",
"if",
"path",
"in",
"widgets",
":",
"self",
".",
"set_editor_cursor",
"(",
"widgets",
"[",
"path",
"]",
",",
"cursor",
")",
"if",
"self",
".",
"initial_widget",
"in",
"self",
".",
"paths_by_widget",
":",
"index",
"=",
"self",
".",
"paths",
".",
"index",
"(",
"self",
".",
"initial_path",
")",
"self",
".",
"sig_goto_file",
".",
"emit",
"(",
"index",
")"
] | Restores initial cursors and initial active editor. | [
"Restores",
"initial",
"cursors",
"and",
"initial",
"active",
"editor",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/fileswitcher.py#L401-L415 | train |
spyder-ide/spyder | spyder/widgets/fileswitcher.py | FileSwitcher.set_dialog_position | def set_dialog_position(self):
"""Positions the file switcher dialog."""
parent = self.parent()
geo = parent.geometry()
width = self.list.width() # This has been set in setup
left = parent.geometry().width()/2 - width/2
# Note: the +1 pixel on the top makes it look better
if isinstance(parent, QMainWindow):
top = (parent.toolbars_menu.geometry().height() +
parent.menuBar().geometry().height() + 1)
else:
top = self.plugins_tabs[0][0].tabBar().geometry().height() + 1
while parent:
geo = parent.geometry()
top += geo.top()
left += geo.left()
parent = parent.parent()
self.move(left, top) | python | def set_dialog_position(self):
"""Positions the file switcher dialog."""
parent = self.parent()
geo = parent.geometry()
width = self.list.width() # This has been set in setup
left = parent.geometry().width()/2 - width/2
# Note: the +1 pixel on the top makes it look better
if isinstance(parent, QMainWindow):
top = (parent.toolbars_menu.geometry().height() +
parent.menuBar().geometry().height() + 1)
else:
top = self.plugins_tabs[0][0].tabBar().geometry().height() + 1
while parent:
geo = parent.geometry()
top += geo.top()
left += geo.left()
parent = parent.parent()
self.move(left, top) | [
"def",
"set_dialog_position",
"(",
"self",
")",
":",
"parent",
"=",
"self",
".",
"parent",
"(",
")",
"geo",
"=",
"parent",
".",
"geometry",
"(",
")",
"width",
"=",
"self",
".",
"list",
".",
"width",
"(",
")",
"# This has been set in setup",
"left",
"=",
"parent",
".",
"geometry",
"(",
")",
".",
"width",
"(",
")",
"/",
"2",
"-",
"width",
"/",
"2",
"# Note: the +1 pixel on the top makes it look better",
"if",
"isinstance",
"(",
"parent",
",",
"QMainWindow",
")",
":",
"top",
"=",
"(",
"parent",
".",
"toolbars_menu",
".",
"geometry",
"(",
")",
".",
"height",
"(",
")",
"+",
"parent",
".",
"menuBar",
"(",
")",
".",
"geometry",
"(",
")",
".",
"height",
"(",
")",
"+",
"1",
")",
"else",
":",
"top",
"=",
"self",
".",
"plugins_tabs",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"tabBar",
"(",
")",
".",
"geometry",
"(",
")",
".",
"height",
"(",
")",
"+",
"1",
"while",
"parent",
":",
"geo",
"=",
"parent",
".",
"geometry",
"(",
")",
"top",
"+=",
"geo",
".",
"top",
"(",
")",
"left",
"+=",
"geo",
".",
"left",
"(",
")",
"parent",
"=",
"parent",
".",
"parent",
"(",
")",
"self",
".",
"move",
"(",
"left",
",",
"top",
")"
] | Positions the file switcher dialog. | [
"Positions",
"the",
"file",
"switcher",
"dialog",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/fileswitcher.py#L417-L436 | train |
spyder-ide/spyder | spyder/widgets/fileswitcher.py | FileSwitcher.get_item_size | def get_item_size(self, content):
"""
Get the max size (width and height) for the elements of a list of
strings as a QLabel.
"""
strings = []
if content:
for rich_text in content:
label = QLabel(rich_text)
label.setTextFormat(Qt.PlainText)
strings.append(label.text())
fm = label.fontMetrics()
return (max([fm.width(s) * 1.3 for s in strings]), fm.height()) | python | def get_item_size(self, content):
"""
Get the max size (width and height) for the elements of a list of
strings as a QLabel.
"""
strings = []
if content:
for rich_text in content:
label = QLabel(rich_text)
label.setTextFormat(Qt.PlainText)
strings.append(label.text())
fm = label.fontMetrics()
return (max([fm.width(s) * 1.3 for s in strings]), fm.height()) | [
"def",
"get_item_size",
"(",
"self",
",",
"content",
")",
":",
"strings",
"=",
"[",
"]",
"if",
"content",
":",
"for",
"rich_text",
"in",
"content",
":",
"label",
"=",
"QLabel",
"(",
"rich_text",
")",
"label",
".",
"setTextFormat",
"(",
"Qt",
".",
"PlainText",
")",
"strings",
".",
"append",
"(",
"label",
".",
"text",
"(",
")",
")",
"fm",
"=",
"label",
".",
"fontMetrics",
"(",
")",
"return",
"(",
"max",
"(",
"[",
"fm",
".",
"width",
"(",
"s",
")",
"*",
"1.3",
"for",
"s",
"in",
"strings",
"]",
")",
",",
"fm",
".",
"height",
"(",
")",
")"
] | Get the max size (width and height) for the elements of a list of
strings as a QLabel. | [
"Get",
"the",
"max",
"size",
"(",
"width",
"and",
"height",
")",
"for",
"the",
"elements",
"of",
"a",
"list",
"of",
"strings",
"as",
"a",
"QLabel",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/fileswitcher.py#L438-L451 | train |
spyder-ide/spyder | spyder/widgets/fileswitcher.py | FileSwitcher.fix_size | def fix_size(self, content):
"""
Adjusts the width and height of the file switcher
based on the relative size of the parent and content.
"""
# Update size of dialog based on relative size of the parent
if content:
width, height = self.get_item_size(content)
# Width
parent = self.parent()
relative_width = parent.geometry().width() * 0.65
if relative_width > self.MAX_WIDTH:
relative_width = self.MAX_WIDTH
self.list.setMinimumWidth(relative_width)
# Height
if len(content) < 15:
max_entries = len(content)
else:
max_entries = 15
max_height = height * max_entries * 1.7
self.list.setMinimumHeight(max_height)
# Resize
self.list.resize(relative_width, self.list.height()) | python | def fix_size(self, content):
"""
Adjusts the width and height of the file switcher
based on the relative size of the parent and content.
"""
# Update size of dialog based on relative size of the parent
if content:
width, height = self.get_item_size(content)
# Width
parent = self.parent()
relative_width = parent.geometry().width() * 0.65
if relative_width > self.MAX_WIDTH:
relative_width = self.MAX_WIDTH
self.list.setMinimumWidth(relative_width)
# Height
if len(content) < 15:
max_entries = len(content)
else:
max_entries = 15
max_height = height * max_entries * 1.7
self.list.setMinimumHeight(max_height)
# Resize
self.list.resize(relative_width, self.list.height()) | [
"def",
"fix_size",
"(",
"self",
",",
"content",
")",
":",
"# Update size of dialog based on relative size of the parent",
"if",
"content",
":",
"width",
",",
"height",
"=",
"self",
".",
"get_item_size",
"(",
"content",
")",
"# Width",
"parent",
"=",
"self",
".",
"parent",
"(",
")",
"relative_width",
"=",
"parent",
".",
"geometry",
"(",
")",
".",
"width",
"(",
")",
"*",
"0.65",
"if",
"relative_width",
">",
"self",
".",
"MAX_WIDTH",
":",
"relative_width",
"=",
"self",
".",
"MAX_WIDTH",
"self",
".",
"list",
".",
"setMinimumWidth",
"(",
"relative_width",
")",
"# Height",
"if",
"len",
"(",
"content",
")",
"<",
"15",
":",
"max_entries",
"=",
"len",
"(",
"content",
")",
"else",
":",
"max_entries",
"=",
"15",
"max_height",
"=",
"height",
"*",
"max_entries",
"*",
"1.7",
"self",
".",
"list",
".",
"setMinimumHeight",
"(",
"max_height",
")",
"# Resize",
"self",
".",
"list",
".",
"resize",
"(",
"relative_width",
",",
"self",
".",
"list",
".",
"height",
"(",
")",
")"
] | Adjusts the width and height of the file switcher
based on the relative size of the parent and content. | [
"Adjusts",
"the",
"width",
"and",
"height",
"of",
"the",
"file",
"switcher",
"based",
"on",
"the",
"relative",
"size",
"of",
"the",
"parent",
"and",
"content",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/fileswitcher.py#L453-L478 | train |
spyder-ide/spyder | spyder/widgets/fileswitcher.py | FileSwitcher.select_row | def select_row(self, steps):
"""Select row in list widget based on a number of steps with direction.
Steps can be positive (next rows) or negative (previous rows).
"""
row = self.current_row() + steps
if 0 <= row < self.count():
self.set_current_row(row) | python | def select_row(self, steps):
"""Select row in list widget based on a number of steps with direction.
Steps can be positive (next rows) or negative (previous rows).
"""
row = self.current_row() + steps
if 0 <= row < self.count():
self.set_current_row(row) | [
"def",
"select_row",
"(",
"self",
",",
"steps",
")",
":",
"row",
"=",
"self",
".",
"current_row",
"(",
")",
"+",
"steps",
"if",
"0",
"<=",
"row",
"<",
"self",
".",
"count",
"(",
")",
":",
"self",
".",
"set_current_row",
"(",
"row",
")"
] | Select row in list widget based on a number of steps with direction.
Steps can be positive (next rows) or negative (previous rows). | [
"Select",
"row",
"in",
"list",
"widget",
"based",
"on",
"a",
"number",
"of",
"steps",
"with",
"direction",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/fileswitcher.py#L493-L500 | train |
spyder-ide/spyder | spyder/widgets/fileswitcher.py | FileSwitcher.previous_row | def previous_row(self):
"""Select previous row in list widget."""
if self.mode == self.SYMBOL_MODE:
self.select_row(-1)
return
prev_row = self.current_row() - 1
if prev_row >= 0:
title = self.list.item(prev_row).text()
else:
title = ''
if prev_row == 0 and '</b></big><br>' in title:
self.list.scrollToTop()
elif '</b></big><br>' in title:
# Select the next previous row, the one following is a title
self.select_row(-2)
else:
self.select_row(-1) | python | def previous_row(self):
"""Select previous row in list widget."""
if self.mode == self.SYMBOL_MODE:
self.select_row(-1)
return
prev_row = self.current_row() - 1
if prev_row >= 0:
title = self.list.item(prev_row).text()
else:
title = ''
if prev_row == 0 and '</b></big><br>' in title:
self.list.scrollToTop()
elif '</b></big><br>' in title:
# Select the next previous row, the one following is a title
self.select_row(-2)
else:
self.select_row(-1) | [
"def",
"previous_row",
"(",
"self",
")",
":",
"if",
"self",
".",
"mode",
"==",
"self",
".",
"SYMBOL_MODE",
":",
"self",
".",
"select_row",
"(",
"-",
"1",
")",
"return",
"prev_row",
"=",
"self",
".",
"current_row",
"(",
")",
"-",
"1",
"if",
"prev_row",
">=",
"0",
":",
"title",
"=",
"self",
".",
"list",
".",
"item",
"(",
"prev_row",
")",
".",
"text",
"(",
")",
"else",
":",
"title",
"=",
"''",
"if",
"prev_row",
"==",
"0",
"and",
"'</b></big><br>'",
"in",
"title",
":",
"self",
".",
"list",
".",
"scrollToTop",
"(",
")",
"elif",
"'</b></big><br>'",
"in",
"title",
":",
"# Select the next previous row, the one following is a title",
"self",
".",
"select_row",
"(",
"-",
"2",
")",
"else",
":",
"self",
".",
"select_row",
"(",
"-",
"1",
")"
] | Select previous row in list widget. | [
"Select",
"previous",
"row",
"in",
"list",
"widget",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/fileswitcher.py#L502-L518 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.