Move cursor after selected an item in autocompletion list - sublimetext

I implemented a Autocompletion plugin for SublimeText
import sublime_plugin
import sublime
tensorflow_functions = ["tf.AggregationMethod()","tf.Assert()","tf.AttrValue()","tf.AttrValue.ListValue()", etc...]
class TensorflowAutocomplete(sublime_plugin.EventListener):
def __init__(self):
self.tf_completions = [("%s \tTensorflow" % s, s) for s in tensorflow_functions]
def on_query_completions(self, view, prefix, locations):
if view.match_selector(locations[0], 'source.python'):
return self.tf_completions
else:
return[]
Is there any ways I can move the cursor into the parenthesis when the user selected an item in the autocompletion list?
I didn't tried anything because I can't find what I want in the API documentation.

You can just use snippets in the completions, so you change tf.Assert() to tf.Assert($1) (jump out with tab) or tf.Assert($0)
If all parens are empty you can just change your code to:
self.tf_completions = [("%s \tTensorflow" % s, s.replace("()", "($1)") for s in tensorflow_functions]

Related

Kv related question - How to bound an on_press/release function to the viewclass of the recycleview?

I've been working on a project which required me to learn kv.
what I'm trying to do is use recycleview to display a list of people that are a part of a dataset I built and allow easy edit of the dataset.
what I've done is read the documentation and simply use the first example from there (with a slight change, the viewclass being a togglebutton:
[The Example][1]
so as for my question, what I want to do is simply bound an on_press/release function to the viewclass objects, for example what I want to do is to bound a function to all of the toggle buttons which appends the button's text to a list when It's being pressed and removes the name from the list when It's being released.
[1]: https://i.stack.imgur.com/55FlM.png
You can do that by adding the on_press to the data:
class RV(RecycleView):
def __init__(self, **kwargs):
self.list = []
super(RV, self).__init__(**kwargs)
self.data = [{'text': str(x), 'on_press':partial(self.toggle, str(x))} for x in range(100)]
def toggle(self, name):
print('toggle')
if name in self.list:
self.list.remove(name)
else:
self.list.append(name)
print('list is now:', self.list)

Building a QTreeView from strings

I'm trying to build a treeview using what's called a slug: which is a string that's split by hyphens (e.g. Fruit-Apple). Then you just loop through the parts and build the tree if the item doesn't already exist. The first item in the list is always the top most parent. Any suggestions or help would be greatly appreciated. I've having issues trying to append the item to the correct parent.
appendCategorySlug('Fruit-Apple')
appendCategorySlug('Fruit-Orange')
appendCategorySlug('Vegetable-Lettuce')
appendCategorySlug('Fruit-Kiwi')
appendCategorySlug('Vegetable-Carrot')
appendCategorySlug('Vegetable-Carrot-Blackbean')
appendCategorySlug('Vegan-Meat-Blackbean')
I'm not quite sure what I've got going wrong here. The results are kind close, but something is off...
import os, sys
from Qt import QtWidgets, QtGui, QtCore
class CategoryView(QtWidgets.QWidget):
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.resize(250,400)
self.categoryModel = QtGui.QStandardItemModel()
self.categoryModel.setHorizontalHeaderLabels(['Items'])
self.categoryProxyModel = QtCore.QSortFilterProxyModel()
self.categoryProxyModel.setSourceModel(self.categoryModel)
self.categoryProxyModel.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.categoryProxyModel.setSortCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.categoryProxyModel.setDynamicSortFilter(True)
self.uiTreeView = QtWidgets.QTreeView()
self.uiTreeView.setModel(self.categoryProxyModel)
self.uiTreeView.sortByColumn(0, QtCore.Qt.AscendingOrder)
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.uiTreeView)
self.setLayout(self.layout)
def appendCategorySlug(self, slug):
# sourceIndex = self.categoryProxyModel.mapToSource(proxyIndex)
# item = self.categoryModel.itemFromIndex(sourceIndex)
parts = slug.split('-')
parent = self.categoryModel.invisibleRootItem()
for name in parts:
# find part and it doesn't exist append it
items = self.categoryModel.findItems(name, QtCore.Qt.MatchExactly | QtCore.Qt.MatchRecursive, 0)
if len(items) == 1:
print items[0].data()
parent = items[0]
item = QtGui.QStandardItem(name)
parent.appendRow(item)
parent = item
def test_CategoryView():
app = QtWidgets.QApplication(sys.argv)
ex = CategoryView()
ex.appendCategorySlug('Fruit-Apple')
ex.appendCategorySlug('Fruit-Orange')
ex.appendCategorySlug('Vegetable-Lettuce')
ex.appendCategorySlug('Fruit-Kiwi')
ex.appendCategorySlug('Vegetable-Carrot')
ex.appendCategorySlug('Vegetable-Carrot-Blackbean')
ex.appendCategorySlug('Vegan-Meat-Blackbean')
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
pass
test_CategoryView()
There are a few issues here. Searching recursively is error-prone because descendant items could have the same name as one of their ancestors. And it is also inefficient, because at each step we only want to know whether an item with the same name exists at the current level - the ones below it are irrelevant. Also, we should avoid searching if the current parent has no children, and make sure that new parents are only created when they're missing (which is the main problem with your current implementation).
The above issues can be fixed most easily if the model's match function is used instead of findItems, since it allows greater control over how the searching is done:
def appendCategorySlug(self, slug):
parts = slug.split('-')
parent = self.categoryModel.invisibleRootItem()
for name in parts:
if parent.rowCount():
indexes = self.categoryModel.match(
parent.child(0).index(),
QtCore.Qt.DisplayRole, name, 1,
QtCore.Qt.MatchExactly)
if indexes:
parent = self.categoryModel.itemFromIndex(indexes[0])
continue
item = QtGui.QStandardItem(name)
parent.appendRow(item)
parent = item
This algorithm can be implemented even more simply with a simple for-loop, and is perhaps easier to understand:
def appendCategorySlug(self, slug):
parts = slug.split('-')
parent = self.categoryModel.invisibleRootItem()
for name in parts:
for row in range(parent.rowCount()):
child = parent.child(row)
if child.text() == name:
parent = child
break
else:
item = QtGui.QStandardItem(name)
parent.appendRow(item)
parent = item

