Display styled json in wxpython - python

I have a wxpython application that display json in a TextCtrl. How can I use StyledTextCtrl to display that json properly highlighted?
Is is just a one-liner change or much bigger?
Btw I created jsyntaxpane and IT IS one liner to highlight several languages. Too bad I need wxPython now.

StyledTextCtrl should work for you. But it doesn't have built-in lexer for JSON.
I'd try options in the following order:
pass stc.STC_LEX_AUTOMATIC to StyledTextCtrl's SetLexer() and see if it highlights your json correctly
choose (try one by one) a lexer from built-in lexers that will show your json correctly
try other components, like:
scintilla
editra
...
add your own custom lexer/hightlighter, see
Python wx.stc custom highlighting
Adding a new lexer to scintilla/scite (...and eventually wxPython StyledTextCtrl)
Hope that helps.

I am using Python 3.7 and a lexer for JSON is available. You can use the below.
stc.StyledTextCtrl.__init__(self, parent)
self.SetLexer(stc.STC_LEX_JSON)
Adding to this, there are other properties which might be useful while using StyledTextCtrl for JSON. These properties are used for font sizing and color for various fields that are part of a normal JSON.
self.StyleSetSpec(stc.STC_JSON_DEFAULT, "fore:#000000,face:%(helv)s,size:%(size)d" % fonts)
self.StyleSetSpec(stc.STC_JSON_NUMBER, "fore:#007F7F,size:%(size)d" % fonts)
self.StyleSetSpec(stc.STC_JSON_KEYWORD, "fore:#007F7F,bold,size:%(size)d" % fonts)
self.StyleSetSpec(stc.STC_JSON_STRING, "fore:#7F0000,size:%(size)d" % fonts)
self.StyleSetSpec(stc.STC_JSON_PROPERTYNAME, "fore:#FF5733,size:%(size)d" % fonts)

Related

how to activate a function when a value from a drop down list is selected in python [duplicate]

Using pyqt4 and python 2.6, I am using a qcombobox to provide a list of options. I am having problems with using the selected option. I have been able to use a signal to trigger a method when the option is selected, but the problem is that when the user clicks run, the contents of several of these comboboxes need to be taken into account. So basically I need to get the selected contents of a combobox as a string. Thus far I have only been able use this:
print combobox1.currentText()
to get this:
PyQt4.QtCore.QString(u'Test Selection2')
when all I really want is the 'Test Selection' bit, any ideas?
My combo box was made like this:
combobox1 = qt.QComboBox()
combobox1.addItems(['Test Selection1', 'Test Selection2'])
mainLayout.addWidget(combobox1, 0, 0)
You can convert the QString type to python string by just using the str
function. Assuming you are not using any Unicode characters you can get a python
string as below:
text = str(combobox1.currentText())
If you are using any unicode characters, you can do:
text = unicode(combobox1.currentText())
Getting the Text of ComboBox when the item is changed
self.ui.comboBox.activated.connect(self.pass_Net_Adap)
def pass_Net_Adap(self):
print str(self.ui.comboBox.currentText())
PyQt4 can be forced to use a new API in which QString is automatically converted to and from a Python object:
import sip
sip.setapi('QString', 2)
With this API, QtCore.QString class is no longer available and self.ui.comboBox.currentText() will return a Python string or unicode object.
See Selecting Incompatible APIs from the doc.
If you want the text value of a QString object you can use the __str__ property, like this:
>>> a = QtCore.QString("Happy Happy, Joy Joy!")
>>> a
PyQt4.QtCore.QString(u'Happy Happy, Joy Joy!')
>>> a.__str__()
u'Happy Happy, Joy Joy!'
Hope that helps.

Remove whitespace at top of sphinx pdflatex table of contents

