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