Skip to content

Instantly share code, notes, and snippets.

@mortie
Last active November 2, 2016 20:48
Show Gist options
  • Save mortie/5805c9cd7a9008085a87dc6e926a6f17 to your computer and use it in GitHub Desktop.
Save mortie/5805c9cd7a9008085a87dc6e926a6f17 to your computer and use it in GitHub Desktop.
def highlight_line(syntax, theme, line):
ranges = []
# Checks if rng is in any of the existing ranges
# Ranges are tuples, (start, end, color)
def inRange(rng):
for r in ranges:
if rng[0] >= r[0] and rng[1] <= r[1]:
return True
return False
for s in syntax:
rx, name = s
color = theme[name]
match = rx.match(line)
# Loop through the matches for this particular syntax regex
for match in re.finditer(rx, line):
rng = match.span()
# Append the range and color if it's not in an existing range
if not inRange(rng):
ranges.append((rng[0], rng[1], color))
# Sort the ranges based on their start value
ranges.sort(key=lambda r: r[0])
# Loop through the line
i = 0
while i < len(line):
# If ranges[0][0] (`start` of the first range) matches i,
# write line[start:end] appropriately colored, and put i after the end of the range
if len(ranges) > 0 and ranges[0][0] == i:
start, end, color = ranges.pop(0)
sys.stdout.write(colorize(line[start:end], color))
i = end
# Otherwise, just write a character
else:
sys.stdout.write(line[i])
i += 1
sys.stdout.write("\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment