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