]> git.lyx.org Git - lyx.git/blob - src/cursor.C
remove unused stuff
[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 void LCursor::resetAnchor()
407 {
408         anchor_ = *this;
409 }
410
411
412
413 bool LCursor::posLeft()
414 {
415         if (pos() == 0)
416                 return false;
417         --pos();
418         return true;
419 }
420
421
422 bool LCursor::posRight()
423 {
424         if (pos() == lastpos())
425                 return false;
426         ++pos();
427         return true;
428 }
429
430
431 CursorSlice LCursor::anchor() const
432 {
433         BOOST_ASSERT(anchor_.depth() >= depth());
434         CursorSlice normal = anchor_[depth() - 1];
435         if (depth() < anchor_.depth() && top() <= normal) {
436                 // anchor is behind cursor -> move anchor behind the inset
437                 ++normal.pos();
438         }
439         return normal;
440 }
441
442
443 CursorSlice LCursor::selBegin() const
444 {
445         if (!selection())
446                 return top();
447         return anchor() < top() ? anchor() : top();
448 }
449
450
451 CursorSlice LCursor::selEnd() const
452 {
453         if (!selection())
454                 return top();
455         return anchor() > top() ? anchor() : top();
456 }
457
458
459 DocIterator LCursor::selectionBegin() const
460 {
461         if (!selection())
462                 return *this;
463         DocIterator di = (anchor() < top() ? anchor_ : *this);
464         di.resize(depth());
465         return di;
466 }
467
468
469 DocIterator LCursor::selectionEnd() const
470 {
471         if (!selection())
472                 return *this;
473         DocIterator di = (anchor() > top() ? anchor_ : *this);
474         if (di.depth() > depth()) {
475                 di.resize(depth());
476                 ++di.pos();
477         }
478         return di;
479 }
480
481
482 void LCursor::setSelection()
483 {
484         selection() = true;
485         // A selection with no contents is not a selection
486 #ifdef WITH_WARNINGS
487 #warning doesnt look ok
488 #endif
489         if (pit() == anchor().pit() && pos() == anchor().pos())
490                 selection() = false;
491 }
492
493
494 void LCursor::setSelection(DocIterator const & where, int n)
495 {
496         setCursor(where);
497         selection() = true;
498         anchor_ = where;
499         pos() += n;
500 }
501
502
503 void LCursor::clearSelection()
504 {
505         selection() = false;
506         mark() = false;
507         resetAnchor();
508 }
509
510
511 int & LCursor::x_target()
512 {
513         return x_target_;
514 }
515
516
517 int LCursor::x_target() const
518 {
519         return x_target_;
520 }
521
522
523 void LCursor::clearTargetX()
524 {
525         x_target_ = -1;
526 }
527
528
529
530 void LCursor::info(odocstream & os) const
531 {
532         for (int i = 1, n = depth(); i < n; ++i) {
533                 operator[](i).inset().infoize(os);
534                 os << "  ";
535         }
536         if (pos() != 0)
537                 prevInset()->infoize2(os);
538         // overwite old message
539         os << "                    ";
540 }
541
542
543 bool LCursor::selHandle(bool sel)
544 {
545         //lyxerr << "LCursor::selHandle" << endl;
546         if (sel == selection())
547                 return false;
548
549         resetAnchor();
550         selection() = sel;
551         return true;
552 }
553
554
555 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
556 {
557         os << "\n cursor:                                | anchor:\n";
558         for (size_t i = 0, n = cur.depth(); i != n; ++i) {
559                 os << " " << cur[i] << " | ";
560                 if (i < cur.anchor_.depth())
561                         os << cur.anchor_[i];
562                 else
563                         os << "-------------------------------";
564                 os << "\n";
565         }
566         for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
567                 os << "------------------------------- | " << cur.anchor_[i] << "\n";
568         }
569         os << " selection: " << cur.selection_
570            << " x_target: " << cur.x_target_ << endl;
571         return os;
572 }
573
574 } // namespace lyx
575
576
577 ///////////////////////////////////////////////////////////////////
578 //
579 // The part below is the non-integrated rest of the original math
580 // cursor. This should be either generalized for texted or moved
581 // back to mathed (in most cases to InsetMathNest).
582 //
583 ///////////////////////////////////////////////////////////////////
584
585 #include "mathed/InsetMathChar.h"
586 #include "mathed/InsetMathGrid.h"
587 #include "mathed/InsetMathScript.h"
588 #include "mathed/InsetMathUnknown.h"
589 #include "mathed/MathFactory.h"
590 #include "mathed/MathMacroArgument.h"
591 #include "mathed/MathStream.h"
592 #include "mathed/MathSupport.h"
593
594
595 namespace lyx {
596
597 //#define FILEDEBUG 1
598
599
600 bool LCursor::isInside(InsetBase const * p)
601 {
602         for (size_t i = 0; i != depth(); ++i)
603                 if (&operator[](i).inset() == p)
604                         return true;
605         return false;
606 }
607
608
609 void LCursor::leaveInset(InsetBase const & inset)
610 {
611         for (size_t i = 0; i != depth(); ++i) {
612                 if (&operator[](i).inset() == &inset) {
613                         resize(i);
614                         return;
615                 }
616         }
617 }
618
619
620 bool LCursor::openable(MathAtom const & t) const
621 {
622         if (!t->isActive())
623                 return false;
624
625         if (t->lock())
626                 return false;
627
628         if (!selection())
629                 return true;
630
631         // we can't move into anything new during selection
632         if (depth() >= anchor_.depth())
633                 return false;
634         if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
635                 return false;
636
637         return true;
638 }
639
640
641 void LCursor::setScreenPos(int x, int y)
642 {
643         x_target() = x;
644         bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
645 }
646
647
648
649 void LCursor::plainErase()
650 {
651         cell().erase(pos());
652 }
653
654
655 void LCursor::markInsert()
656 {
657         insert(char_type(0));
658 }
659
660
661 void LCursor::markErase()
662 {
663         cell().erase(pos());
664 }
665
666
667 void LCursor::plainInsert(MathAtom const & t)
668 {
669         cell().insert(pos(), t);
670         ++pos();
671 }
672
673
674 void LCursor::insert(docstring const & str)
675 {
676         for_each(str.begin(), str.end(),
677                  boost::bind(static_cast<void(LCursor::*)(char_type)>
678                              (&LCursor::insert), this, _1));
679 }
680
681
682 void LCursor::insert(char_type c)
683 {
684         //lyxerr << "LCursor::insert char '" << c << "'" << endl;
685         BOOST_ASSERT(!empty());
686         if (inMathed()) {
687                 cap::selClearOrDel(*this);
688                 insert(new InsetMathChar(c));
689         } else {
690                 text()->insertChar(*this, c);
691         }
692 }
693
694
695 void LCursor::insert(MathAtom const & t)
696 {
697         //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
698         macroModeClose();
699         cap::selClearOrDel(*this);
700         plainInsert(t);
701 }
702
703
704 void LCursor::insert(InsetBase * inset)
705 {
706         if (inMathed())
707                 insert(MathAtom(inset));
708         else
709                 text()->insertInset(*this, inset);
710 }
711
712
713 void LCursor::niceInsert(docstring const & t)
714 {
715         MathArray ar;
716         asArray(t, ar);
717         if (ar.size() == 1)
718                 niceInsert(ar[0]);
719         else
720                 insert(ar);
721 }
722
723
724 void LCursor::niceInsert(MathAtom const & t)
725 {
726         macroModeClose();
727         docstring const safe = cap::grabAndEraseSelection(*this);
728         plainInsert(t);
729         // enter the new inset and move the contents of the selection if possible
730         if (t->isActive()) {
731                 posLeft();
732                 // be careful here: don't use 'pushLeft(t)' as this we need to
733                 // push the clone, not the original
734                 pushLeft(*nextInset());
735                 // We may not use niceInsert here (recursion)
736                 MathArray ar;
737                 asArray(safe, ar);
738                 insert(ar);
739         }
740 }
741
742
743 void LCursor::insert(MathArray const & ar)
744 {
745         macroModeClose();
746         if (selection())
747                 cap::eraseSelection(*this);
748         cell().insert(pos(), ar);
749         pos() += ar.size();
750 }
751
752
753 bool LCursor::backspace()
754 {
755         autocorrect() = false;
756
757         if (selection()) {
758                 cap::selDel(*this);
759                 return true;
760         }
761
762         if (pos() == 0) {
763                 // If empty cell, and not part of a big cell
764                 if (lastpos() == 0 && inset().nargs() == 1) {
765                         popLeft();
766                         // Directly delete empty cell: [|[]] => [|] 
767                         if (inMathed()) {
768                                 plainErase();
769                                 resetAnchor();
770                                 return true;
771                         }
772                         // [|], can not delete from inside
773                         return false;
774                 } else {
775                         // move to left
776                         popLeft();
777                         return true;
778                 }
779         }
780
781         if (inMacroMode()) {
782                 InsetMathUnknown * p = activeMacro();
783                 if (p->name().size() > 1) {
784                         p->setName(p->name().substr(0, p->name().size() - 1));
785                         return true;
786                 }
787         }
788
789         if (pos() != 0 && prevAtom()->nargs() > 0) {
790                 // let's require two backspaces for 'big stuff' and
791                 // highlight on the first
792                 resetAnchor();
793                 selection() = true;
794                 --pos();
795         } else {
796                 --pos();
797                 plainErase();
798         }
799         return true;
800 }
801
802
803 bool LCursor::erase()
804 {
805         autocorrect() = false;
806         if (inMacroMode())
807                 return true;
808
809         if (selection()) {
810                 cap::selDel(*this);
811                 return true;
812         }
813
814         // delete empty cells if possible
815         if (pos() == lastpos() && inset().idxDelete(idx()))
816                 return true;
817
818         // special behaviour when in last position of cell
819         if (pos() == lastpos()) {
820                 bool one_cell = inset().nargs() == 1;
821                 if (one_cell && lastpos() == 0) {
822                         popLeft();
823                         // Directly delete empty cell: [|[]] => [|] 
824                         if (inMathed()) {
825                                 plainErase();
826                                 resetAnchor();
827                                 return true;
828                         }
829                         // [|], can not delete from inside
830                         return false;
831                 }
832                 // remove markup
833                 if (!one_cell)
834                         inset().idxGlue(idx());
835                 return true;
836         }
837
838         // 'clever' UI hack: only erase large items if previously slected
839         if (pos() != lastpos() && nextAtom()->nargs() > 0) {
840                 resetAnchor();
841                 selection() = true;
842                 ++pos();
843         } else {
844                 plainErase();
845         }
846
847         return true;
848 }
849
850
851 bool LCursor::up()
852 {
853         macroModeClose();
854         DocIterator save = *this;
855         if (goUpDown(true))
856                 return true;
857         setCursor(save);
858         autocorrect() = false;
859         return selection();
860 }
861
862
863 bool LCursor::down()
864 {
865         macroModeClose();
866         DocIterator save = *this;
867         if (goUpDown(false))
868                 return true;
869         setCursor(save);
870         autocorrect() = false;
871         return selection();
872 }
873
874
875 bool LCursor::macroModeClose()
876 {
877         if (!inMacroMode())
878                 return false;
879         InsetMathUnknown * p = activeMacro();
880         p->finalize();
881         docstring const s = p->name();
882         --pos();
883         cell().erase(pos());
884
885         // do nothing if the macro name is empty
886         if (s == "\\")
887                 return false;
888
889         // prevent entering of recursive macros
890         // FIXME: this is only a weak attempt... only prevents immediate
891         // recursion
892         docstring const name = s.substr(1);
893         InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
894         if (macro && macro->getInsetName() == name)
895                 lyxerr << "can't enter recursive macro" << endl;
896
897         InsetMathNest * const in = inset().asInsetMath()->asNestInset();
898         if (in && in->interpretString(*this, s))
899                 return true;
900         plainInsert(createInsetMath(name));
901         return true;
902 }
903
904
905 docstring LCursor::macroName()
906 {
907         return inMacroMode() ? activeMacro()->name() : docstring();
908 }
909
910
911 void LCursor::handleNest(MathAtom const & a, int c)
912 {
913         //lyxerr << "LCursor::handleNest: " << c << endl;
914         MathAtom t = a;
915         asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
916         insert(t);
917         posLeft();
918         pushLeft(*nextInset());
919 }
920
921
922 int LCursor::targetX() const
923 {
924         if (x_target() != -1)
925                 return x_target();
926         int x = 0;
927         int y = 0;
928         getPos(x, y);
929         return x;
930 }
931
932
933 void LCursor::setTargetX()
934 {
935         int x;
936         int y;
937         getPos(x, y);
938         x_target_ = x;
939 }
940
941
942 bool LCursor::inMacroMode() const
943 {
944         if (pos() == 0)
945                 return false;
946         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
947         return p && !p->final();
948 }
949
950
951 InsetMathUnknown * LCursor::activeMacro()
952 {
953         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
954 }
955
956
957 void LCursor::pullArg()
958 {
959 #ifdef WITH_WARNINGS
960 #warning Look here
961 #endif
962         MathArray ar = cell();
963         if (popLeft() && inMathed()) {
964                 plainErase();
965                 cell().insert(pos(), ar);
966                 resetAnchor();
967         } else {
968                 //formula()->mutateToText();
969         }
970 }
971
972
973 void LCursor::touch()
974 {
975 #ifdef WITH_WARNINGS
976 #warning look here
977 #endif
978 #if 0
979         DocIterator::const_iterator it = begin();
980         DocIterator::const_iterator et = end();
981         for ( ; it != et; ++it)
982                 it->cell().touch();
983 #endif
984 }
985
986
987 void LCursor::normalize()
988 {
989         if (idx() > lastidx()) {
990                 lyxerr << "this should not really happen - 1: "
991                        << idx() << ' ' << nargs()
992                        << " in: " << &inset() << endl;
993                 idx() = lastidx();
994         }
995
996         if (pos() > lastpos()) {
997                 lyxerr << "this should not really happen - 2: "
998                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
999                        << " in atom: '";
1000                 odocstringstream os;
1001                 WriteStream wi(os, false, true);
1002                 inset().asInsetMath()->write(wi);
1003                 lyxerr << to_utf8(os.str()) << endl;
1004                 pos() = lastpos();
1005         }
1006 }
1007
1008
1009 bool LCursor::goUpDown(bool up)
1010 {
1011         // Be warned: The 'logic' implemented in this function is highly
1012         // fragile. A distance of one pixel or a '<' vs '<=' _really
1013         // matters. So fiddle around with it only if you think you know
1014         // what you are doing!
1015
1016         int xo = 0;
1017         int yo = 0;
1018         getPos(xo, yo);
1019
1020         // check if we had something else in mind, if not, this is the future
1021         // target
1022         if (x_target() == -1)
1023                 x_target() = xo;
1024         else
1025                 xo = x_target();
1026
1027         // try neigbouring script insets
1028         if (!selection()) {
1029                 // try left
1030                 if (pos() != 0) {
1031                         InsetMathScript const * p = prevAtom()->asScriptInset();
1032                         if (p && p->has(up)) {
1033                                 --pos();
1034                                 push(*const_cast<InsetMathScript*>(p));
1035                                 idx() = p->idxOfScript(up);
1036                                 pos() = lastpos();
1037                                 return true;
1038                         }
1039                 }
1040
1041                 // try right
1042                 if (pos() != lastpos()) {
1043                         InsetMathScript const * p = nextAtom()->asScriptInset();
1044                         if (p && p->has(up)) {
1045                                 push(*const_cast<InsetMathScript*>(p));
1046                                 idx() = p->idxOfScript(up);
1047                                 pos() = 0;
1048                                 return true;
1049                         }
1050                 }
1051         }
1052
1053 // FIXME: Switch this on for more robust movement
1054 #if 0
1055
1056         return bruteFind3(*this, xo, yo, up);
1057
1058 #else
1059         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1060         //if (up)
1061         //      yhigh = yo - 4;
1062         //else
1063         //      ylow = yo + 4;
1064         //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
1065         //      lyxerr << "updown: handled by brute find in the same cell" << endl;
1066         //      return true;
1067         //}
1068
1069         // try to find an inset that knows better then we
1070         while (true) {
1071                 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1072                 // ask inset first
1073                 if (inset().idxUpDown(*this, up)) {
1074                         //lyxerr << "idxUpDown triggered" << endl;
1075                         // try to find best position within this inset
1076                         if (!selection())
1077                                 setCursor(bruteFind2(*this, xo, yo));
1078                         return true;
1079                 }
1080
1081                 // no such inset found, just take something "above"
1082                 if (!popLeft()) {
1083                         //lyxerr << "updown: popleft failed (strange case)" << endl;
1084                         int ylow  = up ? 0 : yo + 1;
1085                         int yhigh = up ? yo - 1 : bv().workHeight();
1086                         return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1087                 }
1088
1089                 // any improvement so far?
1090                 //lyxerr << "updown: popLeft succeeded" << endl;
1091                 int xnew;
1092                 int ynew;
1093                 getPos(xnew, ynew);
1094                 if (up ? ynew < yo : ynew > yo)
1095                         return true;
1096         }
1097
1098         // we should not come here.
1099         BOOST_ASSERT(false);
1100 #endif
1101 }
1102
1103
1104 void LCursor::handleFont(string const & font)
1105 {
1106         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1107         docstring safe;
1108         if (selection()) {
1109                 macroModeClose();
1110                 safe = cap::grabAndEraseSelection(*this);
1111         }
1112
1113         if (lastpos() != 0) {
1114                 // something left in the cell
1115                 if (pos() == 0) {
1116                         // cursor in first position
1117                         popLeft();
1118                 } else if (pos() == lastpos()) {
1119                         // cursor in last position
1120                         popRight();
1121                 } else {
1122                         // cursor in between. split cell
1123                         MathArray::iterator bt = cell().begin();
1124                         MathAtom at = createInsetMath(from_utf8(font));
1125                         at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1126                         cell().erase(bt, bt + pos());
1127                         popLeft();
1128                         plainInsert(at);
1129                 }
1130         } else {
1131                 // nothing left in the cell
1132                 pullArg();
1133                 plainErase();
1134         }
1135         insert(safe);
1136 }
1137
1138
1139 void LCursor::message(docstring const & msg) const
1140 {
1141         theLyXFunc().setMessage(msg);
1142 }
1143
1144
1145 void LCursor::errorMessage(docstring const & msg) const
1146 {
1147         theLyXFunc().setErrorMessage(msg);
1148 }
1149
1150
1151 docstring LCursor::selectionAsString(bool label) const
1152 {
1153         if (!selection())
1154                 return docstring();
1155
1156         if (inTexted()) {
1157                 Buffer const & buffer = *bv().buffer();
1158                 ParagraphList const & pars = text()->paragraphs();
1159
1160                 // should be const ...
1161                 pit_type startpit = selBegin().pit();
1162                 pit_type endpit = selEnd().pit();
1163                 size_t const startpos = selBegin().pos();
1164                 size_t const endpos = selEnd().pos();
1165
1166                 if (startpit == endpit)
1167                         return pars[startpit].asString(buffer, startpos, endpos, label);
1168
1169                 // First paragraph in selection
1170                 docstring result = pars[startpit].
1171                         asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1172
1173                 // The paragraphs in between (if any)
1174                 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1175                         Paragraph const & par = pars[pit];
1176                         result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1177                 }
1178
1179                 // Last paragraph in selection
1180                 result += pars[endpit].asString(buffer, 0, endpos, label);
1181
1182                 return result;
1183         }
1184
1185         if (inMathed())
1186                 return cap::grabSelection(*this);
1187
1188         return docstring();
1189 }
1190
1191
1192 string LCursor::currentState()
1193 {
1194         if (inMathed()) {
1195                 odocstringstream os;
1196                 info(os);
1197                 return to_utf8(os.str());
1198         }
1199
1200         if (inTexted())
1201                 return text()->currentState(*this);
1202
1203         return string();
1204 }
1205
1206
1207 docstring LCursor::getPossibleLabel()
1208 {
1209         return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1210 }
1211
1212
1213 Encoding const * LCursor::getEncoding() const
1214 {
1215         if (empty())
1216                 return 0;
1217         if (!bv().buffer())
1218                 return 0;
1219         int s = 0;
1220         // go up until first non-0 text is hit
1221         // (innermost text is 0 in mathed)
1222         for (s = depth() - 1; s >= 0; --s)
1223                 if (operator[](s).text())
1224                         break;
1225         CursorSlice const & sl = operator[](s);
1226         LyXText const & text = *sl.text();
1227         LyXFont font = text.getPar(sl.pit()).getFont(
1228                 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1229         return font.language()->encoding();
1230 }
1231
1232
1233 void LCursor::undispatched()
1234 {
1235         disp_.dispatched(false);
1236 }
1237
1238
1239 void LCursor::dispatched()
1240 {
1241         disp_.dispatched(true);
1242 }
1243
1244
1245 void LCursor::updateFlags(Update::flags f)
1246 {
1247         disp_.update(f);
1248 }
1249
1250
1251 void LCursor::noUpdate()
1252 {
1253         disp_.update(Update::None);
1254 }
1255
1256
1257 LyXFont LCursor::getFont() const
1258 {
1259         // HACK. far from being perfect...
1260         int s = 0;
1261         // go up until first non-0 text is hit
1262         // (innermost text is 0 in mathed)
1263         for (s = depth() - 1; s >= 0; --s)
1264                 if (operator[](s).text())
1265                         break;
1266         CursorSlice const & sl = operator[](s);
1267         LyXText const & text = *sl.text();
1268         LyXFont font = text.getPar(sl.pit()).getFont(
1269                 bv().buffer()->params(),
1270                 sl.pos(),
1271                 outerFont(sl.pit(), text.paragraphs()));
1272
1273         return font;
1274 }
1275
1276
1277 void LCursor::fixIfBroken()
1278 {
1279         // find out last good level
1280         LCursor copy = *this;
1281         size_t newdepth = depth();
1282         while (!copy.empty()) {
1283                 if (copy.idx() > copy.lastidx()) {
1284                         lyxerr << "wrong idx " << copy.idx()
1285                                << ", max is " << copy.lastidx()
1286                                << " at level " << copy.depth()
1287                                << ". Trying to correct this."  << endl;
1288                         newdepth = copy.depth() - 1;
1289                 }
1290                 else if (copy.pit() > copy.lastpit()) {
1291                         lyxerr << "wrong pit " << copy.pit()
1292                                << ", max is " << copy.lastpit()
1293                                << " at level " << copy.depth()
1294                                << ". Trying to correct this."  << endl;
1295                         newdepth = copy.depth() - 1;
1296                 }
1297                 else if (copy.pos() > copy.lastpos()) {
1298                         lyxerr << "wrong pos " << copy.pos()
1299                                << ", max is " << copy.lastpos()
1300                                << " at level " << copy.depth()
1301                                << ". Trying to correct this."  << endl;
1302                         newdepth = copy.depth() - 1;
1303                 }
1304                 copy.pop();
1305         }
1306         // shrink cursor to a size where everything is valid, possibly
1307         // leaving insets
1308         while (depth() > newdepth) {
1309                 pop();
1310                 lyxerr << "correcting cursor to level " << depth() << endl;
1311         }
1312 }
1313
1314
1315 } // namespace lyx