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