Giter Club home page Giter Club logo

vim-pencil's Introduction

vim-pencil

Vint

Rethinking Vim as a tool for writers



demo


Features

The pencil plugin aspires to make Vim as powerful a tool for writers as it is for coders by focusing narrowly on the handful of tweaks needed to smooth the path to writing prose.

  • For editing prose-oriented file types such as text, markdown, mail, rst, tex, textile, and asciidoc
  • Agnostic on soft line wrap versus hard line breaks, supporting both
  • Auto-detects wrap mode via modeline and sampling
  • Adjusts navigation key mappings to suit the wrap mode
  • Creates undo points on common punctuation during Insert mode, including deletion via line <C-U> and word <C-W>
  • Buffer-scoped configuration (with a few minor exceptions, pencil preserves your global settings)
  • Support for Vim’s Conceal feature to hide markup defined by Syntax plugins (e.g., _ and * markup for styled text in _Markdown_)
  • Support for display of mode indicator ( and , e.g.) in the status line
  • Pure Vimscript with no dependencies

In addition, when using hard line break mode:

  • Makes use of Vim’s powerful autoformat while inserting text, except for tables and code blocks where you won’t want it.
  • NEW Optional key mapping to suspend autoformat for the Insert.

Need spell-check, distraction-free editing, and other features? Vim is about customization. To complete your editing environment, learn to configure Vim and draw upon its rich ecosystem of plugins.

Why use Vim for writing?

With plenty of word processing applications available, including those that specifically cater to writers, why use a modal editor like Vim? Several reasons have been offered:

  • Your hands can rest in a neutral ‘home’ position, only rarely straying to reach for mouse, track pad, or arrow keys
  • Minimal chording, with many mnemonic-friendly commands
  • Sophisticated capabilities for navigating and manipulating text
  • Highly configurable, enabling you to build a workflow that suits your needs, with many great plugins available
  • No proprietary format lock-in

But while such reasons might be sound, they remain scant justification to switch away from the familiar word processor. Instead, you need a compelling reason—one that can appeal to a writer’s love for language and the tools of writing.

You can find that reason in Vim’s mysterious command sequences. Take cas for instance. You might see it as a mnemonic for Change Around Sentence to replace an existing sentence. But dig a bit deeper to discover that such commands have a grammar of their own, comprised of nouns, verbs, and modifiers. Think of them as the composable building blocks of a domain specific language for manipulating text, one that can become a powerful tool in expressing yourself. For more details on vi-style editing, see...

Installation

You can install using your favorite Vim package manager. (E.g., Pathogen, Vundle, or Plug.) If you are using a recent version of vim or neovim, you can also use native package support. (See :help packages.)

For those new to Vim: before installing this plugin, consider getting comfortable with the basics of Vim by working through one of the many tutorials available.

Configuration

Initializing by command

You can manually enable, disable, and toggle pencil as a command:

  • Pencil - initialize pencil with auto-detect for the current buffer
  • NoPencil (or PencilOff) - removes navigation mappings and restores buffer to global settings
  • TogglePencil (or PencilToggle) - if on, turns off; if off, initializes with auto-detect

Because auto-detect might not work as intended, you can invoke a command to set the behavior for the current buffer:

  • SoftPencil (or PencilSoft) - initialize pencil with soft line wrap mode
  • HardPencil (or PencilHard) - initialize pencil with hard line break mode (and Vim’s autoformat)

Initializing by file type

Initializing pencil by file type is optional, though doing so will automatically set up your buffers for editing prose.

Add support for your desired file types to your .vimrc:

set nocompatible
filetype plugin on       " may already be in your .vimrc

augroup pencil
  autocmd!
  autocmd FileType markdown,mkd call pencil#init()
  autocmd FileType text         call pencil#init()
augroup END

You can initialize several prose-oriented plugins together:

augroup pencil
  autocmd!
  autocmd FileType markdown,mkd call pencil#init()
                            \ | call lexical#init()
                            \ | call litecorrect#init()
                            \ | call textobj#quote#init()
                            \ | call textobj#sentence#init()
augroup END

For a list of other prose-oriented plugins, consult the See also section below.

Hard line breaks or soft line wrap?

Coders will have the most experience with the former, and writers the latter. But whatever your background, chances are that you must contend with both conventions. This plugin doesn’t force you to choose a side—you can configure each buffer independently.

In most cases you can set a default to suit your preference and let auto-detection figure out what to do.

let g:pencil#wrapModeDefault = 'soft'   " default is 'hard'

augroup pencil
  autocmd!
  autocmd FileType markdown,mkd call pencil#init()
  autocmd FileType text         call pencil#init({'wrap': 'hard'})
augroup END

In the example above, for buffers of type markdown this plugin will auto-detect the line wrap approach, with soft line wrap as the default.

