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