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