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