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