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