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