I'm building my python package documentation as HTML and as a latex PDF. The default latex pdf generated (manual class) has a large amount of white space at the top of the table of contents around the text "CONTENTS". I'm not super familiar with latex so when I've look at the generated .tex file I don't see anything that tells me how to remove the whitespace.
I've searched around and couldn't find a latex solution that worked. I also tried setting the :caption: on the toctree to an empty string, but that actually removes the entire TOC and all of my content.
Can anyone help me with this?
The default behaviour of Sphinx for English language is to use Bjarne option to LaTeX package fncychap for chapter headings. But it also loads package titlesec for generally speaking title headings. It does not make a special chapter definition with titlesec, which simply gather the fncychap definition and wraps it in its own hooks. Anyway, making the story short we find
\ttl#save#mkschap #1->\vspace *{50\p# }{\parindent \z# \raggedright \normalfont \interlinepenalty \#M \DOTIS {#1} \vskip 40\p# }
in a log trace and this is the fncychap definition of \#makeschapterhead as preserved by titlesec in its own macro \ttl#save#mkschap.
fncychap is loaded before sphinx.sty, there is no hook,
edit: in fact the 'fncychap' key whose default value is '\\usepackage[Bjarne]{fncychap}' could serve to add some code to redefine the fncychap setting for un-numbered chapter titles. It is not that different from the approach with 'preamble' key below, except that one would not have needed knowing about titlesec intervention in all this.
but since recent Sphinx 1.5 you can use your own Jinja template for latex content. From the look of your contents which is small, I think you have an older version of Sphinx thus I will go for the LaTeX hacking variant something like this:
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
'preamble': r"""
\makeatletter
\def\ttl#save#mkschap #1{\vspace *{10\p# }{\parindent \z# \raggedright
\color{blue}%
\normalfont \interlinepenalty \#M \DOTIS {#1} \vskip 10\p# }}
\makeatother
""",
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
I have added a \color{blue} in there for demonstration purposes only, and modified the \vspace and \vskip commands which is what you need.
The image shows however that there is some extra source of vertical space between Contents and the TOC contents (it remains even with \vskip 0\p# but one can do \vskip -40\p# ...), but I think you are after the top space above Contents and already using only \vspace*{10pt} reduced it a lot (not visible in screenshot below).

Vim syntax highlighting of doxygen style docstrings in Python

I started working with doxygen to generate the documentation of my Python code.
I use doxypy filter to preprocess the Python docstrings.
My goal is to have a nice syntax highlighting of doxygen comments in Python.
When writing my mainpage in a dedicated .dox file, I found that the doxygen comments can be highlighted in vim with the following command:
set syntax=c.doxygen
I tried the same command for Python but I got nothing:
set syntax=python.doxygen
I also made some googling and couldn't find anything interesting
Here is a typical piece of code I'd like to highlight:
class CompilationTab:
"""
The compilation tab of the verif GUI. It contains the layout description
and the functions required to deal with specific behaviors of the tab
"""
def __init__(self, notebook, tab_name):
"""
The class constructor.
#param notebook Notebook: The parent #c Notebook widget
#param tab_name String: The display name of the tab
"""
Does anybody already fixed this issue?
Thank you for help!
If you look into syntax/doxygen.vim you can read in the preamble of the file that currently only
cpp, c, idl, doxygen and php
files are supported.
Since doxygen.vim works a lot with the syn region command i searched for the line that defines the multiline string in syntax/python.vim.
The interesting part of the command that defines this region is
syn region pythonString start=+[uU]\=\z('''\|"""\)+ end="\z1" keepend
Derived from that what is in doxygen.vim and the above line you can add the following lines
"delete the following line if you don't want to have enhanced colors
let g:doxygen_enhanced_color=1
runtime! syntax/doxygen.vim
syn region doxygenComment matchgroup=pythonString start=+[uU]\=\z('''\|"""\)+ end="\z1" contains=doxygenSyncStart,doxygenStart,doxygenTODO keepend fold containedin=pythonString
to ~/.vim/after/syntax/python.vim or execute them by hand.
In addition you may have to customize the colors of the added doxygen highlighting groups by hand. At least i would do so since the resulting look doesn't conform with my taste.
Perhaps the fold argument of the syn command is of special interest for you. If you set foldmethod to syntax you can fold and unfold the multiline comments. That seems to be useful if you could no longer stand the view of those colors and are to lazy to adjust them :)
without doxygen highlighting:
with doxygen highlighting and g:doxygen_enhanced_color == 1:

wxPython - wx.TextCtrl - forcing styles

just a simple question on a wx.TextCtrl element.
i have this text field where on an application, where the user can add a string on it.
i want a text field with a red text on it.
so i've generated this code:
self.hRepositoryTextfield = wx.TextCtrl(self.hPanel)
self.hRepositoryTextfield.SetDefaultStyle(wx.TextAttr(wx.RED))
if the user copy on this text field some string with applied font on it (for example a black coloured string, or a string with a particular font) the red color, anyway the default style is not respected.
i would like the style i decide for my wx.TextCtrl is always forced according my settings.
how can i do?
thank you in advance
axel
The SetForegroundColor might work on one OS and not on another. It depends on the native widget. I would set the TextCtrl's style flag to wx.TE_RICH. Check out the wxPython demo for an example. You can also use the StyledTextCtrl or FancyText of even the HTMLCtrl.
self.hRepositoryTextfield.SetForegroundColor(wx.RED)
that should work ....
i solved the problem in this way:
in the first part of the code it is defined my textfield style...
self.hRepositoryTextfield.SetStyle(0, len(self.hRepositoryTextfield.GetValue()), wx.TextAttr(wx.RED))
self.hRepositoryTextfield.SetFont(self.hFontLabel)
self.hRepositoryTextfield.Bind(wx.EVT_TEXT, self.forceDefaultStyle)
... then i bind every text change to my forcing-style function:
def forceDefaultStyle(self, event):
hEventObject = event.GetEventObject()
hEventObject.SetStyle(0, len(self.hRepositoryTextfield.GetValue()), wx.TextAttr(wx.RED))
hEventObject.SetFont(self.hFontLabel)
and it works!

How do I use genshi.builder to programmatically build an HTML document?

I recently discovered the genshi.builder module. It reminds me of Divmod Nevow's Stan module. How would one use genshi.builder.tag to build an HTML document with a particular doctype? Or is this even a good thing to do? If not, what is the right way?
It's not possible to build an entire page using just genshi.builder.tag -- you would need to perform some surgery on the resulting stream to insert the doctype. Besides, the resulting code would look horrific. The recommended way to use Genshi is to use a separate template file, generate a stream from it, and then render that stream to the output type you want.
genshi.builder.tag is mostly useful for when you need to generate simple markup from within Python, such as when you're building a form or doing some sort of logic-heavy modification of the output.
See documentation for:
Creating and using templates
The XML-based template language
genshi.builder API docs
If you really want to generate a full document using only builder.tag, this (completely untested) code could be a good starting point:
from itertools import chain
from genshi.core import DOCTYPE, Stream
from genshi.output import DocType
from genshi.builder import tag as t
# Build the page using `genshi.builder.tag`
page = t.html (t.head (t.title ("Hello world!")), t.body (t.div ("Body text")))
# Convert the page element into a stream
stream = page.generate ()
# Chain the page stream with a stream containing only an HTML4 doctype declaration
stream = Stream (chain ([(DOCTYPE, DocType.get ('html4'), None)], stream))
# Convert the stream to text using the "html" renderer (could also be xml, xhtml, text, etc)
text = stream.render ('html')
The resulting page will have no whitespace in it -- it'll look normal, but you'll have a hard time reading the source code because it will be entirely on one line. Implementing appropriate filters to add whitespace is left as an exercise to the reader.
Genshi.builder is for "programmatically generating markup streams"[1]. I believe the purpose of it is as a backend for the templating language. You're probably looking for the templating language for generating a whole page.
You can, however do the following:
>>> import genshi.output
>>> genshi.output.DocType('html')
('html', '-//W3C//DTD HTML 4.01//EN', 'http://www.w3.org/TR/html4/strict.dtd')
See other Doctypes here: http://genshi.edgewall.org/wiki/ApiDocs/genshi.output#genshi.output:DocType
[1] genshi.builder.__doc__

Categories

Resources