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