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