How can I configure the separator character used for :menuselection:?

I am using Sphinx to generate HTML documentation for my project. Under Inline Markup, the Sphinx documentation discusses :menuselection: for marking a sequence of menu selections using markup like:
:menuselection:`Start --> Programs`
This results in the following HTML:
<span class="menuselection">Start ‣ Programs</span>
i.e. the --> gets converted to the small triangle, which I've determined is U+2023, TRIANGULAR BULLET.
That's all well and good, but I'd like to use a different character instead of the triangle. I have searched the Sphinx package and the theme package (sphinx-bootstrap-theme) somewhat exhaustively for 'menuselection', the triangle character, and a few other things, but haven't turned up anything that does the substitution from --> to ‣ (nothing obvious to me, anyway). But something must be converting it between my .rst source and the html.
My question is: what, specifically is doing the conversion (sphinx core? HTML writer? Theme JS?)?
The conversion is done in the sphinx.roles.menusel_role() function. You can create your own version of this function with a different separator character and register it to be used.
Add the following to your project's conf.py:
from docutils import nodes, utils
from docutils.parsers.rst import roles
from sphinx.roles import _amp_re
def patched_menusel_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
text = utils.unescape(text)
if typ == 'menuselection':
text = text.replace('-->', u'\N{RIGHTWARDS ARROW}') # Here is the patch
spans = _amp_re.split(text)
node = nodes.emphasis(rawtext=rawtext)
for i, span in enumerate(spans):
span = span.replace('&&', '&')
if i == 0:
if len(span) > 0:
textnode = nodes.Text(span)
node += textnode
continue
accel_node = nodes.inline()
letter_node = nodes.Text(span[0])
accel_node += letter_node
accel_node['classes'].append('accelerator')
node += accel_node
textnode = nodes.Text(span[1:])
node += textnode
node['classes'].append(typ)
return [node], []
# Use 'patched_menusel_role' function for processing the 'menuselection' role
roles.register_local_role("menuselection", patched_menusel_role)
When building html, make sure to make clean first so that the updated conf.py is re-parsed with the patch.

Change Progress Bar format to show x.x% in pyQt4

I have been trying to find out which the right syntax for the .setFormat() method of the ProgressBar is, but i cannot find any information about that. %p% just shows the percentage as '34%' but I would like to display fractions as well like this: '33.7%'.
Yes you can simply add self.pbar.setFormat('%.02f%%' % (self.step)) with your code
and if you want to implemnt more precise formating you can re implement QProgressbar like this maybe
class qProress(QtGui.QProgressBar):
"""docstring for qProress"""
def __init__(self,args):
super(qProress, self).__init__(args)
self.valueChanged.connect(self.onValueChanged)
def onValueChanged(self, value):
self.setFormat('%.02f%%' % (self.prefixFloat))
def setValue(self, value):
self.prefixFloat = value
QtGui.QProgressBar.setValue(self, int(value))

How can I edit a TreeModelFilters child model?

I am currently trying to filter a TreeView based on the input of a text box, while still allowing the cells of the TreeView to be editable by the user.
The problem I'm running into is not being able to translate an edit on the TreeView while it's using the TreeModelFilter into an edit on the child model, which is a ListStore.
The signal_connect for the cell (CellRendererText) editing looks like this:
renderer.signal_connect('edited') do |w, s1, s2|
cell_edited(s1, s2, treeview, $status)
end
def cell_edited(path, str, trvu, cell)
if str != ""
iter = #store.get_iter(path)
iter[cell] = str
end
end
Which I will admit to being something I found doing a search for editing TreeViews in Gtk2, as I am a GTK2 and GUI newbie in general.
How do I go about translating the path in the TreeViewFilter to the path in the child model (the ListStore)?
Or put more simply: when a user edits a cell in the table while it's filtered, how do I update the correct non-filtered entry in the list?
First of all, You could write your code like below. Its more concise, and it checks to make sure that the path is valid:
renderer.signal_connect('edited') do |ren, path, text|
next unless iter = #store.get_iter(path)
iter[$status] = text if text != ""
end
You're doing everything correctly for a normal treeview, but when you make a Gtk::TreeModelFilter, you need to convert from the filtered iter to the child's iter using:
Gtk::TreeModelFilter#convert_iter_to_child_iter(filter_iter)
http://ruby-gnome2.sourceforge.jp/ja/hiki.cgi?Gtk%3A%3ATreeModelFilter
So your code should read:
renderer.signal_connect('edited') do |ren, path, text|
next unless iter = #store.get_iter(path)
child_iter = #child_store.convert_iter_to_child(iter)
child_iter[$status] = text if text != ""
end
You should have a look at visualruby.net. I'll be releasing a new version that has a great listview/treeview where you have a much easier (and more rubyish) api. The Gtk stuff gets very complicated.

Resources