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