sponsor Vim development Vim logo Vim Book Ad

Txtfmt (The Vim Highlighter) : "Rich text" highlighting in Vim! (colors, underline, bold, italic, etc...)

 script karma  Rating 1108/614, Downloaded by 11487  Comments, bugs, improvements  Vim wiki

created by
Brett Stahlman
script type
Vim's syntax highlighting is very useful for editing files in a particular programming language such as C or Perl. But what if you are using Vim to edit plain text: e.g., personal journal entries, miscellaneous notes or generic documents? In such cases, Vim's statically defined syntax regions are not very useful. What is really needed is a word processor's ability to apply highlighting to an arbitrary selection of text.

=== OVERVIEW ===
Txtfmt (The Vim Highlighter) is a combination syntax/filetype plugin that allows you to highlight plain text in Vim. The highlighting mechanism uses invisible tokens that are inserted into a Txtfmt buffer with the aid of intuitive mappings provided by the filetype plugin. The plugin supports up to 8 configurable foreground and background colors, and all combinations of the following formatting attributes: bold, underline, italic, standout, reverse and undercurl.
Note: Standout, reverse and undercurl are supported only in certain configurations.
    :help txtfmt-'tokrange'

Nearly everything in this plugin is configurable, with defaults that should work for most users "out of the box". The following is a *partial* list of things that can be configured:
    range of characters used as (hidden) highlighting tokens

The usage examples below are intended only to give you a basic feel for how highlighting with Txtfmt works. You can find much more detailed documentation in the Txtfmt help file. However, the project's README.md on Github currently provides the best way to get up and running quickly with Txtfmt:



!!!! NEW FEATURE (introduced in version 3.0) !!!!
Prior to version 3, Txtfmt provided only what are now known as "manual maps". Manual maps operate at the level of individual tokens: e.g., insert a new highlighting token or replace an existing one at or near the cursor location. Although there is no highlighting task that cannot be accomplished with manual maps, manual mode forced users to think too much about the details of how to accomplish a particular highlighting task, especially when regions with pre-existing highlighting were involved. To simplify the use-case of highlighting existing text, Txtfmt version 3.0 introduced several new types of maps, known collectively as "auto maps". Auto maps fall into 2 basic categories:

1. Visual maps: operate on the visually selected text
2. Operator maps: operate on the text moved over (or included in a "text object")

Documentation Note: Auto maps are not yet fully documented in the Txtfmt help file, but their usage is quite simple (simpler than manual maps), so the usage examples below, coupled with the aforementioned README.md on Github, should be more than sufficient for most users to get started.

The next few sections give usage examples of visual/operator auto maps and manual maps.
Note: If you wish to try the examples now, you will need to install and load the plugin. If you're in a hurry, and are familiar with plugin installation, just drop the bundle of files in the proper location, start Vim and execute the following in an empty buffer:

    :set ft=txtfmt

The "INSTALL DETAILS" section below discusses plugin load in greater detail...

