htmltruncate.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. #!/usr/bin/env python
  2. # Copyright (c) 2015 Eric Entzel
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. # The above copyright notice and this permission notice shall be included in all
  10. # copies or substantial portions of the Software.
  11. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17. # SOFTWARE.
  18. from __future__ import print_function
  19. import sys
  20. END = -1
  21. # HTML5 void-elements that do not require a closing tag
  22. # https://html.spec.whatwg.org/multipage/syntax.html#void-elements
  23. VOID_ELEMENTS = ('area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
  24. 'link', 'meta', 'param', 'source', 'track', 'wbr')
  25. class UnbalancedError(Exception):
  26. pass
  27. class OpenTag:
  28. def __init__(self, tag, rest=''):
  29. self.tag = tag
  30. self.rest = rest
  31. def as_string(self):
  32. return '<' + self.tag + self.rest + '>'
  33. class CloseTag(OpenTag):
  34. def as_string(self):
  35. return '</' + self.tag + '>'
  36. class SelfClosingTag(OpenTag):
  37. pass
  38. class Tokenizer:
  39. def __init__(self, input):
  40. self.input = input
  41. self.counter = 0 # points at the next unconsumed character of the input
  42. def __next_char(self):
  43. self.counter += 1
  44. return self.input[self.counter]
  45. def next_token(self):
  46. try:
  47. char = self.input[self.counter]
  48. self.counter += 1
  49. if char == '&':
  50. return self.__entity()
  51. elif char != '<':
  52. return char
  53. elif self.input[self.counter] == '/':
  54. self.counter += 1
  55. return self.__close_tag()
  56. else:
  57. return self.__open_tag()
  58. except IndexError:
  59. return END
  60. def __entity(self):
  61. """Return a token representing an HTML character entity.
  62. Precondition: self.counter points at the charcter after the &
  63. Postcondition: self.counter points at the character after the ;
  64. """
  65. char = self.input[self.counter]
  66. entity = ['&']
  67. while char != ';':
  68. entity.append(char)
  69. char = self.__next_char()
  70. entity.append(';')
  71. self.counter += 1
  72. return ''.join(entity)
  73. def __open_tag(self):
  74. """Return an open/close tag token.
  75. Precondition: self.counter points at the first character of the tag name
  76. Postcondition: self.counter points at the character after the <tag>
  77. """
  78. char = self.input[self.counter]
  79. tag = []
  80. rest = []
  81. while char != '>' and char != ' ':
  82. tag.append(char)
  83. char = self.__next_char()
  84. while char != '>':
  85. rest.append(char)
  86. char = self.__next_char()
  87. if self.input[self.counter - 1] == '/':
  88. self.counter += 1
  89. return SelfClosingTag( ''.join(tag), ''.join(rest) )
  90. elif ''.join(tag) in VOID_ELEMENTS:
  91. self.counter += 1
  92. return SelfClosingTag( ''.join(tag), ''.join(rest) )
  93. else:
  94. self.counter += 1
  95. return OpenTag( ''.join(tag), ''.join(rest) )
  96. def __close_tag(self):
  97. """Return an open/close tag token.
  98. Precondition: self.counter points at the first character of the tag name
  99. Postcondition: self.counter points at the character after the <tag>
  100. """
  101. char = self.input[self.counter]
  102. tag = []
  103. while char != '>':
  104. tag.append(char)
  105. char = self.__next_char()
  106. self.counter += 1
  107. return CloseTag( ''.join(tag) )
  108. def truncate(str, target_len, ellipsis = ''):
  109. """Returns a copy of str truncated to target_len characters,
  110. preserving HTML markup (which does not count towards the length).
  111. Any tags that would be left open by truncation will be closed at
  112. the end of the returned string. Optionally append ellipsis if
  113. the string was truncated."""
  114. stack = [] # open tags are pushed on here, then popped when the matching close tag is found
  115. retval = [] # string to be returned
  116. length = 0 # number of characters (not counting markup) placed in retval so far
  117. tokens = Tokenizer(str)
  118. tok = tokens.next_token()
  119. while tok != END:
  120. if not length < target_len:
  121. retval.append(ellipsis)
  122. break
  123. if tok.__class__.__name__ == 'OpenTag':
  124. stack.append(tok)
  125. retval.append( tok.as_string() )
  126. elif tok.__class__.__name__ == 'CloseTag':
  127. if stack[-1].tag == tok.tag:
  128. stack.pop()
  129. retval.append( tok.as_string() )
  130. else:
  131. raise UnbalancedError( tok.as_string() )
  132. elif tok.__class__.__name__ == 'SelfClosingTag':
  133. retval.append( tok.as_string() )
  134. else:
  135. retval.append(tok)
  136. length += 1
  137. tok = tokens.next_token()
  138. while len(stack) > 0:
  139. tok = CloseTag( stack.pop().tag )
  140. retval.append( tok.as_string() )
  141. return ''.join(retval)
  142. if __name__ == "__main__":
  143. try:
  144. while True:
  145. print(truncate(raw_input("> "), int(sys.argv[1])))
  146. except EOFError:
  147. sys.exit(0)