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