]> git.lyx.org Git - lyx.git/blob - src/Cursor.cpp
Use ASCII number in \char definition
[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         double dummy = 0;
789         Row::const_iterator cit = row.findElement(pos(), boundary(), dummy);
790         // Handle the case of empty row
791         if (cit == row.end()) {
792                 if (row.isRTL())
793                         right_pos = row.pos();
794                 else
795                         left_pos = row.pos() - 1;
796                 return;
797         }
798
799         // skip virtual elements and exit if no non-virtual one exists
800         if (!findNonVirtual(row, cit, !cit->isRTL()))
801                 return;
802
803         // if the position is at the left side of the element, we have to
804         // look at the previous element
805         if (pos() == cit->left_pos()) {
806                 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
807                            << "), AT LEFT of *cit=" << *cit);
808                 // this one is easy (see common case below)
809                 right_pos = pos() - (cit->isRTL() ? 1 : 0);
810                 // at the left of the row
811                 if (cit == row.begin())
812                         return;
813                 --cit;
814                 if (!findNonVirtual(row, cit, true))
815                         return;
816                 // [...[ is the row element, | is cursor position (! with boundary)
817                 // [ 1 2 [ is a ltr row element with pos=1 and endpos=3
818                 // ] 2 1] is an rtl row element with pos=1 and endpos=3
819                 //    [ 1 2 [  [|3 4 [ => (2, 3)
820                 // or [ 1 2 [  ]!4 3 ] => (2, 4)
821                 // or ] 2 1 ]  [|3 4 [ => (1, 3)
822                 // or ] 4 3 ]  ]!2 1 ] => (3, 2)
823                 left_pos = cit->right_pos() - (cit->isRTL() ? 0 : 1);
824                 // happens with consecutive row of same direction
825                 if (left_pos == right_pos) {
826                         left_pos += cit->isRTL() ? 1 : -1;
827                 }
828         }
829         // same code but with the element at the right
830         else if (pos() == cit->right_pos()) {
831                 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
832                            << "), AT RIGHT of *cit=" << *cit);
833                 // this one is easy (see common case below)
834                 left_pos = pos() - (cit->isRTL() ? 0 : 1);
835                 // at the right of the row
836                 if (cit + 1 == row.end())
837                         return;
838                 ++cit;
839                 if (!findNonVirtual(row, cit, false))
840                         return;
841                 //    [ 1 2![  [ 3 4 [ => (2, 3)
842                 // or [ 1 2![  ] 4 3 ] => (2, 4)
843                 // or ] 2 1|]  [ 3 4 [ => (1, 3)
844                 // or ] 4 3|]  ] 2 1 ] => (3, 2)
845                 right_pos = cit->left_pos() - (cit->isRTL() ? 1 : 0);
846                 // happens with consecutive row of same direction
847                 if (right_pos == left_pos)
848                         right_pos += cit->isRTL() ? -1 : 1;
849         }
850         // common case: both positions are inside the row element
851         else {
852                 //    [ 1 2|3 [ => (2, 3)
853                 // or ] 3|2 1 ] => (3, 2)
854                 left_pos = pos() - (cit->isRTL() ? 0 : 1);
855                 right_pos = pos() - (cit->isRTL() ? 1 : 0);
856         }
857
858         // Note that debug message does not catch all early returns above
859         LYXERR(Debug::RTL,"getSurroundingPos(" << pos() << (boundary() ? "b" : "")
860                    << ") => (" << left_pos << ", " << right_pos <<")");
861 }
862
863
864 bool Cursor::posVisToNewRow(bool movingLeft)
865 {
866         Row const & row = textRow();
867         bool par_is_LTR = !row.isRTL();
868
869         // Inside a table, determining whether to move to the next or
870         // previous row should be done based on the table's direction.
871         if (inset().asInsetTabular()) {
872                 par_is_LTR = !inset().asInsetTabular()->isRightToLeft(*this);
873                 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
874         }
875
876         // if moving left in an LTR paragraph or moving right in an
877         // RTL one, move to previous row
878         if (par_is_LTR == movingLeft) {
879                 if (row.pos() == 0) { // we're at first row in paragraph
880                         if (pit() == 0) // no previous paragraph! don't move
881                                 return false;
882                         // move to last pos in previous par
883                         --pit();
884                         pos() = lastpos();
885                         boundary(false);
886                 } else { // move to previous row in this par
887                         pos() = row.pos() - 1; // this is guaranteed to be in previous row
888                         boundary(false);
889                 }
890         }
891         // if moving left in an RTL paragraph or moving right in an
892         // LTR one, move to next row
893         else {
894                 if (row.endpos() == lastpos()) { // we're at last row in paragraph
895                         if (pit() == lastpit()) // last paragraph! don't move
896                                 return false;
897                         // move to first row in next par
898                         ++pit();
899                         pos() = 0;
900                         boundary(false);
901                 } else { // move to next row in this par
902                         pos() = row.endpos();
903                         boundary(false);
904                 }
905         }
906
907         // make sure we're at left-/right-most pos in new row
908         posVisToRowExtremity(!movingLeft);
909
910         return true;
911 }
912
913
914 void Cursor::posVisToRowExtremity(bool left)
915 {
916         LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
917                 << (boundary() ? 1 : 0));
918
919         TextMetrics const & tm = bv_->textMetrics(text());
920         // Looking for extremities is like clicking on the left or the
921         // right of the row.
922         int x = tm.origin().x_ + (left ? 0 : textRow().width());
923         bool b = false;
924         pos() = tm.getPosNearX(textRow(), x, b);
925         boundary(b);
926
927         LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
928                 << (boundary() ? 1 : 0));
929 }
930
931
932 bool Cursor::reverseDirectionNeeded() const
933 {
934         /*
935          * We determine the directions based on the direction of the
936          * bottom() --- i.e., outermost --- paragraph, because that is
937          * the only way to achieve consistency of the arrow's movements
938          * within a paragraph, and thus avoid situations in which the
939          * cursor gets stuck.
940          */
941         return bottom().paragraph().isRTL(bv().buffer().params());
942 }
943
944
945 CursorSlice Cursor::normalAnchor() const
946 {
947         if (!selection())
948                 return top();
949         // LASSERT: There have been several bugs around this code, that seem
950         // to involve failures to reset the anchor. We can at least not crash
951         // in release mode by resetting it ourselves.
952         if (anchor_.depth() < depth()) {
953                 LYXERR0("Cursor is deeper than anchor. PLEASE REPORT.\nCursor is"
954                         << *this);
955                 const_cast<DocIterator &>(anchor_) = *this;
956         }
957
958         CursorSlice normal = anchor_[depth() - 1];
959         if (depth() < anchor_.depth() && top() <= normal) {
960                 // anchor is behind cursor -> move anchor behind the inset
961                 ++normal.pos();
962         }
963         return normal;
964 }
965
966
967 CursorSlice Cursor::selBegin() const
968 {
969         if (!selection())
970                 return top();
971         return normalAnchor() < top() ? normalAnchor() : top();
972 }
973
974
975 CursorSlice Cursor::selEnd() const
976 {
977         if (!selection())
978                 return top();
979         return normalAnchor() > top() ? normalAnchor() : top();
980 }
981
982
983 DocIterator Cursor::selectionBegin() const
984 {
985         if (!selection())
986                 return *this;
987
988         DocIterator di;
989         // FIXME: This is a work-around for the problem that
990         // CursorSlice doesn't keep track of the boundary.
991         if (normalAnchor() == top())
992                 di = anchor_.boundary() > boundary() ? anchor_ : *this;
993         else
994                 di = normalAnchor() < top() ? anchor_ : *this;
995         di.resize(depth());
996         return di;
997 }
998
999
1000 DocIterator Cursor::selectionEnd() const
1001 {
1002         if (!selection())
1003                 return *this;
1004
1005         DocIterator di;
1006         // FIXME: This is a work-around for the problem that
1007         // CursorSlice doesn't keep track of the boundary.
1008         if (normalAnchor() == top())
1009                 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1010         else
1011                 di = normalAnchor() > top() ? anchor_ : *this;
1012
1013         if (di.depth() > depth()) {
1014                 di.resize(depth());
1015                 ++di.pos();
1016         }
1017         return di;
1018 }
1019
1020
1021 void Cursor::setSelection()
1022 {
1023         selection(true);
1024         if (idx() == normalAnchor().idx() &&
1025             pit() == normalAnchor().pit() &&
1026             pos() == normalAnchor().pos())
1027                 selection(false);
1028 }
1029
1030
1031 void Cursor::setSelection(DocIterator const & where, int n)
1032 {
1033         setCursor(where);
1034         selection(true);
1035         anchor_ = where;
1036         pos() += n;
1037 }
1038
1039
1040 void Cursor::clearSelection()
1041 {
1042         selection(false);
1043         setWordSelection(false);
1044         setMark(false);
1045         resetAnchor();
1046 }
1047
1048
1049 void Cursor::setTargetX(int x)
1050 {
1051         x_target_ = x;
1052         textTargetOffset_ = 0;
1053 }
1054
1055
1056 int Cursor::x_target() const
1057 {
1058         return x_target_;
1059 }
1060
1061
1062 void Cursor::clearTargetX()
1063 {
1064         x_target_ = -1;
1065         textTargetOffset_ = 0;
1066 }
1067
1068
1069 void Cursor::updateTextTargetOffset()
1070 {
1071         int x;
1072         int y;
1073         getPos(x, y);
1074         textTargetOffset_ = x - x_target_;
1075 }
1076
1077
1078 void Cursor::info(odocstream & os) const
1079 {
1080         for (int i = 1, n = depth(); i < n; ++i) {
1081                 operator[](i).inset().infoize(os);
1082                 os << "  ";
1083         }
1084         if (pos() != 0) {
1085                 Inset const * inset = prevInset();
1086                 // prevInset() can return 0 in certain case.
1087                 if (inset)
1088                         prevInset()->infoize2(os);
1089         }
1090 }
1091
1092
1093 bool Cursor::selHandle(bool sel)
1094 {
1095         //lyxerr << "Cursor::selHandle" << endl;
1096         if (mark())
1097                 sel = true;
1098         if (sel == selection())
1099                 return false;
1100
1101         if (!sel)
1102                 cap::saveSelection(*this);
1103
1104         resetAnchor();
1105         selection(sel);
1106         return true;
1107 }
1108 } // namespace lyx
1109
1110
1111 ///////////////////////////////////////////////////////////////////
1112 //
1113 // FIXME: Look here
1114 // The part below is the non-integrated rest of the original math
1115 // cursor. This should be either generalized for texted or moved
1116 // back to mathed (in most cases to InsetMathNest).
1117 //
1118 ///////////////////////////////////////////////////////////////////
1119
1120 #include "mathed/InsetMathChar.h"
1121 #include "mathed/InsetMathGrid.h"
1122 #include "mathed/InsetMathScript.h"
1123 #include "mathed/InsetMathUnknown.h"
1124 #include "mathed/MathFactory.h"
1125 #include "mathed/MathStream.h"
1126 #include "mathed/MathSupport.h"
1127
1128
1129 namespace lyx {
1130
1131 bool Cursor::isInside(Inset const * p) const
1132 {
1133         for (size_t i = 0; i != depth(); ++i)
1134                 if (&operator[](i).inset() == p)
1135                         return true;
1136         return false;
1137 }
1138
1139
1140 void Cursor::leaveInset(Inset const & inset)
1141 {
1142         for (size_t i = 0; i != depth(); ++i) {
1143                 if (&operator[](i).inset() == &inset) {
1144                         resize(i);
1145                         return;
1146                 }
1147         }
1148 }
1149
1150
1151 bool Cursor::openable(MathAtom const & t) const
1152 {
1153         if (!t->isActive())
1154                 return false;
1155
1156         if (t->lock())
1157                 return false;
1158
1159         if (!selection())
1160                 return true;
1161
1162         // we can't move into anything new during selection
1163         if (depth() >= anchor_.depth())
1164                 return false;
1165         if (t.nucleus() != &anchor_[depth()].inset())
1166                 return false;
1167
1168         return true;
1169 }
1170
1171
1172 void Cursor::setScreenPos(int x, int /*y*/)
1173 {
1174         setTargetX(x);
1175         //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1176 }
1177
1178
1179
1180 void Cursor::plainErase()
1181 {
1182         cell().erase(pos());
1183 }
1184
1185
1186 void Cursor::markInsert()
1187 {
1188         insert(char_type(0));
1189 }
1190
1191
1192 void Cursor::markErase()
1193 {
1194         cell().erase(pos());
1195 }
1196
1197
1198 void Cursor::plainInsert(MathAtom const & t)
1199 {
1200         cell().insert(pos(), t);
1201         ++pos();
1202         inset().setBuffer(bv_->buffer());
1203         inset().initView();
1204         checkBufferStructure();
1205 }
1206
1207
1208 void Cursor::insert(docstring const & str)
1209 {
1210         for (char_type c : str)
1211                 insert(c);
1212 }
1213
1214
1215 void Cursor::insert(char_type c)
1216 {
1217         //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1218         LASSERT(!empty(), return);
1219         if (inMathed()) {
1220                 cap::selClearOrDel(*this);
1221                 insert(new InsetMathChar(c));
1222         } else {
1223                 text()->insertChar(*this, c);
1224         }
1225 }
1226
1227
1228 void Cursor::insert(MathAtom const & t)
1229 {
1230         //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1231         macroModeClose();
1232         cap::selClearOrDel(*this);
1233         plainInsert(t);
1234 }
1235
1236
1237 void Cursor::insert(Inset * inset0)
1238 {
1239         LASSERT(inset0, return);
1240         if (inMathed())
1241                 insert(MathAtom(inset0->asInsetMath()));
1242         else {
1243                 text()->insertInset(*this, inset0);
1244                 inset0->setBuffer(bv_->buffer());
1245                 inset0->initView();
1246                 if (inset0->isLabeled())
1247                         forceBufferUpdate();
1248         }
1249 }
1250
1251
1252 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1253 {
1254         MathData ar(buffer());
1255         asArray(t, ar, f);
1256         if (ar.size() == 1 && (enter || selection()))
1257                 niceInsert(ar[0]);
1258         else
1259                 insert(ar);
1260         return ar.size();
1261 }
1262
1263
1264 void Cursor::niceInsert(MathAtom const & t)
1265 {
1266         macroModeClose();
1267         docstring const safe = cap::grabAndEraseSelection(*this);
1268         plainInsert(t);
1269         // If possible, enter the new inset and move the contents of the selection
1270         if (t->isActive()) {
1271                 posBackward();
1272                 // be careful here: don't use 'pushBackward(t)' as this we need to
1273                 // push the clone, not the original
1274                 pushBackward(*nextInset());
1275                 // We may not use niceInsert here (recursion)
1276                 MathData ar(buffer());
1277                 asArray(safe, ar);
1278                 insert(ar);
1279         } else if (t->asMacro() && !safe.empty()) {
1280                 MathData ar(buffer());
1281                 asArray(safe, ar);
1282                 docstring const name = t->asMacro()->name();
1283                 MacroData const * data = buffer()->getMacro(name);
1284                 if (data && data->numargs() - data->optionals() > 0) {
1285                         plainInsert(MathAtom(new InsetMathBrace(ar)));
1286                         posBackward();
1287                 }
1288         }
1289 }
1290
1291
1292 void Cursor::insert(MathData const & ar)
1293 {
1294         macroModeClose();
1295         if (selection())
1296                 cap::eraseSelection(*this);
1297         cell().insert(pos(), ar);
1298         pos() += ar.size();
1299         // FIXME audit setBuffer calls
1300         inset().setBuffer(bv_->buffer());
1301 }
1302
1303
1304 bool Cursor::backspace()
1305 {
1306         if (selection()) {
1307                 cap::eraseSelection(*this);
1308                 return true;
1309         }
1310
1311         if (pos() == 0) {
1312                 // If empty cell, and not part of a big cell
1313                 if (lastpos() == 0 && inset().nargs() == 1) {
1314                         popBackward();
1315                         // Directly delete empty cell: [|[]] => [|]
1316                         if (inMathed()) {
1317                                 plainErase();
1318                                 resetAnchor();
1319                                 return true;
1320                         }
1321                         // [|], can not delete from inside
1322                         return false;
1323                 } else {
1324                         if (inMathed())
1325                                 pullArg();
1326                         else
1327                                 popBackward();
1328                         return true;
1329                 }
1330         }
1331
1332         if (inMacroMode()) {
1333                 InsetMathUnknown * p = activeMacro();
1334                 if (p->name().size() > 1) {
1335                         p->setName(p->name().substr(0, p->name().size() - 1));
1336                         return true;
1337                 }
1338         }
1339
1340         if (pos() != 0 && prevAtom()->nargs() > 0) {
1341                 // let's require two backspaces for 'big stuff' and
1342                 // highlight on the first
1343                 resetAnchor();
1344                 selection(true);
1345                 --pos();
1346         } else {
1347                 --pos();
1348                 plainErase();
1349         }
1350         return true;
1351 }
1352
1353
1354 bool Cursor::erase()
1355 {
1356         if (inMacroMode())
1357                 return true;
1358
1359         if (selection()) {
1360                 cap::eraseSelection(*this);
1361                 return true;
1362         }
1363
1364         // delete empty cells if possible
1365         if (pos() == lastpos() && inset().idxDelete(idx()))
1366                 return true;
1367
1368         // special behaviour when in last position of cell
1369         if (pos() == lastpos()) {
1370                 bool one_cell = inset().nargs() == 1;
1371                 if (one_cell && lastpos() == 0) {
1372                         popBackward();
1373                         // Directly delete empty cell: [|[]] => [|]
1374                         if (inMathed()) {
1375                                 plainErase();
1376                                 resetAnchor();
1377                                 return true;
1378                         }
1379                         // [|], can not delete from inside
1380                         return false;
1381                 }
1382                 // remove markup
1383                 if (!one_cell)
1384                         inset().idxGlue(idx());
1385                 return true;
1386         }
1387
1388         // 'clever' UI hack: only erase large items if previously slected
1389         if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1390                 resetAnchor();
1391                 selection(true);
1392                 ++pos();
1393         } else {
1394                 plainErase();
1395         }
1396
1397         return true;
1398 }
1399
1400
1401 bool Cursor::up()
1402 {
1403         macroModeClose();
1404         DocIterator save = *this;
1405         FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1406         this->dispatch(cmd);
1407         if (disp_.dispatched())
1408                 return true;
1409         setCursor(save);
1410         return false;
1411 }
1412
1413
1414 bool Cursor::down()
1415 {
1416         macroModeClose();
1417         DocIterator save = *this;
1418         FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1419         this->dispatch(cmd);
1420         if (disp_.dispatched())
1421                 return true;
1422         setCursor(save);
1423         return false;
1424 }
1425
1426
1427 bool Cursor::macroModeClose()
1428 {
1429         if (!inMacroMode())
1430                 return false;
1431         InsetMathUnknown * p = activeMacro();
1432         p->finalize();
1433         MathData selection(buffer());
1434         asArray(p->selection(), selection);
1435         docstring const s = p->name();
1436         --pos();
1437         cell().erase(pos());
1438
1439         // do nothing if the macro name is empty
1440         if (s == "\\")
1441                 return false;
1442
1443         // trigger updates of macros, at least, if no full
1444         // updates take place anyway
1445         screenUpdateFlags(Update::Force);
1446
1447         docstring const name = s.substr(1);
1448         InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1449         if (in && in->interpretString(*this, s))
1450                 return true;
1451         bool const user_macro = buffer()->getMacro(name, *this, false);
1452         MathAtom atom = user_macro ? MathAtom(new MathMacro(buffer(), name))
1453                                    : createInsetMath(name, buffer());
1454
1455         // try to put argument into macro, if we just inserted a macro
1456         bool macroArg = false;
1457         MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1458         if (atomAsMacro) {
1459                 // macros here are still unfolded (in init mode in fact). So
1460                 // we have to resolve the macro here manually and check its arity
1461                 // to put the selection behind it if arity > 0.
1462                 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1463                 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1464                         macroArg = true;
1465                         atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1466                 } else
1467                         // non-greedy case. Do not touch the arguments behind
1468                         atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1469         }
1470
1471         // insert remembered selection into first argument of a non-macro
1472         else if (atom.nucleus()->nargs() > 0)
1473                 atom.nucleus()->cell(0).append(selection);
1474
1475         MathWordList const & words = mathedWordList();
1476         MathWordList::const_iterator it = words.find(name);
1477         bool keep_mathmode = it != words.end() && (it->second.inset == "font"
1478                                                 || it->second.inset == "oldfont"
1479                                                 || it->second.inset == "mbox");
1480         bool ert_macro = !user_macro && it == words.end() && atomAsMacro;
1481
1482         if (in && in->currentMode() == Inset::TEXT_MODE
1483             && atom.nucleus()->currentMode() == Inset::MATH_MODE
1484             && name != from_ascii("ensuremath") && !ert_macro) {
1485                 MathAtom at(new InsetMathEnsureMath(buffer()));
1486                 at.nucleus()->cell(0).push_back(atom);
1487                 niceInsert(at);
1488                 posForward();
1489         } else if (in && in->currentMode() == Inset::MATH_MODE
1490                    && atom.nucleus()->currentMode() == Inset::TEXT_MODE
1491                    && !keep_mathmode) {
1492                 MathAtom at = createInsetMath("text", buffer());
1493                 at.nucleus()->cell(0).push_back(atom);
1494                 niceInsert(at);
1495                 posForward();
1496         } else
1497                 plainInsert(atom);
1498
1499         // finally put the macro argument behind, if needed
1500         if (macroArg) {
1501                 if (selection.size() > 1 || selection[0]->asScriptInset())
1502                         plainInsert(MathAtom(new InsetMathBrace(selection)));
1503                 else
1504                         insert(selection);
1505         }
1506
1507         return true;
1508 }
1509
1510
1511 docstring Cursor::macroName()
1512 {
1513         return inMacroMode() ? activeMacro()->name() : docstring();
1514 }
1515
1516
1517 void Cursor::handleNest(MathAtom const & a, int c)
1518 {
1519         //lyxerr << "Cursor::handleNest: " << c << endl;
1520         MathAtom t = a;
1521         asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1522         insert(t);
1523         posBackward();
1524         pushBackward(*nextInset());
1525 }
1526
1527
1528 int Cursor::targetX() const
1529 {
1530         if (x_target() != -1)
1531                 return x_target();
1532         int x = 0;
1533         int y = 0;
1534         getPos(x, y);
1535         return x;
1536 }
1537
1538
1539 int Cursor::textTargetOffset() const
1540 {
1541         return textTargetOffset_;
1542 }
1543
1544
1545 void Cursor::setTargetX()
1546 {
1547         int x;
1548         int y;
1549         getPos(x, y);
1550         setTargetX(x);
1551 }
1552
1553
1554 bool Cursor::inMacroMode() const
1555 {
1556         if (!inMathed())
1557                 return false;
1558         if (pos() == 0 || cell().empty())
1559                 return false;
1560         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1561         return p && !p->final();
1562 }
1563
1564
1565 InsetMathUnknown * Cursor::activeMacro()
1566 {
1567         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1568 }
1569
1570
1571 InsetMathUnknown const * Cursor::activeMacro() const
1572 {
1573         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1574 }
1575
1576
1577 void Cursor::pullArg()
1578 {
1579         // FIXME: Look here
1580         MathData ar = cell();
1581         if (popBackward() && inMathed()) {
1582                 plainErase();
1583                 cell().insert(pos(), ar);
1584                 resetAnchor();
1585         } else {
1586                 //formula()->mutateToText();
1587         }
1588 }
1589
1590
1591 void Cursor::touch()
1592 {
1593         // FIXME: look here
1594 #if 0
1595         DocIterator::const_iterator it = begin();
1596         DocIterator::const_iterator et = end();
1597         for ( ; it != et; ++it)
1598                 it->cell().touch();
1599 #endif
1600 }
1601
1602
1603 void Cursor::normalize()
1604 {
1605         if (idx() > lastidx()) {
1606                 lyxerr << "this should not really happen - 1: "
1607                        << idx() << ' ' << nargs()
1608                        << " in: " << &inset() << endl;
1609                 idx() = lastidx();
1610         }
1611
1612         if (pos() > lastpos()) {
1613                 lyxerr << "this should not really happen - 2: "
1614                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1615                        << " in atom: '";
1616                 odocstringstream os;
1617                 otexrowstream ots(os);
1618                 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1619                 inset().asInsetMath()->write(wi);
1620                 lyxerr << to_utf8(os.str()) << endl;
1621                 pos() = lastpos();
1622         }
1623 }
1624
1625
1626 bool Cursor::upDownInMath(bool up)
1627 {
1628         // Be warned: The 'logic' implemented in this function is highly
1629         // fragile. A distance of one pixel or a '<' vs '<=' _really
1630         // matters. So fiddle around with it only if you think you know
1631         // what you are doing!
1632         int xo = 0;
1633         int yo = 0;
1634         getPos(xo, yo);
1635         xo = beforeDispatchPosX_;
1636
1637         // check if we had something else in mind, if not, this is the future
1638         // target
1639         if (x_target_ == -1)
1640                 setTargetX(xo);
1641         else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1642                 // In text mode inside the line (not left or right) possibly set a new target_x,
1643                 // but only if we are somewhere else than the previous target-offset.
1644
1645                 // We want to keep the x-target on subsequent up/down movements
1646                 // that cross beyond the end of short lines. Thus a special
1647                 // handling when the cursor is at the end of line: Use the new
1648                 // x-target only if the old one was before the end of line
1649                 // or the old one was after the beginning of the line
1650                 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1651                 bool left;
1652                 bool right;
1653                 if (inRTL) {
1654                         left = pos() == textRow().endpos();
1655                         right = pos() == textRow().pos();
1656                 } else {
1657                         left = pos() == textRow().pos();
1658                         right = pos() == textRow().endpos();
1659                 }
1660                 if ((!left && !right) ||
1661                                 (left && !right && xo < x_target_) ||
1662                                 (!left && right && x_target_ < xo))
1663                         setTargetX(xo);
1664                 else
1665                         xo = targetX();
1666         } else
1667                 xo = targetX();
1668
1669         // try neigbouring script insets
1670         Cursor old = *this;
1671         if (inMathed() && !selection()) {
1672                 // try left
1673                 if (pos() != 0) {
1674                         InsetMathScript const * p = prevAtom()->asScriptInset();
1675                         if (p && p->has(up)) {
1676                                 --pos();
1677                                 push(*const_cast<InsetMathScript*>(p));
1678                                 idx() = p->idxOfScript(up);
1679                                 pos() = lastpos();
1680
1681                                 // we went in the right direction? Otherwise don't jump into the script
1682                                 int x;
1683                                 int y;
1684                                 getPos(x, y);
1685                                 int oy = beforeDispatchPosY_;
1686                                 if ((!up && y <= oy) ||
1687                                                 (up && y >= oy))
1688                                         operator=(old);
1689                                 else
1690                                         return true;
1691                         }
1692                 }
1693
1694                 // try right
1695                 if (pos() != lastpos()) {
1696                         InsetMathScript const * p = nextAtom()->asScriptInset();
1697                         if (p && p->has(up)) {
1698                                 push(*const_cast<InsetMathScript*>(p));
1699                                 idx() = p->idxOfScript(up);
1700                                 pos() = 0;
1701
1702                                 // we went in the right direction? Otherwise don't jump into the script
1703                                 int x;
1704                                 int y;
1705                                 getPos(x, y);
1706                                 int oy = beforeDispatchPosY_;
1707                                 if ((!up && y <= oy) ||
1708                                                 (up && y >= oy))
1709                                         operator=(old);
1710                                 else
1711                                         return true;
1712                         }
1713                 }
1714         }
1715
1716         // try to find an inset that knows better then we,
1717         if (inset().idxUpDown(*this, up)) {
1718                 //lyxerr << "idxUpDown triggered" << endl;
1719                 // try to find best position within this inset
1720                 if (!selection())
1721                         setCursor(bruteFind(*this, xo, yo));
1722                 return true;
1723         }
1724
1725         // any improvement going just out of inset?
1726         if (popBackward() && inMathed()) {
1727                 //lyxerr << "updown: popBackward succeeded" << endl;
1728                 int xnew;
1729                 int ynew;
1730                 int yold = beforeDispatchPosY_;
1731                 getPos(xnew, ynew);
1732                 if (up ? ynew < yold : ynew > yold)
1733                         return true;
1734         }
1735
1736         // no success, we are probably at the document top or bottom
1737         operator=(old);
1738         return false;
1739 }
1740
1741
1742 InsetMath & Cursor::nextMath()
1743 {
1744         return *nextAtom().nucleus();
1745 }
1746
1747
1748 InsetMath & Cursor::prevMath()
1749 {
1750         return *prevAtom().nucleus();
1751 }
1752
1753
1754 bool Cursor::mathForward(bool word)
1755 {
1756         LASSERT(inMathed(), return false);
1757         if (pos() < lastpos()) {
1758                 if (word) {
1759                         // word: skip a group of insets with same math class
1760                         MathClass mc = nextMath().mathClass();
1761                         do
1762                                 posForward();
1763                         while (pos() < lastpos() && mc == nextMath().mathClass());
1764                 } else if (openable(nextAtom())) {
1765                         // single step: try to enter the next inset
1766                         pushBackward(nextMath());
1767                         inset().idxFirst(*this);
1768                 } else
1769                         posForward();
1770                 return true;
1771         }
1772         if (inset().idxForward(*this))
1773                 return true;
1774         // try to pop forwards --- but don't pop out of math! leave that to
1775         // the FINISH lfuns
1776         int s = depth() - 2;
1777         if (s >= 0 && operator[](s).inset().asInsetMath())
1778                 return popForward();
1779         return false;
1780 }
1781
1782
1783 bool Cursor::mathBackward(bool word)
1784 {
1785         LASSERT(inMathed(), return false);
1786         if (pos() > 0) {
1787                 if (word) {
1788                         // word: skip a group of insets with same math class
1789                         MathClass mc = prevMath().mathClass();
1790                         do
1791                                 posBackward();
1792                         while (pos() > 0 && mc == prevMath().mathClass());
1793                 } else if (openable(prevAtom())) {
1794                         // single step: try to enter the preceding inset
1795                         posBackward();
1796                         push(nextMath());
1797                         inset().idxLast(*this);
1798                 } else
1799                         posBackward();
1800                 return true;
1801         }
1802         if (inset().idxBackward(*this))
1803                 return true;
1804         // try to pop backwards --- but don't pop out of math! leave that to
1805         // the FINISH lfuns
1806         int s = depth() - 2;
1807         if (s >= 0 && operator[](s).inset().asInsetMath())
1808                 return popBackward();
1809         return false;
1810 }
1811
1812
1813 bool Cursor::atFirstOrLastRow(bool up)
1814 {
1815         TextMetrics const & tm = bv_->textMetrics(text());
1816         ParagraphMetrics const & pm = tm.parMetrics(pit());
1817
1818         int row;
1819         if (pos() && boundary())
1820                 row = pm.pos2row(pos() - 1);
1821         else
1822                 row = pm.pos2row(pos());
1823
1824         if (up) {
1825                 if (pit() == 0 && row == 0)
1826                         return true;
1827         } else {
1828                 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1829                                 row + 1 >= int(pm.rows().size()))
1830                         return true;
1831         }
1832         return false;
1833 }
1834
1835
1836 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1837 {
1838         LASSERT(text(), return false);
1839
1840         // where are we?
1841         int xo = 0;
1842         int yo = 0;
1843         getPos(xo, yo);
1844         xo = beforeDispatchPosX_;
1845
1846         // update the targetX - this is here before the "return false"
1847         // to set a new target which can be used by InsetTexts above
1848         // if we cannot move up/down inside this inset anymore
1849         if (x_target_ == -1)
1850                 setTargetX(xo);
1851         else if (xo - textTargetOffset() != x_target() &&
1852                                          depth() == beforeDispatchCursor_.depth()) {
1853                 // In text mode inside the line (not left or right)
1854                 // possibly set a new target_x, but only if we are
1855                 // somewhere else than the previous target-offset.
1856
1857                 // We want to keep the x-target on subsequent up/down
1858                 // movements that cross beyond the end of short lines.
1859                 // Thus a special handling when the cursor is at the
1860                 // end of line: Use the new x-target only if the old
1861                 // one was before the end of line or the old one was
1862                 // after the beginning of the line
1863                 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1864                 bool left;
1865                 bool right;
1866                 if (inRTL) {
1867                         left = pos() == textRow().endpos();
1868                         right = pos() == textRow().pos();
1869                 } else {
1870                         left = pos() == textRow().pos();
1871                         right = pos() == textRow().endpos();
1872                 }
1873                 if ((!left && !right) ||
1874                                 (left && !right && xo < x_target_) ||
1875                                 (!left && right && x_target_ < xo))
1876                         setTargetX(xo);
1877                 else
1878                         xo = targetX();
1879         } else
1880                 xo = targetX();
1881
1882         // first get the current line
1883         TextMetrics & tm = bv_->textMetrics(text());
1884         ParagraphMetrics const & pm = tm.parMetrics(pit());
1885         int row;
1886         if (pos() && boundary())
1887                 row = pm.pos2row(pos() - 1);
1888         else
1889                 row = pm.pos2row(pos());
1890
1891         if (atFirstOrLastRow(up)) {
1892                 // Is there a place for the cursor to go ? If yes, we
1893                 // can execute the DEPM, otherwise we should keep the
1894                 // paragraph to host the cursor.
1895                 Cursor dummy = *this;
1896                 bool valid_destination = false;
1897                 for(; dummy.depth(); dummy.pop())
1898                         if (!dummy.atFirstOrLastRow(up)) {
1899                                 valid_destination = true;
1900                                 break;
1901                         }
1902
1903                 // will a next dispatch follow and if there is a new
1904                 // dispatch will it move the cursor out ?
1905                 if (depth() > 1 && valid_destination) {
1906                         // The cursor hasn't changed yet. This happens when
1907                         // you e.g. move out of an inset. And to give the
1908                         // DEPM the possibility of doing something we must
1909                         // provide it with two different cursors. (Lgb, vfr)
1910                         dummy = *this;
1911                         dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
1912                         dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
1913
1914                         updateNeeded |= bv().checkDepm(dummy, *this);
1915                         updateTextTargetOffset();
1916                         if (updateNeeded)
1917                                 forceBufferUpdate();
1918                 }
1919                 return false;
1920         }
1921
1922         // with and without selection are handled differently
1923         if (!selection()) {
1924                 int yo = bv().getPos(*this).y_;
1925                 Cursor old = *this;
1926                 // To next/previous row
1927                 if (up)
1928                         tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1929                 else
1930                         tm.editXY(*this, xo, yo + textRow().descent() + 1);
1931                 clearSelection();
1932
1933                 // This happens when you move out of an inset.
1934                 // And to give the DEPM the possibility of doing
1935                 // something we must provide it with two different
1936                 // cursors. (Lgb)
1937                 Cursor dummy = *this;
1938                 if (dummy == old)
1939                         ++dummy.pos();
1940                 if (bv().checkDepm(dummy, old)) {
1941                         updateNeeded = true;
1942                         // Make sure that cur gets back whatever happened to dummy (Lgb)
1943                         operator=(dummy);
1944                 }
1945                 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
1946                         posBackward();
1947         } else {
1948                 // if there is a selection, we stay out of any inset,
1949                 // and just jump to the right position:
1950                 Cursor old = *this;
1951                 int next_row = row;
1952                 if (up) {
1953                         if (row > 0) {
1954                                 --next_row;
1955                         } else if (pit() > 0) {
1956                                 --pit();
1957                                 TextMetrics & tm = bv_->textMetrics(text());
1958                                 if (!tm.contains(pit()))
1959                                         tm.newParMetricsUp();
1960                                 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
1961                                 next_row = pmcur.rows().size() - 1;
1962                         }
1963                 } else {
1964                         if (row + 1 < int(pm.rows().size())) {
1965                                 ++next_row;
1966                         } else if (pit() + 1 < int(text()->paragraphs().size())) {
1967                                 ++pit();
1968                                 TextMetrics & tm = bv_->textMetrics(text());
1969                                 if (!tm.contains(pit()))
1970                                         tm.newParMetricsDown();
1971                                 next_row = 0;
1972                         }
1973                 }
1974
1975                 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
1976                 bool bound = false;
1977                 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
1978                 boundary(bound);
1979
1980                 updateNeeded |= bv().checkDepm(*this, old);
1981         }
1982
1983         if (updateNeeded)
1984                 forceBufferUpdate();
1985         updateTextTargetOffset();
1986         return true;
1987 }
1988
1989
1990 void Cursor::handleFont(string const & font)
1991 {
1992         LYXERR(Debug::DEBUG, font);
1993         docstring safe;
1994         if (selection()) {
1995                 macroModeClose();
1996                 safe = cap::grabAndEraseSelection(*this);
1997         }
1998
1999         recordUndoInset();
2000
2001         if (lastpos() != 0) {
2002                 // something left in the cell
2003                 if (pos() == 0) {
2004                         // cursor in first position
2005                         popBackward();
2006                 } else if (pos() == lastpos()) {
2007                         // cursor in last position
2008                         popForward();
2009                 } else {
2010                         // cursor in between. split cell
2011                         MathData::iterator bt = cell().begin();
2012                         MathAtom at = createInsetMath(from_utf8(font), buffer());
2013                         at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2014                         cell().erase(bt, bt + pos());
2015                         popBackward();
2016                         plainInsert(at);
2017                 }
2018         } else {
2019                 // nothing left in the cell
2020                 popBackward();
2021                 plainErase();
2022                 resetAnchor();
2023         }
2024         insert(safe);
2025 }
2026
2027
2028 void Cursor::message(docstring const & msg) const
2029 {
2030         disp_.setMessage(msg);
2031 }
2032
2033
2034 void Cursor::errorMessage(docstring const & msg) const
2035 {
2036         disp_.setMessage(msg);
2037         disp_.setError(true);
2038 }
2039
2040
2041 namespace {
2042
2043 docstring parbreak(Cursor const * cur)
2044 {
2045         odocstringstream os;
2046         os << '\n';
2047         // only add blank line if we're not in a ParbreakIsNewline situation
2048         if (!cur->inset().getLayout().parbreakIsNewline()
2049             && !cur->paragraph().layout().parbreak_is_newline)
2050                 os << '\n';
2051         return os.str();
2052 }
2053
2054 }
2055
2056
2057 docstring Cursor::selectionAsString(bool with_label) const
2058 {
2059         if (!selection())
2060                 return docstring();
2061
2062         if (inMathed())
2063                 return cap::grabSelection(*this);
2064
2065         int const label = with_label
2066                 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
2067
2068         idx_type const startidx = selBegin().idx();
2069         idx_type const endidx = selEnd().idx();
2070         if (startidx != endidx) {
2071                 // multicell selection
2072                 InsetTabular * table = inset().asInsetTabular();
2073                 LASSERT(table, return docstring());
2074                 return table->asString(startidx, endidx);
2075         }
2076
2077         ParagraphList const & pars = text()->paragraphs();
2078
2079         pit_type const startpit = selBegin().pit();
2080         pit_type const endpit = selEnd().pit();
2081         size_t const startpos = selBegin().pos();
2082         size_t const endpos = selEnd().pos();
2083
2084         if (startpit == endpit)
2085                 return pars[startpit].asString(startpos, endpos, label);
2086
2087         // First paragraph in selection
2088         docstring result = pars[startpit].
2089                 asString(startpos, pars[startpit].size(), label)
2090                 + parbreak(this);
2091
2092         // The paragraphs in between (if any)
2093         for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2094                 Paragraph const & par = pars[pit];
2095                 result += par.asString(0, par.size(), label)
2096                         + parbreak(this);
2097         }
2098
2099         // Last paragraph in selection
2100         result += pars[endpit].asString(0, endpos, label);
2101
2102         return result;
2103 }
2104
2105
2106 docstring Cursor::currentState() const
2107 {
2108         if (inMathed()) {
2109                 odocstringstream os;
2110                 info(os);
2111 #ifdef DEVEL_VERSION
2112                 InsetMath * math = inset().asInsetMath();
2113                 if (math)
2114                         os << _(", Inset: ") << math->id();
2115                 os << _(", Cell: ") << idx();
2116                 os << _(", Position: ") << pos();
2117 #endif
2118                 return os.str();
2119         }
2120
2121         if (inTexted())
2122                 return text()->currentState(*this);
2123
2124         return docstring();
2125 }
2126
2127
2128 docstring Cursor::getPossibleLabel() const
2129 {
2130         return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2131 }
2132
2133
2134 Encoding const * Cursor::getEncoding() const
2135 {
2136         if (empty())
2137                 return 0;
2138         BufferParams const & bp = bv().buffer().params();
2139         if (bp.useNonTeXFonts)
2140                 return encodings.fromLyXName("utf8-plain");
2141
2142         CursorSlice const & sl = innerTextSlice();
2143         Text const & text = *sl.text();
2144         Font font = text.getPar(sl.pit()).getFont(bp, sl.pos(),
2145                                                   text.outerFont(sl.pit()));
2146         return font.language()->encoding();
2147 }
2148
2149
2150 void Cursor::undispatched() const
2151 {
2152         disp_.dispatched(false);
2153 }
2154
2155
2156 void Cursor::dispatched() const
2157 {
2158         disp_.dispatched(true);
2159 }
2160
2161
2162 void Cursor::screenUpdateFlags(Update::flags f) const
2163 {
2164         disp_.screenUpdate(f);
2165 }
2166
2167
2168 void Cursor::forceBufferUpdate() const
2169 {
2170         disp_.forceBufferUpdate();
2171 }
2172
2173
2174 void Cursor::clearBufferUpdate() const
2175 {
2176         disp_.clearBufferUpdate();
2177 }
2178
2179
2180 bool Cursor::needBufferUpdate() const
2181 {
2182         return disp_.needBufferUpdate();
2183 }
2184
2185
2186 void Cursor::noScreenUpdate() const
2187 {
2188         disp_.screenUpdate(Update::None);
2189 }
2190
2191
2192 Font Cursor::getFont() const
2193 {
2194         // The logic here should more or less match to the
2195         // Cursor::setCurrentFont logic, i.e. the cursor height should
2196         // give a hint what will happen if a character is entered.
2197         // FIXME: this is not the case, what about removing this method ? (see #10478).
2198
2199         // HACK. far from being perfect...
2200
2201         CursorSlice const & sl = innerTextSlice();
2202         Text const & text = *sl.text();
2203         Paragraph const & par = text.getPar(sl.pit());
2204
2205         // on boundary, so we are really at the character before
2206         pos_type pos = sl.pos();
2207         if (pos > 0 && boundary())
2208                 --pos;
2209
2210         // on space? Take the font before (only for RTL boundary stay)
2211         if (pos > 0) {
2212                 TextMetrics const & tm = bv().textMetrics(&text);
2213                 if (pos == sl.lastpos()
2214                         || (par.isSeparator(pos)
2215                         && !tm.isRTLBoundary(sl.pit(), pos)))
2216                         --pos;
2217         }
2218
2219         // get font at the position
2220         Font font = par.getFont(buffer()->params(), pos,
2221                 text.outerFont(sl.pit()));
2222
2223         return font;
2224 }
2225
2226
2227 bool Cursor::fixIfBroken()
2228 {
2229         bool const broken_cursor = DocIterator::fixIfBroken();
2230         bool const broken_anchor = anchor_.fixIfBroken();
2231
2232         if (broken_cursor || broken_anchor) {
2233                 clearNewWordPosition();
2234                 clearSelection();
2235                 return true;
2236         }
2237         return false;
2238 }
2239
2240
2241 void Cursor::sanitize()
2242 {
2243         setBuffer(&bv_->buffer());
2244         DocIterator::sanitize();
2245         new_word_.sanitize();
2246         if (selection())
2247                 anchor_.sanitize();
2248         else
2249                 resetAnchor();
2250 }
2251
2252
2253 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2254 {
2255         // find inset in common
2256         size_type i;
2257         for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2258                 if (&old[i].inset() != &cur[i].inset())
2259                         break;
2260         }
2261
2262         // update words if we just moved to another paragraph
2263         if (i == old.depth() && i == cur.depth()
2264             && !cur.buffer()->isClean()
2265             && cur.inTexted() && old.inTexted()
2266             && cur.pit() != old.pit()) {
2267                 old.paragraph().updateWords();
2268         }
2269
2270         // notify everything on top of the common part in old cursor,
2271         // but stop if the inset claims the cursor to be invalid now
2272         for (size_type j = i; j < old.depth(); ++j) {
2273                 Cursor inset_pos = old;
2274                 inset_pos.cutOff(j);
2275                 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2276                         return true;
2277         }
2278
2279         // notify everything on top of the common part in new cursor,
2280         // but stop if the inset claims the cursor to be invalid now
2281         for (; i < cur.depth(); ++i) {
2282                 if (cur[i].inset().notifyCursorEnters(cur))
2283                         return true;
2284         }
2285
2286         return false;
2287 }
2288
2289
2290 void Cursor::setCurrentFont()
2291 {
2292         CursorSlice const & cs = innerTextSlice();
2293         Paragraph const & par = cs.paragraph();
2294         pos_type cpit = cs.pit();
2295         pos_type cpos = cs.pos();
2296         Text const & ctext = *cs.text();
2297         TextMetrics const & tm = bv().textMetrics(&ctext);
2298
2299         // are we behind previous char in fact? -> go to that char
2300         if (cpos > 0 && boundary())
2301                 --cpos;
2302
2303         // find position to take the font from
2304         if (cpos != 0) {
2305                 // paragraph end? -> font of last char
2306                 if (cpos == lastpos())
2307                         --cpos;
2308                 // on space? -> look at the words in front of space
2309                 else if (cpos > 0 && par.isSeparator(cpos))     {
2310                         // abc| def -> font of c
2311                         // abc |[WERBEH], i.e. boundary==true -> font of c
2312                         // abc [WERBEH]| def, font of the space
2313                         if (!tm.isRTLBoundary(cpit, cpos))
2314                                 --cpos;
2315                 }
2316         }
2317
2318         // get font
2319         BufferParams const & bufparams = buffer()->params();
2320         current_font = par.getFontSettings(bufparams, cpos);
2321         real_current_font = tm.displayFont(cpit, cpos);
2322
2323         // special case for paragraph end
2324         if (cs.pos() == lastpos()
2325             && tm.isRTLBoundary(cpit, cs.pos())
2326             && !boundary()) {
2327                 Language const * lang = par.getParLanguage(bufparams);
2328                 current_font.setLanguage(lang);
2329                 current_font.fontInfo().setNumber(FONT_OFF);
2330                 real_current_font.setLanguage(lang);
2331                 real_current_font.fontInfo().setNumber(FONT_OFF);
2332         }
2333 }
2334
2335
2336 bool Cursor::textUndo()
2337 {
2338         if (!buffer()->undo().textUndo(*this))
2339                 return false;
2340         sanitize();
2341         return true;
2342 }
2343
2344
2345 bool Cursor::textRedo()
2346 {
2347         if (!buffer()->undo().textRedo(*this))
2348                 return false;
2349         sanitize();
2350         return true;
2351 }
2352
2353
2354 void Cursor::finishUndo() const
2355 {
2356         buffer()->undo().finishUndo();
2357 }
2358
2359
2360 void Cursor::beginUndoGroup() const
2361 {
2362         buffer()->undo().beginUndoGroup(*this);
2363 }
2364
2365
2366 void Cursor::endUndoGroup() const
2367 {
2368         buffer()->undo().endUndoGroup(*this);
2369 }
2370
2371
2372 void Cursor::recordUndo(pit_type from, pit_type to) const
2373 {
2374         buffer()->undo().recordUndo(*this, from, to);
2375 }
2376
2377
2378 void Cursor::recordUndo(pit_type from) const
2379 {
2380         buffer()->undo().recordUndo(*this, from, pit());
2381 }
2382
2383
2384 void Cursor::recordUndo(UndoKind kind) const
2385 {
2386         buffer()->undo().recordUndo(*this, kind);
2387 }
2388
2389
2390 void Cursor::recordUndoInset(Inset const * in) const
2391 {
2392         buffer()->undo().recordUndoInset(*this, in);
2393 }
2394
2395
2396 void Cursor::recordUndoFullBuffer() const
2397 {
2398         buffer()->undo().recordUndoFullBuffer(*this);
2399 }
2400
2401
2402 void Cursor::recordUndoBufferParams() const
2403 {
2404         buffer()->undo().recordUndoBufferParams(*this);
2405 }
2406
2407
2408 void Cursor::recordUndoSelection() const
2409 {
2410         if (inMathed()) {
2411                 if (cap::multipleCellsSelected(*this))
2412                         recordUndoInset();
2413                 else
2414                         recordUndo();
2415         } else {
2416                 buffer()->undo().recordUndo(*this,
2417                         selBegin().pit(), selEnd().pit());
2418         }
2419 }
2420
2421
2422 void Cursor::checkBufferStructure()
2423 {
2424         Buffer const * master = buffer()->masterBuffer();
2425         master->tocBackend().updateItem(*this);
2426         if (master != buffer() && !master->hasGuiDelegate())
2427                 // In case the master has no gui associated with it,
2428                 // the TocItem is not updated (part of bug 5699).
2429                 buffer()->tocBackend().updateItem(*this);
2430
2431         // If the last tracked change of the paragraph has just been
2432         // deleted, then we need to recompute the buffer flag
2433         // tracked_changes_present_.
2434         if (inTexted() && paragraph().isChangeUpdateRequired())
2435                 disp_.forceChangesUpdate();
2436 }
2437
2438
2439 } // namespace lyx