OLD | NEW |
(Empty) | |
| 1 # Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is govered by a BSD-style |
| 3 # license that can be found in the LICENSE file or at |
| 4 # https://developers.google.com/open-source/licenses/bsd |
| 5 |
| 6 """Helper functions for source code syntax highlighting.""" |
| 7 |
| 8 from third_party import ezt |
| 9 |
| 10 from framework import framework_constants |
| 11 |
| 12 |
| 13 # We only attempt to do client-side syntax highlighting on files that we |
| 14 # expect to be source code in languages that we support, and that are |
| 15 # reasonably sized. |
| 16 MAX_PRETTIFY_LINES = 3000 |
| 17 |
| 18 |
| 19 def PrepareSourceLinesForHighlighting(file_contents): |
| 20 """Parse a file into lines for highlighting. |
| 21 |
| 22 Args: |
| 23 file_contents: string contents of the source code file. |
| 24 |
| 25 Returns: |
| 26 A list of _SourceLine objects, one for each line in the source file. |
| 27 """ |
| 28 return [_SourceLine(num + 1, line) for num, line |
| 29 in enumerate(file_contents.splitlines())] |
| 30 |
| 31 |
| 32 class _SourceLine(object): |
| 33 """Convenience class to represent one line of the source code display. |
| 34 |
| 35 Attributes: |
| 36 num: The line's location in the source file. |
| 37 line: String source code line to display. |
| 38 """ |
| 39 |
| 40 def __init__(self, num, line): |
| 41 self.num = num |
| 42 self.line = line |
| 43 |
| 44 def __str__(self): |
| 45 return '%d: %s' % (self.num, self.line) |
| 46 |
| 47 |
| 48 def BuildPrettifyData(num_lines, path): |
| 49 """Return page data to help configure google-code-prettify. |
| 50 |
| 51 Args: |
| 52 num_lines: int number of lines of source code in the file. |
| 53 path: string path to the file, or just the filename. |
| 54 |
| 55 Returns: |
| 56 Dictionary that can be passed to EZT to render a page. |
| 57 """ |
| 58 reasonable_size = num_lines < MAX_PRETTIFY_LINES |
| 59 |
| 60 filename_lower = path[path.rfind('/') + 1:].lower() |
| 61 ext = filename_lower[filename_lower.rfind('.') + 1:] |
| 62 |
| 63 # Note that '' might be a valid entry in these maps. |
| 64 prettify_class = framework_constants.PRETTIFY_CLASS_MAP.get(ext) |
| 65 if prettify_class is None: |
| 66 prettify_class = framework_constants.PRETTIFY_FILENAME_CLASS_MAP.get( |
| 67 filename_lower) |
| 68 supported_lang = prettify_class is not None |
| 69 |
| 70 return { |
| 71 'should_prettify': ezt.boolean(supported_lang and reasonable_size), |
| 72 'prettify_class': prettify_class, |
| 73 } |
OLD | NEW |