38425
|
1 |
/* Title: Pure/PIDE/text.scala
|
34276
|
2 |
Author: Fabian Immler, TU Munich
|
|
3 |
Author: Makarius
|
|
4 |
|
38425
|
5 |
Basic operations on plain text.
|
34276
|
6 |
*/
|
|
7 |
|
|
8 |
package isabelle
|
|
9 |
|
|
10 |
|
38425
|
11 |
object Text
|
34276
|
12 |
{
|
38425
|
13 |
/* edits */
|
34286
|
14 |
|
38425
|
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 |
}
|
34286
|
20 |
|
38425
|
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 + ")"
|
34286
|
25 |
|
|
26 |
|
38425
|
27 |
/* transform offsets */
|
34286
|
28 |
|
38425
|
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
|
34286
|
33 |
|
38425
|
34 |
def convert(offset: Int): Int = transform(true, offset)
|
|
35 |
def revert(offset: Int): Int = transform(false, offset)
|
|
36 |
|
34286
|
37 |
|
38425
|
38 |
/* edit strings */
|
|
39 |
|
|
40 |
private def insert(index: Int, string: String): String =
|
|
41 |
string.substring(0, index) + text + string.substring(index)
|
34276
|
42 |
|
38425
|
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 |
}
|
34276
|
61 |
}
|