Skip to content

Instantly share code, notes, and snippets.

@lyuma
Created January 29, 2022 22:06
Show Gist options
  • Save lyuma/2a8a4d5ff8f3fb4ff8ee26145492e6fa to your computer and use it in GitHub Desktop.
Save lyuma/2a8a4d5ff8f3fb4ff8ee26145492e6fa to your computer and use it in GitHub Desktop.
Indents and colorizes lines based on the number of levels of preprocessor if statements
# Copyright 2021 Lyuma
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys
import re
re_preprocessor = re.compile(r'^\s*#')
re_if = re.compile(r'^\s*#\s*if')
re_else = re.compile(r'^\s*#\s*el[is][ef]')
re_endif = re.compile(r'^\s*#\s*endif')
indentlevel=0
boldcolor = '\x1b[0;1m'
#colorlist=['\x1b[0;32m', '\x1b[0;33m', '\x1b[0;90m', '\x1b0;1;31m', '\x1b0;1;34m', '\x1b0;1;33m']
colorlist=['\x1b[0;37m', '\x1b[1;30m', '\x1b[0;34m', '\x1b[0;33m', '\x1b[0;35m', '\x1b[0;36m', '\x1b[0;37m', '\x1b[0;32m', '\x1b[0;31m']
isatty = True # sys.stdout.isatty()
linenum = 0
for x in sys.stdin.readlines():
linenum += 1
prefix = colorlist[indentlevel]
if re_preprocessor.match(x):
prefix = boldcolor
if not isatty:
prefix = ''
if re_endif.match(x) or re_else.match(x):
indentlevel -= 1
if indentlevel < 0:
prefix = '\x1b[0;1;7;31m*** ERROR ***'
sys.stdout.write(('% 7d ' % (linenum,)) + ('\t' * indentlevel) + boldcolor + '|' + prefix + x)
if re_if.match(x) or re_else.match(x):
indentlevel += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment