###########################################################################
###########################################################################
# ABBREV.TCL : GESTION DES ABBREVIATIONS (STATIQUES PLUS UTILISEES)
# ET DYNAMIQUES
###########################################################################
###########################################################################

package provide stead 2.0

## dabbrev_again - search earlier in the text for abbrevs
# 
# Problème : 
# Ce système dépend de la notion de délimiteur de mot en tcl
# Il faudrait définir un préférence associée au modes
# (pour inclure ou non les caractere _ $ - ...)
# 
proc dabbrev_again {{t .main.t}} {


  global stead

  set context [$t get 0.0 $stead(MATCH_POS)]

  while {1} {
    set matchpos [string last $stead(ABBREV) $context]
  
    if {$matchpos == -1} {
      return [sabbrev]			;# try the static table
    }
    $t mark set matchstart [$t index "0.0 +$matchpos chars"]
    if {[$t compare matchstart == {matchstart wordstart}]} {
      $t mark set matchend [$t index {matchstart wordend}]
      break				;# sort of an `until'
    }
    set context [$t get 0.0 matchstart]
  }

  set stead(MATCH) [$t get matchstart matchend]

  set stead(MATCH_POS) [$t index matchstart]

  $t delete $stead(ABBREV_POS) insert
  $t insert insert $stead(MATCH)
  $t insert insert " "

  xtext_markDirty $t

}

######################################################################
# stead:cmd:dabbrev - expand abbreviation before insert
######################################################################

proc stead:cmd:dabbrev {{t .main.t}} {
  # PROBLEM: this depends on the Text widget's notion of words.
  # it would be nice to be able to expand, say, $tk_l to $tk_library.

  global stead

  $t mark set abbrevstart insert
  while {[$t compare abbrevstart != 1.0] &&
         [string match {[a-zA-Z0-9']} [$t get {abbrevstart - 1 char}]]} {
    $t mark set abbrevstart {abbrevstart -1char}
  }

  set stead(ABBREV_POS) [$t index abbrevstart]	;# for dabbrev_again

  set stead(ABBREV) [$t get abbrevstart insert]

  set context [$t get 0.0 abbrevstart]

  while {1} {
    set matchpos [string last $stead(ABBREV) $context]
  
    if {$matchpos == -1} {return 0}	;# not found

    $t mark set matchstart [$t index "0.0 +$matchpos chars"]
    if {[$t compare matchstart == {matchstart wordstart}]} {
      $t mark set matchend [$t index {matchstart wordend}]
      break				;# sort of an `until'
    }
    set context [$t get 0.0 matchstart]
  }

  set stead(MATCH) [$t get matchstart matchend]

  set stead(MATCH_POS) [$t index matchstart]
  xtext_pushState
  $t delete abbrevstart insert
  $t insert insert $stead(MATCH)

  xtext_markDirty $t
  return 1

}



