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