Identifies and stylizes code in a question or answer.
(soup)
| 209 | |
| 210 | |
| 211 | def stylize_code(soup): |
| 212 | """Identifies and stylizes code in a question or answer.""" |
| 213 | # TODO: Handle blockquotes and markdown |
| 214 | stylized_text = [] |
| 215 | code_blocks = [block.get_text() for block in soup.find_all("code")] |
| 216 | blockquotes = [block.get_text() for block in soup.find_all("blockquote")] |
| 217 | newline = False |
| 218 | |
| 219 | for child in soup.recursiveChildGenerator(): |
| 220 | name = getattr(child, "name", None) |
| 221 | |
| 222 | if name is None: # Leaf (terminal) node |
| 223 | if child in code_blocks: |
| 224 | if newline: # Code block |
| 225 | #if code_blocks.index(child) == len(code_blocks) - 1: # Last code block |
| 226 | #child = child[:-1] |
| 227 | stylized_text.append(("code", u"\n%s" % str(child))) |
| 228 | newline = False |
| 229 | else: # In-line code |
| 230 | stylized_text.append(("code", u"%s" % str(child))) |
| 231 | else: # Plaintext |
| 232 | newline = child.endswith('\n') |
| 233 | stylized_text.append(u"%s" % str(child)) |
| 234 | |
| 235 | if type(stylized_text[-2]) == tuple: |
| 236 | # Remove newline from questions/answers that end with a code block |
| 237 | if stylized_text[-2][1].endswith('\n'): |
| 238 | stylized_text[-2] = ("code", stylized_text[-2][1][:-1]) |
| 239 | |
| 240 | return urwid.Text(stylized_text) |
| 241 | |
| 242 | |
| 243 | def get_search_results(soup): |
no outgoing calls
no test coverage detected
searching dependent graphs…