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