34276
|
1 |
/* Title: Pure/Thy/text_edit.scala
|
|
2 |
Author: Fabian Immler, TU Munich
|
|
3 |
Author: Makarius
|
|
4 |
|
|
5 |
Basic edits on plain text.
|
|
6 |
*/
|
|
7 |
|
|
8 |
package isabelle
|
|
9 |
|
|
10 |
|
|
11 |
sealed abstract class Text_Edit
|
|
12 |
{
|
|
13 |
val start: Int
|
34286
|
14 |
def after(offset: Int): Int
|
34276
|
15 |
def before(offset: Int): Int
|
34286
|
16 |
def edit(string: String, shift: Int): (Option[Text_Edit], String)
|
34276
|
17 |
}
|
|
18 |
|
|
19 |
|
|
20 |
object Text_Edit
|
|
21 |
{
|
34286
|
22 |
/* transform offsets */
|
|
23 |
|
|
24 |
private def after_insert(start: Int, text: String, offset: Int): Int =
|
|
25 |
if (start <= offset) offset + text.length
|
|
26 |
else offset
|
|
27 |
|
|
28 |
private def after_remove(start: Int, text: String, offset: Int): Int =
|
|
29 |
if (start > offset) offset
|
|
30 |
else (offset - text.length) max start
|
|
31 |
|
|
32 |
|
|
33 |
/* edit strings */
|
|
34 |
|
|
35 |
private def insert(index: Int, text: String, string: String): String =
|
|
36 |
string.substring(0, index) + text + string.substring(index)
|
|
37 |
|
|
38 |
private def remove(index: Int, count: Int, string: String): String =
|
|
39 |
string.substring(0, index) + string.substring(index + count)
|
|
40 |
|
|
41 |
|
|
42 |
/* explicit edits */
|
|
43 |
|
34276
|
44 |
case class Insert(start: Int, text: String) extends Text_Edit
|
|
45 |
{
|
34286
|
46 |
def after(offset: Int): Int = after_insert(start, text, offset)
|
|
47 |
def before(offset: Int): Int = after_remove(start, text, offset)
|
34276
|
48 |
|
34286
|
49 |
def can_edit(string_length: Int, shift: Int): Boolean =
|
|
50 |
shift <= start && start <= shift + string_length
|
|
51 |
|
|
52 |
def edit(string: String, shift: Int): (Option[Insert], String) =
|
|
53 |
if (can_edit(string.length, shift)) (None, insert(start - shift, text, string))
|
|
54 |
else (Some(this), string)
|
34276
|
55 |
}
|
|
56 |
|
|
57 |
case class Remove(start: Int, text: String) extends Text_Edit
|
|
58 |
{
|
34286
|
59 |
def after(offset: Int): Int = after_remove(start, text, offset)
|
|
60 |
def before(offset: Int): Int = after_insert(start, text, offset)
|
|
61 |
|
|
62 |
def can_edit(string_length: Int, shift: Int): Boolean =
|
|
63 |
shift <= start && start < shift + string_length
|
34276
|
64 |
|
34286
|
65 |
def edit(string: String, shift: Int): (Option[Remove], String) =
|
|
66 |
if (can_edit(string.length, shift)) {
|
|
67 |
val index = start - shift
|
|
68 |
val count = text.length min (string.length - index)
|
|
69 |
val rest =
|
|
70 |
if (count == text.length) None
|
|
71 |
else Some(Remove(start, text.substring(count)))
|
|
72 |
(rest, remove(index, count, string))
|
|
73 |
}
|
|
74 |
else (Some(this), string)
|
34276
|
75 |
}
|
|
76 |
}
|
|
77 |
|