Wrap text around a selection in emacs - emacs

I would like to wrap some text around selected text in emacs.
From a selection of the lines:
First item
Second item
I would like to get :
\begin{itemize}
\item First item
\item Second item
\end{itemize}
Using C-c C-e in AucTeX collapses the selection into one line:
\begin{itemize}
\item First item Second item
\end{itemize}
The following snippet in yasnippet:
# -*- mode: snippet -*-
# name : wrap item
# expand-env : ((yas-wrap-around-region nil) (item-string "\item "))
# binding : C-M-z
# --
\begin{itemize}
`(let ((text (yas-selected-text))) (when text (replace-regexp-in-string "^" item-string text)))` $0
\end{itemize}
gives:
\begin{itemize}
item First item
item Second item
\end{itemize}
I tried using (item-string "\\item ") instead, but that gives the error:
[yas] elisp error: Invalid use of '\' in replacement text
I would like to have the snippet work as I can modify it for use in other contexts also.

I just wrote some starter code to solve this problem in a general way.
It's at https://github.com/abo-abo/latex-wrap.
It already works for the specific case that you describe,
and you can help me extend it by posting issues.

Related

emacs make square block comments with right aligned border

I need to write code comments with aligned borders on all four sides due to an externally enforced coding standard.
What's the easiest way, in Emacs, to:
Convert some text into a block comment in this format
Edit the text in a block comment and have Emacs reflow it correctly
Comment format examples:
#*****************************************************************************#
#* This is a block comment. It has right-aligned borders. *#
#* *#
#* It can have separate paragraphs. Text in a long paragraph flows from one *#
#* line to the next with one space of internal padding. *#
#* *#
#* The right hand border is at char 78 *#
#*****************************************************************************#
sub MySub
{
#***************************************************************************#
#* The left hand edge of the comment is aligned with the current code *#
#* block, but the right hand border is still at char 78 *#
#***************************************************************************#
my $var = 3;
}
auto-fill-mode by itself doesn't preserve the right hand border.
The venerable and versatile library "rebox2" can do this.
To install, download https://raw.github.com/lewang/rebox2/master/rebox2.el into your site-lisp dir, and add the following to your .emacs file:
(require 'rebox2)
; The following template defines the specific style required here,
; which does not correspond to any built-in rebox2 style.
;
; "75" means that the style is registered as x75, where "x" depends
; on the current langauge mode. The "?" char is switched for the language
; specific comment char
;
; "999" is the weighting used for recognising this comment style.
; This value works for me.
(rebox-register-template
75
999
'("?*************?"
"?* box123456 *?"
"?*************?"))
(add-hook 'perl-mode-hook (lambda ()
; The "style loop" specifies a list of box styles which rebox will cycle
; through if you refill (M-q) a box repeatedly. Having "11" in this loop
; will allow you to easily "unbox" a comment block, e.g. for "uncomment-region"
(set (make-local-variable 'rebox-style-loop) '(75 11))
; The "min-fill-column" setting ensures that the box is not made narrower
; when the text is short
(set (make-local-variable 'rebox-min-fill-column) 79)
(rebox-mode 1)))
Now:
To convert some text into a block comment in this format, you just select the text and do M-q
To edit the text in a block comment, you can just edit the text directly, and emacs will reflow the box automatically. (You may need to do M-q to request a reflow if emacs doesn't automatically do it.)
M-x customize-variable RET comment-style RET
Then choose "box" from value-menue
You could use yasnippet for inserting and overwrite-mode for editing.
If you want word wrapping, you could also kill rectangle C-x r k,
switch to a temp buffer C-x b,
yank rectangle C-x r y. Edit there to your heart's content. Afterwards,
kill rectangle from the temp buffer and paste into your source.
Here's the block begin/end snippet:
# -*- mode: snippet -*-
# name: block comment
# key: bb
# --
`(concat "#" (make-string (- 80 aya-tab-position) ?*) "#")`
$0
`(concat "#" (make-string (- 80 aya-tab-position) ?*) "#")`
Here's the block line snippet:
# -*- mode: snippet -*-
# name: block comment line
# key: bl
# --
`"#* "`$1${1:$(make-string (- 78 aya-tab-position (length text)) ? )}#
Note that I'm using here the auto-yasnippet package variable aya-tab-position.
To use it in a snippet, you have to expand the snippet with aya-open-line.
You can get both packages from MELPA.
A partial answer to (1) (but I'd love to hear a better one):
Type the comment para as plain text
M-x set-fill-column 76
Place the cursor at the start of the comment para and manually typing in the opening "#* " (note space)
With the cursor at the first letter of the comment para, run M-x set-fill-prefix
Now use M-q to reflow the para
This will sort the word wrapping and put the left hand border in place.
Finally, manually add the top, bottom and right hand borders.
See http://www.gnu.org/software/emacs/manual/html_node/emacs/Fill-Prefix.html
The same approach can be used for some of (2):
Ensure that set-fill-column and set-fill-prefix are correct (see above)
Delete all the right hand border markers
Reflow the para using M-q
Finally, manually add the top, bottom and right hand borders.

How to get literal forward slashes in org-mode?

In text, can I make org-mode ignore forward slashes somehow? Phonetics uses /s/ to denote a certain level of analysis.
I assume that you do not want the text to appear emphasized in the buffer, nor in the output. This is a slightly more complex answer which will achieve that result:
There is a variable defined by Org-mode called org-emphasis-alist which defines the different emphasis modes, what their plain-text syntaxes are, and how they are exported to HTML. You can achieve the result you want by changing the value of this variable before Org-mode has been loaded. That last part is critical so note it well—Org-mode reads the value of org-emphasis-alist when it is loaded and uses that value to generate a regular expression for highlighting ("font-lock") purposes.
Here are two routes to that:
Add the following lines to your .emacs file above the lines that load Org-mode:
(setq org-emphasis-alist
`(("*" bold "<b>" "</b>")
;; ("/" italic "<i>" "</i>")
("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
("=" org-code "<code>" "</code>" verbatim)
("~" org-verbatim "<code>" "</code>" verbatim)
("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
"<del>" "</del>")))
(Notice the commented out line.)
Make the change through Emacs' customization facility:
M-x customize RET
In the search box enter Org Emphasis and click Search.
Click the down arrow next to Org Emphasis Alist to reveal its value.
Find and click the second DEL button—corresponding to the italic list item.
Click the Save for future sessions button at the top of the buffer.
You can use
#+OPTIONS: *:nil
to turn off text-emphasis (bold,italics,underline). This will however only work on export itself, the emphasis will still be visible.
See the manual for other export options.
If you like the standard emphasis functionality of the forward slashes in org-mode, you could also just define a new environment. I put something like the following in the preamble whenever I do phonetics/phonology typesetting:
\newcommand\uRep[1]{$/$\textipa{#1}$/$}

Collapsing the current outline in Emacs org-mode

Say I am in org-mode in a document with the following structure:
* First headline
* Second headline
** Section A
Here is one line
Here is another line
blah, blah
** Section B
Say the cursor is on the line that reads Here is another line. I would like to collapse ** Section A from this location with a keyboard shortcut.
If I press <TAB> it does not collapse ** Section A, as I would need the cursor to be on the stars for this to work.
If I press <Shift-TAB> it collapses all outlines, and not the current one.
Is there any way to cycle through the collapsing of the outline in scope (i.e. the "current outline")?
You can customize the behaviour of the org-cycle command (which is bound to <TAB>) by changing the value of org-cycle-emulate-tab.
To get it to collapse ** Section A when your cursor is on Here is another line add the following line to your .emacs file:
(setq org-cycle-emulate-tab 'white)
The white will allow you to still use <TAB> to indent in empty lines. From org-mode Github:
org-cycle-emulate-tab's value is t
Documentation:
Where should `org-cycle' emulate TAB.
nil Never
white Only in completely white lines
whitestart Only at the beginning of lines, before the first non-white char
t Everywhere except in headlines
exc-hl-bol Everywhere except at the start of a headline
If you don't mind doing this in two steps:
C-c C-p: move the cursor to the previous heading (** Section A in your example)
TAB: fold the section
This method doesn't require any configuration, as long as you get used to it.

Org-mode & Latex export: Any way to put short & long names in sectioning commands? Workarounds?

In standard Latex, one can use something like...
\section[short head]{A longer and more meaningful heading version for the section}
...that gives both a long and short version of a section (or other sectioning command) Thus, allowing for both meaningful sectioning 'titles' and, also, reasonable-looking running heads, TOCs, beamer navigation, etc..
Is there any way to easily achieve this in org mode? (That is without hard coding the sectioning commands in LATEX snippets and, thus, defeating most of the flexibility of changing sectioning levels and repurposing content for beamer, book, and article classes that is my reason for wanting to try orgmode, in first place?)
I tried a "workaround" that did not work. I tried editing the possible latex export classes by adding another class to org-export-latex-classes. This new class changes sectioning commands from \section{%s} to \section%s(EDIT-Fixed typo in slashes). Then I tested using [short]{longer version} in orgmode sections of the file. It worked, except it acted as if the longer version section heading was just "{" and "longer version" was body text! What is up with that?
Since version 8.0 the "org-export-latex-classes" strategy won't work anymore.
Instead, and dare I say much more elegantly, you can set the ALT_TITLE property for the heading.
See http://orgmode.org/manual/Table-of-contents.html.
The following org code:
* The Long Title of Section 1
:PROPERTIES:
:ALT_TITLE: Section 1
:END:
Lorem ipsum.
** The Long Title of Subsection 1-1
:PROPERTIES:
:ALT_TITLE: Subsection 1-1
:END:
Dolor sit amet.
will export to LaTeX as:
[...]
\section[Section 1]{The Long Title of Section 1}
\label{sec-1}
Lorem ipsum.
\subsection[Subsection 1-1]{The Long Title of Subsection 1-1}
\label{sec-1-1}
Dolor sit amet.
You had the right idea with creating your own LaTeX class. The problem lies with the way the templates are filled by the default org-fill-template function. I'm not so great with Lisp, but this this hack will do the trick. Add the following to your .emacs file:
(defun my-section (level text)
(let* ((in "") (out "")
(short-title (if (string-match "\\[.*\\]" text)
(substring text (match-beginning 0)
(match-end 0))
nil)))
(if short-title (setq text (substring text (match-end 0) -1)))
(setq in (org-fill-template
"\\section%S{%s}"
(list (cons "S" (or short-title ""))
(cons "s" (or text ""))))
out (copy-sequence "\\end{section}"))
(cons text (list in out in out))))
(add-to-list 'org-export-latex-classes
'("test"
"\\documentclass{article}"
my-section))
This declares a new latex class by adding a "test" class to the org-export-latex-classes. Here we declare, instead of the normal \\section{%s} stuff a function that takes two parameters --- the current level and the headline text --- and returns a modified cons cell. Some details of this information can be found in org-latex-export.el.
Above the adding to the list is where we actually define the function. This is honestly a hacky version, and I pulled a lot from the org-beamer-sectioning function in org-beamer.el file. This function basically searches the headline for anything that is like a LaTeX short label (i.e. [....]) removes it from the headline and sticks it before the actual section label. Right now this hack will only generate \section statements, no matter how deep the level - if you want something more intelligent like \chapter or \subsection or even unnumbered items, you'll need to do some more Lisping; again, see org-beamer.el for some help.
This bit of org-mode code
#+latex_class: test
* [short 1] this is 1 star
test
** this is a 2 star
test
*** [short 3] this is a 3 star
test
**** what happens
exports to LaTeX as (only relevant sections shown here):
\section[short 1]{ this is 1 star}
\label{sec-1}
test
\section{ this is a 2 star }
\label{sec-1-1}
test
\section[short 3]{ this is a 3 star}
\label{sec-1-1-1}
test
\section{ what happens }
\label{sec-1-1-1-1}
\end{section}
\end{section}
\end{section}
\end{section}
Although it's not a straight org-mode solution, it seems to work and can be a starting point for you. One of these days I might try to write it up properly and get it folded into the org-mode distribution.
It is possible to use the following commands in latex to define the text that should appear in the header to replace section names. But the TOC will still contain the original names.
\chaptermarks
\sectionmarks
\subsectionmarks
...
So, in org-mode you can write
* Long section title
#+LaTeX: \sectionmark{Short title}
edit: it actually doesn't work on the very page where the section name appears. On this one only, the full name is still put in the header.

How can I change a list of plain lines into headlines/TODO items?

If I paste in a block of text composed of separated lines, is there any way to convert each of those lines into either headlines or TODO list items? So:
item
item
item
becomes:
* item
* item
* item
without my having to type [Meta][Return] at the begging of each line?
With a default org-mode configuration, select your lines up to and including the newline at the end of the last line, and do M-x org-toggle-heading. With a prefix argument, it tells org-mode how many levels in it should make the heading (C-u 4 M-x org-toggle-heading)
For example with following command:
M-x query-replace-regex RET ^\(.*\)$ RET * \1 RET
Select your three lines, and while your cursor is on the first column of the fourth line type C-xrt*SPACERET.
This calls the string-rectangle to insert the string *[space] in the vertical selection delimited by the mark and the cursor (i.e., the first column).
C-xrt is a very useful command when editing aligned text.
To convert the line prefix from a Workflowy export (0-n leading spaces followed by a single -):
M-x replace-regexp RET ^ *- RET \,(make-string (length \&) ?*)