1/*  Title:      Pure/PIDE/line.scala
2    Author:     Makarius
3
4Line-oriented text documents, with some bias towards VSCode.
5*/
6
7package isabelle
8
9
10import scala.annotation.tailrec
11
12
13object Line
14{
15  /* logical lines */
16
17  def normalize(text: String): String =
18    if (text.contains('\r')) text.replace("\r\n", "\n") else text
19
20  def logical_lines(text: String): List[String] =
21    split_lines(normalize(text))
22
23
24  /* position */
25
26  object Position
27  {
28    val zero: Position = Position()
29    val offside: Position = Position(line = -1)
30
31    object Ordering extends scala.math.Ordering[Position]
32    {
33      def compare(p1: Position, p2: Position): Int = p1 compare p2
34    }
35  }
36
37  sealed case class Position(line: Int = 0, column: Int = 0)
38  {
39    def line1: Int = line + 1
40    def column1: Int = column + 1
41    def print: String = line1.toString + ":" + column1.toString
42
43    def compare(that: Position): Int =
44      line compare that.line match {
45        case 0 => column compare that.column
46        case i => i
47      }
48
49    def advance(text: String): Position =
50      if (text.isEmpty) this
51      else {
52        val lines = logical_lines(text)
53        val l = line + lines.length - 1
54        val c = (if (l == line) column else 0) + Library.trim_line(lines.last).length
55        Position(l, c)
56      }
57  }
58
59
60  /* range (right-open interval) */
61
62  object Range
63  {
64    def apply(start: Position): Range = Range(start, start)
65    val zero: Range = Range(Position.zero)
66  }
67
68  sealed case class Range(start: Position, stop: Position)
69  {
70    if (start.compare(stop) > 0)
71      error("Bad line range: " + start.print + ".." + stop.print)
72
73    def print: String =
74      if (start == stop) start.print
75      else start.print + ".." + stop.print
76  }
77
78
79  /* positions within document node */
80
81  object Node_Position
82  {
83    def offside(name: String): Node_Position = Node_Position(name, Position.offside)
84  }
85
86  sealed case class Node_Position(name: String, pos: Position = Position.zero)
87  {
88    def line: Int = pos.line
89    def line1: Int = pos.line1
90    def column: Int = pos.column
91    def column1: Int = pos.column1
92  }
93
94  sealed case class Node_Range(name: String, range: Range = Range.zero)
95  {
96    def start: Position = range.start
97    def stop: Position = range.stop
98  }
99
100
101  /* document with newline as separator (not terminator) */
102
103  object Document
104  {
105    def apply(text: String): Document =
106      Document(logical_lines(text).map(s => Line(Library.isolate_substring(s))))
107
108    val empty: Document = apply("")
109
110    private def split(line_text: String): List[Line] =
111      if (line_text == "") List(Line.empty) else apply(line_text).lines
112
113    private def chop(lines: List[Line]): (String, List[Line]) =
114      lines match {
115        case Nil => ("", Nil)
116        case line :: rest => (line.text, rest)
117      }
118
119    private def length(lines: List[Line]): Int =
120      if (lines.isEmpty) 0
121      else ((0 /: lines) { case (n, line) => n + line.text.length + 1 }) - 1
122
123    def text(lines: List[Line]): String = lines.mkString("", "\n", "")
124  }
125
126  sealed case class Document(lines: List[Line])
127  {
128    lazy val text_length: Text.Offset = Document.length(lines)
129    def text_range: Text.Range = Text.Range(0, text_length)
130
131    lazy val text: String = Document.text(lines)
132
133    def get_text(range: Text.Range): Option[String] =
134      if (text_range.contains(range)) Some(range.substring(text)) else None
135
136    override def toString: String = text
137
138    override def equals(that: Any): Boolean =
139      that match {
140        case other: Document => lines == other.lines
141        case _ => false
142      }
143    override def hashCode(): Int = lines.hashCode
144
145    def position(text_offset: Text.Offset): Position =
146    {
147      @tailrec def move(i: Text.Offset, lines_count: Int, lines_rest: List[Line]): Position =
148      {
149        lines_rest match {
150          case Nil => require(i == 0); Position(lines_count)
151          case line :: ls =>
152            val n = line.text.length
153            if (ls.isEmpty || i <= n)
154              Position(lines_count).advance(line.text.substring(n - i))
155            else move(i - (n + 1), lines_count + 1, ls)
156        }
157      }
158      move(text_offset, 0, lines)
159    }
160
161    def range(text_range: Text.Range): Range =
162      Range(position(text_range.start), position(text_range.stop))
163
164    def offset(pos: Position): Option[Text.Offset] =
165    {
166      val l = pos.line
167      val c = pos.column
168      val n = lines.length
169      if (0 <= l && l < n) {
170        if (0 <= c && c <= lines(l).text.length) {
171          val line_offset =
172            (0 /: lines.iterator.take(l)) { case (n, line) => n + line.text.length + 1 }
173          Some(line_offset + c)
174        }
175        else None
176      }
177      else if (l == n && c == 0) Some(text_length)
178      else None
179    }
180
181    def change(remove: Range, insert: String): Option[(List[Text.Edit], Document)] =
182    {
183      for {
184        edit_start <- offset(remove.start)
185        if remove.stop == remove.start || offset(remove.stop).isDefined
186        l1 = remove.start.line
187        l2 = remove.stop.line
188        if l1 <= l2
189        (removed_text, new_lines) <-
190        {
191          val c1 = remove.start.column
192          val c2 = remove.stop.column
193
194          val (prefix, lines1) = lines.splitAt(l1)
195          val (s1, rest1) = Document.chop(lines1)
196
197          if (l1 == l2) {
198            if (0 <= c1 && c1 <= c2 && c2 <= s1.length) {
199              Some(
200                if (lines1.isEmpty) ("", prefix ::: Document.split(insert))
201                else {
202                  val removed_text = s1.substring(c1, c2)
203                  val changed_text = s1.substring(0, c1) + insert + s1.substring(c2)
204                  (removed_text, prefix ::: Document.split(changed_text) ::: rest1)
205                })
206            }
207            else None
208          }
209          else {
210            val (middle, lines2) = rest1.splitAt(l2 - l1 - 1)
211            val (s2, rest2) = Document.chop(lines2)
212            if (0 <= c1 && c1 <= s1.length && 0 <= c2 && c2 <= s2.length) {
213              Some(
214                if (lines1.isEmpty) ("", prefix ::: Document.split(insert))
215                else {
216                  val r1 = s1.substring(c1)
217                  val r2 = s2.substring(0, c2)
218                  val removed_text =
219                    if (lines2.isEmpty) Document.text(Line(r1) :: middle)
220                    else Document.text(Line(r1) :: middle ::: List(Line(r2)))
221                  val changed_text = s1.substring(0, c1) + insert + s2.substring(c2)
222                  (removed_text, prefix ::: Document.split(changed_text) ::: rest2)
223                })
224            }
225            else None
226          }
227        }
228      }
229      yield
230        (Text.Edit.removes(edit_start, removed_text) ::: Text.Edit.inserts(edit_start, insert),
231          Document(new_lines))
232    }
233  }
234
235
236  /* line text */
237
238  val empty: Line = new Line("")
239  def apply(text: String): Line = if (text == "") empty else new Line(text)
240}
241
242final class Line private(val text: String)
243{
244  require(text.forall(c => c != '\r' && c != '\n'))
245
246  override def equals(that: Any): Boolean =
247    that match {
248      case other: Line => text == other.text
249      case _ => false
250    }
251  override def hashCode(): Int = text.hashCode
252  override def toString: String = text
253}
254