Sunday, April 18, 2010

Convert Text to a (TeXShop) Convenient Label

TeXShop support smart selection of words. If you double-click a text, the whole word is selected. A word in TeXShop consists of the letters 'A/a' to 'Z/z' and underscores. Spaces and hyphen '-' are not interpreted as word but as whitespaces separating words. With BibDesk installed 1), you can press the F5 key within a \ref-command and a list will pop up with all the labels defined in your text.
If you want to quickly select a label in order to copy and paste it manually to a reference (e.g., if you do not use \ref but \autoref instead, the latter is not recognized as reference command by BibDesk), spaces and hyphens (and other punctuation characters) are really annoying as you cannot simply select the label using a double click. Even more annoying: If a label is selected from the proposal list (activiated via F5), only the label characters before the first space or punctuation character are pasted.
For that reason I do not use whitespaces or punctuation characters in labels. Since I do not want to convert all characters myself, I have added a new macro to TeXShop (with a nice shortkey on Cmd+'_') which does the trick:
--Applescript direct

-- Converts spaces and punctuation characters to underscores, useable for labels
-- (C) 2010 Jens von Pilgrim
tell application "TeXShop"
set snippet to the content of the selection of the front document
-- replace commands
set snippet to do shell script ¬
"echo " & the quoted form of snippet & ¬
" | sed -E 's/([[:space:]]|[[:punct:]])/_/g'"
set the selection of the front document to snippet
end tell
Note: In a previous posting, I published a macro creating section headers automatically. I have improved this macro in order to convert the whitespaces and punctuation characters in labels as well.
1)Thank you, Herb Schulz, for reminding me that it's BibDesk which adds the completion list to TeXShop ;-)

Post a Comment