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