User:AndreasJS/gutenbergnotes.vim

"

"Here is a vim script that will format the footnotes from Project Gutenberg texts. I used it for [[Anabasis]].
"Original format:
"Pasion came with three hundred hoplites and three hundred peltasts[1].
" ...
"[1] "Targeteers" armed with a light shield instead of the larger one
"...
"Final format:
"Pasion came with three hundred hoplites and three hundred peltasts.<ref>
"Targeteers" armed with a light shield instead of the larger one
"...</ref> 
"...
"Open file in [[w:Vim (text editor)|Vim]], the run the script with the :source command.
"
set wrapscan
"
" Swap ref number with . or ,   
%s/\(\[[0-9]\+\]\)\([,.]\)/\2\1/g
"
" Split line at ref number
%s/.\[[0-9]\+\]/&\r/g
"
" Add </ref> at end of ref text
g/^\[[0-9]\+\]/;/^$/s/^$/<\/ref>/
"
set nowrapscan
  0                        "got to top of file
  while 1
      if search("\[[0-9][0-9]*\]$", "W") == 0  " Find ref number in main text
        break              
      endif
      mark a               "remember position of ref number in main text
                           " remember ref number in main text
      normal y$
    try
"
" Find where ref numbers start with [1] again
      /.\[1\]$/mark b
    catch /E385/           "If ref numbers don't start with [1] again
      $mark b              "mark the end of file
    endtry
    try
"
" Delete the ref text only if before the next [1] ref number
      let x = @@
      let x = substitute(x, "\[", "\\\\[", "")
      let x = substitute(x, "\]", "\\\\]", "")
      execute '/^\%>''a' . x . '/;/<\/ref>\%<''b/d'
    catch /E385/           "if the ref text is missing
      normal 'b-
      continue             "find next ref number in main text
    endtry
"
" Go back to the ref number in main text
    normal 'a
"
" add reference text
    normal p
  endwhile
set wrapscan
"
" Final formatting
g/^<\/ref>/j
g/^\[[0-9]\+\] /-s/$/<ref>/
%s/^\[[0-9]\+\] //
%s/\[[0-9]\+\]//
%s/^  *//
"