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 |
{
|
38426
|
13 |
/* offset and range */
|
|
14 |
|
|
15 |
type Offset = Int
|
|
16 |
|
|
17 |
sealed case class Range(val start: Offset, val stop: Offset)
|
38427
|
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 |
}
|
38426
|
23 |
|
|
24 |
|
|
25 |
/* editing */
|
34286
|
26 |
|
38425
|
27 |
object Edit
|
|
28 |
{
|
38426
|
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)
|
38425
|
31 |
}
|
34286
|
32 |
|
38426
|
33 |
class Edit(val is_insert: Boolean, val start: Offset, val text: String)
|
38425
|
34 |
{
|
|
35 |
override def toString =
|
|
36 |
(if (is_insert) "Insert(" else "Remove(") + (start, text).toString + ")"
|
34286
|
37 |
|
|
38 |
|
38425
|
39 |
/* transform offsets */
|
34286
|
40 |
|
38426
|
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
|
34286
|
45 |
|
38426
|
46 |
def convert(i: Offset): Offset = transform(true, i)
|
|
47 |
def revert(i: Offset): Offset = transform(false, i)
|
38425
|
48 |
|
34286
|
49 |
|
38425
|
50 |
/* edit strings */
|
|
51 |
|
38426
|
52 |
private def insert(i: Offset, string: String): String =
|
|
53 |
string.substring(0, i) + text + string.substring(i)
|
34276
|
54 |
|
38426
|
55 |
private def remove(i: Offset, count: Int, string: String): String =
|
|
56 |
string.substring(0, i) + string.substring(i + count)
|
38425
|
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 {
|
38426
|
65 |
val i = start - shift
|
|
66 |
val count = text.length min (string.length - i)
|
38425
|
67 |
val rest =
|
|
68 |
if (count == text.length) None
|
|
69 |
else Some(Edit.remove(start, text.substring(count)))
|
38426
|
70 |
(rest, remove(i, count, string))
|
38425
|
71 |
}
|
|
72 |
}
|
34276
|
73 |
}
|