org-mode export to html: links open in new tabs? - org-mode

In html created from org-mode, you can have links open in new tabs if specified as
#+ATTR_HTML: target="_blank"
[[http://cnn.com][CNN]]
which I found here.
However, this doesn't work if [[http://cnn.com][CNN]] is a bulleted item. For instance,
#+ATTR_HTML: target="_blank"
- [[http://cnn.com][CNN]]
Or
- #+ATTR_HTML: target="_blank"
[[http://cnn.com][CNN]]
1) How can I make this work, and 2) can I set this html attribute for all links on a particular page by specifying some form of this option at the top (possibly some argument to #+OPTIONS:)?

I found adding the following works:
#+HTML_HEAD: <base target="_blank">

Short answer: replace string in function org-export-attach-captions-and-attributes:
diff -u -L /home/eab/.emacs.d/el-get/org-mode/lisp/org-exp.el -L \#\<buffer\ el-get/org-exp.el\> /home/eab/.emacs.d/el-get/org-mode/lisp/org-exp.el /tmp/buffer-content-8644Ge2
--- /home/eab/.emacs.d/el-get/org-mode/lisp/org-exp.el
+++ #<buffer el-get/org-exp.el>
## -1935,7 +1935,7 ##
"\\|"
"^[ \t]*\\(|[^-]\\)"
"\\|"
- "^[ \t]*\\[\\[.*\\]\\][ \t]*$"))
+ "^.*\\[\\[.*\\]\\][ \t]*$"))
cap shortn attr label end)
(while (re-search-forward re nil t)
(cond
Long comment about troubles.
Let see source code of function, which parses #+ATTR_BACKEND into text properties.
(defun org-export-attach-captions-and-attributes (target-alist)
"Move #+CAPTION, #+ATTR_BACKEND, and #+LABEL text into text properties.
If the next thing following is a table, add the text properties to the first
table line. If it is a link, add it to the line containing the link."
(goto-char (point-min))
(remove-text-properties (point-min) (point-max)
'(org-caption nil org-attributes nil))
(let ((case-fold-search t)
(re (concat "^[ \t]*#\\+caption:[ \t]+\\(.*\\)"
"\\|"
"^[ \t]*#\\+attr_" (symbol-name org-export-current-backend) ":[ \t]+\\(.*\\)"
"\\|"
"^[ \t]*#\\+label:[ \t]+\\(.*\\)"
"\\|"
"^[ \t]*\\(|[^-]\\)"
"\\|"
"^[ \t]*\\[\\[.*\\]\\][ \t]*$"))
...)))
org-export-current-backend is HTML in this case.
It works for such text
#+ATTR_HTML: target="_blank"
[[http://cnn.com][CNN]]
like this:
1) parse whole line #+ATTR_HTML: target="_blank" by regexp "^[ \t]*#\\+attr_"...
2) parse whole line [[http://cnn.com][CNN]] by regexp "^[ \t]*\\[\\[.*\\]\\][ \t]*$"
3) delete string #+ATTR_HTML: target="_blank" before export to html
4) set property target="_blank" for line [[http://cnn.com][CNN]]
And then org-mode prepares html link for export with this property.
If I replace string "^[ \t]*\\[\\[.*\\]\\][ \t]*$" by "^.*\\[\\[.*\\]\\][ \t]*$" then this patched function works for
#+ATTR_HTML: target="_blank"
- [[http://cnn.com][CNN]]
too. But there is a problem for list
- [[http://cnn.com][CNN]]
- [[http://cnn.com][CNN]]
- some text
If I put ATTR_HTML before each link
#+ATTR_HTML: target="_blank"
- [[http://cnn.com][CNN]]
#+ATTR_HTML: target="_blank"
- [[http://cnn.com][CNN]]
- some text
then I get such output html
* CNN
* CNN
* some text
There is a extra gap in list. So, I can't get output like this
* CNN
* CNN
* some text
only
* CNN
* CNN
* some text
This example demonstrates that org-mode isn't flexible in some cases. I can write lisp function, which sets this html attribute for all links in exported text, and add this feature to #+OPTIONS: or something. But I can't complicate more and more org-mode exporting system in this way, because there are some org-mode syntax limitations - it is simple.
If I have problems with org-publish like these, I think: may be I need something else for make-up except org-mode? )

You can include html into your template if you have couple of links, like this
My projects
- ##html:Example##

Related

Changing color of text in html export from org-mode

It is possible to specify text modifiers such as bold, italics, strikethrough, etc. in a .org file very easily (see link).
Similarly, is there any way to specify text color for just a small section of a .org file such that the text is appropriately colored in the exported html file? I think this would be quite useful while taking highlighted notes fast.
Expected behavior:
This is a sample sentence in normal text color.
<font color="red">
This is a sample sentence in red text color.
</font>
<font color="green">
This is a sample sentence in green text color.
</font>
You can use a macro:
#+MACRO: color ##html:<font color="$1">$2</font>##
* This is a test
This is a sample sentence in normal text color.
{{{color(red,This is a sample sentence in red text color.)}}}
{{{color(green,This is a sample sentence in green text color.)}}}
with the limitation that the second argument cannot contain a comma (and maybe some other characters).
If you are annoyed by macros. Then add the following to your Emacs config,
(org-add-link-type
"color"
(lambda (path)
(message (concat "color "
(progn (add-text-properties
0 (length path)
(list 'face `((t (:foreground ,path))))
path) path))))
(lambda (path desc format)
(cond
((eq format 'html)
(format "<span style=\"color:%s;\">%s</span>" path desc))
((eq format 'latex)
(format "{\\color{%s}%s}" path desc)))))
example in org-mode:
- This is [[color:green][green text]]
- This is [[color:red][red]]
org-faq

Hyperlinks within org-babel source code blocks?

I'd like to have some hyperlinks on the comments of an org-babel source code block. My goal is to export a file as html and be able to track some references, as in the following minimal example:
#+BEGIN_SRC lisp
(princ "Hello World!") ;; [[stackoverflow.com/blabla1234][Got this from SO.]]
#+END_SRC
"Problem" is that links don't get embedded inside of source code blocks (which actually makes a lot of sense).
Is there a way of overriding this behaviour, or an alternative syntax to insert hyperlinks within src blocks?
It is probably not possible now (as of org-mode 8.3.4). The HTML export engine currently doesn't appear to have a mechanism for escaping protected characters. You should submit implement it or submit a feature request! (details)
Some workarounds:
Imitate the output with raw HTML
You can output raw HTML that would otherwise look like the source block and it will render with the link intact:
#+BEGIN_HTML
<pre class="src src-sh">
(princ "Hello World!") ;; Got this from SO.
</pre>
#+END_HTML
Prevent Substitution
If your code is free of greater than and less than symbols you may be able to prevent them from being substituted with
(setq org-html-protect-char-alist '(("&" . "&"))
or if that doesn't work:
(setq htmlize-basic-character-table
;; Map characters in the 0-127 range to either one-character strings
;; or to numeric entities.
(let ((table (make-vector 128 ?\0)))
;; Map characters in the 32-126 range to themselves, others to
;; &#CODE entities;
(dotimes (i 128)
(setf (aref table i) (if (and (>= i 32) (<= i 126))
(char-to-string i)
(format "&#%d;" i))))
;; Set exceptions manually.
(setf
;; Don't escape newline, carriage return, and TAB.
(aref table ?\n) "\n"
(aref table ?\r) "\r"
(aref table ?\t) "\t"
;; Escape &, <, and >.
(aref table ?&) "&"
;;(aref table ?<) "<"
;;(aref table ?>) ">"
;; Not escaping '"' buys us a measurable speedup. It's only
;; necessary to quote it for strings used in attribute values,
;; which htmlize doesn't typically do.
;(aref table ?\") """
)
table))
Note that both are hacks which simply don't escape the HTML tag delimiters themselves. If syntax highlighting applies to any characters it will break the resulting HTML link by inserting <span>'s.

Secret structure in org-mode?

I'm wondering I if there's any functionality in org-mode that can make me able to operate with secret structure, that is: structure that I can see when I'm editing but that is treated as if it wasn't there when exporting. It's mainly importing when I export to ascii.
Example:
I would like this in the .org file:
* Normal heading
** Secret heading 1
Some text 1
** Secret heading 2
Some text 2
** Secret heading 3
Some text 3
To be exported to this:
Normal heading
--------------
Some text 1
Some text 2
Some text 3
What makes the headings secret can be anything like a tag, a property or something else but the secret headings should be foldable.
Edit:
Found this solution (from here) (I'm using org-mode 7.9.3 f. It doesn't work. Headlines with the :ignoreheading: tag are still displayed:
;; backend aware export preprocess hook
(defun sa-org-export-preprocess-hook ()
"My backend aware export preprocess hook."
(save-excursion
(when (eq org-export-current-backend 'latex)
;; ignoreheading tag for bibliographies and appendices
(let* ((tag "ignoreheading"))
(org-map-entries (lambda ()
(delete-region (point-at-bol) (point-at-eol)))
(concat ":" tag ":"))))))
(add-hook 'org-export-preprocess-hook 'sa-org-export-preprocess-hook)
You can use the EXCLUDE_TAGS property and tag certain sections, then export with org-export-exclude-tags. E.g:
#+EXCLUDE_TAGS: noexport
* Public Section
* Secret Section :noexport:
Documentation here.
What you want is addressed here -- and here's the answer (repeated):
Add the following to your .emacs file:
(require 'ox-extra)
(ox-extras-activate '(ignore-headlines))
Use the ignore tag on headlines you'd like to have ignored (while not ignoring their content)
I upgraded to org-mode 8.2.5h and with that this works:
(defun sa-ignore-headline (contents backend info)
"Ignore headlines with tag `ignoreheading'."
(when (and (org-export-derived-backend-p backend 'latex 'html 'ascii)
(string-match "\\`.*ignoreheading.*\n"
(downcase contents)))
(replace-match "" nil nil contents)))
(add-to-list 'org-export-filter-headline-functions 'sa-ignore-headline)
But only if you don't have the options: #+OPTIONS: tags:nil. Guess it's sort of obvious that tags shouldn't be filtered away before a filtering that relies on a certain tag is invoked - but that bugged me for quite some time.
Note: when exporting to ascii the headline underlining will remain without the headline, so you need this setting too:
(setq org-ascii-underline (quote ((ascii) (latin1) (utf-8))))
... to remove headlines all together.
In the linked question about the ignoreheading tag I posted a working, simpler org-export-before-parsing-hook solution for Org 8.2.10 in Emacs 24.1.1.
It is based on the documentation of the org-map-entries function which also states that it wraps it in save-recursion automatically. It is simpler than using concat because the second argument to org-map-entries is an agenda-style match string.
While trying to solve the same problem I found this thread describing how to extend ox-extra.el using a notignore tag. This method does not export any headings unless explicitly tagged notignore. Content of the heading are exported normally.
For most of my documents the notignore approach is more useful than the 'ignore' approach because the majority of headings are 'secret structure' not intended for export.
Presently I have notignore-headlines activated in my init.el file. Can anyone suggest a way to activate this on a per document basis.

Customizing org-mode exports

So, I have been using org-mode for taking my research notes for some time now. I love how I can seamlessly export to both latex (for my papers) and html (for my blog). However, whenever I define macros with \newcommand with #+LATEX_HEADER, these do not show up in the HTML export at all.
I currently handle this by putting the all these commands as
(\newcommand \newcommand etc. etc.)
at the top and then manually removing the "(" and ")" from the tex file.
What I wish I could do was to keep a drawer for these commands and customize html and latex export of org mode to handle this drawer appropriately.
For example, I would add the following in the org file:
:LATEX_MACROS:
\newcommand{\norm}[1]{\lVert{#1}\rVert}
\newcommand{\abs}[1]{\lvert{#1}\rvert}
\newcommand{\half}{\frac{1}{2}}
:END:
And after export, this shows up in the latex file verbatim in header section
and in the html file as
\(
\newcommand{\norm}[1]{\lVert{#1}\rVert}
\newcommand{\abs}[1]{\lvert{#1}\rvert}
\newcommand{\half}{\frac{1}{2}}
\)
Here's a standalone way that works with Org, pdflatex and MathJax at the time of this writing. Make sure the drawers (or at least the LATEXMACROS drawer) are exported (this is the default), then insert near the top of the Org file:
#+OPTIONS: toc:nil
#+DRAWERS: LATEXMACROS ...
:LATEXMACROS:
##html:<div style="display: none">##
\(
\global\def\mymacro{...}
\global\def\mymacrow2args#1#2{...}
...
\)
##html:</div>##
:END:
#+TOC: headlines
This works around the following problems:
We have to use a math environment (here \( ... \)), otherwise Org escapes the TeX syntax.
We cannot use \newcommand, because LaTeX expects them to be in the preamble and MathJaX does not receive it. \newcommand can be used outside of the preamble, but then LaTeX (unlike MathJax) restricts the defined macros to the current math environment. We usually want to use them anywhere in the file.
We cannot use a plain \def because it behaves like \newcommand in terms of scoping (global for MathJax, local for LaTeX). We cannot use \xdef either because MathJax does not know it.
MathJax does not know \global but that won't prevent it from using \def which is global anyway. However, it will print a red warning for each \global in the web page. To get rid of them, we put the math environment inside an undisplayed HTML section.
For MathJax, the macros won't be defined in time for the table of content in its default location. If you use macros in headlines and want a TOC, disable the default with #+OPTIONS: toc:nil and manually add it after the drawer with #+TOC: headlines.
Caveats:
It's not possible to preview latex fragments which use custom macros, because the small TeX file Org build won't include our environment.
Unlike \newcommand, \def silently replaces anything. Also, its syntax is slightly different.
The math environment takes up some vertical space in the output of pdflatex, so we have to put it where that doesn't matter (e.g. before the first headline).
This is probably really version dependent:
Org mode may get better at exporting LaTeX macros (e.g. sending them to MathJax by being smarter when parsing #+LATEX_HEADER, providing a new export option, not escaping \newcommand and putting those into a correctly handled preamble).
MathJax may start accepting \xdef as an alias of \def or ignoring \global (so that the HTML section trick is not needed anymore).
I figured out how to do it myself. Note that this is perhaps not the most elegant solution since it does not place the latex part in the beginning of the latex file (i.e. outside \begin{document}), but it works well enough for me.
(setq org-export-blocks
(cons '(latexmacro org-export-blocks-latexmacro) org-export-blocks))
(defun org-export-blocks-latexmacro (body &rest headers)
(message "exporting latex macros")
(cond
((eq org-export-current-backend 'html) (concat "\\(" body "\\)"))
((eq org-export-current-backend 'latex) body)
(t nil))
)
Alternative solution (not stand-alone), using Org's dynamic blocks.
It has none of the caveats of my original solution (because it generates what Org actually expects for LaTeX or HTML)
It's possible to edit the macros in LaTeX mode (C-c C-')
Callback
Create a file named org-dblock-write:block-macro.el with the following content and add it to Emacs' load path.
(defun org-dblock-write:block-macro (params)
(let ((block-name (or (plist-get params :from) "macros"))
(org-buf (current-buffer)))
(with-temp-buffer
(let ((tmp-buf (current-buffer)))
(set-buffer org-buf)
(save-excursion
(org-babel-goto-named-src-block block-name)
(org-babel-mark-block)
(let ((mblock-begin (region-beginning))
(mblock-end (region-end)))
(set-buffer tmp-buf)
(insert-buffer-substring org-buf mblock-begin mblock-end)))
(set-buffer org-buf)
(insert "#+BEGIN_HTML\n\\(\n")
(insert-buffer-substring tmp-buf)
(insert "\\)\n#+END_HTML\n")
(set-buffer tmp-buf)
(beginning-of-buffer)
(while (re-search-forward "^" nil t)
(replace-match "#+LATEX_HEADER: " nil nil))
(set-buffer org-buf)
(insert-buffer-substring tmp-buf)))))
Org file
Somewhere in the file, create:
A LaTeX source block named "macros" containing your macros
An empty block-macro dynamic block
You can change the name of the source block, and use a :from <custom-name> header argument in the dynamic block. Also, note the :exports none in the source block (usually you don't want to export the LaTeX source).
#+NAME: macros
#+BEGIN_SRC latex :exports none
\newcommand\a{a}
\def\b{b}
\DeclareMathOperator\c{c}
#+END_SRC
#+BEGIN: block-macro
#+END:
Now use C-c C-c with the point on the dynamic block, and it will update to:
#+BEGIN: block-macro
#+BEGIN_HTML
\(
\newcommand\a{a}
\def\b{b}
\DeclareMathOperator\c{c}
\)
#+END_HTML
#+LATEX_HEADER: \newcommand\a{a}
#+LATEX_HEADER: \def\b{b}
#+LATEX_HEADER: \DeclareMathOperator\c{c}
#+LATEX_HEADER:
#+END:
Do this whenever the macros are modified.
I usually have a file with many custom definitions which I reuse for many documents and I want to use it also in my org documents.
The following is a modification of Blout's answer, so please read his answer for more info.
Define macro
(defun org-dblock-write:insert-latex-macros (params)
(let ((text)
(file (plist-get params :file)))
(with-temp-buffer
(insert-file file)
(setq text (split-string (buffer-string) "\n" t)))
(insert (mapconcat (lambda (str) (concat "#+LATEX_HEADER: " str)) text "\n"))
(insert "\n#+BEGIN_HTML\n\\(\n")
(insert (mapconcat 'identity text "\n"))
(insert "\n\\)\n#+END_HTML")))
Usage
File macros.tex:
\newcommand\a{a}
\def\b{b}
\DeclareMathOperator\c{c}
In org file:
#+BEGIN: insert-latex-macros :file "macros.tex"
#+BEGIN_HTML
\(
\newcommand\a{a}
\def\b{b}
\DeclareMathOperator\c{c}
\)
#+END_HTML
#+LATEX_HEADER: \newcommand\a{a}
#+LATEX_HEADER: \def\b{b}
#+LATEX_HEADER: \DeclareMathOperator\c{c}
#+LATEX_HEADER:
#+END:

Basic HTML operations in Emacs

I am working with HTML in Emacs and I am looking for ways to make basics operations as:
convert list of string to HTML-list
one
two
three
to
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
add class to list of elements
<a></a>
<a></a>
<a></a>
to
<a class="one"></a>
<a class="one"></a>
<a class="one"></a>
Is there any extensions which can helps me?
I would do this with a macro:
Move to the first line, and type C-x (
Type the <li>, move to the end </li>, and move to the next line
End and repeat the macro on the remaining lines with C-x e e e e e...
This can easily be generalized to add classes to your <a> tags, and many other things.
You should take a look at zencoding , it's pretty useful. Here's a youtube video showing it with yasnippet, showing some functionality like what you want.
You can add class to list of elements using command M-x replace-string.
Here is an Emacs Lisp function which performs the first task (operates on selected text):
(defun my-make-list (start end)
(interactive "r")
(insert "<ul>\n")
(mapcar '(lambda (line) (insert (concat " <li>" line "</li>\n")))
(split-string (buffer-substring start end) "\n"))
(insert "</ul>")
(delete-region start end))
In the second case I would just use search/replace.