2

Is it possible to access highlighted text via a shell script?

I want to make a keyboard shortcut to use 'espeak' to read highlighted text.

2 Answers 2

2

Yes, this is relatively easy, there are plenty of tools for clipboard manipulation, I've used them for filling in apple device registration and email verification along with xdotool… a lot easier than filling in the form 1000 times…

So, setup a shortcut to be /home/bob/bin/speak.sh

speak.sh:

#!/bin/bash

xclip -o | xclip -selection clipboard -i
xclip -o | espeak
0
1

short: usually you cannot do this (unless the selection was copied to the clipboard)

long: there are a few special cases, e.g., xterm has a feature which (is normally disabled) allows an application to read the selected text via escape sequence. That is described in XTerm Control Sequences:

        Ps = 5 2  -> Manipulate Selection Data.  These controls may
      be disabled using the allowWindowOps resource.  The parameter
      Pt is parsed as
           Pc; Pd
      The first, Pc, may contain zero or more characters from the
      set c  p  s  0  1  2  3  4  5  6  7 .  It is used to construct
      a list of selection parameters for clipboard, primary, select,
      or cut buffers 0 through 7 respectively, in the order given.
      If the parameter is empty, xterm uses s 0 , to specify the
      configurable primary/clipboard selection and cut buffer 0.
      The second parameter, Pd, gives the selection data.  Normally
      this is a string encoded in base64.  The data becomes the new
      selection, which is then available for pasting by other appli-
      cations.
      If the second parameter is a ? , xterm replies to the host
      with the selection data encoded using the same protocol.
      If the second parameter is neither a base64 string nor ? ,
      then the selection is cleared.

That is, if the allowWindowOps resource is enabled, an application could do something like

printf '\033]52;s;?\007'

and read the selection data as a base64 string. But that's a special case.

Some applications of course copy to the clipboard (see FAQ), but not all. For instance rxvt, etc., use the primary selection. There is no solution which would work everywhere.

Further reading:

3
  • Your answer is very misleading. Many applications (including xterm!) expose selected text as the primary selection which is immediately visible to other applications that connect to the same X display. Oct 25, 2016 at 21:57
  • To complete your comment, you should provide an example of a scriptable application which will grab the primary selection as requested by OP. Oct 25, 2016 at 22:16
  • xclip as in the other answer. Or xsel. Oct 25, 2016 at 22:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .