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