]> git.lyx.org Git - lyx.git/blob - src/Cursor.cpp
Merge branch 'master' of git.lyx.org:lyx
[lyx.git] / src / Cursor.cpp
1 /**
2  * \file Cursor.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  * \author Alfredo Braunstein
8  * \author Dov Feldstern
9  * \author André Pönitz
10  * \author Stefan Schimanski
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "Buffer.h"
18 #include "BufferView.h"
19 #include "CoordCache.h"
20 #include "Cursor.h"
21 #include "CutAndPaste.h"
22 #include "DispatchResult.h"
23 #include "Encoding.h"
24 #include "Font.h"
25 #include "FuncCode.h"
26 #include "FuncRequest.h"
27 #include "Language.h"
28 #include "Layout.h"
29 #include "LyXAction.h"
30 #include "LyXRC.h"
31 #include "Paragraph.h"
32 #include "ParIterator.h"
33 #include "Row.h"
34 #include "Text.h"
35 #include "TextMetrics.h"
36 #include "TocBackend.h"
37
38 #include "support/debug.h"
39 #include "support/docstream.h"
40 #include "support/ExceptionMessage.h"
41 #include "support/gettext.h"
42 #include "support/lassert.h"
43
44 #include "insets/InsetTabular.h"
45 #include "insets/InsetText.h"
46
47 #include "mathed/InsetMath.h"
48 #include "mathed/InsetMathBrace.h"
49 #include "mathed/InsetMathScript.h"
50 #include "mathed/MacroTable.h"
51 #include "mathed/MathData.h"
52 #include "mathed/MathMacro.h"
53
54 #include "support/bind.h"
55
56 #include <sstream>
57 #include <limits>
58 #include <map>
59 #include <algorithm>
60
61 using namespace std;
62
63 namespace lyx {
64
65 namespace {
66
67 // Find position closest to (x, y) in cell given by iter.
68 // Used only in mathed
69 DocIterator bruteFind(Cursor const & c, int x, int y)
70 {
71         double best_dist = numeric_limits<double>::max();
72
73         DocIterator result;
74
75         DocIterator it = c;
76         it.pos() = 0;
77         DocIterator et = c;
78         et.pos() = et.lastpos();
79         for (size_t i = 0;; ++i) {
80                 int xo;
81                 int yo;
82                 Inset const * inset = &it.inset();
83                 CoordCache::Insets const & insetCache = c.bv().coordCache().getInsets();
84
85                 // FIXME: in the case where the inset is not in the cache, this
86                 // means that no part of it is visible on screen. In this case
87                 // we don't do elaborate search and we just return the forwarded
88                 // DocIterator at its beginning.
89                 if (!insetCache.has(inset)) {
90                         it.top().pos() = 0;
91                         return it;
92                 }
93
94                 Point const o = insetCache.xy(inset);
95                 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
96                 // Convert to absolute
97                 xo += o.x_;
98                 yo += o.y_;
99                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
100                 // '<=' in order to take the last possible position
101                 // this is important for clicking behind \sum in e.g. '\sum_i a'
102                 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
103                         << " best: " << best_dist);
104                 if (d <= best_dist) {
105                         best_dist = d;
106                         result = it;
107                 }
108                 if (it == et)
109                         break;
110                 it.forwardPos();
111         }
112         return result;
113 }
114
115
116 } // namespace anon
117
118
119 CursorData::CursorData()
120         : DocIterator(), anchor_(),
121           selection_(false), mark_(false), word_selection_(false),
122           current_font(inherit_font),
123           autocorrect_(false), macromode_(false)
124 {}
125
126
127 CursorData::CursorData(Buffer * buffer)
128         : DocIterator(buffer), anchor_(),
129           selection_(false), mark_(false), word_selection_(false),
130           current_font(inherit_font),
131           autocorrect_(false), macromode_(false)
132 {}
133
134
135 CursorData::CursorData(DocIterator const & dit)
136         : DocIterator(dit), anchor_(),
137           selection_(false), mark_(false), word_selection_(false),
138           current_font(inherit_font),
139           autocorrect_(false), macromode_(false)
140 {}
141
142
143
144
145 ostream & operator<<(ostream & os, CursorData const & cur)
146 {
147         os << "\n cursor:                                | anchor:\n";
148         for (size_t i = 0, n = cur.depth(); i != n; ++i) {
149                 os << " " << cur[i] << " | ";
150                 if (i < cur.anchor_.depth())
151                         os << cur.anchor_[i];
152                 else
153                         os << "-------------------------------";
154                 os << "\n";
155         }
156         for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
157                 os << "------------------------------- | " << cur.anchor_[i] << "\n";
158         }
159         os << " selection: " << cur.selection_
160 //         << " x_target: " << cur.x_target_
161            << " boundary: " << cur.boundary() << endl;
162         return os;
163 }
164
165
166 LyXErr & operator<<(LyXErr & os, CursorData const & cur)
167 {
168         os.stream() << cur;
169         return os;
170 }
171
172
173 // be careful: this is called from the bv's constructor, too, so
174 // bv functions are not yet available!
175 Cursor::Cursor(BufferView & bv)
176         : CursorData(&bv.buffer()), bv_(&bv),
177           x_target_(-1), textTargetOffset_(0),
178           beforeDispatchPosX_(0), beforeDispatchPosY_(0)
179 {}
180
181
182 void Cursor::reset()
183 {
184         clear();
185         push_back(CursorSlice(buffer()->inset()));
186         anchor_ = doc_iterator_begin(buffer());
187         anchor_.clear();
188         new_word_ = doc_iterator_begin(buffer());
189         new_word_.clear();
190         clearTargetX();
191         selection_ = false;
192         mark_ = false;
193 }
194
195
196 // this (intentionally) does neither touch anchor nor selection status
197 void Cursor::setCursor(DocIterator const & cur)
198 {
199         DocIterator::operator=(cur);
200 }
201
202
203 void Cursor::setCursorToAnchor()
204 {
205         if (selection()) {
206                 DocIterator normal = anchor_;
207                 while (depth() < normal.depth())
208                         normal.pop_back();
209                 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
210                         ++normal.pos();
211                 setCursor(normal);
212         }
213 }
214
215
216 void Cursor::setCursorData(CursorData const & data)
217 {
218         CursorData::operator=(data);
219 }
220
221
222 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
223 {
224         Cursor cur = *this;
225
226         // Try to fix cursor in case it is broken.
227         cur.fixIfBroken();
228
229         // Is this a function that acts on inset at point?
230         Inset * inset = cur.nextInset();
231         if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
232             && inset && inset->getStatus(cur, cmd, status))
233                 return true;
234
235         // This is, of course, a mess. Better create a new doc iterator and use
236         // this in Inset::getStatus. This might require an additional
237         // BufferView * arg, though (which should be avoided)
238         //Cursor safe = *this;
239         bool res = false;
240         for ( ; cur.depth(); cur.pop()) {
241                 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
242                 // LASSERT: Is it safe to continue here, or should we return?
243                 LASSERT(cur.idx() <= cur.lastidx(), /**/);
244                 LASSERT(cur.pit() <= cur.lastpit(), /**/);
245                 LASSERT(cur.pos() <= cur.lastpos(), /**/);
246
247                 // The inset's getStatus() will return 'true' if it made
248                 // a definitive decision on whether it want to handle the
249                 // request or not. The result of this decision is put into
250                 // the 'status' parameter.
251                 if (cur.inset().getStatus(cur, cmd, status)) {
252                         res = true;
253                         break;
254                 }
255         }
256         return res;
257 }
258
259
260 void Cursor::saveBeforeDispatchPosXY()
261 {
262         getPos(beforeDispatchPosX_, beforeDispatchPosY_);
263 }
264
265
266 void Cursor::dispatch(FuncRequest const & cmd0)
267 {
268         LYXERR(Debug::ACTION, "Cursor::dispatch: cmd: " << cmd0 << '\n' << *this);
269         if (empty())
270                 return;
271
272         fixIfBroken();
273         FuncRequest cmd = cmd0;
274         Cursor safe = *this;
275         Cursor old = *this;
276         disp_ = DispatchResult();
277
278         beginUndoGroup();
279
280         // Is this a function that acts on inset at point?
281         if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
282             && nextInset()) {
283                 disp_.dispatched(true);
284                 disp_.screenUpdate(Update::FitCursor | Update::Force);
285                 FuncRequest tmpcmd = cmd;
286                 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
287                         << cmd0 << endl << *this);
288                 nextInset()->dispatch(*this, tmpcmd);
289                 if (disp_.dispatched()) {
290                         endUndoGroup();
291                         return;
292                 }
293         }
294
295         // store some values to be used inside of the handlers
296         beforeDispatchCursor_ = *this;
297         for (; depth(); pop(), boundary(false)) {
298                 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
299                         << cmd0 << endl << *this);
300
301                 // In any of these cases, the cursor is invalid, and we should
302                 // try to save this document rather than crash.
303                 LBUFERR(pos() <= lastpos());
304                 LBUFERR(idx() <= lastidx());
305                 LBUFERR(pit() <= lastpit());
306
307                 // The common case is 'LFUN handled, need update', so make the
308                 // LFUN handler's life easier by assuming this as default value.
309                 // The handler can reset the update and val flags if necessary.
310                 disp_.screenUpdate(Update::FitCursor | Update::Force);
311                 disp_.dispatched(true);
312                 inset().dispatch(*this, cmd);
313                 if (disp_.dispatched())
314                         break;
315         }
316
317         // it completely to get a 'bomb early' behaviour in case this
318         // object will be used again.
319         if (!disp_.dispatched()) {
320                 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
321                 // We might have invalidated the cursor when removing an empty
322                 // paragraph while the cursor could not be moved out the inset
323                 // while we initially thought we could. This might happen when
324                 // a multiline inset becomes an inline inset when the second
325                 // paragraph is removed.
326                 if (safe.pit() > safe.lastpit()) {
327                         safe.pit() = safe.lastpit();
328                         safe.pos() = safe.lastpos();
329                 }
330                 operator=(safe);
331                 disp_.screenUpdate(Update::None);
332                 disp_.dispatched(false);
333         } else {
334                 // restore the previous one because nested Cursor::dispatch calls
335                 // are possible which would change it
336                 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
337         }
338         endUndoGroup();
339
340         // NOTE: The code below has been copied to BufferView::dispatch.
341         // If you need to modify this, please update the other one too.
342
343         // notify insets we just left
344         if (*this != old) {
345                 old.beginUndoGroup();
346                 old.fixIfBroken();
347                 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
348                 if (badcursor) {
349                         fixIfBroken();
350                         bv().resetInlineCompletionPos();
351                 }
352                 old.endUndoGroup();
353         }
354 }
355
356
357 DispatchResult const & Cursor::result() const
358 {
359         return disp_;
360 }
361
362
363 BufferView & Cursor::bv() const
364 {
365         LBUFERR(bv_);
366         return *bv_;
367 }
368
369
370 void Cursor::pop()
371 {
372         LBUFERR(depth() >= 1);
373         pop_back();
374 }
375
376
377 void Cursor::push(Inset & p)
378 {
379         push_back(CursorSlice(p));
380         p.setBuffer(*buffer());
381 }
382
383
384 void Cursor::pushBackward(Inset & p)
385 {
386         LASSERT(!empty(), return);
387         //lyxerr << "Entering inset " << t << " front" << endl;
388         push(p);
389         p.idxFirst(*this);
390 }
391
392
393 bool Cursor::popBackward()
394 {
395         LASSERT(!empty(), return false);
396         if (depth() == 1)
397                 return false;
398         pop();
399         return true;
400 }
401
402
403 bool Cursor::popForward()
404 {
405         LASSERT(!empty(), return false);
406         //lyxerr << "Leaving inset from in back" << endl;
407         const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
408         if (depth() == 1)
409                 return false;
410         pop();
411         pos() += lastpos() - lp + 1;
412         return true;
413 }
414
415
416 int Cursor::currentMode()
417 {
418         LASSERT(!empty(), return Inset::UNDECIDED_MODE);
419         for (int i = depth() - 1; i >= 0; --i) {
420                 int res = operator[](i).inset().currentMode();
421                 bool locked_mode = operator[](i).inset().lockedMode();
422                 // Also return UNDECIDED_MODE when the mode is locked,
423                 // as in this case it is treated the same as TEXT_MODE
424                 if (res != Inset::UNDECIDED_MODE || locked_mode)
425                         return res;
426         }
427         return Inset::TEXT_MODE;
428 }
429
430
431 bool Cursor::inCoordCache() const
432 {
433         // the root inset is not in cache, but we do not need it.
434         if (depth() == 1)
435                 return true;
436         CoordCache::Insets const & icache = bv_->coordCache().getInsets();
437         for (size_t i = 1 ; i < depth() ; ++i)
438                 if (!icache.has(&(*this)[i].inset()))
439                         return false;
440         return true;
441 }
442
443
444 void Cursor::getPos(int & x, int & y) const
445 {
446         Point p = bv().getPos(*this);
447         x = p.x_;
448         y = p.y_;
449 }
450
451
452 Row const & Cursor::textRow() const
453 {
454         CursorSlice const & cs = innerTextSlice();
455         ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
456         return pm.getRow(pos(), boundary());
457 }
458
459
460 void Cursor::resetAnchor()
461 {
462         anchor_ = *this;
463         checkNewWordPosition();
464 }
465
466
467 void Cursor::markNewWordPosition()
468 {
469         if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
470                 FontSpan nw = locateWord(WHOLE_WORD);
471                 if (nw.size() == 1) {
472                         LYXERR(Debug::DEBUG, "start new word: "
473                                 << " par: " << pit()
474                                 << " pos: " << nw.first);
475                         new_word_ = *this;
476                 }
477         }
478 }
479
480
481 void Cursor::clearNewWordPosition()
482 {
483         if (!new_word_.empty()) {
484                 LYXERR(Debug::DEBUG, "clear new word: "
485                         << " par: " << pit()
486                         << " pos: " << pos());
487                 new_word_.resize(0);
488         }
489 }
490
491
492 void Cursor::checkNewWordPosition()
493 {
494         if (!lyxrc.spellcheck_continuously || new_word_.empty())
495                 return ;
496         if (!inTexted())
497                 clearNewWordPosition();
498         else {
499                 // forget the position of the current new word if
500                 // 1) the paragraph changes or
501                 // 2) the count of nested insets changes or
502                 // 3) the cursor pos is out of paragraph bound
503                 if (pit() != new_word_.pit() ||
504                         depth() != new_word_.depth() ||
505                         new_word_.pos() > new_word_.lastpos()) {
506                         clearNewWordPosition();
507                 } else if (new_word_.fixIfBroken())
508                         // 4) or the remembered position was "broken"
509                         clearNewWordPosition();
510                 else {
511                         FontSpan nw = locateWord(WHOLE_WORD);
512                         if (!nw.empty()) {
513                                 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
514                                 if (nw.intersect(ow).empty())
515                                         clearNewWordPosition();
516                                 else
517                                         LYXERR(Debug::DEBUG, "new word: "
518                                                    << " par: " << pit()
519                                                    << " pos: " << nw.first << ".." << nw.last);
520                         } else {
521                                 clearNewWordPosition();
522                         }
523                 }
524         }
525 }
526
527
528 bool Cursor::posBackward()
529 {
530         if (pos() == 0)
531                 return false;
532         --pos();
533         return true;
534 }
535
536
537 bool Cursor::posForward()
538 {
539         if (pos() == lastpos())
540                 return false;
541         ++pos();
542         return true;
543 }
544
545
546 bool Cursor::posVisRight(bool skip_inset)
547 {
548         Cursor new_cur = *this; // where we will move to
549         pos_type left_pos; // position visually left of current cursor
550         pos_type right_pos; // position visually right of current cursor
551
552         getSurroundingPos(left_pos, right_pos);
553
554         LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
555
556         // Are we at an inset?
557         new_cur.pos() = right_pos;
558         new_cur.boundary(false);
559         if (!skip_inset &&
560                 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
561                 // we actually move the cursor at the end of this
562                 // function, for now we just keep track of the new
563                 // position in new_cur...
564                 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
565         }
566
567         // Are we already at rightmost pos in row?
568         else if (text()->empty() || right_pos == -1) {
569
570                 new_cur = *this;
571                 if (!new_cur.posVisToNewRow(false)) {
572                         LYXERR(Debug::RTL, "not moving!");
573                         return false;
574                 }
575
576                 // we actually move the cursor at the end of this
577                 // function, for now just keep track of the new
578                 // position in new_cur...
579                 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
580                         << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
581
582         }
583         // normal movement to the right
584         else {
585                 new_cur = *this;
586                 // Recall, if the cursor is at position 'x', that
587                 // means *before* the character at position 'x'. In
588                 // RTL, "before" means "to the right of", in LTR, "to
589                 // the left of". So currently our situation is this:
590                 // the position to our right is 'right_pos' (i.e.,
591                 // we're currently to the left of 'right_pos'). In
592                 // order to move to the right, it depends whether or
593                 // not the character at 'right_pos' is RTL.
594                 bool const new_pos_is_RTL = paragraph().getFontSettings(
595                         buffer()->params(), right_pos).isVisibleRightToLeft();
596                 // If the character at 'right_pos' *is* LTR, then in
597                 // order to move to the right of it, we need to be
598                 // *after* 'right_pos', i.e., move to position
599                 // 'right_pos' + 1.
600                 if (!new_pos_is_RTL) {
601                         new_cur.pos() = right_pos + 1;
602                         // set the boundary to true in two situations:
603                         if (
604                         // 1. if new_pos is now lastpos, and we're in
605                         // an RTL paragraph (this means that we're
606                         // moving right to the end of an LTR chunk
607                         // which is at the end of an RTL paragraph);
608                                 (new_cur.pos() == lastpos()
609                                  && paragraph().isRTL(buffer()->params()))
610                         // 2. if the position *after* right_pos is RTL
611                         // (we want to be *after* right_pos, not
612                         // before right_pos + 1!)
613                                 || paragraph().getFontSettings(buffer()->params(),
614                                                 new_cur.pos()).isVisibleRightToLeft()
615                         )
616                                 new_cur.boundary(true);
617                         else // set the boundary to false
618                                 new_cur.boundary(false);
619                 }
620                 // Otherwise (if the character at position 'right_pos'
621                 // is RTL), then moving to the right of it is as easy
622                 // as setting the new position to 'right_pos'.
623                 else {
624                         new_cur.pos() = right_pos;
625                         new_cur.boundary(false);
626                 }
627
628         }
629
630         bool const moved = new_cur != *this || new_cur.boundary() != boundary();
631
632         if (moved) {
633                 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
634                         << (new_cur.boundary() ? " (boundary)" : ""));
635                 *this = new_cur;
636         }
637
638         return moved;
639 }
640
641
642 bool Cursor::posVisLeft(bool skip_inset)
643 {
644         Cursor new_cur = *this; // where we will move to
645         pos_type left_pos; // position visually left of current cursor
646         pos_type right_pos; // position visually right of current cursor
647
648         getSurroundingPos(left_pos, right_pos);
649
650         LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
651
652         // Are we at an inset?
653         new_cur.pos() = left_pos;
654         new_cur.boundary(false);
655         if (!skip_inset &&
656                 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
657                 // we actually move the cursor at the end of this
658                 // function, for now we just keep track of the new
659                 // position in new_cur...
660                 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
661         }
662
663         // Are we already at leftmost pos in row?
664         else if (text()->empty() || left_pos == -1) {
665
666                 new_cur = *this;
667                 if (!new_cur.posVisToNewRow(true)) {
668                         LYXERR(Debug::RTL, "not moving!");
669                         return false;
670                 }
671
672                 // we actually move the cursor at the end of this
673                 // function, for now just keep track of the new
674                 // position in new_cur...
675                 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
676                         << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
677
678         }
679         // normal movement to the left
680         else {
681                 new_cur = *this;
682                 // Recall, if the cursor is at position 'x', that
683                 // means *before* the character at position 'x'. In
684                 // RTL, "before" means "to the right of", in LTR, "to
685                 // the left of". So currently our situation is this:
686                 // the position to our left is 'left_pos' (i.e., we're
687                 // currently to the right of 'left_pos'). In order to
688                 // move to the left, it depends whether or not the
689                 // character at 'left_pos' is RTL.
690                 bool const new_pos_is_RTL = paragraph().getFontSettings(
691                         buffer()->params(), left_pos).isVisibleRightToLeft();
692                 // If the character at 'left_pos' *is* RTL, then in
693                 // order to move to the left of it, we need to be
694                 // *after* 'left_pos', i.e., move to position
695                 // 'left_pos' + 1.
696                 if (new_pos_is_RTL) {
697                         new_cur.pos() = left_pos + 1;
698                         // set the boundary to true in two situations:
699                         if (
700                         // 1. if new_pos is now lastpos and we're in
701                         // an LTR paragraph (this means that we're
702                         // moving left to the end of an RTL chunk
703                         // which is at the end of an LTR paragraph);
704                                 (new_cur.pos() == lastpos()
705                                  && !paragraph().isRTL(buffer()->params()))
706                         // 2. if the position *after* left_pos is not
707                         // RTL (we want to be *after* left_pos, not
708                         // before left_pos + 1!)
709                                 || !paragraph().getFontSettings(buffer()->params(),
710                                                 new_cur.pos()).isVisibleRightToLeft()
711                         )
712                                 new_cur.boundary(true);
713                         else // set the boundary to false
714                                 new_cur.boundary(false);
715                 }
716                 // Otherwise (if the character at position 'left_pos'
717                 // is LTR), then moving to the left of it is as easy
718                 // as setting the new position to 'left_pos'.
719                 else {
720                         new_cur.pos() = left_pos;
721                         new_cur.boundary(false);
722                 }
723
724         }
725
726         bool const moved = new_cur != *this || new_cur.boundary() != boundary();
727
728         if (moved) {
729                 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
730                         << (new_cur.boundary() ? " (boundary)" : ""));
731                 *this = new_cur;
732         }
733
734         return moved;
735 }
736
737
738 namespace {
739
740 // Return true on success
741 bool findNonVirtual(Row const & row, Row::const_iterator & cit, bool onleft)
742 {
743         if (onleft) {
744                 while (cit != row.begin() && cit->isVirtual())
745                         --cit;
746         } else {
747                 while (cit != row.end() && cit->isVirtual())
748                         ++cit;
749         }
750         return cit != row.end() && !cit->isVirtual();
751 }
752
753 }
754
755 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const
756 {
757         // by default, we know nothing.
758         left_pos = -1;
759         right_pos = -1;
760
761         Row const & row = textRow();
762         TextMetrics const & tm = bv_->textMetrics(text());
763         double dummy = 0;
764         Row::const_iterator cit = tm.findRowElement(row, pos(), boundary(), dummy);
765         // Handle the case of empty row
766         if (cit == row.end()) {
767                 if (paragraph().isRTL(buffer()->params()))
768                         right_pos = row.pos();
769                 else
770                         left_pos = row.pos() - 1;
771                 return;
772         }
773
774         // skip virtual elements and exit if no non-virtual one exists
775         if (!findNonVirtual(row, cit, !cit->isRTL()))
776                 return;
777
778         // if the position is at the left side of the element, we have to
779         // look at the previous element
780         if (pos() == cit->left_pos()) {
781                 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
782                            << "), AT LEFT of *cit=" << *cit);
783                 // this one is easy (see common case below)
784                 right_pos = pos() - (cit->isRTL() ? 1 : 0);
785                 // at the left of the row
786                 if (cit == row.begin())
787                         return;
788                 --cit;
789                 if (!findNonVirtual(row, cit, true))
790                         return;
791                 // [...[ is the row element, | is cursor position (! with boundary)
792                 // [ 1 2 [ is a ltr row element with pos=1 and endpos=3
793                 // ] 2 1] is an rtl row element with pos=1 and endpos=3
794                 //    [ 1 2 [  [|3 4 [ => (2, 3)
795                 // or [ 1 2 [  ]!4 3 ] => (2, 4)
796                 // or ] 2 1 ]  [|3 4 [ => (1, 3)
797                 // or ] 4 3 ]  ]!2 1 ] => (3, 2)
798                 left_pos = cit->right_pos() - (cit->isRTL() ? 0 : 1);
799                 // happens with consecutive row of same direction
800                 if (left_pos == right_pos) {
801                         left_pos += cit->isRTL() ? 1 : -1;
802                 }
803         }
804         // same code but with the element at the right
805         else if (pos() == cit->right_pos()) {
806                 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
807                            << "), AT RIGHT of *cit=" << *cit);
808                 // this one is easy (see common case below)
809                 left_pos = pos() - (cit->isRTL() ? 0 : 1);
810                 // at the right of the row
811                 if (cit + 1 == row.end())
812                         return;
813                 ++cit;
814                 if (!findNonVirtual(row, cit, false))
815                         return;
816                 //    [ 1 2![  [ 3 4 [ => (2, 3)
817                 // or [ 1 2![  ] 4 3 ] => (2, 4)
818                 // or ] 2 1|]  [ 3 4 [ => (1, 3)
819                 // or ] 4 3|]  ] 2 1 ] => (3, 2)
820                 right_pos = cit->left_pos() - (cit->isRTL() ? 1 : 0);
821                 // happens with consecutive row of same direction
822                 if (right_pos == left_pos)
823                         right_pos += cit->isRTL() ? -1 : 1;
824         }
825         // common case: both positions are inside the row element
826         else {
827                 //    [ 1 2|3 [ => (2, 3)
828                 // or ] 3|2 1 ] => (3, 2)
829                 left_pos = pos() - (cit->isRTL() ? 0 : 1);
830                 right_pos = pos() - (cit->isRTL() ? 1 : 0);
831         }
832
833         // Note that debug message does not catch all early returns above
834         LYXERR(Debug::RTL,"getSurroundingPos(" << pos() << (boundary() ? "b" : "")
835                    << ") => (" << left_pos << ", " << right_pos <<")");
836 }
837
838
839 bool Cursor::posVisToNewRow(bool movingLeft)
840 {
841         Paragraph const & par = paragraph();
842         Buffer const & buf = *buffer();
843         Row const & row = textRow();
844         bool par_is_LTR = !par.isRTL(buf.params());
845
846         // Inside a table, determining whether to move to the next or
847         // previous row should be done based on the table's direction.
848         if (inset().asInsetTabular()) {
849                 par_is_LTR = !inset().asInsetTabular()->isRightToLeft(*this);
850                 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
851         }
852
853         // if moving left in an LTR paragraph or moving right in an
854         // RTL one, move to previous row
855         if (par_is_LTR == movingLeft) {
856                 if (row.pos() == 0) { // we're at first row in paragraph
857                         if (pit() == 0) // no previous paragraph! don't move
858                                 return false;
859                         // move to last pos in previous par
860                         --pit();
861                         pos() = lastpos();
862                         boundary(false);
863                 } else { // move to previous row in this par
864                         pos() = row.pos() - 1; // this is guaranteed to be in previous row
865                         boundary(false);
866                 }
867         }
868         // if moving left in an RTL paragraph or moving right in an
869         // LTR one, move to next row
870         else {
871                 if (row.endpos() == lastpos()) { // we're at last row in paragraph
872                         if (pit() == lastpit()) // last paragraph! don't move
873                                 return false;
874                         // move to first row in next par
875                         ++pit();
876                         pos() = 0;
877                         boundary(false);
878                 } else { // move to next row in this par
879                         pos() = row.endpos();
880                         boundary(false);
881                 }
882         }
883
884         // make sure we're at left-/right-most pos in new row
885         posVisToRowExtremity(!movingLeft);
886
887         return true;
888 }
889
890
891 void Cursor::posVisToRowExtremity(bool left)
892 {
893         LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
894                 << (boundary() ? 1 : 0));
895
896         TextMetrics const & tm = bv_->textMetrics(text());
897         // Looking for extremities is like clicking on the left or the
898         // right of the row.
899         int x = tm.origin().x_ + (left ? 0 : textRow().width());
900         bool b = false;
901         pos() = tm.getPosNearX(textRow(), x, b);
902         boundary(b);
903
904         LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
905                 << (boundary() ? 1 : 0));
906 }
907
908
909 bool Cursor::reverseDirectionNeeded() const
910 {
911         /*
912          * We determine the directions based on the direction of the
913          * bottom() --- i.e., outermost --- paragraph, because that is
914          * the only way to achieve consistency of the arrow's movements
915          * within a paragraph, and thus avoid situations in which the
916          * cursor gets stuck.
917          */
918         return bottom().paragraph().isRTL(bv().buffer().params());
919 }
920
921
922 CursorSlice Cursor::normalAnchor() const
923 {
924         if (!selection())
925                 return top();
926         // LASSERT: There have been several bugs around this code, that seem
927         // to involve failures to reset the anchor. We can at least not crash
928         // in release mode by resetting it ourselves.
929         if (anchor_.depth() < depth()) {
930                 LYXERR0("Cursor is deeper than anchor. PLEASE REPORT.\nCursor is"
931                         << *this);
932                 const_cast<DocIterator &>(anchor_) = *this;
933         }
934
935         CursorSlice normal = anchor_[depth() - 1];
936         if (depth() < anchor_.depth() && top() <= normal) {
937                 // anchor is behind cursor -> move anchor behind the inset
938                 ++normal.pos();
939         }
940         return normal;
941 }
942
943
944 CursorSlice Cursor::selBegin() const
945 {
946         if (!selection())
947                 return top();
948         return normalAnchor() < top() ? normalAnchor() : top();
949 }
950
951
952 CursorSlice Cursor::selEnd() const
953 {
954         if (!selection())
955                 return top();
956         return normalAnchor() > top() ? normalAnchor() : top();
957 }
958
959
960 DocIterator Cursor::selectionBegin() const
961 {
962         if (!selection())
963                 return *this;
964
965         DocIterator di;
966         // FIXME: This is a work-around for the problem that
967         // CursorSlice doesn't keep track of the boundary.
968         if (normalAnchor() == top())
969                 di = anchor_.boundary() > boundary() ? anchor_ : *this;
970         else
971                 di = normalAnchor() < top() ? anchor_ : *this;
972         di.resize(depth());
973         return di;
974 }
975
976
977 DocIterator Cursor::selectionEnd() const
978 {
979         if (!selection())
980                 return *this;
981
982         DocIterator di;
983         // FIXME: This is a work-around for the problem that
984         // CursorSlice doesn't keep track of the boundary.
985         if (normalAnchor() == top())
986                 di = anchor_.boundary() < boundary() ? anchor_ : *this;
987         else
988                 di = normalAnchor() > top() ? anchor_ : *this;
989
990         if (di.depth() > depth()) {
991                 di.resize(depth());
992                 ++di.pos();
993         }
994         return di;
995 }
996
997
998 void Cursor::setSelection()
999 {
1000         selection(true);
1001         if (idx() == normalAnchor().idx() &&
1002             pit() == normalAnchor().pit() &&
1003             pos() == normalAnchor().pos())
1004                 selection(false);
1005 }
1006
1007
1008 void Cursor::setSelection(DocIterator const & where, int n)
1009 {
1010         setCursor(where);
1011         selection(true);
1012         anchor_ = where;
1013         pos() += n;
1014 }
1015
1016
1017 void Cursor::clearSelection()
1018 {
1019         selection(false);
1020         setWordSelection(false);
1021         setMark(false);
1022         resetAnchor();
1023 }
1024
1025
1026 void Cursor::setTargetX(int x)
1027 {
1028         x_target_ = x;
1029         textTargetOffset_ = 0;
1030 }
1031
1032
1033 int Cursor::x_target() const
1034 {
1035         return x_target_;
1036 }
1037
1038
1039 void Cursor::clearTargetX()
1040 {
1041         x_target_ = -1;
1042         textTargetOffset_ = 0;
1043 }
1044
1045
1046 void Cursor::updateTextTargetOffset()
1047 {
1048         int x;
1049         int y;
1050         getPos(x, y);
1051         textTargetOffset_ = x - x_target_;
1052 }
1053
1054
1055 void Cursor::info(odocstream & os) const
1056 {
1057         for (int i = 1, n = depth(); i < n; ++i) {
1058                 operator[](i).inset().infoize(os);
1059                 os << "  ";
1060         }
1061         if (pos() != 0) {
1062                 Inset const * inset = prevInset();
1063                 // prevInset() can return 0 in certain case.
1064                 if (inset)
1065                         prevInset()->infoize2(os);
1066         }
1067 }
1068
1069
1070 bool Cursor::selHandle(bool sel)
1071 {
1072         //lyxerr << "Cursor::selHandle" << endl;
1073         if (mark())
1074                 sel = true;
1075         if (sel == selection())
1076                 return false;
1077
1078         if (!sel)
1079                 cap::saveSelection(*this);
1080
1081         resetAnchor();
1082         selection(sel);
1083         return true;
1084 }
1085 } // namespace lyx
1086
1087
1088 ///////////////////////////////////////////////////////////////////
1089 //
1090 // FIXME: Look here
1091 // The part below is the non-integrated rest of the original math
1092 // cursor. This should be either generalized for texted or moved
1093 // back to mathed (in most cases to InsetMathNest).
1094 //
1095 ///////////////////////////////////////////////////////////////////
1096
1097 #include "mathed/InsetMathChar.h"
1098 #include "mathed/InsetMathGrid.h"
1099 #include "mathed/InsetMathScript.h"
1100 #include "mathed/InsetMathUnknown.h"
1101 #include "mathed/MathFactory.h"
1102 #include "mathed/MathStream.h"
1103 #include "mathed/MathSupport.h"
1104
1105
1106 namespace lyx {
1107
1108 bool Cursor::isInside(Inset const * p) const
1109 {
1110         for (size_t i = 0; i != depth(); ++i)
1111                 if (&operator[](i).inset() == p)
1112                         return true;
1113         return false;
1114 }
1115
1116
1117 void Cursor::leaveInset(Inset const & inset)
1118 {
1119         for (size_t i = 0; i != depth(); ++i) {
1120                 if (&operator[](i).inset() == &inset) {
1121                         resize(i);
1122                         return;
1123                 }
1124         }
1125 }
1126
1127
1128 bool Cursor::openable(MathAtom const & t) const
1129 {
1130         if (!t->isActive())
1131                 return false;
1132
1133         if (t->lock())
1134                 return false;
1135
1136         if (!selection())
1137                 return true;
1138
1139         // we can't move into anything new during selection
1140         if (depth() >= anchor_.depth())
1141                 return false;
1142         if (t.nucleus() != &anchor_[depth()].inset())
1143                 return false;
1144
1145         return true;
1146 }
1147
1148
1149 void Cursor::setScreenPos(int x, int /*y*/)
1150 {
1151         setTargetX(x);
1152         //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1153 }
1154
1155
1156
1157 void Cursor::plainErase()
1158 {
1159         cell().erase(pos());
1160 }
1161
1162
1163 void Cursor::markInsert()
1164 {
1165         insert(char_type(0));
1166 }
1167
1168
1169 void Cursor::markErase()
1170 {
1171         cell().erase(pos());
1172 }
1173
1174
1175 void Cursor::plainInsert(MathAtom const & t)
1176 {
1177         cell().insert(pos(), t);
1178         ++pos();
1179         inset().setBuffer(bv_->buffer());
1180         inset().initView();
1181         checkBufferStructure();
1182 }
1183
1184
1185 void Cursor::insert(docstring const & str)
1186 {
1187         for_each(str.begin(), str.end(),
1188                  bind(static_cast<void(Cursor::*)(char_type)>
1189                              (&Cursor::insert), this, _1));
1190 }
1191
1192
1193 void Cursor::insert(char_type c)
1194 {
1195         //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1196         LASSERT(!empty(), return);
1197         if (inMathed()) {
1198                 cap::selClearOrDel(*this);
1199                 insert(new InsetMathChar(c));
1200         } else {
1201                 text()->insertChar(*this, c);
1202         }
1203 }
1204
1205
1206 void Cursor::insert(MathAtom const & t)
1207 {
1208         //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1209         macroModeClose();
1210         cap::selClearOrDel(*this);
1211         plainInsert(t);
1212 }
1213
1214
1215 void Cursor::insert(Inset * inset0)
1216 {
1217         LASSERT(inset0, return);
1218         if (inMathed())
1219                 insert(MathAtom(inset0->asInsetMath()));
1220         else {
1221                 text()->insertInset(*this, inset0);
1222                 inset0->setBuffer(bv_->buffer());
1223                 inset0->initView();
1224                 if (inset0->isLabeled())
1225                         forceBufferUpdate();
1226         }
1227 }
1228
1229
1230 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1231 {
1232         MathData ar(buffer());
1233         asArray(t, ar, f);
1234         if (ar.size() == 1 && (enter || selection()))
1235                 niceInsert(ar[0]);
1236         else
1237                 insert(ar);
1238         return ar.size();
1239 }
1240
1241
1242 void Cursor::niceInsert(MathAtom const & t)
1243 {
1244         macroModeClose();
1245         docstring const safe = cap::grabAndEraseSelection(*this);
1246         plainInsert(t);
1247         // If possible, enter the new inset and move the contents of the selection
1248         if (t->isActive()) {
1249                 posBackward();
1250                 // be careful here: don't use 'pushBackward(t)' as this we need to
1251                 // push the clone, not the original
1252                 pushBackward(*nextInset());
1253                 // We may not use niceInsert here (recursion)
1254                 MathData ar(buffer());
1255                 asArray(safe, ar);
1256                 insert(ar);
1257         } else if (t->asMacro() && !safe.empty()) {
1258                 MathData ar(buffer());
1259                 asArray(safe, ar);
1260                 docstring const name = t->asMacro()->name();
1261                 MacroData const * data = buffer()->getMacro(name);
1262                 if (data && data->numargs() - data->optionals() > 0) {
1263                         plainInsert(MathAtom(new InsetMathBrace(ar)));
1264                         posBackward();
1265                 }
1266         }
1267 }
1268
1269
1270 void Cursor::insert(MathData const & ar)
1271 {
1272         macroModeClose();
1273         if (selection())
1274                 cap::eraseSelection(*this);
1275         cell().insert(pos(), ar);
1276         pos() += ar.size();
1277         // FIXME audit setBuffer calls
1278         inset().setBuffer(bv_->buffer());
1279 }
1280
1281
1282 bool Cursor::backspace()
1283 {
1284         if (selection()) {
1285                 cap::eraseSelection(*this);
1286                 return true;
1287         }
1288
1289         if (pos() == 0) {
1290                 // If empty cell, and not part of a big cell
1291                 if (lastpos() == 0 && inset().nargs() == 1) {
1292                         popBackward();
1293                         // Directly delete empty cell: [|[]] => [|]
1294                         if (inMathed()) {
1295                                 plainErase();
1296                                 resetAnchor();
1297                                 return true;
1298                         }
1299                         // [|], can not delete from inside
1300                         return false;
1301                 } else {
1302                         if (inMathed())
1303                                 pullArg();
1304                         else
1305                                 popBackward();
1306                         return true;
1307                 }
1308         }
1309
1310         if (inMacroMode()) {
1311                 InsetMathUnknown * p = activeMacro();
1312                 if (p->name().size() > 1) {
1313                         p->setName(p->name().substr(0, p->name().size() - 1));
1314                         return true;
1315                 }
1316         }
1317
1318         if (pos() != 0 && prevAtom()->nargs() > 0) {
1319                 // let's require two backspaces for 'big stuff' and
1320                 // highlight on the first
1321                 resetAnchor();
1322                 selection(true);
1323                 --pos();
1324         } else {
1325                 --pos();
1326                 plainErase();
1327         }
1328         return true;
1329 }
1330
1331
1332 bool Cursor::erase()
1333 {
1334         if (inMacroMode())
1335                 return true;
1336
1337         if (selection()) {
1338                 cap::eraseSelection(*this);
1339                 return true;
1340         }
1341
1342         // delete empty cells if possible
1343         if (pos() == lastpos() && inset().idxDelete(idx()))
1344                 return true;
1345
1346         // special behaviour when in last position of cell
1347         if (pos() == lastpos()) {
1348                 bool one_cell = inset().nargs() == 1;
1349                 if (one_cell && lastpos() == 0) {
1350                         popBackward();
1351                         // Directly delete empty cell: [|[]] => [|]
1352                         if (inMathed()) {
1353                                 plainErase();
1354                                 resetAnchor();
1355                                 return true;
1356                         }
1357                         // [|], can not delete from inside
1358                         return false;
1359                 }
1360                 // remove markup
1361                 if (!one_cell)
1362                         inset().idxGlue(idx());
1363                 return true;
1364         }
1365
1366         // 'clever' UI hack: only erase large items if previously slected
1367         if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1368                 resetAnchor();
1369                 selection(true);
1370                 ++pos();
1371         } else {
1372                 plainErase();
1373         }
1374
1375         return true;
1376 }
1377
1378
1379 bool Cursor::up()
1380 {
1381         macroModeClose();
1382         DocIterator save = *this;
1383         FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1384         this->dispatch(cmd);
1385         if (disp_.dispatched())
1386                 return true;
1387         setCursor(save);
1388         return false;
1389 }
1390
1391
1392 bool Cursor::down()
1393 {
1394         macroModeClose();
1395         DocIterator save = *this;
1396         FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1397         this->dispatch(cmd);
1398         if (disp_.dispatched())
1399                 return true;
1400         setCursor(save);
1401         return false;
1402 }
1403
1404
1405 bool Cursor::macroModeClose()
1406 {
1407         if (!inMacroMode())
1408                 return false;
1409         InsetMathUnknown * p = activeMacro();
1410         p->finalize();
1411         MathData selection(buffer());
1412         asArray(p->selection(), selection);
1413         docstring const s = p->name();
1414         --pos();
1415         cell().erase(pos());
1416
1417         // do nothing if the macro name is empty
1418         if (s == "\\")
1419                 return false;
1420
1421         // trigger updates of macros, at least, if no full
1422         // updates take place anyway
1423         screenUpdateFlags(Update::Force);
1424
1425         docstring const name = s.substr(1);
1426         InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1427         if (in && in->interpretString(*this, s))
1428                 return true;
1429         MathAtom atom = buffer()->getMacro(name, *this, false) ?
1430                 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1431
1432         // try to put argument into macro, if we just inserted a macro
1433         bool macroArg = false;
1434         MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1435         if (atomAsMacro) {
1436                 // macros here are still unfolded (in init mode in fact). So
1437                 // we have to resolve the macro here manually and check its arity
1438                 // to put the selection behind it if arity > 0.
1439                 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1440                 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1441                         macroArg = true;
1442                         atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1443                 } else
1444                         // non-greedy case. Do not touch the arguments behind
1445                         atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1446         }
1447
1448         // insert remembered selection into first argument of a non-macro
1449         else if (atom.nucleus()->nargs() > 0)
1450                 atom.nucleus()->cell(0).append(selection);
1451
1452         plainInsert(atom);
1453
1454         // finally put the macro argument behind, if needed
1455         if (macroArg) {
1456                 if (selection.size() > 1 || selection[0]->asScriptInset())
1457                         plainInsert(MathAtom(new InsetMathBrace(selection)));
1458                 else
1459                         insert(selection);
1460         }
1461
1462         return true;
1463 }
1464
1465
1466 docstring Cursor::macroName()
1467 {
1468         return inMacroMode() ? activeMacro()->name() : docstring();
1469 }
1470
1471
1472 void Cursor::handleNest(MathAtom const & a, int c)
1473 {
1474         //lyxerr << "Cursor::handleNest: " << c << endl;
1475         MathAtom t = a;
1476         asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1477         insert(t);
1478         posBackward();
1479         pushBackward(*nextInset());
1480 }
1481
1482
1483 int Cursor::targetX() const
1484 {
1485         if (x_target() != -1)
1486                 return x_target();
1487         int x = 0;
1488         int y = 0;
1489         getPos(x, y);
1490         return x;
1491 }
1492
1493
1494 int Cursor::textTargetOffset() const
1495 {
1496         return textTargetOffset_;
1497 }
1498
1499
1500 void Cursor::setTargetX()
1501 {
1502         int x;
1503         int y;
1504         getPos(x, y);
1505         setTargetX(x);
1506 }
1507
1508
1509 bool Cursor::inMacroMode() const
1510 {
1511         if (!inMathed())
1512                 return false;
1513         if (pos() == 0 || cell().empty())
1514                 return false;
1515         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1516         return p && !p->final();
1517 }
1518
1519
1520 InsetMathUnknown * Cursor::activeMacro()
1521 {
1522         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1523 }
1524
1525
1526 InsetMathUnknown const * Cursor::activeMacro() const
1527 {
1528         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1529 }
1530
1531
1532 void Cursor::pullArg()
1533 {
1534         // FIXME: Look here
1535         MathData ar = cell();
1536         if (popBackward() && inMathed()) {
1537                 plainErase();
1538                 cell().insert(pos(), ar);
1539                 resetAnchor();
1540         } else {
1541                 //formula()->mutateToText();
1542         }
1543 }
1544
1545
1546 void Cursor::touch()
1547 {
1548         // FIXME: look here
1549 #if 0
1550         DocIterator::const_iterator it = begin();
1551         DocIterator::const_iterator et = end();
1552         for ( ; it != et; ++it)
1553                 it->cell().touch();
1554 #endif
1555 }
1556
1557
1558 void Cursor::normalize()
1559 {
1560         if (idx() > lastidx()) {
1561                 lyxerr << "this should not really happen - 1: "
1562                        << idx() << ' ' << nargs()
1563                        << " in: " << &inset() << endl;
1564                 idx() = lastidx();
1565         }
1566
1567         if (pos() > lastpos()) {
1568                 lyxerr << "this should not really happen - 2: "
1569                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1570                        << " in atom: '";
1571                 odocstringstream os;
1572                 TexRow texrow(false);
1573                 otexrowstream ots(os,texrow);
1574                 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1575                 inset().asInsetMath()->write(wi);
1576                 lyxerr << to_utf8(os.str()) << endl;
1577                 pos() = lastpos();
1578         }
1579 }
1580
1581
1582 bool Cursor::upDownInMath(bool up)
1583 {
1584         // Be warned: The 'logic' implemented in this function is highly
1585         // fragile. A distance of one pixel or a '<' vs '<=' _really
1586         // matters. So fiddle around with it only if you think you know
1587         // what you are doing!
1588         int xo = 0;
1589         int yo = 0;
1590         getPos(xo, yo);
1591         xo = beforeDispatchPosX_;
1592
1593         // check if we had something else in mind, if not, this is the future
1594         // target
1595         if (x_target_ == -1)
1596                 setTargetX(xo);
1597         else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1598                 // In text mode inside the line (not left or right) possibly set a new target_x,
1599                 // but only if we are somewhere else than the previous target-offset.
1600
1601                 // We want to keep the x-target on subsequent up/down movements
1602                 // that cross beyond the end of short lines. Thus a special
1603                 // handling when the cursor is at the end of line: Use the new
1604                 // x-target only if the old one was before the end of line
1605                 // or the old one was after the beginning of the line
1606                 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1607                 bool left;
1608                 bool right;
1609                 if (inRTL) {
1610                         left = pos() == textRow().endpos();
1611                         right = pos() == textRow().pos();
1612                 } else {
1613                         left = pos() == textRow().pos();
1614                         right = pos() == textRow().endpos();
1615                 }
1616                 if ((!left && !right) ||
1617                                 (left && !right && xo < x_target_) ||
1618                                 (!left && right && x_target_ < xo))
1619                         setTargetX(xo);
1620                 else
1621                         xo = targetX();
1622         } else
1623                 xo = targetX();
1624
1625         // try neigbouring script insets
1626         Cursor old = *this;
1627         if (inMathed() && !selection()) {
1628                 // try left
1629                 if (pos() != 0) {
1630                         InsetMathScript const * p = prevAtom()->asScriptInset();
1631                         if (p && p->has(up)) {
1632                                 --pos();
1633                                 push(*const_cast<InsetMathScript*>(p));
1634                                 idx() = p->idxOfScript(up);
1635                                 pos() = lastpos();
1636
1637                                 // we went in the right direction? Otherwise don't jump into the script
1638                                 int x;
1639                                 int y;
1640                                 getPos(x, y);
1641                                 int oy = beforeDispatchPosY_;
1642                                 if ((!up && y <= oy) ||
1643                                                 (up && y >= oy))
1644                                         operator=(old);
1645                                 else
1646                                         return true;
1647                         }
1648                 }
1649
1650                 // try right
1651                 if (pos() != lastpos()) {
1652                         InsetMathScript const * p = nextAtom()->asScriptInset();
1653                         if (p && p->has(up)) {
1654                                 push(*const_cast<InsetMathScript*>(p));
1655                                 idx() = p->idxOfScript(up);
1656                                 pos() = 0;
1657
1658                                 // we went in the right direction? Otherwise don't jump into the script
1659                                 int x;
1660                                 int y;
1661                                 getPos(x, y);
1662                                 int oy = beforeDispatchPosY_;
1663                                 if ((!up && y <= oy) ||
1664                                                 (up && y >= oy))
1665                                         operator=(old);
1666                                 else
1667                                         return true;
1668                         }
1669                 }
1670         }
1671
1672         // try to find an inset that knows better then we,
1673         if (inset().idxUpDown(*this, up)) {
1674                 //lyxerr << "idxUpDown triggered" << endl;
1675                 // try to find best position within this inset
1676                 if (!selection())
1677                         setCursor(bruteFind(*this, xo, yo));
1678                 return true;
1679         }
1680
1681         // any improvement going just out of inset?
1682         if (popBackward() && inMathed()) {
1683                 //lyxerr << "updown: popBackward succeeded" << endl;
1684                 int xnew;
1685                 int ynew;
1686                 int yold = beforeDispatchPosY_;
1687                 getPos(xnew, ynew);
1688                 if (up ? ynew < yold : ynew > yold)
1689                         return true;
1690         }
1691
1692         // no success, we are probably at the document top or bottom
1693         operator=(old);
1694         return false;
1695 }
1696
1697
1698 bool Cursor::atFirstOrLastRow(bool up)
1699 {
1700         TextMetrics const & tm = bv_->textMetrics(text());
1701         ParagraphMetrics const & pm = tm.parMetrics(pit());
1702
1703         int row;
1704         if (pos() && boundary())
1705                 row = pm.pos2row(pos() - 1);
1706         else
1707                 row = pm.pos2row(pos());
1708
1709         if (up) {
1710                 if (pit() == 0 && row == 0)
1711                         return true;
1712         } else {
1713                 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1714                                 row + 1 >= int(pm.rows().size()))
1715                         return true;
1716         }
1717         return false;
1718 }
1719
1720
1721 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1722 {
1723         LASSERT(text(), return false);
1724
1725         // where are we?
1726         int xo = 0;
1727         int yo = 0;
1728         getPos(xo, yo);
1729         xo = beforeDispatchPosX_;
1730
1731         // update the targetX - this is here before the "return false"
1732         // to set a new target which can be used by InsetTexts above
1733         // if we cannot move up/down inside this inset anymore
1734         if (x_target_ == -1)
1735                 setTargetX(xo);
1736         else if (xo - textTargetOffset() != x_target() &&
1737                                          depth() == beforeDispatchCursor_.depth()) {
1738                 // In text mode inside the line (not left or right)
1739                 // possibly set a new target_x, but only if we are
1740                 // somewhere else than the previous target-offset.
1741
1742                 // We want to keep the x-target on subsequent up/down
1743                 // movements that cross beyond the end of short lines.
1744                 // Thus a special handling when the cursor is at the
1745                 // end of line: Use the new x-target only if the old
1746                 // one was before the end of line or the old one was
1747                 // after the beginning of the line
1748                 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1749                 bool left;
1750                 bool right;
1751                 if (inRTL) {
1752                         left = pos() == textRow().endpos();
1753                         right = pos() == textRow().pos();
1754                 } else {
1755                         left = pos() == textRow().pos();
1756                         right = pos() == textRow().endpos();
1757                 }
1758                 if ((!left && !right) ||
1759                                 (left && !right && xo < x_target_) ||
1760                                 (!left && right && x_target_ < xo))
1761                         setTargetX(xo);
1762                 else
1763                         xo = targetX();
1764         } else
1765                 xo = targetX();
1766
1767         // first get the current line
1768         TextMetrics & tm = bv_->textMetrics(text());
1769         ParagraphMetrics const & pm = tm.parMetrics(pit());
1770         int row;
1771         if (pos() && boundary())
1772                 row = pm.pos2row(pos() - 1);
1773         else
1774                 row = pm.pos2row(pos());
1775
1776         if (atFirstOrLastRow(up)) {
1777                 // Is there a place for the cursor to go ? If yes, we
1778                 // can execute the DEPM, otherwise we should keep the
1779                 // paragraph to host the cursor.
1780                 Cursor dummy = *this;
1781                 bool valid_destination = false;
1782                 for(; dummy.depth(); dummy.pop())
1783                         if (!dummy.atFirstOrLastRow(up)) {
1784                                 valid_destination = true;
1785                                 break;
1786                         }
1787
1788                 // will a next dispatch follow and if there is a new
1789                 // dispatch will it move the cursor out ?
1790                 if (depth() > 1 && valid_destination) {
1791                         // The cursor hasn't changed yet. This happens when
1792                         // you e.g. move out of an inset. And to give the
1793                         // DEPM the possibility of doing something we must
1794                         // provide it with two different cursors. (Lgb, vfr)
1795                         dummy = *this;
1796                         dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
1797                         dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
1798
1799                         updateNeeded |= bv().checkDepm(dummy, *this);
1800                         updateTextTargetOffset();
1801                         if (updateNeeded)
1802                                 forceBufferUpdate();
1803                 }
1804                 return false;
1805         }
1806
1807         // with and without selection are handled differently
1808         if (!selection()) {
1809                 int yo = bv().getPos(*this).y_;
1810                 Cursor old = *this;
1811                 // To next/previous row
1812                 if (up)
1813                         tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1814                 else
1815                         tm.editXY(*this, xo, yo + textRow().descent() + 1);
1816                 clearSelection();
1817
1818                 // This happens when you move out of an inset.
1819                 // And to give the DEPM the possibility of doing
1820                 // something we must provide it with two different
1821                 // cursors. (Lgb)
1822                 Cursor dummy = *this;
1823                 if (dummy == old)
1824                         ++dummy.pos();
1825                 if (bv().checkDepm(dummy, old)) {
1826                         updateNeeded = true;
1827                         // Make sure that cur gets back whatever happened to dummy (Lgb)
1828                         operator=(dummy);
1829                 }
1830                 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
1831                         posBackward();
1832         } else {
1833                 // if there is a selection, we stay out of any inset,
1834                 // and just jump to the right position:
1835                 Cursor old = *this;
1836                 int next_row = row;
1837                 if (up) {
1838                         if (row > 0) {
1839                                 --next_row;
1840                         } else if (pit() > 0) {
1841                                 --pit();
1842                                 TextMetrics & tm = bv_->textMetrics(text());
1843                                 if (!tm.contains(pit()))
1844                                         tm.newParMetricsUp();
1845                                 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
1846                                 next_row = pmcur.rows().size() - 1;
1847                         }
1848                 } else {
1849                         if (row + 1 < int(pm.rows().size())) {
1850                                 ++next_row;
1851                         } else if (pit() + 1 < int(text()->paragraphs().size())) {
1852                                 ++pit();
1853                                 TextMetrics & tm = bv_->textMetrics(text());
1854                                 if (!tm.contains(pit()))
1855                                         tm.newParMetricsDown();
1856                                 next_row = 0;
1857                         }
1858                 }
1859
1860                 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
1861                 bool bound = false;
1862                 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
1863                 boundary(bound);
1864
1865                 updateNeeded |= bv().checkDepm(*this, old);
1866         }
1867
1868         if (updateNeeded)
1869                 forceBufferUpdate();
1870         updateTextTargetOffset();
1871         return true;
1872 }
1873
1874
1875 void Cursor::handleFont(string const & font)
1876 {
1877         LYXERR(Debug::DEBUG, font);
1878         docstring safe;
1879         if (selection()) {
1880                 macroModeClose();
1881                 safe = cap::grabAndEraseSelection(*this);
1882         }
1883
1884         recordUndoInset();
1885
1886         if (lastpos() != 0) {
1887                 // something left in the cell
1888                 if (pos() == 0) {
1889                         // cursor in first position
1890                         popBackward();
1891                 } else if (pos() == lastpos()) {
1892                         // cursor in last position
1893                         popForward();
1894                 } else {
1895                         // cursor in between. split cell
1896                         MathData::iterator bt = cell().begin();
1897                         MathAtom at = createInsetMath(from_utf8(font), buffer());
1898                         at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
1899                         cell().erase(bt, bt + pos());
1900                         popBackward();
1901                         plainInsert(at);
1902                 }
1903         } else {
1904                 // nothing left in the cell
1905                 popBackward();
1906                 plainErase();
1907                 resetAnchor();
1908         }
1909         insert(safe);
1910 }
1911
1912
1913 void Cursor::message(docstring const & msg) const
1914 {
1915         disp_.setMessage(msg);
1916 }
1917
1918
1919 void Cursor::errorMessage(docstring const & msg) const
1920 {
1921         disp_.setMessage(msg);
1922         disp_.setError(true);
1923 }
1924
1925
1926 namespace {
1927
1928 docstring parbreak(Cursor const * cur)
1929 {
1930         odocstringstream os;
1931         os << '\n';
1932         // only add blank line if we're not in a ParbreakIsNewline situation
1933         if (!cur->inset().getLayout().parbreakIsNewline()
1934             && !cur->paragraph().layout().parbreak_is_newline)
1935                 os << '\n';
1936         return os.str();
1937 }
1938
1939 }
1940
1941
1942 docstring Cursor::selectionAsString(bool with_label) const
1943 {
1944         if (!selection())
1945                 return docstring();
1946
1947         if (inMathed())
1948                 return cap::grabSelection(*this);
1949
1950         int const label = with_label
1951                 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
1952
1953         idx_type const startidx = selBegin().idx();
1954         idx_type const endidx = selEnd().idx();
1955         if (startidx != endidx) {
1956                 // multicell selection
1957                 InsetTabular * table = inset().asInsetTabular();
1958                 LASSERT(table, return docstring());
1959                 return table->asString(startidx, endidx);
1960         }
1961
1962         ParagraphList const & pars = text()->paragraphs();
1963
1964         pit_type const startpit = selBegin().pit();
1965         pit_type const endpit = selEnd().pit();
1966         size_t const startpos = selBegin().pos();
1967         size_t const endpos = selEnd().pos();
1968
1969         if (startpit == endpit)
1970                 return pars[startpit].asString(startpos, endpos, label);
1971
1972         // First paragraph in selection
1973         docstring result = pars[startpit].
1974                 asString(startpos, pars[startpit].size(), label)
1975                 + parbreak(this);
1976
1977         // The paragraphs in between (if any)
1978         for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1979                 Paragraph const & par = pars[pit];
1980                 result += par.asString(0, par.size(), label)
1981                         + parbreak(this);
1982         }
1983
1984         // Last paragraph in selection
1985         result += pars[endpit].asString(0, endpos, label);
1986
1987         return result;
1988 }
1989
1990
1991 docstring Cursor::currentState() const
1992 {
1993         if (inMathed()) {
1994                 odocstringstream os;
1995                 info(os);
1996 #ifdef DEVEL_VERSION
1997                 InsetMath * math = inset().asInsetMath();
1998                 if (math)
1999                         os << _(", Inset: ") << math->id();
2000                 os << _(", Cell: ") << idx();
2001                 os << _(", Position: ") << pos();
2002 #endif
2003                 return os.str();
2004         }
2005
2006         if (inTexted())
2007                 return text()->currentState(*this);
2008
2009         return docstring();
2010 }
2011
2012
2013 docstring Cursor::getPossibleLabel() const
2014 {
2015         return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2016 }
2017
2018
2019 Encoding const * Cursor::getEncoding() const
2020 {
2021         if (empty())
2022                 return 0;
2023         CursorSlice const & sl = innerTextSlice();
2024         Text const & text = *sl.text();
2025         Font font = text.getPar(sl.pit()).getFont(
2026                 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2027         return font.language()->encoding();
2028 }
2029
2030
2031 void Cursor::undispatched() const
2032 {
2033         disp_.dispatched(false);
2034 }
2035
2036
2037 void Cursor::dispatched() const
2038 {
2039         disp_.dispatched(true);
2040 }
2041
2042
2043 void Cursor::screenUpdateFlags(Update::flags f) const
2044 {
2045         disp_.screenUpdate(f);
2046 }
2047
2048
2049 void Cursor::forceBufferUpdate() const
2050 {
2051         disp_.forceBufferUpdate();
2052 }
2053
2054
2055 void Cursor::clearBufferUpdate() const
2056 {
2057         disp_.clearBufferUpdate();
2058 }
2059
2060
2061 bool Cursor::needBufferUpdate() const
2062 {
2063         return disp_.needBufferUpdate();
2064 }
2065
2066
2067 void Cursor::noScreenUpdate() const
2068 {
2069         disp_.screenUpdate(Update::None);
2070 }
2071
2072
2073 Font Cursor::getFont() const
2074 {
2075         // The logic here should more or less match to the
2076         // Cursor::setCurrentFont logic, i.e. the cursor height should
2077         // give a hint what will happen if a character is entered.
2078
2079         // HACK. far from being perfect...
2080
2081         CursorSlice const & sl = innerTextSlice();
2082         Text const & text = *sl.text();
2083         Paragraph const & par = text.getPar(sl.pit());
2084
2085         // on boundary, so we are really at the character before
2086         pos_type pos = sl.pos();
2087         if (pos > 0 && boundary())
2088                 --pos;
2089
2090         // on space? Take the font before (only for RTL boundary stay)
2091         if (pos > 0) {
2092                 TextMetrics const & tm = bv().textMetrics(&text);
2093                 if (pos == sl.lastpos()
2094                         || (par.isSeparator(pos)
2095                         && !tm.isRTLBoundary(sl.pit(), pos)))
2096                         --pos;
2097         }
2098
2099         // get font at the position
2100         Font font = par.getFont(buffer()->params(), pos,
2101                 text.outerFont(sl.pit()));
2102
2103         return font;
2104 }
2105
2106
2107 bool Cursor::fixIfBroken()
2108 {
2109         bool const broken_cursor = DocIterator::fixIfBroken();
2110         bool const broken_anchor = anchor_.fixIfBroken();
2111
2112         if (broken_cursor || broken_anchor) {
2113                 clearNewWordPosition();
2114                 clearSelection();
2115                 return true;
2116         }
2117         return false;
2118 }
2119
2120
2121 void Cursor::sanitize()
2122 {
2123         setBuffer(&bv_->buffer());
2124         DocIterator::sanitize();
2125         if (selection())
2126                 anchor_.sanitize();
2127         else
2128                 resetAnchor();
2129 }
2130
2131
2132 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2133 {
2134         // find inset in common
2135         size_type i;
2136         for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2137                 if (&old[i].inset() != &cur[i].inset())
2138                         break;
2139         }
2140
2141         // update words if we just moved to another paragraph
2142         if (i == old.depth() && i == cur.depth()
2143             && !cur.buffer()->isClean()
2144             && cur.inTexted() && old.inTexted()
2145             && cur.pit() != old.pit()) {
2146                 old.paragraph().updateWords();
2147         }
2148
2149         // notify everything on top of the common part in old cursor,
2150         // but stop if the inset claims the cursor to be invalid now
2151         for (size_type j = i; j < old.depth(); ++j) {
2152                 Cursor inset_pos = old;
2153                 inset_pos.cutOff(j);
2154                 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2155                         return true;
2156         }
2157
2158         // notify everything on top of the common part in new cursor,
2159         // but stop if the inset claims the cursor to be invalid now
2160         for (; i < cur.depth(); ++i) {
2161                 if (cur[i].inset().notifyCursorEnters(cur))
2162                         return true;
2163         }
2164
2165         return false;
2166 }
2167
2168
2169 void Cursor::setCurrentFont()
2170 {
2171         CursorSlice const & cs = innerTextSlice();
2172         Paragraph const & par = cs.paragraph();
2173         pos_type cpit = cs.pit();
2174         pos_type cpos = cs.pos();
2175         Text const & ctext = *cs.text();
2176         TextMetrics const & tm = bv().textMetrics(&ctext);
2177
2178         // are we behind previous char in fact? -> go to that char
2179         if (cpos > 0 && boundary())
2180                 --cpos;
2181
2182         // find position to take the font from
2183         if (cpos != 0) {
2184                 // paragraph end? -> font of last char
2185                 if (cpos == lastpos())
2186                         --cpos;
2187                 // on space? -> look at the words in front of space
2188                 else if (cpos > 0 && par.isSeparator(cpos))     {
2189                         // abc| def -> font of c
2190                         // abc |[WERBEH], i.e. boundary==true -> font of c
2191                         // abc [WERBEH]| def, font of the space
2192                         if (!tm.isRTLBoundary(cpit, cpos))
2193                                 --cpos;
2194                 }
2195         }
2196
2197         // get font
2198         BufferParams const & bufparams = buffer()->params();
2199         current_font = par.getFontSettings(bufparams, cpos);
2200         real_current_font = tm.displayFont(cpit, cpos);
2201
2202         // special case for paragraph end
2203         if (cs.pos() == lastpos()
2204             && tm.isRTLBoundary(cpit, cs.pos())
2205             && !boundary()) {
2206                 Language const * lang = par.getParLanguage(bufparams);
2207                 current_font.setLanguage(lang);
2208                 current_font.fontInfo().setNumber(FONT_OFF);
2209                 real_current_font.setLanguage(lang);
2210                 real_current_font.fontInfo().setNumber(FONT_OFF);
2211         }
2212 }
2213
2214
2215 bool Cursor::textUndo()
2216 {
2217         if (!buffer()->undo().textUndo(*this))
2218                 return false;
2219         sanitize();
2220         return true;
2221 }
2222
2223
2224 bool Cursor::textRedo()
2225 {
2226         if (!buffer()->undo().textRedo(*this))
2227                 return false;
2228         sanitize();
2229         return true;
2230 }
2231
2232
2233 void Cursor::finishUndo() const
2234 {
2235         buffer()->undo().finishUndo();
2236 }
2237
2238
2239 void Cursor::beginUndoGroup() const
2240 {
2241         buffer()->undo().beginUndoGroup(*this);
2242 }
2243
2244
2245 void Cursor::endUndoGroup() const
2246 {
2247         buffer()->undo().endUndoGroup(*this);
2248 }
2249
2250
2251 void Cursor::recordUndo(pit_type from, pit_type to) const
2252 {
2253         buffer()->undo().recordUndo(*this, from, to);
2254 }
2255
2256
2257 void Cursor::recordUndo(pit_type from) const
2258 {
2259         buffer()->undo().recordUndo(*this, from, pit());
2260 }
2261
2262
2263 void Cursor::recordUndo(UndoKind kind) const
2264 {
2265         buffer()->undo().recordUndo(*this, kind);
2266 }
2267
2268
2269 void Cursor::recordUndoInset(Inset const * in) const
2270 {
2271         buffer()->undo().recordUndoInset(*this, in);
2272 }
2273
2274
2275 void Cursor::recordUndoFullBuffer() const
2276 {
2277         buffer()->undo().recordUndoFullBuffer(*this);
2278 }
2279
2280
2281 void Cursor::recordUndoBufferParams() const
2282 {
2283         buffer()->undo().recordUndoBufferParams(*this);
2284 }
2285
2286
2287 void Cursor::recordUndoSelection() const
2288 {
2289         if (inMathed()) {
2290                 if (cap::multipleCellsSelected(*this))
2291                         recordUndoInset();
2292                 else
2293                         recordUndo();
2294         } else {
2295                 buffer()->undo().recordUndo(*this,
2296                         selBegin().pit(), selEnd().pit());
2297         }
2298 }
2299
2300
2301 void Cursor::checkBufferStructure()
2302 {
2303         Buffer const * master = buffer()->masterBuffer();
2304         master->tocBackend().updateItem(*this);
2305         if (master != buffer() && !master->hasGuiDelegate())
2306                 // In case the master has no gui associated with it,
2307                 // the TocItem is not updated (part of bug 5699).
2308                 buffer()->tocBackend().updateItem(*this);
2309
2310         // If the last tracked change of the paragraph has just been
2311         // deleted, then we need to recompute the buffer flag
2312         // tracked_changes_present_.
2313         if (inTexted() && paragraph().isChangeUpdateRequired())
2314                 disp_.forceChangesUpdate();
2315 }
2316
2317
2318 } // namespace lyx