]> git.lyx.org Git - lyx.git/blob - src/Cursor.cpp
BufferParams.h: add comment
[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  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "BufferView.h"
16 #include "bufferview_funcs.h"
17 #include "Buffer.h"
18 #include "Cursor.h"
19 #include "CoordCache.h"
20 #include "CutAndPaste.h"
21 #include "debug.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
36 #include "insets/InsetTabular.h"
37 #include "insets/InsetText.h"
38
39 #include "mathed/MathData.h"
40 #include "mathed/InsetMath.h"
41 #include "mathed/InsetMathScript.h"
42 #include "mathed/MacroTable.h"
43
44 #include "support/limited_stack.h"
45
46 #include <boost/assert.hpp>
47 #include <boost/bind.hpp>
48 #include <boost/current_function.hpp>
49
50 #include <sstream>
51 #include <limits>
52 #include <map>
53
54 namespace lyx {
55
56 using std::string;
57 using std::vector;
58 using std::endl;
59 using std::min;
60 using std::for_each;
61
62 namespace {
63
64         bool
65         positionable(DocIterator const & cursor, DocIterator const & anchor)
66         {
67                 // avoid deeper nested insets when selecting
68                 if (cursor.depth() > anchor.depth())
69                         return false;
70
71                 // anchor might be deeper, should have same path then
72                 for (size_t i = 0; i < cursor.depth(); ++i)
73                         if (&cursor[i].inset() != &anchor[i].inset())
74                                 return false;
75
76                 // position should be ok.
77                 return true;
78         }
79
80
81         // Find position closest to (x, y) in cell given by iter.
82         // Used only in mathed
83         DocIterator bruteFind2(Cursor const & c, int x, int y)
84         {
85                 double best_dist = std::numeric_limits<double>::max();
86
87                 DocIterator result;
88
89                 DocIterator it = c;
90                 it.top().pos() = 0;
91                 DocIterator et = c;
92                 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
93                 for (size_t i = 0;; ++i) {
94                         int xo;
95                         int yo;
96                         Inset const * inset = &it.inset();
97                         std::map<Inset const *, Point> const & data =
98                                 c.bv().coordCache().getInsets().getData();
99                         std::map<Inset const *, Point>::const_iterator I = data.find(inset);
100
101                         // FIXME: in the case where the inset is not in the cache, this
102                         // means that no part of it is visible on screen. In this case
103                         // we don't do elaborate search and we just return the forwarded
104                         // DocIterator at its beginning.
105                         if (I == data.end()) {
106                                 it.top().pos() = 0;
107                                 return it;
108                         }
109
110                         Point o = I->second;
111                         inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
112                         // Convert to absolute
113                         xo += o.x_;
114                         yo += o.y_;
115                         double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
116                         // '<=' in order to take the last possible position
117                         // this is important for clicking behind \sum in e.g. '\sum_i a'
118                         LYXERR(Debug::DEBUG) << "i: " << i << " d: " << d
119                                 << " best: " << best_dist << endl;
120                         if (d <= best_dist) {
121                                 best_dist = d;
122                                 result = it;
123                         }
124                         if (it == et)
125                                 break;
126                         it.forwardPos();
127                 }
128                 return result;
129         }
130
131
132         /// 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                 BOOST_ASSERT(!cursor.empty());
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 = std::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_funcs::getPos(bv, 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         /// moves position closest to (x, y) in given box
189         bool bruteFind3(Cursor & cur, int x, int y, bool up)
190         {
191                 BufferView & bv = cur.bv();
192                 int ylow  = up ? 0 : y + 1;
193                 int yhigh = up ? y - 1 : bv.workHeight();
194                 int xlow = 0;
195                 int xhigh = bv.workWidth();
196
197 // FIXME: bit more work needed to get 'from' and 'to' right.
198                 pit_type from = cur.bottom().pit();
199                 //pit_type to = cur.bottom().pit();
200                 //lyxerr << "Pit start: " << from << endl;
201
202                 //lyxerr << "bruteFind3: x: " << x << " y: " << y
203                 //      << " xlow: " << xlow << " xhigh: " << xhigh
204                 //      << " ylow: " << ylow << " yhigh: " << yhigh
205                 //      << endl;
206                 Inset & inset = bv.buffer()->inset();
207                 DocIterator it = doc_iterator_begin(inset);
208                 it.pit() = from;
209                 DocIterator et = doc_iterator_end(inset);
210
211                 double best_dist = std::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_funcs::status(&bv, it) == bv_funcs::CUR_INSIDE
217                             && (!cur.selection() || positionable(it, cur.anchor_))) {
218                                 Point p = bv_funcs::getPos(bv, 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         docstring parbreak(Paragraph const & par)
249         {
250                 odocstringstream ods;
251                 ods << '\n';
252                 // only add blank line if we're not in an ERT inset
253                 if (par.ownerCode() != Inset::ERT_CODE)
254                         ods << '\n';
255                 return ods.str();
256         }
257
258 } // namespace anon
259
260
261 // be careful: this is called from the bv's constructor, too, so
262 // bv functions are not yet available!
263 Cursor::Cursor(BufferView & bv)
264         : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
265           selection_(false), mark_(false), logicalpos_(false)
266 {}
267
268
269 void Cursor::reset(Inset & inset)
270 {
271         clear();
272         push_back(CursorSlice(inset));
273         anchor_ = DocIterator(inset);
274         clearTargetX();
275         selection_ = false;
276         mark_ = false;
277 }
278
279
280 // this (intentionally) does neither touch anchor nor selection status
281 void Cursor::setCursor(DocIterator const & cur)
282 {
283         DocIterator::operator=(cur);
284 }
285
286
287 void Cursor::dispatch(FuncRequest const & cmd0)
288 {
289         LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
290                              << " cmd: " << cmd0 << '\n'
291                              << *this << endl;
292         if (empty())
293                 return;
294
295         fixIfBroken();
296         FuncRequest cmd = cmd0;
297         Cursor safe = *this;
298
299         for (; depth(); pop()) {
300                 LYXERR(Debug::DEBUG) << "Cursor::dispatch: cmd: "
301                         << cmd0 << endl << *this << endl;
302                 BOOST_ASSERT(pos() <= lastpos());
303                 BOOST_ASSERT(idx() <= lastidx());
304                 BOOST_ASSERT(pit() <= lastpit());
305
306                 // The common case is 'LFUN handled, need update', so make the
307                 // LFUN handler's life easier by assuming this as default value.
308                 // The handler can reset the update and val flags if necessary.
309                 disp_.update(Update::FitCursor | Update::Force);
310                 disp_.dispatched(true);
311                 inset().dispatch(*this, cmd);
312                 if (disp_.dispatched())
313                         break;
314         }
315         // it completely to get a 'bomb early' behaviour in case this
316         // object will be used again.
317         if (!disp_.dispatched()) {
318                 LYXERR(Debug::DEBUG) << "RESTORING OLD CURSOR!" << endl;
319                 operator=(safe);
320                 disp_.update(Update::None);
321                 disp_.dispatched(false);
322         }
323 }
324
325
326 DispatchResult Cursor::result() const
327 {
328         return disp_;
329 }
330
331
332 BufferView & Cursor::bv() const
333 {
334         BOOST_ASSERT(bv_);
335         return *bv_;
336 }
337
338
339 Buffer & Cursor::buffer() const
340 {
341         BOOST_ASSERT(bv_);
342         BOOST_ASSERT(bv_->buffer());
343         return *bv_->buffer();
344 }
345
346
347 void Cursor::pop()
348 {
349         BOOST_ASSERT(depth() >= 1);
350         pop_back();
351 }
352
353
354 void Cursor::push(Inset & p)
355 {
356         push_back(CursorSlice(p));
357 }
358
359
360 void Cursor::pushLeft(Inset & p)
361 {
362         BOOST_ASSERT(!empty());
363         //lyxerr << "Entering inset " << t << " left" << endl;
364         push(p);
365         p.idxFirst(*this);
366 }
367
368
369 bool Cursor::popLeft()
370 {
371         BOOST_ASSERT(!empty());
372         //lyxerr << "Leaving inset to the left" << endl;
373         inset().notifyCursorLeaves(*this);
374         if (depth() == 1)
375                 return false;
376         pop();
377         return true;
378 }
379
380
381 bool Cursor::popRight()
382 {
383         BOOST_ASSERT(!empty());
384         //lyxerr << "Leaving inset to the right" << endl;
385         const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
386         inset().notifyCursorLeaves(*this);
387         if (depth() == 1)
388                 return false;
389         pop();
390         pos() += lastpos() - lp + 1;
391         return true;
392 }
393
394
395 int Cursor::currentMode()
396 {
397         BOOST_ASSERT(!empty());
398         for (int i = depth() - 1; i >= 0; --i) {
399                 int res = operator[](i).inset().currentMode();
400                 if (res != Inset::UNDECIDED_MODE)
401                         return res;
402         }
403         return Inset::TEXT_MODE;
404 }
405
406
407 void Cursor::getPos(int & x, int & y) const
408 {
409         Point p = bv_funcs::getPos(bv(), *this, boundary());
410         x = p.x_;
411         y = p.y_;
412 }
413
414
415 Row const & Cursor::textRow() const
416 {
417         ParagraphMetrics const & pm = bv().parMetrics(text(), pit());
418         BOOST_ASSERT(!pm.rows().empty());
419         return pm.getRow(pos(), boundary());
420 }
421
422
423 void Cursor::resetAnchor()
424 {
425         anchor_ = *this;
426 }
427
428
429
430 bool Cursor::posLeft()
431 {
432         if (pos() == 0)
433                 return false;
434         --pos();
435         return true;
436 }
437
438
439 bool Cursor::posRight()
440 {
441         if (pos() == lastpos())
442                 return false;
443         ++pos();
444         return true;
445 }
446
447
448 CursorSlice Cursor::anchor() const
449 {
450         BOOST_ASSERT(anchor_.depth() >= depth());
451         CursorSlice normal = anchor_[depth() - 1];
452         if (depth() < anchor_.depth() && top() <= normal) {
453                 // anchor is behind cursor -> move anchor behind the inset
454                 ++normal.pos();
455         }
456         return normal;
457 }
458
459
460 CursorSlice Cursor::selBegin() const
461 {
462         if (!selection())
463                 return top();
464         return anchor() < top() ? anchor() : top();
465 }
466
467
468 CursorSlice Cursor::selEnd() const
469 {
470         if (!selection())
471                 return top();
472         return anchor() > top() ? anchor() : top();
473 }
474
475
476 DocIterator Cursor::selectionBegin() const
477 {
478         if (!selection())
479                 return *this;
480         DocIterator di = (anchor() < top() ? anchor_ : *this);
481         di.resize(depth());
482         return di;
483 }
484
485
486 DocIterator Cursor::selectionEnd() const
487 {
488         if (!selection())
489                 return *this;
490         DocIterator di = (anchor() > top() ? anchor_ : *this);
491         if (di.depth() > depth()) {
492                 di.resize(depth());
493                 ++di.pos();
494         }
495         return di;
496 }
497
498
499 void Cursor::setSelection()
500 {
501         selection() = true;
502         // A selection with no contents is not a selection
503 #ifdef WITH_WARNINGS
504 #warning doesnt look ok
505 #endif
506         if (pit() == anchor().pit() && pos() == anchor().pos())
507                 selection() = false;
508 }
509
510
511 void Cursor::setSelection(DocIterator const & where, int n)
512 {
513         setCursor(where);
514         selection() = true;
515         anchor_ = where;
516         pos() += n;
517 }
518
519
520 void Cursor::clearSelection()
521 {
522         selection() = false;
523         mark() = false;
524         resetAnchor();
525 }
526
527
528 int & Cursor::x_target()
529 {
530         return x_target_;
531 }
532
533
534 int Cursor::x_target() const
535 {
536         return x_target_;
537 }
538
539
540 void Cursor::clearTargetX()
541 {
542         x_target_ = -1;
543 }
544
545
546
547 void Cursor::info(odocstream & os) const
548 {
549         for (int i = 1, n = depth(); i < n; ++i) {
550                 operator[](i).inset().infoize(os);
551                 os << "  ";
552         }
553         if (pos() != 0) {
554                 Inset const * inset = prevInset();
555                 // prevInset() can return 0 in certain case.
556                 if (inset)
557                         prevInset()->infoize2(os);
558         }
559         // overwite old message
560         os << "                    ";
561 }
562
563
564 bool Cursor::selHandle(bool sel)
565 {
566         //lyxerr << "Cursor::selHandle" << endl;
567         if (sel == selection())
568                 return false;
569
570         resetAnchor();
571         selection() = sel;
572         cap::saveSelection(*this);
573         return true;
574 }
575
576
577 std::ostream & operator<<(std::ostream & os, Cursor const & cur)
578 {
579         os << "\n cursor:                                | anchor:\n";
580         for (size_t i = 0, n = cur.depth(); i != n; ++i) {
581                 os << " " << cur[i] << " | ";
582                 if (i < cur.anchor_.depth())
583                         os << cur.anchor_[i];
584                 else
585                         os << "-------------------------------";
586                 os << "\n";
587         }
588         for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
589                 os << "------------------------------- | " << cur.anchor_[i] << "\n";
590         }
591         os << " selection: " << cur.selection_
592            << " x_target: " << cur.x_target_ << endl;
593         return os;
594 }
595
596 } // namespace lyx
597
598
599 ///////////////////////////////////////////////////////////////////
600 //
601 // The part below is the non-integrated rest of the original math
602 // cursor. This should be either generalized for texted or moved
603 // back to mathed (in most cases to InsetMathNest).
604 //
605 ///////////////////////////////////////////////////////////////////
606
607 #include "mathed/InsetMathChar.h"
608 #include "mathed/InsetMathGrid.h"
609 #include "mathed/InsetMathScript.h"
610 #include "mathed/InsetMathUnknown.h"
611 #include "mathed/MathFactory.h"
612 #include "mathed/MathStream.h"
613 #include "mathed/MathSupport.h"
614
615
616 namespace lyx {
617
618 //#define FILEDEBUG 1
619
620
621 bool Cursor::isInside(Inset const * p)
622 {
623         for (size_t i = 0; i != depth(); ++i)
624                 if (&operator[](i).inset() == p)
625                         return true;
626         return false;
627 }
628
629
630 void Cursor::leaveInset(Inset const & inset)
631 {
632         for (size_t i = 0; i != depth(); ++i) {
633                 if (&operator[](i).inset() == &inset) {
634                         resize(i);
635                         return;
636                 }
637         }
638 }
639
640
641 bool Cursor::openable(MathAtom const & t) const
642 {
643         if (!t->isActive())
644                 return false;
645
646         if (t->lock())
647                 return false;
648
649         if (!selection())
650                 return true;
651
652         // we can't move into anything new during selection
653         if (depth() >= anchor_.depth())
654                 return false;
655         if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
656                 return false;
657
658         return true;
659 }
660
661
662 void Cursor::setScreenPos(int x, int y)
663 {
664         x_target() = x;
665         bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
666 }
667
668
669
670 void Cursor::plainErase()
671 {
672         cell().erase(pos());
673 }
674
675
676 void Cursor::markInsert()
677 {
678         insert(char_type(0));
679 }
680
681
682 void Cursor::markErase()
683 {
684         cell().erase(pos());
685 }
686
687
688 void Cursor::plainInsert(MathAtom const & t)
689 {
690         cell().insert(pos(), t);
691         ++pos();
692 }
693
694
695 void Cursor::insert(docstring const & str)
696 {
697         for_each(str.begin(), str.end(),
698                  boost::bind(static_cast<void(Cursor::*)(char_type)>
699                              (&Cursor::insert), this, _1));
700 }
701
702
703 void Cursor::insert(char_type c)
704 {
705         //lyxerr << "Cursor::insert char '" << c << "'" << endl;
706         BOOST_ASSERT(!empty());
707         if (inMathed()) {
708                 cap::selClearOrDel(*this);
709                 insert(new InsetMathChar(c));
710         } else {
711                 text()->insertChar(*this, c);
712         }
713 }
714
715
716 void Cursor::insert(MathAtom const & t)
717 {
718         //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
719         macroModeClose();
720         cap::selClearOrDel(*this);
721         plainInsert(t);
722 }
723
724
725 void Cursor::insert(Inset * inset)
726 {
727         if (inMathed())
728                 insert(MathAtom(inset));
729         else
730                 text()->insertInset(*this, inset);
731 }
732
733
734 void Cursor::niceInsert(docstring const & t)
735 {
736         MathData ar;
737         asArray(t, ar);
738         if (ar.size() == 1)
739                 niceInsert(ar[0]);
740         else
741                 insert(ar);
742 }
743
744
745 void Cursor::niceInsert(MathAtom const & t)
746 {
747         macroModeClose();
748         docstring const safe = cap::grabAndEraseSelection(*this);
749         plainInsert(t);
750         // enter the new inset and move the contents of the selection if possible
751         if (t->isActive()) {
752                 posLeft();
753                 // be careful here: don't use 'pushLeft(t)' as this we need to
754                 // push the clone, not the original
755                 pushLeft(*nextInset());
756                 // We may not use niceInsert here (recursion)
757                 MathData ar;
758                 asArray(safe, ar);
759                 insert(ar);
760         }
761 }
762
763
764 void Cursor::insert(MathData const & ar)
765 {
766         macroModeClose();
767         if (selection())
768                 cap::eraseSelection(*this);
769         cell().insert(pos(), ar);
770         pos() += ar.size();
771 }
772
773
774 bool Cursor::backspace()
775 {
776         autocorrect() = false;
777
778         if (selection()) {
779                 cap::eraseSelection(*this);
780                 return true;
781         }
782
783         if (pos() == 0) {
784                 // If empty cell, and not part of a big cell
785                 if (lastpos() == 0 && inset().nargs() == 1) {
786                         popLeft();
787                         // Directly delete empty cell: [|[]] => [|] 
788                         if (inMathed()) {
789                                 plainErase();
790                                 resetAnchor();
791                                 return true;
792                         }
793                         // [|], can not delete from inside
794                         return false;
795                 } else {
796                         if (inMathed())
797                                 pullArg();
798                         else
799                                 popLeft();
800                         return true;
801                 }
802         }
803
804         if (inMacroMode()) {
805                 InsetMathUnknown * p = activeMacro();
806                 if (p->name().size() > 1) {
807                         p->setName(p->name().substr(0, p->name().size() - 1));
808                         return true;
809                 }
810         }
811
812         if (pos() != 0 && prevAtom()->nargs() > 0) {
813                 // let's require two backspaces for 'big stuff' and
814                 // highlight on the first
815                 resetAnchor();
816                 selection() = true;
817                 --pos();
818         } else {
819                 --pos();
820                 plainErase();
821         }
822         return true;
823 }
824
825
826 bool Cursor::erase()
827 {
828         autocorrect() = false;
829         if (inMacroMode())
830                 return true;
831
832         if (selection()) {
833                 cap::eraseSelection(*this);
834                 return true;
835         }
836
837         // delete empty cells if possible
838         if (pos() == lastpos() && inset().idxDelete(idx()))
839                 return true;
840
841         // special behaviour when in last position of cell
842         if (pos() == lastpos()) {
843                 bool one_cell = inset().nargs() == 1;
844                 if (one_cell && lastpos() == 0) {
845                         popLeft();
846                         // Directly delete empty cell: [|[]] => [|] 
847                         if (inMathed()) {
848                                 plainErase();
849                                 resetAnchor();
850                                 return true;
851                         }
852                         // [|], can not delete from inside
853                         return false;
854                 }
855                 // remove markup
856                 if (!one_cell)
857                         inset().idxGlue(idx());
858                 return true;
859         }
860
861         // 'clever' UI hack: only erase large items if previously slected
862         if (pos() != lastpos() && nextAtom()->nargs() > 0) {
863                 resetAnchor();
864                 selection() = true;
865                 ++pos();
866         } else {
867                 plainErase();
868         }
869
870         return true;
871 }
872
873
874 bool Cursor::up()
875 {
876         macroModeClose();
877         DocIterator save = *this;
878         if (goUpDown(true))
879                 return true;
880         setCursor(save);
881         autocorrect() = false;
882         return selection();
883 }
884
885
886 bool Cursor::down()
887 {
888         macroModeClose();
889         DocIterator save = *this;
890         if (goUpDown(false))
891                 return true;
892         setCursor(save);
893         autocorrect() = false;
894         return selection();
895 }
896
897
898 bool Cursor::macroModeClose()
899 {
900         if (!inMacroMode())
901                 return false;
902         InsetMathUnknown * p = activeMacro();
903         p->finalize();
904         docstring const s = p->name();
905         --pos();
906         cell().erase(pos());
907
908         // do nothing if the macro name is empty
909         if (s == "\\")
910                 return false;
911
912         // trigger updates of macros, at least, if no full
913         // updates take place anyway
914         updateFlags(Update::Force);
915
916         docstring const name = s.substr(1);
917         InsetMathNest * const in = inset().asInsetMath()->asNestInset();
918         if (in && in->interpretString(*this, s))
919                 return true;
920         plainInsert(createInsetMath(name));
921         return true;
922 }
923
924
925 docstring Cursor::macroName()
926 {
927         return inMacroMode() ? activeMacro()->name() : docstring();
928 }
929
930
931 void Cursor::handleNest(MathAtom const & a, int c)
932 {
933         //lyxerr << "Cursor::handleNest: " << c << endl;
934         MathAtom t = a;
935         asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
936         insert(t);
937         posLeft();
938         pushLeft(*nextInset());
939 }
940
941
942 int Cursor::targetX() const
943 {
944         if (x_target() != -1)
945                 return x_target();
946         int x = 0;
947         int y = 0;
948         getPos(x, y);
949         return x;
950 }
951
952
953 void Cursor::setTargetX()
954 {
955         int x;
956         int y;
957         getPos(x, y);
958         x_target_ = x;
959 }
960
961
962 bool Cursor::inMacroMode() const
963 {
964         if (pos() == 0)
965                 return false;
966         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
967         return p && !p->final();
968 }
969
970
971 InsetMathUnknown * Cursor::activeMacro()
972 {
973         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
974 }
975
976
977 void Cursor::pullArg()
978 {
979 #ifdef WITH_WARNINGS
980 #warning Look here
981 #endif
982         MathData ar = cell();
983         if (popLeft() && inMathed()) {
984                 plainErase();
985                 cell().insert(pos(), ar);
986                 resetAnchor();
987         } else {
988                 //formula()->mutateToText();
989         }
990 }
991
992
993 void Cursor::touch()
994 {
995 #ifdef WITH_WARNINGS
996 #warning look here
997 #endif
998 #if 0
999         DocIterator::const_iterator it = begin();
1000         DocIterator::const_iterator et = end();
1001         for ( ; it != et; ++it)
1002                 it->cell().touch();
1003 #endif
1004 }
1005
1006
1007 void Cursor::normalize()
1008 {
1009         if (idx() > lastidx()) {
1010                 lyxerr << "this should not really happen - 1: "
1011                        << idx() << ' ' << nargs()
1012                        << " in: " << &inset() << endl;
1013                 idx() = lastidx();
1014         }
1015
1016         if (pos() > lastpos()) {
1017                 lyxerr << "this should not really happen - 2: "
1018                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1019                        << " in atom: '";
1020                 odocstringstream os;
1021                 WriteStream wi(os, false, true);
1022                 inset().asInsetMath()->write(wi);
1023                 lyxerr << to_utf8(os.str()) << endl;
1024                 pos() = lastpos();
1025         }
1026 }
1027
1028
1029 bool Cursor::goUpDown(bool up)
1030 {
1031         // Be warned: The 'logic' implemented in this function is highly
1032         // fragile. A distance of one pixel or a '<' vs '<=' _really
1033         // matters. So fiddle around with it only if you think you know
1034         // what you are doing!
1035
1036         int xo = 0;
1037         int yo = 0;
1038         getPos(xo, yo);
1039
1040         // check if we had something else in mind, if not, this is the future
1041         // target
1042         if (x_target() == -1)
1043                 x_target() = xo;
1044         else
1045                 xo = x_target();
1046
1047         // try neigbouring script insets
1048         if (!selection()) {
1049                 // try left
1050                 if (pos() != 0) {
1051                         InsetMathScript const * p = prevAtom()->asScriptInset();
1052                         if (p && p->has(up)) {
1053                                 --pos();
1054                                 push(*const_cast<InsetMathScript*>(p));
1055                                 idx() = p->idxOfScript(up);
1056                                 pos() = lastpos();
1057                                 return true;
1058                         }
1059                 }
1060
1061                 // try right
1062                 if (pos() != lastpos()) {
1063                         InsetMathScript const * p = nextAtom()->asScriptInset();
1064                         if (p && p->has(up)) {
1065                                 push(*const_cast<InsetMathScript*>(p));
1066                                 idx() = p->idxOfScript(up);
1067                                 pos() = 0;
1068                                 return true;
1069                         }
1070                 }
1071         }
1072
1073 // FIXME: Switch this on for more robust movement
1074 #if 0
1075
1076         return bruteFind3(*this, xo, yo, up);
1077
1078 #else
1079         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1080         //if (up)
1081         //      yhigh = yo - 4;
1082         //else
1083         //      ylow = yo + 4;
1084         //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
1085         //      lyxerr << "updown: handled by brute find in the same cell" << endl;
1086         //      return true;
1087         //}
1088
1089         // try to find an inset that knows better then we
1090         while (true) {
1091                 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1092                 // ask inset first
1093                 if (inset().idxUpDown(*this, up)) {
1094                         //lyxerr << "idxUpDown triggered" << endl;
1095                         // try to find best position within this inset
1096                         if (!selection())
1097                                 setCursor(bruteFind2(*this, xo, yo));
1098                         return true;
1099                 }
1100
1101                 // no such inset found, just take something "above"
1102                 if (!popLeft()) {
1103                         //lyxerr << "updown: popleft failed (strange case)" << endl;
1104                         int ylow  = up ? 0 : yo + 1;
1105                         int yhigh = up ? yo - 1 : bv().workHeight();
1106                         return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1107                 }
1108
1109                 // any improvement so far?
1110                 //lyxerr << "updown: popLeft succeeded" << endl;
1111                 int xnew;
1112                 int ynew;
1113                 getPos(xnew, ynew);
1114                 if (up ? ynew < yo : ynew > yo)
1115                         return true;
1116         }
1117
1118         // we should not come here.
1119         BOOST_ASSERT(false);
1120 #endif
1121 }
1122
1123
1124 void Cursor::handleFont(string const & font)
1125 {
1126         LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1127         docstring safe;
1128         if (selection()) {
1129                 macroModeClose();
1130                 safe = cap::grabAndEraseSelection(*this);
1131         }
1132
1133         if (lastpos() != 0) {
1134                 // something left in the cell
1135                 if (pos() == 0) {
1136                         // cursor in first position
1137                         popLeft();
1138                 } else if (pos() == lastpos()) {
1139                         // cursor in last position
1140                         popRight();
1141                 } else {
1142                         // cursor in between. split cell
1143                         MathData::iterator bt = cell().begin();
1144                         MathAtom at = createInsetMath(from_utf8(font));
1145                         at.nucleus()->cell(0) = MathData(bt, bt + pos());
1146                         cell().erase(bt, bt + pos());
1147                         popLeft();
1148                         plainInsert(at);
1149                 }
1150         } else {
1151                 // nothing left in the cell
1152                 pullArg();
1153                 plainErase();
1154         }
1155         insert(safe);
1156 }
1157
1158
1159 void Cursor::message(docstring const & msg) const
1160 {
1161         theLyXFunc().setMessage(msg);
1162 }
1163
1164
1165 void Cursor::errorMessage(docstring const & msg) const
1166 {
1167         theLyXFunc().setErrorMessage(msg);
1168 }
1169
1170
1171 docstring Cursor::selectionAsString(bool label) const
1172 {
1173         if (!selection())
1174                 return docstring();
1175
1176         if (inTexted()) {
1177                 Buffer const & buffer = *bv().buffer();
1178                 ParagraphList const & pars = text()->paragraphs();
1179
1180                 // should be const ...
1181                 pit_type startpit = selBegin().pit();
1182                 pit_type endpit = selEnd().pit();
1183                 size_t const startpos = selBegin().pos();
1184                 size_t const endpos = selEnd().pos();
1185
1186                 if (startpit == endpit)
1187                         return pars[startpit].asString(buffer, startpos, endpos, label);
1188
1189                 // First paragraph in selection
1190                 docstring result = pars[startpit].
1191                         asString(buffer, startpos, pars[startpit].size(), label)
1192                                  + parbreak(pars[startpit]);
1193
1194                 // The paragraphs in between (if any)
1195                 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1196                         Paragraph const & par = pars[pit];
1197                         result += par.asString(buffer, 0, par.size(), label)
1198                                   + parbreak(pars[pit]);
1199                 }
1200
1201                 // Last paragraph in selection
1202                 result += pars[endpit].asString(buffer, 0, endpos, label);
1203
1204                 return result;
1205         }
1206
1207         if (inMathed())
1208                 return cap::grabSelection(*this);
1209
1210         return docstring();
1211 }
1212
1213
1214 docstring Cursor::currentState()
1215 {
1216         if (inMathed()) {
1217                 odocstringstream os;
1218                 info(os);
1219                 return os.str();
1220         }
1221
1222         if (inTexted())
1223                 return text()->currentState(*this);
1224
1225         return docstring();
1226 }
1227
1228
1229 docstring Cursor::getPossibleLabel()
1230 {
1231         return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1232 }
1233
1234
1235 Encoding const * Cursor::getEncoding() const
1236 {
1237         if (empty())
1238                 return 0;
1239         if (!bv().buffer())
1240                 return 0;
1241         int s = 0;
1242         // go up until first non-0 text is hit
1243         // (innermost text is 0 in mathed)
1244         for (s = depth() - 1; s >= 0; --s)
1245                 if (operator[](s).text())
1246                         break;
1247         CursorSlice const & sl = operator[](s);
1248         Text const & text = *sl.text();
1249         Font font = text.getPar(sl.pit()).getFont(
1250                 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1251         return font.language()->encoding();
1252 }
1253
1254
1255 void Cursor::undispatched()
1256 {
1257         disp_.dispatched(false);
1258 }
1259
1260
1261 void Cursor::dispatched()
1262 {
1263         disp_.dispatched(true);
1264 }
1265
1266
1267 void Cursor::updateFlags(Update::flags f)
1268 {
1269         disp_.update(f);
1270 }
1271
1272
1273 void Cursor::noUpdate()
1274 {
1275         disp_.update(Update::None);
1276 }
1277
1278
1279 Font Cursor::getFont() const
1280 {
1281         // HACK. far from being perfect...
1282         int s = 0;
1283         // go up until first non-0 text is hit
1284         // (innermost text is 0 in mathed)
1285         for (s = depth() - 1; s >= 0; --s)
1286                 if (operator[](s).text())
1287                         break;
1288         CursorSlice const & sl = operator[](s);
1289         Text const & text = *sl.text();
1290         Font font = text.getPar(sl.pit()).getFont(
1291                 bv().buffer()->params(),
1292                 sl.pos(),
1293                 outerFont(sl.pit(), text.paragraphs()));
1294
1295         return font;
1296 }
1297
1298
1299 void Cursor::fixIfBroken()
1300 {
1301         // find out last good level
1302         Cursor copy = *this;
1303         size_t newdepth = depth();
1304         while (!copy.empty()) {
1305                 if (copy.idx() > copy.lastidx()) {
1306                         lyxerr << "wrong idx " << copy.idx()
1307                                << ", max is " << copy.lastidx()
1308                                << " at level " << copy.depth()
1309                                << ". Trying to correct this."  << endl;
1310                         lyxerr << "old: " << *this << endl;
1311                         newdepth = copy.depth() - 1;
1312                 }
1313                 else if (copy.pit() > copy.lastpit()) {
1314                         lyxerr << "wrong pit " << copy.pit()
1315                                << ", max is " << copy.lastpit()
1316                                << " at level " << copy.depth()
1317                                << ". Trying to correct this."  << endl;
1318                         lyxerr << "old: " << *this << endl;
1319                         newdepth = copy.depth() - 1;
1320                 }
1321                 else if (copy.pos() > copy.lastpos()) {
1322                         lyxerr << "wrong pos " << copy.pos()
1323                                << ", max is " << copy.lastpos()
1324                                << " at level " << copy.depth()
1325                                << ". Trying to correct this."  << endl;
1326                         lyxerr << "old: " << *this << endl;
1327                         newdepth = copy.depth() - 1;
1328                 }
1329                 copy.pop();
1330         }
1331         // shrink cursor to a size where everything is valid, possibly
1332         // leaving insets
1333         while (depth() > newdepth) {
1334                 pop();
1335                 lyxerr << "correcting cursor to level " << depth() << endl;
1336                 lyxerr << "new: " << *this << endl;
1337                 clearSelection();
1338         }
1339 }
1340
1341
1342 bool Cursor::isRTL() const
1343 {
1344         return innerParagraph().isRightToLeftPar(bv().buffer()->params());
1345 }
1346
1347
1348 } // namespace lyx