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