]> git.lyx.org Git - lyx.git/blob - src/cursor.C
fix table crash;
[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 "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()
318 {
319         if (anchor_.size() < size()) {
320                 lyxerr << "anchor_.size() < cursor_.size() "
321                         "should not happen when accessing the anchor" << endl;
322                 BOOST_ASSERT(false);
323         }
324         BOOST_ASSERT(!anchor_.empty());
325         // this size is cursor_.size()
326         return anchor_[size() - 1];
327 }
328
329
330 CursorSlice const & LCursor::anchor() const
331 {
332         if (anchor_.size() < size()) {
333                 lyxerr << "anchor_.size() < cursor_.size() "
334                         "should not happen when accessing the anchor" << endl;
335                 BOOST_ASSERT(false);
336         }
337         // this size is cursor_.size()
338         BOOST_ASSERT(!anchor_.empty());
339         return anchor_[size() - 1];
340 }
341
342
343 CursorSlice const & LCursor::selBegin() const
344 {
345         if (!selection())
346                 return back();
347         return anchor() < back() ? anchor() : back();
348 }
349
350
351 CursorSlice const & LCursor::selEnd() const
352 {
353         if (!selection())
354                 return back();
355         return anchor() > back() ? anchor() : back();
356 }
357
358
359 DocIterator LCursor::selectionBegin() const
360 {
361         if (!selection())
362                 return *this;
363         return anchor() < back() ? anchor_ : *this;
364 }
365
366
367 DocIterator LCursor::selectionEnd() const
368 {
369         if (!selection())
370                 return *this;
371         return anchor() > back() ? anchor_ : *this;
372 }
373
374
375 void LCursor::setSelection()
376 {
377         selection() = true;
378         // a selection with no contents is not a selection
379 #warning doesnt look ok
380         if (par() == anchor().par() && pos() == anchor().pos())
381                 selection() = false;
382 }
383
384
385 void LCursor::setSelection(DocIterator const & where, size_t n)
386 {
387         setCursor(where, true);
388         anchor_ = where;
389         pos() += n;
390 }
391
392
393 void LCursor::clearSelection()
394 {
395         selection() = false;
396         mark() = false;
397         resetAnchor();
398         bv().unsetXSel();
399 }
400
401
402 int & LCursor::x_target()
403 {
404         return x_target_;
405 }
406
407
408 int LCursor::x_target() const
409 {
410         return x_target_;
411 }
412
413
414 void LCursor::clearTargetX()
415 {
416         x_target_ = -1;
417 }
418
419
420
421 void LCursor::info(std::ostream & os) const
422 {
423         for (int i = 1, n = depth(); i < n; ++i) {
424                 operator[](i).inset().infoize(os);
425                 os << "  ";
426         }
427         if (pos() != 0)
428                 prevInset()->infoize2(os);
429         // overwite old message
430         os << "                    ";
431 }
432
433
434 string LCursor::grabSelection()
435 {
436         if (!selection())
437                 return string();
438
439         CursorSlice i1 = selBegin();
440         CursorSlice i2 = selEnd();
441
442         if (i1.idx() == i2.idx()) {
443                 if (i1.inset().asMathInset()) {
444                         MathArray::const_iterator it = i1.cell().begin();
445                         return asString(MathArray(it + i1.pos(), it + i2.pos()));
446                 } else {
447                         return "unknown selection 1";
448                 }
449         }
450
451         row_type r1, r2;
452         col_type c1, c2;
453         region(i1, i2, r1, r2, c1, c2);
454
455         string data;
456         if (i1.inset().asMathInset()) {
457                 for (row_type row = r1; row <= r2; ++row) {
458                         if (row > r1)
459                                 data += "\\\\";
460                         for (col_type col = c1; col <= c2; ++col) {
461                                 if (col > c1)
462                                         data += '&';
463                                 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
464                         }
465                 }
466         } else {
467                 data = "unknown selection 2";
468         }
469         return data;
470 }
471
472
473 void LCursor::eraseSelection()
474 {
475         //lyxerr << "LCursor::eraseSelection" << endl;
476         CursorSlice const & i1 = selBegin();
477         CursorSlice const & i2 = selEnd();
478 #ifdef WITH_WARNINGS
479 #warning FIXME
480 #endif
481         if (i1.inset().asMathInset()) {
482                 if (i1.idx() == i2.idx()) {
483                         i1.cell().erase(i1.pos(), i2.pos());
484                 } else {
485                         MathInset * p = i1.asMathInset();
486                         row_type r1, r2;
487                         col_type c1, c2;
488                         region(i1, i2, r1, r2, c1, c2);
489                         for (row_type row = r1; row <= r2; ++row)
490                                 for (col_type col = c1; col <= c2; ++col)
491                                         p->cell(p->index(row, col)).clear();
492                 }
493                 back() = i1;
494         } else {
495                 lyxerr << "can't erase this selection 1" << endl;
496         }
497         //lyxerr << "LCursor::eraseSelection end" << endl;
498 }
499
500
501 string LCursor::grabAndEraseSelection()
502 {
503         if (!selection())
504                 return string();
505         string res = grabSelection();
506         eraseSelection();
507         selection() = false;
508         return res;
509 }
510
511
512 void LCursor::selCopy()
513 {
514         if (selection()) {
515                 theCutBuffer.push(grabSelection());
516                 selection() = false;
517         } else {
518                 //theCutBuffer.erase();
519         }
520 }
521
522
523 void LCursor::selCut()
524 {
525         theCutBuffer.push(grabAndEraseSelection());
526 }
527
528
529 void LCursor::selDel()
530 {
531         //lyxerr << "LCursor::selDel" << endl;
532         if (selection()) {
533                 eraseSelection();
534                 selection() = false;
535         }
536 }
537
538
539 void LCursor::selPaste(size_t n)
540 {
541         selClearOrDel();
542         if (n < theCutBuffer.size())
543                 paste(theCutBuffer[n]);
544         //grabSelection();
545         selection() = false;
546 }
547
548
549 void LCursor::selHandle(bool sel)
550 {
551         //lyxerr << "LCursor::selHandle" << endl;
552         if (sel == selection())
553                 return;
554         resetAnchor();
555         selection() = sel;
556 }
557
558
559 void LCursor::selClearOrDel()
560 {
561         //lyxerr << "LCursor::selClearOrDel" << endl;
562         if (lyxrc.auto_region_delete)
563                 selDel();
564         else
565                 selection() = false;
566 }
567
568
569 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
570 {
571         for (size_t i = 0, n = cur.size(); i != n; ++i) {
572                 os << " " << cur.operator[](i) << " | ";
573                 if (i < cur.anchor_.size())
574                         os << cur.anchor_[i];
575                 else
576                         os << "-------------------------------";
577                 os << "\n";
578         }
579         for (size_t i = cur.size(), n = cur.anchor_.size(); 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
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 MathNestInset).
595 //
596 ///////////////////////////////////////////////////////////////////
597
598 #include "mathed/math_charinset.h"
599 #include "mathed/math_factory.h"
600 #include "mathed/math_gridinset.h"
601 #include "mathed/math_macroarg.h"
602 #include "mathed/math_mathmlstream.h"
603 #include "mathed/math_scriptinset.h"
604 #include "mathed/math_support.h"
605 #include "mathed/math_unknowninset.h"
606
607 //#define FILEDEBUG 1
608
609
610 bool LCursor::isInside(InsetBase const * p)
611 {
612         for (unsigned i = 0; i < depth(); ++i)
613                 if (&operator[](i).inset() == p)
614                         return true;
615         return false;
616 }
617
618
619 bool LCursor::openable(MathAtom const & t) const
620 {
621         if (!t->isActive())
622                 return false;
623
624         if (t->lock())
625                 return false;
626
627         if (!selection())
628                 return true;
629
630         // we can't move into anything new during selection
631         if (depth() >= anchor_.size())
632                 return false;
633         if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
634                 return false;
635
636         return true;
637 }
638
639
640 bool positionable(DocIterator const & cursor,
641         DocIterator const & anchor)
642 {
643         // avoid deeper nested insets when selecting
644         if (cursor.size() > anchor.size())
645                 return false;
646
647         // anchor might be deeper, should have same path then
648         for (size_t i = 0; i < cursor.size(); ++i)
649                 if (&cursor[i].inset() != &anchor[i].inset())
650                         return false;
651
652         // position should be ok.
653         return true;
654 }
655
656
657 void LCursor::setScreenPos(int x, int y)
658 {
659         x_target() = x;
660         bruteFind(x, y, 0, bv().workWidth(), 0, bv().workHeight());
661 }
662
663
664
665 void LCursor::plainErase()
666 {
667         cell().erase(pos());
668 }
669
670
671 void LCursor::markInsert()
672 {
673         insert(char(0));
674 }
675
676
677 void LCursor::markErase()
678 {
679         cell().erase(pos());
680 }
681
682
683 void LCursor::plainInsert(MathAtom const & t)
684 {
685         cell().insert(pos(), t);
686         ++pos();
687 }
688
689
690 void LCursor::insert(string const & str)
691 {
692         //lyxerr << "LCursor::insert str '" << str << "'" << endl;
693         for (string::const_iterator it = str.begin(); it != str.end(); ++it)
694                 insert(*it);
695 }
696
697
698 void LCursor::insert(char c)
699 {
700         //lyxerr << "LCursor::insert char '" << c << "'" << endl;
701         BOOST_ASSERT(!empty());
702         if (inMathed()) {
703                 selClearOrDel();
704                 insert(new MathCharInset(c));
705         } else {
706                 text()->insertChar(*this, c);
707         }
708 }
709
710
711 void LCursor::insert(MathAtom const & t)
712 {
713         //lyxerr << "LCursor::insert MathAtom: " << endl;
714         macroModeClose();
715         selClearOrDel();
716         plainInsert(t);
717         lyxerr << "LCursor::insert MathAtom: cur:\n" << *this << endl;
718 }
719
720
721 void LCursor::insert(InsetBase * inset)
722 {
723         if (inMathed())
724                 insert(MathAtom(inset));
725         else
726                 text()->insertInset(*this, inset);
727 }
728
729
730 void LCursor::niceInsert(string const & t)
731 {
732         MathArray ar;
733         asArray(t, ar);
734         if (ar.size() == 1)
735                 niceInsert(ar[0]);
736         else
737                 insert(ar);
738 }
739
740
741 void LCursor::niceInsert(MathAtom const & t)
742 {
743         macroModeClose();
744         string safe = grabAndEraseSelection();
745         plainInsert(t);
746         // enter the new inset and move the contents of the selection if possible
747         if (t->isActive()) {
748                 posLeft();
749                 // be careful here: don't use 'pushLeft(t)' as this we need to
750                 // push the clone, not the original
751                 pushLeft(*nextInset());
752                 paste(safe);
753         }
754 }
755
756
757 void LCursor::insert(MathArray const & ar)
758 {
759         macroModeClose();
760         if (selection())
761                 eraseSelection();
762         cell().insert(pos(), ar);
763         pos() += ar.size();
764 }
765
766
767 bool LCursor::backspace()
768 {
769         autocorrect() = false;
770
771         if (selection()) {
772                 selDel();
773                 return true;
774         }
775
776         if (pos() == 0) {
777                 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
778                         return false;
779                 pullArg();
780                 return true;
781         }
782
783         if (inMacroMode()) {
784                 MathUnknownInset * p = activeMacro();
785                 if (p->name().size() > 1) {
786                         p->setName(p->name().substr(0, p->name().size() - 1));
787                         return true;
788                 }
789         }
790
791         if (pos() != 0 && prevAtom()->nargs() > 0) {
792                 // let's require two backspaces for 'big stuff' and
793                 // highlight on the first
794                 resetAnchor();
795                 selection() = true;
796                 --pos();
797         } else {
798                 --pos();
799                 plainErase();
800         }
801         return true;
802 }
803
804
805 bool LCursor::erase()
806 {
807         autocorrect() = false;
808         if (inMacroMode())
809                 return true;
810
811         if (selection()) {
812                 selDel();
813                 return true;
814         }
815
816         // delete empty cells if possible
817         if (pos() == lastpos() && inset().idxDelete(idx()))
818                 return true;
819
820         // special behaviour when in last position of cell
821         if (pos() == lastpos()) {
822                 bool one_cell = inset().nargs() == 1;
823                 if (one_cell && depth() == 1 && lastpos() == 0)
824                         return false;
825                 // remove markup
826                 if (one_cell)
827                         pullArg();
828                 else
829                         inset().idxGlue(idx());
830                 return true;
831         }
832
833         // 'clever' UI hack: only erase large items if previously slected
834         if (pos() != lastpos() && inset().nargs() > 0) {
835                 resetAnchor();
836                 selection() = true;
837                 ++pos();
838         } else {
839                 plainErase();
840         }
841
842         return true;
843 }
844
845
846 bool LCursor::up()
847 {
848         macroModeClose();
849         DocIterator save = *this;
850         if (goUpDown(true))
851                 return true;
852         setCursor(save, false);
853         autocorrect() = false;
854         return selection();
855 }
856
857
858 bool LCursor::down()
859 {
860         macroModeClose();
861         DocIterator save = *this;
862         if (goUpDown(false))
863                 return true;
864         setCursor(save, false);
865         autocorrect() = false;
866         return selection();
867 }
868
869
870 void LCursor::macroModeClose()
871 {
872         if (!inMacroMode())
873                 return;
874         MathUnknownInset * p = activeMacro();
875         p->finalize();
876         string s = p->name();
877         --pos();
878         cell().erase(pos());
879
880         // do nothing if the macro name is empty
881         if (s == "\\")
882                 return;
883
884         string const name = s.substr(1);
885
886         // prevent entering of recursive macros
887         InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
888         if (macro && macro->getInsetName() == name)
889                 lyxerr << "can't enter recursive macro" << endl;
890
891         niceInsert(createMathInset(name));
892 }
893
894
895 string LCursor::macroName()
896 {
897         return inMacroMode() ? activeMacro()->name() : string();
898 }
899
900
901 void LCursor::handleNest(MathAtom const & a, int c)
902 {
903         //lyxerr << "LCursor::handleNest: " << c << endl;
904         MathAtom t = a;
905         asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
906         insert(t);
907         posLeft();
908         pushLeft(*nextInset());
909 }
910
911
912 int LCursor::targetX() const
913 {
914         if (x_target() != -1)
915                 return x_target();
916         int x = 0;
917         int y = 0;
918         getPos(x, y);
919         return x;
920 }
921
922
923 void LCursor::adjust(pos_type from, int diff)
924 {
925         if (pos() > from)
926                 pos() += diff;
927         if (anchor().pos() > from)
928                 anchor().pos() += diff;
929         // just to be on the safe side
930         // theoretically unecessary
931         normalize();
932 }
933
934
935 bool LCursor::inMacroMode() const
936 {
937         if (!pos() != 0)
938                 return false;
939         MathUnknownInset const * p = prevAtom()->asUnknownInset();
940         return p && !p->final();
941 }
942
943
944 MathUnknownInset * LCursor::activeMacro()
945 {
946         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
947 }
948
949
950 void LCursor::pullArg()
951 {
952 #ifdef WITH_WARNINGS
953 #warning Look here
954 #endif
955         MathArray ar = cell();
956         if (popLeft() && inMathed()) {
957                 plainErase();
958                 cell().insert(pos(), ar);
959                 resetAnchor();
960         } else {
961                 //formula()->mutateToText();
962         }
963 }
964
965
966 void LCursor::touch()
967 {
968 #ifdef WITH_WARNINGS
969 #warning look here
970 #endif
971 #if 0
972         DocIterator::const_iterator it = begin();
973         DocIterator::const_iterator et = end();
974         for ( ; it != et; ++it)
975                 it->cell().touch();
976 #endif
977 }
978
979
980 void LCursor::normalize()
981 {
982         if (idx() >= nargs()) {
983                 lyxerr << "this should not really happen - 1: "
984                        << idx() << ' ' << nargs()
985                        << " in: " << &inset() << endl;
986         }
987         idx() = min(idx(), lastidx());
988
989         if (pos() > lastpos()) {
990                 lyxerr << "this should not really happen - 2: "
991                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
992                        << " in atom: '";
993                 WriteStream wi(lyxerr, false, true);
994                 inset().asMathInset()->write(wi);
995                 lyxerr << endl;
996         }
997         pos() = min(pos(), lastpos());
998 }
999
1000
1001 bool LCursor::goUpDown(bool up)
1002 {
1003         // Be warned: The 'logic' implemented in this function is highly
1004         // fragile. A distance of one pixel or a '<' vs '<=' _really
1005         // matters. So fiddle around with it only if you think you know
1006         // what you are doing!
1007
1008   int xo = 0;
1009         int yo = 0;
1010         getPos(xo, yo);
1011
1012         // check if we had something else in mind, if not, this is the future goal
1013         if (x_target() == -1)
1014                 x_target() = xo;
1015         else
1016                 xo = x_target();
1017
1018         // try neigbouring script insets
1019         if (!selection()) {
1020                 // try left
1021                 if (pos() != 0) {
1022                         MathScriptInset const * p = prevAtom()->asScriptInset();
1023                         if (p && p->has(up)) {
1024                                 --pos();
1025                                 push(inset());
1026                                 idx() = up; // the superscript has index 1
1027                                 pos() = lastpos();
1028                                 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1029                                 return true;
1030                         }
1031                 }
1032
1033                 // try right
1034                 if (pos() != lastpos()) {
1035                         MathScriptInset const * p = nextAtom()->asScriptInset();
1036                         if (p && p->has(up)) {
1037                                 push(inset());
1038                                 idx() = up;
1039                                 pos() = 0;
1040                                 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1041                                 return true;
1042                         }
1043                 }
1044         }
1045
1046         // try current cell for e.g. text insets
1047         if (inset().idxUpDown2(*this, up))
1048                 return true;
1049
1050         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1051         //if (up)
1052         //      yhigh = yo - 4;
1053         //else
1054         //      ylow = yo + 4;
1055         //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1056         //      lyxerr << "updown: handled by brute find in the same cell" << endl;
1057         //      return true;
1058         //}
1059
1060         // try to find an inset that knows better then we
1061         while (1) {
1062                 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1063                 // ask inset first
1064                 if (inset().idxUpDown(*this, up)) {
1065                         // try to find best position within this inset
1066                         if (!selection())
1067                                 bruteFind2(xo, yo);
1068                         return true;
1069                 }
1070
1071                 // no such inset found, just take something "above"
1072                 //lyxerr << "updown: handled by strange case" << endl;
1073                 if (!popLeft()) {
1074                         int ylow  = up ? 0 : yo + 1;
1075                         int yhigh = up ? yo - 1 : bv().workHeight();
1076                         return bruteFind(xo, yo, 0, bv().workWidth(), ylow, yhigh);
1077                 }
1078
1079                 // any improvement so far?
1080                 int xnew, ynew;
1081                 getPos(xnew, ynew);
1082                 if (up ? ynew < yo : ynew > yo)
1083                         return true;
1084         }
1085 }
1086
1087
1088 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1089 {
1090         BOOST_ASSERT(!empty());
1091         par_type beg, end;
1092         CursorSlice bottom = operator[](0);
1093         LyXText * text = bottom.text();
1094         BOOST_ASSERT(text);
1095         getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
1096
1097         DocIterator it = doc_iterator_begin(bv().buffer()->inset());
1098         DocIterator et = doc_iterator_end(bv().buffer()->inset());
1099         //lyxerr << "x: " << x << " y: " << y << endl;
1100         //lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
1101         //lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
1102
1103         it.par() = beg;
1104         //et.par() = text->parOffset(end);
1105
1106         double best_dist = 10e10;
1107         DocIterator best_cursor = it;
1108
1109         for ( ; it != et; it.forwardPos()) {
1110                 // avoid invalid nesting when selecting
1111                 if (!selection() || positionable(it, anchor_)) {
1112                         int xo = 0, yo = 0;
1113                         CursorSlice & cur = it.back();
1114                         cur.inset().getCursorPos(cur, xo, yo);
1115                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1116                                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1117                                 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
1118                                 // '<=' in order to take the last possible position
1119                                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1120                                 if (d <= best_dist) {
1121                                         //lyxerr << "*" << endl;
1122                                         best_dist   = d;
1123                                         best_cursor = it;
1124                                 }
1125                         }
1126                 }
1127         }
1128
1129         //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
1130         if (best_dist < 1e10)
1131                 setCursor(best_cursor, false);
1132         return best_dist < 1e10;
1133 }
1134
1135
1136 void LCursor::bruteFind2(int x, int y)
1137 {
1138         double best_dist = 1e10;
1139
1140         DocIterator it = *this;
1141         it.back().pos() = 0;
1142         DocIterator et = *this;
1143         et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
1144         for (int i = 0; ; ++i) {
1145                 int xo, yo;
1146                 CursorSlice & cur = it.back();
1147                 cur.inset().getCursorPos(cur, xo, yo);
1148                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1149                 // '<=' in order to take the last possible position
1150                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1151                 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1152                 if (d <= best_dist) {
1153                         best_dist = d;
1154                         setCursor(it, false);
1155                 }
1156                 if (it == et)
1157                         break;
1158                 it.forwardPos();
1159         }
1160 }
1161
1162
1163 CursorSlice LCursor::normalAnchor()
1164 {
1165         if (anchor_.size() < depth()) {
1166                 resetAnchor();
1167                 lyxerr << "unusual Anchor size" << endl;
1168         }
1169         //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1170         // use Anchor on the same level as Cursor
1171         CursorSlice normal = anchor_[size() - 1];
1172 #if 0
1173         if (depth() < anchor_.size() && !(normal < xx())) {
1174                 // anchor is behind cursor -> move anchor behind the inset
1175                 ++normal.pos_;
1176         }
1177 #endif
1178         return normal;
1179 }
1180
1181
1182 void LCursor::handleFont(string const & font)
1183 {
1184         lyxerr << "LCursor::handleFont: " << font << endl;
1185         string safe;
1186         if (selection()) {
1187                 macroModeClose();
1188                 safe = grabAndEraseSelection();
1189         }
1190
1191         if (lastpos() != 0) {
1192                 // something left in the cell
1193                 if (pos() == 0) {
1194                         // cursor in first position
1195                         popLeft();
1196                 } else if (pos() == lastpos()) {
1197                         // cursor in last position
1198                         popRight();
1199                 } else {
1200                         // cursor in between. split cell
1201                         MathArray::iterator bt = cell().begin();
1202                         MathAtom at = createMathInset(font);
1203                         at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1204                         cell().erase(bt, bt + pos());
1205                         popLeft();
1206                         plainInsert(at);
1207                 }
1208         } else {
1209                 // nothing left in the cell
1210                 pullArg();
1211                 plainErase();
1212         }
1213         insert(safe);
1214 }
1215
1216
1217 void LCursor::message(string const & msg) const
1218 {
1219         bv().owner()->getLyXFunc().setMessage(msg);
1220 }
1221
1222
1223 void LCursor::errorMessage(string const & msg) const
1224 {
1225         bv().owner()->getLyXFunc().setErrorMessage(msg);
1226 }
1227
1228
1229 string LCursor::selectionAsString(bool label) const
1230 {
1231         if (!selection())
1232                 return string();
1233
1234         if (inTexted()) {
1235                 Buffer const & buffer = *bv().buffer();
1236                 ParagraphList & pars = text()->paragraphs();
1237
1238                 // should be const ...
1239                 par_type startpit = selBegin().par();
1240                 par_type endpit = selEnd().par();
1241                 size_t const startpos = selBegin().pos();
1242                 size_t const endpos = selEnd().pos();
1243
1244                 if (startpit == endpit)
1245                         return pars[startpit].asString(buffer, startpos, endpos, label);
1246
1247                 // First paragraph in selection
1248                 string result = pars[startpit].
1249                         asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1250
1251                 // The paragraphs in between (if any)
1252                 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1253                         Paragraph & par = pars[pit];
1254                         result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1255                 }
1256
1257                 // Last paragraph in selection
1258                 result += pars[endpit].asString(buffer, 0, endpos, label);
1259
1260                 return result;
1261         }
1262
1263 #ifdef WITH_WARNINGS
1264 #warning and mathed?
1265 #endif
1266         return string();
1267 }
1268
1269
1270 string LCursor::currentState()
1271 {
1272         if (inMathed()) {
1273                 std::ostringstream os;
1274                 info(os);
1275                 return os.str();
1276         }
1277
1278         if (inTexted())
1279          return text()->currentState(*this);
1280
1281         return string();
1282 }
1283
1284
1285 string LCursor::getPossibleLabel()
1286 {
1287         return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1288 }
1289
1290
1291 Encoding const * LCursor::getEncoding() const
1292 {
1293         if (empty())
1294                 return 0;
1295         if (!bv().buffer())
1296                 return 0;
1297         int s = 0;
1298         // go up until first non-0 text is hit
1299         // (innermost text is 0 in mathed)
1300         for (s = size() - 1; s >= 0; --s)
1301                 if (operator[](s).text())
1302                         break;
1303         CursorSlice const & sl = operator[](s);
1304         LyXText & text = *sl.text();
1305         LyXFont font = text.getPar(sl.par()).getFont(
1306                 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1307         return font.language()->encoding();
1308 }
1309
1310
1311 void LCursor::undispatched()
1312 {
1313         disp_.dispatched(false);
1314 }
1315
1316
1317 void LCursor::dispatched()
1318 {
1319         disp_.dispatched(true);
1320 }
1321
1322
1323 void LCursor::noUpdate()
1324 {
1325         disp_.update(false);
1326 }