bouzidanas/streamlit-code-editor

Get selected text instead of ALL in Code Editor

anthoniraj opened this issue · 2 comments

There should be an option and shortcut key to retrieve selected text from the code editor. This would be useful when we use code editor for Python or SQL script execution.

New custom command added to Code Editor called "returnSelection" that should return selected text to Streamlit app. You will find this new addition in version 0.1.12

Example Code Editor with button that returned what is selected:

import json
import streamlit as st
from code_editor import code_editor

# code editor config variables
height = [19, 22]
language="python"
theme="default"
shortcuts="vscode"
focus=False
wrap=True

# Button that calls `"returnSelection"` command when clicked.
editor_btns = [{
    "name": "Run",
    "feather": "Play",
    "primary": true,
    "hasText": true,
    "showWithIcon": true,
    "commands": ["returnSelection"],
    "style": {"bottom": "0.44rem", "right": "0.4rem"}
  }]

sample_python_code = '''# This is some sample code
a=2
if a > 1:
    print("The value is greater than 1")
'''

# code editor
response_dict = code_editor(sample_python_code,  height = height, lang=language, theme=theme, shortcuts=shortcuts, focus=focus, buttons=editor_btns, options={"wrap": wrap})

# show response dict
if len(response_dict['id']) != 0 and ( response_dict['type'] == "selection" or response_dict['type'] == "submit" ):
    st.write(response_dict)

Added a new property to the response dictionary that is returned by the code_editor function. This property is called selected and contains the portion of the contents of the editor that is highlighted at the moment of return. I also added an argument to the function called response_mode which allows the editor to send a new response when the text selection changes. To do this, add response_mode="select" as an additional argument to code_editor(). So something like:

import streamlit as st
from code_editor import code_editor
...
response = code_editor(..., `response_mode="select")
st.write(response)

These new additions should allow you to tackle your example use case as well as others.

I will consider this feature request completed!