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