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