Change the Color Syntax for the Gradio Code Control
Gradio - 2025-07-31
Introduction
All I wanted to do was increase the font size and the color of the comments.
(older eyes, and I've always liked a dim green for comments)
I set off to research the problem for a while on the internet etc... nothing.
Tried the AI mess... same thing, nothing.
Although both agreed, neither knew the answer. :)
Just kept telling me things I already knew. :(
Which was CSS.
I set out to figure out how to change it myself. Since I'm working with Gradio, I made a simple Gradio app to help me figure it out. But once I figured out how to change the font size and comment color, it kinda went on to include the whole syntax for the languge Python.
And during my internet research, there seems to be others facing same exact problem. They want to change the colors for the gr.Code() control.
And since I found no solution myself, out there...
Now, I'd like to share with everyone how simple it is to add to this to most any Gradio app that uses the gr.Code() control for displaying the language Python.
gr.Code() Background.
Gradio uses 'CodeMirror' for the gr.Code() control, Gradio used CodeMirror v5 in Gradio 3.x and 4.x. But Gradio moved to CodeMirror v6 in Gradio 5.x.
The names of the CSS elements that CodeMirror itself uses, changed between CodeMirror v5 and CodeMirror v6. Which creates more CSS values to have to work with.
But I divide them into two. One set of CSS names for each of the two versions needed. I programatically check for which Gradio Version I am running and swap CSS name sets to account for differences between the CSS names in the two versions. (Swapping css name sets, leads to something else later on.)
But a 'CSS name set' as I am calling it, is, just a variable I've shoved a bunch of CSS text into. Then assign the variable to the 'css' property of Gradio control. I can create a number of these variables with the same, or different style in it. Then assign whichever I choose when program runs or from an external app settings file.
Testing
It has been tested using the following Gradio versions.
| Gradio Version | Pass-Fail | CodeMirror Version |
|---|---|---|
| 3.3.1 | FAIL * | 5 |
| 3.41.2 | PASS | 5 |
| 4.28.3 | PASS | 5 |
| 4.44.0 | PASS | 5 |
| 5.6.0 | PASS | 6 |
| 5.30.0 | PASS | 6 |
| 5.32.0 | PASS | 6 |
| 5.37.0 | PASS | 6 |
| 5.38.0 | PASS | 6 |
| * There was an error indicating that possibly Version 3.3.1 was before the gr.Code() control was introduced? (I did not look into it.) |
||
Demo 1
Filename: gr_Rock_ColorSyntaxHighlight_Demo_v1.pyThis 'Static' demo for Gradio's gr.Code control shows the color syntax highlighting, color customization method, via css for the Python language.
If you want to try changing the colors, edit 'gr_Rock_ColorSyntaxHighlight_Demo_v1.py' before running.
Try it:
python gr_Rock_ColorSyntaxHighlight_Demo_v1.py
# gr_Rock_ColorSyntaxHighlight_Demo_v1.py
# Static Demo for Gradio's gr.Code control
# This demo shows the color syntax highlighting
# Color customization method via css for the Python language
# It is very simple to add to any Gradio gr.Code() app displaying Python.
# 14 variables and 1 small function is all you need to add to your code.
# Let's get started...
# We need to import Gradio obviously.
import gradio as gr
# ===============================================================================
# ===============================================================================
# ===============================================================================
# Colors and Font Size Variables List (14 variables)
# ------------------------------------
# NOTE: THESE are the DEFAULT colors used for the Python language type.
# CHANGE THESE to change colors and font size to your preference.
# These variables are used by the function that creates the custom css code.
# -------------------------------------------------------------------------------
# Main Code window font size and size attribute (I wanted a larger font !) (2)
clrFONTSIZE = 22
clrFONTSIZEATTR = "px"
# Python Default Color Syntax - Color List (12)
clrKEYWORDS = "#fda331"
clrMETHODS = "#b5bd68"
clrVARIABLES = "#6fb3d2"
clrFUNCTIONS = "#fda331"
clrCOMMAS = "#cc99cc"
clrCURLYBRACES = "#cc99cc"
clrNUMBERS = "#fda331"
clrEQUALS = "#cc99cc"
clrSQUAREBRACKETS = "#cc99cc"
clrQUOTEDSTRINGS = "#b5bd68"
clrDOUBLEQUOTEDfSTRINGS = "#8abeb7"
clrCOMMENTS = "#808080"
# Do Not Modify
# Used to build the custom css for the language Python (1 small function)
def create_grcode_css(grcode_elem_id):
global clrFONTSIZE, clrFONTSIZEATTR, clrKEYWORDS, clrMETHODS, clrVARIABLES
global clrFUNCTIONS, clrCOMMAS, clrCURLYBRACES, clrNUMBERS, clrEQUALS
global clrSQUAREBRACKETS, clrQUOTEDSTRINGS, clrDOUBLEQUOTEDfSTRINGS, clrCOMMENTS
python_lang_types = ["KEYWORDS","METHODS","VARIABLES","FUNCTIONS","COMMAS","CURLYBRACES","NUMBERS","EQUALS","SQUAREBRACKETS","QUOTEDSTRINGS","DOUBLEQUOTEDfSTRINGS","COMMENTS"]
fontsize_css= ".cm-editor .cm-content {font-size: " + str(clrFONTSIZE) + clrFONTSIZEATTR + " !important;}"
# get Gradio version
grVersion = gr.__version__
grVs = grVersion.split('.')
grMajorVersion = int(grVs[0])
if grMajorVersion < 5:
# css list for CodeMirror 5, for Gradio Versions 3 and 4.
grcode_css_list = [".ͼ1q {color: " + clrKEYWORDS + ";}", ".ͼ1r {color: " + clrMETHODS + ";}", ".ͼ1s {color: " + clrVARIABLES + ";}",
".ͼ1t {color: " + clrFUNCTIONS + ";}", ".ͼ1w {color: " + clrCOMMAS + ";}", ".ͼ1x {color: " + clrCURLYBRACES + ";}",
".ͼ1z {color: " + clrNUMBERS + ";}", ".ͼ21 {color: " + clrEQUALS + ";}",".ͼ23 {color: " + clrSQUAREBRACKETS + ";}",
".ͼ28 {color: " + clrQUOTEDSTRINGS + ";}", ".ͼ2a {color: " + clrDOUBLEQUOTEDfSTRINGS + ";}", ".ͼ2c {color: " + clrCOMMENTS + "; font-style: italic;}"]
else:
# css list for CodeMirror 6, for Gradio Version 5.
grcode_css_list = [".ͼp {color: " + clrKEYWORDS + ";}", ".ͼq {color: " + clrMETHODS + ";}", ".ͼr {color: " + clrVARIABLES + ";}",
".ͼs {color: " + clrFUNCTIONS + ";}", ".ͼv {color: " + clrCOMMAS + ";}", ".ͼw {color: " + clrCURLYBRACES + ";}",
".ͼy {color: " + clrNUMBERS + ";}", ".ͼ10 {color: " + clrEQUALS + ";}",".ͼ12 {color: " + clrSQUAREBRACKETS + ";}",
".ͼ17 {color: " + clrQUOTEDSTRINGS + ";}", ".ͼ19 {color: " + clrDOUBLEQUOTEDfSTRINGS + ";}", ".ͼ1b {color: " + clrCOMMENTS + "; font-style: italic;}"]
# make a header comment, findable in the sea of css source, helpful note of version for debugging?
grcode_css = f"/* Rock's CSS for the Python language using the gr.Code Control - Running Gradio Version: {grVersion}*/\n"
# add on the css for the main code font size
grcode_css = grcode_css + f"#{grcode_elem_id} {fontsize_css} /* MAIN FONT SIZE */\n"
# add the css for each of the colors in the Color List, for the Python language type
for i in range(len(python_lang_types)):
lang_type = python_lang_types[i]
css = grcode_css_list[i]
grcode_css = grcode_css + f"#{grcode_elem_id} {css} /* {lang_type} */\n"
return grcode_css
# Build the css string we are going to use when we initialize gr.Blocks()
# The name you gave the 'elem_id' of the gr.Code control
# is what you pass to 'create_grcode_css()'. I named mine 'rk-code'.
# Can be named most anything that will not conflict with other css in your ui.
# See line below and the the gr.Code control's 'elem_id' as an example.
custom_css = create_grcode_css("rk-code")
# When you build your ui, you initialize gr.Blocks()
# and apply the custom_css code created.
# Here's a trimmed down ui example:
# import gradio as gr
# the 14 variables...
# the 1 small function...
# custom_css = create_grcode_css("rk-code")
# with gr.Blocks(css=custom_css) as demo:
# code_editor = gr.Code(language="python", elem_id="rk-code", interactive=True)
# demo.launch()
# That's it !
# Happy coloring !!
# ===============================================================================
# ===============================================================================
# ===============================================================================
# The rest is:
# The Gradio gr.Blocks() section.
# A function 'load_myself()' to load 'this' file in the editor.
# So when the ui is loaded, there is some code to actually look at.
def load_myself():
"""
Loads MySelf. Obviously. And it's another type of syntax... triple quotes...
"""
try:
with open(__file__, 'r') as f:
return f.read()
except Exception as e:
return f"Error loading file: {e}"
return ""
# Build ui
with gr.Blocks(css=custom_css) as demo:
# My ui title header
gr.HTML("Rock's Demo for Gradio's gr.Code to Change Color Syntax Highlighting Colors via CSS - Running Gradio Version: " + gr.__version__)
# The actual gr.Code() editor control
code_editor = gr.Code(language="python", elem_id="rk-code", interactive=True, lines=15)
# Run this when the app loads - Load 'this' file into 'code_editor'.
demo.load(load_myself, inputs=[], outputs=[code_editor])
# Launch the ui
demo.launch()
# -EOF-
Demo 2
Filename: gr_Rock_ColorSyntaxHighlight_Demo_v2.pyFilename: gr_Rock_CodeColors.py
In the second 'Static' demo I placed the functional part of creating the css outside the app, and import it from the external file: 'gr_Rock_CodeColors.py' and I import the function: 'create_grcode_css()' from it.
Makes your main file smaller, and the color syntax code is out of the way.
If you want to try changing the colors, edit 'gr_Rock_CodeColors.py' before running.
Try it:
python gr_Rock_ColorSyntaxHighlight_Demo_v2.py
# gr_Rock_ColorSyntaxHighlight_Demo_v2.py
# Static Demo for Gradio's gr.Code control
# This shows the color syntax highlighting
# Color customization method via css for the Python language
# In this second demo we place the functional part of creating the css
# outside the app, and import it from an external file
# from filename: gr_Rock_CodeColors.py we import the function: create_grcode_css()
# It is very simple to add to any Gradio gr.Code() app displaying Python.
# 14 variables and 1 small function is all you need to add to your code.
# Let's get started...
# We need to import Gradio obviously.
import gradio as gr
# import our custom css creation utils
from gr_Rock_CodeColors import create_grcode_css
# Build the css string we are going to use when we initialize gr.Blocks()
# The name you gave the 'elem_id' of the gr.Code control
# is what you pass to 'create_grcode_css()'. I named mine 'rk-code'.
# Can be named most anything that will not conflict with other css in your ui.
# See line below and the the gr.Code control's 'elem_id' as an example.
custom_css = create_grcode_css("rk-code")
# When you build your ui, you initialize gr.Blocks()
# and apply the custom_css code created.
# Here's an even more trimmed down ui example:
# import gradio as gr
# from gr_Rock_CodeColors import create_grcode_css
# custom_css = create_grcode_css("rk-code")
# with gr.Blocks(css=custom_css) as demo:
# code_editor = gr.Code(language="python", elem_id="rk-code", interactive=True)
# demo.launch()
# That's it !
# Happy coloring and coding !!
# ===============================================================================
# ===============================================================================
# ===============================================================================
# The rest is:
# The Gradio gr.Blocks() section.
# A function 'load_myself()' to load 'this' file in the editor.
# So when the ui is loaded, there is some code to actually look at.
def load_myself():
"""
Loads MySelf. Obviously. And it's another type of syntax... triple quotes...
"""
try:
with open(__file__, 'r') as f:
return f.read()
except Exception as e:
return f"Error loading file: {e}"
return ""
# Build ui
with gr.Blocks(css=custom_css) as demo:
# My ui title header
gr.HTML("Rock's Demo for gr.Code to Change Color Syntax Highlighting Colors via CSS - Running Gradio Version: " + gr.__version__)
# The actual gr.Code() editor control
code_editor = gr.Code(language="python", elem_id="rk-code", interactive=True, lines=15)
# Run this when the app loads - Load 'this' file into 'code_editor'.
demo.load(load_myself, inputs=[], outputs=[code_editor])
# Launch the ui
demo.launch()
# -EOF-
# this import only needed for gr.__version__
import gradio as gr
# ===============================================================================
# ===============================================================================
# ===============================================================================
# Colors and Font Size Variables List (14 variables)
# ------------------------------------
# NOTE: THESE are the DEFAULT colors used for the Python language type.
# CHANGE THESE to change colors and font size to your preference.
# These variables are used by the function that creates the custom css code.
# -------------------------------------------------------------------------------
# Main Code window font size and size attribute (I wanted a larger font !)
clrFONTSIZE = 22
clrFONTSIZEATTR = "px"
# Python Color Syntax - Color List (12)
clrKEYWORDS = "#fda331"
clrMETHODS = "#b5bd68"
clrVARIABLES = "#6fb3d2"
clrFUNCTIONS = "#fda331"
clrCOMMAS = "#cc99cc"
clrCURLYBRACES = "#cc99cc"
clrNUMBERS = "#fda331"
clrEQUALS = "#cc99cc"
clrSQUAREBRACKETS = "#cc99cc"
clrQUOTEDSTRINGS = "#b5bd68"
clrDOUBLEQUOTEDfSTRINGS = "#8abeb7"
clrCOMMENTS = "#808080"
# Do Not Modify
# Used to build the custom css for the language Python (1 small function)
def create_grcode_css(grcode_elem_id):
global clrFONTSIZE, clrFONTSIZEATTR, clrKEYWORDS, clrMETHODS, clrVARIABLES
global clrFUNCTIONS, clrCOMMAS, clrCURLYBRACES, clrNUMBERS, clrEQUALS
global clrSQUAREBRACKETS, clrQUOTEDSTRINGS, clrDOUBLEQUOTEDfSTRINGS, clrCOMMENTS
python_lang_types = ["KEYWORDS","METHODS","VARIABLES","FUNCTIONS","COMMAS","CURLYBRACES","NUMBERS","EQUALS","SQUAREBRACKETS","QUOTEDSTRINGS","DOUBLEQUOTEDfSTRINGS","COMMENTS"]
fontsize_css= ".cm-editor .cm-content {font-size: " + str(clrFONTSIZE) + clrFONTSIZEATTR + " !important;}"
# get Gradio version
grVersion = gr.__version__
grVs = grVersion.split('.')
grMajorVersion = int(grVs[0])
if grMajorVersion < 5:
# css list for CodeMirror 5, for Gradio Versions 3 and 4.
grcode_css_list = [".ͼ1q {color: " + clrKEYWORDS + ";}", ".ͼ1r {color: " + clrMETHODS + ";}", ".ͼ1s {color: " + clrVARIABLES + ";}",
".ͼ1t {color: " + clrFUNCTIONS + ";}", ".ͼ1w {color: " + clrCOMMAS + ";}", ".ͼ1x {color: " + clrCURLYBRACES + ";}",
".ͼ1z {color: " + clrNUMBERS + ";}", ".ͼ21 {color: " + clrEQUALS + ";}",".ͼ23 {color: " + clrSQUAREBRACKETS + ";}",
".ͼ28 {color: " + clrQUOTEDSTRINGS + ";}", ".ͼ2a {color: " + clrDOUBLEQUOTEDfSTRINGS + ";}", ".ͼ2c {color: " + clrCOMMENTS + "; font-style: italic;}"]
else:
# css list for CodeMirror 6, for Gradio Version 5.
grcode_css_list = [".ͼp {color: " + clrKEYWORDS + ";}", ".ͼq {color: " + clrMETHODS + ";}", ".ͼr {color: " + clrVARIABLES + ";}",
".ͼs {color: " + clrFUNCTIONS + ";}", ".ͼv {color: " + clrCOMMAS + ";}", ".ͼw {color: " + clrCURLYBRACES + ";}",
".ͼy {color: " + clrNUMBERS + ";}", ".ͼ10 {color: " + clrEQUALS + ";}",".ͼ12 {color: " + clrSQUAREBRACKETS + ";}",
".ͼ17 {color: " + clrQUOTEDSTRINGS + ";}", ".ͼ19 {color: " + clrDOUBLEQUOTEDfSTRINGS + ";}", ".ͼ1b {color: " + clrCOMMENTS + "; font-style: italic;}"]
# make a header comment, findable in the sea of css source, helpful note of version for debugging?
grcode_css = f"/* Rock's CSS for the Python language using the gr.Code Control - Running Gradio Version: {grVersion}*/\n"
# add on the css for the main code font size
grcode_css = grcode_css + f"#{grcode_elem_id} {fontsize_css} /* MAIN FONT SIZE */\n"
# add the css for each of the colors in the Color List, for the Python language type
for i in range(len(python_lang_types)):
lang_type = python_lang_types[i]
css = grcode_css_list[i]
grcode_css = grcode_css + f"#{grcode_elem_id} {css} /* {lang_type} */\n"
return grcode_css
Smallest 'Static' Example (Based on Demo 2)
1. Modify 'gr_Rock_CodeColors' to change the colors to suit.
2. Then start the app listed below and just paste some code into the code edit window.
Here's a very trimmed down ui example:
import gradio as gr
from gr_Rock_CodeColors import create_grcode_css
custom_css = create_grcode_css("rk-code")
with gr.Blocks(css=custom_css) as demo:
code_editor = gr.Code(language="python", elem_id="rk-code", interactive=True)
demo.launch()
Live Demo 3
Filename: gr_Rock_ColorSyntaxHighlight_LiveDemo_v3.py
In this third demo, is the tool I made to figure this all out.
- It loads, itself.
- It saves, itself.
And has enough 'css' code to get it going for Gradio Version 5.0 and higher. You would have to change the CSS name(s) in the code to get it to work on Gradio Versions older than v5.0.
I start it from the command line via gradio's reload method like so:
gradio gr_Rock_ColorSyntaxHighlight_LiveDemo_v3.py
# gr_Rock_ColorSyntaxHighlight_LiveDemo_v3.py
# You can edit this code, live, used Gradio's reload feature
# I used this to figure out Gradio's gr.Code
# control color syntax highlighting css.
#
import gradio as gr
# A function to load 'this' file in the editor. Loaded when the ui is loaded.
def load_myself():
try:
with open(__file__, 'r') as f:
return f.read()
except Exception as e:
gr.Info(f"Error loading file: {e}", duration=5.0, title="Error Loading")
# A function to save file in the editor.
def save_myself(content):
try:
with open(__file__, 'w') as f:
f.write(content)
except Exception as e:
gr.Info(f"Error saving file: {e}", duration=5.0, title="Error Saving")
# In the very begining, there was this part... only...
# But, I used Gradio's 'reload' feature, then just did the normal
# Run, Debug, Edit, Save (Gradio reloads) Run, Debug, Edit...
# Just to figure out this small bit of code below, then the rest of the names...
custom_css = """
#rk-code .cm-editor .cm-content {font-size: 22px !important;} /* FONTSIZE - 22px */
#rk-code .ͼ1b {color: #559955; font-style: italic;} /* COMMENTS - DIM GREEN*/
"""
# Build the ui.
with gr.Blocks(css=custom_css) as demo:
gr.HTML("Rock's LIVE - Demo for Gradio gr.Code to Change Color Syntax Highlighting Colors - Running Gradio Version: " + gr.__version__)
save_button = gr.Button("Save Changes")
code_editor = gr.Code(language="python", value="", interactive=True, lines=15, elem_id="rk-code")
save_button.click(save_myself, inputs=code_editor, outputs=None)
# Run this when the app loads - Load 'this' file into 'code_editor'.
demo.load(load_myself, inputs=[], outputs=[code_editor])
# Launch the ui
demo.launch()
# -EOF-
Try and edit something in the CSS, and when you save your code changes, a few moments later, after Gradio detects the change and reloads the program, you'll see the changes.
'This program', and the 'F12 key' in my browser to inspect the CSS elements and code, is what I used to get all the CSS names, in both variations of the CSS in Gradio. Plus all of the testing. (This program became a very useful too. I'm sure I'll be using it again)
I still had to find a way to reload color changes without reloading or re-starting the app !
Although this is what I refer to as 'static' and is fine for apps which need no color change while running. Also, a lot of users are ok with saving color settings, then re-starting the app. Demo 1 and Demo 2 is ok for that type of 'static' application. And Demo 3 uses reload which you can not use (should not) in production.
Dynamic Demo 4
Filename: gr_Rock_ColorSyntaxHighlight_DynamicDemo_v4.pyI use gr.Blocks() for most of my Gradio interfaces, and you can not 'update' blocks. Which is why the app has been 'static', up until now.
I figured out that if I embed my custom CSS in an gr.HTML() control, the gr.HTML() control WILL update when I reassign the custom css to it. And therefore update the CSS in my app (on the web page). And therefore change the colors in the gr.Code() control without reloading the app. You can probably use an existing (in your app) gr.HTML() control since the CSS names are different from everything else.
I have LIVE dynamic updating colors !!! :)
Try it:
python gr_Rock_ColorSyntaxHighlight_DynamicDemo_v4.py
# gr_Rock_ColorSyntaxHighlight_DynamicDemo_v4.py
# Dynamic Demo for Gradio's gr.Code control
# This shows the color syntax highlighting
# Color customization method via css for the Python language
# In this fourth demo we create two different css variables.
# each variable with a different color for the COMMENTS in Python.
# Then we load that css as the css for a gr.HTML() control.
# Then we just update the gr.HTML() control. No reloading Gradio !
# So now dynamic updating is very simple to add to any Gradio gr.Code() app displaying Python.
# 14 variables, 1 small function and a gr.HTML() control is all you need to add to your code.
# You can probably use an existing gr.HTML() control in your project,
# since the css is targeting by the document 'element id'.
# Let's get started...
# We need to import Gradio obviously.
import gradio as gr
# ===============================================================================
# ===============================================================================
# ===============================================================================
# (14 variables)
# Main Code window font size and size attribute (I wanted a larger font !) (2)
clrFONTSIZE = 22
clrFONTSIZEATTR = "px"
# Python Default Color Syntax - Color List (12)
clrKEYWORDS = "#fda331"
clrMETHODS = "#b5bd68"
clrVARIABLES = "#6fb3d2"
clrFUNCTIONS = "#fda331"
clrCOMMAS = "#cc99cc"
clrCURLYBRACES = "#cc99cc"
clrNUMBERS = "#fda331"
clrEQUALS = "#cc99cc"
clrSQUAREBRACKETS = "#cc99cc"
clrQUOTEDSTRINGS = "#b5bd68"
clrDOUBLEQUOTEDfSTRINGS = "#8abeb7"
clrCOMMENTS = "#808080"
# Do Not Modify
# Used to build the custom css for the language Python (1 small function)
def create_grcode_css(grcode_elem_id):
global clrFONTSIZE, clrFONTSIZEATTR, clrKEYWORDS, clrMETHODS, clrVARIABLES
global clrFUNCTIONS, clrCOMMAS, clrCURLYBRACES, clrNUMBERS, clrEQUALS
global clrSQUAREBRACKETS, clrQUOTEDSTRINGS, clrDOUBLEQUOTEDfSTRINGS, clrCOMMENTS
python_lang_types = ["KEYWORDS","METHODS","VARIABLES","FUNCTIONS","COMMAS","CURLYBRACES","NUMBERS","EQUALS","SQUAREBRACKETS","QUOTEDSTRINGS","DOUBLEQUOTEDfSTRINGS","COMMENTS"]
fontsize_css= ".cm-editor .cm-content {font-size: " + str(clrFONTSIZE) + clrFONTSIZEATTR + " !important;}"
# get Gradio version
grVersion = gr.__version__
grVs = grVersion.split('.')
grMajorVersion = int(grVs[0])
if grMajorVersion < 5:
# css list for CodeMirror 5, for Gradio Versions 3 and 4.
grcode_css_list = [".ͼ1q {color: " + clrKEYWORDS + ";}", ".ͼ1r {color: " + clrMETHODS + ";}", ".ͼ1s {color: " + clrVARIABLES + ";}",
".ͼ1t {color: " + clrFUNCTIONS + ";}", ".ͼ1w {color: " + clrCOMMAS + ";}", ".ͼ1x {color: " + clrCURLYBRACES + ";}",
".ͼ1z {color: " + clrNUMBERS + ";}", ".ͼ21 {color: " + clrEQUALS + ";}",".ͼ23 {color: " + clrSQUAREBRACKETS + ";}",
".ͼ28 {color: " + clrQUOTEDSTRINGS + ";}", ".ͼ2a {color: " + clrDOUBLEQUOTEDfSTRINGS + ";}", ".ͼ2c {color: " + clrCOMMENTS + "; font-style: italic;}"]
else:
# css list for CodeMirror 6, for Gradio Version 5.
grcode_css_list = [".ͼp {color: " + clrKEYWORDS + ";}", ".ͼq {color: " + clrMETHODS + ";}", ".ͼr {color: " + clrVARIABLES + ";}",
".ͼs {color: " + clrFUNCTIONS + ";}", ".ͼv {color: " + clrCOMMAS + ";}", ".ͼw {color: " + clrCURLYBRACES + ";}",
".ͼy {color: " + clrNUMBERS + ";}", ".ͼ10 {color: " + clrEQUALS + ";}",".ͼ12 {color: " + clrSQUAREBRACKETS + ";}",
".ͼ17 {color: " + clrQUOTEDSTRINGS + ";}", ".ͼ19 {color: " + clrDOUBLEQUOTEDfSTRINGS + ";}", ".ͼ1b {color: " + clrCOMMENTS + "; font-style: italic;}"]
# make a header comment, findable in the sea of css source, helpful note of version for debugging?
grcode_css = "\n"
return grcode_css
# Build the css string we are going change the gr.Code() colors with.
# The name you gave the 'elem_id' of the gr.Code control
# is what you pass to 'create_grcode_css()'. I named mine 'rk-code'.
# Can be named most anything that will not conflict with other css in your ui.
# See line below and the the gr.Code control's 'elem_id' as an example.
# we have not changed any colors, so create custom css set with the default colors
custom_css = create_grcode_css("rk-code")
# change a color(s), make another custom css set, with different color(s) set
clrCOMMENTS = "#339933" # change just the 'comment' color to 'dim green'
custom_css2 = create_grcode_css("rk-code")
# ===============================================================================
# ===============================================================================
# ===============================================================================
# The rest is:
# The Gradio gr.Blocks() section.
# A function 'load_myself()' to load 'this' file in the editor.
# So when the ui is loaded, there is some code to actually look at.
def load_myself():
"""
Loads MySelf. Obviously. And it's another type of syntax... triple quotes...
"""
try:
with open(__file__, 'r') as f:
return f.read()
except Exception as e:
return f"Error loading file: {e}"
return ""
# we just return the css style variable - default colors
def change_comment_color():
global custom_css
return custom_css
# we just return the css style variable - changed colors
def change_comment_color2():
global custom_css2
return custom_css2
# Build ui
with gr.Blocks() as demo:
# My ui (long winded) title header
gr.HTML("Rock's Demo for Gradio's gr.Code to Dynamically Change Color Syntax Highlighting Colors via CSS - Running Gradio Version: " + gr.__version__)
change_comment_button = gr.Button("Change Comment to Default")
change_comment_button2 = gr.Button("Change Comment to Dim Green")
# The nothing in it but 'STYLE' gr.HTML() control
# I use the gr.HTML() to embed the custom css
# When this component updates, the style changes
# I suppose I could locate it anywhere, but I keep it beside the gr.Code() control :)
dynamic_css_html = gr.HTML(custom_css, min_height=1, max_height=1, padding=False)
# The actual gr.Code() editor control
code_editor = gr.Code(language="python", elem_id="rk-code", interactive=True, lines=15)
change_comment_button.click(change_comment_color, inputs=[], outputs=[dynamic_css_html])
change_comment_button2.click(change_comment_color2, inputs=[], outputs=[dynamic_css_html])
# Run this when the app loads - Load 'this' file into 'code_editor'.
demo.load(load_myself, inputs=[], outputs=[code_editor])
# Launch the ui
demo.launch()
# -EOF-
Swapping css name sets gives me the ability to jump between color schemes.
(This could be carried further to have external files, JSON with the color values, and load them on the fly from the JSON files.)
That is what I did to demo the LIVE dynamic ability of changing the colors.
I created two seperate custom css variables, holding different colors sets for the syntax. And then I swap which css is used. And apply it to the gr.HTML() value, and that updates the css for the gr.Code() control.
The same function 'create_grcode_css()' is used to create both custom css variables with the css in it.
Live Dynamic Demo 5
Filename: gr_Rock_ColorSyntaxHighlight_LiveDynamicDemo_v5.py
Changes from Dynamic Demo 4
- Removed creating of the second custom css.
- Added a color picker in the ui.
- Now watch the 'COMMENTS' color change in the code window LIVE, while you move the color picker. :)
Try it:
python gr_Rock_ColorSyntaxHighlight_LiveDynamicDemo_v5.py
# gr_Rock_ColorSyntaxHighlight_LiveDynamicDemo_v5.py
# Dynamic Demo for Gradio's gr.Code control
# This shows the color syntax highlighting
# Color customization method via css for the Python language
# In this fifth demo we create a css variable with the default colors.
# Added a color picker for the Comments color and use that color to create the second css.
# Then we load that css as the css for a gr.HTML() control. LIVE.
# Then we just update the gr.HTML() control. No reloading Gradio !
# So now live dynamic updating is very simple to add to any Gradio gr.Code() app displaying Python.
# 14 variables, 1 small function and a gr.HTML() control is all you need to add to your code.
# You can probably use an existing gr.HTML() control in your project,
# since the css is targeting by the document 'element id'.
# Let's get started...
# We need to import Gradio obviously.
import gradio as gr
# ===============================================================================
# ===============================================================================
# ===============================================================================
# (14 variables)
# Main Code window font size and size attribute (I wanted a larger font !) (2)
clrFONTSIZE = 22
clrFONTSIZEATTR = "px"
# Python Default Color Syntax - Color List (12)
clrKEYWORDS = "#fda331"
clrMETHODS = "#b5bd68"
clrVARIABLES = "#6fb3d2"
clrFUNCTIONS = "#fda331"
clrCOMMAS = "#cc99cc"
clrCURLYBRACES = "#cc99cc"
clrNUMBERS = "#fda331"
clrEQUALS = "#cc99cc"
clrSQUAREBRACKETS = "#cc99cc"
clrQUOTEDSTRINGS = "#b5bd68"
clrDOUBLEQUOTEDfSTRINGS = "#8abeb7"
clrCOMMENTS = "#808080"
# Do Not Modify
# Used to build the custom css for the language Python (1 small function)
def create_grcode_css(grcode_elem_id):
global clrFONTSIZE, clrFONTSIZEATTR, clrKEYWORDS, clrMETHODS, clrVARIABLES
global clrFUNCTIONS, clrCOMMAS, clrCURLYBRACES, clrNUMBERS, clrEQUALS
global clrSQUAREBRACKETS, clrQUOTEDSTRINGS, clrDOUBLEQUOTEDfSTRINGS, clrCOMMENTS
python_lang_types = ["KEYWORDS","METHODS","VARIABLES","FUNCTIONS","COMMAS","CURLYBRACES","NUMBERS","EQUALS","SQUAREBRACKETS","QUOTEDSTRINGS","DOUBLEQUOTEDfSTRINGS","COMMENTS"]
fontsize_css= ".cm-editor .cm-content {font-size: " + str(clrFONTSIZE) + clrFONTSIZEATTR + " !important;}"
# get Gradio version
grVersion = gr.__version__
grVs = grVersion.split('.')
grMajorVersion = int(grVs[0])
if grMajorVersion < 5:
# css list for CodeMirror 5, for Gradio Versions 3 and 4.
grcode_css_list = [".ͼ1q {color: " + clrKEYWORDS + ";}", ".ͼ1r {color: " + clrMETHODS + ";}", ".ͼ1s {color: " + clrVARIABLES + ";}",
".ͼ1t {color: " + clrFUNCTIONS + ";}", ".ͼ1w {color: " + clrCOMMAS + ";}", ".ͼ1x {color: " + clrCURLYBRACES + ";}",
".ͼ1z {color: " + clrNUMBERS + ";}", ".ͼ21 {color: " + clrEQUALS + ";}",".ͼ23 {color: " + clrSQUAREBRACKETS + ";}",
".ͼ28 {color: " + clrQUOTEDSTRINGS + ";}", ".ͼ2a {color: " + clrDOUBLEQUOTEDfSTRINGS + ";}", ".ͼ2c {color: " + clrCOMMENTS + "; font-style: italic;}"]
else:
# css list for CodeMirror 6, for Gradio Version 5.
grcode_css_list = [".ͼp {color: " + clrKEYWORDS + ";}", ".ͼq {color: " + clrMETHODS + ";}", ".ͼr {color: " + clrVARIABLES + ";}",
".ͼs {color: " + clrFUNCTIONS + ";}", ".ͼv {color: " + clrCOMMAS + ";}", ".ͼw {color: " + clrCURLYBRACES + ";}",
".ͼy {color: " + clrNUMBERS + ";}", ".ͼ10 {color: " + clrEQUALS + ";}",".ͼ12 {color: " + clrSQUAREBRACKETS + ";}",
".ͼ17 {color: " + clrQUOTEDSTRINGS + ";}", ".ͼ19 {color: " + clrDOUBLEQUOTEDfSTRINGS + ";}", ".ͼ1b {color: " + clrCOMMENTS + "; font-style: italic;}"]
# make a header comment, findable in the sea of css source, helpful note of version for debugging?
grcode_css = "\n"
return grcode_css
# Build the css string we are going change the gr.Code() colors with.
# The name you gave the 'elem_id' of the gr.Code control
# is what you pass to 'create_grcode_css()'. I named mine 'rk-code'.
# Can be named most anything that will not conflict with other css in your ui.
# See line below and the the gr.Code control's 'elem_id' as an example.
# we have not changed any colors, so create custom css set with the default colors
custom_css = create_grcode_css("rk-code")
# ===============================================================================
# ===============================================================================
# ===============================================================================
# The rest is:
# The Gradio gr.Blocks() section.
# A function 'load_myself()' to load 'this' file in the editor.
# So when the ui is loaded, there is some code to actually look at.
def load_myself():
"""
Loads MySelf. Obviously. And it's another type of syntax... triple quotes...
"""
try:
with open(__file__, 'r') as f:
return f.read()
except Exception as e:
return f"Error loading file: {e}"
return ""
# we just return the css style variable - default colors
def change_comment_color():
global custom_css
return custom_css
# my standard color picker function
# supposed to return hex...
def pick(color):
global clrCOMMENTS
if color.startswith("#"):
clrCOMMENTS = color
return create_grcode_css("rk-code")
try:
rgba_values = [float(x.strip()) for x in color.replace('rgba(', '').replace(')', '').split(',')]
r, g, b, a = rgba_values
hex_color = "#{:02x}{:02x}{:02x}".format(int(r), int(g), int(b))
clrCOMMENTS = hex_color
return create_grcode_css("rk-code")
except (ValueError, IndexError):
clrCOMMENTS = ""
return create_grcode_css("rk-code")
# Build ui
with gr.Blocks() as demo:
# My ui (long winded) title header
gr.HTML("Rock's Live Demo for Gradio's gr.Code to Dynamically Change Color Syntax Highlighting Colors via CSS - Running Gradio Version: " + gr.__version__)
change_comment_button = gr.Button("Change COMMENTS to Default")
mycolor = gr.ColorPicker(label="Choose COMMENTS Color")
# The nothing in it but 'STYLE' gr.HTML() control
# I use the gr.HTML() to embed the custom css
# When this component updates, the style changes
# I suppose I could locate it anywhere, but I keep it beside the gr.Code() control :)
dynamic_css_html = gr.HTML(custom_css, min_height=1, max_height=1, padding=False)
# The actual gr.Code() editor control
code_editor = gr.Code(language="python", elem_id="rk-code", interactive=True, lines=15)
change_comment_button.click(change_comment_color, inputs=[], outputs=[dynamic_css_html])
mycolor.change(pick, inputs=[mycolor], outputs=[dynamic_css_html])
# Run this when the app loads - Load 'this' file into 'code_editor'.
demo.load(load_myself, inputs=[], outputs=[code_editor])
# Launch the ui
demo.launch()
# -EOF-
Fin
That's it !
You can now incorporate changing the syntax highlighted colors, 'on-the-fly', with Gradio's gr.Code() control for the Python language.
Happy coloring !!
You can download the whole thing from the repository at GitHub github.com/rock-stevens/change-color-syntax-gradio-code-control