Surprisingly sphinx does not offer a role to markup other parameters. Using :obj:`...` creates a random, misleading link and ``...`` renders into a completely different format. Therefore I would like to define a custom role arg which I can use like this:
def is_comment(self, ln: str) -> bool:
'''
Check if :arg:`ln` is a comment.
:param ln: The current line
:return: :const:`True` if :arg:`ln` is a comment
'''
I have already figured out that I can define a custom role by setting rst_prolog in docs/source/conf.py (thanks to this answer)
rst_prolog = '''
.. role:: arg
'''
However, I am lost how to define how this role is supposed to be rendered.
It is easy to inherit from a different role like this:
rst_prolog = '''
.. role:: arg(obj)
'''
Which looks good but has the same problem like using obj directly: It creates wrong links.
My second attempt was to not inherit from another role but specify a class as shown here:
rst_prolog = '''
.. role:: arg
:class: code
'''
but that gives several error messages <rst_prolog>:3: WARNING: Explicit markup ends without a blank line; unexpected unindent. Adding an empty line below does not help.
Is there an easy way to make arg(obj) not be a link?
What am I doing wrong in my second attempt?
EDIT: I am one step further. The problem in my second attempt was that I indented :class: code with a tab. Using spaces instead silences the error message but the code is not highlighted.
Right Click > Inspect in Firefox shows that it is correctly translated to
Check if <span class="code">ln</span> is a comment.
However, the code class is ignored.
If I inspect the True (which is rendered as expected) I see that it is using the code class and that the code class is defined in nature.css as
code {
background-color: #ecf0f3;
color: #222;
/* padding: 1px 2px; */
font-size: 1.1em;
font-family: monospace;
}
How do I use the code class?
Related
In my Rails 4 app, I have a Post model, with :copy and :short_copy as custom attributes (strings).
These attributes contain copies for social medias (Facebook, Twitter, Instagram, Pinterest, etc.).
I display the content of these attributes in my Posts#Show view.
Currently, URLs, #hashtags and #mentions are formatted like the rest of the text.
What I would like to do is to format them in a different fashion, for instance in another color or in bold.
I found the twitter-text gem, which seems to offer such features, but my problem is that I do NOT need — and do NOT want — to have these URLs, #hashtags and #mentions turn into real links.
Indeed, it looks like the twitter-text gem converts URLs, #hashtags and #mentions by default with Twitter::Autolink, as explained in this Stack Overflow question.
That's is not what I am looking for: I just want to update the style of my URLs, #hashtags and #mentions.
How can I do this in Ruby / Rails?
—————
UPDATE:
Following Wes Foster's answer, I implemented the following method in post.rb:
def highlight(string)
string.gsub!(/\S*#(\[[^\]]+\]|\S+)/, '<span class="highlight">\1</span>')
end
Then, I defined the following CSS class:
.highlight {
color: #337ab7;
}
Last, I implemented <%= highlight(post.copy) %> in the desired view.
I now get the following error:
ArgumentError
wrong number of arguments (1 for 2..3)
<td><%= highlight(post.copy) %></td>
What am I doing wrong?
—————
I'm sure each of the following regex patterns could be improved to match even more options, however, the following code works for me:
def highlight_url(str)
str.gsub!(/(https?:\/\/[\S]+)/, '[\1]')
end
def highlight_hashtag(str)
str.gsub!(/\S*#(\[[^\]]+\]|\S+)/, '[#\1]')
end
def highlight_mention(str)
str.gsub!(/\B(\#[a-z0-9_-]+)/i, '[\1]')
end
# Initial string
str = "Myself and #doggirl bought a new car: http://carpictures.com #nomoremoney"
# Pass through each
highlight_mention(str)
highlight_hashtag(str)
highlight_url(str)
puts str # > Myself and [#doggirl] bought a new car: [http://carpictures.com] [#nomoremoney]
In this example, I've wrapped the matches with brackets []. You should use a span tag and style it. Also, you can wrap all three gsub! into a single method for simplicity.
Updated for the asker's add-on error question
It looks like the error is references another method named highlight. Try changing the name of the method from highlight to new_highlight to see if that fixes the new problem.
I've installed the package control "evernote plugin"and view in browser for Sublime3. When I passed the code to evernote, Sublime3 come out an alert as follows.
Evernote complained:
The contents of the note are not valid.
The inline HTML tag 'iostream' is not allowed in Evernote notes.
Retry?
My code is as follows.
#include <iostream>
using namespace std;
int main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
cout << result;
// terminate the program:
return 0;
}
How can I cope with it?
From the sublime-evernote package wiki:
Raw HTML
Take extra care in not using prohibited elements (see here).
Evernote will complain if you use unsupported elements (such as <style>) or unsupported attributes (such as class or id).
If you wish to have the code within a raw html block interpreted as Markdown, specify a markdown="1" attribute for the outermost element:
<div markdown="1">
**Note**:
This is important!
</div>
Source: https://github.com/bordaigorl/sublime-evernote/wiki/Supported-Markdown#raw-html
You have to use
<iostream>
Otherwise it will be interpreted by Markdown as literal HTML (and passed as such to Evernote)
-- update--
You can deal with this problem by reinstall the sublime-evernot.I have tried, and it works well!
clone this repository with
$ git clone --recursive http://github.com/bordaigorl/sublime-evernote.git
in
Windows: %APPDATA%/Roaming/Sublime Text 3/Packages/
OSX: ~/Library/Application Support/Sublime Text 3/Packages/
Linux: ~/.Sublime Text 3/Packages/
https://github.com/timlockridge/SublimeEvernote
sublime-evernote supports Fenced Code Blocks of GitHub as mentioned in its wiki. Quoting the wiki:
Fenced code blocks GitHub style are supported. If a language is specified, pygments is used to highlight the code.
So the correct way to send code is to include it within a block of triple backticks. Quoting the Github help link for fenced code blocks:
You can create fenced code blocks by placing triple backticks ``` before and after the code block. We recommend placing a blank line before and after code blocks to make the raw formatting easier to read.
You can add an optional language identifier to enable syntax highlighting in your fenced code block.
We use Linguist to perform language detection and syntax highlighting. You can find out which keywords are valid in the languages YAML file.
As mentioned above, you can also specify the language after the backticks. For example, for your code, you need to enclose it within:
```c++
```
After enclosing it like this, send it to evernote, and it will appear with proper syntax highlighting.
I'm trying to create a shiny R application. I have some troubles to show euro symbol (and return it) in a radio button. I've tried different version of code:
library(shiny)
runApp(list(
ui= navbarPage(title = 'shoe euro',
radioButtons('var', 'var',
c("INCOME_MGL",
"INCOME_MGL€",
"INCOME_MGL€",
"INCOME_MGL€",
"INCOME_MGL\u20ac")
)),
server=function(input, output, session) {
}))
But the "€" doesn't appear in the web page. Moreover if I select the second option the page returns an error:
"Error in fromJSON(content, handler, default.size, depth, allowComments, :
invalid JSON input"
The problem lies in the class shiny-options-group in the div function. The way this class works appears to convert & to &, preventing the browser from converting € into € because it first changes it into €. Try the following as your ui.R to see it happen.
library(shiny)
options = as.list(c("a","b",HTML("€"),"€"))
shinyUI(fluidPage("test",fluidRow(div(class = "shiny-options-group", options))))
The reason this is happening in your radio button widget is that radioButtons calls generateOptions to create the list of options, and generateOptions returns div(class = "shiny-options-group", options), where options is derived from a manipulation of the choices parameter in the radioButtons function. Here is what you could do:
Get the code for generateOptions here (line 653).
Define the new function generateOptions2 using the exact same code as generateOptions, but change the class parameter at the end.
Get the code for radioButtons by running shiny::radioButtons
Define a new function radioButtons2 and in it replace the generateOptions with generateOptions2.
Set the environment for both new functions to shiny by running something like environment(radioButtons2) <- environment(radioButtons)
Use radioButtons2 in your code instead of radioButtons
The only thing I don't know is what to change the class parameter to in generateOptions2. I don't know much about div classes.
Update
I may have spoken too soon. It looks like the problem goes far deeper. The div function calls tags$div, which calls tag with the first argument set to "div". tag then calls the base function structure with the parameter class = "shiny.tag". structure then calls the primitive function attributes with the parameter class = "shiny.tag". attributes with this parameter then converts & in to &. Therefore, it looks like there is no way to use the div function and get back the euro symbol. I tried replacing div in generateOptions2 with HTML, but that returned a bunch of garbage when I ran the app. You'd have to change the behavior of class = "shiny.tag", but that could have far-reaching unpredictable effects.
Update 2
Figured it out! The trick is to use gsub to replace every & with just & before it is returned from generateOptions2. I put a functioning version of what you posted on github. It requires loading the two functions I mentioned earlier, which (in my repository) are stored in a file called functions.R. The important line in generateOptions2 is gsub(pattern = "&", replacement = "&", div(class = "shiny-options-group", options)).
I need to get an element coordinates(location) using cooresponding page-object method.
Now I'm using the following method to get it:
- myelementname_element.wd.location[0] --> to get X
- myelementname_element.wd.location[1] --> to get Y
But I'm constantly getting the following warning:
DEPRECATION WARNING
You are calling a method named wd at d:/JenkinsWorkspace/jenkins/...
This method does not exist in page-object so it is being passed to the driver.
This feature will be removed in the near future.
Please change your code to call the correct page-object method.
Could you please help me and provide me with corresponding page-object method?
TIA,
ANNA
To use methods supported by watir-webdriver (or selenium-webdriver) elements, but not directly supported by the page-object-gem elements, you need to first get the native element. This is done by calling the element method for the page-object-gem element:
myelementname_element.element
As you can see, you can get the three different gem element classes by doing:
puts page.myelementname_element.class
#=> PageObject::Elements::TextField
puts page.myelementname_element.element.class
#=> Watir::TextField
puts page.myelementname_element.element.wd.class
#=> Selenium::WebDriver::Element
For your specific example, you want to do:
myelementname_element.element.wd.location[0]
myelementname_element.element.wd.location[1]
Is it possible to strike text through in Restructured Text?
Something that for example renders as a <strike> tag when converted to HTML, like:
ReSTructuredText
I checked the docs better, as suggested by Ville Säävuori, and I decided to add the strikethrough like this:
.. role:: strike
:class: strike
In the document, this can be applied as follows:
:strike:`This text is crossed out`
Then in my css file I have an entry:
.strike {
text-decoration: line-through;
}
There is at least three ways of doing it:
.. role:: strike
An example of :strike:`strike through text`.
.. container:: strike
Here the full block of test is striked through.
An undecorated paragraph.
.. class:: strike
This paragraph too is is striked through.
.. admonition:: cancelled
:class: strike
I strike through cancelled text.
After applying rst2html you get:
<p>An example of <span class="strike">strike through text</span>.</p>
<div class="strike container">
Here the full block of test is striked through.</div>
<p>An undecorated paragraph.</p>
<p class="strike">This paragraph too is is striked through.</p>
<div class="strike admonition">
<p class="first admonition-title">cancelled</p>
<p class="last">I strike through cancelled text.</p>
You use them with a style
.strike {
text-decoration: line-through;
}
Here I have taken the admonition directive as example but any
directive that allow the :class: option would do.
As it generates a span the role directive is the only one that
allow to apply your style to a part of a paragraph.
It is redundant to add a class strike to a directive also named
strike, as suggest Gozzilli, because the directive name is the default
class for the html output.
I have checked these syntax both with rest2html and Sphinx. But
while everything works as expected with rest2html the class
directive fail with Sphinx. You have to replace it with
.. rst-class:: strike
This paragraph too is is striked through.
This is only stated in a small
footnote of Sphinx reSt Primer.
According to the official spec there is no directive for strikethrough markup in ReST.
However, if the environment allows for :raw: role or you are able to write your own roles, then you can write a custom plugin for it.
I found the other answers very helpful.
I am not very familiar with Sphinx but I am using it for a project. I too wanted the strike-through ability and have got it working based on the previous answers.
To be clear, I added my strikethrough role as gozzilli mentioned but I saved it inside my conf.py using the rst_prolog variable as discussed in the stack overflow thread here. This means that this role is available to all of your rest files.
I then extended the base html template as described above by creating layout.htmlwithin _templatesinside my source directory. The contents of this file are:
{% extends "!layout.html" %}
{% set css_files = css_files + ["_static/myStyle.css"] %}
This basically includes a custom css file to all your built default html docs.
Finally, in my _static directory within my source directory I included the file myStyle.css which contains:
.strike {
text-decoration: line-through;
}
Which the other answers have already provided.
I am merely writing this answer as it wasn't obvious to me with my limited Sphinx experience which files to edit.
Here's a Python definition of a del role, which works better than the accepted answer if you want to use the role in multiple pages of a Pelican blog or a Sphinx documentation project:
from docutils import nodes
from docutils.parsers.rst import roles
def deleted_role(_role, rawtext, text, _lineno, _inliner, options={}, _content=[]):
roles.set_classes(options)
options.setdefault('classes', []).append("del")
return [nodes.inline(rawtext, text, **options)], []
roles.register_canonical_role('del', deleted_role)
Even better would be to extend the HTML writer to produce a proper <del> tag, like this:
from docutils import nodes
from docutils.parsers.rst import roles
from docutils.writers._html_base import HTMLTranslator
class delnode(nodes.inline):
pass
def visit_delnode(self, node):
self.body.append(self.starttag(node, 'del', ''))
def depart_delnode(self, node):
self.body.append('</del>')
HTMLTranslator.visit_delnode = visit_delnode
HTMLTranslator.depart_delnode = depart_delnode
def deleted_role(_role, rawtext, text, _lineno, _inliner, options={}, _content=[]):
roles.set_classes(options)
return [delnode(rawtext, text, **options)], []
roles.register_canonical_role('del', deleted_role)
You can trivially adjust it to produce an <s>, of course.
Consider the user may have a different background, so here is no one solution that can be suitable for everyone.
1.Only one file
If you only use it only on one file. For example, you published a simple project to PyPI, and you may probably just only one README.rst file. The following may you want.
.. |ss| raw:: html
<strike>
.. |se| raw:: html
</strike>
single line
=============
|ss| abc\ |se|\defg
multiple line
=============
|ss|
line 1
line 2
|se|
789
you can copy and paste it on this website: https://livesphinx.herokuapp.com/
and will see the picture as the following:
It's simple, and you can on directly see the preview on some IDE, for example, PyCharm.
bellow is writing for the users of Sphinx
2.beginner of Sphinx
If you are a beginner of Sphinx. ( I mean maybe you want to use Sphinx to create a document, but Python is not familiar for you ) then try as following:
# conf.py
from pathlib import Path
html_static_path = ['_static', ]
html_css_files = ['css/user.define.css'] # If you want to control which HTML should contain it, you can put it on the HTML, which is very like the answer by #Gregory Kuhn.
with open(Path(__file__).parent / Path('_static/css/user.define.rst'), 'r') as f:
user_define_role = f.read()
rst_prolog = '\n'.join([ user_define_role + '\n',]) # will be included at the beginning of every source file that is read.
# rst_epilog = '\n'.join([ user_define_role + '\n',]) # it's ok if you put it on the end.
user.define.rst
.. role:: strike
user.define.css
.strike {text-decoration: line-through;}
With the rst_prolog, It can auto-add the role on each rst files, but if you change the content( that file, it contains a format that you define), then you must rebuild to make the render is correct.
3.Create roles
You can create an extension to achieve it.
# conf.py
extensions = ['_ext.rst_roles', ]
html_static_path = ['_static', ]
html_css_files = ['css/user.define.css']
# rst_roles.py
from sphinx.application import Sphinx
from docutils.parsers.rst import roles
from docutils import nodes
from docutils.parsers.rst.states import Inliner
def strike_role(role, rawtext, text, lineno, inliner: Inliner, options={}, content=[]):
your_css_strike_name = 'strike'
return nodes.inline(rawtext, text, **dict(classes=[your_css_strike_name])), []
def setup(app: Sphinx):
roles.register_canonical_role('my-strike', strike_role) # usage: :my-strike:`content ...`
The full architecture:
conf.py
_ext/
rst_roles.py
_static/
css/
user.define.css
about the rules, you can reference this link rst-roles
And I vary recommended you to see the docutils.parsers.rst.roles.py .
I wrote an extension for this.
Just pip install sphinxnotes-strike and use:
:strike:`text`
or
:del:`text`
to show strike text.
For more info: https://sphinx-notes.github.io/strike/
Since Docutils 0.17, the HTML5-writer uses <del> if a matching class value is found in inline, literal, or container elements:
.. role:: del
:del:`This text has been deleted`, here is the rest of the paragraph.
.. container:: del
This paragraph has been deleted.