egedit: do not save cursor movement in undo -- this is my stupid habit, and it comple...
[iv.d.git] / egeditor / editor.d
blob59b48367513ff7dfa659e5ebf7200426625c17b0
1 /* Invisible Vector Library.
2 * simple FlexBox-based TUI engine
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, version 3 of the License ONLY.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 module iv.egeditor.editor /*is aliced*/;
18 //version = egeditor_scan_time;
19 //version = egeditor_scan_time_to_file;
20 // this is idiocity, i should change my habits
21 //version = egeditor_record_movement_undo;
23 import iv.alice;
24 import iv.strex;
25 import iv.utfutil;
26 import iv.vfs;
27 debug import iv.vfs.io;
29 version(egeditor_scan_time) import iv.pxclock;
31 version(egeditor_record_movement_undo) {
32 public enum EgEditorMovementUndo = true;
33 } else {
34 public enum EgEditorMovementUndo = false;
38 // ////////////////////////////////////////////////////////////////////////// //
39 /// this interface is used to measure text for pixel-sized editor
40 abstract class EgTextMeter {
41 int currofs; /// x offset for current char (i.e. the last char that was passed to `advance()` should be drawn with this offset)
42 int currwdt; /// current line width (including, the last char that was passed to `advance()`), preferably without trailing empty space between chars
43 int currheight; /// current text height; keep this in sync with the current state; `reset` should set it to "default text height"
45 /// this should reset text width iterator (and curr* fields); tabsize > 0: process tabs as... well... tabs ;-); tabsize < 0: calculating height
46 abstract void reset (int tabsize) nothrow;
48 /// advance text width iterator, fix all curr* fields
49 abstract void advance (dchar ch, in ref GapBuffer.HighState hs) nothrow;
51 /// finish text iterator; it should NOT reset curr* fields!
52 /// WARNING: EditorEngine tries to call this after each `reset()`, but user code may not
53 abstract void finish () nothrow;
57 // ////////////////////////////////////////////////////////////////////////// //
58 /// highlighter should be able to work line-by-line
59 class EditorHL {
60 protected:
61 GapBuffer gb; /// this will be set by EditorEngine on attaching
62 LineCache lc; /// this will be set by EditorEngine on attaching
64 public:
65 this () {} ///
67 /// return true if highlighting for this line was changed
68 abstract bool fixLine (int line);
70 /// mark line as "need rehighlighting" (and possibly other text too)
71 /// wasInsDel: some lines was inserted/deleted down the text
72 abstract void lineChanged (int line, bool wasInsDel);
76 // ////////////////////////////////////////////////////////////////////////// //
77 ///
78 public final class GapBuffer {
79 public:
80 static align(1) struct HighState {
81 align(1):
82 ubyte kwtype; // keyword number
83 ubyte kwidx; // index in keyword
84 @property pure nothrow @safe @nogc {
85 ushort u16 () const { pragma(inline, true); return cast(ushort)((kwidx<<8)|kwtype); }
86 short s16 () const { pragma(inline, true); return cast(short)((kwidx<<8)|kwtype); }
87 void u16 (ushort v) { pragma(inline, true); kwtype = v&0xff; kwidx = (v>>8)&0xff; }
88 void s16 (short v) { pragma(inline, true); kwtype = v&0xff; kwidx = (v>>8)&0xff; }
92 private:
93 HighState hidummy;
94 bool mSingleLine;
96 protected:
97 enum MinGapSize = 1024; // bytes in gap
98 enum GrowGran = 65536; // must be power of 2
99 enum MinGapSizeSmall = 64; // bytes in gap
100 enum GrowGranSmall = 0x100; // must be power of 2
102 static assert(GrowGran >= MinGapSize);
103 static assert(GrowGranSmall >= MinGapSizeSmall);
105 @property uint MGS () const pure nothrow @safe @nogc { pragma(inline, true); return (mSingleLine ? MinGapSizeSmall : MinGapSize); }
107 protected:
108 char* tbuf; // text buffer
109 HighState* hbuf; // highlight buffer
110 uint tbused; // not including gap
111 uint tbsize; // including gap
112 uint tbmax = 512*1024*1024+MinGapSize; // maximum buffer size
113 uint gapstart, gapend; // tbuf[gapstart..gapend]; gap cannot be empty
114 uint bufferChangeCounter; // will simply increase on each buffer change
116 static private bool xrealloc(T) (ref T* ptr, ref uint cursize, int newsize, uint gran) nothrow @trusted @nogc {
117 import core.stdc.stdlib : realloc;
118 assert(gran > 1);
119 uint nsz = ((newsize+gran-1)/gran)*gran;
120 assert(nsz >= newsize);
121 T* nb = cast(T*)realloc(ptr, nsz*T.sizeof);
122 if (nb is null) return false;
123 cursize = nsz;
124 ptr = nb;
125 return true;
128 final:
129 // initial alloc
130 void initTBuf (bool hadHBuf) nothrow @nogc {
131 import core.stdc.stdlib : free, malloc, realloc;
132 assert(tbuf is null);
133 assert(hbuf is null);
134 immutable uint nsz = (mSingleLine ? GrowGranSmall : GrowGran);
135 tbuf = cast(char*)malloc(nsz);
136 if (tbuf is null) assert(0, "out of memory for text buffers");
137 // allocate highlight buffer if necessary
138 if (hadHBuf) {
139 hbuf = cast(HighState*)malloc(nsz*hbuf[0].sizeof);
140 if (hbuf is null) assert(0, "out of memory for text buffers");
141 hbuf[0..nsz] = HighState.init;
143 tbused = 0;
144 tbsize = nsz;
145 gapstart = 0;
146 gapend = tbsize;
149 // ensure that we can place a text of size `size` in buffer, and will still have at least MGS bytes free
150 // may change `tbsize`, but will not touch `tbused`
151 bool growTBuf (uint size) nothrow @nogc {
152 if (size > tbmax) return false; // too big
153 immutable uint mingapsize = MGS; // desired gap buffer size
154 immutable uint unused = tbsize-tbused; // number of unused bytes in buffer
155 assert(tbused <= tbsize);
156 if (size <= tbused && unused >= mingapsize) return true; // nothing to do, we have enough room in buffer
157 // if the gap is bigger than the minimal gap size, check if we have enough extra bytes to avoid allocation
158 if (unused > mingapsize) {
159 immutable uint extra = unused-mingapsize; // extra bytes we can spend
160 immutable uint bgrow = size-tbused; // number of bytes we need
161 if (extra >= bgrow) return true; // yay, no need to realloc
163 // have to grow
164 immutable uint newsz = size+mingapsize;
165 immutable uint gran = (mSingleLine ? GrowGranSmall : GrowGran);
166 uint hbufsz = tbsize;
167 if (!xrealloc(tbuf, tbsize, newsz, gran)) return false;
168 // reallocate highlighting buffer only if we already have one
169 if (hbuf !is null) {
170 if (!xrealloc(hbuf, hbufsz, newsz, gran)) { tbsize = hbufsz; return false; } // HACK!
171 assert(tbsize == hbufsz);
173 assert(tbsize >= newsz);
174 return true;
177 protected:
178 uint pos2real (uint pos) const pure @safe nothrow @nogc {
179 pragma(inline, true);
180 return pos+(pos >= gapstart ? gapend-gapstart : 0);
183 public:
184 HighState defhs; /// default highlighting state for new text
186 public:
188 this (bool asingleline) nothrow @nogc {
189 mSingleLine = asingleline;
190 initTBuf(false); // don't allocate hbuf yet
194 ~this () nothrow @nogc {
195 import core.stdc.stdlib : free;
196 if (tbuf !is null) free(tbuf);
197 if (hbuf !is null) free(hbuf);
200 /// remove all text from buffer
201 /// WILL NOT call deletion hooks!
202 void clear () nothrow @nogc {
203 import core.stdc.stdlib : free;
204 immutable bool hadHBuf = (hbuf !is null);
205 if (tbuf !is null) { free(tbuf); tbuf = null; }
206 if (hadHBuf) { free(hbuf); hbuf = null; }
207 ++bufferChangeCounter;
208 initTBuf(hadHBuf);
211 @property bool hasHiBuffer () const pure nothrow @safe @nogc { pragma(inline, true); return (hbuf !is null); } ///
213 /// after calling this with `true`, `hasHiBuffer` may still be false if there is no memory for it
214 @property void hasHiBuffer (bool v) nothrow @trusted @nogc {
215 if (v != hasHiBuffer) {
216 if (v) {
217 // create highlighting buffer
218 import core.stdc.stdlib : malloc;
219 assert(hbuf is null);
220 assert(tbsize > 0);
221 hbuf = cast(HighState*)malloc(tbsize*hbuf[0].sizeof);
222 if (hbuf !is null) hbuf[0..tbsize] = HighState.init;
223 } else {
224 // remove highlighitng buffer
225 import core.stdc.stdlib : free;
226 assert(hbuf !is null);
227 free(hbuf);
228 hbuf = null;
233 /// "single line" mode, for line editors
234 bool singleline () const pure @safe nothrow @nogc { pragma(inline, true); return mSingleLine; }
236 /// size of text buffer without gap, in one-byte chars
237 @property int textsize () const pure @safe nothrow @nogc { pragma(inline, true); return tbused; }
239 @property char opIndex (uint pos) const pure @trusted nothrow @nogc { pragma(inline, true); return (pos < tbused ? tbuf[pos+(pos >= gapstart ? gapend-gapstart : 0)] : '\n'); } ///
240 @property ref HighState hi (uint pos) pure @trusted nothrow @nogc { pragma(inline, true); return (hbuf !is null && pos < tbused ? hbuf[pos+(pos >= gapstart ? gapend-gapstart : 0)] : (hidummy = hidummy.init)); } ///
242 @property dchar uniAt (uint pos) const @trusted nothrow @nogc {
243 immutable ts = tbused;
244 if (pos >= ts) return '\n';
245 Utf8DecoderFast udc;
246 while (pos < ts) {
247 if (udc.decodeSafe(cast(ubyte)tbuf[pos2real(pos++)])) return udc.codepoint;
249 return udc.codepoint;
252 @property dchar uniAtAndAdvance (ref int pos) const @trusted nothrow @nogc {
253 immutable ts = tbused;
254 if (pos < 0) pos = 0;
255 if (pos >= ts) return '\n';
256 Utf8DecoderFast udc;
257 while (pos < ts) {
258 if (udc.decodeSafe(cast(ubyte)tbuf[pos2real(pos++)])) return udc.codepoint;
260 return udc.codepoint;
263 /// return utf-8 character length at buffer position pos or -1 on error (or 1 on error if "always positive")
264 /// never returns zero
265 int utfuckLenAt(bool alwaysPositive=true) (int pos) const @trusted nothrow @nogc {
266 immutable ts = tbused;
267 if (pos < 0 || pos >= ts) {
268 static if (alwaysPositive) return 1; else return -1;
270 char ch = tbuf[pos2real(pos)];
271 if (ch < 128) return 1;
272 Utf8DecoderFast udc;
273 auto spos = pos;
274 while (pos < ts) {
275 ch = tbuf[pos2real(pos++)];
276 if (udc.decode(cast(ubyte)ch)) {
277 static if (alwaysPositive) {
278 return (udc.invalid ? 1 : pos-spos);
279 } else {
280 return (udc.invalid ? -1 : pos-spos);
284 static if (alwaysPositive) return 1; else return -1;
287 // ensure that the buffer has room for at least one char in the gap
288 // note that this may move gap
289 protected void ensureGap () pure @safe nothrow @nogc {
290 pragma(inline, true);
291 // if we have zero-sized gap, assume that it is at end; we always have a room for at least MinGapSize(Small) chars
292 if (gapstart >= gapend || gapstart >= tbused) {
293 assert(tbused <= tbsize);
294 gapstart = tbused;
295 gapend = tbsize;
296 assert(gapend-gapstart >= MGS);
300 /// put the gap *before* `pos`
301 void moveGapAtPos (int pos) @trusted nothrow @nogc {
302 import core.stdc.string : memmove;
303 immutable ts = tbused; // i will need it in several places
304 if (pos < 0) pos = 0;
305 if (pos > ts) pos = ts;
306 if (ts == 0) { gapstart = 0; gapend = tbsize; return; } // unlikely case, but...
307 ensureGap(); // we should have a gap
308 /* cases:
309 * pos is before gap: shift [pos..gapstart] to gapend-len, shift gap
310 * pos is after gap: shift [gapend..pos] to gapstart, shift gap
312 if (pos < gapstart) {
313 // pos is before gap
314 int len = gapstart-pos; // to shift
315 memmove(tbuf+gapend-len, tbuf+pos, len);
316 if (hbuf !is null) memmove(hbuf+gapend-len, hbuf+pos, len*hbuf[0].sizeof);
317 gapstart -= len;
318 gapend -= len;
319 } else if (pos > gapstart) {
320 // pos is after gap
321 int len = pos-gapstart;
322 memmove(tbuf+gapstart, tbuf+gapend, len);
323 if (hbuf !is null) memmove(hbuf+gapstart, hbuf+gapend, len*hbuf[0].sizeof);
324 gapstart += len;
325 gapend += len;
327 // if we moved gap to buffer end, grow it; `ensureGap()` will do it for us
328 ensureGap();
329 assert(gapstart == pos);
330 assert(gapstart < gapend);
331 assert(gapstart <= ts);
334 /// put the gap at the end of the text
335 void moveGapAtEnd () @trusted nothrow @nogc { moveGapAtPos(tbused); }
337 /// put text into buffer; will either put all the text, or nothing
338 /// returns success flag
339 bool append (const(char)[] str...) @trusted nothrow @nogc { return (put(tbused, str) >= 0); }
341 /// put text into buffer; will either put all the text, or nothing
342 /// returns new position or -1
343 int put (int pos, const(char)[] str...) @trusted nothrow @nogc {
344 import core.stdc.string : memcpy;
345 if (pos < 0) pos = 0;
346 bool atend = (pos >= tbused);
347 if (atend) pos = tbused;
348 if (str.length == 0) return pos;
349 if (tbmax-(tbsize-tbused) < str.length) return -1; // no room
350 if (!growTBuf(tbused+cast(uint)str.length)) return -1; // memory allocation failed
351 //TODO: this can be made faster, but meh...
352 immutable slen = cast(uint)str.length;
353 if (atend || gapend-gapstart < slen) moveGapAtEnd(); // this will grow the gap, so it will take all available room
354 if (!atend) moveGapAtPos(pos); // condition is used for tiny speedup
355 assert(gapend-gapstart >= slen);
356 memcpy(tbuf+gapstart, str.ptr, str.length);
357 if (hbuf !is null) hbuf[gapstart..gapstart+str.length] = defhs;
358 gapstart += slen;
359 tbused += slen;
360 pos += slen;
361 ensureGap();
362 assert(tbsize-tbused >= MGS);
363 ++bufferChangeCounter;
364 return pos;
367 /// remove count bytes from the current position; will either remove all of 'em, or nothing
368 /// returns success flag
369 bool remove (int pos, int count) @trusted nothrow @nogc {
370 import core.stdc.string : memmove;
371 if (count < 0) return false;
372 if (count == 0) return true;
373 immutable ts = tbused; // cache current text size
374 if (pos < 0) pos = 0;
375 if (pos > ts) pos = ts;
376 if (ts-pos < count) return false; // not enough text here
377 assert(gapstart < gapend);
378 ++bufferChangeCounter; // buffer will definitely be changed
379 for (;;) {
380 // at the start of the gap: i can just increase gap
381 if (pos == gapstart) {
382 gapend += count;
383 tbused -= count;
384 return true;
386 // removing text just before gap: increase gap (backspace does this)
387 if (pos+count == gapstart) {
388 gapstart -= count;
389 tbused -= count;
390 assert(gapstart == pos);
391 return true;
393 // both variants failed; move gap at `pos` and try again
394 moveGapAtPos(pos);
398 /// count how much eols we have in this range
399 int countEolsInRange (int pos, int count) const @trusted nothrow @nogc {
400 import core.stdc.string : memchr;
401 if (count < 1 || pos <= -count || pos >= tbused) return 0;
402 if (pos+count > tbused) count = tbused-pos;
403 int res = 0;
404 while (count > 0) {
405 int npos = fastFindCharIn(pos, count, '\n')+1;
406 if (npos <= 0) break;
407 ++res;
408 count -= (npos-pos);
409 pos = npos;
411 return res;
414 /// using `memchr`, jumps over gap; never moves after `tbused`
415 public uint fastSkipEol (int pos) const @trusted nothrow @nogc {
416 import core.stdc.string : memchr;
417 immutable ts = tbused;
418 if (ts == 0 || pos >= ts) return ts;
419 if (pos < 0) pos = 0;
420 // check text before gap
421 if (pos < gapstart) {
422 auto fp = cast(char*)memchr(tbuf+pos, '\n', gapstart-pos);
423 if (fp !is null) return cast(int)(fp-tbuf)+1;
424 pos = gapstart; // new starting position
426 assert(pos >= gapstart);
427 // check after gap and to text end
428 int left = ts-pos;
429 if (left > 0) {
430 auto stx = tbuf+gapend+(pos-gapstart);
431 assert(cast(usize)(tbuf+tbsize-stx) >= left);
432 auto fp = cast(char*)memchr(stx, '\n', left);
433 if (fp !is null) return pos+cast(int)(fp-stx)+1;
435 return ts;
438 /// using `memchr`, jumps over gap; returns `tbused` if not found
439 public uint fastFindChar (int pos, char ch) const @trusted nothrow @nogc {
440 int res = fastFindCharIn(pos, tbused, ch);
441 return (res >= 0 ? res : tbused);
444 /// use `memchr`, jumps over gap; returns -1 if not found
445 public int fastFindCharIn (int pos, int len, char ch) const @trusted nothrow @nogc {
446 import core.stdc.string : memchr;
447 immutable ts = tbused;
448 if (len < 1) return -1;
449 if (ts == 0 || pos >= ts) return -1;
450 if (pos < 0) {
451 if (pos <= -len) return -1;
452 len += pos;
453 pos = 0;
455 if (tbused-pos < len) len = tbused-pos;
456 assert(len > 0);
457 int left;
458 // check text before gap
459 if (pos < gapstart) {
460 left = gapstart-pos;
461 if (left > len) left = len;
462 auto fp = cast(char*)memchr(tbuf+pos, ch, left);
463 if (fp !is null) return cast(int)(fp-tbuf);
464 if ((len -= left) == 0) return -1;
465 pos = gapstart; // new starting position
467 assert(pos >= gapstart);
468 // check after gap and to text end
469 left = ts-pos;
470 if (left > len) left = len;
471 if (left > 0) {
472 auto stx = tbuf+gapend+(pos-gapstart);
473 assert(cast(usize)(tbuf+tbsize-stx) >= left);
474 auto fp = cast(char*)memchr(stx, ch, left);
475 if (fp !is null) return pos+cast(int)(fp-stx);
477 return -1;
480 /// bufparts range
481 /// this is hack for regexp searchers
482 /// do not store returned slice anywhere for a long time!
483 /// slice *will* be invalidated on next gap buffer operation!
484 public auto bufparts (int pos) nothrow @nogc {
485 static struct Range {
486 nothrow @nogc:
487 GapBuffer gb;
488 bool aftergap; // fr is "aftergap"?
489 const(char)[] fr;
490 private this (GapBuffer agb, int pos) {
491 gb = agb;
492 auto ts = agb.tbused;
493 if (ts == 0 || pos >= ts) { gb = null; return; }
494 if (pos < 0) pos = 0;
495 if (pos < agb.gapstart) {
496 fr = agb.tbuf[pos..agb.gapstart];
497 } else {
498 int left = ts-pos;
499 if (left < 1) { gb = null; return; }
500 pos -= agb.gapstart;
501 fr = agb.tbuf[agb.gapend+pos..agb.gapend+pos+left];
502 aftergap = true;
505 @property bool empty () pure const @safe { pragma(inline, true); return (gb is null); }
506 @property const(char)[] front () pure @safe { pragma(inline, true); return fr; }
507 void popFront () {
508 if (aftergap) gb = null;
509 if (gb is null) { fr = null; return; }
510 int left = gb.textsize-gb.gapstart;
511 if (left < 1) { gb = null; fr = null; return; }
512 fr = gb.tbuf[gb.gapend..gb.gapend+left];
513 aftergap = true;
516 return Range(this, pos);
519 /// this calls dg with continuous buffer parts, so you can write 'em to a file, for example
520 public final void forEachBufPart (int pos, int len, scope void delegate (const(char)[] buf) dg) {
521 if (dg is null) return;
522 immutable ts = tbused;
523 if (len < 1) return;
524 if (ts == 0 || pos >= ts) return;
525 if (pos < 0) {
526 if (pos <= -len) return;
527 len += pos;
528 pos = 0;
530 assert(len > 0);
531 int left;
532 // check text before gap
533 if (pos < gapstart) {
534 left = gapstart-pos;
535 if (left > len) left = len;
536 assert(left > 0);
537 dg(tbuf[pos..pos+left]);
538 if ((len -= left) == 0) return; // nothing more to do
539 pos = gapstart; // new starting position
541 assert(pos >= gapstart);
542 // check after gap and to text end
543 left = ts-pos;
544 if (left > len) left = len;
545 if (left > 0) {
546 auto stx = tbuf+gapend+(pos-gapstart);
547 assert(cast(usize)(tbuf+tbsize-stx) >= left);
548 dg(stx[0..left]);
552 public:
554 static bool hasEols (const(char)[] str) pure nothrow @trusted @nogc {
555 import core.stdc.string : memchr;
556 uint left = cast(uint)str.length;
557 return (left > 0 && memchr(str.ptr, '\n', left) !is null);
560 /// index or -1
561 static int findEol (const(char)[] str) pure nothrow @trusted @nogc {
562 if (str.length > int.max) assert(0, "string too long");
563 int left = cast(int)str.length;
564 if (left > 0) {
565 import core.stdc.string : memchr;
566 auto dp = cast(const(char)*)memchr(str.ptr, '\n', left);
567 if (dp !is null) return cast(int)(dp-str.ptr);
569 return -1;
572 /// count number of '\n' chars in string
573 static int countEols (const(char)[] str) pure nothrow @trusted @nogc {
574 import core.stdc.string : memchr;
575 if (str.length > int.max) assert(0, "string too long");
576 int count = 0;
577 uint left = cast(uint)str.length;
578 auto dsp = str.ptr;
579 while (left > 0) {
580 auto ep = cast(const(char)*)memchr(dsp, '\n', left);
581 if (ep is null) break;
582 ++count;
583 ++ep;
584 left -= cast(uint)(ep-dsp);
585 dsp = ep;
587 return count;
592 // ////////////////////////////////////////////////////////////////////////// //
593 // Self-Healing Line Cache (utm) implementation
594 //TODO(?): don't do full cache repairing
595 private final class LineCache {
596 private:
597 // line offset/height cache item
598 // to be safe, locache[mLineCount] is always valid and holds gb.textsize
599 static align(1) struct LOCItem {
600 align(1):
601 uint ofs;
602 private uint mheight; // 0: unknown; line height; high bit is reserved for "viswrap" flag
603 pure nothrow @safe @nogc:
604 @property bool validHeight () const { pragma(inline, true); return ((mheight&0x7fff_ffffU) != 0); }
605 @property void resetHeight () { pragma(inline, true); mheight &= 0x8000_0000U; } // doesn't reset "viswrap" flag
606 @property uint height () const { pragma(inline, true); return (mheight&0x7fff_ffffU); }
607 @property void height (uint v) { pragma(inline, true); assert(v <= 0x7fff_ffffU); mheight = (mheight&0x8000_0000)|v; }
608 @property bool viswrap () const { pragma(inline, true); return ((mheight&0x8000_0000U) != 0); }
609 @property viswrap (bool v) { pragma(inline, true); if (v) mheight |= 0x8000_0000U; else mheight &= 0x7fff_ffffU; }
610 @property void resetHeightAndWrap () { pragma(inline, true); mheight = 0; }
611 @property void resetHeightAndSetWrap () { pragma(inline, true); mheight = 0x8000_0000U; }
612 void initWithPos (uint pos) { pragma(inline, true); ofs = pos; mheight = 0; }
615 private:
616 GapBuffer gb;
617 LOCItem* locache; // line info cache
618 uint locsize; // number of allocated items in locache
619 uint mLineCount; // total number of lines (and valid items in cache too)
620 EgTextMeter textMeter; // null: monospaced font
621 int mLineHeight = 1; // line height, in pixels/cells; <0: variable; 0: invalid state
622 dchar delegate (char ch) nothrow recode1byte; // not null: delegate to recode from 1bt to unishit
623 int mWordWrapWidth = 0; // >0: "visual wrap"; either in pixels (if textMeter is set) or in cells
625 public:
626 // utfuck-8 and visual tabs support
627 // WARNING! this will SIGNIFICANTLY slow down coordinate calculations!
628 bool utfuck = false; /// should x coordinate calculation assume that the text is in UTF-8?
629 bool visualtabs = false; /// should x coordinate calculation assume that tabs are not one-char width?
630 ubyte tabsize = 2; /// tab size, in spaces
632 final: // just in case the compiler won't notice "final class"
633 private:
634 void initLC () nothrow @nogc {
635 import core.stdc.stdlib : realloc;
636 // allocate initial line cache
637 uint ICS = (gb.mSingleLine ? 2 : 1024);
638 locache = cast(typeof(locache[0])*)realloc(locache, ICS*locache[0].sizeof);
639 if (locache is null) assert(0, "out of memory for line cache");
640 locache[0..ICS] = LOCItem.init;
641 locache[1].ofs = gb.textsize; // just in case
642 locsize = ICS;
643 mLineCount = 1; // we always have at least one line, even if it is empty
646 // `total` is new number of entries in cache; actual number will be greater by one
647 bool growLineCache (uint total) nothrow @nogc {
648 if (total >= int.max/8) assert(0, "egeditor: wtf?!");
649 ++total; // for last item
650 if (locsize < total) {
651 // have to allocate more
652 if (!GapBuffer.xrealloc(locache, locsize, total, (locsize < 4096 ? 0x400 : 0x1000))) return false;
654 return true;
657 int calcLineHeight (int lidx) nothrow {
658 assert(lidx >= 0 && lidx < mLineCount);
659 int ls = locache[lidx].ofs;
660 int le = locache[lidx+1].ofs;
661 if (locache[lidx].viswrap) ++le;
662 textMeter.reset(-1); // nobody cares about tab widths here
663 scope(exit) textMeter.finish();
664 int maxh = textMeter.currheight;
665 if (maxh < 1) maxh = 1;
666 auto tbufcopy = gb.tbuf;
667 auto hbufcopy = gb.hbuf;
668 gb.hidummy = GapBuffer.HighState.init; // just in case
669 if (utfuck) {
670 Utf8DecoderFast udc;
671 GapBuffer.HighState* hs = (hbufcopy !is null ? hbufcopy+gb.pos2real(ls) : &gb.hidummy);
672 while (ls < le) {
673 char ch = tbufcopy[gb.pos2real(ls++)];
674 if (udc.decodeSafe(cast(ubyte)ch)) {
675 immutable dchar dch = udc.codepoint;
676 textMeter.advance(dch, *hs);
678 if (textMeter.currheight > maxh) maxh = textMeter.currheight;
679 if (ls < le && hbufcopy !is null) hs = hbufcopy+gb.pos2real(ls);
681 } else {
682 auto rc1b = recode1byte;
683 while (ls < le) {
684 immutable uint rpos = gb.pos2real(ls++);
685 dchar dch = (rc1b !is null ? rc1b(tbufcopy[rpos]) : cast(dchar)tbufcopy[rpos]);
686 GapBuffer.HighState* hs = (hbufcopy !is null ? hbufcopy+rpos : &gb.hidummy);
687 textMeter.advance(dch, *hs);
688 if (textMeter.currheight > maxh) maxh = textMeter.currheight;
691 //{ import core.stdc.stdio; printf("line #%d height is %d\n", lidx, maxh); }
692 return maxh;
695 // -1: not found
696 int findLineCacheIndex (uint pos) const nothrow @nogc {
697 int lcount = mLineCount;
698 if (lcount <= 0) return -1;
699 if (pos >= gb.tbused) return lcount-1;
700 if (lcount == 1) return (pos < locache[1].ofs ? 0 : -1);
701 if (pos < locache[lcount].ofs) {
702 // yay! use binary search to find the line
703 int bot = 0, i = lcount-1;
704 while (bot != i) {
705 int mid = i-(i-bot)/2;
706 //!assert(mid >= 0 && mid < locused);
707 immutable ls = locache[mid].ofs;
708 immutable le = locache[mid+1].ofs;
709 if (pos >= ls && pos < le) return mid; // i found her!
710 if (pos < ls) i = mid-1; else bot = mid;
712 return i;
714 return -1;
717 // get range for current wrapped line: [ltop..lbot)
718 void wwGetTopBot (int lidx, int* ltop, int* lbot) const nothrow @trusted @nogc {
719 if (lidx < 0) lidx = 0;
720 if (lidx >= mLineCount) { *ltop = *lbot = mLineCount; return; }
721 *ltop = *lbot = lidx;
722 if (mWordWrapWidth <= 0) { *lbot += 1; return; }
723 immutable bool curIsMiddle = locache[lidx].viswrap;
724 // find first (top) line move up to previous unwrapped, and then one down
725 if (lidx > 0) while (lidx > 0 && locache[lidx-1].viswrap) --lidx;
726 *ltop = lidx;
727 // find last (bottom) line (if current is wrapped, move down to first unwrapped; then one down anyway)
728 lidx = *lbot;
729 if (curIsMiddle) while (lidx < mLineCount && locache[lidx].viswrap) ++lidx;
730 if (++lidx > mLineCount) lidx = mLineCount; // just in case
731 *lbot = lidx;
732 assert(*ltop < *lbot);
735 int collapseWrappedLine (int lidx) nothrow @nogc {
736 import core.stdc.string : memmove;
737 if (mWordWrapWidth <= 0 || gb.mSingleLine || lidx < 0 || lidx >= mLineCount) return lidx;
738 if (!locache[lidx].viswrap) return lidx; // early exit
739 int ltop, lbot;
740 wwGetTopBot(lidx, &ltop, &lbot);
741 immutable int tokill = lbot-ltop-1;
742 version(none) { import core.stdc.stdio; printf("collapsing: lidx=%d; ltop=%d; lbot=%d; tokill=%d; left=%d\n", lidx, ltop, lbot, tokill, mLineCount-lbot); }
743 if (tokill <= 0) return lidx; // nothing to do
744 // remove cache items for wrapped lines
745 if (lbot <= mLineCount) memmove(locache+ltop+1, locache+lbot, (mLineCount-lbot+1)*locache[0].sizeof);
746 lbot -= tokill;
747 mLineCount -= tokill;
748 // and fix wrapping flag
749 locache[ltop].resetHeightAndWrap();
750 return ltop;
753 // do word wrapping; line cache should be calculated and repaired for the given line
754 // (and down, if it was already wrapped)
755 // returns next line index to possible wrap
756 //TODO: "unwrap" line if word wrapping is not set?
757 //TODO: make it faster
758 //TODO: unicode blanks?
759 int doWordWrapping (int lidx) nothrow {
760 import core.stdc.string : memmove;
762 static bool isBlank (char ch) pure nothrow @safe @nogc { pragma(inline, true); return (ch == '\t' || ch == ' '); }
764 immutable int www = mWordWrapWidth;
765 if (www <= 0 || gb.mSingleLine) return mLineCount;
766 if (lidx < 0) lidx = 0;
767 if (lidx >= mLineCount) return mLineCount;
768 // find first and last line, if it was already wrapped
769 int ltop, lbot;
770 wwGetTopBot(lidx, &ltop, &lbot);
771 // now the hard part
772 if (textMeter) textMeter.reset(visualtabs ? tabsize : 0);
773 scope(exit) textMeter.finish();
774 version(none) { import core.stdc.stdio; printf("lidx=%d; ltop=%d; lbot=%d, linecount=%d\n", lidx, ltop, lbot, mLineCount); }
775 // we have line range here; go, ninja, go
776 lidx = ltop;
777 int cpos = locache[lidx].ofs;
778 int cwdt = 0;
779 int lastWordStartPos = 0;
780 immutable bool utfuckmode = utfuck;
781 immutable int tabsz = (visualtabs ? tabsize : 0);
782 auto tm = textMeter;
783 while (gb[cpos] != '\n') {
784 // go until cwdt allows us; but we have to have at least one char
785 int nwdt; // "new" width with the current char
786 int lpos = cpos; // "last position"
787 if (tm is null) {
788 if (tabsz > 0 && gb[cpos] == '\t') {
789 // skip tab
790 nwdt = ((cwdt+tabsz)/tabsz)*tabsz;
791 } else {
792 nwdt = cwdt+1;
793 if (utfuckmode) cpos += gb.utfuckLenAt!true(cpos); else ++cpos;
795 } else {
796 dchar dch = (utfuckmode ? gb.uniAtAndAdvance(cpos) : recode1byte is null ? cast(dchar)gb[cpos++] : recode1byte(gb[cpos++]));
797 tm.advance(dch, gb.hi(lpos));
798 nwdt = tm.currwdt;
800 //{ import core.stdc.stdio; printf(" lidx=%d; lineofs=%d; linelen=%d; cwdt=%d; nwdt=%d; maxwdt=%d; lpos=%d; cpos=%d\n", lidx, locache[lidx].ofs, locache[lidx].len, cwdt, nwdt, www, lpos, cpos); }
801 // if we have at least one char in line, check if we should wrap here
802 if (lpos > locache[lidx].ofs) {
803 if (nwdt > www) {
804 // should wrap here
805 if (tm !is null) {
806 tm.finish();
807 tm.reset(visualtabs ? tabsize : 0);
809 // if we have at least one word, wrap on it
810 if (lastWordStartPos > 0) {
811 cpos = lastWordStartPos;
812 lastWordStartPos = 0;
813 } else {
814 cpos = lpos;
816 locache[lidx].resetHeightAndSetWrap();
817 ++lidx;
818 if (lidx == lbot) {
819 // insert new cache record
820 growLineCache(mLineCount+1);
821 if (lidx <= mLineCount) memmove(locache+lidx+1, locache+lidx, (mLineCount-lidx+1)*locache[0].sizeof);
822 ++mLineCount;
823 ++lbot;
825 // setup next line
826 locache[lidx] = LOCItem.init; // reset all, including height and wrapping
827 locache[lidx].ofs = cpos;
828 cwdt = 0;
829 continue;
830 } else {
831 // check for word boundary
832 if (isBlank(gb[lpos]) && !isBlank(gb[cpos])) lastWordStartPos = cpos;
835 // go on
836 cwdt = nwdt;
838 locache[lidx].resetHeightAndWrap();
839 // remove unused cache items
840 version(none) { import core.stdc.stdio; printf(" 00: lidx=%d; ltop=%d; lbot=%d, linecount=%d\n", lidx, ltop, lbot, mLineCount); }
841 assert(lidx < lbot);
842 //TODO: make it faster
843 ++lidx; // to kill: [lidx..lbot)
844 immutable int tokill = lbot-lidx;
845 if (tokill > 0) {
846 version(none) { import core.stdc.stdio; printf(" xx: lidx=%d; ltop=%d; lbot=%d, linecount=%d; tokill=%d\n", lidx, ltop, lbot, mLineCount, tokill); }
847 if (lbot <= mLineCount) memmove(locache+lidx, locache+lbot, (mLineCount-lbot+1)*locache[0].sizeof);
848 lbot -= tokill;
849 mLineCount -= tokill;
851 version(none) { import core.stdc.stdio; printf(" 01: lidx=%d; ltop=%d; lbot=%d, linecount=%d\n", lidx, ltop, lbot, mLineCount); }
852 assert(lidx == lbot);
853 assert(mLineCount > 0);
854 assert(locache[lbot].ofs == cpos+(cpos < gb.textsize ? 1 : 0));
855 return lbot;
858 public:
859 this (GapBuffer agb) nothrow @nogc {
860 assert(agb !is null);
861 gb = agb;
862 initLC();
865 ~this () nothrow @nogc {
866 if (locache !is null) {
867 import core.stdc.stdlib : free;
868 free(locache);
872 public:
873 /// there is always at least one line, so `linecount` is never zero
874 @property int linecount () const pure nothrow @safe @nogc { pragma(inline, true); return mLineCount; }
876 void clear () nothrow @nogc {
877 import core.stdc.stdlib : free;
878 gb.clear();
879 // free old buffers
880 if (locache !is null) { free(locache); locache = null; }
881 // allocate new buffer
882 initLC();
885 /** load file like this:
886 * if (!lc.resizeBuffer(filesize)) throw new Exception("memory?");
887 * scope(failure) lc.clear();
888 * fl.rawReadExact(lc.getBufferPtr[]);
889 * if (!lc.rebuild()) throw new Exception("memory?");
892 /// allocate text buffer for the text of the given size
893 bool resizeBuffer (uint newsize) nothrow @nogc {
894 if (newsize > gb.tbmax) return false;
895 clear();
896 //{ import core.stdc.stdio; printf("resizing buffer to %u bytes\n", newsize); }
897 if (!gb.growTBuf(newsize)) return false;
898 gb.tbused = gb.gapstart = newsize;
899 gb.gapend = gb.tbsize;
900 gb.ensureGap();
901 return true;
904 /// get continuous buffer pointer, so we can read the whole file into it
905 char[] getBufferPtr () nothrow @nogc {
906 gb.moveGapAtEnd();
907 return gb.tbuf[0..gb.textsize];
910 /// count lines, fill line cache, do word wrapping
911 bool rebuild () nothrow {
912 import core.stdc.string : memset;
913 //gb.moveGapAtEnd(); // just in case
914 immutable ts = gb.textsize;
915 const(char)* tb = gb.tbuf;
916 if (gb.mSingleLine) {
917 // easy
918 growLineCache(1);
919 assert(locsize > 0);
920 mLineCount = 1;
921 locache[0..2] = LOCItem.init;
922 locache[1].ofs = ts;
923 return true;
925 version(egeditor_scan_time) auto stt = clockMilli();
926 version(none) {
927 // less memory fragmentation
928 int lcount = gb.countEolsInRange(0, ts)+1; // total number of lines
929 //{ import core.stdc.stdio; printf("loaded %u bytes; %d lines found\n", gb.textsize, lcount); }
930 if (!growLineCache(lcount)) return false;
931 assert(lcount+1 <= locsize);
932 //locache[0..lcount+1] = LOCItem.init; // reset all lines
933 memset(locache, 0, (lcount+1)*locache[0].sizeof); // reset all lines (help compiler a little)
934 uint pos = 0;
935 LOCItem* lcp = locache; // help compiler a little
936 foreach (immutable uint lidx; 0..lcount) {
937 lcp.initWithPos(pos);
938 ++lcp;
939 pos = gb.fastSkipEol(pos);
941 // last line
942 assert(lcp is locache+lcount);
943 lcp.ofs = gb.textsize;
944 } else {
945 // faster scanning
946 if (gb.textsize == 0) {
947 // no text
948 if (!growLineCache(1)) return false; // should have at least one
949 assert(locsize >= 2);
950 locache[0].initWithPos(0);
951 locache[1].initWithPos(0);
952 mLineCount = 1;
953 } else {
954 int lcount = 0; // total number of lines
955 //{ import core.stdc.stdio; printf("loaded %u bytes; %d lines found\n", gb.textsize, lcount); }
956 if (!growLineCache(1)) return false; // should have at least one
957 uint pos = 0;
958 while (pos < ts) {
959 if (lcount+1 >= locsize) { if (!growLineCache(lcount+1)) return false; }
960 locache[lcount++].initWithPos(pos);
961 pos = gb.fastSkipEol(pos);
963 assert(lcount > 0);
964 // hack for last empty line, if it ends with '\n'
965 if (ts && gb[ts-1] == '\n') {
966 if (lcount+1 >= locsize) { if (!growLineCache(lcount+1)) return false; }
967 locache[lcount++].initWithPos(ts);
969 // last line
970 assert(pos == ts);
971 assert(lcount < locsize);
972 locache[lcount].initWithPos(pos);
973 mLineCount = lcount;
976 version(egeditor_scan_time) {
977 import core.stdc.stdio;
978 auto et = clockMilli()-stt;
979 version(egeditor_scan_time_to_file) {
980 if (auto fo = fopen("ztime.log", "a")) {
981 scope(exit) fo.fclose();
982 fo.fprintf("%u lines (%u bytes) scanned in %u milliseconds\n", mLineCount, gb.textsize, cast(uint)et);
984 } else {
985 printf("%u lines (%u bytes) scanned in %u milliseconds\n", mLineCount, gb.textsize, cast(uint)et);
987 stt = clockMilli(); // for wrapping
989 if (mWordWrapWidth > 0) {
990 int lidx = 0;
991 while (lidx < mLineCount) lidx = doWordWrapping(lidx);
992 version(egeditor_scan_time) {
993 import core.stdc.stdio;
994 et = clockMilli()-stt;
995 version(egeditor_scan_time_to_file) {
996 if (auto fo = fopen("ztime.log", "a")) {
997 scope(exit) fo.fclose();
998 fo.fprintf(" %u lines wrapped in %u milliseconds\n", mLineCount, cast(uint)et);
1000 } else {
1001 printf(" %u lines wrapped in %u milliseconds\n", mLineCount, cast(uint)et);
1005 return true;
1008 /// put text into buffer; will either put all the text, or nothing
1009 /// returns success flag
1010 bool append (const(char)[] str...) nothrow { return (put(gb.textsize, str) >= 0); }
1012 /// put text into buffer; will either put all the text, or nothing
1013 /// returns new position or -1
1014 int put (int pos, const(char)[] str...) nothrow {
1015 if (pos < 0) pos = 0;
1016 bool atend = (pos >= gb.textsize);
1017 if (str.length == 0) return pos;
1018 if (atend) pos = gb.textsize;
1019 auto ppos = gb.put(pos, str);
1020 if (ppos < 0) return ppos;
1021 // heal line cache for single-line case
1022 if (gb.mSingleLine) {
1023 assert(mLineCount == 1);
1024 assert(locsize > 1);
1025 assert(locache[0].ofs == 0);
1026 locache[1].ofs = gb.textsize;
1027 locache[0].resetHeightAndWrap();
1028 locache[1].resetHeightAndWrap();
1029 } else {
1030 assert(ppos > pos);
1031 int newlines = GapBuffer.countEols(str);
1032 immutable insertedLines = newlines;
1033 auto lidx = findLineCacheIndex(pos);
1034 immutable int ldelta = ppos-pos;
1035 assert((!atend && lidx >= 0) || (atend && (lidx < 0 || lidx == mLineCount-1)));
1036 if (atend) lidx = mLineCount-1;
1037 int wraplidx = lidx;
1038 if (newlines == 0) {
1039 // no lines was inserted, just repair the length
1040 // no need to collapse wrapped line here, 'cause `doWordWrapping()` will rewrap it anyway
1041 locache[lidx++].resetHeight();
1042 } else {
1043 import core.stdc.string : memmove;
1044 //FIXME: make this faster for wrapped lines
1045 wraplidx = lidx = collapseWrappedLine(wraplidx);
1046 // we will start repairing from the last good line
1047 pos = locache[lidx].ofs;
1048 // inserted some new lines, make room for 'em
1049 growLineCache(mLineCount+newlines);
1050 if (lidx <= mLineCount) memmove(locache+lidx+newlines, locache+lidx, (mLineCount-lidx+1)*locache[0].sizeof);
1051 mLineCount += newlines;
1052 // no need to clear inserted lines, we'll overwrite em
1053 // recalc offsets and lengthes
1054 while (newlines-- >= 0) {
1055 locache[lidx].ofs = pos;
1056 locache[lidx++].resetHeightAndWrap();
1057 pos = gb.fastSkipEol(pos);
1060 // repair line cache (offsets) -- for now; switch to "repair on demand" later?
1061 if (lidx <= mLineCount) foreach (ref lc; locache[lidx..mLineCount+1]) lc.ofs += ldelta;
1062 if (mWordWrapWidth > 0) {
1063 foreach (immutable c; 0..insertedLines+1) wraplidx = doWordWrapping(wraplidx);
1066 return ppos;
1069 /// remove count bytes from the current position; will either remove all of 'em, or nothing
1070 /// returns success flag
1071 bool remove (int pos, int count) nothrow {
1072 if (gb.mSingleLine) {
1073 // easy
1074 if (!gb.remove(pos, count)) return false;
1075 assert(mLineCount == 1);
1076 assert(locsize > 1);
1077 assert(locache[0].ofs == 0);
1078 locache[1].ofs = gb.textsize;
1079 locache[0].resetHeightAndWrap();
1080 locache[1].resetHeightAndWrap();
1081 } else {
1082 // hard
1083 import core.stdc.string : memmove;
1084 if (count < 0) return false;
1085 if (count == 0) return true;
1086 if (pos < 0) pos = 0;
1087 if (pos > gb.textsize) pos = gb.textsize;
1088 if (gb.textsize-pos < count) return false; // not enough text here
1089 auto lidx = findLineCacheIndex(pos);
1090 assert(lidx >= 0);
1091 int newlines = gb.countEolsInRange(pos, count);
1092 if (!gb.remove(pos, count)) return false;
1093 // repair line cache
1094 if (newlines == 0) {
1095 // no need to collapse wrapped line here, 'cause `doWordWrapping()` will rewrap it anyway
1096 locache[lidx].resetHeight();
1097 } else {
1098 import core.stdc.string : memmove;
1099 if (mWordWrapWidth > 0) {
1100 // collapse wordwrapped line into one, it is easier this way; it is safe to collapse lines in modified text
1101 //FIXME: make this faster for wrapped lines
1102 lidx = collapseWrappedLine(lidx);
1103 // collapse deleted lines too, so we can remove 'em as if they were normal ones
1104 foreach (immutable c; 1..newlines+1) collapseWrappedLine(lidx+c);
1106 // remove unused lines
1107 if (lidx+1 <= mLineCount) memmove(locache+lidx+1, locache+lidx+1+newlines, (mLineCount-lidx)*locache[0].sizeof);
1108 mLineCount -= newlines;
1109 // fix current line
1110 locache[lidx].resetHeightAndWrap();
1112 if (lidx+1 <= mLineCount) foreach (ref lc; locache[lidx+1..mLineCount+1]) lc.ofs -= count;
1113 if (mWordWrapWidth > 0) {
1114 lidx = doWordWrapping(lidx);
1115 // and next one, 'cause it was modified by collapser
1116 doWordWrapping(lidx);
1119 return true;
1122 int lineHeightPixels (int lidx, bool forceRecalc=false) nothrow {
1123 int h;
1124 assert(textMeter !is null);
1125 if (lidx < 0 || mLineCount == 0 || lidx >= mLineCount) {
1126 textMeter.reset(0);
1127 h = (textMeter.currheight > 0 ? textMeter.currheight : 1);
1128 textMeter.finish();
1129 } else {
1130 if (forceRecalc || !locache[lidx].validHeight) locache[lidx].height = calcLineHeight(lidx);
1131 h = locache[lidx].height;
1133 return h;
1136 bool isLastWrappedLine (int lidx) nothrow @nogc { pragma(inline, true); return (lidx >= 0 && lidx < mLineCount ? !locache[lidx].viswrap : true); }
1137 bool isWrappedLine (int lidx) nothrow @nogc { pragma(inline, true); return (lidx >= 0 && lidx < mLineCount ? locache[lidx].viswrap : false); }
1139 /// get number of *symbols* to line end (this is not always equal to number of bytes for utfuck)
1140 int syms2eol (int pos) nothrow {
1141 immutable ts = gb.textsize;
1142 if (pos < 0) pos = 0;
1143 if (pos >= ts) return 0;
1144 int epos = line2pos(pos2line(pos)+1);
1145 if (!utfuck) return epos-pos; // fast path
1146 // slow path
1147 int count = 0;
1148 while (pos < epos) {
1149 pos += gb.utfuckLenAt!true(pos);
1150 ++count;
1152 return count;
1155 /// get line for the given position
1156 int pos2line (int pos) nothrow {
1157 immutable ts = gb.textsize;
1158 if (pos < 0) return 0;
1159 if (pos == 0 || ts == 0) return 0;
1160 if (pos >= ts) return mLineCount-1; // end of text: no need to update line offset cache
1161 if (mLineCount == 1) return 0;
1162 int lcidx = findLineCacheIndex(pos);
1163 assert(lcidx >= 0 && lcidx < mLineCount);
1164 return lcidx;
1167 /// get position (starting) for the given line
1168 /// it will be 0 for negative lines, and `textsize` for positive out of bounds lines
1169 int line2pos (int lidx) nothrow {
1170 if (lidx < 0 || gb.textsize == 0) return 0;
1171 if (lidx > mLineCount-1) return gb.textsize;
1172 if (mLineCount == 1) {
1173 assert(lidx == 0);
1174 return 0;
1176 return locache[lidx].ofs;
1179 alias linestart = line2pos; /// ditto
1181 /// get ending position for the given line (position of '\n')
1182 /// it may be `textsize`, though, if this is the last line, and it doesn't end with '\n'
1183 int lineend (int lidx) nothrow {
1184 if (lidx < 0 || gb.textsize == 0) return 0;
1185 if (lidx > mLineCount-1) return gb.textsize;
1186 if (mLineCount == 1) {
1187 assert(lidx == 0);
1188 return gb.textsize;
1190 if (lidx == mLineCount-1) return gb.textsize;
1191 auto res = locache[lidx+1].ofs;
1192 assert(res > 0);
1193 return res-1;
1196 // move by `x` utfucked chars
1197 // `pos` should point to line start
1198 // will never go beyond EOL
1199 private int utfuck_x2pos (int x, int pos) nothrow {
1200 immutable ts = gb.textsize;
1201 const(char)* tbuf = gb.tbuf;
1202 if (pos < 0) pos = 0;
1203 if (mWordWrapWidth <= 0 || gb.mSingleLine) {
1204 if (gb.mSingleLine) {
1205 // single line
1206 while (pos < ts && x > 0) {
1207 pos += gb.utfuckLenAt!true(pos); // "always positive"
1208 --x;
1210 } else {
1211 // multiline
1212 while (pos < ts && x > 0) {
1213 if (tbuf[gb.pos2real(pos)] == '\n') break;
1214 pos += gb.utfuckLenAt!true(pos); // "always positive"
1215 --x;
1218 } else {
1219 if (pos >= ts) return ts;
1220 int lidx = findLineCacheIndex(pos);
1221 assert(lidx >= 0);
1222 int epos = locache[lidx+1].ofs;
1223 while (pos < epos && x > 0) {
1224 if (tbuf[gb.pos2real(pos)] == '\n') break;
1225 pos += gb.utfuckLenAt!true(pos); // "always positive"
1226 --x;
1229 if (pos > ts) pos = ts;
1230 return pos;
1233 // convert line offset to screen x coordinate
1234 // `pos` should point into line (somewhere)
1235 private int utfuck_pos2x(bool dotabs=false) (int pos) nothrow {
1236 immutable ts = gb.textsize;
1237 if (pos < 0) pos = 0;
1238 if (pos > ts) pos = ts;
1239 immutable bool sl = gb.mSingleLine;
1240 const(char)* tbuf = gb.tbuf;
1241 int x = 0;
1242 if (mWordWrapWidth <= 0) {
1243 // find line start
1244 int spos = pos;
1245 if (!sl) {
1246 while (spos > 0 && tbuf[gb.pos2real(spos-1)] != '\n') --spos;
1247 } else {
1248 spos = 0;
1250 // now `spos` points to line start; walk over utfucked chars
1251 while (spos < pos) {
1252 char ch = tbuf[gb.pos2real(spos)];
1253 if (!sl && ch == '\n') break;
1254 static if (dotabs) {
1255 if (ch == '\t' && visualtabs && tabsize > 0) {
1256 x = ((x+tabsize)/tabsize)*tabsize;
1257 } else {
1258 ++x;
1260 } else {
1261 ++x;
1263 spos += (ch < 128 ? 1 : gb.utfuckLenAt!true(spos));
1265 } else {
1266 // word-wrapped, eh...
1267 int lidx = findLineCacheIndex(pos);
1268 assert(lidx >= 0);
1269 int spos = locache[lidx].ofs;
1270 int epos = locache[lidx+1].ofs;
1271 assert(pos < epos);
1272 // now `spos` points to line start; walk over utfucked chars
1273 while (spos < pos) {
1274 char ch = tbuf[gb.pos2real(spos)];
1275 if (!sl && ch == '\n') break;
1276 static if (dotabs) {
1277 if (ch == '\t' && visualtabs && tabsize > 0) {
1278 x = ((x+tabsize)/tabsize)*tabsize;
1279 } else {
1280 ++x;
1282 } else {
1283 ++x;
1285 spos += (ch < 128 ? 1 : gb.utfuckLenAt!true(spos));
1288 return x;
1291 /// get position for the given text coordinates
1292 int xy2pos (int x, int y) nothrow {
1293 auto ts = gb.textsize;
1294 if (ts == 0 || y < 0) return 0;
1295 if (y > mLineCount-1) return ts;
1296 if (x < 0) x = 0;
1297 if (mLineCount == 1) {
1298 assert(y == 0);
1299 return (!utfuck ? (x < ts ? x : ts) : utfuck_x2pos(x, 0));
1301 uint ls = locache[y].ofs;
1302 uint le = locache[y+1].ofs;
1303 if (ls == le) {
1304 // this should be last empty line
1305 //if (y != mLineCount-1) { import std.format; assert(0, "fuuuuu; y=%u; lc=%u; locused=%u".format(y, mLineCount, locused)); }
1306 assert(y == mLineCount-1);
1307 return ls;
1309 if (!utfuck) {
1310 // we want line end (except for last empty line, where we want end-of-text)
1311 if (x >= le-ls) return (y != mLineCount-1 ? le-1 : le);
1312 return ls+x; // somewhere in line
1313 } else {
1314 // fuck
1315 return utfuck_x2pos(x, ls);
1319 /// get text coordinates for the given position
1320 void pos2xy (int pos, out int x, out int y) nothrow {
1321 immutable ts = gb.textsize;
1322 if (pos <= 0 || ts == 0) return; // x and y autoinited
1323 if (pos > ts) pos = ts;
1324 if (mLineCount == 1) {
1325 // y is autoinited
1326 x = (!utfuck ? pos : utfuck_pos2x(pos));
1327 return;
1329 const(char)* tbuf = gb.tbuf;
1330 if (pos == ts) {
1331 // end of text: no need to update line offset cache
1332 y = mLineCount-1;
1333 if (!gb.mSingleLine) {
1334 while (pos > 0 && tbuf[gb.pos2real(--pos)] != '\n') ++x;
1335 } else {
1336 x = pos;
1338 return;
1340 int lcidx = findLineCacheIndex(pos);
1341 assert(lcidx >= 0 && lcidx < mLineCount);
1342 immutable ls = locache[lcidx].ofs;
1343 //auto le = lineofsc[lcidx+1];
1344 //!assert(pos >= ls && pos < le);
1345 y = cast(uint)lcidx;
1346 x = (!utfuck ? pos-ls : utfuck_pos2x(pos));
1349 /// get text coordinates (adjusted for tabs) for the given position
1350 void pos2xyVT (int pos, out int x, out int y) nothrow {
1351 if (!utfuck && (!visualtabs || tabsize == 0)) { pos2xy(pos, x, y); return; }
1353 void tabbedX() (int ls) {
1354 x = 0;
1355 version(none) {
1356 //TODO:FIXME: fix this!
1357 while (ls < pos) {
1358 int tp = fastFindCharIn(ls, pos-ls, '\t');
1359 if (tp < 0) { x += pos-ls; return; }
1360 x += tp-ls;
1361 ls = tp;
1362 while (ls < pos && tbuf[pos2real(ls++)] == '\t') {
1363 x = ((x+tabsize)/tabsize)*tabsize;
1366 } else {
1367 const(char)* tbuf = gb.tbuf;
1368 while (ls < pos) {
1369 if (tbuf[gb.pos2real(ls++)] == '\t') x = ((x+tabsize)/tabsize)*tabsize; else ++x;
1374 auto ts = gb.textsize;
1375 if (pos <= 0 || ts == 0) return; // x and y autoinited
1376 if (pos > ts) pos = ts;
1377 if (mLineCount == 1) {
1378 // y is autoinited
1379 if (utfuck) { x = utfuck_pos2x!true(pos); return; }
1380 if (!visualtabs || tabsize == 0) { x = pos; return; }
1381 tabbedX(0);
1382 return;
1384 if (pos == ts) {
1385 // end of text: no need to update line offset cache
1386 const(char)* tbuf = gb.tbuf;
1387 y = mLineCount-1;
1388 while (pos > 0 && (gb.mSingleLine || tbuf[gb.pos2real(--pos)] != '\n')) ++x;
1389 if (utfuck) { x = utfuck_pos2x!true(ts); return; }
1390 if (visualtabs && tabsize != 0) { int ls = pos+1; pos = ts; tabbedX(ls); return; }
1391 return;
1393 int lcidx = findLineCacheIndex(pos);
1394 assert(lcidx >= 0 && lcidx < mLineCount);
1395 auto ls = locache[lcidx].ofs;
1396 //auto le = lineofsc[lcidx+1];
1397 //!assert(pos >= ls && pos < le);
1398 y = cast(uint)lcidx;
1399 if (utfuck) { x = utfuck_pos2x!true(pos); return; }
1400 if (visualtabs && tabsize > 0) { tabbedX(ls); return; }
1401 x = pos-ls;
1406 // ////////////////////////////////////////////////////////////////////////// //
1407 private final class UndoStack {
1408 public:
1409 enum Type : ubyte {
1410 None,
1412 CurMove, // pos: old position; len: old topline (sorry)
1413 TextRemove, // pos: position; len: length; deleted chars follows
1414 TextInsert, // pos: position; len: length
1415 // grouping
1416 GroupStart,
1417 GroupEnd,
1420 private:
1421 static align(1) struct Action {
1422 align(1):
1423 enum Flag : ubyte {
1424 BlockMarking = 1<<0, // block marking state
1425 LastBE = 1<<1, // last block move was at end?
1426 Changed = 1<<2, // "changed" flag
1427 //VisTabs = 1<<3, // editor was in "visual tabs" mode
1430 @property nothrow pure @safe @nogc {
1431 bool bmarking () const { pragma(inline, true); return (flags&Flag.BlockMarking) != 0; }
1432 bool lastbe () const { pragma(inline, true); return (flags&Flag.LastBE) != 0; }
1433 bool txchanged () const { pragma(inline, true); return (flags&Flag.Changed) != 0; }
1434 //bool vistabs () const { pragma(inline, true); return (flags&Flag.VisTabs) != 0; }
1436 void bmarking (bool v) { pragma(inline, true); if (v) flags |= Flag.BlockMarking; else flags &= ~(Flag.BlockMarking); }
1437 void lastbe (bool v) { pragma(inline, true); if (v) flags |= Flag.LastBE; else flags &= ~(Flag.LastBE); }
1438 void txchanged (bool v) { pragma(inline, true); if (v) flags |= Flag.Changed; else flags &= ~(Flag.Changed); }
1439 //void vistabs (bool v) { pragma(inline, true); if (v) flags |= Flag.VisTabs; else flags &= ~Flag.VisTabs; }
1442 Type type;
1443 int pos;
1444 int len;
1445 // after undoing action
1446 int cx, cy, topline, xofs;
1447 int bs, be; // block position
1448 ubyte flags;
1449 // data follows
1450 char[0] data;
1453 version(Posix) private import core.sys.posix.unistd : off_t;
1455 private:
1456 version(Posix) int tmpfd = -1; else enum tmpfd = -1;
1457 version(Posix) off_t tmpsize = 0;
1458 bool asRedo;
1459 // undo buffer format:
1460 // last uint is always record size (not including size uints); record follows (up), then size again
1461 uint maxBufSize = 32*1024*1024;
1462 ubyte* undoBuffer;
1463 uint ubUsed, ubSize;
1464 bool asRich;
1466 final:
1467 version(Posix) void initTempFD () nothrow {
1468 import core.sys.posix.fcntl /*: open*/;
1469 static if (is(typeof(O_CLOEXEC)) && is(typeof(O_TMPFILE))) {
1470 auto xfd = open("/tmp/_egundoz", O_RDWR|O_CLOEXEC|O_TMPFILE, 0x1b6/*0o600*/);
1471 if (xfd < 0) return;
1472 tmpfd = xfd;
1473 tmpsize = 0;
1477 // returns record size
1478 version(Posix) uint loadLastRecord(bool fullrecord=true) (bool dropit=false) nothrow {
1479 import core.stdc.stdio : SEEK_SET, SEEK_END;
1480 import core.sys.posix.unistd : lseek, read;
1481 assert(tmpfd >= 0);
1482 uint sz;
1483 if (tmpsize < sz.sizeof) return 0;
1484 lseek(tmpfd, tmpsize-sz.sizeof, SEEK_SET);
1485 if (read(tmpfd, &sz, sz.sizeof) != sz.sizeof) return 0;
1486 if (tmpsize < sz+sz.sizeof*2) return 0;
1487 if (sz < Action.sizeof) return 0;
1488 lseek(tmpfd, tmpsize-sz-sz.sizeof, SEEK_SET);
1489 static if (fullrecord) {
1490 alias rsz = sz;
1491 } else {
1492 auto rsz = cast(uint)Action.sizeof;
1494 if (ubSize < rsz) {
1495 import core.stdc.stdlib : realloc;
1496 auto nb = cast(ubyte*)realloc(undoBuffer, rsz);
1497 if (nb is null) return 0;
1498 undoBuffer = nb;
1499 ubSize = rsz;
1501 ubUsed = rsz;
1502 if (read(tmpfd, undoBuffer, rsz) != rsz) return 0;
1503 if (dropit) tmpsize -= sz+sz.sizeof*2;
1504 return rsz;
1507 bool saveLastRecord () nothrow {
1508 version(Posix) {
1509 import core.stdc.stdio : SEEK_SET;
1510 import core.sys.posix.unistd : lseek, write;
1511 if (tmpfd >= 0) {
1512 assert(ubUsed >= Action.sizeof);
1513 scope(exit) {
1514 import core.stdc.stdlib : free;
1515 if (ubUsed > 65536) {
1516 free(undoBuffer);
1517 undoBuffer = null;
1518 ubUsed = ubSize = 0;
1521 auto ofs = lseek(tmpfd, tmpsize, SEEK_SET);
1522 if (write(tmpfd, &ubUsed, ubUsed.sizeof) != ubUsed.sizeof) return false;
1523 if (write(tmpfd, undoBuffer, ubUsed) != ubUsed) return false;
1524 if (write(tmpfd, &ubUsed, ubUsed.sizeof) != ubUsed.sizeof) return false;
1525 write(tmpfd, &tmpsize, tmpsize.sizeof);
1526 tmpsize += ubUsed+uint.sizeof*2;
1529 return true;
1532 // return `true` if something was removed
1533 bool removeFirstUndo () nothrow {
1534 import core.stdc.string : memmove;
1535 version(Posix) assert(tmpfd < 0);
1536 if (ubUsed == 0) return false;
1537 uint np = (*cast(uint*)undoBuffer)+4*2;
1538 assert(np <= ubUsed);
1539 if (np == ubUsed) { ubUsed = 0; return true; }
1540 memmove(undoBuffer, undoBuffer+np, ubUsed-np);
1541 ubUsed -= np;
1542 return true;
1545 // return `null` if it can't; undo buffer is in invalid state then
1546 Action* addUndo (int dataSize) nothrow {
1547 import core.stdc.stdlib : realloc;
1548 import core.stdc.string : memset;
1549 version(Posix) if (tmpfd < 0) {
1550 if (dataSize < 0 || dataSize >= maxBufSize) return null; // no room
1551 uint asz = cast(uint)Action.sizeof+dataSize+4*2;
1552 if (asz > maxBufSize) return null;
1553 if (ubSize-ubUsed < asz) {
1554 uint nasz = ubUsed+asz;
1555 if (nasz&0xffff) nasz = (nasz|0xffff)+1;
1556 if (nasz > maxBufSize) {
1557 while (ubSize-ubUsed < asz) { if (!removeFirstUndo()) return null; }
1558 } else {
1559 auto nb = cast(ubyte*)realloc(undoBuffer, nasz);
1560 if (nb is null) {
1561 while (ubSize-ubUsed < asz) { if (!removeFirstUndo()) return null; }
1562 } else {
1563 undoBuffer = nb;
1564 ubSize = nasz;
1568 assert(ubSize-ubUsed >= asz);
1569 *cast(uint*)(undoBuffer+ubUsed) = asz-4*2;
1570 auto res = cast(Action*)(undoBuffer+ubUsed+4);
1571 *cast(uint*)(undoBuffer+ubUsed+asz-4) = asz-4*2;
1572 ubUsed += asz;
1573 memset(res, 0, asz-4*2);
1574 return res;
1577 // has temp file
1578 if (dataSize < 0 || dataSize >= int.max/4) return null; // wtf?!
1579 uint asz = cast(uint)Action.sizeof+dataSize;
1580 if (ubSize < asz) {
1581 auto nb = cast(ubyte*)realloc(undoBuffer, asz);
1582 if (nb is null) return null;
1583 undoBuffer = nb;
1584 ubSize = asz;
1586 ubUsed = asz;
1587 auto res = cast(Action*)undoBuffer;
1588 memset(res, 0, asz);
1589 return res;
1593 // can return null
1594 Action* lastUndoHead () nothrow {
1595 version(Posix) if (tmpfd >= 0) {
1596 if (loadLastRecord!false()) return null;
1597 return cast(Action*)undoBuffer;
1600 if (ubUsed == 0) return null;
1601 auto sz = *cast(uint*)(undoBuffer+ubUsed-4);
1602 return cast(Action*)(undoBuffer+ubUsed-4-sz);
1606 Action* popUndo () nothrow {
1607 version(Posix) if (tmpfd >= 0) {
1608 auto len = loadLastRecord!true(true); // pop it
1609 return (len ? cast(Action*)undoBuffer : null);
1612 if (ubUsed == 0) return null;
1613 auto sz = *cast(uint*)(undoBuffer+ubUsed-4);
1614 auto res = cast(Action*)(undoBuffer+ubUsed-4-sz);
1615 ubUsed -= sz+4*2;
1616 return res;
1620 public:
1621 this (bool aAsRich, bool aAsRedo, bool aIntoFile) nothrow {
1622 asRedo = aAsRedo;
1623 asRich = aAsRich;
1624 if (aIntoFile) {
1625 initTempFD();
1626 if (tmpfd < 0) {
1627 //version(aliced) { import iv.rawtty; ttyBeep(); }
1632 ~this () nothrow {
1633 import core.stdc.stdlib : free;
1634 import core.sys.posix.unistd : close;
1635 if (tmpfd >= 0) { close(tmpfd); tmpfd = -1; }
1636 if (undoBuffer !is null) free(undoBuffer);
1639 void clear (bool doclose=false) nothrow {
1640 ubUsed = 0;
1641 if (doclose) {
1642 version(Posix) {
1643 import core.stdc.stdlib : free;
1644 if (tmpfd >= 0) {
1645 import core.sys.posix.unistd : close;
1646 close(tmpfd);
1647 tmpfd = -1;
1650 if (undoBuffer !is null) free(undoBuffer);
1651 undoBuffer = null;
1652 ubSize = 0;
1653 } else {
1654 if (ubSize > 65536) {
1655 import core.stdc.stdlib : realloc;
1656 auto nb = cast(ubyte*)realloc(undoBuffer, 65536);
1657 if (nb !is null) {
1658 undoBuffer = nb;
1659 ubSize = 65536;
1662 version(Posix) if (tmpfd >= 0) tmpsize = 0;
1666 void alwaysChanged () nothrow {
1667 if (tmpfd < 0) {
1668 auto pos = 0;
1669 while (pos < ubUsed) {
1670 auto sz = *cast(uint*)(undoBuffer+pos);
1671 auto res = cast(Action*)(undoBuffer+pos+4);
1672 pos += sz+4*2;
1673 switch (res.type) {
1674 case Type.TextRemove:
1675 case Type.TextInsert:
1676 res.txchanged = true;
1677 break;
1678 default:
1681 } else {
1682 version(Posix) {
1683 import core.stdc.stdio : SEEK_SET;
1684 import core.sys.posix.unistd : lseek, read, write;
1685 off_t cpos = 0;
1686 Action act;
1687 while (cpos < tmpsize) {
1688 uint sz;
1689 lseek(tmpfd, cpos, SEEK_SET);
1690 if (read(tmpfd, &sz, sz.sizeof) != sz.sizeof) break;
1691 if (sz < Action.sizeof) assert(0, "wtf?!");
1692 if (read(tmpfd, &act, Action.sizeof) != Action.sizeof) break;
1693 switch (act.type) {
1694 case Type.TextRemove:
1695 case Type.TextInsert:
1696 if (act.txchanged != true) {
1697 act.txchanged = true;
1698 lseek(tmpfd, cpos+sz.sizeof, SEEK_SET);
1699 write(tmpfd, &act, Action.sizeof);
1701 break;
1702 default:
1704 cpos += sz+sz.sizeof*2;
1710 private void fillCurPos (Action* ua, EditorEngine ed) nothrow {
1711 if (ua !is null && ed !is null) {
1712 //TODO: correct x according to "visual tabs" mode (i.e. make it "normal x")
1713 ua.cx = ed.cx;
1714 ua.cy = ed.cy;
1715 ua.topline = ed.mTopLine;
1716 ua.xofs = ed.mXOfs;
1717 ua.bs = ed.bstart;
1718 ua.be = ed.bend;
1719 ua.bmarking = ed.markingBlock;
1720 ua.lastbe = ed.lastBGEnd;
1721 ua.txchanged = ed.txchanged;
1722 //ua.vistabs = ed.visualtabs;
1726 version(egeditor_record_movement_undo)
1727 bool addCurMove (EditorEngine ed, bool fromRedo=false) nothrow {
1728 if (auto lu = lastUndoHead()) {
1729 if (lu.type == Type.CurMove) {
1730 if (lu.cx == ed.cx && lu.cy == ed.cy && lu.topline == ed.mTopLine && lu.xofs == ed.mXOfs &&
1731 lu.bs == ed.bstart && lu.be == ed.bend && lu.bmarking == ed.markingBlock &&
1732 lu.lastbe == ed.lastBGEnd /*&& lu.vistabs == ed.visualtabs*/) return true;
1735 if (!asRedo && !fromRedo && ed.redo !is null) ed.redo.clear();
1736 auto act = addUndo(0);
1737 if (act is null) { clear(); return false; }
1738 act.type = Type.CurMove;
1739 fillCurPos(act, ed);
1740 return saveLastRecord();
1743 bool addTextRemove (EditorEngine ed, int pos, int count, bool fromRedo=false) nothrow {
1744 if (!asRedo && !fromRedo && ed.redo !is null) ed.redo.clear();
1745 GapBuffer gb = ed.gb;
1746 assert(gb !is null);
1747 if (pos < 0 || pos >= gb.textsize) return true;
1748 if (count < 1) return true;
1749 if (count >= maxBufSize) { clear(); return false; }
1750 if (count > gb.textsize-pos) { clear(); return false; }
1751 int realcount = count;
1752 if (asRich && realcount > 0) {
1753 if (realcount >= int.max/gb.hbuf[0].sizeof/2) return false;
1754 realcount += realcount*cast(int)gb.hbuf[0].sizeof;
1756 auto act = addUndo(realcount);
1757 if (act is null) { clear(); return false; }
1758 act.type = Type.TextRemove;
1759 act.pos = pos;
1760 act.len = count;
1761 fillCurPos(act, ed);
1762 auto dp = act.data.ptr;
1763 while (count--) *dp++ = gb[pos++];
1764 // save attrs for rich editor
1765 if (asRich && realcount > 0) {
1766 pos = act.pos;
1767 count = act.len;
1768 auto dph = cast(GapBuffer.HighState*)dp;
1769 while (count--) *dph++ = gb.hi(pos++);
1771 return saveLastRecord();
1774 bool addTextInsert (EditorEngine ed, int pos, int count, bool fromRedo=false) nothrow {
1775 if (!asRedo && !fromRedo && ed.redo !is null) ed.redo.clear();
1776 auto act = addUndo(0);
1777 if (act is null) { clear(); return false; }
1778 act.type = Type.TextInsert;
1779 act.pos = pos;
1780 act.len = count;
1781 fillCurPos(act, ed);
1782 return saveLastRecord();
1785 bool addGroupStart (EditorEngine ed, bool fromRedo=false) nothrow {
1786 if (!asRedo && !fromRedo && ed.redo !is null) ed.redo.clear();
1787 auto act = addUndo(0);
1788 if (act is null) { clear(); return false; }
1789 act.type = Type.GroupStart;
1790 fillCurPos(act, ed);
1791 return saveLastRecord();
1794 bool addGroupEnd (EditorEngine ed, bool fromRedo=false) nothrow {
1795 if (!asRedo && !fromRedo && ed.redo !is null) ed.redo.clear();
1796 auto act = addUndo(0);
1797 if (act is null) { clear(); return false; }
1798 act.type = Type.GroupEnd;
1799 fillCurPos(act, ed);
1800 return saveLastRecord();
1803 @property bool hasUndo () const pure nothrow @safe @nogc { pragma(inline, true); return (tmpfd < 0 ? (ubUsed > 0) : (tmpsize > 0)); }
1805 private bool copyAction (Action* ua) nothrow {
1806 import core.stdc.string : memcpy;
1807 if (ua is null) return true;
1808 auto na = addUndo(ua.type == Type.TextRemove ? ua.len : 0);
1809 if (na is null) return false;
1810 memcpy(na, ua, Action.sizeof+(ua.type == Type.TextRemove ? ua.len : 0));
1811 return saveLastRecord();
1814 // return "None" in case of error
1815 Type undoAction (EditorEngine ed) {
1816 UndoStack oppos = (asRedo ? ed.undo : ed.redo);
1817 assert(ed !is null);
1818 auto ua = popUndo();
1819 if (ua is null) return Type.None;
1820 //debug(egauto) if (!asRedo) { { import iv.vfs; auto fo = VFile("z00_undo.bin", "a"); fo.writeln(*ua); } }
1821 Type res = ua.type;
1822 final switch (ua.type) {
1823 case Type.None: assert(0, "wtf?!");
1824 case Type.GroupStart:
1825 case Type.GroupEnd:
1826 if (oppos !is null) { if (!oppos.copyAction(ua)) oppos.clear(); }
1827 break;
1828 case Type.CurMove:
1829 version(egeditor_record_movement_undo) {
1830 if (oppos !is null) { if (oppos.addCurMove(ed, asRedo) == Type.None) oppos.clear(); }
1831 break;
1832 } else {
1833 assert(0, "egeditor undo: this should never happen");
1835 case Type.TextInsert: // remove inserted text
1836 if (oppos !is null) { if (oppos.addTextRemove(ed, ua.pos, ua.len, asRedo) == Type.None) oppos.clear(); }
1837 //ed.writeLogAction(ua.pos, -ua.len);
1838 ed.ubTextRemove(ua.pos, ua.len);
1839 break;
1840 case Type.TextRemove: // insert removed text
1841 if (oppos !is null) { if (oppos.addTextInsert(ed, ua.pos, ua.len, asRedo) == Type.None) oppos.clear(); }
1842 if (ed.ubTextInsert(ua.pos, ua.data.ptr[0..ua.len])) {
1843 if (asRich) ed.ubTextSetAttrs(ua.pos, (cast(GapBuffer.HighState*)(ua.data.ptr+ua.len))[0..ua.len]);
1845 //ed.writeLogAction(ua.pos, ua.len);
1846 break;
1848 //FIXME: optimize redraw
1849 if (ua.bs != ed.bstart || ua.be != ed.bend) {
1850 if (ua.bs < ua.be) {
1851 // undo has block
1852 if (ed.bstart < ed.bend) ed.markLinesDirtySE(ed.lc.pos2line(ed.bstart), ed.lc.pos2line(ed.bend)); // old block is dirty
1853 ed.markLinesDirtySE(ed.lc.pos2line(ua.bs), ed.lc.pos2line(ua.be)); // new block is dirty
1854 } else {
1855 // undo has no block
1856 if (ed.bstart < ed.bend) ed.markLinesDirtySE(ed.lc.pos2line(ed.bstart), ed.lc.pos2line(ed.bend)); // old block is dirty
1859 ed.bstart = ua.bs;
1860 ed.bend = ua.be;
1861 ed.markingBlock = ua.bmarking;
1862 ed.lastBGEnd = ua.lastbe;
1863 // don't restore "visual tabs" mode
1864 //TODO: correct x according to "visual tabs" mode (i.e. make it "visual x")
1865 ed.cx = ua.cx;
1866 ed.cy = ua.cy;
1867 ed.mTopLine = ua.topline;
1868 ed.mXOfs = ua.xofs;
1869 ed.txchanged = ua.txchanged;
1870 return res;
1875 // ////////////////////////////////////////////////////////////////////////// //
1876 /// main editor engine: does all the undo/redo magic, block management, etc.
1877 class EditorEngine {
1878 public:
1880 enum CodePage : ubyte {
1881 koi8u, ///
1882 cp1251, ///
1883 cp866, ///
1885 CodePage codepage = CodePage.koi8u; ///
1887 /// from koi to codepage
1888 final char recodeCharTo (char ch) pure const nothrow {
1889 pragma(inline, true);
1890 return
1891 codepage == CodePage.cp1251 ? uni2cp1251(koi2uni(ch)) :
1892 codepage == CodePage.cp866 ? uni2cp866(koi2uni(ch)) :
1896 /// from codepage to koi
1897 final char recodeCharFrom (char ch) pure const nothrow {
1898 pragma(inline, true);
1899 return
1900 codepage == CodePage.cp1251 ? uni2koi(cp12512uni(ch)) :
1901 codepage == CodePage.cp866 ? uni2koi(cp8662uni(ch)) :
1905 /// recode to codepage
1906 final char recodeU2B (dchar dch) pure const nothrow {
1907 final switch (codepage) {
1908 case CodePage.koi8u: return uni2koi(dch);
1909 case CodePage.cp1251: return uni2cp1251(dch);
1910 case CodePage.cp866: return uni2cp866(dch);
1914 /// should not be called for utfuck mode
1915 final dchar recode1b (char ch) pure const nothrow {
1916 final switch (codepage) {
1917 case CodePage.koi8u: return koi2uni(ch);
1918 case CodePage.cp1251: return cp12512uni(ch);
1919 case CodePage.cp866: return cp8662uni(ch);
1923 protected:
1924 int lineHeightPixels = 0; /// <0: use line height API, proportional fonts; 0: everything is cell-based (tty); >0: constant line height in pixels; proprotional fonts
1925 int prevTopLine = -1;
1926 int mTopLine = 0;
1927 int prevXOfs = -1;
1928 int mXOfs = 0;
1929 int cx, cy;
1930 int[] dirtyLines; // line heights or 0 if not dirty; hack!
1931 int winx, winy, winw, winh;
1932 GapBuffer gb;
1933 LineCache lc;
1934 EditorHL hl;
1935 UndoStack undo, redo;
1936 int bstart = -1, bend = -1; // marked block position
1937 bool markingBlock;
1938 bool lastBGEnd; // last block grow was at end?
1939 bool txchanged;
1940 bool mReadOnly; // has any effect only if you are using `insertText()` and `deleteText()` API!
1941 bool mSingleLine; // has any effect only if you are using `insertText()` and `deleteText()` API!
1942 bool mKillTextOnChar; // mostly for single-line: remove all text on new char; will autoreset on move
1944 char[] indentText; // this buffer is actively reused, do not expose!
1945 int inPasteMode;
1947 bool mAsRich; /// this is "rich editor", so engine should save/restore highlighting info in undo
1949 protected:
1950 bool[int] linebookmarked; /// is this line bookmarked?
1952 public:
1953 //EgTextMeter textMeter; /// *MUST* be set when `inPixels` is true
1954 final @property EgTextMeter textMeter () nothrow @nogc { return lc.textMeter; }
1955 final @property void textMeter (EgTextMeter tm) nothrow @nogc { lc.textMeter = tm; }
1957 final @property int wordWrapPos () const nothrow @nogc { pragma(inline, true); return lc.mWordWrapWidth; }
1958 final @property void wordWrapPos (int v) nothrow {
1959 if (v < 0) v = 0;
1960 if (lc.mWordWrapWidth != v) {
1961 auto pos = curpos;
1962 lc.mWordWrapWidth = v;
1963 lc.rebuild();
1964 gotoPos!true(pos);
1968 public:
1969 /// is editor in "paste mode" (i.e. we are pasting chars from clipboard, and should skip autoindenting)?
1970 final @property bool pasteMode () const pure nothrow @safe @nogc { return (inPasteMode > 0); }
1971 final resetPasteMode () pure nothrow @safe @nogc { inPasteMode = 0; } /// reset "paste mode"
1974 void clearBookmarks () nothrow { linebookmarked.clear(); }
1976 enum BookmarkChangeMode { Toggle, Set, Reset } ///
1979 void bookmarkChange (int cy, BookmarkChangeMode mode) nothrow {
1980 if (cy < 0 || cy >= lc.linecount) return;
1981 if (mSingleLine) return; // ignore for single-line mode
1982 final switch (mode) {
1983 case BookmarkChangeMode.Toggle:
1984 if (cy in linebookmarked) linebookmarked.remove(cy); else linebookmarked[cy] = true;
1985 markLinesDirty(cy, 1);
1986 break;
1987 case BookmarkChangeMode.Set:
1988 if (cy !in linebookmarked) {
1989 linebookmarked[cy] = true;
1990 markLinesDirty(cy, 1);
1992 break;
1993 case BookmarkChangeMode.Reset:
1994 if (cy in linebookmarked) {
1995 linebookmarked.remove(cy);
1996 markLinesDirty(cy, 1);
1998 break;
2003 final void doBookmarkToggle () nothrow { pragma(inline, true); bookmarkChange(cy, BookmarkChangeMode.Toggle); }
2006 final @property bool isLineBookmarked (int lidx) nothrow {
2007 pragma(inline, true);
2008 return ((lidx in linebookmarked) !is null);
2012 final void doBookmarkJumpUp () nothrow {
2013 int bestBM = -1;
2014 foreach (int lidx; linebookmarked.byKey) {
2015 if (lidx < cy && lidx > bestBM) bestBM = lidx;
2017 if (bestBM >= 0) {
2018 version(egeditor_record_movement_undo) pushUndoCurPos();
2019 cy = bestBM;
2020 normXY;
2021 growBlockMark();
2022 makeCurLineVisibleCentered();
2027 final void doBookmarkJumpDown () nothrow {
2028 int bestBM = int.max;
2029 foreach (int lidx; linebookmarked.byKey) {
2030 if (lidx > cy && lidx < bestBM) bestBM = lidx;
2032 if (bestBM < lc.linecount) {
2033 version(egeditor_record_movement_undo) pushUndoCurPos();
2034 cy = bestBM;
2035 normXY;
2036 growBlockMark();
2037 makeCurLineVisibleCentered();
2041 ///WARNING! don't mutate bookmarks here!
2042 final void forEachBookmark (scope void delegate (int lidx) dg) {
2043 if (dg is null) return;
2044 foreach (int lidx; linebookmarked.byKey) dg(lidx);
2047 /// call this from `willBeDeleted()` (only!) to fix bookmarks
2048 final void bookmarkDeletionFix (int pos, int len, int eolcount) nothrow {
2049 if (eolcount && linebookmarked.length > 0) {
2050 import core.stdc.stdlib : malloc, free;
2051 // remove bookmarks whose lines are removed, move other bookmarks
2052 auto py = lc.pos2line(pos);
2053 auto ey = lc.pos2line(pos+len);
2054 bool wholeFirstLineDeleted = (pos == lc.line2pos(py)); // do we want to remove the whole first line?
2055 bool wholeLastLineDeleted = (pos+len == lc.line2pos(ey)); // do we want to remove the whole last line?
2056 if (wholeLastLineDeleted) --ey; // yes, `ey` is one line down the last, fix it
2057 // build new bookmark array
2058 int* newbm = cast(int*)malloc(int.sizeof*linebookmarked.length);
2059 if (newbm !is null) {
2060 scope(exit) free(newbm);
2061 int newbmpos = 0;
2062 bool smthWasChanged = false;
2063 foreach (int lidx; linebookmarked.byKey) {
2064 // remove "first line" bookmark if "first line" is deleted
2065 if (wholeFirstLineDeleted && lidx == py) { smthWasChanged = true; continue; }
2066 // remove "last line" bookmark if "last line" is deleted
2067 if (wholeLastLineDeleted && lidx == ey) { smthWasChanged = true; continue; }
2068 // remove bookmarks that are in range
2069 if (lidx > py && lidx < ey) continue;
2070 // fix bookmark line if necessary
2071 if (lidx >= ey) { smthWasChanged = true; lidx -= eolcount; }
2072 if (lidx >= 0 && lidx < lc.linecount) {
2073 //assert(lidx >= 0 && lidx < lc.linecount);
2074 // add this bookmark to new list
2075 newbm[newbmpos++] = lidx;
2078 // rebuild list if something was changed
2079 if (smthWasChanged) {
2080 fullDirty(); //TODO: optimize this
2081 linebookmarked.clear;
2082 foreach (int lidx; newbm[0..newbmpos]) linebookmarked[lidx] = true;
2084 } else {
2085 // out of memory, what to do? just clear bookmarks for now
2086 linebookmarked.clear;
2087 fullDirty(); // just in case
2092 /// call this from `willBeInserted()` or `wasInserted()` to fix bookmarks
2093 final void bookmarkInsertionFix (int pos, int len, int eolcount) nothrow {
2094 if (eolcount && linebookmarked.length > 0) {
2095 import core.stdc.stdlib : malloc, free;
2096 // move affected bookmarks down
2097 auto py = lc.pos2line(pos);
2098 if (pos != lc.line2pos(py)) ++py; // not the whole first line was modified, don't touch bookmarks on it
2099 // build new bookmark array
2100 int* newbm = cast(int*)malloc(int.sizeof*linebookmarked.length);
2101 if (newbm !is null) {
2102 scope(exit) free(newbm);
2103 int newbmpos = 0;
2104 bool smthWasChanged = false;
2105 foreach (int lidx; linebookmarked.byKey) {
2106 // fix bookmark line if necessary
2107 if (lidx >= py) { smthWasChanged = true; lidx += eolcount; }
2108 if (lidx < 0 || lidx >= lc.linecount) continue;
2109 //assert(lidx >= 0 && lidx < gb.linecount);
2110 // add this bookmark to new list
2111 newbm[newbmpos++] = lidx;
2113 // rebuild list if something was changed
2114 if (smthWasChanged) {
2115 fullDirty(); //TODO: optimize this
2116 linebookmarked.clear;
2117 foreach (int lidx; newbm[0..newbmpos]) linebookmarked[lidx] = true;
2119 } else {
2120 // out of memory, what to do? just clear bookmarks for now
2121 linebookmarked.clear;
2122 fullDirty(); // just in case
2127 public:
2129 this (int x0, int y0, int w, int h, EditorHL ahl=null, bool asingleline=false) {
2130 if (w < 2) w = 2;
2131 if (h < 1) h = 1;
2132 winx = x0;
2133 winy = y0;
2134 winw = w;
2135 winh = h;
2136 //setDirtyLinesLength(visibleLinesPerWindow);
2137 gb = new GapBuffer(asingleline);
2138 lc = new LineCache(gb);
2139 lc.recode1byte = &recode1b;
2140 hl = ahl;
2141 if (ahl !is null) { hl.gb = gb; hl.lc = lc; }
2142 undo = new UndoStack(mAsRich, false, !asingleline);
2143 redo = new UndoStack(mAsRich, true, !asingleline);
2144 mSingleLine = asingleline;
2147 private void setDirtyLinesLength (usize len) nothrow {
2148 if (len > int.max/4) assert(0, "wtf?!");
2149 if (dirtyLines.length > len) {
2150 dirtyLines.length = len;
2151 dirtyLines.assumeSafeAppend;
2152 dirtyLines[] = -1;
2153 } else if (dirtyLines.length < len) {
2154 auto optr = dirtyLines.ptr;
2155 auto olen = dirtyLines.length;
2156 dirtyLines.length = len;
2157 if (dirtyLines.ptr !is optr) {
2158 import core.memory : GC;
2159 if (dirtyLines.ptr is GC.addrOf(dirtyLines.ptr)) GC.setAttr(dirtyLines.ptr, GC.BlkAttr.NO_INTERIOR);
2161 //dirtyLines[olen..$] = -1;
2162 dirtyLines[] = -1;
2166 // utfuck switch hooks
2167 protected void beforeUtfuckSwitch (bool newisutfuck) {} /// utfuck switch hook
2168 protected void afterUtfuckSwitch (bool newisutfuck) {} /// utfuck switch hook
2170 final @property {
2172 bool utfuck () const pure nothrow @safe @nogc { pragma(inline, true); return lc.utfuck; }
2174 /// this switches "utfuck" mode
2175 /// note that utfuck mode is FUCKIN' SLOW and buggy
2176 /// you should not lose any text, but may encounter visual and positional glitches
2177 void utfuck (bool v) {
2178 if (lc.utfuck == v) return;
2179 beforeUtfuckSwitch(v);
2180 auto pos = curpos;
2181 lc.utfuck = v;
2182 lc.pos2xy(pos, cx, cy);
2183 fullDirty();
2184 afterUtfuckSwitch(v);
2187 ref inout(GapBuffer.HighState) defaultRichStyle () inout pure nothrow @trusted @nogc { pragma(inline, true); return cast(typeof(return))gb.defhs; } ///
2189 @property bool asRich () const pure nothrow @safe @nogc { pragma(inline, true); return mAsRich; } ///
2191 /// WARNING! changing this will reset undo/redo buffers!
2192 void asRich (bool v) {
2193 if (mAsRich != v) {
2194 // detach highlighter for "rich mode"
2195 if (v && hl !is null) {
2196 hl.gb = null;
2197 hl.lc = null;
2198 hl = null;
2200 mAsRich = v;
2201 if (undo !is null) {
2202 delete undo;
2203 undo = new UndoStack(mAsRich, false, !singleline);
2205 if (redo !is null) {
2206 delete redo;
2207 redo = new UndoStack(mAsRich, true, !singleline);
2209 gb.hasHiBuffer = v; // "rich" mode require highlighting buffer, normal mode doesn't, as it has no highlighter
2210 if (v && !gb.hasHiBuffer) assert(0, "out of memory"); // alas
2214 @property bool hasHiBuffer () const pure nothrow @safe @nogc { pragma(inline, true); return gb.hasHiBuffer; }
2215 @property void hasHiBuffer (bool v) nothrow @trusted @nogc {
2216 if (mAsRich) return; // cannot change
2217 if (hl !is null) return; // cannot change too
2218 gb.hasHiBuffer = v; // otherwise it is ok to change it
2221 int x0 () const pure nothrow @safe @nogc { pragma(inline, true); return winx; } ///
2222 int y0 () const pure nothrow @safe @nogc { pragma(inline, true); return winy; } ///
2223 int width () const pure nothrow @safe @nogc { pragma(inline, true); return winw; } ///
2224 int height () const pure nothrow @safe @nogc { pragma(inline, true); return winh; } ///
2226 void x0 (int v) { pragma(inline, true); move(v, winy); } ///
2227 void y0 (int v) { pragma(inline, true); move(winx, v); } ///
2228 void width (int v) { pragma(inline, true); resize(v, winh); } ///
2229 void height (int v) { pragma(inline, true); resize(winw, v); } ///
2231 /// has any effect only if you are using `insertText()` and `deleteText()` API!
2232 bool readonly () const pure nothrow @safe @nogc { pragma(inline, true); return mReadOnly; }
2233 void readonly (bool v) nothrow { pragma(inline, true); mReadOnly = v; } ///
2235 /// "single line" mode, for line editors
2236 bool singleline () const pure nothrow @safe @nogc { pragma(inline, true); return mSingleLine; }
2238 /// "buffer change counter"
2239 uint bufferCC () const pure nothrow @safe @nogc { pragma(inline, true); return gb.bufferChangeCounter; }
2240 void bufferCC (uint v) pure nothrow { pragma(inline, true); gb.bufferChangeCounter = v; } ///
2242 bool killTextOnChar () const pure nothrow @safe @nogc { pragma(inline, true); return mKillTextOnChar; } ///
2243 void killTextOnChar (bool v) nothrow { ///
2244 pragma(inline, true);
2245 if (mKillTextOnChar != v) {
2246 mKillTextOnChar = v;
2247 fullDirty();
2251 bool inPixels () const pure nothrow @safe @nogc { pragma(inline, true); return (lineHeightPixels != 0); } ///
2253 /// this can recalc height cache
2254 int linesPerWindow () nothrow {
2255 pragma(inline, true);
2256 return
2257 lineHeightPixels == 0 || lineHeightPixels == 1 ? winh :
2258 lineHeightPixels > 0 ? (winh <= lineHeightPixels ? 1 : winh/lineHeightPixels) :
2259 calcLinesPerWindow();
2262 /// this can recalc height cache
2263 int visibleLinesPerWindow () nothrow {
2264 pragma(inline, true);
2265 return
2266 lineHeightPixels == 0 || lineHeightPixels == 1 ? winh :
2267 lineHeightPixels > 0 ? (winh <= lineHeightPixels ? 1 : winh/lineHeightPixels+(winh%lineHeightPixels ? 1 : 0)) :
2268 calcVisLinesPerWindow();
2272 // for variable line height
2273 protected final int calcVisLinesPerWindow () nothrow {
2274 if (textMeter is null) assert(0, "you forgot to setup `textMeter` for EditorEngine");
2275 int hgtleft = winh;
2276 if (hgtleft < 1) return 1; // just in case
2277 int lidx = mTopLine;
2278 int lcount = 0;
2279 while (hgtleft > 0) {
2280 auto lh = lc.lineHeightPixels(lidx++);
2281 ++lcount;
2282 hgtleft -= lh;
2284 return lcount;
2287 // for variable line height
2288 protected final int calcLinesPerWindow () nothrow {
2289 if (textMeter is null) assert(0, "you forgot to setup `textMeter` for EditorEngine");
2290 int hgtleft = winh;
2291 if (hgtleft < 1) return 1; // just in case
2292 int lidx = mTopLine;
2293 int lcount = 0;
2294 //{ import core.stdc.stdio; printf("=== clpw ===\n"); }
2295 for (;;) {
2296 auto lh = lc.lineHeightPixels(lidx++);
2297 //if (gb.mLineCount > 0) { import core.stdc.stdio; printf("*clpw: lidx=%d; height=%d; hgtleft=%d\n", lidx-1, lh, hgtleft); }
2298 hgtleft -= lh;
2299 if (hgtleft >= 0) ++lcount;
2300 if (hgtleft <= 0) break;
2302 //{ import core.stdc.stdio; printf("clpw: %d\n", lcount); }
2303 return (lcount ? lcount : 1);
2306 /// has lille sense if `inPixels` is false
2307 final int linePixelHeight (int lidx) nothrow {
2308 if (!inPixels) return 1;
2309 if (lineHeightPixels > 0) {
2310 return lineHeightPixels;
2311 } else {
2312 if (textMeter is null) assert(0, "you forgot to setup `textMeter` for EditorEngine");
2313 return lc.lineHeightPixels(lidx);
2317 /// resize control
2318 void resize (int nw, int nh) {
2319 if (nw < 2) nw = 2;
2320 if (nh < 1) nh = 1;
2321 if (nw != winw || nh != winh) {
2322 winw = nw;
2323 winh = nh;
2324 auto nvl = visibleLinesPerWindow;
2325 setDirtyLinesLength(nvl);
2326 makeCurLineVisible();
2327 fullDirty();
2331 /// move control
2332 void move (int nx, int ny) {
2333 if (winx != nx || winy != ny) {
2334 winx = nx;
2335 winy = ny;
2336 fullDirty();
2340 /// move and resize control
2341 void moveResize (int nx, int ny, int nw, int nh) {
2342 move(nx, ny);
2343 resize(nw, nh);
2346 final @property void curx (int v) nothrow @system { gotoXY(v, cy); } ///
2347 final @property void cury (int v) nothrow @system { gotoXY(cx, v); } ///
2349 final @property nothrow {
2350 /// has active marked block?
2351 bool hasMarkedBlock () const pure @safe @nogc { pragma(inline, true); return (bstart < bend); }
2353 int curx () const pure @safe @nogc { pragma(inline, true); return cx; } ///
2354 int cury () const pure @safe @nogc { pragma(inline, true); return cy; } ///
2355 int xofs () const pure @safe @nogc { pragma(inline, true); return mXOfs; } ///
2357 int topline () const pure @safe @nogc { pragma(inline, true); return mTopLine; } ///
2358 int linecount () const pure @safe @nogc { pragma(inline, true); return lc.linecount; } ///
2359 int textsize () const pure @safe @nogc { pragma(inline, true); return gb.textsize; } ///
2361 char opIndex (int pos) const pure @safe @nogc { pragma(inline, true); return gb[pos]; } /// returns '\n' for out-of-bounds query
2363 /// returns '\n' for out-of-bounds query
2364 dchar dcharAt (int pos) const {
2365 auto ts = gb.textsize;
2366 if (pos < 0 || pos >= ts) return '\n';
2367 if (!lc.utfuck) {
2368 final switch (codepage) {
2369 case CodePage.koi8u: return koi2uni(gb[pos]);
2370 case CodePage.cp1251: return cp12512uni(gb[pos]);
2371 case CodePage.cp866: return cp8662uni(gb[pos]);
2373 assert(0);
2375 Utf8DecoderFast udc;
2376 while (pos < ts) {
2377 if (udc.decodeSafe(cast(ubyte)gb[pos++])) return cast(dchar)udc.codepoint;
2379 return udc.replacement;
2382 /// this advances `pos`, and returns '\n' for out-of-bounds query
2383 dchar dcharAtAdvance (ref int pos) const {
2384 auto ts = gb.textsize;
2385 if (pos < 0) { pos = 0; return '\n'; }
2386 if (pos >= ts) { pos = ts; return '\n'; }
2387 if (!lc.utfuck) {
2388 immutable char ch = gb[pos++];
2389 final switch (codepage) {
2390 case CodePage.koi8u: return koi2uni(ch);
2391 case CodePage.cp1251: return cp12512uni(ch);
2392 case CodePage.cp866: return cp8662uni(ch);
2394 assert(0);
2396 Utf8DecoderFast udc;
2397 while (pos < ts) {
2398 if (udc.decodeSafe(cast(ubyte)gb[pos++])) return cast(dchar)udc.codepoint;
2400 return udc.replacement;
2403 /// this works correctly with utfuck
2404 int nextpos (int pos) const {
2405 if (pos < 0) return 0;
2406 immutable ts = gb.textsize;
2407 if (pos >= ts) return ts;
2408 if (!lc.utfuck) return pos+1;
2409 Utf8DecoderFast udc;
2410 while (pos < ts) if (udc.decodeSafe(cast(ubyte)gb[pos++])) break;
2411 return pos;
2414 /// this sometimes works correctly with utfuck
2415 int prevpos (int pos) const {
2416 if (pos <= 0) return 0;
2417 immutable ts = gb.textsize;
2418 if (ts == 0) return 0;
2419 if (pos > ts) pos = ts;
2420 --pos;
2421 if (lc.utfuck) {
2422 while (pos > 0 && !isValidUtf8Start(cast(ubyte)gb[pos])) --pos;
2424 return pos;
2427 bool textChanged () const pure { pragma(inline, true); return txchanged; } ///
2428 void textChanged (bool v) pure { pragma(inline, true); txchanged = v; } ///
2430 bool visualtabs () const pure { pragma(inline, true); return (lc.visualtabs && lc.tabsize > 0); } ///
2433 void visualtabs (bool v) {
2434 if (lc.visualtabs != v) {
2435 lc.visualtabs = v;
2436 fullDirty();
2440 ubyte tabsize () const pure { pragma(inline, true); return lc.tabsize; } ///
2443 void tabsize (ubyte v) {
2444 if (lc.tabsize != v) {
2445 lc.tabsize = v;
2446 if (lc.visualtabs) fullDirty();
2450 /// mark whole visible text as dirty
2451 final void fullDirty () nothrow { dirtyLines[] = -1; }
2455 @property void topline (int v) nothrow {
2456 if (v < 0) v = 0;
2457 if (v > lc.linecount) v = lc.linecount-1;
2458 immutable auto moldtop = mTopLine;
2459 mTopLine = v; // for linesPerWindow
2460 if (v+linesPerWindow > lc.linecount) {
2461 v = lc.linecount-linesPerWindow;
2462 if (v < 0) v = 0;
2464 if (v != moldtop) {
2465 mTopLine = moldtop;
2466 version(egeditor_record_movement_undo) pushUndoCurPos();
2467 mTopLine = v;
2471 /// absolute coordinates in text
2472 final void gotoXY(bool vcenter=false) (int nx, int ny) nothrow {
2473 if (nx < 0) nx = 0;
2474 if (ny < 0) ny = 0;
2475 if (ny >= lc.linecount) ny = lc.linecount-1;
2476 auto pos = lc.xy2pos(nx, ny);
2477 lc.pos2xy(pos, nx, ny);
2478 if (nx != cx || ny != cy) {
2479 version(egeditor_record_movement_undo) pushUndoCurPos();
2480 cx = nx;
2481 cy = ny;
2482 static if (vcenter) makeCurLineVisibleCentered(); else makeCurLineVisible();
2487 final void gotoPos(bool vcenter=false) (int pos) nothrow {
2488 if (pos < 0) pos = 0;
2489 if (pos > gb.textsize) pos = gb.textsize;
2490 int rx, ry;
2491 lc.pos2xy(pos, rx, ry);
2492 gotoXY!vcenter(rx, ry);
2495 final int curpos () nothrow { pragma(inline, true); return lc.xy2pos(cx, cy); } ///
2496 final void curpos (int pos) nothrow { pragma(inline, true); gotoPos(pos); } ///
2499 void clearUndo () nothrow {
2500 if (undo !is null) undo.clear();
2501 if (redo !is null) redo.clear();
2505 void clear () nothrow {
2506 lc.clear();
2507 txchanged = false;
2508 if (undo !is null) undo.clear();
2509 if (redo !is null) redo.clear();
2510 cx = cy = mTopLine = mXOfs = 0;
2511 prevTopLine = -1;
2512 prevXOfs = -1;
2513 dirtyLines[] = -1;
2514 bstart = bend = -1;
2515 markingBlock = false;
2516 lastBGEnd = false;
2517 txchanged = false;
2521 void clearAndDisableUndo () {
2522 if (undo !is null) delete undo;
2523 if (redo !is null) delete redo;
2527 void reinstantiateUndo () {
2528 if (undo is null) undo = new UndoStack(mAsRich, false, !mSingleLine);
2529 if (redo is null) redo = new UndoStack(mAsRich, true, !mSingleLine);
2533 void loadFile (const(char)[] fname) { loadFile(VFile(fname)); }
2536 void loadFile (VFile fl) {
2537 import core.stdc.stdlib : malloc, free;
2538 clear();
2539 scope(failure) clear();
2540 auto fpos = fl.tell;
2541 auto fsz = fl.size;
2542 if (fpos < fsz) {
2543 if (fsz-fpos >= gb.tbmax) throw new Exception("text too big");
2544 uint filesize = cast(uint)(fsz-fpos);
2545 if (!lc.resizeBuffer(filesize)) throw new Exception("text too big");
2546 scope(failure) clear();
2547 fl.rawReadExact(lc.getBufferPtr[]);
2548 if (!lc.rebuild()) throw new Exception("out of memory");
2553 void saveFile (const(char)[] fname) { saveFile(VFile(fname, "w")); }
2556 void saveFile (VFile fl) {
2557 gb.forEachBufPart(0, gb.textsize, delegate (const(char)[] buf) { fl.rawWriteExact(buf); });
2558 txchanged = false;
2559 if (undo !is null) undo.alwaysChanged();
2560 if (redo !is null) redo.alwaysChanged();
2563 /// attach new highlighter; return previous one
2564 /// note that you can't reuse one highlighter for several editors!
2565 EditorHL attachHiglighter (EditorHL ahl) {
2566 if (mAsRich) { assert(hl is null); return null; } // oops
2567 if (ahl is hl) return ahl; // nothing to do
2568 EditorHL prevhl = hl;
2569 if (ahl is null) {
2570 // detach
2571 if (hl !is null) {
2572 hl.gb = null;
2573 hl.lc = null;
2574 hl = null;
2575 gb.hasHiBuffer = false; // don't need it
2576 fullDirty();
2578 return prevhl; // return previous
2580 if (ahl.lc !is null) {
2581 if (ahl.lc !is lc) throw new Exception("highlighter already used by another editor");
2582 if (ahl !is hl) assert(0, "something is VERY wrong");
2583 return ahl;
2585 if (hl !is null) { hl.gb = null; hl.lc = null; }
2586 ahl.gb = gb;
2587 ahl.lc = lc;
2588 hl = ahl;
2589 gb.hasHiBuffer = true; // need it
2590 if (!gb.hasHiBuffer) assert(0, "out of memory"); // alas
2591 ahl.lineChanged(0, true);
2592 fullDirty();
2593 return prevhl;
2597 EditorHL detachHighlighter () {
2598 if (mAsRich) { assert(hl is null); return null; } // oops
2599 auto res = hl;
2600 if (res !is null) {
2601 hl.gb = null;
2602 hl.lc = null;
2603 hl = null;
2604 gb.hasHiBuffer = false; // don't need it
2605 fullDirty();
2607 return res;
2610 /// override this method to draw something before any other page drawing will be done
2611 public void drawPageBegin () {}
2613 /// override this method to draw one text line
2614 /// highlighting is done, other housekeeping is done, only draw
2615 /// lidx is always valid
2616 /// must repaint the whole line
2617 /// use `winXXX` vars to know window dimensions
2618 public abstract void drawLine (int lidx, int yofs, int xskip);
2620 /// just clear the line; you have to override this, 'cause it is used to clear empty space
2621 /// use `winXXX` vars to know window dimensions
2622 public abstract void drawEmptyLine (int yofs);
2624 /// override this method to draw something after page was drawn, but before drawing the status
2625 public void drawPageMisc () {}
2627 /// override this method to draw status line; it will be called after `drawPageBegin()`
2628 public void drawStatus () {}
2630 /// override this method to draw something after status was drawn, but before drawing the cursor
2631 public void drawPagePost () {}
2633 /// override this method to draw text cursor; it will be called after `drawPageMisc()`
2634 public abstract void drawCursor ();
2636 /// override this method to draw something (or flush drawing buffer) after everything was drawn
2637 public void drawPageEnd () {}
2639 /** draw the page; it will fix coords, call necessary methods and so on. you are usually don't need to override this.
2640 * page drawing flow:
2641 * drawPageBegin();
2642 * page itself with drawLine() or drawEmptyLine();
2643 * drawPageMisc();
2644 * drawStatus();
2645 * drawPagePost();
2646 * drawCursor();
2647 * drawPageEnd();
2649 void drawPage () {
2650 makeCurLineVisible();
2652 if (prevTopLine != mTopLine || prevXOfs != mXOfs) {
2653 prevTopLine = mTopLine;
2654 prevXOfs = mXOfs;
2655 dirtyLines[] = -1;
2658 drawPageBegin();
2659 immutable int lhp = lineHeightPixels;
2660 immutable int ydelta = (inPixels ? lhp : 1);
2661 bool alwaysDirty = false;
2662 auto pos = lc.xy2pos(0, mTopLine);
2663 auto lc = lc.linecount;
2664 int lyofs = 0;
2665 //TODO: optimize redrawing for variable line height mode
2666 foreach (int y; 0..visibleLinesPerWindow) {
2667 bool dirty = (mTopLine+y < lc && hl !is null && hl.fixLine(mTopLine+y));
2668 if (!alwaysDirty) {
2669 if (lhp < 0) {
2670 // variable line height, hacks
2671 alwaysDirty = (!alwaysDirty && y < dirtyLines.length ? (dirtyLines.ptr[y] != linePixelHeight(mTopLine+y)) : true);
2672 } else if (!dirty && y < dirtyLines.length) {
2673 // tty or constant pixel height
2674 dirty = (dirtyLines.ptr[y] != 0);
2676 dirty = true;
2678 if (dirty || alwaysDirty) {
2679 if (y < dirtyLines.length) dirtyLines.ptr[y] = (lhp >= 0 ? 0 : linePixelHeight(mTopLine+y));
2680 if (mTopLine+y < lc) {
2681 drawLine(mTopLine+y, lyofs, mXOfs);
2682 } else {
2683 drawEmptyLine(lyofs);
2686 lyofs += (ydelta > 0 ? ydelta : linePixelHeight(mTopLine+y));
2688 drawPageMisc();
2689 drawStatus();
2690 drawPagePost();
2691 drawCursor();
2692 drawPageEnd();
2695 /// force cursor coordinates to be in text
2696 final void normXY () nothrow {
2697 lc.pos2xy(curpos, cx, cy);
2701 final void makeCurXVisible () nothrow {
2702 // use "real" x coordinate to calculate x offset
2703 if (cx < 0) cx = 0;
2704 int rx;
2705 if (!inPixels) {
2706 int ry;
2707 lc.pos2xyVT(curpos, rx, ry);
2708 if (rx < mXOfs) mXOfs = rx;
2709 if (rx-mXOfs >= winw) mXOfs = rx-winw+1;
2710 } else {
2711 rx = localCursorX();
2712 rx += mXOfs;
2713 if (rx < mXOfs) mXOfs = rx-8;
2714 if (rx+4-mXOfs > winw) mXOfs = rx-winw+4;
2716 if (mXOfs < 0) mXOfs = 0;
2719 /// in symbols, not chars
2720 final int linelen (int lidx) nothrow {
2721 if (lidx < 0 || lidx >= lc.linecount) return 0;
2722 auto pos = lc.line2pos(lidx);
2723 auto ts = gb.textsize;
2724 if (pos > ts) pos = ts;
2725 int res = 0;
2726 if (!lc.utfuck) {
2727 if (mSingleLine) return ts-pos;
2728 while (pos < ts) {
2729 if (gb[pos++] == '\n') break;
2730 ++res;
2732 } else {
2733 immutable bool sl = mSingleLine;
2734 while (pos < ts) {
2735 char ch = gb[pos++];
2736 if (!sl && ch == '\n') break;
2737 ++res;
2738 if (ch >= 128) {
2739 --pos;
2740 pos += gb.utfuckLenAt(pos);
2744 return res;
2747 /// cursor position in "local" coords: from widget (x0,y0), possibly in pixels
2748 final int localCursorX () nothrow {
2749 int rx;
2750 localCursorXY(&rx, null);
2751 return rx;
2754 /// cursor position in "local" coords: from widget (x0,y0), possibly in pixels
2755 final void localCursorXY (int* lcx, int* lcy) nothrow {
2756 int rx, ry;
2757 if (!inPixels) {
2758 lc.pos2xyVT(curpos, rx, ry);
2759 ry -= mTopLine;
2760 rx -= mXOfs;
2761 if (lcx !is null) *lcx = rx;
2762 if (lcy !is null) *lcy = ry;
2763 } else {
2764 lc.pos2xy(curpos, rx, ry);
2765 if (textMeter is null) assert(0, "you forgot to setup `textMeter` for EditorEngine");
2766 if (lcy !is null) {
2767 if (lineHeightPixels > 0) {
2768 *lcy = (ry-mTopLine)*lineHeightPixels;
2769 } else {
2770 if (ry >= mTopLine) {
2771 for (int ll = mTopLine; ll < ry; ++ll) *lcy += lc.lineHeightPixels(ll);
2772 } else {
2773 for (int ll = mTopLine-1; ll >= ry; --ll) *lcy -= lc.lineHeightPixels(ll);
2777 if (rx == 0) { if (lcx !is null) *lcx = 0-mXOfs; return; }
2778 if (lcx !is null) {
2779 textMeter.reset(visualtabs ? lc.tabsize : 0);
2780 scope(exit) textMeter.finish(); // just in case
2781 auto pos = lc.linestart(ry);
2782 immutable int le = lc.linestart(ry+1);
2783 immutable bool ufuck = lc.utfuck;
2784 if (mSingleLine) {
2785 while (pos < le) {
2786 // advance one symbol
2787 textMeter.advance(dcharAtAdvance(pos), gb.hi(pos));
2788 --rx;
2789 if (rx == 0) break;
2791 } else {
2792 while (pos < le) {
2793 // advance one symbol
2794 if (gb[pos] == '\n') break;
2795 textMeter.advance(dcharAtAdvance(pos), gb.hi(pos));
2796 --rx;
2797 if (rx == 0) {
2798 // hack for kerning
2799 if (gb[pos] != '\n' && pos < le) {
2800 textMeter.advance(dcharAtAdvance(pos), gb.hi(pos));
2801 *lcx = textMeter.currofs;
2802 return;
2804 break;
2808 *lcx = textMeter.currwdt-mXOfs;
2813 /// convert coordinates in widget into text coordinates; can be used to convert mouse click position into text position
2814 /// WARNING: ty can be equal to linecount or -1!
2815 final void widget2text (int mx, int my, out int tx, out int ty) nothrow {
2816 if (!inPixels) {
2817 int ry = my+mTopLine;
2818 if (ry < 0) { ty = -1; return; } // tx is zero here
2819 if (ry >= lc.linecount) { ty = lc.linecount; return; } // tx is zero here
2820 if (mx <= 0 && mXOfs == 0) return; // tx is zero here
2821 // ah, screw it! user should not call this very often, so i can stop caring about speed.
2822 int visx = -mXOfs;
2823 auto pos = lc.line2pos(ry);
2824 auto ts = gb.textsize;
2825 int rx = 0;
2826 immutable bool ufuck = lc.utfuck;
2827 immutable bool sl = mSingleLine;
2828 while (pos < ts) {
2829 // advance one symbol
2830 char ch = gb[pos];
2831 if (!sl && ch == '\n') { tx = rx; return; } // done anyway
2832 int nextx = visx+1;
2833 if (ch == '\t' && visualtabs) {
2834 // hack!
2835 nextx = ((visx+mXOfs)/tabsize+1)*tabsize-mXOfs;
2837 if (mx >= visx && mx < nextx) { tx = rx; return; }
2838 visx = nextx;
2839 if (!ufuck || ch < 128) {
2840 ++pos;
2841 } else {
2842 pos = nextpos(pos);
2844 ++rx;
2846 } else {
2847 if (textMeter is null) assert(0, "you forgot to setup `textMeter` for EditorEngine");
2848 int ry;
2849 if (lineHeightPixels > 0) {
2850 ry = my/lineHeightPixels+mTopLine;
2851 } else {
2852 ry = mTopLine;
2853 if (my >= 0) {
2854 // down
2855 int lcy = 0;
2856 while (lcy < my) {
2857 lcy += lc.lineHeightPixels(ry);
2858 if (lcy > my) break;
2859 ++ry;
2860 if (lcy == my) break;
2862 } else {
2863 // up
2864 ry = mTopLine-1;
2865 int lcy = 0;
2866 while (ry >= 0) {
2867 int upy = lcy-lc.lineHeightPixels(ry);
2868 if (my >= upy && my < lcy) break;
2869 lcy = upy;
2873 if (ry < 0) { ty = -1; return; } // tx is zero here
2874 if (ry >= lc.linecount) { ty = lc.linecount; return; } // tx is zero here
2875 ty = ry;
2876 if (mx <= 0 && mXOfs == 0) return; // tx is zero here
2877 // now the hard part
2878 textMeter.reset(visualtabs ? lc.tabsize : 0);
2879 scope(exit) textMeter.finish(); // just in case
2880 int visx0 = -mXOfs;
2881 auto pos = lc.line2pos(ry);
2882 immutable ts = gb.textsize;
2883 int rx = 0;
2884 immutable bool ufuck = lc.utfuck;
2885 immutable bool sl = mSingleLine;
2886 while (pos < ts) {
2887 // advance one symbol
2888 char ch = gb[pos];
2889 if (!sl && ch == '\n') { tx = rx; return; } // done anyway
2890 if (!ufuck || ch < 128) {
2891 textMeter.advance(cast(dchar)ch, gb.hi(pos));
2892 ++pos;
2893 } else {
2894 textMeter.advance(dcharAtAdvance(pos), gb.hi(pos));
2896 immutable int visx1 = textMeter.currwdt-mXOfs;
2897 // visx0 is current char x start
2898 // visx1 is current char x end
2899 // so if our mx is in [visx0..visx1), we are at current char
2900 if (mx >= visx0 && mx < visx1) {
2901 // it is more natural this way
2902 if (mx >= visx0+(visx1-visx0)/2 && pos < lc.linestart(ry+1)) ++rx;
2903 tx = rx;
2904 return;
2906 ++rx;
2907 visx0 = visx1;
2913 final void makeCurLineVisible () nothrow {
2914 if (cy < 0) cy = 0;
2915 if (cy >= lc.linecount) cy = lc.linecount-1;
2916 if (cy < mTopLine) {
2917 mTopLine = cy;
2918 } else {
2919 if (cy > mTopLine+linesPerWindow-1) {
2920 mTopLine = cy-linesPerWindow+1;
2921 if (mTopLine < 0) mTopLine = 0;
2924 setDirtyLinesLength(visibleLinesPerWindow);
2925 makeCurXVisible();
2929 final void makeCurLineVisibleCentered (bool forced=false) nothrow {
2930 if (forced || !isCurLineVisible) {
2931 if (cy < 0) cy = 0;
2932 if (cy >= lc.linecount) cy = lc.linecount-1;
2933 mTopLine = cy-linesPerWindow/2;
2934 if (mTopLine < 0) mTopLine = 0;
2935 if (mTopLine+linesPerWindow > lc.linecount) {
2936 mTopLine = lc.linecount-linesPerWindow;
2937 if (mTopLine < 0) mTopLine = 0;
2940 setDirtyLinesLength(visibleLinesPerWindow);
2941 makeCurXVisible();
2945 final bool isCurLineBeforeTop () nothrow {
2946 pragma(inline, true);
2947 return (cy < mTopLine);
2951 final bool isCurLineAfterBottom () nothrow {
2952 pragma(inline, true);
2953 return (cy > mTopLine+linesPerWindow-1);
2957 final bool isCurLineVisible () nothrow {
2958 pragma(inline, true);
2959 return (cy >= mTopLine && cy < mTopLine+linesPerWindow);
2960 //if (cy < mTopLine) return false;
2961 //if (cy > mTopLine+linesPerWindow-1) return false;
2962 //return true;
2965 /// `updateDown`: update all the page (as new lines was inserted/removed)
2966 final void lineChanged (int lidx, bool updateDown) {
2967 if (lidx < 0 || lidx >= lc.linecount) return;
2968 if (hl !is null) hl.lineChanged(lidx, updateDown);
2969 if (lidx < mTopLine) { if (updateDown) dirtyLines[] = -1; return; }
2970 if (lidx >= mTopLine+linesPerWindow) return;
2971 immutable stl = lidx-mTopLine;
2972 assert(stl >= 0);
2973 if (stl < dirtyLines.length) {
2974 if (updateDown) {
2975 dirtyLines[stl..$] = -1;
2976 } else {
2977 dirtyLines.ptr[stl] = -1;
2983 final void lineChangedByPos (int pos, bool updateDown) { return lineChanged(lc.pos2line(pos), updateDown); }
2986 final void markLinesDirty (int lidx, int count) nothrow {
2987 if (prevTopLine != mTopLine || prevXOfs != mXOfs) return; // we will refresh the whole page anyway
2988 if (count < 1 || lidx >= lc.linecount) return;
2989 if (count > lc.linecount) count = lc.linecount;
2990 if (lidx >= mTopLine+linesPerWindow) return;
2991 int le = lidx+count;
2992 if (le <= mTopLine) { dirtyLines[] = -1; return; } // just in case
2993 if (lidx < mTopLine) { dirtyLines[] = -1; lidx = mTopLine; return; } // just in cale
2994 if (le > mTopLine+visibleLinesPerWindow) le = mTopLine+visibleLinesPerWindow;
2995 immutable stl = lidx-mTopLine;
2996 assert(stl >= 0);
2997 if (stl < dirtyLines.length) {
2998 auto el = le-mTopLine;
2999 if (el > dirtyLines.length) el = cast(int)dirtyLines.length;
3000 dirtyLines.ptr[stl..el] = -1;
3005 final void markLinesDirtySE (int lidxs, int lidxe) nothrow {
3006 if (lidxe < lidxs) { int tmp = lidxs; lidxs = lidxe; lidxe = tmp; }
3007 markLinesDirty(lidxs, lidxe-lidxs+1);
3011 final void markRangeDirty (int pos, int len) nothrow {
3012 if (prevTopLine != mTopLine || prevXOfs != mXOfs) return; // we will refresh the whole page anyway
3013 int l0 = lc.pos2line(pos);
3014 int l1 = lc.pos2line(pos+len+1);
3015 markLinesDirtySE(l0, l1);
3019 final void markBlockDirty () nothrow {
3020 //FIXME: optimize updating with block boundaries
3021 if (bstart >= bend) return;
3022 markRangeDirty(bstart, bend-bstart);
3025 /// do various fixups before text deletion
3026 /// cursor coords *may* be already changed
3027 /// will be called before text deletion by `deleteText` or `replaceText` APIs
3028 /// eolcount: number of eols in (to be) deleted block
3029 protected void willBeDeleted (int pos, int len, int eolcount) nothrow {
3030 //FIXME: optimize updating with block boundaries
3031 if (len < 1) return; // just in case
3032 assert(pos >= 0 && cast(long)pos+len <= gb.textsize);
3033 bookmarkDeletionFix(pos, len, eolcount);
3034 if (hasMarkedBlock) {
3035 if (pos+len <= bstart) {
3036 // move whole block up
3037 markBlockDirty();
3038 bstart -= len;
3039 bend -= len;
3040 markBlockDirty();
3041 lastBGEnd = false;
3042 } else if (pos <= bstart && pos+len >= bend) {
3043 // whole block will be deleted
3044 doBlockResetMark(false); // skip undo
3045 } else if (pos >= bstart && pos+len <= bend) {
3046 // deleting something inside block, move end
3047 markBlockDirty();
3048 bend -= len;
3049 if (bstart >= bend) {
3050 doBlockResetMark(false); // skip undo
3051 } else {
3052 markBlockDirty();
3053 lastBGEnd = true;
3055 } else if (pos >= bstart && pos < bend && pos+len > bend) {
3056 // chopping block end
3057 markBlockDirty();
3058 bend = pos;
3059 if (bstart >= bend) {
3060 doBlockResetMark(false); // skip undo
3061 } else {
3062 markBlockDirty();
3063 lastBGEnd = true;
3069 /// do various fixups after text deletion
3070 /// cursor coords *may* be already changed
3071 /// will be called after text deletion by `deleteText` or `replaceText` APIs
3072 /// eolcount: number of eols in deleted block
3073 /// pos and len: they were valid *before* deletion!
3074 protected void wasDeleted (int pos, int len, int eolcount) nothrow {
3077 /// do various fixups before text insertion
3078 /// cursor coords *may* be already changed
3079 /// will be called before text insertion by `insertText` or `replaceText` APIs
3080 /// eolcount: number of eols in (to be) inserted block
3081 protected void willBeInserted (int pos, int len, int eolcount) nothrow {
3084 /// do various fixups after text insertion
3085 /// cursor coords *may* be already changed
3086 /// will be called after text insertion by `insertText` or `replaceText` APIs
3087 /// eolcount: number of eols in inserted block
3088 protected void wasInserted (int pos, int len, int eolcount) nothrow {
3089 //FIXME: optimize updating with block boundaries
3090 if (len < 1) return;
3091 assert(pos >= 0 && cast(long)pos+len <= gb.textsize);
3092 bookmarkInsertionFix(pos, len, eolcount);
3093 if (markingBlock && pos == bend) {
3094 bend += len;
3095 markBlockDirty();
3096 lastBGEnd = true;
3097 return;
3099 if (hasMarkedBlock) {
3100 if (pos <= bstart) {
3101 // move whole block down
3102 markBlockDirty();
3103 bstart += len;
3104 bend += len;
3105 markBlockDirty();
3106 lastBGEnd = false;
3107 } else if (pos < bend) {
3108 // move end of block down
3109 markBlockDirty();
3110 bend += len;
3111 markBlockDirty();
3112 lastBGEnd = true;
3117 /// should be called after cursor position change
3118 protected final void growBlockMark () nothrow {
3119 if (!markingBlock || bstart < 0) return;
3120 makeCurLineVisible();
3121 int ry;
3122 int pos = curpos;
3123 if (pos < bstart) {
3124 if (lastBGEnd) {
3125 // move end
3126 ry = lc.pos2line(bend);
3127 bend = bstart;
3128 bstart = pos;
3129 lastBGEnd = false;
3130 } else {
3131 // move start
3132 ry = lc.pos2line(bstart);
3133 if (bstart == pos) return;
3134 bstart = pos;
3135 lastBGEnd = false;
3137 } else if (pos > bend) {
3138 // move end
3139 if (bend == pos) return;
3140 ry = lc.pos2line(bend-1);
3141 bend = pos;
3142 lastBGEnd = true;
3143 } else if (pos >= bstart && pos < bend) {
3144 // shrink block
3145 if (lastBGEnd) {
3146 // from end
3147 if (bend == pos) return;
3148 ry = lc.pos2line(bend-1);
3149 bend = pos;
3150 } else {
3151 // from start
3152 if (bstart == pos) return;
3153 ry = lc.pos2line(bstart);
3154 bstart = pos;
3157 markLinesDirtySE(ry, cy);
3160 /// all the following text operations will be grouped into one undo action
3161 bool undoGroupStart () {
3162 return (undo !is null ? undo.addGroupStart(this) : false);
3165 /// end undo action started with `undoGroupStart()`
3166 bool undoGroupEnd () {
3167 return (undo !is null ? undo.addGroupEnd(this) : false);
3170 /// build autoindent for the current line, put it into `indentText`
3171 /// `indentText` will include '\n'
3172 protected final void buildIndent (int pos) {
3173 if (indentText.length) { indentText.length = 0; indentText.assumeSafeAppend; }
3174 void putToIT (char ch) {
3175 auto optr = indentText.ptr;
3176 indentText ~= ch;
3177 if (optr !is indentText.ptr) {
3178 import core.memory : GC;
3179 if (indentText.ptr is GC.addrOf(indentText.ptr)) {
3180 GC.setAttr(indentText.ptr, GC.BlkAttr.NO_INTERIOR); // less false positives
3184 putToIT('\n');
3185 pos = lc.line2pos(lc.pos2line(pos));
3186 auto ts = gb.textsize;
3187 int curx = 0;
3188 while (pos < ts) {
3189 if (curx == cx) break;
3190 auto ch = gb[pos];
3191 if (ch == '\n') break;
3192 if (ch > ' ') break;
3193 putToIT(ch);
3194 ++pos;
3195 ++curx;
3199 /// delete text, save undo, mark updated lines
3200 /// return `false` if operation cannot be performed
3201 /// if caller wants to delete more text than buffer has, it is ok
3202 /// calls `dg` *after* undo saving, but before `willBeDeleted()`
3203 final bool deleteText(string movecursor="none") (int pos, int count, scope void delegate (int pos, int count) dg=null) {
3204 static assert(movecursor == "none" || movecursor == "start" || movecursor == "end");
3205 if (mReadOnly) return false;
3206 killTextOnChar = false;
3207 auto ts = gb.textsize;
3208 if (pos < 0 || pos >= ts || count < 0) return false;
3209 if (ts-pos < count) count = ts-pos;
3210 if (count > 0) {
3211 bool undoOk = false;
3212 if (undo !is null) undoOk = undo.addTextRemove(this, pos, count);
3213 if (dg !is null) dg(pos, count);
3214 int delEols = (!mSingleLine ? gb.countEolsInRange(pos, count) : 0);
3215 willBeDeleted(pos, count, delEols);
3216 //writeLogAction(pos, -count);
3217 // hack: if new linecount is different, there was '\n' in text
3218 auto olc = lc.linecount;
3219 if (!lc.remove(pos, count)) {
3220 if (undoOk) undo.popUndo(); // remove undo record
3221 return false;
3223 txchanged = true;
3224 static if (movecursor != "none") lc.pos2xy(pos, cx, cy);
3225 wasDeleted(pos, count, delEols);
3226 lineChangedByPos(pos, (lc.linecount != olc));
3227 } else {
3228 static if (movecursor != "none") {
3229 int rx, ry;
3230 lc.pos2xy(curpos, rx, ry);
3231 if (rx != cx || ry != cy) {
3232 version(egeditor_record_movement_undo) {
3233 immutable bool okmove = pushUndoCurPos();
3234 } else {
3235 enum okmove = true;
3237 if (okmove) {
3238 cx = rx;
3239 cy = ry;
3240 markLinesDirty(cy, 1);
3245 return true;
3248 /// ugly name is intentional
3249 /// this replaces editor text, clears undo and sets `killTextOnChar` if necessary
3250 /// it also ignores "readonly" flag
3251 final bool setNewText (const(char)[] text, bool killOnChar=true) {
3252 auto oldro = mReadOnly;
3253 scope(exit) mReadOnly = oldro;
3254 mReadOnly = false;
3255 clear();
3256 auto res = insertText!"end"(0, text);
3257 clearUndo();
3258 if (mSingleLine) killTextOnChar = killOnChar;
3259 fullDirty();
3260 return res;
3263 /// insert text, save undo, mark updated lines
3264 /// return `false` if operation cannot be performed
3265 final bool insertText(string movecursor="none", bool doIndent=true) (int pos, const(char)[] str) {
3266 static assert(movecursor == "none" || movecursor == "start" || movecursor == "end");
3267 if (mReadOnly) return false;
3268 if (mKillTextOnChar) {
3269 killTextOnChar = false;
3270 if (gb.textsize > 0) {
3271 undoGroupStart();
3272 bstart = bend = -1;
3273 markingBlock = false;
3274 deleteText!"start"(0, gb.textsize);
3275 undoGroupEnd();
3278 auto ts = gb.textsize;
3279 if (pos < 0 || str.length >= int.max/3) return false;
3280 if (pos > ts) pos = ts;
3281 if (str.length > 0) {
3282 int nlc = (!mSingleLine ? GapBuffer.countEols(str) : 0);
3283 static if (doIndent) {
3284 if (nlc) {
3285 // want indenting and has at least one newline, hard case
3286 buildIndent(pos);
3287 if (indentText.length) {
3288 int toinsert = cast(int)str.length+nlc*(cast(int)indentText.length-1);
3289 bool undoOk = false;
3290 bool doRollback = false;
3291 // record undo
3292 if (undo !is null) undoOk = undo.addTextInsert(this, pos, toinsert);
3293 willBeInserted(pos, toinsert, nlc);
3294 auto spos = pos;
3295 auto ipos = pos;
3296 while (str.length > 0) {
3297 int elp = GapBuffer.findEol(str);
3298 if (elp < 0) elp = cast(int)str.length;
3299 if (elp > 0) {
3300 // insert text
3301 auto newpos = lc.put(ipos, str[0..elp]);
3302 if (newpos < 0) { doRollback = true; break; }
3303 ipos = newpos;
3304 str = str[elp..$];
3305 } else {
3306 // insert newline
3307 assert(str[0] == '\n');
3308 auto newpos = lc.put(ipos, indentText);
3309 if (newpos < 0) { doRollback = true; break; }
3310 ipos = newpos;
3311 str = str[1..$];
3314 if (doRollback) {
3315 // operation failed, rollback it
3316 if (ipos > spos) lc.remove(spos, ipos-spos); // remove inserted text
3317 if (undoOk) undo.popUndo(); // remove undo record
3318 return false;
3320 //if (ipos-spos != toinsert) { import core.stdc.stdio : stderr, fprintf; fprintf(stderr, "spos=%d; ipos=%d; ipos-spos=%d; toinsert=%d; nlc=%d; sl=%d; il=%d\n", spos, ipos, ipos-spos, toinsert, nlc, cast(int)str.length, cast(int)indentText.length); }
3321 assert(ipos-spos == toinsert);
3322 static if (movecursor == "start") lc.pos2xy(spos, cx, cy);
3323 else static if (movecursor == "end") lc.pos2xy(ipos, cx, cy);
3324 txchanged = true;
3325 lineChangedByPos(spos, true);
3326 wasInserted(spos, toinsert, nlc);
3327 return true;
3331 // either we don't want indenting, or there are no eols in new text
3333 bool undoOk = false;
3334 // record undo
3335 if (undo !is null) undoOk = undo.addTextInsert(this, pos, cast(int)str.length);
3336 willBeInserted(pos, cast(int)str.length, nlc);
3337 // insert text
3338 auto newpos = lc.put(pos, str[]);
3339 if (newpos < 0) {
3340 // operation failed, rollback it
3341 if (undoOk) undo.popUndo(); // remove undo record
3342 return false;
3344 static if (movecursor == "start") lc.pos2xy(pos, cx, cy);
3345 else static if (movecursor == "end") lc.pos2xy(newpos, cx, cy);
3346 txchanged = true;
3347 lineChangedByPos(pos, (nlc > 0));
3348 wasInserted(pos, newpos-pos, nlc);
3351 return true;
3354 /// replace text at pos, save undo, mark updated lines
3355 /// return `false` if operation cannot be performed
3356 final bool replaceText(string movecursor="none", bool doIndent=false) (int pos, int count, const(char)[] str) {
3357 static assert(movecursor == "none" || movecursor == "start" || movecursor == "end");
3358 if (mReadOnly) return false;
3359 if (count < 0 || pos < 0) return false;
3360 if (mKillTextOnChar) {
3361 killTextOnChar = false;
3362 if (gb.textsize > 0) {
3363 undoGroupStart();
3364 bstart = bend = -1;
3365 markingBlock = false;
3366 deleteText!"start"(0, gb.textsize);
3367 undoGroupEnd();
3370 auto ts = gb.textsize;
3371 if (pos >= ts) pos = ts;
3372 if (count > ts-pos) count = ts-pos;
3373 bool needToRestoreBlock = (markingBlock || hasMarkedBlock);
3374 auto bs = bstart;
3375 auto be = bend;
3376 auto mb = markingBlock;
3377 undoGroupStart();
3378 scope(exit) undoGroupEnd();
3379 auto ocp = curpos;
3380 deleteText!movecursor(pos, count);
3381 static if (movecursor == "none") { bool cmoved = false; if (ocp > pos) { cmoved = true; ocp -= count; } }
3382 if (insertText!(movecursor, doIndent)(pos, str)) {
3383 static if (movecursor == "none") { if (cmoved) ocp += count; }
3384 if (needToRestoreBlock && !hasMarkedBlock) {
3385 // restore block if it was deleted
3386 bstart = bs;
3387 bend = be-count+cast(int)str.length;
3388 markingBlock = mb;
3389 if (bend < bstart) markingBlock = false;
3390 lastBGEnd = true;
3391 } else if (hasMarkedBlock && bs == pos && bstart > pos) {
3392 // consider the case when replaced text is inside the block,
3393 // and block is starting on the text
3394 bstart = pos;
3395 lastBGEnd = false; //???
3396 markBlockDirty();
3398 return true;
3400 return false;
3404 bool doBlockWrite (const(char)[] fname) {
3405 killTextOnChar = false;
3406 if (!hasMarkedBlock) return true;
3407 if (bend-bstart <= 0) return true;
3408 return doBlockWrite(VFile(fname, "w"));
3412 bool doBlockWrite (VFile fl) {
3413 import core.stdc.stdlib : malloc, free;
3414 killTextOnChar = false;
3415 if (!hasMarkedBlock) return true;
3416 gb.forEachBufPart(bstart, bend-bstart, delegate (const(char)[] buf) { fl.rawWriteExact(buf); });
3417 return true;
3421 bool doBlockRead (const(char)[] fname) { return doBlockRead(VFile(fname)); }
3424 bool doBlockRead (VFile fl) {
3425 //FIXME: optimize this!
3426 import core.stdc.stdlib : realloc, free;
3427 import core.stdc.string : memcpy;
3428 // read block data into temp buffer
3429 if (mReadOnly) return false;
3430 killTextOnChar = false;
3431 char* btext;
3432 scope(exit) if (btext !is null) free(btext);
3433 int blen = 0;
3434 char[1024] tb = void;
3435 for (;;) {
3436 auto rd = fl.rawRead(tb[]);
3437 if (rd.length == 0) break;
3438 if (blen+rd.length > int.max/2) return false;
3439 auto nb = cast(char*)realloc(btext, blen+rd.length);
3440 if (nb is null) return false;
3441 btext = nb;
3442 memcpy(btext+blen, rd.ptr, rd.length);
3443 blen += cast(int)rd.length;
3445 return insertText!("start", false)(curpos, btext[0..blen]); // no indent
3449 bool doBlockDelete () {
3450 if (mReadOnly) return false;
3451 if (!hasMarkedBlock) return true;
3452 return deleteText!"start"(bstart, bend-bstart, (pos, count) { doBlockResetMark(false); });
3456 bool doBlockCopy () {
3457 //FIXME: optimize this!
3458 import core.stdc.stdlib : malloc, free;
3459 if (mReadOnly) return false;
3460 killTextOnChar = false;
3461 if (!hasMarkedBlock) return true;
3462 // copy block data into temp buffer
3463 int blen = bend-bstart;
3464 GapBuffer.HighState* hsbuf;
3465 scope(exit) if (hsbuf !is null) free(hsbuf);
3466 if (asRich) {
3467 // rich text: get atts
3468 hsbuf = cast(GapBuffer.HighState*)malloc(blen*hsbuf[0].sizeof);
3469 if (hsbuf is null) return false;
3470 foreach (int pp; bstart..bend) hsbuf[pp-bstart] = gb.hi(pp);
3472 // normal text
3473 char* btext = cast(char*)malloc(blen);
3474 if (btext is null) return false; // alas
3475 scope(exit) free(btext);
3476 foreach (int pp; bstart..bend) btext[pp-bstart] = gb[pp];
3477 auto stp = curpos;
3478 return insertText!("start", false)(stp, btext[0..blen]); // no indent
3479 // attrs
3480 if (asRich) {
3481 foreach (immutable int idx; 0..blen) gb.hi(stp+idx) = hsbuf[idx];
3486 bool doBlockMove () {
3487 //FIXME: optimize this!
3488 import core.stdc.stdlib : malloc, free;
3489 if (mReadOnly) return false;
3490 killTextOnChar = false;
3491 if (!hasMarkedBlock) return true;
3492 int pos = curpos;
3493 if (pos >= bstart && pos < bend) return false; // can't do this while we are inside the block
3494 // copy block data into temp buffer
3495 int blen = bend-bstart;
3496 GapBuffer.HighState* hsbuf;
3497 scope(exit) if (hsbuf !is null) free(hsbuf);
3498 if (asRich) {
3499 // rich text: get atts
3500 hsbuf = cast(GapBuffer.HighState*)malloc(blen*hsbuf[0].sizeof);
3501 if (hsbuf is null) return false;
3502 foreach (int pp; bstart..bend) hsbuf[pp-bstart] = gb.hi(pp);
3504 char* btext = cast(char*)malloc(blen);
3505 if (btext is null) return false; // alas
3506 scope(exit) free(btext);
3507 foreach (int pp; bstart..bend) btext[pp-bstart] = gb[pp];
3508 // group undo action
3509 bool undoOk = undoGroupStart();
3510 if (pos >= bstart) pos -= blen;
3511 if (!doBlockDelete()) {
3512 // rollback
3513 if (undoOk) undo.popUndo();
3514 return false;
3516 auto stp = pos;
3517 if (!insertText!("start", false)(pos, btext[0..blen])) {
3518 // rollback
3519 if (undoOk) undo.popUndo();
3520 return false;
3522 // attrs
3523 if (asRich) {
3524 foreach (immutable int idx; 0..blen) gb.hi(stp+idx) = hsbuf[idx];
3526 // mark moved block
3527 bstart = pos;
3528 bend = pos+blen;
3529 markBlockDirty();
3530 undoGroupEnd();
3531 return true;
3535 void doDelete () {
3536 if (mReadOnly) return;
3537 int pos = curpos;
3538 if (pos >= gb.textsize) return;
3539 if (!lc.utfuck) {
3540 deleteText!"start"(pos, 1);
3541 } else {
3542 deleteText!"start"(pos, gb.utfuckLenAt(pos));
3547 void doBackspace () {
3548 if (mReadOnly) return;
3549 killTextOnChar = false;
3550 int pos = curpos;
3551 if (pos == 0) return;
3552 immutable int ppos = prevpos(pos);
3553 deleteText!"start"(ppos, pos-ppos);
3557 void doBackByIndent () {
3558 if (mReadOnly) return;
3559 int pos = curpos;
3560 int ls = lc.xy2pos(0, cy);
3561 if (pos == ls) { doDeleteWord(); return; }
3562 if (gb[pos-1] > ' ') { doDeleteWord(); return; }
3563 int rx, ry;
3564 lc.pos2xy(pos, rx, ry);
3565 int del = 2-rx%2;
3566 if (del > 1 && (pos-2 < ls || gb[pos-2] > ' ')) del = 1;
3567 pos -= del;
3568 deleteText!"start"(pos, del);
3572 void doDeleteWord () {
3573 if (mReadOnly) return;
3574 int pos = curpos;
3575 if (pos == 0) return;
3576 auto ch = gb[pos-1];
3577 if (!mSingleLine && ch == '\n') { doBackspace(); return; }
3578 int stpos = pos-1;
3579 // find word start
3580 if (ch <= ' ') {
3581 while (stpos > 0) {
3582 ch = gb[stpos-1];
3583 if ((!mSingleLine && ch == '\n') || ch > ' ') break;
3584 --stpos;
3586 } else if (isWordChar(ch)) {
3587 while (stpos > 0) {
3588 ch = gb[stpos-1];
3589 if (!isWordChar(ch)) break;
3590 --stpos;
3593 if (pos == stpos) return;
3594 deleteText!"start"(stpos, pos-stpos);
3598 void doKillLine () {
3599 if (mReadOnly) return;
3600 int ls = lc.xy2pos(0, cy);
3601 int le;
3602 if (cy == lc.linecount-1) {
3603 le = gb.textsize;
3604 } else {
3605 le = lc.xy2pos(0, cy+1);
3607 if (ls < le) deleteText!"start"(ls, le-ls);
3611 void doKillToEOL () {
3612 if (mReadOnly) return;
3613 int pos = curpos;
3614 auto ts = gb.textsize;
3615 if (mSingleLine) {
3616 if (pos < ts) deleteText!"start"(pos, ts-pos);
3617 } else {
3618 if (pos < ts && gb[pos] != '\n') {
3619 int epos = pos+1;
3620 while (epos < ts && gb[epos] != '\n') ++epos;
3621 deleteText!"start"(pos, epos-pos);
3626 /// split line at current position
3627 bool doLineSplit (bool autoindent=true) {
3628 if (mReadOnly || mSingleLine) return false;
3629 if (autoindent) {
3630 return insertText!("end", true)(curpos, "\n");
3631 } else {
3632 return insertText!("end", false)(curpos, "\n");
3636 /// put char in koi8
3637 void doPutChar (char ch) {
3638 if (mReadOnly) return;
3639 if (!mSingleLine && ch == '\n') { doLineSplit(inPasteMode <= 0); return; }
3640 if (ch > 127 && lc.utfuck) {
3641 char[8] ubuf = void;
3642 int len = utf8Encode(ubuf[], koi2uni(ch));
3643 if (len < 1) { ubuf[0] = '?'; len = 1; }
3644 insertText!("end", true)(curpos, ubuf[0..len]);
3645 return;
3647 if (ch >= 128 && codepage != CodePage.koi8u) ch = recodeCharTo(ch);
3648 if (inPasteMode <= 0) {
3649 insertText!("end", true)(curpos, (&ch)[0..1]);
3650 } else {
3651 insertText!("end", false)(curpos, (&ch)[0..1]);
3656 void doPutDChar (dchar dch) {
3657 if (mReadOnly) return;
3658 if (!Utf8DecoderFast.isValidDC(dch)) dch = Utf8DecoderFast.replacement;
3659 if (dch < 128) { doPutChar(cast(char)dch); return; }
3660 char[4] ubuf = void;
3661 auto len = utf8Encode(ubuf[], dch);
3662 if (len < 1) return;
3663 if (lc.utfuck) {
3664 insertText!"end"(curpos, ubuf.ptr[0..len]);
3665 } else {
3666 // recode to codepage
3667 doPutChar(recodeU2B(dch));
3672 void doPutTextUtf (const(char)[] str) {
3673 if (mReadOnly) return;
3674 if (str.length == 0) return;
3676 if (!mSingleLine && utfuck && inPasteMode > 0) {
3677 insertText!"end"(curpos, str);
3678 return;
3681 bool ugstarted = false;
3682 void startug () { if (!ugstarted) { ugstarted = true; undoGroupStart(); } }
3683 scope(exit) if (ugstarted) undoGroupEnd();
3685 Utf8DecoderFast udc;
3686 foreach (immutable char ch; str) {
3687 if (udc.decodeSafe(cast(ubyte)ch)) {
3688 dchar dch = cast(dchar)udc.codepoint;
3689 if (!mSingleLine && dch == '\n') { startug(); doLineSplit(inPasteMode <= 0); continue; }
3690 startug();
3691 doPutChar(recodeU2B(dch));
3696 /// put text in koi8
3697 void doPutText (const(char)[] str) {
3698 if (mReadOnly) return;
3699 if (str.length == 0) return;
3701 if (!mSingleLine && !utfuck && codepage == CodePage.koi8u && inPasteMode > 0) {
3702 insertText!"end"(curpos, str);
3703 return;
3706 bool ugstarted = false;
3707 void startug () { if (!ugstarted) { ugstarted = true; undoGroupStart(); } }
3708 scope(exit) if (ugstarted) undoGroupEnd();
3710 usize pos = 0;
3711 char ch;
3712 while (pos < str.length) {
3713 auto stpos = pos;
3714 while (pos < str.length) {
3715 ch = str.ptr[pos];
3716 if (!mSingleLine && ch == '\n') break;
3717 if (ch >= 128) break;
3718 ++pos;
3720 if (stpos < pos) { startug(); insertText!"end"(curpos, str.ptr[stpos..pos]); }
3721 if (pos >= str.length) break;
3722 ch = str.ptr[pos];
3723 if (!mSingleLine && ch == '\n') { startug(); doLineSplit(inPasteMode <= 0); ++pos; continue; }
3724 if (ch < ' ') { startug(); insertText!"end"(curpos, str.ptr[pos..pos+1]); ++pos; continue; }
3725 Utf8DecoderFast udc;
3726 stpos = pos;
3727 while (pos < str.length) if (udc.decode(cast(ubyte)(str.ptr[pos++]))) break;
3728 startug();
3729 if (udc.complete) {
3730 insertText!"end"(curpos, str.ptr[stpos..pos]);
3731 } else {
3732 ch = uni2koi(Utf8DecoderFast.replacement);
3733 insertText!"end"(curpos, (&ch)[0..1]);
3739 void doPasteStart () {
3740 if (mKillTextOnChar) {
3741 killTextOnChar = false;
3742 if (gb.textsize > 0) {
3743 undoGroupStart();
3744 bstart = bend = -1;
3745 markingBlock = false;
3746 deleteText!"start"(0, gb.textsize);
3747 undoGroupEnd();
3750 undoGroupStart();
3751 ++inPasteMode;
3755 void doPasteEnd () {
3756 killTextOnChar = false;
3757 if (--inPasteMode < 0) inPasteMode = 0;
3758 undoGroupEnd();
3761 protected final bool xIndentLine (int lidx) {
3762 //TODO: rollback
3763 if (mReadOnly) return false;
3764 if (lidx < 0 || lidx >= lc.linecount) return false;
3765 auto pos = lc.xy2pos(0, lidx);
3766 auto epos = lc.xy2pos(0, lidx+1);
3767 auto stpos = pos;
3768 // if line consists of blanks only, don't do anything
3769 while (pos < epos) {
3770 auto ch = gb[pos];
3771 if (ch == '\n') return true;
3772 if (ch > ' ') break;
3773 ++pos;
3775 if (pos >= gb.textsize) return true;
3776 pos = stpos;
3777 char[2] spc = ' ';
3778 return insertText!("none", false)(pos, spc[]);
3782 void doIndentBlock () {
3783 if (mReadOnly) return;
3784 killTextOnChar = false;
3785 if (!hasMarkedBlock) return;
3786 int sy = lc.pos2line(bstart);
3787 int ey = lc.pos2line(bend-1);
3788 bool bsAtBOL = (bstart == lc.line2pos(sy));
3789 undoGroupStart();
3790 scope(exit) undoGroupEnd();
3791 foreach (int lidx; sy..ey+1) xIndentLine(lidx);
3792 if (bsAtBOL) bstart = lc.line2pos(sy); // line already marked as dirty
3795 protected final bool xUnindentLine (int lidx) {
3796 if (mReadOnly) return false;
3797 if (lidx < 0 || lidx >= lc.linecount) return true;
3798 auto pos = lc.xy2pos(0, lidx);
3799 auto len = 1;
3800 if (gb[pos] > ' ' || gb[pos] == '\n') return true;
3801 if (pos+1 < gb.textsize && gb[pos+1] <= ' ' && gb[pos+1] != '\n') ++len;
3802 return deleteText!"none"(pos, len);
3806 void doUnindentBlock () {
3807 if (mReadOnly) return;
3808 killTextOnChar = false;
3809 if (!hasMarkedBlock) return;
3810 int sy = lc.pos2line(bstart);
3811 int ey = lc.pos2line(bend-1);
3812 undoGroupStart();
3813 scope(exit) undoGroupEnd();
3814 foreach (int lidx; sy..ey+1) xUnindentLine(lidx);
3817 // ////////////////////////////////////////////////////////////////////// //
3818 // actions
3820 version(egeditor_record_movement_undo) {
3821 /// push cursor position to undo stack
3822 final bool pushUndoCurPos () nothrow {
3823 return (undo !is null ? undo.addCurMove(this) : false);
3827 // returns old state
3828 enum SetupShiftMarkingMixin = q{
3829 auto omb = markingBlock;
3830 scope(exit) markingBlock = omb;
3831 if (domark) {
3832 if (!hasMarkedBlock) {
3833 int pos = curpos;
3834 bstart = bend = pos;
3835 lastBGEnd = true;
3837 markingBlock = true;
3842 void doWordLeft (bool domark=false) {
3843 mixin(SetupShiftMarkingMixin);
3844 killTextOnChar = false;
3845 int pos = curpos;
3846 if (pos == 0) return;
3847 auto ch = gb[pos-1];
3848 if (!mSingleLine && ch == '\n') { doLeft(); return; }
3849 int stpos = pos-1;
3850 // find word start
3851 if (ch <= ' ') {
3852 while (stpos > 0) {
3853 ch = gb[stpos-1];
3854 if ((!mSingleLine && ch == '\n') || ch > ' ') break;
3855 --stpos;
3858 if (stpos > 0 && isWordChar(ch)) {
3859 while (stpos > 0) {
3860 ch = gb[stpos-1];
3861 if (!isWordChar(ch)) break;
3862 --stpos;
3865 version(egeditor_record_movement_undo) pushUndoCurPos();
3866 lc.pos2xy(stpos, cx, cy);
3867 growBlockMark();
3871 void doWordRight (bool domark=false) {
3872 mixin(SetupShiftMarkingMixin);
3873 killTextOnChar = false;
3874 int pos = curpos;
3875 if (pos == gb.textsize) return;
3876 auto ch = gb[pos];
3877 if (!mSingleLine && ch == '\n') { doRight(); return; }
3878 int epos = pos+1;
3879 // find word start
3880 if (ch <= ' ') {
3881 while (epos < gb.textsize) {
3882 ch = gb[epos];
3883 if ((!mSingleLine && ch == '\n') || ch > ' ') break;
3884 ++epos;
3886 } else if (isWordChar(ch)) {
3887 while (epos < gb.textsize) {
3888 ch = gb[epos];
3889 if (!isWordChar(ch)) {
3890 if (ch <= ' ') {
3891 while (epos < gb.textsize) {
3892 ch = gb[epos];
3893 if ((!mSingleLine && ch == '\n') || ch > ' ') break;
3894 ++epos;
3897 break;
3899 ++epos;
3902 version(egeditor_record_movement_undo) pushUndoCurPos();
3903 lc.pos2xy(epos, cx, cy);
3904 growBlockMark();
3908 void doTextTop (bool domark=false) {
3909 mixin(SetupShiftMarkingMixin);
3910 if (lc.mLineCount < 2) return;
3911 killTextOnChar = false;
3912 if (mTopLine == 0 && cy == 0) return;
3913 version(egeditor_record_movement_undo) pushUndoCurPos();
3914 mTopLine = cy = 0;
3915 growBlockMark();
3919 void doTextBottom (bool domark=false) {
3920 mixin(SetupShiftMarkingMixin);
3921 if (lc.mLineCount < 2) return;
3922 killTextOnChar = false;
3923 if (cy >= lc.linecount-1) return;
3924 version(egeditor_record_movement_undo) pushUndoCurPos();
3925 cy = lc.linecount-1;
3926 growBlockMark();
3930 void doPageTop (bool domark=false) {
3931 mixin(SetupShiftMarkingMixin);
3932 if (lc.mLineCount < 2) return;
3933 killTextOnChar = false;
3934 if (cy == mTopLine) return;
3935 version(egeditor_record_movement_undo) pushUndoCurPos();
3936 cy = mTopLine;
3937 growBlockMark();
3941 void doPageBottom (bool domark=false) {
3942 mixin(SetupShiftMarkingMixin);
3943 if (lc.mLineCount < 2) return;
3944 killTextOnChar = false;
3945 int ny = mTopLine+linesPerWindow-1;
3946 if (ny >= lc.linecount) ny = lc.linecount-1;
3947 if (cy != ny) {
3948 version(egeditor_record_movement_undo) pushUndoCurPos();
3949 cy = ny;
3951 growBlockMark();
3955 void doScrollUp (bool domark=false) {
3956 mixin(SetupShiftMarkingMixin);
3957 if (mTopLine > 0) {
3958 killTextOnChar = false;
3959 version(egeditor_record_movement_undo) pushUndoCurPos();
3960 --mTopLine;
3961 --cy;
3962 } else if (cy > 0) {
3963 killTextOnChar = false;
3964 version(egeditor_record_movement_undo) pushUndoCurPos();
3965 --cy;
3967 growBlockMark();
3971 void doScrollDown (bool domark=false) {
3972 mixin(SetupShiftMarkingMixin);
3973 if (mTopLine+linesPerWindow < lc.linecount) {
3974 killTextOnChar = false;
3975 version(egeditor_record_movement_undo) pushUndoCurPos();
3976 ++mTopLine;
3977 ++cy;
3978 } else if (cy < lc.linecount-1) {
3979 killTextOnChar = false;
3980 version(egeditor_record_movement_undo) pushUndoCurPos();
3981 ++cy;
3983 growBlockMark();
3987 void doUp (bool domark=false) {
3988 mixin(SetupShiftMarkingMixin);
3989 if (cy > 0) {
3990 killTextOnChar = false;
3991 version(egeditor_record_movement_undo) pushUndoCurPos();
3992 --cy;
3993 // visjump
3994 if (winh >= 24 && isCurLineBeforeTop) {
3995 mTopLine = cy-(winh/3);
3996 if (mTopLine < 0) mTopLine = 0;
3997 setDirtyLinesLength(visibleLinesPerWindow);
3998 makeCurXVisible();
4001 growBlockMark();
4005 void doDown (bool domark=false) {
4006 mixin(SetupShiftMarkingMixin);
4007 if (cy < lc.linecount-1) {
4008 killTextOnChar = false;
4009 version(egeditor_record_movement_undo) pushUndoCurPos();
4010 ++cy;
4011 // visjump
4012 if (winh >= 24 && isCurLineAfterBottom) {
4013 mTopLine = cy+(winh/3)-linesPerWindow+1;
4014 if (mTopLine < 0) mTopLine = 0;
4015 setDirtyLinesLength(visibleLinesPerWindow);
4016 makeCurXVisible();
4019 growBlockMark();
4023 void doLeft (bool domark=false) {
4024 mixin(SetupShiftMarkingMixin);
4025 int rx, ry;
4026 killTextOnChar = false;
4027 lc.pos2xy(curpos, rx, ry);
4028 if (cx > rx) cx = rx;
4029 if (cx > 0) {
4030 version(egeditor_record_movement_undo) pushUndoCurPos();
4031 --cx;
4032 } else if (cy > 0) {
4033 // to prev line
4034 version(egeditor_record_movement_undo) pushUndoCurPos();
4035 lc.pos2xy(lc.xy2pos(0, cy)-1, cx, cy);
4037 growBlockMark();
4041 void doRight (bool domark=false) {
4042 mixin(SetupShiftMarkingMixin);
4043 int rx, ry;
4044 killTextOnChar = false;
4045 lc.pos2xy(lc.xy2pos(cx+1, cy), rx, ry);
4046 if (cx+1 > rx) {
4047 if (cy < lc.linecount-1) {
4048 version(egeditor_record_movement_undo) pushUndoCurPos();
4049 cx = 0;
4050 ++cy;
4052 } else {
4053 version(egeditor_record_movement_undo) pushUndoCurPos();
4054 ++cx;
4056 growBlockMark();
4060 void doPageUp (bool domark=false) {
4061 mixin(SetupShiftMarkingMixin);
4062 if (linesPerWindow < 2 || lc.mLineCount < 2) return;
4063 killTextOnChar = false;
4064 int ntl = mTopLine-(linesPerWindow-1);
4065 int ncy = cy-(linesPerWindow-1);
4066 if (ntl < 0) ntl = 0;
4067 if (ncy < 0) ncy = 0;
4068 if (ntl != mTopLine || ncy != cy) {
4069 version(egeditor_record_movement_undo) pushUndoCurPos();
4070 mTopLine = ntl;
4071 cy = ncy;
4073 growBlockMark();
4077 void doPageDown (bool domark=false) {
4078 mixin(SetupShiftMarkingMixin);
4079 if (linesPerWindow < 2 || lc.mLineCount < 2) return;
4080 killTextOnChar = false;
4081 int ntl = mTopLine+(linesPerWindow-1);
4082 int ncy = cy+(linesPerWindow-1);
4083 if (ntl+linesPerWindow >= lc.linecount) ntl = lc.linecount-linesPerWindow;
4084 if (ncy >= lc.linecount) ncy = lc.linecount-1;
4085 if (ntl < 0) ntl = 0;
4086 if (ntl != mTopLine || ncy != cy) {
4087 version(egeditor_record_movement_undo) pushUndoCurPos();
4088 mTopLine = ntl;
4089 cy = ncy;
4091 growBlockMark();
4095 void doHome (bool smart=true, bool domark=false) {
4096 mixin(SetupShiftMarkingMixin);
4097 killTextOnChar = false;
4098 if (cx != 0) {
4099 version(egeditor_record_movement_undo) pushUndoCurPos();
4100 cx = 0;
4101 } else {
4102 if (!smart) return;
4103 int nx = 0;
4104 auto pos = lc.xy2pos(0, cy);
4105 while (pos < gb.textsize) {
4106 auto ch = gb[pos];
4107 if (!mSingleLine && ch == '\n') return;
4108 if (ch > ' ') break;
4109 ++pos;
4110 ++nx;
4112 if (nx != cx) {
4113 version(egeditor_record_movement_undo) pushUndoCurPos();
4114 cx = nx;
4117 growBlockMark();
4121 void doEnd (bool domark=false) {
4122 mixin(SetupShiftMarkingMixin);
4123 int rx, ry;
4124 killTextOnChar = false;
4125 int ep;
4126 if (cy >= lc.linecount-1) {
4127 ep = gb.textsize;
4128 } else {
4129 ep = lc.lineend(cy);
4130 //if (gb[ep] != '\n') ++ep; // word wrapping
4132 lc.pos2xy(ep, rx, ry);
4133 if (rx != cx || ry != cy) {
4134 version(egeditor_record_movement_undo) pushUndoCurPos();
4135 cx = rx;
4136 cy = ry;
4138 growBlockMark();
4142 /*private*/protected void doUndoRedo (UndoStack us) { // "allMembers" trait: shut the fuck up!
4143 if (us is null) return;
4144 killTextOnChar = false;
4145 int level = 0;
4146 while (us.hasUndo) {
4147 auto tp = us.undoAction(this);
4148 switch (tp) {
4149 case UndoStack.Type.GroupStart:
4150 if (--level <= 0) return;
4151 break;
4152 case UndoStack.Type.GroupEnd:
4153 ++level;
4154 break;
4155 default:
4156 if (level <= 0) return;
4157 break;
4162 void doUndo () { doUndoRedo(undo); } ///
4163 void doRedo () { doUndoRedo(redo); } ///
4166 void doBlockResetMark (bool saveUndo=true) nothrow {
4167 killTextOnChar = false;
4168 if (bstart < bend) {
4169 version(egeditor_record_movement_undo) if (saveUndo) pushUndoCurPos();
4170 markLinesDirtySE(lc.pos2line(bstart), lc.pos2line(bend-1));
4172 bstart = bend = -1;
4173 markingBlock = false;
4176 /// toggle block marking mode
4177 void doToggleBlockMarkMode () {
4178 killTextOnChar = false;
4179 if (bstart == bend && markingBlock) { doBlockResetMark(false); return; }
4180 if (bstart < bend && !markingBlock) doBlockResetMark(false);
4181 int pos = curpos;
4182 if (!hasMarkedBlock) {
4183 bstart = bend = pos;
4184 markingBlock = true;
4185 lastBGEnd = true;
4186 } else {
4187 if (pos != bstart) {
4188 bend = pos;
4189 if (bend < bstart) { pos = bstart; bstart = bend; bend = pos; }
4191 markingBlock = false;
4192 dirtyLines[] = -1; //FIXME: optimize
4197 void doSetBlockStart () {
4198 killTextOnChar = false;
4199 auto pos = curpos;
4200 if ((hasMarkedBlock || (bstart == bend && bstart >= 0 && bstart < gb.textsize)) && pos < bend) {
4201 //if (pos < bstart) markRangeDirty(pos, bstart-pos); else markRangeDirty(bstart, pos-bstart);
4202 bstart = pos;
4203 lastBGEnd = false;
4204 } else {
4205 doBlockResetMark();
4206 bstart = bend = pos;
4207 lastBGEnd = false;
4209 markingBlock = false;
4210 dirtyLines[] = -1; //FIXME: optimize
4214 void doSetBlockEnd () {
4215 auto pos = curpos;
4216 if ((hasMarkedBlock || (bstart == bend && bstart >= 0 && bstart < gb.textsize)) && pos > bstart) {
4217 //if (pos < bend) markRangeDirty(pos, bend-pos); else markRangeDirty(bend, pos-bend);
4218 bend = pos;
4219 lastBGEnd = true;
4220 } else {
4221 doBlockResetMark();
4222 bstart = bend = pos;
4223 lastBGEnd = true;
4225 markingBlock = false;
4226 dirtyLines[] = -1; //FIXME: optimize
4229 protected:
4230 // called by undo/redo processors
4231 final void ubTextRemove (int pos, int len) {
4232 if (mReadOnly) return;
4233 killTextOnChar = false;
4234 int nlc = (!mSingleLine ? gb.countEolsInRange(pos, len) : 0);
4235 bookmarkDeletionFix(pos, len, nlc);
4236 lineChangedByPos(pos, (nlc > 0));
4237 lc.remove(pos, len);
4240 // called by undo/redo processors
4241 final bool ubTextInsert (int pos, const(char)[] str) {
4242 if (mReadOnly) return true;
4243 killTextOnChar = false;
4244 if (str.length == 0) return true;
4245 int nlc = (!mSingleLine ? gb.countEols(str) : 0);
4246 bookmarkInsertionFix(pos, pos+cast(int)str.length, nlc);
4247 if (lc.put(pos, str) >= 0) {
4248 lineChangedByPos(pos, (nlc > 0));
4249 return true;
4250 } else {
4251 return false;
4255 // can be called only after `ubTextInsert`, and with the same pos/length
4256 // usually it is done by undo/redo action if the editor is in "rich mode"
4257 final void ubTextSetAttrs (int pos, const(GapBuffer.HighState)[] hs) {
4258 if (mReadOnly || hs.length == 0) return;
4259 assert(gb.hasHiBuffer);
4260 foreach (const ref hi; hs) gb.hbuf[gb.pos2real(pos++)] = hi;
4263 // ////////////////////////////////////////////////////////////////////// //
4264 public static struct TextRange {
4265 private:
4266 EditorEngine ed;
4267 int pos;
4268 int left; // chars left, including front
4269 char frontch = 0;
4270 nothrow:
4271 private:
4272 this (EditorEngine aed, int apos, int aleft, char afrontch) pure {
4273 ed = aed;
4274 pos = apos;
4275 left = aleft;
4276 frontch = afrontch;
4279 this (EditorEngine aed, usize lo, usize hi) {
4280 ed = aed;
4281 if (aed !is null && lo < hi && lo < aed.gb.textsize) {
4282 pos = cast(int)lo;
4283 if (hi > ed.gb.textsize) hi = ed.gb.textsize;
4284 left = cast(int)hi-pos+1; // compensate for first popFront
4285 popFront();
4288 public:
4289 @property bool empty () const pure @safe @nogc { pragma(inline, true); return (left <= 0); }
4290 @property char front () const pure @safe @nogc { pragma(inline, true); return frontch; }
4291 void popFront () {
4292 if (ed is null || left < 2) { left = 0; frontch = 0; return; }
4293 --left;
4294 if (pos >= ed.gb.textsize) { left = 0; frontch = 0; return; }
4295 frontch = ed.gb[pos++];
4297 auto save () pure { pragma(inline, true); return TextRange(ed, pos, left, frontch); }
4298 @property usize length () const pure @safe @nogc { pragma(inline, true); return (left > 0 ? left : 0); }
4299 alias opDollar = length;
4300 char opIndex (usize idx) {
4301 pragma(inline, true);
4302 return (left > 0 && idx < left ? (idx == 0 ? frontch : ed.gb[pos+cast(int)idx-1]) : 0);
4304 auto opSlice () pure { pragma(inline, true); return this.save; }
4305 //WARNING: logic untested!
4306 auto opSlice (uint lo, uint hi) {
4307 if (ed is null || left <= 0 || lo >= left || lo >= hi) return TextRange(null, 0, 0);
4308 hi -= lo; // convert to length
4309 if (hi > left) hi = left;
4310 if (left-lo > hi) hi = left-lo;
4311 return TextRange(ed, cast(int)lo+1, cast(int)hi, ed.gb[cast(int)lo]);
4313 // make it bidirectional, just for fun
4314 //WARNING: completely untested!
4315 char back () const pure {
4316 pragma(inline, true);
4317 return (ed !is null && left > 0 ? (left == 1 ? frontch : ed.gb[pos+left-2]) : 0);
4319 void popBack () {
4320 if (ed is null || left < 2) { left = 0; frontch = 0; return; }
4321 --left;
4325 public:
4326 /// range interface to editor text
4327 /// WARNING! do not change anything while range is active, or results *WILL* be UD
4328 final TextRange opSlice (usize lo, usize hi) nothrow { return TextRange(this, lo, hi); }
4329 final TextRange opSlice () nothrow { return TextRange(this, 0, gb.textsize); } /// ditto
4330 final int opDollar () nothrow { return gb.textsize; } ///
4333 final TextRange markedBlockRange () nothrow {
4334 if (!hasMarkedBlock) return TextRange.init;
4335 return TextRange(this, bstart, bend);
4338 static:
4340 bool isWordChar (char ch) pure nothrow {
4341 return (ch.isalnum || ch == '_' || ch > 127);