]> git.lyx.org Git - lyx.git/blob - src/Cursor.cpp
some de-boostification
[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 André Pönitz
9  * \author Stefan Schimanski
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "Bidi.h"
17 #include "BufferView.h"
18 #include "Buffer.h"
19 #include "Cursor.h"
20 #include "CoordCache.h"
21 #include "CutAndPaste.h"
22 #include "DispatchResult.h"
23 #include "Encoding.h"
24 #include "FuncRequest.h"
25 #include "Language.h"
26 #include "lfuns.h"
27 #include "Font.h"
28 #include "LyXFunc.h" // only for setMessage()
29 #include "LyXRC.h"
30 #include "Row.h"
31 #include "Text.h"
32 #include "Paragraph.h"
33 #include "paragraph_funcs.h"
34 #include "ParIterator.h"
35 #include "TextMetrics.h"
36
37 #include "support/debug.h"
38 #include "support/docstream.h"
39
40 #include "insets/InsetTabular.h"
41 #include "insets/InsetText.h"
42
43 #include "mathed/InsetMath.h"
44 #include "mathed/InsetMathScript.h"
45 #include "mathed/MacroTable.h"
46 #include "mathed/MathData.h"
47 #include "mathed/MathMacro.h"
48
49 #include <boost/assert.hpp>
50 #include <boost/bind.hpp>
51 #include <boost/current_function.hpp>
52
53 #include <sstream>
54 #include <limits>
55 #include <map>
56
57 using std::string;
58 using std::vector;
59 using std::endl;
60 using std::min;
61 using std::for_each;
62
63
64 namespace lyx {
65
66 namespace {
67
68 bool positionable(DocIterator const & cursor, DocIterator const & anchor)
69 {
70         // avoid deeper nested insets when selecting
71         if (cursor.depth() > anchor.depth())
72                 return false;
73
74         // anchor might be deeper, should have same path then
75         for (size_t i = 0; i < cursor.depth(); ++i)
76                 if (&cursor[i].inset() != &anchor[i].inset())
77                         return false;
78
79         // position should be ok.
80         return true;
81 }
82
83
84 // Find position closest to (x, y) in cell given by iter.
85 // Used only in mathed
86 DocIterator bruteFind2(Cursor const & c, int x, int y)
87 {
88         double best_dist = std::numeric_limits<double>::max();
89
90         DocIterator result;
91
92         DocIterator it = c;
93         it.top().pos() = 0;
94         DocIterator et = c;
95         et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
96         for (size_t i = 0;; ++i) {
97                 int xo;
98                 int yo;
99                 Inset const * inset = &it.inset();
100                 std::map<Inset const *, Geometry> const & data =
101                         c.bv().coordCache().getInsets().getData();
102                 std::map<Inset const *, Geometry>::const_iterator I = data.find(inset);
103
104                 // FIXME: in the case where the inset is not in the cache, this
105                 // means that no part of it is visible on screen. In this case
106                 // we don't do elaborate search and we just return the forwarded
107                 // DocIterator at its beginning.
108                 if (I == data.end()) {
109                         it.top().pos() = 0;
110                         return it;
111                 }
112
113                 Point o = I->second.pos;
114                 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
115                 // Convert to absolute
116                 xo += o.x_;
117                 yo += o.y_;
118                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
119                 // '<=' in order to take the last possible position
120                 // this is important for clicking behind \sum in e.g. '\sum_i a'
121                 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
122                         << " best: " << best_dist);
123                 if (d <= best_dist) {
124                         best_dist = d;
125                         result = it;
126                 }
127                 if (it == et)
128                         break;
129                 it.forwardPos();
130         }
131         return result;
132 }
133
134
135 /*
136 /// moves position closest to (x, y) in given box
137 bool bruteFind(Cursor & cursor,
138         int x, int y, int xlow, int xhigh, int ylow, int yhigh)
139 {
140         BOOST_ASSERT(!cursor.empty());
141         Inset & inset = cursor[0].inset();
142         BufferView & bv = cursor.bv();
143
144         CoordCache::InnerParPosCache const & cache =
145                 bv.coordCache().getParPos().find(cursor.bottom().text())->second;
146         // Get an iterator on the first paragraph in the cache
147         DocIterator it(inset);
148         it.push_back(CursorSlice(inset));
149         it.pit() = cache.begin()->first;
150         // Get an iterator after the last paragraph in the cache
151         DocIterator et(inset);
152         et.push_back(CursorSlice(inset));
153         et.pit() = boost::prior(cache.end())->first;
154         if (et.pit() >= et.lastpit())
155                 et = doc_iterator_end(inset);
156         else
157                 ++et.pit();
158
159         double best_dist = std::numeric_limits<double>::max();;
160         DocIterator best_cursor = et;
161
162         for ( ; it != et; it.forwardPos(true)) {
163                 // avoid invalid nesting when selecting
164                 if (!cursor.selection() || positionable(it, cursor.anchor_)) {
165                         Point p = bv.getPos(it, false);
166                         int xo = p.x_;
167                         int yo = p.y_;
168                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
169                                 double const dx = xo - x;
170                                 double const dy = yo - y;
171                                 double const d = dx * dx + dy * dy;
172                                 // '<=' in order to take the last possible position
173                                 // this is important for clicking behind \sum in e.g. '\sum_i a'
174                                 if (d <= best_dist) {
175                                         //      lyxerr << "*" << endl;
176                                         best_dist   = d;
177                                         best_cursor = it;
178                                 }
179                         }
180                 }
181         }
182
183         if (best_cursor != et) {
184                 cursor.setCursor(best_cursor);
185                 return true;
186         }
187
188         return false;
189 }
190 */
191
192
193 /// moves position closest to (x, y) in given box
194 bool bruteFind3(Cursor & cur, int x, int y, bool up)
195 {
196         BufferView & bv = cur.bv();
197         int ylow  = up ? 0 : y + 1;
198         int yhigh = up ? y - 1 : bv.workHeight();
199         int xlow = 0;
200         int xhigh = bv.workWidth();
201
202 // FIXME: bit more work needed to get 'from' and 'to' right.
203         pit_type from = cur.bottom().pit();
204         //pit_type to = cur.bottom().pit();
205         //lyxerr << "Pit start: " << from << endl;
206
207         //lyxerr << "bruteFind3: x: " << x << " y: " << y
208         //      << " xlow: " << xlow << " xhigh: " << xhigh
209         //      << " ylow: " << ylow << " yhigh: " << yhigh
210         //      << endl;
211         Inset & inset = bv.buffer().inset();
212         DocIterator it = doc_iterator_begin(inset);
213         it.pit() = from;
214         DocIterator et = doc_iterator_end(inset);
215
216         double best_dist = std::numeric_limits<double>::max();
217         DocIterator best_cursor = et;
218
219         for ( ; it != et; it.forwardPos()) {
220                 // avoid invalid nesting when selecting
221                 if (bv.cursorStatus(it) == CUR_INSIDE
222                                 && (!cur.selection() || positionable(it, cur.anchor_))) {
223                         Point p = bv.getPos(it, false);
224                         int xo = p.x_;
225                         int yo = p.y_;
226                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
227                                 double const dx = xo - x;
228                                 double const dy = yo - y;
229                                 double const d = dx * dx + dy * dy;
230                                 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
231                                 //      << " dx: " << dx << " dy: " << dy
232                                 //      << " idx: " << it.idx() << " pos: " << it.pos()
233                                 //      << " it:\n" << it
234                                 //      << endl;
235                                 // '<=' in order to take the last possible position
236                                 // this is important for clicking behind \sum in e.g. '\sum_i a'
237                                 if (d <= best_dist) {
238                                         //lyxerr << "*" << endl;
239                                         best_dist   = d;
240                                         best_cursor = it;
241                                 }
242                         }
243                 }
244         }
245
246         //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
247         if (best_cursor == et)
248                 return false;
249         cur.setCursor(best_cursor);
250         return true;
251 }
252
253 docstring parbreak(Paragraph const & par)
254 {
255         odocstringstream ods;
256         ods << '\n';
257         // only add blank line if we're not in an ERT or Listings inset
258         if (par.ownerCode() != ERT_CODE
259                         && par.ownerCode() != LISTINGS_CODE)
260                 ods << '\n';
261         return ods.str();
262 }
263
264 } // namespace anon
265
266
267 // be careful: this is called from the bv's constructor, too, so
268 // bv functions are not yet available!
269 Cursor::Cursor(BufferView & bv)
270         : DocIterator(), bv_(&bv), anchor_(), x_target_(-1), textTargetOffset_(0),
271           selection_(false), mark_(false), logicalpos_(false),
272           current_font(inherit_font)
273 {}
274
275
276 void Cursor::reset(Inset & inset)
277 {
278         clear();
279         push_back(CursorSlice(inset));
280         anchor_ = DocIterator(inset);
281         clearTargetX();
282         selection_ = false;
283         mark_ = false;
284 }
285
286
287 // this (intentionally) does neither touch anchor nor selection status
288 void Cursor::setCursor(DocIterator const & cur)
289 {
290         DocIterator::operator=(cur);
291 }
292
293
294 void Cursor::dispatch(FuncRequest const & cmd0)
295 {
296         LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION
297                              << " cmd: " << cmd0 << '\n' << *this);
298         if (empty())
299                 return;
300
301         fixIfBroken();
302         FuncRequest cmd = cmd0;
303         Cursor safe = *this;
304         
305         // store some values to be used inside of the handlers
306         getPos(beforeDispX_, beforeDispY_);
307         beforeDispatchCursor_ = *this;
308         for (; depth(); pop()) {
309                 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
310                         << cmd0 << endl << *this);
311                 BOOST_ASSERT(pos() <= lastpos());
312                 BOOST_ASSERT(idx() <= lastidx());
313                 BOOST_ASSERT(pit() <= lastpit());
314
315                 // The common case is 'LFUN handled, need update', so make the
316                 // LFUN handler's life easier by assuming this as default value.
317                 // The handler can reset the update and val flags if necessary.
318                 disp_.update(Update::FitCursor | Update::Force);
319                 disp_.dispatched(true);
320                 inset().dispatch(*this, cmd);
321                 if (disp_.dispatched())
322                         break;
323         }
324         
325         // it completely to get a 'bomb early' behaviour in case this
326         // object will be used again.
327         if (!disp_.dispatched()) {
328                 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
329                 operator=(safe);
330                 disp_.update(Update::None);
331                 disp_.dispatched(false);
332         } else {
333                 // restore the previous one because nested Cursor::dispatch calls
334                 // are possible which would change it
335                 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
336         }
337 }
338
339
340 DispatchResult Cursor::result() const
341 {
342         return disp_;
343 }
344
345
346 BufferView & Cursor::bv() const
347 {
348         BOOST_ASSERT(bv_);
349         return *bv_;
350 }
351
352
353 Buffer & Cursor::buffer() const
354 {
355         BOOST_ASSERT(bv_);
356         return bv_->buffer();
357 }
358
359
360 void Cursor::pop()
361 {
362         BOOST_ASSERT(depth() >= 1);
363         pop_back();
364 }
365
366
367 void Cursor::push(Inset & p)
368 {
369         push_back(CursorSlice(p));
370 }
371
372
373 void Cursor::pushBackward(Inset & p)
374 {
375         BOOST_ASSERT(!empty());
376         //lyxerr << "Entering inset " << t << " front" << endl;
377         push(p);
378         p.idxFirst(*this);
379 }
380
381
382 bool Cursor::popBackward()
383 {
384         BOOST_ASSERT(!empty());
385         //lyxerr << "Leaving inset from in front" << endl;
386         inset().notifyCursorLeaves(*this);
387         if (depth() == 1)
388                 return false;
389         pop();
390         return true;
391 }
392
393
394 bool Cursor::popForward()
395 {
396         BOOST_ASSERT(!empty());
397         //lyxerr << "Leaving inset from in back" << endl;
398         const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
399         inset().notifyCursorLeaves(*this);
400         if (depth() == 1)
401                 return false;
402         pop();
403         pos() += lastpos() - lp + 1;
404         return true;
405 }
406
407
408 int Cursor::currentMode()
409 {
410         BOOST_ASSERT(!empty());
411         for (int i = depth() - 1; i >= 0; --i) {
412                 int res = operator[](i).inset().currentMode();
413                 if (res != Inset::UNDECIDED_MODE)
414                         return res;
415         }
416         return Inset::TEXT_MODE;
417 }
418
419
420 void Cursor::getPos(int & x, int & y) const
421 {
422         Point p = bv().getPos(*this, boundary());
423         x = p.x_;
424         y = p.y_;
425 }
426
427
428 Row const & Cursor::textRow() const
429 {
430         ParagraphMetrics const & pm = bv().parMetrics(text(), pit());
431         BOOST_ASSERT(!pm.rows().empty());
432         return pm.getRow(pos(), boundary());
433 }
434
435
436 void Cursor::resetAnchor()
437 {
438         anchor_ = *this;
439 }
440
441
442
443 bool Cursor::posBackward()
444 {
445         if (pos() == 0)
446                 return false;
447         --pos();
448         return true;
449 }
450
451
452 bool Cursor::posForward()
453 {
454         if (pos() == lastpos())
455                 return false;
456         ++pos();
457         return true;
458 }
459
460
461 CursorSlice Cursor::anchor() const
462 {
463         BOOST_ASSERT(anchor_.depth() >= depth());
464         CursorSlice normal = anchor_[depth() - 1];
465         if (depth() < anchor_.depth() && top() <= normal) {
466                 // anchor is behind cursor -> move anchor behind the inset
467                 ++normal.pos();
468         }
469         return normal;
470 }
471
472
473 CursorSlice Cursor::selBegin() const
474 {
475         if (!selection())
476                 return top();
477         return anchor() < top() ? anchor() : top();
478 }
479
480
481 CursorSlice Cursor::selEnd() const
482 {
483         if (!selection())
484                 return top();
485         return anchor() > top() ? anchor() : top();
486 }
487
488
489 DocIterator Cursor::selectionBegin() const
490 {
491         if (!selection())
492                 return *this;
493         DocIterator di = (anchor() < top() ? anchor_ : *this);
494         di.resize(depth());
495         return di;
496 }
497
498
499 DocIterator Cursor::selectionEnd() const
500 {
501         if (!selection())
502                 return *this;
503         DocIterator di = (anchor() > top() ? anchor_ : *this);
504         if (di.depth() > depth()) {
505                 di.resize(depth());
506                 ++di.pos();
507         }
508         return di;
509 }
510
511
512 void Cursor::setSelection()
513 {
514         selection() = true;
515         // A selection with no contents is not a selection
516         // FIXME: doesnt look ok
517         if (pit() == anchor().pit() && pos() == anchor().pos())
518                 selection() = false;
519 }
520
521
522 void Cursor::setSelection(DocIterator const & where, int n)
523 {
524         setCursor(where);
525         selection() = true;
526         anchor_ = where;
527         pos() += n;
528 }
529
530
531 void Cursor::clearSelection()
532 {
533         selection() = false;
534         mark() = false;
535         resetAnchor();
536 }
537
538
539 void Cursor::setTargetX(int x)
540 {
541         x_target_ = x;
542         textTargetOffset_ = 0;
543 }
544
545
546 int Cursor::x_target() const
547 {
548         return x_target_;
549 }
550
551
552 void Cursor::clearTargetX()
553 {
554         x_target_ = -1;
555         textTargetOffset_ = 0;
556 }
557
558
559 void Cursor::updateTextTargetOffset()
560 {
561         int x;
562         int y;
563         getPos(x, y);
564         textTargetOffset_ = x - x_target_;
565 }
566
567
568 void Cursor::info(odocstream & os) const
569 {
570         for (int i = 1, n = depth(); i < n; ++i) {
571                 operator[](i).inset().infoize(os);
572                 os << "  ";
573         }
574         if (pos() != 0) {
575                 Inset const * inset = prevInset();
576                 // prevInset() can return 0 in certain case.
577                 if (inset)
578                         prevInset()->infoize2(os);
579         }
580         // overwite old message
581         os << "                    ";
582 }
583
584
585 bool Cursor::selHandle(bool sel)
586 {
587         //lyxerr << "Cursor::selHandle" << endl;
588         if (sel == selection())
589                 return false;
590
591         if (!sel)
592                 cap::saveSelection(*this);
593
594         resetAnchor();
595         selection() = sel;
596         return true;
597 }
598
599
600 std::ostream & operator<<(std::ostream & os, Cursor const & cur)
601 {
602         os << "\n cursor:                                | anchor:\n";
603         for (size_t i = 0, n = cur.depth(); i != n; ++i) {
604                 os << " " << cur[i] << " | ";
605                 if (i < cur.anchor_.depth())
606                         os << cur.anchor_[i];
607                 else
608                         os << "-------------------------------";
609                 os << "\n";
610         }
611         for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
612                 os << "------------------------------- | " << cur.anchor_[i] << "\n";
613         }
614         os << " selection: " << cur.selection_
615            << " x_target: " << cur.x_target_ << endl;
616         return os;
617 }
618
619
620 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
621 {
622         os.stream() << cur;
623         return os;
624 }
625
626
627 } // namespace lyx
628
629
630 ///////////////////////////////////////////////////////////////////
631 //
632 // FIXME: Look here
633 // The part below is the non-integrated rest of the original math
634 // cursor. This should be either generalized for texted or moved
635 // back to mathed (in most cases to InsetMathNest).
636 //
637 ///////////////////////////////////////////////////////////////////
638
639 #include "mathed/InsetMathChar.h"
640 #include "mathed/InsetMathGrid.h"
641 #include "mathed/InsetMathScript.h"
642 #include "mathed/InsetMathUnknown.h"
643 #include "mathed/MathFactory.h"
644 #include "mathed/MathStream.h"
645 #include "mathed/MathSupport.h"
646
647
648 namespace lyx {
649
650 //#define FILEDEBUG 1
651
652
653 bool Cursor::isInside(Inset const * p)
654 {
655         for (size_t i = 0; i != depth(); ++i)
656                 if (&operator[](i).inset() == p)
657                         return true;
658         return false;
659 }
660
661
662 void Cursor::leaveInset(Inset const & inset)
663 {
664         for (size_t i = 0; i != depth(); ++i) {
665                 if (&operator[](i).inset() == &inset) {
666                         resize(i);
667                         return;
668                 }
669         }
670 }
671
672
673 bool Cursor::openable(MathAtom const & t) const
674 {
675         if (!t->isActive())
676                 return false;
677
678         if (t->lock())
679                 return false;
680
681         if (!selection())
682                 return true;
683
684         // we can't move into anything new during selection
685         if (depth() >= anchor_.depth())
686                 return false;
687         if (t.nucleus() != &anchor_[depth()].inset())
688                 return false;
689
690         return true;
691 }
692
693
694 void Cursor::setScreenPos(int x, int /*y*/)
695 {
696         setTargetX(x);
697         //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
698 }
699
700
701
702 void Cursor::plainErase()
703 {
704         cell().erase(pos());
705 }
706
707
708 void Cursor::markInsert()
709 {
710         insert(char_type(0));
711 }
712
713
714 void Cursor::markErase()
715 {
716         cell().erase(pos());
717 }
718
719
720 void Cursor::plainInsert(MathAtom const & t)
721 {
722         cell().insert(pos(), t);
723         ++pos();
724 }
725
726
727 void Cursor::insert(docstring const & str)
728 {
729         for_each(str.begin(), str.end(),
730                  boost::bind(static_cast<void(Cursor::*)(char_type)>
731                              (&Cursor::insert), this, _1));
732 }
733
734
735 void Cursor::insert(char_type c)
736 {
737         //lyxerr << "Cursor::insert char '" << c << "'" << endl;
738         BOOST_ASSERT(!empty());
739         if (inMathed()) {
740                 cap::selClearOrDel(*this);
741                 insert(new InsetMathChar(c));
742         } else {
743                 text()->insertChar(*this, c);
744         }
745 }
746
747
748 void Cursor::insert(MathAtom const & t)
749 {
750         //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
751         macroModeClose();
752         cap::selClearOrDel(*this);
753         plainInsert(t);
754 }
755
756
757 void Cursor::insert(Inset * inset)
758 {
759         if (inMathed())
760                 insert(MathAtom(inset));
761         else
762                 text()->insertInset(*this, inset);
763 }
764
765
766 void Cursor::niceInsert(docstring const & t)
767 {
768         MathData ar;
769         asArray(t, ar);
770         if (ar.size() == 1)
771                 niceInsert(ar[0]);
772         else
773                 insert(ar);
774 }
775
776
777 void Cursor::niceInsert(MathAtom const & t)
778 {
779         macroModeClose();
780         docstring const safe = cap::grabAndEraseSelection(*this);
781         plainInsert(t);
782         // enter the new inset and move the contents of the selection if possible
783         if (t->isActive()) {
784                 posBackward();
785                 // be careful here: don't use 'pushBackward(t)' as this we need to
786                 // push the clone, not the original
787                 pushBackward(*nextInset());
788                 // We may not use niceInsert here (recursion)
789                 MathData ar;
790                 asArray(safe, ar);
791                 insert(ar);
792         }
793 }
794
795
796 void Cursor::insert(MathData const & ar)
797 {
798         macroModeClose();
799         if (selection())
800                 cap::eraseSelection(*this);
801         cell().insert(pos(), ar);
802         pos() += ar.size();
803 }
804
805
806 bool Cursor::backspace()
807 {
808         autocorrect() = false;
809
810         if (selection()) {
811                 cap::eraseSelection(*this);
812                 return true;
813         }
814
815         if (pos() == 0) {
816                 // If empty cell, and not part of a big cell
817                 if (lastpos() == 0 && inset().nargs() == 1) {
818                         popBackward();
819                         // Directly delete empty cell: [|[]] => [|]
820                         if (inMathed()) {
821                                 plainErase();
822                                 resetAnchor();
823                                 return true;
824                         }
825                         // [|], can not delete from inside
826                         return false;
827                 } else {
828                         if (inMathed())
829                                 pullArg();
830                         else
831                                 popBackward();
832                         return true;
833                 }
834         }
835
836         if (inMacroMode()) {
837                 InsetMathUnknown * p = activeMacro();
838                 if (p->name().size() > 1) {
839                         p->setName(p->name().substr(0, p->name().size() - 1));
840                         return true;
841                 }
842         }
843
844         if (pos() != 0 && prevAtom()->nargs() > 0) {
845                 // let's require two backspaces for 'big stuff' and
846                 // highlight on the first
847                 resetAnchor();
848                 selection() = true;
849                 --pos();
850         } else {
851                 --pos();
852                 plainErase();
853         }
854         return true;
855 }
856
857
858 bool Cursor::erase()
859 {
860         autocorrect() = false;
861         if (inMacroMode())
862                 return true;
863
864         if (selection()) {
865                 cap::eraseSelection(*this);
866                 return true;
867         }
868
869         // delete empty cells if possible
870         if (pos() == lastpos() && inset().idxDelete(idx()))
871                 return true;
872
873         // special behaviour when in last position of cell
874         if (pos() == lastpos()) {
875                 bool one_cell = inset().nargs() == 1;
876                 if (one_cell && lastpos() == 0) {
877                         popBackward();
878                         // Directly delete empty cell: [|[]] => [|]
879                         if (inMathed()) {
880                                 plainErase();
881                                 resetAnchor();
882                                 return true;
883                         }
884                         // [|], can not delete from inside
885                         return false;
886                 }
887                 // remove markup
888                 if (!one_cell)
889                         inset().idxGlue(idx());
890                 return true;
891         }
892
893         // 'clever' UI hack: only erase large items if previously slected
894         if (pos() != lastpos() && nextAtom()->nargs() > 0) {
895                 resetAnchor();
896                 selection() = true;
897                 ++pos();
898         } else {
899                 plainErase();
900         }
901
902         return true;
903 }
904
905
906 bool Cursor::up()
907 {
908         macroModeClose();
909         DocIterator save = *this;
910         FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
911         this->dispatch(cmd);
912         if (disp_.dispatched())
913                 return true;
914         setCursor(save);
915         autocorrect() = false;
916         return false;
917 }
918
919
920 bool Cursor::down()
921 {
922         macroModeClose();
923         DocIterator save = *this;
924         FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
925         this->dispatch(cmd);
926         if (disp_.dispatched())
927                 return true;
928         setCursor(save);
929         autocorrect() = false;
930         return false;
931 }
932
933
934 bool Cursor::macroModeClose()
935 {
936         if (!inMacroMode())
937                 return false;
938         InsetMathUnknown * p = activeMacro();
939         p->finalize();
940         docstring const s = p->name();
941         --pos();
942         cell().erase(pos());
943
944         // do nothing if the macro name is empty
945         if (s == "\\")
946                 return false;
947
948         // trigger updates of macros, at least, if no full
949         // updates take place anyway
950         updateFlags(Update::Force);
951
952         docstring const name = s.substr(1);
953         InsetMathNest * const in = inset().asInsetMath()->asNestInset();
954         if (in && in->interpretString(*this, s))
955                 return true;
956         MathAtom atom = createInsetMath(name);
957         MathMacro * atomAsMacro = atom.nucleus()->asMacro();
958         if (atomAsMacro) {
959                 // make non-greedy, i.e. don't eat parameters from the right
960                 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT);
961         }
962         plainInsert(atom);
963         return true;
964 }
965
966
967 docstring Cursor::macroName()
968 {
969         return inMacroMode() ? activeMacro()->name() : docstring();
970 }
971
972
973 void Cursor::handleNest(MathAtom const & a, int c)
974 {
975         //lyxerr << "Cursor::handleNest: " << c << endl;
976         MathAtom t = a;
977         asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
978         insert(t);
979         posBackward();
980         pushBackward(*nextInset());
981 }
982
983
984 int Cursor::targetX() const
985 {
986         if (x_target() != -1)
987                 return x_target();
988         int x = 0;
989         int y = 0;
990         getPos(x, y);
991         return x;
992 }
993
994
995 int Cursor::textTargetOffset() const
996 {
997         return textTargetOffset_;
998 }
999
1000
1001 void Cursor::setTargetX()
1002 {
1003         int x;
1004         int y;
1005         getPos(x, y);
1006         setTargetX(x);
1007 }
1008
1009
1010 bool Cursor::inMacroMode() const
1011 {
1012         if (!inMathed())
1013                 return false;
1014         if (pos() == 0)
1015                 return false;
1016         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1017         return p && !p->final();
1018 }
1019
1020
1021 InsetMathUnknown * Cursor::activeMacro()
1022 {
1023         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1024 }
1025
1026
1027 void Cursor::pullArg()
1028 {
1029         // FIXME: Look here
1030         MathData ar = cell();
1031         if (popBackward() && inMathed()) {
1032                 plainErase();
1033                 cell().insert(pos(), ar);
1034                 resetAnchor();
1035         } else {
1036                 //formula()->mutateToText();
1037         }
1038 }
1039
1040
1041 void Cursor::touch()
1042 {
1043         // FIXME: look here
1044 #if 0
1045         DocIterator::const_iterator it = begin();
1046         DocIterator::const_iterator et = end();
1047         for ( ; it != et; ++it)
1048                 it->cell().touch();
1049 #endif
1050 }
1051
1052
1053 void Cursor::normalize()
1054 {
1055         if (idx() > lastidx()) {
1056                 lyxerr << "this should not really happen - 1: "
1057                        << idx() << ' ' << nargs()
1058                        << " in: " << &inset() << endl;
1059                 idx() = lastidx();
1060         }
1061
1062         if (pos() > lastpos()) {
1063                 lyxerr << "this should not really happen - 2: "
1064                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1065                        << " in atom: '";
1066                 odocstringstream os;
1067                 WriteStream wi(os, false, true);
1068                 inset().asInsetMath()->write(wi);
1069                 lyxerr << to_utf8(os.str()) << endl;
1070                 pos() = lastpos();
1071         }
1072 }
1073
1074
1075 bool Cursor::upDownInMath(bool up)
1076 {
1077         // Be warned: The 'logic' implemented in this function is highly
1078         // fragile. A distance of one pixel or a '<' vs '<=' _really
1079         // matters. So fiddle around with it only if you think you know
1080         // what you are doing!
1081         int xo = 0;
1082         int yo = 0;
1083         getPos(xo, yo);
1084         xo = beforeDispX_;
1085
1086         // check if we had something else in mind, if not, this is the future
1087         // target
1088         if (x_target_ == -1)
1089                 setTargetX(xo);
1090         else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1091                 // In text mode inside the line (not left or right) possibly set a new target_x,
1092                 // but only if we are somewhere else than the previous target-offset.
1093                 
1094                 // We want to keep the x-target on subsequent up/down movements
1095                 // that cross beyond the end of short lines. Thus a special
1096                 // handling when the cursor is at the end of line: Use the new
1097                 // x-target only if the old one was before the end of line
1098                 // or the old one was after the beginning of the line
1099                 bool inRTL = isWithinRtlParagraph(*this);
1100                 bool left;
1101                 bool right;
1102                 if (inRTL) {
1103                         left = pos() == textRow().endpos();
1104                         right = pos() == textRow().pos();
1105                 } else {
1106                         left = pos() == textRow().pos();
1107                         right = pos() == textRow().endpos();
1108                 }
1109                 if ((!left && !right) ||
1110                                 (left && !right && xo < x_target_) ||
1111                                 (!left && right && x_target_ < xo))
1112                         setTargetX(xo);
1113                 else
1114                         xo = targetX();
1115         } else
1116                 xo = targetX();
1117
1118         // try neigbouring script insets
1119         Cursor old = *this;
1120         if (inMathed() && !selection()) {
1121                 // try left
1122                 if (pos() != 0) {
1123                         InsetMathScript const * p = prevAtom()->asScriptInset();
1124                         if (p && p->has(up)) {
1125                                 --pos();
1126                                 push(*const_cast<InsetMathScript*>(p));
1127                                 idx() = p->idxOfScript(up);
1128                                 pos() = lastpos();
1129                                 
1130                                 // we went in the right direction? Otherwise don't jump into the script
1131                                 int x;
1132                                 int y;
1133                                 getPos(x, y);
1134                                 if ((!up && y <= beforeDispY_) ||
1135                                                 (up && y >= beforeDispY_))
1136                                         operator=(old);
1137                                 else
1138                                         return true;
1139                         }
1140                 }
1141                 
1142                 // try right
1143                 if (pos() != lastpos()) {
1144                         InsetMathScript const * p = nextAtom()->asScriptInset();
1145                         if (p && p->has(up)) {
1146                                 push(*const_cast<InsetMathScript*>(p));
1147                                 idx() = p->idxOfScript(up);
1148                                 pos() = 0;
1149                                 
1150                                 // we went in the right direction? Otherwise don't jump into the script
1151                                 int x;
1152                                 int y;
1153                                 getPos(x, y);
1154                                 if ((!up && y <= beforeDispY_) ||
1155                                                 (up && y >= beforeDispY_))
1156                                         operator=(old);
1157                                 else
1158                                         return true;
1159                         }
1160                 }
1161         }
1162                 
1163         // try to find an inset that knows better then we,
1164         if (inset().idxUpDown(*this, up)) {
1165                 //lyxerr << "idxUpDown triggered" << endl;
1166                 // try to find best position within this inset
1167                 if (!selection())
1168                         setCursor(bruteFind2(*this, xo, yo));
1169                 return true;
1170         }
1171         
1172         // any improvement going just out of inset?
1173         if (popBackward() && inMathed()) {
1174                 //lyxerr << "updown: popBackward succeeded" << endl;
1175                 int xnew;
1176                 int ynew;
1177                 getPos(xnew, ynew);
1178                 if (up ? ynew < beforeDispY_ : ynew > beforeDispY_)
1179                         return true;
1180         }
1181         
1182         // no success, we are probably at the document top or bottom
1183         operator=(old);
1184         return false;
1185 }
1186
1187
1188 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1189 {
1190         BOOST_ASSERT(text());
1191
1192         // where are we?
1193         int xo = 0;
1194         int yo = 0;
1195         getPos(xo, yo);
1196         xo = beforeDispX_;
1197         
1198         // update the targetX - this is here before the "return false"
1199         // to set a new target which can be used by InsetTexts above
1200         // if we cannot move up/down inside this inset anymore
1201         if (x_target_ == -1)
1202                 setTargetX(xo);
1203         else if (xo - textTargetOffset() != x_target() &&
1204                                          depth() == beforeDispatchCursor_.depth()) {
1205                 // In text mode inside the line (not left or right) possibly set a new target_x,
1206                 // but only if we are somewhere else than the previous target-offset.
1207                 
1208                 // We want to keep the x-target on subsequent up/down movements
1209                 // that cross beyond the end of short lines. Thus a special
1210                 // handling when the cursor is at the end of line: Use the new
1211                 // x-target only if the old one was before the end of line
1212                 // or the old one was after the beginning of the line
1213                 bool inRTL = isWithinRtlParagraph(*this);
1214                 bool left;
1215                 bool right;
1216                 if (inRTL) {
1217                         left = pos() == textRow().endpos();
1218                         right = pos() == textRow().pos();
1219                 } else {
1220                         left = pos() == textRow().pos();
1221                         right = pos() == textRow().endpos();
1222                 }
1223                 if ((!left && !right) ||
1224                                 (left && !right && xo < x_target_) ||
1225                                 (!left && right && x_target_ < xo))
1226                         setTargetX(xo);
1227                 else
1228                         xo = targetX();
1229         } else
1230                 xo = targetX();
1231                 
1232         // first get the current line
1233         TextMetrics & tm = bv_->textMetrics(text());
1234         ParagraphMetrics const & pm = tm.parMetrics(pit());
1235         int row;
1236         if (pos() && boundary())
1237                 row = pm.pos2row(pos() - 1);
1238         else
1239                 row = pm.pos2row(pos());
1240                 
1241         // are we not at the start or end?
1242         if (up) {
1243                 if (pit() == 0 && row == 0)
1244                         return false;
1245         } else {
1246                 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1247                                 row + 1 >= int(pm.rows().size()))
1248                         return false;
1249         }       
1250
1251         // with and without selection are handled differently
1252         if (!selection()) {
1253                 int yo = bv().getPos(*this, boundary()).y_;
1254                 Cursor old = *this;
1255                 // To next/previous row
1256                 if (up)
1257                         tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1258                 else
1259                         tm.editXY(*this, xo, yo + textRow().descent() + 1);
1260                 clearSelection();
1261                 
1262                 // This happens when you move out of an inset.
1263                 // And to give the DEPM the possibility of doing
1264                 // something we must provide it with two different
1265                 // cursors. (Lgb)
1266                 Cursor dummy = *this;
1267                 if (dummy == old)
1268                         ++dummy.pos();
1269                 if (bv().checkDepm(dummy, old)) {
1270                         updateNeeded = true;
1271                         // Make sure that cur gets back whatever happened to dummy(Lgb)
1272                         operator=(dummy);
1273                 }
1274         } else {
1275                 // if there is a selection, we stay out of any inset, and just jump to the right position:
1276                 Cursor old = *this;
1277                 if (up) {
1278                         if (row > 0) {
1279                                 top().pos() = std::min(tm.x2pos(pit(), row - 1, xo), top().lastpos());
1280                         } else if (pit() > 0) {
1281                                 --pit();
1282                                 ParagraphMetrics const & pmcur = bv_->parMetrics(text(), pit());
1283                                 top().pos() = std::min(tm.x2pos(pit(), pmcur.rows().size() - 1, xo), top().lastpos());
1284                         }
1285                 } else {
1286                         if (row + 1 < int(pm.rows().size())) {
1287                                 top().pos() = std::min(tm.x2pos(pit(), row + 1, xo), top().lastpos());
1288                         } else if (pit() + 1 < int(text()->paragraphs().size())) {
1289                                 ++pit();
1290                                 top().pos() = std::min(tm.x2pos(pit(), 0, xo), top().lastpos());
1291                         }
1292                 }
1293
1294                 updateNeeded |= bv().checkDepm(*this, old);
1295         }
1296
1297         updateTextTargetOffset();
1298         return true;
1299 }       
1300
1301
1302 void Cursor::handleFont(string const & font)
1303 {
1304         LYXERR(Debug::DEBUG, BOOST_CURRENT_FUNCTION << ": " << font);
1305         docstring safe;
1306         if (selection()) {
1307                 macroModeClose();
1308                 safe = cap::grabAndEraseSelection(*this);
1309         }
1310
1311         if (lastpos() != 0) {
1312                 // something left in the cell
1313                 if (pos() == 0) {
1314                         // cursor in first position
1315                         popBackward();
1316                 } else if (pos() == lastpos()) {
1317                         // cursor in last position
1318                         popForward();
1319                 } else {
1320                         // cursor in between. split cell
1321                         MathData::iterator bt = cell().begin();
1322                         MathAtom at = createInsetMath(from_utf8(font));
1323                         at.nucleus()->cell(0) = MathData(bt, bt + pos());
1324                         cell().erase(bt, bt + pos());
1325                         popBackward();
1326                         plainInsert(at);
1327                 }
1328         } else {
1329                 // nothing left in the cell
1330                 pullArg();
1331                 plainErase();
1332         }
1333         insert(safe);
1334 }
1335
1336
1337 void Cursor::message(docstring const & msg) const
1338 {
1339         theLyXFunc().setMessage(msg);
1340 }
1341
1342
1343 void Cursor::errorMessage(docstring const & msg) const
1344 {
1345         theLyXFunc().setErrorMessage(msg);
1346 }
1347
1348
1349 docstring Cursor::selectionAsString(bool label) const
1350 {
1351         if (!selection())
1352                 return docstring();
1353
1354         if (inTexted()) {
1355                 Buffer const & buffer = bv().buffer();
1356                 ParagraphList const & pars = text()->paragraphs();
1357
1358                 // should be const ...
1359                 pit_type startpit = selBegin().pit();
1360                 pit_type endpit = selEnd().pit();
1361                 size_t const startpos = selBegin().pos();
1362                 size_t const endpos = selEnd().pos();
1363
1364                 if (startpit == endpit)
1365                         return pars[startpit].asString(buffer, startpos, endpos, label);
1366
1367                 // First paragraph in selection
1368                 docstring result = pars[startpit].
1369                         asString(buffer, startpos, pars[startpit].size(), label)
1370                                  + parbreak(pars[startpit]);
1371
1372                 // The paragraphs in between (if any)
1373                 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1374                         Paragraph const & par = pars[pit];
1375                         result += par.asString(buffer, 0, par.size(), label)
1376                                   + parbreak(pars[pit]);
1377                 }
1378
1379                 // Last paragraph in selection
1380                 result += pars[endpit].asString(buffer, 0, endpos, label);
1381
1382                 return result;
1383         }
1384
1385         if (inMathed())
1386                 return cap::grabSelection(*this);
1387
1388         return docstring();
1389 }
1390
1391
1392 docstring Cursor::currentState()
1393 {
1394         if (inMathed()) {
1395                 odocstringstream os;
1396                 info(os);
1397                 return os.str();
1398         }
1399
1400         if (inTexted())
1401                 return text()->currentState(*this);
1402
1403         return docstring();
1404 }
1405
1406
1407 docstring Cursor::getPossibleLabel()
1408 {
1409         return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1410 }
1411
1412
1413 Encoding const * Cursor::getEncoding() const
1414 {
1415         if (empty())
1416                 return 0;
1417         int s = 0;
1418         // go up until first non-0 text is hit
1419         // (innermost text is 0 in mathed)
1420         for (s = depth() - 1; s >= 0; --s)
1421                 if (operator[](s).text())
1422                         break;
1423         CursorSlice const & sl = operator[](s);
1424         Text const & text = *sl.text();
1425         Font font = text.getPar(sl.pit()).getFont(
1426                 bv().buffer().params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1427         return font.language()->encoding();
1428 }
1429
1430
1431 void Cursor::undispatched()
1432 {
1433         disp_.dispatched(false);
1434 }
1435
1436
1437 void Cursor::dispatched()
1438 {
1439         disp_.dispatched(true);
1440 }
1441
1442
1443 void Cursor::updateFlags(Update::flags f)
1444 {
1445         disp_.update(f);
1446 }
1447
1448
1449 void Cursor::noUpdate()
1450 {
1451         disp_.update(Update::None);
1452 }
1453
1454
1455 Font Cursor::getFont() const
1456 {
1457         // The logic here should more or less match to the Cursor::setCurrentFont
1458         // logic, i.e. the cursor height should give a hint what will happen
1459         // if a character is entered.
1460         
1461         // HACK. far from being perfect...
1462         // go up until first non-0 text is hit
1463         // (innermost text is 0 in mathed)
1464         int s = 0;
1465         for (s = depth() - 1; s >= 0; --s)
1466                 if (operator[](s).text())
1467                         break;
1468         CursorSlice const & sl = operator[](s);
1469         Text const & text = *sl.text();
1470         Paragraph const & par = text.getPar(sl.pit());
1471         
1472         // on boundary, so we are really at the character before
1473         pos_type pos = sl.pos();
1474         if (pos > 0 && boundary())
1475                 --pos;
1476         
1477         // on space? Take the font before (only for RTL boundary stay)
1478         if (pos > 0) {
1479                 TextMetrics const & tm = bv().textMetrics(&text);
1480                 if (pos == sl.lastpos()
1481                         || (par.isSeparator(pos) 
1482                         && !tm.isRTLBoundary(sl.pit(), pos)))
1483                         --pos;
1484         }
1485         
1486         // get font at the position
1487         Font font = par.getFont(bv().buffer().params(), pos,
1488                 outerFont(sl.pit(), text.paragraphs()));
1489
1490         return font;
1491 }
1492
1493
1494 bool Cursor::fixIfBroken()
1495 {
1496         if (DocIterator::fixIfBroken()) {
1497                         clearSelection();
1498                         resetAnchor();
1499                         return true;
1500         }
1501         return false;
1502 }
1503
1504
1505 bool notifyCursorLeaves(DocIterator const & old, Cursor & cur)
1506 {
1507         // find inset in common
1508         size_type i;
1509         for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
1510                 if (&old.inset() != &cur.inset())
1511                         break;
1512         }
1513         
1514         // notify everything on top of the common part in old cursor,
1515         // but stop if the inset claims the cursor to be invalid now
1516         for (;  i < old.depth(); ++i) {
1517                 if (old[i].inset().notifyCursorLeaves(cur))
1518                         return true;
1519         }
1520         
1521         return false;
1522 }
1523
1524
1525 void Cursor::setCurrentFont()
1526 {
1527         CursorSlice const & cs = innerTextSlice();
1528         Paragraph const & par = cs.paragraph();
1529         pos_type cpit = cs.pit();
1530         pos_type cpos = cs.pos();
1531         Text const & ctext = *cs.text();
1532         TextMetrics const & tm = bv().textMetrics(&ctext);
1533
1534         // are we behind previous char in fact? -> go to that char
1535         if (cpos > 0 && boundary())
1536                 --cpos;
1537
1538         // find position to take the font from
1539         if (cpos != 0) {
1540                 // paragraph end? -> font of last char
1541                 if (cpos == lastpos())
1542                         --cpos;
1543                 // on space? -> look at the words in front of space
1544                 else if (cpos > 0 && par.isSeparator(cpos))     {
1545                         // abc| def -> font of c
1546                         // abc |[WERBEH], i.e. boundary==true -> font of c
1547                         // abc [WERBEH]| def, font of the space
1548                         if (!tm.isRTLBoundary(cpit, cpos))
1549                                 --cpos;
1550                 }
1551         }
1552
1553         // get font
1554         BufferParams const & bufparams = buffer().params();
1555         current_font = par.getFontSettings(bufparams, cpos);
1556         real_current_font = tm.getDisplayFont(cpit, cpos);
1557
1558         // special case for paragraph end
1559         if (cs.pos() == lastpos()
1560             && tm.isRTLBoundary(cpit, cs.pos())
1561             && !boundary()) {
1562                 Language const * lang = par.getParLanguage(bufparams);
1563                 current_font.setLanguage(lang);
1564                 current_font.fontInfo().setNumber(FONT_OFF);
1565                 real_current_font.setLanguage(lang);
1566                 real_current_font.fontInfo().setNumber(FONT_OFF);
1567         }
1568 }
1569
1570
1571 bool Cursor::textUndo()
1572 {
1573         DocIterator dit = *this;
1574         // Undo::textUndo() will modify dit.
1575         if (!bv_->buffer().undo().textUndo(dit))
1576                 return false;
1577         // Set cursor
1578         setCursor(dit);
1579         selection() = false;
1580         resetAnchor();
1581         fixIfBroken();
1582         return true;
1583 }
1584
1585
1586 bool Cursor::textRedo()
1587 {
1588         DocIterator dit = *this;
1589         // Undo::textRedo() will modify dit.
1590         if (!bv_->buffer().undo().textRedo(dit))
1591                 return false;
1592         // Set cursor
1593         setCursor(dit);
1594         selection() = false;
1595         resetAnchor();
1596         fixIfBroken();
1597         return true;
1598 }
1599
1600
1601 void Cursor::finishUndo()
1602 {
1603         bv_->buffer().undo().finishUndo();
1604 }
1605
1606
1607 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to)
1608 {
1609         bv_->buffer().undo().recordUndo(*this, kind, from, to);
1610 }
1611
1612
1613 void Cursor::recordUndo(UndoKind kind, pit_type from)
1614 {
1615         bv_->buffer().undo().recordUndo(*this, kind, from);
1616 }
1617
1618
1619 void Cursor::recordUndo(UndoKind kind)
1620 {
1621         bv_->buffer().undo().recordUndo(*this, kind);
1622 }
1623
1624
1625 void Cursor::recordUndoInset(UndoKind kind)
1626 {
1627         bv_->buffer().undo().recordUndoInset(*this, kind);
1628 }
1629
1630
1631 void Cursor::recordUndoFullDocument()
1632 {
1633         bv_->buffer().undo().recordUndoFullDocument(*this);
1634 }
1635
1636
1637 void Cursor::recordUndoSelection()
1638 {
1639         bv_->buffer().undo().recordUndo(*this, ATOMIC_UNDO,
1640                 selBegin().pit(), selEnd().pit());
1641 }
1642
1643
1644 } // namespace lyx