9

I want to capture the mouse selected text from a jupyter text widget .

import ipywidgets as widgets
text = widgets.Textarea(
    value='Hello World',
    description='String:',
    disabled=False
)
display(text)

In the following example when World is selected and left click is complete then I want to capture the text highlighted .

enter image description here

Shakti
  • 2,013
  • 8
  • 27
  • 40
  • 2
    I don't believe it is possible to get the selected portion of text from ipywidgets. – ac24 Jun 01 '20 at 18:36

2 Answers2

5

With a JS you can add listener on select event of the original text widget. Then the selected text is copied into a sel_text widget. Finally you can access it through the sel_text.value

import ipywidgets as widgets
from IPython.display import Javascript

ta_description = 'String:'
text = widgets.Textarea(
    value='Hello big World',
    description=ta_description,
    disabled=False
)
sel_text = widgets.Text(
    value='',
    description='selected text:',
    disabled=True
)
display(text, sel_text)

jscript = f'''

function put2widget(arg) {{
    var manager = window.IPython.WidgetManager._managers[0];
    var ta = manager.get_model('{sel_text.model_id}');
    ta.then(function(model) {{
        model.set('value', arg)
        model.save()
    }});
}}

function getSelection(event) {{
  const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd);
  put2widget(selection)

}}

const area = document.querySelectorAll('label[title="{ta_description}"]')[0].parentNode.getElementsByTagName('textarea')[0]
area.addEventListener("select", getSelection); 

'''

Javascript(jscript)
igrinis
  • 12,398
  • 20
  • 45
-1

There no way to capture or print the mouse selected keyword in Jupyter.