]> git.lyx.org Git - lyx.git/blob - src/Cursor.cpp
Reset stream properties after changing them
[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 // be careful: this is called from the bv's constructor, too, so
265 // bv functions are not yet available!
266 Cursor::Cursor(BufferView & bv)
267         : CursorData(&bv.buffer()), bv_(&bv),
268           x_target_(-1), textTargetOffset_(0),
269           beforeDispatchPosX_(0), beforeDispatchPosY_(0)
270 {}
271
272
273 void Cursor::reset()
274 {
275         clear();
276         push_back(CursorSlice(buffer()->inset()));
277         anchor_ = doc_iterator_begin(buffer());
278         anchor_.clear();
279         new_word_ = doc_iterator_begin(buffer());
280         new_word_.clear();
281         clearTargetX();
282         selection_ = false;
283         mark_ = false;
284 }
285
286
287 // this (intentionally) does neither touch anchor nor selection status
288 void Cursor::setCursor(DocIterator const & cur)
289 {
290         DocIterator::operator=(cur);
291 }
292
293
294 void Cursor::setCursorToAnchor()
295 {
296         if (selection()) {
297                 DocIterator normal = anchor_;
298                 while (depth() < normal.depth())
299                         normal.pop_back();
300                 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
301                         ++normal.pos();
302                 setCursor(normal);
303         }
304 }
305
306
307 void Cursor::setCursorData(CursorData const & data)
308 {
309         CursorData::operator=(data);
310 }
311
312
313 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
314 {
315         Cursor cur = *this;
316
317         // Try to fix cursor in case it is broken.
318         cur.fixIfBroken();
319
320         // Is this a function that acts on inset at point?
321         Inset * inset = cur.nextInset();
322         if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
323             && inset && inset->getStatus(cur, cmd, status))
324                 return true;
325
326         // This is, of course, a mess. Better create a new doc iterator and use
327         // this in Inset::getStatus. This might require an additional
328         // BufferView * arg, though (which should be avoided)
329         //Cursor safe = *this;
330         bool res = false;
331         for ( ; cur.depth(); cur.pop()) {
332                 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
333                 // LASSERT: Is it safe to continue here, or should we return?
334                 LASSERT(cur.idx() <= cur.lastidx(), /**/);
335                 LASSERT(cur.pit() <= cur.lastpit(), /**/);
336                 LASSERT(cur.pos() <= cur.lastpos(), /**/);
337
338                 // The inset's getStatus() will return 'true' if it made
339                 // a definitive decision on whether it want to handle the
340                 // request or not. The result of this decision is put into
341                 // the 'status' parameter.
342                 if (cur.inset().getStatus(cur, cmd, status)) {
343                         res = true;
344                         break;
345                 }
346         }
347         return res;
348 }
349
350
351 void Cursor::saveBeforeDispatchPosXY()
352 {
353         getPos(beforeDispatchPosX_, beforeDispatchPosY_);
354 }
355
356
357 void Cursor::dispatch(FuncRequest const & cmd0)
358 {
359         LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
360         if (empty())
361                 return;
362
363         fixIfBroken();
364         FuncRequest cmd = cmd0;
365         Cursor safe = *this;
366         Cursor old = *this;
367         disp_ = DispatchResult();
368
369         beginUndoGroup();
370
371         // Is this a function that acts on inset at point?
372         if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
373             && nextInset()) {
374                 disp_.dispatched(true);
375                 disp_.screenUpdate(Update::FitCursor | Update::Force);
376                 FuncRequest tmpcmd = cmd;
377                 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
378                         << cmd0 << endl << *this);
379                 nextInset()->dispatch(*this, tmpcmd);
380                 if (disp_.dispatched()) {
381                         endUndoGroup();
382                         return;
383                 }
384         }
385
386         // store some values to be used inside of the handlers
387         beforeDispatchCursor_ = *this;
388         for (; depth(); pop(), boundary(false)) {
389                 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
390                         << cmd0 << endl << *this);
391
392                 // In any of these cases, the cursor is invalid, and we should
393                 // try to save this document rather than crash.
394                 LBUFERR(pos() <= lastpos());
395                 LBUFERR(idx() <= lastidx());
396                 LBUFERR(pit() <= lastpit());
397
398                 // The common case is 'LFUN handled, need update', so make the
399                 // LFUN handler's life easier by assuming this as default value.
400                 // The handler can reset the update and val flags if necessary.
401                 disp_.screenUpdate(Update::FitCursor | Update::Force);
402                 disp_.dispatched(true);
403                 inset().dispatch(*this, cmd);
404                 if (disp_.dispatched())
405                         break;
406         }
407
408         // it completely to get a 'bomb early' behaviour in case this
409         // object will be used again.
410         if (!disp_.dispatched()) {
411                 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
412                 // We might have invalidated the cursor when removing an empty
413                 // paragraph while the cursor could not be moved out the inset
414                 // while we initially thought we could. This might happen when
415                 // a multiline inset becomes an inline inset when the second
416                 // paragraph is removed.
417                 if (safe.pit() > safe.lastpit()) {
418                         safe.pit() = safe.lastpit();
419                         safe.pos() = safe.lastpos();
420                 }
421                 operator=(safe);
422                 disp_.screenUpdate(Update::None);
423                 disp_.dispatched(false);
424         } else {
425                 // restore the previous one because nested Cursor::dispatch calls
426                 // are possible which would change it
427                 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
428         }
429         endUndoGroup();
430
431         // notify insets we just left
432         if (*this != old) {
433                 old.beginUndoGroup();
434                 old.fixIfBroken();
435                 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
436                 if (badcursor) {
437                         fixIfBroken();
438                         bv().resetInlineCompletionPos();
439                 }
440                 old.endUndoGroup();
441         }
442 }
443
444
445 DispatchResult const & Cursor::result() const
446 {
447         return disp_;
448 }
449
450
451 BufferView & Cursor::bv() const
452 {
453         LBUFERR(bv_);
454         return *bv_;
455 }
456
457
458 void Cursor::pop()
459 {
460         LBUFERR(depth() >= 1);
461         pop_back();
462 }
463
464
465 void Cursor::push(Inset & p)
466 {
467         push_back(CursorSlice(p));
468         p.setBuffer(*buffer());
469 }
470
471
472 void Cursor::pushBackward(Inset & p)
473 {
474         LASSERT(!empty(), return);
475         //lyxerr << "Entering inset " << t << " front" << endl;
476         push(p);
477         p.idxFirst(*this);
478 }
479
480
481 bool Cursor::popBackward()
482 {
483         LASSERT(!empty(), return false);
484         if (depth() == 1)
485                 return false;
486         pop();
487         return true;
488 }
489
490
491 bool Cursor::popForward()
492 {
493         LASSERT(!empty(), return false);
494         //lyxerr << "Leaving inset from in back" << endl;
495         const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
496         if (depth() == 1)
497                 return false;
498         pop();
499         pos() += lastpos() - lp + 1;
500         return true;
501 }
502
503
504 int Cursor::currentMode()
505 {
506         LASSERT(!empty(), return Inset::UNDECIDED_MODE);
507         for (int i = depth() - 1; i >= 0; --i) {
508                 int res = operator[](i).inset().currentMode();
509                 bool locked_mode = operator[](i).inset().lockedMode();
510                 // Also return UNDECIDED_MODE when the mode is locked,
511                 // as in this case it is treated the same as TEXT_MODE
512                 if (res != Inset::UNDECIDED_MODE || locked_mode)
513                         return res;
514         }
515         return Inset::TEXT_MODE;
516 }
517
518
519 void Cursor::getPos(int & x, int & y) const
520 {
521         Point p = bv().getPos(*this);
522         x = p.x_;
523         y = p.y_;
524 }
525
526
527 Row const & Cursor::textRow() const
528 {
529         CursorSlice const & cs = innerTextSlice();
530         ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
531         return pm.getRow(pos(), boundary());
532 }
533
534
535 void Cursor::resetAnchor()
536 {
537         anchor_ = *this;
538         checkNewWordPosition();
539 }
540
541
542 void Cursor::markNewWordPosition()
543 {
544         if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
545                 FontSpan nw = locateWord(WHOLE_WORD);
546                 if (nw.size() == 1) {
547                         LYXERR(Debug::DEBUG, "start new word: "
548                                 << " par: " << pit()
549                                 << " pos: " << nw.first);
550                         new_word_ = *this;
551                 }
552         }
553 }
554
555
556 void Cursor::clearNewWordPosition()
557 {
558         if (!new_word_.empty()) {
559                 LYXERR(Debug::DEBUG, "clear new word: "
560                         << " par: " << pit()
561                         << " pos: " << pos());
562                 new_word_.resize(0);
563         }
564 }
565
566
567 void Cursor::checkNewWordPosition()
568 {
569         if (!lyxrc.spellcheck_continuously || new_word_.empty())
570                 return ;
571         if (!inTexted())
572                 clearNewWordPosition();
573         else {
574                 // forget the position of the current new word if
575                 // 1) the paragraph changes or
576                 // 2) the count of nested insets changes or
577                 // 3) the cursor pos is out of paragraph bound
578                 if (pit() != new_word_.pit() ||
579                         depth() != new_word_.depth() ||
580                         new_word_.pos() > new_word_.lastpos()) {
581                         clearNewWordPosition();
582                 } else if (new_word_.fixIfBroken())
583                         // 4) or the remembered position was "broken"
584                         clearNewWordPosition();
585                 else {
586                         FontSpan nw = locateWord(WHOLE_WORD);
587                         if (!nw.empty()) {
588                                 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
589                                 if (nw.intersect(ow).empty())
590                                         clearNewWordPosition();
591                                 else
592                                         LYXERR(Debug::DEBUG, "new word: "
593                                                    << " par: " << pit()
594                                                    << " pos: " << nw.first << ".." << nw.last);
595                         } else {
596                                 clearNewWordPosition();
597                         }
598                 }
599         }
600 }
601
602
603 bool Cursor::posBackward()
604 {
605         if (pos() == 0)
606                 return false;
607         --pos();
608         return true;
609 }
610
611
612 bool Cursor::posForward()
613 {
614         if (pos() == lastpos())
615                 return false;
616         ++pos();
617         return true;
618 }
619
620
621 bool Cursor::posVisRight(bool skip_inset)
622 {
623         Cursor new_cur = *this; // where we will move to
624         pos_type left_pos; // position visually left of current cursor
625         pos_type right_pos; // position visually right of current cursor
626
627         getSurroundingPos(left_pos, right_pos);
628
629         LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
630
631         // Are we at an inset?
632         new_cur.pos() = right_pos;
633         new_cur.boundary(false);
634         if (!skip_inset &&
635                 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
636                 // we actually move the cursor at the end of this
637                 // function, for now we just keep track of the new
638                 // position in new_cur...
639                 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
640         }
641
642         // Are we already at rightmost pos in row?
643         else if (text()->empty() || right_pos == -1) {
644
645                 new_cur = *this;
646                 if (!new_cur.posVisToNewRow(false)) {
647                         LYXERR(Debug::RTL, "not moving!");
648                         return false;
649                 }
650
651                 // we actually move the cursor at the end of this
652                 // function, for now just keep track of the new
653                 // position in new_cur...
654                 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
655                         << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
656
657         }
658         // normal movement to the right
659         else {
660                 new_cur = *this;
661                 // Recall, if the cursor is at position 'x', that
662                 // means *before* the character at position 'x'. In
663                 // RTL, "before" means "to the right of", in LTR, "to
664                 // the left of". So currently our situation is this:
665                 // the position to our right is 'right_pos' (i.e.,
666                 // we're currently to the left of 'right_pos'). In
667                 // order to move to the right, it depends whether or
668                 // not the character at 'right_pos' is RTL.
669                 bool const new_pos_is_RTL = paragraph().getFontSettings(
670                         buffer()->params(), right_pos).isVisibleRightToLeft();
671                 // If the character at 'right_pos' *is* LTR, then in
672                 // order to move to the right of it, we need to be
673                 // *after* 'right_pos', i.e., move to position
674                 // 'right_pos' + 1.
675                 if (!new_pos_is_RTL) {
676                         new_cur.pos() = right_pos + 1;
677                         // set the boundary to true in two situations:
678                         if (
679                         // 1. if new_pos is now lastpos, and we're in
680                         // an RTL paragraph (this means that we're
681                         // moving right to the end of an LTR chunk
682                         // which is at the end of an RTL paragraph);
683                                 (new_cur.pos() == lastpos()
684                                  && paragraph().isRTL(buffer()->params()))
685                         // 2. if the position *after* right_pos is RTL
686                         // (we want to be *after* right_pos, not
687                         // before right_pos + 1!)
688                                 || paragraph().getFontSettings(buffer()->params(),
689                                                 new_cur.pos()).isVisibleRightToLeft()
690                         )
691                                 new_cur.boundary(true);
692                         else // set the boundary to false
693                                 new_cur.boundary(false);
694                 }
695                 // Otherwise (if the character at position 'right_pos'
696                 // is RTL), then moving to the right of it is as easy
697                 // as setting the new position to 'right_pos'.
698                 else {
699                         new_cur.pos() = right_pos;
700                         new_cur.boundary(false);
701                 }
702
703         }
704
705         bool moved = (new_cur.pos() != pos()
706                                   || new_cur.pit() != pit()
707                                   || new_cur.boundary() != boundary()
708                                   || &new_cur.inset() != &inset());
709
710         if (moved) {
711                 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
712                         << (new_cur.boundary() ? " (boundary)" : ""));
713                 *this = new_cur;
714         }
715
716         return moved;
717 }
718
719
720 bool Cursor::posVisLeft(bool skip_inset)
721 {
722         Cursor new_cur = *this; // where we will move to
723         pos_type left_pos; // position visually left of current cursor
724         pos_type right_pos; // position visually right of current cursor
725
726         getSurroundingPos(left_pos, right_pos);
727
728         LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
729
730         // Are we at an inset?
731         new_cur.pos() = left_pos;
732         new_cur.boundary(false);
733         if (!skip_inset &&
734                 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
735                 // we actually move the cursor at the end of this
736                 // function, for now we just keep track of the new
737                 // position in new_cur...
738                 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
739         }
740
741         // Are we already at leftmost pos in row?
742         else if (text()->empty() || left_pos == -1) {
743
744                 new_cur = *this;
745                 if (!new_cur.posVisToNewRow(true)) {
746                         LYXERR(Debug::RTL, "not moving!");
747                         return false;
748                 }
749
750                 // we actually move the cursor at the end of this
751                 // function, for now just keep track of the new
752                 // position in new_cur...
753                 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
754                         << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
755
756         }
757         // normal movement to the left
758         else {
759                 new_cur = *this;
760                 // Recall, if the cursor is at position 'x', that
761                 // means *before* the character at position 'x'. In
762                 // RTL, "before" means "to the right of", in LTR, "to
763                 // the left of". So currently our situation is this:
764                 // the position to our left is 'left_pos' (i.e., we're
765                 // currently to the right of 'left_pos'). In order to
766                 // move to the left, it depends whether or not the
767                 // character at 'left_pos' is RTL.
768                 bool const new_pos_is_RTL = paragraph().getFontSettings(
769                         buffer()->params(), left_pos).isVisibleRightToLeft();
770                 // If the character at 'left_pos' *is* RTL, then in
771                 // order to move to the left of it, we need to be
772                 // *after* 'left_pos', i.e., move to position
773                 // 'left_pos' + 1.
774                 if (new_pos_is_RTL) {
775                         new_cur.pos() = left_pos + 1;
776                         // set the boundary to true in two situations:
777                         if (
778                         // 1. if new_pos is now lastpos and we're in
779                         // an LTR paragraph (this means that we're
780                         // moving left to the end of an RTL chunk
781                         // which is at the end of an LTR paragraph);
782                                 (new_cur.pos() == lastpos()
783                                  && !paragraph().isRTL(buffer()->params()))
784                         // 2. if the position *after* left_pos is not
785                         // RTL (we want to be *after* left_pos, not
786                         // before left_pos + 1!)
787                                 || !paragraph().getFontSettings(buffer()->params(),
788                                                 new_cur.pos()).isVisibleRightToLeft()
789                         )
790                                 new_cur.boundary(true);
791                         else // set the boundary to false
792                                 new_cur.boundary(false);
793                 }
794                 // Otherwise (if the character at position 'left_pos'
795                 // is LTR), then moving to the left of it is as easy
796                 // as setting the new position to 'left_pos'.
797                 else {
798                         new_cur.pos() = left_pos;
799                         new_cur.boundary(false);
800                 }
801
802         }
803
804         bool moved = (new_cur.pos() != pos()
805                                   || new_cur.pit() != pit()
806                                   || new_cur.boundary() != boundary());
807
808         if (moved) {
809                 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
810                         << (new_cur.boundary() ? " (boundary)" : ""));
811                 *this = new_cur;
812         }
813
814         return moved;
815 }
816
817
818 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
819 {
820         // preparing bidi tables
821         Paragraph const & par = paragraph();
822         Buffer const & buf = *buffer();
823         Row const & row = textRow();
824         Bidi bidi;
825         bidi.computeTables(par, buf, row);
826
827         LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
828
829         // The cursor is painted *before* the character at pos(), or,
830         // if 'boundary' is true, *after* the character at (pos() -
831         // 1). So we already have one known position around the
832         // cursor:
833         pos_type const known_pos = boundary() && pos() > 0 ? pos() - 1 : pos();
834
835         // edge case: if we're at the end of the paragraph, things are
836         // a little different (because lastpos is a position which
837         // does not really "exist" --- there's no character there
838         // yet).
839         if (known_pos == lastpos()) {
840                 if (par.isRTL(buf.params())) {
841                         left_pos = -1;
842                         right_pos = bidi.vis2log(row.pos());
843                 } else {
844                         // LTR paragraph
845                         right_pos = -1;
846                         left_pos = bidi.vis2log(row.endpos() - 1);
847                 }
848                 return;
849         }
850
851         // Whether 'known_pos' is to the left or to the right of the
852         // cursor depends on whether it is an RTL or LTR character...
853         bool const cur_is_RTL =
854                 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
855         // ... in the following manner:
856         // For an RTL character, "before"
857         // means "to the right" and "after" means "to the left"; and
858         // for LTR, it's the reverse. So, 'known_pos' is to the right
859         // of the cursor if (RTL && boundary) or (!RTL && !boundary):
860         bool const known_pos_on_right = cur_is_RTL == boundary();
861
862         // So we now know one of the positions surrounding the cursor.
863         // Let's determine the other one:
864         if (known_pos_on_right) {
865                 right_pos = known_pos;
866                 // *visual* position of 'left_pos':
867                 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
868                 // If the position we just identified as 'left_pos' is
869                 // a "skipped separator" (a separator which is at the
870                 // logical end of a row, except for the last row in a
871                 // paragraph; such separators are not painted, so they
872                 // "are not really there"; note that in bidi text,
873                 // such a separator could appear visually in the
874                 // middle of a row), set 'left_pos' to the *next*
875                 // position to the left.
876                 if (bidi.inRange(v_left_pos)
877                                 && bidi.vis2log(v_left_pos) + 1 == row.endpos()
878                                 && row.endpos() < lastpos()
879                                 && par.isSeparator(bidi.vis2log(v_left_pos)))
880                         --v_left_pos;
881
882                 // calculate the logical position of 'left_pos', if in row
883                 if (!bidi.inRange(v_left_pos))
884                         left_pos = -1;
885                 else
886                         left_pos = bidi.vis2log(v_left_pos);
887                 // If the position we identified as 'right_pos' is a
888                 // "skipped separator", set 'right_pos' to the *next*
889                 // position to the right.
890                 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos()
891                                 && par.isSeparator(right_pos)) {
892                         pos_type const v_right_pos = bidi.log2vis(right_pos) + 1;
893                         if (!bidi.inRange(v_right_pos))
894                                 right_pos = -1;
895                         else
896                                 right_pos = bidi.vis2log(v_right_pos);
897                 }
898         } else {
899                 // known_pos is on the left
900                 left_pos = known_pos;
901                 // *visual* position of 'right_pos'
902                 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
903                 // If the position we just identified as 'right_pos'
904                 // is a "skipped separator", set 'right_pos' to the
905                 // *next* position to the right.
906                 if (bidi.inRange(v_right_pos)
907                                 && bidi.vis2log(v_right_pos) + 1 == row.endpos()
908                                 && row.endpos() < lastpos()
909                                 && par.isSeparator(bidi.vis2log(v_right_pos)))
910                         ++v_right_pos;
911
912                 // calculate the logical position of 'right_pos', if in row
913                 if (!bidi.inRange(v_right_pos))
914                         right_pos = -1;
915                 else
916                         right_pos = bidi.vis2log(v_right_pos);
917                 // If the position we identified as 'left_pos' is a
918                 // "skipped separator", set 'left_pos' to the *next*
919                 // position to the left.
920                 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos()
921                                 && par.isSeparator(left_pos)) {
922                         pos_type const v_left_pos = bidi.log2vis(left_pos) - 1;
923                         if (!bidi.inRange(v_left_pos))
924                                 left_pos = -1;
925                         else
926                                 left_pos = bidi.vis2log(v_left_pos);
927                 }
928         }
929         return;
930 }
931
932
933 bool Cursor::posVisToNewRow(bool movingLeft)
934 {
935         Paragraph const & par = paragraph();
936         Buffer const & buf = *buffer();
937         Row const & row = textRow();
938         bool par_is_LTR = !par.isRTL(buf.params());
939
940         // Inside a table, determining whether to move to the next or
941         // previous row should be done based on the table's direction.
942         int s = depth() - 1;
943         if (s >= 1 && (*this)[s].inset().asInsetTabular()) {
944                 par_is_LTR = !(*this)[s].inset().asInsetTabular()->isRightToLeft(*this);
945                 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
946         }
947
948         // if moving left in an LTR paragraph or moving right in an
949         // RTL one, move to previous row
950         if (par_is_LTR == movingLeft) {
951                 if (row.pos() == 0) { // we're at first row in paragraph
952                         if (pit() == 0) // no previous paragraph! don't move
953                                 return false;
954                         // move to last pos in previous par
955                         --pit();
956                         pos() = lastpos();
957                         boundary(false);
958                 } else { // move to previous row in this par
959                         pos() = row.pos() - 1; // this is guaranteed to be in previous row
960                         boundary(false);
961                 }
962         }
963         // if moving left in an RTL paragraph or moving right in an
964         // LTR one, move to next row
965         else {
966                 if (row.endpos() == lastpos()) { // we're at last row in paragraph
967                         if (pit() == lastpit()) // last paragraph! don't move
968                                 return false;
969                         // move to first row in next par
970                         ++pit();
971                         pos() = 0;
972                         boundary(false);
973                 } else { // move to next row in this par
974                         pos() = row.endpos();
975                         boundary(false);
976                 }
977         }
978
979         // make sure we're at left-/right-most pos in new row
980         posVisToRowExtremity(!movingLeft);
981
982         return true;
983 }
984
985
986 void Cursor::posVisToRowExtremity(bool left)
987 {
988         // prepare bidi tables
989         Paragraph const & par = paragraph();
990         Buffer const & buf = *buffer();
991         Row const & row = textRow();
992         Bidi bidi;
993         bidi.computeTables(par, buf, row);
994
995         LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
996                 << (boundary() ? 1 : 0));
997
998         if (left) { // move to leftmost position
999                 // if this is an RTL paragraph, and we're at the last row in the
1000                 // paragraph, move to lastpos
1001                 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
1002                         pos() = lastpos();
1003                 else {
1004                         pos() = bidi.vis2log(row.pos());
1005
1006                         // Moving to the leftmost position in the row,
1007                         // the cursor should normally be placed to the
1008                         // *left* of the leftmost position. A very
1009                         // common exception, though, is if the
1010                         // leftmost character also happens to be the
1011                         // separator at the (logical) end of the row
1012                         // --- in this case, the separator is
1013                         // positioned beyond the left margin, and we
1014                         // don't want to move the cursor there (moving
1015                         // to the left of the separator is equivalent
1016                         // to moving to the next line). So, in this
1017                         // case we actually want to place the cursor
1018                         // to the *right* of the leftmost position
1019                         // (the separator). Another exception is if
1020                         // we're moving to the logically last position
1021                         // in the row, which is *not* a separator:
1022                         // this means that the entire row has no
1023                         // separators (if there were any, the row
1024                         // would have been broken there); and
1025                         // therefore in this case we also move to the
1026                         // *right* of the last position (this
1027                         // indicates to the user that there is no
1028                         // space after this position, and is
1029                         // consistent with the behavior in the middle
1030                         // of a row --- moving right or left moves to
1031                         // the next/previous character; if we were to
1032                         // move to the *left* of this position, that
1033                         // would simulate a separator which is not
1034                         // really there!). Finally, there is an
1035                         // exception to the previous exception: if
1036                         // this non-separator-but-last-position-in-row
1037                         // is an inset, then we *do* want to stay to
1038                         // the left of it anyway: this is the
1039                         // "boundary" which we simulate at insets.
1040
1041                         // Another exception is when row.endpos() is
1042                         // 0.
1043
1044                         // do we want to be to the right of pos?
1045                         // as explained above, if at last pos in row, stay to the right
1046                         bool const right_of_pos = row.endpos() > 0
1047                                 && pos() == row.endpos() - 1 && !par.isInset(pos());
1048
1049                         // Now we know if we want to be to the left or to the right of pos,
1050                         // let's make sure we are where we want to be.
1051                         bool const new_pos_is_RTL =
1052                                 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1053
1054                         if (new_pos_is_RTL != right_of_pos) {
1055                                 ++pos();
1056                                 boundary(true);
1057                         }
1058                 }
1059         } else {
1060                 // move to rightmost position
1061                 // if this is an LTR paragraph, and we're at the last row in the
1062                 // paragraph, move to lastpos
1063                 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
1064                         pos() = lastpos();
1065                 else {
1066                         pos() = row.endpos() > 0 ? bidi.vis2log(row.endpos() - 1) : 0;
1067
1068                         // Moving to the rightmost position in the
1069                         // row, the cursor should normally be placed
1070                         // to the *right* of the rightmost position. A
1071                         // very common exception, though, is if the
1072                         // rightmost character also happens to be the
1073                         // separator at the (logical) end of the row
1074                         // --- in this case, the separator is
1075                         // positioned beyond the right margin, and we
1076                         // don't want to move the cursor there (moving
1077                         // to the right of the separator is equivalent
1078                         // to moving to the next line). So, in this
1079                         // case we actually want to place the cursor
1080                         // to the *left* of the rightmost position
1081                         // (the separator). Another exception is if
1082                         // we're moving to the logically last position
1083                         // in the row, which is *not* a separator:
1084                         // this means that the entire row has no
1085                         // separators (if there were any, the row
1086                         // would have been broken there); and
1087                         // therefore in this case we also move to the
1088                         // *left* of the last position (this indicates
1089                         // to the user that there is no space after
1090                         // this position, and is consistent with the
1091                         // behavior in the middle of a row --- moving
1092                         // right or left moves to the next/previous
1093                         // character; if we were to move to the
1094                         // *right* of this position, that would
1095                         // simulate a separator which is not really
1096                         // there!). Finally, there is an exception to
1097                         // the previous exception: if this
1098                         // non-separator-but-last-position-in-row is
1099                         // an inset, then we *do* want to stay to the
1100                         // right of it anyway: this is the "boundary"
1101                         // which we simulate at insets. Another
1102                         // exception is when row.endpos() is 0.
1103
1104                         // do we want to be to the left of pos?
1105                         // as explained above, if at last pos in row, stay to the left,
1106                         // unless the last position is the same as the first.
1107                         bool const left_of_pos = row.endpos() > 0
1108                                 && pos() == row.endpos() - 1 && !par.isInset(pos());
1109
1110                         // Now we know if we want to be to the left or to the right of pos,
1111                         // let's make sure we are where we want to be.
1112                         bool const new_pos_is_RTL =
1113                                 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
1114
1115                         if (new_pos_is_RTL == left_of_pos) {
1116                                 ++pos();
1117                                 boundary(true);
1118                         }
1119                 }
1120         }
1121         LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1122                 << (boundary() ? 1 : 0));
1123 }
1124
1125
1126 CursorSlice Cursor::normalAnchor() const
1127 {
1128         if (!selection())
1129                 return top();
1130         // LASSERT: There have been several bugs around this code, that seem
1131         // to involve failures to reset the anchor. We can at least not crash
1132         // in release mode by resetting it ourselves.
1133         LASSERT(anchor_.depth() >= depth(),
1134                 const_cast<DocIterator &>(anchor_) = *this);
1135
1136         CursorSlice normal = anchor_[depth() - 1];
1137         if (depth() < anchor_.depth() && top() <= normal) {
1138                 // anchor is behind cursor -> move anchor behind the inset
1139                 ++normal.pos();
1140         }
1141         return normal;
1142 }
1143
1144
1145 DocIterator & Cursor::realAnchor()
1146 {
1147         return anchor_;
1148 }
1149
1150
1151 CursorSlice Cursor::selBegin() const
1152 {
1153         if (!selection())
1154                 return top();
1155         return normalAnchor() < top() ? normalAnchor() : top();
1156 }
1157
1158
1159 CursorSlice Cursor::selEnd() const
1160 {
1161         if (!selection())
1162                 return top();
1163         return normalAnchor() > top() ? normalAnchor() : top();
1164 }
1165
1166
1167 DocIterator Cursor::selectionBegin() const
1168 {
1169         if (!selection())
1170                 return *this;
1171
1172         DocIterator di;
1173         // FIXME: This is a work-around for the problem that
1174         // CursorSlice doesn't keep track of the boundary.
1175         if (normalAnchor() == top())
1176                 di = anchor_.boundary() > boundary() ? anchor_ : *this;
1177         else
1178                 di = normalAnchor() < top() ? anchor_ : *this;
1179         di.resize(depth());
1180         return di;
1181 }
1182
1183
1184 DocIterator Cursor::selectionEnd() const
1185 {
1186         if (!selection())
1187                 return *this;
1188
1189         DocIterator di;
1190         // FIXME: This is a work-around for the problem that
1191         // CursorSlice doesn't keep track of the boundary.
1192         if (normalAnchor() == top())
1193                 di = anchor_.boundary() < boundary() ? anchor_ : *this;
1194         else
1195                 di = normalAnchor() > top() ? anchor_ : *this;
1196
1197         if (di.depth() > depth()) {
1198                 di.resize(depth());
1199                 ++di.pos();
1200         }
1201         return di;
1202 }
1203
1204
1205 void Cursor::setSelection()
1206 {
1207         setSelection(true);
1208         if (idx() == normalAnchor().idx() &&
1209             pit() == normalAnchor().pit() &&
1210             pos() == normalAnchor().pos())
1211                 setSelection(false);
1212 }
1213
1214
1215 void Cursor::setSelection(DocIterator const & where, int n)
1216 {
1217         setCursor(where);
1218         setSelection(true);
1219         anchor_ = where;
1220         pos() += n;
1221 }
1222
1223
1224 void Cursor::clearSelection()
1225 {
1226         setSelection(false);
1227         setWordSelection(false);
1228         setMark(false);
1229         resetAnchor();
1230 }
1231
1232
1233 void Cursor::setTargetX(int x)
1234 {
1235         x_target_ = x;
1236         textTargetOffset_ = 0;
1237 }
1238
1239
1240 int Cursor::x_target() const
1241 {
1242         return x_target_;
1243 }
1244
1245
1246 void Cursor::clearTargetX()
1247 {
1248         x_target_ = -1;
1249         textTargetOffset_ = 0;
1250 }
1251
1252
1253 void Cursor::updateTextTargetOffset()
1254 {
1255         int x;
1256         int y;
1257         getPos(x, y);
1258         textTargetOffset_ = x - x_target_;
1259 }
1260
1261
1262 void Cursor::info(odocstream & os) const
1263 {
1264         for (int i = 1, n = depth(); i < n; ++i) {
1265                 operator[](i).inset().infoize(os);
1266                 os << "  ";
1267         }
1268         if (pos() != 0) {
1269                 Inset const * inset = prevInset();
1270                 // prevInset() can return 0 in certain case.
1271                 if (inset)
1272                         prevInset()->infoize2(os);
1273         }
1274         // overwite old message
1275         os << "                    ";
1276 }
1277
1278
1279 bool Cursor::selHandle(bool sel)
1280 {
1281         //lyxerr << "Cursor::selHandle" << endl;
1282         if (mark())
1283                 sel = true;
1284         if (sel == selection())
1285                 return false;
1286
1287         if (!sel)
1288                 cap::saveSelection(*this);
1289
1290         resetAnchor();
1291         setSelection(sel);
1292         return true;
1293 }
1294
1295
1296 ostream & operator<<(ostream & os, Cursor const & cur)
1297 {
1298         os << "\n cursor:                                | anchor:\n";
1299         for (size_t i = 0, n = cur.depth(); i != n; ++i) {
1300                 os << " " << cur[i] << " | ";
1301                 if (i < cur.anchor_.depth())
1302                         os << cur.anchor_[i];
1303                 else
1304                         os << "-------------------------------";
1305                 os << "\n";
1306         }
1307         for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
1308                 os << "------------------------------- | " << cur.anchor_[i] << "\n";
1309         }
1310         os << " selection: " << cur.selection_
1311            << " x_target: " << cur.x_target_
1312            << " boundary: " << cur.boundary() << endl;
1313         return os;
1314 }
1315
1316
1317 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
1318 {
1319         os.stream() << cur;
1320         return os;
1321 }
1322
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         anchor_.sanitize();
2354 }
2355
2356
2357 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2358 {
2359         // find inset in common
2360         size_type i;
2361         for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2362                 if (&old[i].inset() != &cur[i].inset())
2363                         break;
2364         }
2365
2366         // update words if we just moved to another paragraph
2367         if (i == old.depth() && i == cur.depth()
2368             && !cur.buffer()->isClean()
2369             && cur.inTexted() && old.inTexted()
2370             && cur.pit() != old.pit()) {
2371                 old.paragraph().updateWords();
2372         }
2373
2374         // notify everything on top of the common part in old cursor,
2375         // but stop if the inset claims the cursor to be invalid now
2376         for (size_type j = i; j < old.depth(); ++j) {
2377                 Cursor inset_pos = old;
2378                 inset_pos.cutOff(j);
2379                 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2380                         return true;
2381         }
2382
2383         // notify everything on top of the common part in new cursor,
2384         // but stop if the inset claims the cursor to be invalid now
2385         for (; i < cur.depth(); ++i) {
2386                 if (cur[i].inset().notifyCursorEnters(cur))
2387                         return true;
2388         }
2389
2390         return false;
2391 }
2392
2393
2394 void Cursor::setCurrentFont()
2395 {
2396         CursorSlice const & cs = innerTextSlice();
2397         Paragraph const & par = cs.paragraph();
2398         pos_type cpit = cs.pit();
2399         pos_type cpos = cs.pos();
2400         Text const & ctext = *cs.text();
2401         TextMetrics const & tm = bv().textMetrics(&ctext);
2402
2403         // are we behind previous char in fact? -> go to that char
2404         if (cpos > 0 && boundary())
2405                 --cpos;
2406
2407         // find position to take the font from
2408         if (cpos != 0) {
2409                 // paragraph end? -> font of last char
2410                 if (cpos == lastpos())
2411                         --cpos;
2412                 // on space? -> look at the words in front of space
2413                 else if (cpos > 0 && par.isSeparator(cpos))     {
2414                         // abc| def -> font of c
2415                         // abc |[WERBEH], i.e. boundary==true -> font of c
2416                         // abc [WERBEH]| def, font of the space
2417                         if (!tm.isRTLBoundary(cpit, cpos))
2418                                 --cpos;
2419                 }
2420         }
2421
2422         // get font
2423         BufferParams const & bufparams = buffer()->params();
2424         current_font = par.getFontSettings(bufparams, cpos);
2425         real_current_font = tm.displayFont(cpit, cpos);
2426
2427         // special case for paragraph end
2428         if (cs.pos() == lastpos()
2429             && tm.isRTLBoundary(cpit, cs.pos())
2430             && !boundary()) {
2431                 Language const * lang = par.getParLanguage(bufparams);
2432                 current_font.setLanguage(lang);
2433                 current_font.fontInfo().setNumber(FONT_OFF);
2434                 real_current_font.setLanguage(lang);
2435                 real_current_font.fontInfo().setNumber(FONT_OFF);
2436         }
2437 }
2438
2439
2440 bool Cursor::textUndo()
2441 {
2442         if (!buffer()->undo().textUndo(*this))
2443                 return false;
2444         sanitize();
2445         return true;
2446 }
2447
2448
2449 bool Cursor::textRedo()
2450 {
2451         if (!buffer()->undo().textRedo(*this))
2452                 return false;
2453         sanitize();
2454         return true;
2455 }
2456
2457
2458 void Cursor::finishUndo() const
2459 {
2460         buffer()->undo().finishUndo();
2461 }
2462
2463
2464 void Cursor::beginUndoGroup() const
2465 {
2466         buffer()->undo().beginUndoGroup();
2467 }
2468
2469
2470 void Cursor::endUndoGroup() const
2471 {
2472         buffer()->undo().endUndoGroup(*this);
2473 }
2474
2475
2476 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to) const
2477 {
2478         buffer()->undo().recordUndo(*this, kind, from, to);
2479 }
2480
2481
2482 void Cursor::recordUndo(UndoKind kind, pit_type from) const
2483 {
2484         buffer()->undo().recordUndo(*this, kind, from);
2485 }
2486
2487
2488 void Cursor::recordUndo(UndoKind kind) const
2489 {
2490         buffer()->undo().recordUndo(*this, kind);
2491 }
2492
2493
2494 void Cursor::recordUndoInset(UndoKind kind, Inset const * inset) const
2495 {
2496         buffer()->undo().recordUndoInset(*this, kind, inset);
2497 }
2498
2499
2500 void Cursor::recordUndoFullBuffer() const
2501 {
2502         buffer()->undo().recordUndoFullBuffer(*this);
2503 }
2504
2505
2506 void Cursor::recordUndoBufferParams() const
2507 {
2508         buffer()->undo().recordUndoBufferParams(*this);
2509 }
2510
2511
2512 void Cursor::recordUndoSelection() const
2513 {
2514         if (inMathed()) {
2515                 if (cap::multipleCellsSelected(*this))
2516                         recordUndoInset();
2517                 else
2518                         recordUndo();
2519         } else {
2520                 buffer()->undo().recordUndo(*this, ATOMIC_UNDO,
2521                         selBegin().pit(), selEnd().pit());
2522         }
2523 }
2524
2525
2526 void Cursor::checkBufferStructure()
2527 {
2528         Buffer const * master = buffer()->masterBuffer();
2529         master->tocBackend().updateItem(*this);
2530         if (master != buffer() && !master->hasGuiDelegate())
2531                 // In case the master has no gui associated with it,
2532                 // the TocItem is not updated (part of bug 5699).
2533                 buffer()->tocBackend().updateItem(*this);
2534 }
2535
2536
2537 } // namespace lyx