newline.mjs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Proceess '\n'
  2. import { isSpace } from '../common/utils.mjs'
  3. export default function newline (state, silent) {
  4. let pos = state.pos
  5. if (state.src.charCodeAt(pos) !== 0x0A/* \n */) { return false }
  6. const pmax = state.pending.length - 1
  7. const max = state.posMax
  8. // ' \n' -> hardbreak
  9. // Lookup in pending chars is bad practice! Don't copy to other rules!
  10. // Pending string is stored in concat mode, indexed lookups will cause
  11. // convertion to flat mode.
  12. if (!silent) {
  13. if (pmax >= 0 && state.pending.charCodeAt(pmax) === 0x20) {
  14. if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 0x20) {
  15. // Find whitespaces tail of pending chars.
  16. let ws = pmax - 1
  17. while (ws >= 1 && state.pending.charCodeAt(ws - 1) === 0x20) ws--
  18. state.pending = state.pending.slice(0, ws)
  19. state.push('hardbreak', 'br', 0)
  20. } else {
  21. state.pending = state.pending.slice(0, -1)
  22. state.push('softbreak', 'br', 0)
  23. }
  24. } else {
  25. state.push('softbreak', 'br', 0)
  26. }
  27. }
  28. pos++
  29. // skip heading spaces for next line
  30. while (pos < max && isSpace(state.src.charCodeAt(pos))) { pos++ }
  31. state.pos = pos
  32. return true
  33. }