For buffers of type text, it will initialize with hard line breaks, even if auto-detect might suggest soft line wrap.

Automatic formatting

The ‘autoformat’ feature affects HardPencil (hard line break) mode only.

When inserting text while in HardPencil mode, Vim’s powerful autoformat feature will be enabled by default and can offer many of the same benefits as soft line wrap.

To set the default behavior in your .vimrc:

let g:pencil#autoformat = 1      " 0=disable, 1=enable (def)

You can override this default during initialization, as in:

augroup pencil
  autocmd!
  autocmd FileType markdown call pencil#init({'wrap': 'hard', 'autoformat': 1})
  autocmd FileType text     call pencil#init({'wrap': 'hard', 'autoformat': 0})
  ...
augroup END

...where buffers of type markdown and text will use hard line breaks, but text buffers will have autoformat disabled.

Suspend automatic formatting for the Insert

There are two useful exceptions where autoformat (when enabled for the buffer) will be temporarily disabled for the current Insert:

First is pencil’s ‘blacklisting’ feature: if used with popular prose-oriented syntax plugins, pencil will suspend autoformat when you enter Insert mode from inside a code block or table.

Second, where blacklisting falls short, you can optionally map a buffer-scoped ‘modifier’ key to suspend autoformat during the next Insert:

let g:pencil#map#suspend_af = 'K'   " default is no mapping

Using the above mapping, with Ko you’ll enter Insert mode with the cursor on a new line, but autoformat will suspend for that Insert. Using o by itself will retain autoformat.

By default no modifier key is mapped.

(See the advanced section below for details on how blacklisting is implemented and configured).

Manual formatting

Note that you need not rely on Vim’s autoformat exclusively and can manually reformat paragraphs with standard Vim commands:

  • gqap - format current paragraph (see :help gq for details)
  • vapJgqap - merge two paragraphs (current and next) and format
  • ggVGgq or :g/^/norm gqq - format all paragraphs in buffer

Optionally, you can map these operations to underutilized keys in your .vimrc:

nnoremap <silent> Q gqap
xnoremap <silent> Q gq
nnoremap <silent> <leader>Q vapJgqap

Or you may wish to ‘unformat’, (i.e., remove hard line breaks) when using soft line wrap.

  • vipJ - join all lines in current paragraph
  • :%norm vipJ - unformat all paragraphs in buffer

Default textwidth

You can configure the textwidth to be used in HardPencil (hard line break) mode when no textwidth is set globally, locally, or available via modeline. It defaults to 74, but you can change that value in your .vimrc:

let g:pencil#textwidth = 74

Sentence spacing

By default, when formatting text (through gwip, e.g.) only one space will be inserted after a period(.), exclamation point(!), or question mark(?). You can change this default:

let g:pencil#joinspaces = 0     " 0=one_space (def), 1=two_spaces

Cursor wrap

By default, h/l and the left/right cursor keys will move to the previous/next line after reaching first/last character in a line with a hard break. If you wish to retain the default Vim behavior, set the cursorwrap value to 0 in your .vimrc:

let g:pencil#cursorwrap = 1     " 0=disable, 1=enable (def)

Concealing __markup__

pencil enables Vim’s powerful Conceal feature, although support among Syntax and Colorscheme plugins is currently spotty.

You can change pencil’s default settings for conceal in your .vimrc:

let g:pencil#conceallevel = 3     " 0=disable, 1=one char, 2=hide char, 3=hide all (def)
let g:pencil#concealcursor = 'c'  " n=normal, v=visual, i=insert, c=command (def)

For more details on Vim’s Conceal feature, see:

:help conceallevel
:help concealcursor

Concealing styled text in Markdown

Syntax plugins such as tpope/vim-markdown support concealing the markup characters when displaying _italic_, **bold**, and ***bold italic*** styled text.

To use Vim’s Conceal feature with Markdown, you will need to install:

  1. tpope/vim-markdown as it’s currently the only Markdown syntax plugin that supports conceal.

  2. A monospaced font (such as Cousine) featuring the italic, bold, and bold italic style variant for styled text.

  3. A colorscheme (such as preservim/vim-colors-pencil) which supports the Markdown-specific highlight groups for styled text.

You should then only see the _ and * markup for the cursor line and in visual selections.

Terminal users: consult your terminal’s documentation to configure your terminal to support bold and italic styles.

Status line indicator

Your status line can reflect the wrap mode for pencil buffers. For example, to represent HardPencil (hard line break) mode. To configure your status line and ruler, add to your .vimrc:

set statusline=%<%f\ %h%m%r%w\ \ %{PencilMode()}\ %=\ col\ %c%V\ \ line\ %l\,%L\ %P
set rulerformat=%-12.(%l,%c%V%)%{PencilMode()}\ %P

