src/Pure/PIDE/text.scala
author wenzelm
Sun Aug 15 23:07:22 2010 +0200 (2010-08-15)
changeset 38427 7066fbd315ae
parent 38426 2858ec7b6dd8
child 38477 f01f4ab2a0af
permissions -rw-r--r--
some derived operations on Text.Range;
     1 /*  Title:      Pure/PIDE/text.scala
     2     Author:     Fabian Immler, TU Munich
     3     Author:     Makarius
     4 
     5 Basic operations on plain text.
     6 */
     7 
     8 package isabelle
     9 
    10 
    11 object Text
    12 {
    13   /* offset and range */
    14 
    15   type Offset = Int
    16 
    17   sealed case class Range(val start: Offset, val stop: Offset)
    18   {
    19     def contains(i: Offset): Boolean = start <= i && i < stop
    20     def map(f: Offset => Offset): Range = Range(f(start), f(stop))
    21     def +(i: Offset): Range = map(_ + i)
    22   }
    23 
    24 
    25   /* editing */
    26 
    27   object Edit
    28   {
    29     def insert(start: Offset, text: String): Edit = new Edit(true, start, text)
    30     def remove(start: Offset, text: String): Edit = new Edit(false, start, text)
    31   }
    32 
    33   class Edit(val is_insert: Boolean, val start: Offset, val text: String)
    34   {
    35     override def toString =
    36       (if (is_insert) "Insert(" else "Remove(") + (start, text).toString + ")"
    37 
    38 
    39     /* transform offsets */
    40 
    41     private def transform(do_insert: Boolean, i: Offset): Offset =
    42       if (i < start) i
    43       else if (is_insert == do_insert) i + text.length
    44       else (i - text.length) max start
    45 
    46     def convert(i: Offset): Offset = transform(true, i)
    47     def revert(i: Offset): Offset = transform(false, i)
    48 
    49 
    50     /* edit strings */
    51 
    52     private def insert(i: Offset, string: String): String =
    53       string.substring(0, i) + text + string.substring(i)
    54 
    55     private def remove(i: Offset, count: Int, string: String): String =
    56       string.substring(0, i) + string.substring(i + count)
    57 
    58     def can_edit(string: String, shift: Int): Boolean =
    59       shift <= start && start < shift + string.length
    60 
    61     def edit(string: String, shift: Int): (Option[Edit], String) =
    62       if (!can_edit(string, shift)) (Some(this), string)
    63       else if (is_insert) (None, insert(start - shift, string))
    64       else {
    65         val i = start - shift
    66         val count = text.length min (string.length - i)
    67         val rest =
    68           if (count == text.length) None
    69           else Some(Edit.remove(start, text.substring(count)))
    70         (rest, remove(i, count, string))
    71       }
    72   }
    73 }