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