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