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