Macro get_word()?

Tony Balinski ajbj at free.fr
Mon Jan 22 14:21:24 CET 2007


Quoting YT Lim <ytlim23 at yahoo.com.au>:

> Has someone implemented a macro routine to perform
> get_word()? I.e. when the cursor is anywhere inside a
> word (delimited by spaces), the routine will return
> the complete word.
>
> /Why Tea

The following looks for word ends rather than delimiting spaces. If you
want contiguous non-space characters (as opposed to non-word characters)
use different regex patterns, eg "(?<=\\s|^)(?=\\S)" of the start of
non-space sequences, and "(?<=\\S)(?=\\s|$)" for the end, instead of
"<", ">" below.

  # get_word_at_pos([pos [, string]]) - return the word at position pos
  #       in the string string. If string is not given, use the current
  #       document's text; if pos is not given, use the current cursor
  #       position in the document. If the position is not at the start,
  #       inside, or at the end of a word, an empty string is returned.

  define get_word_at_pos
    {
    pos = $cursor
    if ($n_args > 0)
      pos = $1
    string = ""
    use_string = 0
    if ($n_args > 1)
      {
      string = $1
      use_string = 1
      }

    # look to start and end of previous word; this must overlap pos
    if (use_string == 0)
      {
      beg = search("<", pos, "regex", "backward")
      end = search(">", beg, "regex")
      word = get_range(beg, end)
      }
    else
      {
      beg = search_string(string, "<", pos, "regex", "backward")
      end = search_string(string, ">", beg, "regex")
      word = substring(string, beg, end)
      }
    if (beg <= pos && pos <= end)
      return word
    return "" # failed
    }





More information about the Discuss mailing list