section_number.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. """
  2. Section number plugin for Pelican
  3. ================================
  4. Adds section numbers to section titles of the article
  5. """
  6. from pelican import signals, contents
  7. def _extract_level(text, idx):
  8. end = text.find(">", idx)
  9. if end == -1:
  10. return (idx, -1)
  11. try:
  12. level = int(text[idx : end])
  13. return (end, level)
  14. except:
  15. return (idx, -1)
  16. def _level_str(level_nums, level_max):
  17. ret = u''
  18. if len(level_nums) > level_max:
  19. return ret
  20. for n in level_nums:
  21. ret += str(n) + '.'
  22. return ret[:-1] + ' '
  23. def _insert_title_number(text, level_max):
  24. ret = u''
  25. idx = 0
  26. levels = []
  27. level_nums = []
  28. while True:
  29. idx = text.find("<h", idx)
  30. if idx == -1:
  31. break
  32. (idx, level) = _extract_level(text, idx + 2)
  33. if level == -1:
  34. continue
  35. if not levels:
  36. levels += [level]
  37. level_nums += [1]
  38. elif level == levels[-1]:
  39. level_nums[-1] += 1
  40. elif level < levels[-1]:
  41. while level < levels[-1]:
  42. levels.pop()
  43. level_nums.pop()
  44. level_nums[-1] += 1
  45. else:
  46. while level > levels[-1]:
  47. levels += [levels[-1] + 1]
  48. level_nums += [1]
  49. text = text[:idx+1] + _level_str(level_nums, level_max) + text[idx+1:]
  50. #print text.encode('gb2312')
  51. return text
  52. def process_content(content):
  53. if content._content is None:
  54. return
  55. level_max = content.settings.get('SECTION_NUMBER_MAX', 3)
  56. if level_max <= 0:
  57. return
  58. content._content = _insert_title_number(content._content, level_max)
  59. def register():
  60. signals.content_object_init.connect(process_content)