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