/paragraphs.sed

https://code.google.com/p/latex-makefile/ · sed · 81 lines · 41 code · 10 blank · 30 comment · 0 complexity · 9b72386b72fddc1d85bbd4f5c0461c95 MD5 · raw file

  1. # This uses a neat trick from the Sed & Awk Book from O'Reilly:
  2. # Ensure that the last line looks like the end of a paragraph; if it isn't
  3. # blank, hold it and blank it out.
  4. ${
  5. /^$/!{
  6. H
  7. s/.*//
  8. }
  9. }
  10. # Non-blank lines get held in the hold buffer
  11. /^$/!{
  12. H
  13. d
  14. }
  15. # Blank lines signify the end of a paragraph.
  16. # Swap blank into hold buffer (bringing paragraph into pattern buffer).
  17. # Move newline prefix to end of paragraph.
  18. /^$/{
  19. x
  20. s/^\(\n\)\(.*\)/\2\1/
  21. }
  22. # Each P inside of :: represents a paragraph that we need to acquire. When we
  23. # see two or more P, we reduce the number by one, append the recently acquired
  24. # paragraph to the pattern space, then hold the whole thing and delete the
  25. # pattern space. This puts the most recent paragraph into the hold buffer and
  26. # starts the process over with paragraph accumulation.
  27. # When discovering that we need, e.g., three more paragraphs, we can do the
  28. # following:
  29. #
  30. # s/^/::PPP::/
  31. # G
  32. # h
  33. # d
  34. #
  35. # This prefixes the current paragraph with the number of paragraphs needed,
  36. # appends the contents of the hold space (a single newline after paragraph
  37. # processing), puts everything back into the hold space, and deletes the
  38. # pattern space (looping back to the beginning of the script, where paragraph
  39. # processing begins). See "needonemore" for a convenience label that you can
  40. # branch to for adding one paragraph.
  41. /^::P\(P\{1,\}\)::/{
  42. s//::\1::/
  43. G
  44. h
  45. d
  46. }
  47. # If we have exactly one P, then we swap it out for a zero and let processing
  48. # continue (after :start).
  49. /^::P::/{
  50. s//::0::/
  51. G
  52. }
  53. b start
  54. # Convenience subroutines
  55. :needonemore
  56. s/^/::P::/
  57. G
  58. h
  59. d
  60. :needtwomore
  61. s/^/::PP::/
  62. G
  63. h
  64. d
  65. :needthreemore
  66. s/^/::PPP::/
  67. G
  68. h
  69. d
  70. # Start regular processing (this file is intended to be a preamble)
  71. :start