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