src/Pure/PIDE/text.scala
author wenzelm
Sun Aug 15 21:42:13 2010 +0200 (2010-08-15)
changeset 38425 e467db701d78
parent 38154 src/Pure/PIDE/text_edit.scala@343cb5d4034a
child 38426 2858ec7b6dd8
permissions -rw-r--r--
moved Text_Edit to Text.Edit;
tuned;
     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   /* edits */
    14 
    15   object Edit
    16   {
    17     def insert(start: Int, text: String): Edit = new Edit(true, start, text)
    18     def remove(start: Int, text: String): Edit = new Edit(false, start, text)
    19   }
    20 
    21   class Edit(val is_insert: Boolean, val start: Int, val text: String)
    22   {
    23     override def toString =
    24       (if (is_insert) "Insert(" else "Remove(") + (start, text).toString + ")"
    25 
    26 
    27     /* transform offsets */
    28 
    29     private def transform(do_insert: Boolean, offset: Int): Int =
    30       if (offset < start) offset
    31       else if (is_insert == do_insert) offset + text.length
    32       else (offset - text.length) max start
    33 
    34     def convert(offset: Int): Int = transform(true, offset)
    35     def revert(offset: Int): Int = transform(false, offset)
    36 
    37 
    38     /* edit strings */
    39 
    40     private def insert(index: Int, string: String): String =
    41       string.substring(0, index) + text + string.substring(index)
    42 
    43     private def remove(index: Int, count: Int, string: String): String =
    44       string.substring(0, index) + string.substring(index + count)
    45 
    46     def can_edit(string: String, shift: Int): Boolean =
    47       shift <= start && start < shift + string.length
    48 
    49     def edit(string: String, shift: Int): (Option[Edit], String) =
    50       if (!can_edit(string, shift)) (Some(this), string)
    51       else if (is_insert) (None, insert(start - shift, string))
    52       else {
    53         val index = start - shift
    54         val count = text.length min (string.length - index)
    55         val rest =
    56           if (count == text.length) None
    57           else Some(Edit.remove(start, text.substring(count)))
    58         (rest, remove(index, count, string))
    59       }
    60   }
    61 }