Suppose you wish to make a block of text blue, bold-italic.
Select the text to be highlighted using either mouse or visual mode (e.g., v or V). Then type...
At the resulting Txtfmt prompt, enter the following and hit Enter:
Note: You could also have typed "fbi,cb" (without the `='), which would have *added* bold-italic on top of any existing format attributes.
Mnemonic: The `=' causes any existing format attributes to be overwritten; `+' (the default) adds to, and `-' subtracts from the existing attributes. More on this later...

Suppose you wish to make the word under the cursor red, bold-underline.
In normal mode, with cursor positioned on the word to be highlighted, type...
Vim is now waiting for a motion or text object. Enter the 'inner word' text object specification:
At the resulting Txtfmt prompt, type the following and hit Enter:

Now, suppose you wish to italicize and underline the line containing the word just highlighted and the subsequent 2 lines. In normal mode, with cursor still on the previously-highlighted word, type...
Once again, Vim awaits a motion. Enter the normal mode command to move down 2 lines:
At the resulting Txtfmt prompt, type the following and hit Enter:
Note: Because you used "fui" instead of "f=ui", the word you highlighted in the first step has retained the bold attribute.

Up until now, we've been applying highlighting to all of the text in a range. But it is also possible to target specific sub-regions within the visually-selected or operated-on text. To apply highlighting selectively, append a `/` to the highlighting spec, followed by a "selector pattern expression": e.g.,

    <highlighting-spec> / <selector-pattern>

Selector patterns are essentially boolean expressions combining format/color specs with standard logical operators `&&', `||', `(...)', and `!'.

Example: Suppose after highlighting many words and phrases in your document with f=b,cr,kg (bold, red text on green background), you decide that f=bi,cb (bold-italic, color blue) would have been a better choice. Making the change manually would be tedious; fortunately, selector patterns provide a better way. Simply select a range of lines containing all the text you wish to change and execute...
At the prompt, type the following and hit Enter:
    f+i,cb,k-/ fb && cr && kg
Explanation: The highlighting spec adds italic, changes text color to blue and removes background highlighting altogether, but affects *only* bold red text on a green background.

The syntax of selector patterns is very similar to that of highlighting specs, and is best explained with examples:

        Action: Add underline attribute
        Applies To: Red text

        Action: Make foreground color blue
        Applies To: Text that is red OR has *both* bold *and* italic attributes
        Note: `f&' should be read as "has *all* of the following attributes"

        Action: Add underline attribute AND make background color green
        Applies To: Text that is red AND has *either* bold *or* italic attributes
        Note: `f|' should be read as "has *any* of the following attributes"

        Action: Add italic attribute
        Applies To: Text that is red OR has bold-underline format attributes and no others

    cb kr f-i / fbi & !(cr & k-)
        Action: Set fg color blue, bg color red, and remove italic attribute
        Applies To: Text that is bold-italic AND is NOT red with clear background

** Points to Note **
Tip: Whitespace (ignored by Txtfmt) can be used to make the expressions (both highlighting and selector) easier to read.
Caveat: `f&<attrs>' and `f|<attrs>' are atomic constructs, which do not permit embedded spaces.
Tip: For logical AND and OR, you can drop one of the &'s or |'s.
Rationale: Logical operators | and & are equivalent to || and &&, respectively, but to avoid confusion with the special `f|' and `f&' primitives, some users may prefer the longer forms.
Tip: You can drop the `=' from `f=<attrs>' in a selector expression.
Rationale: `=' is the default operator in selector expressions: i.e., f=ub is equivalent to fub.
Distinction: In the auto-map highlighting spec itself (i.e., the "action" portion of the spec), f=ub and fub mean different things: the former means set to *exactly* underline-bold, whereas fub is a synonym for f+ub, which means add underline-bold on top of existing format attributes.

Note: As mentioned earlier, auto maps are much easier to use than manual maps, but for the sake of completeness, here's a walkthrough showing the use of manual maps...

Suppose you wish to enter some green text...
In Normal mode, you execute one of Txtfmt's "insert-token" mappings (e.g., \i, \I, \a, \A, \o, etc.), and enter the following at the prompt:
Mnemonic: color green
The text you type now is green.

While typing green text, you wish to emphasize a phrase by making it bold-italic. You execute another mapping (e.g., CTRL-\ CTRL-\ in insert mode) and enter "fbi" or "fib" at the prompt.
Mnemonic: format bold italic
The text you type now is green bold-italic.
Note: Inserting the bold-italic token did not affect the text color, because the color and format regions are completely "orthogonal".

Now you wish to switch to a blue background. Execute another mapping (e.g., CTRL-\ CTRL-\ in insert mode) and enter "kb" at the prompt.
Mnemonic: bac_k_ground blue
The text you type now is green bold-italic on a blue background.

At this point, any of the open highlighting regions can be terminated with the corresponding `-' specifier:
    f- (no format attributes)
    c- (no color)
    k- (no background color)

Alternatively, you can enter a non-terminator highlighting spec to change subsequent highlighting without explicitly terminating the preceding region. Inserting "cr", for instance, would switch from green text color to red.

To finish the example, let's terminate the 3 active regions by executing the insert-token mapping (CTRL-\ CTRL-\) one last time and entering the following at the prompt:
Mnemonic: remove color, remove format, remove bac_k_ground color
Now, the text you type should be plain, unhighlighted text. Notice how multiple format/color specifiers can be concatenated in a comma (or dot) separated list, thereby reducing the number of times you have to execute the mapping. You can use this feature to insert both the start and end tokens of a region at once: e.g.,
This specifier would enter a bold-italic token, followed immediately by the "no format" token, leaving the cursor between the two.
Explanation: Txtfmt lets you replace one of the commas with a dot to indicate where the cursor should be positioned after the token insertion.

If you wish to make your highlighted documents available to non-Vim users, simply use the :TOhtml command distributed with Vim to output an HTML version of the Txtfmt buffer.

=== TUTORIAL ===




=== FEEDBACK ===
I would greatly appreciate your feedback on this plugin:
brettstahlman AT gmail DOT com

Also, please rate this plugin!

The following applications represent a few of the many possible uses of the Txtfmt plugin:
    -For taking notes (e.g., notes taken while reviewing large programming projects)
    -As part of a personal journaling system
    -For highlighting .otl files created with Ned Konz' TVO (The Vim Outliner) plugin
    -For highlighting files created with 'Notes' (Hari Krishna Dara's lightweight note management plugin)
    -For highlighting text files created with Yongping Guo's TxtBrowser plugin
    -For beautifying block diagrams created with Dr. Charles Campbell's drawit plugin
    -For sprucing up programming language comments
     Don't laugh! You can embed Txtfmt formatting regions within other syntax regions (e.g., C comments)
     :help txtfmt-'nested'

install details
The Txtfmt distribution comprises the following files:

    Txtfmt help file
    Txtfmt filetype plugin (contains mappings for working with Txtfmt tokens)
    Txtfmt syntax file (defines the Txtfmt syntax highlighting)
    Txtfmt common configuration code (contains configuration script needed by
    both the filetype and syntax plugins)
    (Not needed by most users)
    Bram Moolenaar's patch to fix indent.vim's handling of dot-separated lists
    in 'filetype' option values (required only if your version of Vim is older
    than 7.2 and you plan to "nest" Txtfmt within other filetypes) For details,
        :help txtfmt-combining.

Txtfmt can be installed using any of the standard Vim plugin mechanisms: e.g., Pathogen, Vundle, etc. If you're not using a plugin manager, simply uncompress the Txtfmt distribution somewhere in your 'runtimepath' (e.g., ~/.vim/) and run the following command to prepare the Txtfmt help:

    :helptags ALL

Caveat: Like most plugins, Txtfmt requires both filetype detection and syntax highlighting to be enabled, yet neither is enabled in Vim's default configuration; thus, unless you copied the commands from the example vimrc (or source the example file from your own vimrc), you will probably need to add something like the following to your vimrc:

    syntax on
    filetype plugin on

At this point, if the plugin has been properly installed, you can load the plugin manually by executing the following from the Vim command line:

    :set ft=txtfmt

A better approach, however, is to ensure that Txtfmt is loaded automatically whenever you open certain files. Several approaches are outlined below...

Method 1: Custom filetype.vim

If it doesn't already exist, create your own filetype.vim in the first directory of 'runtimepath' (e.g., ~/.vim) and add an autocommand that associates txtfmt with the desired file extensions.

    " -- filetype.vim --
    augroup filetypedetect
      " Treat files with the following extensions as Txtfmt files: .txt, .tf, .jnl
      au! BufRead,BufNewFile *.txt,*.tf,*.jnl    setfiletype txtfmt
    augroup END

Method 2: Plugin-specific file in ftdetect

If it doesn't already exist, create your own "ftdetect" folder in the first directory of 'runtimepath' (e.g., ~/.vim). In ftdetect, create a file called "txtfmt.vim" containing an autocommand that associates txtfmt with the desired file extensions.

    " -- ftdetect/txtfmt.vim --
    " Treat files with the following extensions as Txtfmt files: .txt, .tf, .jnl
    au! BufRead,BufNewFile *.txt,*.tf,*.jnl    set filetype=txtfmt

Note: When ftdetect is used, there's no need to wrap your autocommands in an `augroup` block, as your script is sourced from within an autocommand group.

    :help new-filetype

Method 3: Modeline

Modelines can be used to set filetype=txtfmt when the files you wish to highlight do not share a common extension. Simply add a line like the following to the beginning or end of a file you wish to highlight:


Note: You'll need to close and reopen the file to cause the line to be processed.

It is quite possible to use Txtfmt highlighting in a file associated with another filetype plugin. For instance, if you're using a plugin that facilitates note-taking or journaling, you may wish to use Txtfmt to highlight the entries. It is even possible to "nest" Txtfmt highlighting regions within syntax regions defined by other plugins, but nesting must be enabled explicitly by setting the `txtfmt-'nested'` option.

    :help txtfmt-combining
    :help txtfmt-nesting

rate this script Life Changing Helpful Unfulfilling 
script versions (upload new version)

Click on the package to download.

package script version date Vim version user release notes
txtfmt_v5.0.tar.gz 5.0 2023-05-07 7.4 Brett Stahlman Version 5.0
** New Feature: "Shortcut Maps"
Customizable visual maps and operators that let you apply your favorite highlighting combinations with fewer keystrokes and less cognitive load.
txtfmt_v4.2.1.tar.gz 4.2.1 2023-04-19 7.4 Brett Stahlman Version 4.2.1
Bugfix: Fixed bug capable of generating error after a highlighting operation on a region beginning at the start of a line.
txtfmt_v4.2.tar.gz 4.2 2023-04-17 7.4 Brett Stahlman Version 4.2
Bugfix: Fixed broken "smart delete" operator.
Enhancement: Added logic that treats backslashes specially when escape=bslash, doubling or halving them as necessary to prevent a highlighting or smart delete operation from changing the number of *displayed* backslashes.
Enhancement: Stopped treating CTRL-C cancellation of a highlighting/delete operation as an error.
txtfmt_v4.1a.tar.gz v4.1a 2020-05-17 7.0 Brett Stahlman Version 4.1 Alpha release:
** !!! Much Faster Syntax !!!: Eliminated redundant group permutations to
achieve a signficant reduction in the number of syntax groups required for
** New Feature(s): "Smart" versions of indent/dedent/retab maps/commands,
which take Txtfmt 'leadingindent' option into account
txtfmt_v4.0a.tar.gz 4.0a 2018-11-26 7.4 Brett Stahlman Version 4.0 Alpha release:
** New Feature: 'leadingindent' option permits suppression of highlighting in whitespace at start of line.
** Syntax Engine Refactor: All syntax now generated dynamically. (Prior to this, certain sections of vimscript were generated offline by an embedded perl script.)
txtfmt_v3.1.tar.gz 3.1 2016-09-03 7.0 Brett Stahlman Bugfix: In "linewise visual" mode only, highlight map (\h) generated error on attempt to restore selection, and smart delete map (\d) failed to delete entire selection (left one too many newlines).
txtfmt_v3.0.tar.gz 3.0 2016-05-14 7.0 Brett Stahlman "Auto Maps" Formal Release:
-Visual/operator maps simplify highlighting: visually select (or move over) region to be highlighted, specify desired change, and let Txtfmt "make it so". (No more fiddling with start/end tokens.)
-Selective highlighting via "selector pattern expressions": e.g., add italic, but only to text that is currently red-bold; change currently red text to yellow; etc...
-Various minor fixes/enhancements.
txtfmt_v3.0beta-2.tar.gz 3.0beta-2 2016-04-28 7.0 Brett Stahlman Added "True Color" support for color terminals in Neovim. (Prior to this, highlighting was invisible in Neovim color terminals when the $NVIM_TUI_ENABLE_TRUE_COLOR env var was used to enable 24-bit "true color".)
txtfmt_v3.0beta-1.tar.gz 3.0beta-1 2016-04-23 7.0 Brett Stahlman "Auto-maps" Beta release:
!!! New Feature !!! - "Selective Highlighting"
Modify highlighting spec with a "selector pattern" that targets only a subset of the selection: e.g.,
    f+u / cr && fbi
...to add underline attribute, but only to text that is red bold-italic already.
txtfmt_v3.0alpha-6.tar.gz 3.0alpha-6 2016-04-17 7.0 Brett Stahlman Bugfix: Automatic line breaking during token insertion breaks auto map highlighting. (Occurs only when 'textwidth' is nonzero, and the tokens inserted by an auto map cause 'textwidth' to be exceeded.)
txtfmt_v3.0alpha-5.tar.gz 3.0alpha-5 2016-04-10 7.0 Brett Stahlman "Auto-maps" alpha release:
Bugfix: Calls to s:Contains_hlable were causing cursor to move backwards spuriously (due to failure to restore cursor pos after temporary move), which broke highlighting in certain scenarios (and could conceivably have been preventing timely exit from Vmap_collect search loop).
Note: This release *may* provide a fix for the Annis Monadjem issue.
txtfmt_v3.0alpha-4.tar.gz 3.0alpha-4 2016-03-27 7.0 Brett Stahlman "Auto-maps" alpha release:
Minor change to logic pertaining to cleanup of unnecessary tokens near end of buffer.
txtfmt_v3.0alpha-3.tar.gz 3.0alpha-3 2016-03-27 7.0 Brett Stahlman "Auto-maps" alpha release:
Bugfix for issue affecting highlighting of regions near end of buffer.
txtfmt_v3.0alpha-2.tar.gz 3.0alpha-2 2016-03-17 7.0 Brett Stahlman Minor bugfixes and UI tweaks to alpha release of "auto maps" feature: e.g., `f-' and `c-' now mean "clear format" and "clear color", respectively.
txtfmt_v3.0alpha.tar.gz 3.0 alpha 2016-01-30 7.0 Brett Stahlman Alpha release of "auto maps" feature: includes both visual and operator-pending maps for highlighting existing regions. UI not yet frozen. User feedback desired.
txtfmt_v24.vba 2.4 2010-09-28 7.0 Brett Stahlman Version 2.4 repackaged in Vimball format
See original version 2.4 release notes for additional details
txtfmt_v2.4.tar.gz 2.4 2010-09-18 6.0 Brett Stahlman *** TOKENS NOW COMPLETELY CONCEALED (with Vim 7.3) ***
-Makes using the "conceal" feature the default for Vim versions >= 7.3.
Important Note: If you have legacy files for which you do not wish to use "conceal", read the following:
:help txtfmt-conceal-history
:help txtfmt-viewing-old-files-without-conceal
-Provides more accurate definition of "turquoise" color in default color map: LightGreen changed to DarkCyan.
-Fixed handling of bad modeline options.
txtfmt_v2.3.tar.gz 2.3 2010-06-08 6.0 Brett Stahlman Prevents E21 in several scenarios: e.g.,
-Txtfmt used within a Vim help buffer (e.g., ft=help.txtfmt)
-Txtfmt loaded when 'nomodifiable' is set globally.
txtfmt_v2.2.tar.gz 2.2 2010-02-16 6.0 Brett Stahlman -Loading Txtfmt no longer makes all windows the same size when 'equalalways' is set
-Fixed several anomalies caused by Txtfmt load when 'winfixheight' is set:
-"test page" displayed in 2 windows
-chain of errors when initial window contains changes
-Txtfmt buffer loaded in 2 windows
-Added logic that attempts to make "test page" at least 20 lines high
txtfmt_v2.1.tar.gz 2.1 2009-11-26 6.0 Brett Stahlman Minor fix in Define_syntax to ensure that 'containedin' clause does not refer to nonexistent "inner escape" region when there are no active foreground colors.
txtfmt_v2.0.tar.gz 2.0 2009-09-29 6.0 Brett Stahlman !!!!! Formal Release of Version 2.0 (bg color and 'conceal' patch support) !!!!!
Incorporated perl script used to generate large portion of Define_syntax into syntax/txtfmt.vim, and provided Vim command line used to update the auto-generated script block.
txtfmt_v2.0b.tar.gz 2.0b 2009-09-16 6.0 Brett Stahlman !!!!! Version 2.0 beta release (background colors and 'conceal' patch) !!!!!
Code cleanup (removed unused functions, streamlined color name lookup)
txtfmt_v2.0a.tar.gz 2.0a 2009-08-25 6.0 Brett Stahlman !!!!! MAJOR RELEASE !!!!!
-Added support for background colors!!!
-Added support for Vince Negri's 'conceal' patch, which can make Txtfmt tokens consume zero screen width
txtfmt_v1.5.tar.gz 1.5 2009-03-05 6.0 Brett Stahlman -Removed (obsolete) multibyte syntax patch from distribution
-Updated help to reflect fact that several issues affecting Txtfmt have been eliminated in Vim 7.2
txtfmt_v1.4.tar.gz 1.4 2009-02-23 6.0 Brett Stahlman -Fixed several of the operator-pending "jump to token" maps
-Added more robust mechanism for hiding tokens, eliminating dependence upon "Ignore" group whenever possible
-Added help section "Color terminal pitfalls" containing...
    -Description of "Ignore" group issue and recommended workarounds
    -Description of gnome-terminal issue and recommended workarounds
-Fixed broken link in helpfile
-Minor cosmetic fix on test page
txtfmt_v1.3.tar.gz 1.3 2008-12-16 6.0 Brett Stahlman Fixed "bold" attribute display in color terminals. Prior to this fix, the default Txtfmt colors were unaffected by the bold attribute. With this fix, the bold attribute will cause dark colors to appear brighter (lighter) in a color terminal.
txtfmt_v1.2.tar.gz 1.2 2008-08-17 6.0 Brett Stahlman Added missing help tags for a number of options.
txtfmt_v1.1.tar.gz 1.1 2008-06-04 6.0 Brett Stahlman NOW WORKS WITH MULTIBYTE ENCODINGS!!! (no patch required)
-Added logic to determine whether the running Vim treats syntax match offsets as byte or character offsets. (This logic renders the multi-byte syntax patch obsolete.)
-Help file additions: added instructions for using Txtfmt with TVO (:help txtfmt-nesting-tvo-example), and outlined a strategy for achieving "colorscheme independence" by defining colors according to default highlighting groups (:help txtfmt-colorschemes)
txtfmt_v1.0e.tar.gz 1.0e 2008-05-11 6.0 Brett Stahlman -Fixed bug that prevented buf-local color definitions from being used.
-Added to the help file a description of a possible strategy for making txtfmt
color definitions dependent upon current colorscheme.
-Fixed bug that sometimes prevented txtfmt option changes from taking effect
when a txtfmt buffer was re-edited.
-Fixed bug that prevented insert-token mappings from working in Replace mode.
txtfmt_v1.0d.tar.gz 1.0d 2008-04-28 6.0 Brett Stahlman Applied the <silent> attribute to prevent the jump-to-token
mappings from echoing to the command line
txtfmt_v1.0c.tar.gz 1.0c 2008-04-19 6.0 Brett Stahlman -Added buffer-local mapping (\ga) and command (:GetTokInfo) for obtaining
information about a specific character/token in a txtfmt buffer.
(Functionality is analogous to that of Vim's ga normal mode command.)
-Fixed documentation and reporting bug that caused a 0-based color index to be
displayed instead of the 1-based index specified in the help file. (Affected
:MakeTestPage, \ga, :GetTokInfo and documentation)
txtfmt_v1.0b.tar.gz 1.0b 2008-04-10 6.0 Brett Stahlman Fixed bug in ftplugin that caused sample "user-maps" (defined for testing) to override any user-defined ones.
txtfmt_v1.0a.tar.gz 1.0a 2008-04-06 6.0 Brett Stahlman Initial upload
ip used for rating:

If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to the maillist. Help Bram help Uganda.
Vim at Github