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