]> git.lyx.org Git - lyx.git/blob - src/cursor.C
Use 'assign' as the name for the operation that opens/closes branch
[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         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 DocIterator LCursor::selectionBegin() const
348 {
349         if (!selection())
350                 return *this;
351         return anchor() < back() ? anchor_ : *this;
352 }
353
354
355 DocIterator 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(DocIterator const & where, size_t n)
373 {
374         setCursor(where, true);
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 #ifdef WITH_WARNINGS
466 #warning FIXME
467 #endif
468         if (i1.inset().asMathInset()) {
469                 if (i1.idx() == i2.idx()) {
470                         i1.cell().erase(i1.pos(), i2.pos());
471                 } else {
472                         MathInset * p = i1.asMathInset();
473                         row_type r1, r2;
474                         col_type c1, c2;
475                         region(i1, i2, r1, r2, c1, c2);
476                         for (row_type row = r1; row <= r2; ++row)
477                                 for (col_type col = c1; col <= c2; ++col)
478                                         p->cell(p->index(row, col)).clear();
479                 }
480                 back() = i1;
481         } else {
482                 lyxerr << "can't erase this selection 1" << endl;
483         }
484         //lyxerr << "LCursor::eraseSelection end" << endl;
485 }
486
487
488 string LCursor::grabAndEraseSelection()
489 {
490         if (!selection())
491                 return string();
492         string res = grabSelection();
493         eraseSelection();
494         selection() = false;
495         return res;
496 }
497
498
499 void LCursor::selClear()
500 {
501         resetAnchor();
502         clearSelection();
503 }
504
505
506 void LCursor::selCopy()
507 {
508         if (selection()) {
509                 theCutBuffer.push(grabSelection());
510                 selection() = false;
511         } else {
512                 //theCutBuffer.erase();
513         }
514 }
515
516
517 void LCursor::selCut()
518 {
519         theCutBuffer.push(grabAndEraseSelection());
520 }
521
522
523 void LCursor::selDel()
524 {
525         //lyxerr << "LCursor::selDel" << endl;
526         if (selection()) {
527                 eraseSelection();
528                 selection() = false;
529         }
530 }
531
532
533 void LCursor::selPaste(size_t n)
534 {
535         selClearOrDel();
536         if (n < theCutBuffer.size())
537                 paste(theCutBuffer[n]);
538         //grabSelection();
539         selection() = false;
540 }
541
542
543 void LCursor::selHandle(bool sel)
544 {
545         //lyxerr << "LCursor::selHandle" << endl;
546         if (sel == selection())
547                 return;
548         resetAnchor();
549         selection() = sel;
550 }
551
552
553 void LCursor::selClearOrDel()
554 {
555         //lyxerr << "LCursor::selClearOrDel" << endl;
556         if (lyxrc.auto_region_delete)
557                 selDel();
558         else
559                 selection() = false;
560 }
561
562
563 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
564 {
565         for (size_t i = 0, n = cur.size(); i != n; ++i) {
566                 os << " " << cur.operator[](i) << " | ";
567                 if (i < cur.anchor_.size())
568                         os << cur.anchor_[i];
569                 else
570                         os << "-------------------------------";
571                 os << "\n";
572         }
573         for (size_t i = cur.size(), n = cur.anchor_.size(); i < n; ++i) {
574                 os << "------------------------------- | " << cur.anchor_[i] << "\n";
575         }
576         os << " selection: " << cur.selection_
577            << " x_target: " << cur.x_target_ << endl;
578         return os;
579 }
580
581
582
583
584 ///////////////////////////////////////////////////////////////////
585 //
586 // The part below is the non-integrated rest of the original math
587 // cursor. This should be either generalized for texted or moved
588 // back to mathed (in most cases to MathNestInset).
589 //
590 ///////////////////////////////////////////////////////////////////
591
592 #include "mathed/math_charinset.h"
593 #include "mathed/math_factory.h"
594 #include "mathed/math_gridinset.h"
595 #include "mathed/math_macroarg.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(DocIterator const & cursor,
635         DocIterator 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         insert(char(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                 insert(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         lyxerr << "LCursor::insert MathAtom: cur:\n" << *this << endl;
712 }
713
714
715 void LCursor::insert(InsetBase * inset)
716 {
717         if (inMathed())
718                 insert(MathAtom(inset));
719         else
720                 text()->insertInset(*this, inset);
721 }
722
723
724 void LCursor::niceInsert(string const & t)
725 {
726         MathArray ar;
727         asArray(t, ar);
728         if (ar.size() == 1)
729                 niceInsert(ar[0]);
730         else
731                 insert(ar);
732 }
733
734
735 void LCursor::niceInsert(MathAtom const & t)
736 {
737         macroModeClose();
738         string safe = grabAndEraseSelection();
739         plainInsert(t);
740         // enter the new inset and move the contents of the selection if possible
741         if (t->isActive()) {
742                 posLeft();
743                 // be careful here: don't use 'pushLeft(t)' as this we need to
744                 // push the clone, not the original
745                 pushLeft(*nextInset());
746                 paste(safe);
747         }
748 }
749
750
751 void LCursor::insert(MathArray const & ar)
752 {
753         macroModeClose();
754         if (selection())
755                 eraseSelection();
756         cell().insert(pos(), ar);
757         pos() += ar.size();
758 }
759
760
761 bool LCursor::backspace()
762 {
763         autocorrect() = false;
764
765         if (selection()) {
766                 selDel();
767                 return true;
768         }
769
770         if (pos() == 0) {
771                 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
772                         return false;
773                 pullArg();
774                 return true;
775         }
776
777         if (inMacroMode()) {
778                 MathUnknownInset * p = activeMacro();
779                 if (p->name().size() > 1) {
780                         p->setName(p->name().substr(0, p->name().size() - 1));
781                         return true;
782                 }
783         }
784
785         if (pos() != 0 && prevAtom()->nargs() > 0) {
786                 // let's require two backspaces for 'big stuff' and
787                 // highlight on the first
788                 resetAnchor();
789                 selection() = true;
790                 --pos();
791         } else {
792                 --pos();
793                 plainErase();
794         }
795         return true;
796 }
797
798
799 bool LCursor::erase()
800 {
801         autocorrect() = false;
802         if (inMacroMode())
803                 return true;
804
805         if (selection()) {
806                 selDel();
807                 return true;
808         }
809
810         // delete empty cells if possible
811         if (pos() == lastpos() && inset().idxDelete(idx()))
812                 return true;
813
814         // special behaviour when in last position of cell
815         if (pos() == lastpos()) {
816                 bool one_cell = inset().nargs() == 1;
817                 if (one_cell && depth() == 1 && lastpos() == 0)
818                         return false;
819                 // remove markup
820                 if (one_cell)
821                         pullArg();
822                 else
823                         inset().idxGlue(idx());
824                 return true;
825         }
826
827         // 'clever' UI hack: only erase large items if previously slected
828         if (pos() != lastpos() && inset().nargs() > 0) {
829                 resetAnchor();
830                 selection() = true;
831                 ++pos();
832         } else {
833                 plainErase();
834         }
835
836         return true;
837 }
838
839
840 bool LCursor::up()
841 {
842         macroModeClose();
843         DocIterator save = *this;
844         if (goUpDown(true))
845                 return true;
846         setCursor(save, false);
847         autocorrect() = false;
848         return selection();
849 }
850
851
852 bool LCursor::down()
853 {
854         macroModeClose();
855         DocIterator save = *this;
856         if (goUpDown(false))
857                 return true;
858         setCursor(save, false);
859         autocorrect() = false;
860         return selection();
861 }
862
863
864 void LCursor::macroModeClose()
865 {
866         if (!inMacroMode())
867                 return;
868         MathUnknownInset * p = activeMacro();
869         p->finalize();
870         string s = p->name();
871         --pos();
872         cell().erase(pos());
873
874         // do nothing if the macro name is empty
875         if (s == "\\")
876                 return;
877
878         string const name = s.substr(1);
879
880         // prevent entering of recursive macros
881         InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
882         if (macro && macro->getInsetName() == name)
883                 lyxerr << "can't enter recursive macro" << endl;
884
885         niceInsert(createMathInset(name));
886 }
887
888
889 string LCursor::macroName()
890 {
891         return inMacroMode() ? activeMacro()->name() : string();
892 }
893
894
895 void LCursor::handleNest(MathAtom const & a, int c)
896 {
897         //lyxerr << "LCursor::handleNest: " << c << endl;
898         MathAtom t = a;
899         asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
900         insert(t);
901         posLeft();
902         pushLeft(*nextInset());
903 }
904
905
906 int LCursor::targetX() const
907 {
908         if (x_target() != -1)
909                 return x_target();
910         int x = 0;
911         int y = 0;
912         getPos(x, y);
913         return x;
914 }
915
916
917 void LCursor::adjust(pos_type from, int diff)
918 {
919         if (pos() > from)
920                 pos() += diff;
921         if (anchor().pos() > from)
922                 anchor().pos() += diff;
923         // just to be on the safe side
924         // theoretically unecessary
925         normalize();
926 }
927
928
929 bool LCursor::inMacroMode() const
930 {
931         if (!pos() != 0)
932                 return false;
933         MathUnknownInset const * p = prevAtom()->asUnknownInset();
934         return p && !p->final();
935 }
936
937
938 MathUnknownInset * LCursor::activeMacro()
939 {
940         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
941 }
942
943
944 void LCursor::pullArg()
945 {
946 #ifdef WITH_WARNINGS
947 #warning Look here
948 #endif
949         MathArray ar = cell();
950         if (popLeft() && inMathed()) {
951                 plainErase();
952                 cell().insert(pos(), ar);
953                 resetAnchor();
954         } else {
955                 //formula()->mutateToText();
956         }
957 }
958
959
960 void LCursor::touch()
961 {
962 #ifdef WITH_WARNINGS
963 #warning look here
964 #endif
965 #if 0
966         DocIterator::const_iterator it = begin();
967         DocIterator::const_iterator et = end();
968         for ( ; it != et; ++it)
969                 it->cell().touch();
970 #endif
971 }
972
973
974 void LCursor::normalize()
975 {
976         if (idx() >= nargs()) {
977                 lyxerr << "this should not really happen - 1: "
978                        << idx() << ' ' << nargs()
979                        << " in: " << &inset() << endl;
980         }
981         idx() = min(idx(), lastidx());
982
983         if (pos() > lastpos()) {
984                 lyxerr << "this should not really happen - 2: "
985                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
986                        << " in atom: '";
987                 WriteStream wi(lyxerr, false, true);
988                 inset().asMathInset()->write(wi);
989                 lyxerr << endl;
990         }
991         pos() = min(pos(), lastpos());
992 }
993
994
995 bool LCursor::goUpDown(bool up)
996 {
997         // Be warned: The 'logic' implemented in this function is highly
998         // fragile. A distance of one pixel or a '<' vs '<=' _really
999         // matters. So fiddle around with it only if you think you know
1000         // what you are doing!
1001
1002   int xo = 0;
1003         int yo = 0;
1004         getPos(xo, yo);
1005
1006         // check if we had something else in mind, if not, this is the future goal
1007         if (x_target() == -1)
1008                 x_target() = xo;
1009         else
1010                 xo = x_target();
1011
1012         // try neigbouring script insets
1013         if (!selection()) {
1014                 // try left
1015                 if (pos() != 0) {
1016                         MathScriptInset const * p = prevAtom()->asScriptInset();
1017                         if (p && p->has(up)) {
1018                                 --pos();
1019                                 push(inset());
1020                                 idx() = up; // the superscript has index 1
1021                                 pos() = lastpos();
1022                                 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1023                                 return true;
1024                         }
1025                 }
1026
1027                 // try right
1028                 if (pos() != lastpos()) {
1029                         MathScriptInset const * p = nextAtom()->asScriptInset();
1030                         if (p && p->has(up)) {
1031                                 push(inset());
1032                                 idx() = up;
1033                                 pos() = 0;
1034                                 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1035                                 return true;
1036                         }
1037                 }
1038         }
1039
1040         // try current cell for e.g. text insets
1041         if (inset().idxUpDown2(*this, up))
1042                 return true;
1043
1044         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1045         //if (up)
1046         //      yhigh = yo - 4;
1047         //else
1048         //      ylow = yo + 4;
1049         //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1050         //      lyxerr << "updown: handled by brute find in the same cell" << endl;
1051         //      return true;
1052         //}
1053
1054         // try to find an inset that knows better then we
1055         while (1) {
1056                 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1057                 // ask inset first
1058                 if (inset().idxUpDown(*this, up)) {
1059                         // try to find best position within this inset
1060                         if (!selection())
1061                                 bruteFind2(xo, yo);
1062                         return true;
1063                 }
1064
1065                 // no such inset found, just take something "above"
1066                 //lyxerr << "updown: handled by strange case" << endl;
1067                 if (!popLeft()) {
1068                         int ylow  = up ? 0 : yo + 1;
1069                         int yhigh = up ? yo - 1 : bv().workHeight();
1070                         return bruteFind(xo, yo, 0, bv().workWidth(), ylow, yhigh);
1071                 }
1072
1073                 // any improvement so far?
1074                 int xnew, ynew;
1075                 getPos(xnew, ynew);
1076                 if (up ? ynew < yo : ynew > yo)
1077                         return true;
1078         }
1079 }
1080
1081
1082 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1083 {
1084         BOOST_ASSERT(!empty());
1085         par_type beg, end;
1086         CursorSlice bottom = operator[](0);
1087         LyXText * text = bottom.text();
1088         BOOST_ASSERT(text);
1089         getParsInRange(text->paragraphs(), ylow, yhigh, beg, end);
1090
1091         DocIterator it = doc_iterator_begin(bv().buffer()->inset());
1092         DocIterator et = doc_iterator_end(bv().buffer()->inset());
1093         //lyxerr << "x: " << x << " y: " << y << endl;
1094         //lyxerr << "xlow: " << xlow << " ylow: " << ylow << endl;
1095         //lyxerr << "xhigh: " << xhigh << " yhigh: " << yhigh << endl;
1096
1097         it.par() = beg;
1098         //et.par() = text->parOffset(end);
1099
1100         double best_dist = 10e10;
1101         DocIterator best_cursor = it;
1102
1103         for ( ; it != et; it.forwardPos()) {
1104                 // avoid invalid nesting when selecting
1105                 if (!selection() || positionable(it, anchor_)) {
1106                         int xo = 0, yo = 0;
1107                         CursorSlice & cur = it.back();
1108                         cur.inset().getCursorPos(cur, xo, yo);
1109                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1110                                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1111                                 //lyxerr << "xo: " << xo << " yo: " << yo << " d: " << d << endl;
1112                                 // '<=' in order to take the last possible position
1113                                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1114                                 if (d <= best_dist) {
1115                                         //lyxerr << "*" << endl;
1116                                         best_dist   = d;
1117                                         best_cursor = it;
1118                                 }
1119                         }
1120                 }
1121         }
1122
1123         //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
1124         if (best_dist < 1e10)
1125                 setCursor(best_cursor, false);
1126         return best_dist < 1e10;
1127 }
1128
1129
1130 void LCursor::bruteFind2(int x, int y)
1131 {
1132         double best_dist = 1e10;
1133
1134         DocIterator it = *this;
1135         it.back().pos() = 0;
1136         DocIterator et = *this;
1137         et.back().pos() = et.back().asMathInset()->cell(et.back().idx()).size();
1138         for (int i = 0; ; ++i) {
1139                 int xo, yo;
1140                 CursorSlice & cur = it.back();
1141                 cur.inset().getCursorPos(cur, xo, yo);
1142                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1143                 // '<=' in order to take the last possible position
1144                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1145                 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1146                 if (d <= best_dist) {
1147                         best_dist = d;
1148                         setCursor(it, false);
1149                 }
1150                 if (it == et)
1151                         break;
1152                 it.forwardPos();
1153         }
1154 }
1155
1156
1157 CursorSlice LCursor::normalAnchor()
1158 {
1159         if (anchor_.size() < depth()) {
1160                 resetAnchor();
1161                 lyxerr << "unusual Anchor size" << endl;
1162         }
1163         //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1164         // use Anchor on the same level as Cursor
1165         CursorSlice normal = anchor_[size() - 1];
1166 #if 0
1167         if (depth() < anchor_.size() && !(normal < xx())) {
1168                 // anchor is behind cursor -> move anchor behind the inset
1169                 ++normal.pos_;
1170         }
1171 #endif
1172         return normal;
1173 }
1174
1175
1176 void LCursor::handleFont(string const & font)
1177 {
1178         lyxerr << "LCursor::handleFont: " << font << endl;
1179         string safe;
1180         if (selection()) {
1181                 macroModeClose();
1182                 safe = grabAndEraseSelection();
1183         }
1184
1185         if (lastpos() != 0) {
1186                 // something left in the cell
1187                 if (pos() == 0) {
1188                         // cursor in first position
1189                         popLeft();
1190                 } else if (pos() == lastpos()) {
1191                         // cursor in last position
1192                         popRight();
1193                 } else {
1194                         // cursor in between. split cell
1195                         MathArray::iterator bt = cell().begin();
1196                         MathAtom at = createMathInset(font);
1197                         at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1198                         cell().erase(bt, bt + pos());
1199                         popLeft();
1200                         plainInsert(at);
1201                 }
1202         } else {
1203                 // nothing left in the cell
1204                 pullArg();
1205                 plainErase();
1206         }
1207         insert(safe);
1208 }
1209
1210
1211 void LCursor::message(string const & msg) const
1212 {
1213         bv().owner()->getLyXFunc().setMessage(msg);
1214 }
1215
1216
1217 void LCursor::errorMessage(string const & msg) const
1218 {
1219         bv().owner()->getLyXFunc().setErrorMessage(msg);
1220 }
1221
1222
1223 string LCursor::selectionAsString(bool label) const
1224 {
1225         if (!selection())
1226                 return string();
1227
1228         if (inTexted()) {
1229                 Buffer const & buffer = *bv().buffer();
1230                 ParagraphList & pars = text()->paragraphs();
1231
1232                 // should be const ...
1233                 par_type startpit = selBegin().par();
1234                 par_type endpit = selEnd().par();
1235                 size_t const startpos = selBegin().pos();
1236                 size_t const endpos = selEnd().pos();
1237
1238                 if (startpit == endpit)
1239                         return pars[startpit].asString(buffer, startpos, endpos, label);
1240
1241                 // First paragraph in selection
1242                 string result = pars[startpit].
1243                         asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1244
1245                 // The paragraphs in between (if any)
1246                 for (par_type pit = startpit + 1; pit != endpit; ++pit) {
1247                         Paragraph & par = pars[pit];
1248                         result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1249                 }
1250
1251                 // Last paragraph in selection
1252                 result += pars[endpit].asString(buffer, 0, endpos, label);
1253
1254                 return result;
1255         }
1256
1257 #ifdef WITH_WARNINGS
1258 #warning and mathed?
1259 #endif
1260         return string();
1261 }
1262
1263
1264 string LCursor::currentState()
1265 {
1266         if (inMathed()) {
1267                 std::ostringstream os;
1268                 info(os);
1269                 return os.str();
1270         }
1271
1272         if (inTexted())
1273          return text()->currentState(*this);
1274
1275         return string();
1276 }
1277
1278
1279 string LCursor::getPossibleLabel()
1280 {
1281         return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1282 }
1283
1284
1285 Encoding const * LCursor::getEncoding() const
1286 {
1287         if (empty())
1288                 return 0;
1289         if (!bv().buffer())
1290                 return 0;
1291         int s = 0;
1292         // go up until first non-0 text is hit
1293         // (innermost text is 0 in mathed)
1294         for (s = size() - 1; s >= 0; --s)
1295                 if (operator[](s).text())
1296                         break;
1297         CursorSlice const & sl = operator[](s);
1298         LyXText & text = *sl.text();
1299         LyXFont font = text.getPar(sl.par()).getFont(
1300                 bv().buffer()->params(), sl.pos(), outerFont(sl.par(), text.paragraphs()));
1301         return font.language()->encoding();
1302 }
1303
1304
1305 void LCursor::undispatched()
1306 {
1307         disp_.dispatched(false);
1308 }
1309
1310
1311 void LCursor::dispatched()
1312 {
1313         disp_.dispatched(true);
1314 }
1315
1316
1317 void LCursor::noUpdate()
1318 {
1319         disp_.update(false);
1320 }