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