or if using bling/vim-airline:

let g:airline_section_x = '%{PencilMode()}'

The default indicators now include ‘auto’ for when Vim’s autoformat is active in hard line break mode. (If autoformat is suspended for the Insert, it’ll show the ‘hard’ indicator.)

let g:pencil#mode_indicators = {'hard': 'H', 'auto': 'A', 'soft': 'S', 'off': '',}

If Unicode is detected, the default indicators are:

let g:pencil#mode_indicators = {'hard': '', 'auto': 'ª', 'soft': '', 'off': '',}

If you don’t like the default indicators, you can specify your own in your .vimrc.

Note that PencilMode() will return blank for buffers in which pencil has not been initialized.

Advanced pencil

Advanced initialization

You may want to refactor initialization statements into a function in your .vimrc to set up a buffer for writing:

function! Prose()
  call pencil#init()
  call lexical#init()
  call litecorrect#init()
  call textobj#quote#init()
  call textobj#sentence#init()

  " manual reformatting shortcuts
  nnoremap <buffer> <silent> Q gqap
  xnoremap <buffer> <silent> Q gq
  nnoremap <buffer> <silent> <leader>Q vapJgqap

  " force top correction on most recent misspelling
  nnoremap <buffer> <c-s> [s1z=<c-o>
  inoremap <buffer> <c-s> <c-g>u<Esc>[s1z=`]A<c-g>u

  " replace common punctuation
  iabbrev <buffer> --iabbrev <buffer> ---iabbrev <buffer> << «
  iabbrev <buffer> >> »

  " open most folds
  setlocal foldlevel=6

  " replace typographical quotes (reedes/vim-textobj-quote)
  map <silent> <buffer> <leader>qc <Plug>ReplaceWithCurly
  map <silent> <buffer> <leader>qs <Plug>ReplaceWithStraight

  " highlight words (reedes/vim-wordy)
  noremap <silent> <buffer> <F8> :<C-u>NextWordy<cr>
  xnoremap <silent> <buffer> <F8> :<C-u>NextWordy<cr>
  inoremap <silent> <buffer> <F8> <C-o>:NextWordy<cr>

endfunction

" automatically initialize buffer by file type
autocmd FileType markdown,mkd,text call Prose()

" invoke manually by command for other file types
command! -nargs=0 Prose call Prose()

For highly-granular control, you can override pencil and other configuration settings when initializing buffers by file type:

augroup pencil
  autocmd!
  autocmd FileType markdown,mkd call pencil#init()
                            \ | call litecorrect#init()
                            \ | setl spell spl=en_us fdl=4 noru nonu nornu
                            \ | setl fdo+=search
  autocmd Filetype git,gitsendemail,*commit*,*COMMIT*
                            \   call pencil#init({'wrap': 'hard', 'textwidth': 72})
                            \ | call litecorrect#init()
                            \ | setl spell spl=en_us et sw=2 ts=2 noai
  autocmd Filetype mail         call pencil#init({'wrap': 'hard', 'textwidth': 60})
                            \ | call litecorrect#init()
                            \ | setl spell spl=en_us et sw=2 ts=2 noai nonu nornu
  autocmd Filetype html,xml     call pencil#init({'wrap': 'soft'})
                            \ | call litecorrect#init()
                            \ | setl spell spl=en_us et sw=2 ts=2
augroup END

Configurable options for pencil#init() include: autoformat, concealcursor, conceallevel, cursorwrap, joinspaces, textwidth, and wrap. These are detailed above.

Autoformat manual control

The ‘autoformat’ feature affects HardPencil (hard line break) mode only.

To suspend autoformat for the next Insert, see above.

When you need to manually enable/disable autoformat for the current buffer, you can do so with a command:

  • PFormat - enable autoformat for buffer (can still be disabled via blacklisting)
  • PFormatOff - disable autoformat for buffer
  • PFormatToggle - toggle to enable if disabled, etc.

You can map a key in your .vimrc to toggle Vim’s autoformat:

noremap <silent> <F7> :<C-u>PFormatToggle<cr>
inoremap <silent> <F7> <C-o>:PFormatToggle<cr>

Autoformat blacklisting (and whitelisting)

The ‘autoformat’ feature affects HardPencil (hard line break) mode only.

When editing formatted text, such as a table or code block, Vim’s autoformat will wreak havoc with the formatting. In these cases you will want autoformat suspended for the duration of the Insert.

When entering Insert mode, pencil will determine the highlight group at the cursor position. If that group has been blacklisted, pencil will suspend autoformat for the Insert. For example, if editing a buffer of type ‘markdown’, autoformat will be suspended if you invoke Insert mode from inside a markdownFencedCodeBlock highlight group.

Blacklists are now declared by file type. The default blacklists (and whitelists) are declared in the plugin/pencil.vim module. Here’s an excerpt showing the configuration for the ‘markdown’ file type:

  let g:pencil#autoformat_config = {
        \   'markdown': {
        \     'black': [
        \       'htmlH[0-9]',
        \       'markdown(Code|H[0-9]|Url|IdDeclaration|Link|Rule|Highlight[A-Za-z0-9]+)',
        \       'markdown(FencedCodeBlock|InlineCode)',
        \       'mkd(Code|Rule|Delimiter|Link|ListItem|IndentCode)',
        \       'mmdTable[A-Za-z0-9]*',
        \     ],
        \     'white': [
        \      'markdown(Code|Link)',
        \     ],
        \   },
        [snip]
        \ }

The whitelist will override the blacklist and enable Vim’s autoformat if text that would normally be blacklisted doesn’t dominate the entire line. This allows autoformat to work with inline code and links.

Auto-detecting wrap mode

If you didn’t explicitly specify a wrap mode during initialization, pencil will attempt to detect it.

It will first look for a textwidth (or tw) specified in a modeline. Failing that, pencil will then sample lines from the start of the buffer.

Detect via modeline

Will the wrap mode be detected accurately? Maybe. But you can improve its chances by giving pencil an explicit hint.

At the bottom of this document is a odd-looking code:

<!-- vim: set tw=73 :-->

This is an optional ‘modeline’ that tells Vim to run the following command upon loading the file into a buffer:

:set textwidth=73

It tells pencil to assume hard line breaks, regardless of whether or not soft line wrap is the default editing mode for buffers of type ‘markdown’.

You explicitly specify soft wrap mode by specifying a textwidth of 0:

<!-- vim: set tw=0 :-->

Note that if the modelines feature is disabled (such as for security reasons) the textwidth will still be set by this plugin.

Detect via sampling

If no modeline with a textwidth is found, pencil will sample the initial lines from the buffer, looking for those excessively-long.

There are two settings you can add to your .vimrc to tweak this behavior.

The maximum number of lines to sample from the start of the buffer:

let g:pencil#softDetectSample = 20

Set that value to 0 to disable detection via line sampling.

When the number of bytes on a sampled line per exceeds this next value, then pencil assumes soft line wrap.

let g:pencil#softDetectThreshold = 130

If no such lines found, pencil falls back to the default wrap mode.

See also

Bloggers and developers discuss pencil and its brethern:

Other plugins of specific interest to writers:

Markdown syntax plugins

Markdown users typically won’t need to install a syntax plugin unless they want the latest version of Pope’s syntax highlighting:

  • tpope/vim-markdown - (recommended) the latest version of Pope’s syntax plugin which ships with Vim

Those using tables and footnotes should consider installing this plugin:

Alternatives to Tim Pope’s syntax highlighting include:

Note that the plasticboy and gabrielelana plugins may incorrectly reformat bulleted lists when Vim’s autoformat is active in pencil’s HardPencil mode.

If you find the pencil plugin useful, check out these others originally by @reedes:

Unimpressed by pencil? vim-pandoc offers prose-oriented features with its own Markdown variant.

Future development

If you’ve spotted a problem or have an idea on improving pencil, please report it as an issue, or better yet submit a pull request.

vim-pencil's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vim-pencil's Issues

Un-Initialize (Save + Restore Settings)

If for whatever reason a file has been incorrectly detected as text, changing the filetype won't disable vim-pencil. The previous settings need to be save, then restored.

Perhaps :mkview in init(), with autocmd FileType * loadview followed be a delete-view-file-operation.

Though it might be simpler in the long run to individual save each option to a buffer-local dictionary?

This would also be useful when switching from code to embedded prose.

Better autoformat support for AsciiDocList

When a heading is on the preceding line, autoformat will include that line in the reformat.

Need lookbehind to disable autoformat if the heading is present on that previous line. Otherwise allow autoformat.

What exactly is 'soft' line wrapping?

I just installed this plugin as I wanted to explore using vim to write prose. I think I may be confused as to what 'soft' wrapping mode actually is because in all my attempts to use it so far it doesn't do anything.

So I've got the textwidth set to 74 (default I think but I set it explicitly anyway). In hard wrapping mode if I try to type more than 74 chars it inserts a line break at a convenient point and moves me on to the next line. I understand this and it works how I expect.

In soft mode I can just keep typing until I myself decide to hit enter and insert a line break. Which is the behaviour I'm used to from using Vim as a code editor. I was expecting soft wrap mode to be something like it wrapping the lines visually but there being no line breaks inserted. I suppose it is doing this but at the terminal width not at 74 characters.

Sorry if this is not appropriate for an 'issue', I realise it's not a bug or enhancement but I couldn't find anywhere to ask the question (I tried IRC but got no response).

Thanks.

Reorganize commands

Reorganize commands to make them more friendly to command-line completion.

Autoformat indicator

I have a small feature proposal. I haven't forked this project, but I wouldn't mind doing so and creating a pull request if that sort of thing is welcomed.

My current workflow using vim-pencil with LaTeX involves frequently toggling autoformat on and off (for instance, to switch from writing a paragraph to writing an equation, where I want to manually specify all formatting), as I haven't quite figured out g:pencil#autoformat_blacklist. I thought it might be nice to provide a convenience function, similar to PencilMode(), which returns a string (preferably user-overridable) indicating whether or not autoformat is enabled. To this end, I put the following in my .vimrc and it seems to work for my purposes:

let g:pencil#autoformat_indicators = {'auto': 'auto', 'noauto': 'noauto'}
fun! PencilAutoformat()
    if exists('b:last_autoformat')
        if b:last_autoformat
            return get(g:pencil#autoformat_indicators, 'auto', 'auto')
        else
            return get(g:pencil#autoformat_indicators, 'noauto', 'noauto')
        en
    else
        return ''
    en
endf

If this were built into plugin/pencil.vim (again, like PencilMode()), people could then add something like this to their .vimrc:

let g:pencil#autoformat_indicators = {'auto': 'a+', 'noauto': 'a-',}
let statusline=%<%f\ %{PencilMode()}\ %{PencilAutoformat()}

Custom abberviations no longer work when Pencil is loaded

Hello,

I have a small list of custom insert mode abbreviations for some unicode symbols, however, whenever I edit a filetype that Pencil is called for they appear to no longer function. If I check :ab they appear to be loaded though.

I'm also using Litecorrect however disabling that does not yield any difference. Disabling Pencil fixes the issue (but I obviously don't want that :-))

Is there anything I should be doing different to prevent this?

Hard wrapping not working for ft=mail

I don't know what I'm doing wrong here. Maybe I misunderstand the readme. I have the following in my .vimrc

augroup pencil
    autocmd!
    autocmd FileType text     call pencil#init()
    autocmd FileType mail     call pencil#init({'wrap': 'hard', 'textwidth': '72'})
    autocmd FileType markdown call pencil#init()
augroup END

Nonetheless, if I start writing an email with ft=mail textwidth remains 0. As I got it from the readme, even without enforcing both wrap and textwidth I should get textwidth set -- doesn't work either.

If I verbose set tw? it says that it got loaded from pencil but it 0. On the contrary, if I do :HardPencil everything works as expected.

Any help appreciated.

Mapping <cr>

Hello,
I really want to use Pencil, but it breaks my own mapping of <cr>. Could add an option to change or disable the default mappings?

Add additional autoformat blacklisting rule

Sorry in case this is actually obvious: How do I add additional rules for blacklisting? I would like code blocks in ft=mail not to be automatically formatted.

Sorry to bother you with that filetype. :-) I would flattr your work, if I could!

Pencil Mode breaks remapped movement keys

I remapped my movement keys from hjkl to jkl;. When I turn on pencil mode it is hard-coded to set j to gj (down) and k to gk (up).

Ideally, the plugin would remap the currently used movement keys for up/down to gj and gk.

Bug in setting hard line break mode

If

  • the default mode is soft
  • there is no modeline
  • none of the lines exceed the soft threshold length

It'll go to soft mode when it should be detected with hard mode.

Disabling Pencil doesn't seem to work after it's fully loaded

Guessing this is a conflict with one of my other plugins or my environment, I'd be surprised if it was globally broken (but who knows?).

To reproduce:

  • Enable Pencil as per the documentation, including having it autoload for Markdown document types: https://github.com/bitprophet/dotfiles/blob/9a04c666d8afe603a4f97251e16a9ab2a22a5dc8/.vimrc#L384-L389
  • Edit a Markdown document
  • Start making a bullet list, run into #31
  • Try turning off Pencil temporarily using :NoPencil (or :TogglePencil - same behavior for both)
  • Continue editing bullet list - #31 continues happening (autoformat is running automatically, joining lines)
  • Only quitting vim, commenting out Pencil's block in vimrc, and re-opening suffices.
    • I haven't dug to see exactly how Pencil works its magic or I'd provide more data on related settings.

A strange but hopefully illuminating wrinkle:

  • I can reproduce the issue with blank buffers like so:
    • Run vim by itself w/ no filename, with Pencil enabled in the rc file
    • :set ft=markdown
    • Type a Markdown bullet list, trigger #31
  • But I can prevent it (somewhat unhelpfully) by doing this:
    • Run vim by itself, as above, still with Pencil enabled
    • Immediately execute :NoPencil
    • Then do :set ft=markdown, type stuff, and things work fine - no #31 behavior occurs.

Other notes:

  • This is all reproducible on both OS X 10.10 native CLI vim 7.3, and on MacVim (GUI) 7.4, so my guess about it being 7.3-specific was incorrect.
  • My dotfiles repo, with my .vimrc and .vim/, can be seen here: https://github.com/bitprophet/dotfiles
  • I manually install plugins and don't actually use a plugin manager, so that shouldn't be a factor. I installed Pencil from HEAD a day or two ago, manually copying the 2 actual plugin files to the appropriate folders.
    • Tho I just noticed I still enable Pathogen at the top of my vimrc...I haven't actually USED that in years, so gonna nuke it. Heh. EDIT: yea, no difference in behavior after that.

Single digit "3" on its own blocks/breaks formatting

Starting with this text for example:

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.

If I add text in the middle of the paragraph then it fails to wrap properly at the occurance of the "3":

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
A B C D E F G H I J K L M N O P Q R S T Free Software Foundation;
either version
3 of the License, or (at your option) any later version.

Not avoiding autoformat for tables

Example of table in a Markdown variant:

Tables Are Cool
col 1 is left-aligned $1600
col 2 is centered $12
col 3 is right-aligned $1

If the user enters Insert mode from inside table, there may be no highlight code on the synstack to exclude.

One option is to have pencil parse the line, looking for leading '|' when filetype is markdown. That might best go into a new vim-pencil-markdown project

Better yet, provide pull request to Syntax plugins to provide highlighting for tables. Then those highlights can be added to Pencil's exclude list.

Vim-pencil initialization changes some mappings of the previously set keymap.

How to reproduce:

" set russian keymap
set keymap=russian-jcukewin

" activate vim-pencil 
:Pencil

" switch to specified keymap
<C-^>

" try to input letter "б" (same key as , and <)
" ',' (comma) is entered instead of the letter "б" 

If the keymap is reset after Pencil is activated, the mappings work as they should.

In hard mode, disable auto format for visual-based insert

Given a list in a document in pencil's hard line break mode:

*foo
bar
baz

With the cursor at the *, use the commands <C-v>jjIxyz you should end up with

xyz foo
xyz bar
xyz baz

but instead you weirdly get

xyz foo bar baz
xyz foo bar
xyz foo bar

When user hits insert and highlight stack is empty, check nearby

Hardpencil mode issue.

If at the end of a line in a list of links, such as

...the synstack call may return .

Then pencil enables autoformat and the text is disrupted.

Checking one character to the left would detect the syntax and the blacklist mechanism could then prevent autoformat.

Error on malformed modelines

Given:

<!-- vim: tw=65 -->

"50k/4.md" 26L, 641C
Error detected while processing modelines:
line 26:
E518: Unknown option: -->
Press ENTER or type command to continue

Need IgnoreList

For plasticboy/vim-markdown, the [mkdNonListItemBlock] should be treated like a [] when scanning a line looking for a blacklisted highlight group.

Otherwise we're not finding the blacklist item.

Note that mkdNonListItemBlock should be removed from the blacklist and moved to an IgnoreList.

What should the iskeyword strategy be for prose, if anything?

W can be used to traverse words separated by spaces, which is the common case.

My experiments:

" skip over punctuation inside and adjacent to words
setl iskeyword+=.,?,;,!,(,),[,],{,},',-,`
setl iskeyword+=\,
setl iskeyword+=\"
" TODO «» “” ‘’

" for D&D, #3, ~40, 100%, $200, etc.
setl iskeyword+=&,#,~,%,$
setl iskeyword+=\|
"setl iskeyword+=^   not working?

" and various math operators (200+3=203)
setl iskeyword+=+
setl iskeyword+=*
setl iskeyword+=>
setl iskeyword+==
setl iskeyword+=<

setl iskeyword+=:,/     " consider urls to be words

setl iskeyword+=\\      " and escaped markdown chars, like \_
setl iskeyword+=@-@     " and email@addresses
setl iskeyword+=-

"set iskeyword=!-~,^*,^45,^124,^34,192-255,^_

Can't disable conceal

I can't disable conceal even if I have the following codes in my .vimrc

let g:pencil#conceallevel = 0

so **word** still show as word without the surrounding **

Possible plugin conflict preventing initial wrap in hard line mode?

When toggling between hard/soft modes on a file with long lines (I've commented out any vim-pencil autocmds for the sake of debugging) :SoftPencil works as expected (setting wrap w/o cutting off words, remapping nav keys, etc.), while :HardPencil, though it sets nowrap and textwidth=80 correctly, does not create hard line breaks upon mode switch. The lines simply run off the screen until an edit is attempted, at which point the line is finally auto formatted to the appropriate textwidth.

I can't tell 100% from the documentation -- isn't vim-pencil supposed to create and undo hard line breaks upon mode switches? If so, what would be interfering with this initial wrap (my .vimrc and a list of plugins are below)? Note also that, after hard line breaks have been created via auto format on a given line, calling :SoftPencil does not rejoin these lines into the original line, now softly wrapped, it merely soft wraps the lines that have not yet been touched by autoformat.

If not, where would you recommend I insert this behavior into my vim-pencil version (just some execute "normal gggqG" commands, etc.)? I just thought this was the whole point of vim-pencil!

Hopefully this helps other users get set-up with vim-pencil, as I have spent some time trying to figure out where my setup might have gone wrong.

Current plugins

  • delimitMate
  • goyo.vim
  • limelight.vim
  • nerdcommenter
  • taskpaper.vim
  • vim-misc
  • vim-pandoc-syntax
  • vim-session
  • vim-pencil

.vimrc

It is unlikely that conflicts are here... I leave the setting of formatoptions, etc. to vim-pencil, though in vim-pencil section below I have experimented (to no avail) with setting, e.g., textwidth to some non-zero value manually.

set nocompatible

let mapleader=" "

execute pathogen#infect()

"mappings ===============================================
"removes key functionality when learning new maps
":inoremap <esc> <nop>
":inoremap jk <esc>
:nnoremap <leader>ev :vsplit $MYVIMRC<cr>
:nnoremap <leader>sv :source $MYVIMRC<cr>
:nnoremap <leader>el :vsplit #<cr>
:nnoremap <leader>et :vsplit ~/Dropbox/Notes/todo.taskpaper<cr>
"quotes around word
":nnoremap <leader>" viw<esc>a"<esc>hbi"<esc>lel
"python specific commenting
":autocmd FileType python     nnoremap <buffer> <localleader>c I#<esc>
":autocmd FileType python     :iabbrev <buffer> iff if:<left>

"operator mappings
:onoremap p i(
:onoremap in( :<c-u>normal! f(vi(<cr>
:onoremap il( :<c-u>normal! F)vi(<cr>

"markdown mappings
"change header if marked with equal signs
":onoremap ih :<c-u>execute "normal! ?^==\\+$\r:nohlsearch\rkvg_"<cr>

"snippets
:iabbrev eml    [email protected]
:iabbrev zml    [email protected]
"=============================================================

" allow backspacing over everything in insert mode
set backspace=indent,eol,start

set history=1000    " keep 50 lines of command line history
set showcmd     " display incomplete commands
set incsearch       " do incremental searching
"set autochdir      " 

" In many terminal emulators the mouse works just fine, thus enable it.
if has('mouse')
  set mouse=a
endif

" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
  syntax on
  set hlsearch
endif

filetype plugin indent on

" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event handler
" (happens when dropping a file on gvim).
" Also don't do it when the mark is in the first line, that is the default
" position when opening a file.
autocmd BufReadPost *
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\   exe "normal! g`\"" |
\ endif

" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
" Only define it when not defined already.
if !exists(":DiffOrig")
  command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
          \ | wincmd p | diffthis
endif

":set spell
":set spelllang=en,de

set backupdir=~/.vimbackups,/tmp

set pastetoggle=<F1>
:nnoremap <F5> "=strftime("%c")<CR>P
:inoremap <F5> <C-R>=strftime("%c")<CR>

"from theunixschool.com
map #2 :wq!

"prevents sync discrepancies by checking for changes to the files of
"open buffers
au CursorHold * checktime

let g:session_autosave = 'no'

"will auto wrap text 
"set formatoptions+=a 

"see for navigating by sentences etc.
":help text-objects

"VIM-PENCIL========================================================= 
"let g:pencil#wrapModeDefault = 'hard'   " default is 'hard'

"set number
"set nopaste
"set tw=80 
"set nowrap
"set fo+=tca

"let g:pencil#textwidth = 74

augroup pencil
    "autocmd!
    "autocmd FileType markdown,mkd,md call pencil#init({'wrap': 'hard'})
    "autocmd FileType text,txt  call
    "pencil#init({'wrap': 'hard'}) had to manually add a macro to correctly
    "hard wrap existing lines don't kno what's pencil's deal is autocmd
    "FileType text,txt,markdown,mkd,md :HardPencil
    "autocmd FileType markdown,mkd,md  execute "normal magggqG`a"
    "autocmd FileType text,txt,markdown,mkd,md  execute "normal magggqG`a"
    "autocmd BufWritePre text,txt,markdown,mkd,md :SoftPencil
    "autocmd BufWritePost text,txt,markdown,mkd,md :HardPencil
augroup END

"GOYO===============================================================

function! s:goyo_enter()
  "Setup to quit vim in GOYO
  let b:quitting = 0
  let b:quitting_bang = 0
  autocmd QuitPre <buffer> let b:quitting = 1
  cabbrev <buffer> q! let b:quitting_bang = 1 <bar> q!
endfunction

function! s:goyo_leave()
  " Quit Vim if this is the only remaining buffer
  if b:quitting && len(filter(range(1, bufnr('$')), 'buflisted(v:val)')) == 1
    if b:quitting_bang
      qa!
    else
      qa
    endif
  endif
endfunction

"autocmd FileType markdown,mkd,md :Goyo
"autocmd FileType text,txt :Goyo
let g:goyo_margin_top=2
let g:goyo_margin_bottom=2
:set scrolloff=999

"autocmd User GoyoEnter call <SID>goyo_enter()
"autocmd User GoyoLeave call <SID>goyo_leave()

Typing below one line jumps it up to the one above it unless there is a line break between

Maybe this is standard functionality? Seems like something funky is going on though... being able to type two lines without spaces between them is hopefully an option? To repro: if I'm making a list in markdown, for example, when I type one entry, hit enter and start to type the next bullet or dash immediately below the line above it (with no space in between), then it jumps up to the previous line.

Is there a setting to stop that? Or is one of my other plugins messing with me?

image

Thanks!!

hard pencil mode deleting issue

steps to reproduce the issue:

  1. launch vim
  2. copy the code snippet below into vim
function! ToggleGUICruft()
    if &guioptions=='i'
        exec('set guioptions=imTrL')
    else
        exec('set guioptions=i')
    endif
endfunction

3, vip= to format the code
4. run :HardPencil
5. yip to copy the code snippet and paste it to the blank space.
6. move the cursor the beginning of endfuntion and press <BS> key.

result:

function! ToggleGUICruft()
    if &guioptions=='i'
        exec('set guioptions=imTrL')
    else
        exec('set guioptions=i')
    endif
endfunction

function! ToggleGUICruft()
    if &guioptions=='i'
        exec('set guioptions=imTrL')
    else exec('set guioptions=i') endifendfunction

Possible to use a subset of this in combination with Vimwiki?

Hi there!

I love Pencil, and I'd like to use some of the features (hard wrap at 80 chars at least) when editing my Vimwiki, but if I do that some of the auto-formatting on <cr>, amongst other things breaks for that filetype which means things like new todo list entries don't get created, for example.

Any idea if it's possible to do the hard wrap portion of this plugin in a vimwiki context?

Thanks!

Support asciidoc in blacklist (and whitelist)

Full support may be tricky, as the asciidoc syntax file that ships with Vim does not play well with Vim's autoformat capability, specifically on formatting list elements (hi asciidocList).

To reproduce problem, outside of pencil compare editing list elements in markdown and asciidoc with Vim's autoformat enabled.

Provisionally blacklisting asciidocList until this is sorted out.

pencil#init() when called with 'wrap': 'hard' and disabled modeline gives error

When calling pencil#init({'wrap':'hard'}) on a window without a modeline:

Error detected while processing function pencil#init:
line   42:
E121: Undefined variable: b:max_textwidth
E15: Invalid expression: &modeline == 0 && b:max_textwidth > 0
E121: Undefined variable: b:max_textwidth
E15: Invalid expression: &modeline == 0 && b:max_textwidth > 0

I've tracked it down to line 109 of autoload/pencil.vim, and it seems through some combination of conditionals that because I'm specifying hard mode, detect_wrap_mode() never gets called, and this is where b:max_textwidth gets set. It seems like there should be some sort of default, but looking over detect_wrap_mode() I'm not entirely sure if that should be &textwidth or not. I'll poke around a bit at it and see if setting that helps, but in the mean time I wanted to record the issue.

Figure out way to make global settings only active for pencil mode

For example, whichwrap and virtualedit are globally-scoped settings. Setlocal for these doesn't appear to be working as expected.

Investigate how to automatically set/unset these for the buffers in which a pencil mode is active.

Use BufEnter and BufLeave events to set/restore these global settings.

Setting Font and Color-Theme only for Markdown

Hello,

I am pretty new to Vim and I stumbled on your cool plugin. I like it a lot for editing Markdown files. In general I prefer a black theme (molokai) and CamingoCode as my default font.

But for editing Markdown files I would prefer to have Cousine as a font and vim-colors-pencil (light) as colourscheme. How can I automatically switch to that for Markdown files and switch automatically back to my default theme for non Markdown files?

I hope you can help me with that topic.

Greetings from Germany

YAML Auto-formatting in Auto Mode

Is it possible to add support to automatically disable default autofomatting when recognising YAML header in markdown file? Since it tries to format YAML header to one line in auto mode. And it is pretty annoying to switch modes manually.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.