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