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