]> git.lyx.org Git - features.git/blob - src/mathed/InsetMathNest.cpp
* fix a serious data loss problem: undo did not save the whole
[features.git] / src / mathed / InsetMathNest.cpp
1 /**
2  * \file InsetMathNest.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetMathNest.h"
14
15 #include "InsetMathArray.h"
16 #include "InsetMathBig.h"
17 #include "InsetMathBox.h"
18 #include "InsetMathBrace.h"
19 #include "InsetMathColor.h"
20 #include "InsetMathComment.h"
21 #include "InsetMathDelim.h"
22 #include "InsetMathHull.h"
23 #include "InsetMathRef.h"
24 #include "InsetMathScript.h"
25 #include "InsetMathSpace.h"
26 #include "InsetMathSymbol.h"
27 #include "InsetMathUnknown.h"
28 #include "MathData.h"
29 #include "MathFactory.h"
30 #include "MathMacro.h"
31 #include "MathMacroArgument.h"
32 #include "MathParser.h"
33 #include "MathStream.h"
34 #include "MathSupport.h"
35
36 #include "Bidi.h"
37 #include "Buffer.h"
38 #include "BufferView.h"
39 #include "CoordCache.h"
40 #include "Cursor.h"
41 #include "CutAndPaste.h"
42 #include "DispatchResult.h"
43 #include "FuncRequest.h"
44 #include "FuncStatus.h"
45 #include "LyXFunc.h"
46 #include "LyXRC.h"
47 #include "OutputParams.h"
48 #include "Text.h"
49
50 #include "frontends/Clipboard.h"
51 #include "frontends/Painter.h"
52 #include "frontends/Selection.h"
53
54 #include "support/debug.h"
55 #include "support/gettext.h"
56 #include "support/lstrings.h"
57 #include "support/textutils.h"
58 #include "support/docstream.h"
59
60 #include <algorithm>
61 #include <sstream>
62
63 using namespace std;
64 using namespace lyx::support;
65
66 namespace lyx {
67
68 using cap::copySelection;
69 using cap::grabAndEraseSelection;
70 using cap::cutSelection;
71 using cap::replaceSelection;
72 using cap::selClearOrDel;
73
74
75 InsetMathNest::InsetMathNest(idx_type nargs)
76         : cells_(nargs), lock_(false), mouse_hover_(false)
77 {}
78
79
80 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
81         : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_),
82           mouse_hover_(false)
83 {}
84
85
86 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
87 {
88         cells_ = inset.cells_;
89         lock_ = inset.lock_;
90         mouse_hover_ = false;
91         InsetMath::operator=(inset);
92         return *this;
93 }
94
95
96 InsetMath::idx_type InsetMathNest::nargs() const
97 {
98         return cells_.size();
99 }
100
101
102 void InsetMathNest::cursorPos(BufferView const & bv,
103                 CursorSlice const & sl, bool /*boundary*/,
104                 int & x, int & y) const
105 {
106 // FIXME: This is a hack. Ideally, the coord cache should not store
107 // absolute positions, but relative ones. This would mean to call
108 // setXY() not in MathData::draw(), but in the parent insets' draw()
109 // with the correctly adjusted x,y values. But this means that we'd have
110 // to touch all (math)inset's draw() methods. Right now, we'll store
111 // absolute value, and make them here relative, only to make them
112 // absolute again when actually drawing the cursor. What a mess.
113         BOOST_ASSERT(&sl.inset() == this);
114         MathData const & ar = sl.cell();
115         CoordCache const & coord_cache = bv.coordCache();
116         if (!coord_cache.getArrays().has(&ar)) {
117                 // this can (semi-)legally happen if we just created this cell
118                 // and it never has been drawn before. So don't ASSERT.
119                 //lyxerr << "no cached data for array " << &ar << endl;
120                 x = 0;
121                 y = 0;
122                 return;
123         }
124         Point const pt = coord_cache.getArrays().xy(&ar);
125         if (!coord_cache.getInsets().has(this)) {
126                 // same as above
127                 //lyxerr << "no cached data for inset " << this << endl;
128                 x = 0;
129                 y = 0;
130                 return;
131         }
132         Point const pt2 = coord_cache.getInsets().xy(this);
133         //lyxerr << "retrieving position cache for MathData "
134         //      << pt.x_ << ' ' << pt.y_ << endl;
135         x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
136         y = pt.y_ - pt2.y_;
137 //      lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
138 //              << " asc: " << ascent() << "  des: " << descent()
139 //              << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
140         // move cursor visually into empty cells ("blue rectangles");
141         if (ar.empty())
142                 x += 2;
143 }
144
145
146 void InsetMathNest::metrics(MetricsInfo const & mi) const
147 {
148         MetricsInfo m = mi;
149         for (idx_type i = 0, n = nargs(); i != n; ++i) {
150                 Dimension dim;
151                 cell(i).metrics(m, dim);
152         }
153 }
154
155
156 bool InsetMathNest::idxNext(Cursor & cur) const
157 {
158         BOOST_ASSERT(&cur.inset() == this);
159         if (cur.idx() == cur.lastidx())
160                 return false;
161         ++cur.idx();
162         cur.pos() = 0;
163         return true;
164 }
165
166
167 bool InsetMathNest::idxForward(Cursor & cur) const
168 {
169         return idxNext(cur);
170 }
171
172
173 bool InsetMathNest::idxPrev(Cursor & cur) const
174 {
175         BOOST_ASSERT(&cur.inset() == this);
176         if (cur.idx() == 0)
177                 return false;
178         --cur.idx();
179         cur.pos() = cur.lastpos();
180         return true;
181 }
182
183
184 bool InsetMathNest::idxBackward(Cursor & cur) const
185 {
186         return idxPrev(cur);
187 }
188
189
190 bool InsetMathNest::idxFirst(Cursor & cur) const
191 {
192         BOOST_ASSERT(&cur.inset() == this);
193         if (nargs() == 0)
194                 return false;
195         cur.idx() = 0;
196         cur.pos() = 0;
197         return true;
198 }
199
200
201 bool InsetMathNest::idxLast(Cursor & cur) const
202 {
203         BOOST_ASSERT(&cur.inset() == this);
204         if (nargs() == 0)
205                 return false;
206         cur.idx() = cur.lastidx();
207         cur.pos() = cur.lastpos();
208         return true;
209 }
210
211
212 void InsetMathNest::dump() const
213 {
214         odocstringstream oss;
215         WriteStream os(oss);
216         os << "---------------------------------------------\n";
217         write(os);
218         os << "\n";
219         for (idx_type i = 0, n = nargs(); i != n; ++i)
220                 os << cell(i) << "\n";
221         os << "---------------------------------------------\n";
222         lyxerr << to_utf8(oss.str());
223 }
224
225
226 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
227 {
228 #if 0
229         if (lock_)
230                 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
231                                         Color_mathlockbg);
232 #endif
233         setPosCache(pi, x, y);
234 }
235
236
237 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
238 {
239         BufferView & bv = *pi.base.bv;
240         // this should use the x/y values given, not the cached values
241         Cursor & cur = bv.cursor();
242         if (!cur.selection())
243                 return;
244         if (&cur.inset() != this)
245                 return;
246
247         // FIXME: hack to get position cache warm
248         bool const original_drawing_state = pi.pain.isDrawingEnabled();
249         pi.pain.setDrawingEnabled(false);
250         draw(pi, x, y);
251         pi.pain.setDrawingEnabled(original_drawing_state);
252
253         CursorSlice s1 = cur.selBegin();
254         CursorSlice s2 = cur.selEnd();
255
256         //lyxerr << "InsetMathNest::drawing selection: "
257         //      << " s1: " << s1 << " s2: " << s2 << endl;
258         if (s1.idx() == s2.idx()) {
259                 MathData const & c = cell(s1.idx());
260                 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
261                 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
262                 int y1 = g.pos.y_ - g.dim.ascent();
263                 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
264                 int y2 = g.pos.y_ + g.dim.descent();
265                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
266         //lyxerr << "InsetMathNest::drawing selection 3: "
267         //      << " x1: " << x1 << " x2: " << x2
268         //      << " y1: " << y1 << " y2: " << y2 << endl;
269         } else {
270                 for (idx_type i = 0; i < nargs(); ++i) {
271                         if (idxBetween(i, s1.idx(), s2.idx())) {
272                                 MathData const & c = cell(i);
273                                 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
274                                 int x1 = g.pos.x_;
275                                 int y1 = g.pos.y_ - g.dim.ascent();
276                                 int x2 = g.pos.x_ + g.dim.width();
277                                 int y2 = g.pos.y_ + g.dim.descent();
278                                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
279                         }
280                 }
281         }
282 }
283
284
285 void InsetMathNest::validate(LaTeXFeatures & features) const
286 {
287         for (idx_type i = 0; i < nargs(); ++i)
288                 cell(i).validate(features);
289 }
290
291
292 void InsetMathNest::replace(ReplaceData & rep)
293 {
294         for (idx_type i = 0; i < nargs(); ++i)
295                 cell(i).replace(rep);
296 }
297
298
299 bool InsetMathNest::contains(MathData const & ar) const
300 {
301         for (idx_type i = 0; i < nargs(); ++i)
302                 if (cell(i).contains(ar))
303                         return true;
304         return false;
305 }
306
307
308 bool InsetMathNest::lock() const
309 {
310         return lock_;
311 }
312
313
314 void InsetMathNest::lock(bool l)
315 {
316         lock_ = l;
317 }
318
319
320 bool InsetMathNest::isActive() const
321 {
322         return nargs() > 0;
323 }
324
325
326 MathData InsetMathNest::glue() const
327 {
328         MathData ar;
329         for (size_t i = 0; i < nargs(); ++i)
330                 ar.append(cell(i));
331         return ar;
332 }
333
334
335 void InsetMathNest::write(WriteStream & os) const
336 {
337         os << '\\' << name().c_str();
338         for (size_t i = 0; i < nargs(); ++i)
339                 os << '{' << cell(i) << '}';
340         if (nargs() == 0)
341                 os.pendingSpace(true);
342         if (lock_ && !os.latex()) {
343                 os << "\\lyxlock";
344                 os.pendingSpace(true);
345         }
346 }
347
348
349 void InsetMathNest::normalize(NormalStream & os) const
350 {
351         os << '[' << name().c_str();
352         for (size_t i = 0; i < nargs(); ++i)
353                 os << ' ' << cell(i);
354         os << ']';
355 }
356
357
358 int InsetMathNest::latex(odocstream & os, OutputParams const & runparams) const
359 {
360         WriteStream wi(os, runparams.moving_arg, true);
361         write(wi);
362         return wi.line();
363 }
364
365
366 bool InsetMathNest::setMouseHover(bool mouse_hover)
367 {
368         mouse_hover_ = mouse_hover;
369         return true;
370 }
371
372
373 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
374 {
375         // FIXME: look here
376 #if 0
377         MathData & ar = cur.cell();
378         // remove base-only "scripts"
379         for (pos_type i = 0; i + 1 < ar.size(); ++i) {
380                 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
381                 if (p && p->nargs() == 1) {
382                         MathData ar = p->nuc();
383                         erase(i);
384                         insert(i, ar);
385                         cur.adjust(i, ar.size() - 1);
386                 }
387         }
388
389         // glue adjacent font insets of the same kind
390         for (pos_type i = 0; i + 1 < size(); ++i) {
391                 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
392                 InsetMathFont const * q = operator[](i + 1)->asFontInset();
393                 if (p && q && p->name() == q->name()) {
394                         p->cell(0).append(q->cell(0));
395                         erase(i + 1);
396                         cur.adjust(i, -1);
397                 }
398         }
399 #endif
400         return false;
401 }
402
403
404 void InsetMathNest::handleFont
405         (Cursor & cur, docstring const & arg, char const * const font)
406 {
407         handleFont(cur, arg, from_ascii(font));
408 }
409
410
411 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg, docstring const & font)
412 {
413         // this whole function is a hack and won't work for incremental font
414         // changes...
415
416         if (cur.inset().asInsetMath()->name() == font) {
417                 cur.recordUndoInset();
418                 cur.handleFont(to_utf8(font));
419         } else {
420                 CursorSlice i1 = cur.selBegin();
421                 CursorSlice i2 = cur.selEnd();
422                 if (!i1.inset().asInsetMath())
423                         return;
424                 if (i1.idx() == i2.idx()) {
425                         // the easy case where only one cell is selected
426                         cur.recordUndo();
427                         cur.handleNest(createInsetMath(font));
428                         cur.insert(arg);
429                         return;
430                 }
431                 
432                 // multiple selected cells in a simple non-grid inset
433                 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
434                         cur.recordUndoInset();
435                         for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
436                                 // select cell
437                                 cur.idx() = i;
438                                 cur.pos() = 0;
439                                 cur.resetAnchor();
440                                 cur.pos() = cur.lastpos();
441                                 cur.setSelection();
442                                 
443                                 // change font of cell
444                                 cur.handleNest(createInsetMath(font));
445                                 cur.insert(arg);
446                                 
447                                 // cur is in the font inset now. If the loop continues,
448                                 // we need to get outside again for the next cell
449                                 if (i + 1 <= i2.idx())
450                                         cur.pop_back();
451                         }
452                         return;
453                 }
454
455                 // the complicated case with multiple selected cells in a grid
456                 cur.recordUndoInset();
457                 Inset::row_type r1, r2;
458                 Inset::col_type c1, c2;
459                 cap::region(i1, i2, r1, r2, c1, c2);
460                 for (Inset::row_type row = r1; row <= r2; ++row) {
461                         for (Inset::col_type col = c1; col <= c2; ++col) {
462                                 // select cell
463                                 cur.idx() = i1.asInsetMath()->index(row, col);
464                                 cur.pos() = 0;
465                                 cur.resetAnchor();
466                                 cur.pos() = cur.lastpos();
467                                 cur.setSelection();
468
469                                 // change font of cell
470                                 cur.handleNest(createInsetMath(font));
471                                 cur.insert(arg);
472
473                                 // cur is in the font inset now. If the loop continues,
474                                 // we need to get outside again for the next cell
475                                 if (col + 1 <= c2 || row + 1 <= r2)
476                                         cur.pop_back();
477                         }
478                 }
479         }
480 }
481
482
483 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
484 {
485         cur.recordUndo();
486         Font font;
487         bool b;
488         font.fromString(to_utf8(arg), b);
489         if (font.fontInfo().color() != Color_inherit) {
490                 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
491                 cur.handleNest(at, 0);
492         }
493 }
494
495
496 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
497 {
498         //lyxerr << "InsetMathNest: request: " << cmd << endl;
499         //CursorSlice sl = cur.current();
500
501         switch (cmd.action) {
502
503         case LFUN_PASTE: {
504                 cur.recordUndoSelection();
505                 cur.message(_("Paste"));
506                 replaceSelection(cur);
507                 docstring topaste;
508                 if (cmd.argument().empty() && !theClipboard().isInternal())
509                         topaste = theClipboard().getAsText();
510                 else {
511                         size_t n = 0;
512                         idocstringstream is(cmd.argument());
513                         is >> n;
514                         topaste = cap::selection(n);
515                 }
516                 cur.niceInsert(topaste);
517                 cur.clearSelection(); // bug 393
518                 cur.finishUndo();
519                 break;
520         }
521
522         case LFUN_CUT:
523                 cur.recordUndo();
524                 cutSelection(cur, true, true);
525                 cur.message(_("Cut"));
526                 // Prevent stale position >= size crash
527                 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
528                 cur.normalize();
529                 break;
530
531         case LFUN_COPY:
532                 copySelection(cur);
533                 cur.message(_("Copy"));
534                 break;
535
536         case LFUN_MOUSE_PRESS:
537                 lfunMousePress(cur, cmd);
538                 break;
539
540         case LFUN_MOUSE_MOTION:
541                 lfunMouseMotion(cur, cmd);
542                 break;
543
544         case LFUN_MOUSE_RELEASE:
545                 lfunMouseRelease(cur, cmd);
546                 break;
547
548         case LFUN_FINISHED_LEFT: // in math, left is backwards
549         case LFUN_FINISHED_BACKWARD:
550                 cur.bv().cursor() = cur;
551                 break;
552
553         case LFUN_FINISHED_RIGHT: // in math, right is forward
554         case LFUN_FINISHED_FORWARD:
555                 ++cur.pos();
556                 cur.bv().cursor() = cur;
557                 break;
558
559         case LFUN_CHAR_RIGHT:
560         case LFUN_CHAR_LEFT:
561         case LFUN_CHAR_BACKWARD:
562         case LFUN_CHAR_FORWARD:
563                 cur.updateFlags(Update::Decoration | Update::FitCursor);
564         case LFUN_CHAR_RIGHT_SELECT:
565         case LFUN_CHAR_LEFT_SELECT:
566         case LFUN_CHAR_BACKWARD_SELECT:
567         case LFUN_CHAR_FORWARD_SELECT: {
568                 // are we in a selection?
569                 bool select = (cmd.action == LFUN_CHAR_RIGHT_SELECT 
570                                            || cmd.action == LFUN_CHAR_LEFT_SELECT
571                                            || cmd.action == LFUN_CHAR_BACKWARD_SELECT
572                                            || cmd.action == LFUN_CHAR_FORWARD_SELECT);
573                 // are we moving forward or backwards? 
574                 // If the command was RIGHT or LEFT, then whether we're moving forward
575                 // or backwards depends on the cursor movement mode (logical or visual):
576                 //  * in visual mode, since math is always LTR, right -> forward, 
577                 //    left -> backwards
578                 //  * in logical mode, the mapping is determined by the
579                 //    reverseDirectionNeeded() function
580                 
581                 bool forward;
582                 kb_action finish_lfun;
583
584                 if (cmd.action == LFUN_CHAR_FORWARD 
585                                 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
586                         forward = true;
587                         finish_lfun = LFUN_FINISHED_FORWARD;
588                 }
589                 else if (cmd.action == LFUN_CHAR_BACKWARD
590                                 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
591                         forward = false;
592                         finish_lfun = LFUN_FINISHED_BACKWARD;
593                 }
594                 else {
595                         bool right = (cmd.action == LFUN_CHAR_RIGHT_SELECT
596                                                   || cmd.action == LFUN_CHAR_RIGHT);
597                         if (lyxrc.visual_cursor || !reverseDirectionNeeded(cur))
598                                 forward = right;
599                         else 
600                                 forward = !right;
601
602                         if (right)
603                                 finish_lfun = LFUN_FINISHED_RIGHT;
604                         else
605                                 finish_lfun = LFUN_FINISHED_LEFT;
606                 }
607                 // Now that we know exactly what we want to do, let's do it!
608                 cur.selHandle(select);
609                 cur.autocorrect() = false;
610                 cur.clearTargetX();
611                 cur.macroModeClose();
612                 // try moving forward or backwards as necessary...
613                 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
614                         // ... and if movement failed, then finish forward or backwards
615                         // as necessary
616                         cmd = FuncRequest(finish_lfun);
617                         cur.undispatched();
618                 }
619                 break;
620         }
621
622         case LFUN_DOWN:
623         case LFUN_UP:
624                 cur.updateFlags(Update::Decoration | Update::FitCursor);
625         case LFUN_DOWN_SELECT:
626         case LFUN_UP_SELECT: {
627                 // close active macro
628                 if (cur.inMacroMode()) {
629                         cur.macroModeClose();
630                         break;
631                 }
632                 
633                 // stop/start the selection
634                 bool select = cmd.action == LFUN_DOWN_SELECT ||
635                         cmd.action == LFUN_UP_SELECT;
636                 cur.selHandle(select);
637                 
638                 // go up/down
639                 bool up = cmd.action == LFUN_UP || cmd.action == LFUN_UP_SELECT;
640                 bool successful = cur.upDownInMath(up);
641                 if (successful)
642                         break;
643                 
644                 if (cur.fixIfBroken())
645                         // FIXME: Something bad happened. We pass the corrected Cursor
646                         // instead of letting things go worse.
647                         break;
648
649                 // We did not manage to move the cursor.
650                 cur.undispatched();
651                 break;
652         }
653
654         case LFUN_MOUSE_DOUBLE:
655         case LFUN_MOUSE_TRIPLE:
656         case LFUN_WORD_SELECT:
657                 cur.pos() = 0;
658                 cur.idx() = 0;
659                 cur.resetAnchor();
660                 cur.selection() = true;
661                 cur.pos() = cur.lastpos();
662                 cur.idx() = cur.lastidx();
663                 break;
664
665         case LFUN_PARAGRAPH_UP:
666         case LFUN_PARAGRAPH_DOWN:
667                 cur.updateFlags(Update::Decoration | Update::FitCursor);
668         case LFUN_PARAGRAPH_UP_SELECT:
669         case LFUN_PARAGRAPH_DOWN_SELECT:
670                 break;
671
672         case LFUN_LINE_BEGIN:
673         case LFUN_WORD_BACKWARD:
674         case LFUN_WORD_LEFT:
675                 cur.updateFlags(Update::Decoration | Update::FitCursor);
676         case LFUN_LINE_BEGIN_SELECT:
677         case LFUN_WORD_BACKWARD_SELECT:
678         case LFUN_WORD_LEFT_SELECT:
679                 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
680                                 cmd.action == LFUN_WORD_LEFT_SELECT || 
681                                 cmd.action == LFUN_LINE_BEGIN_SELECT);
682                 cur.macroModeClose();
683                 if (cur.pos() != 0) {
684                         cur.pos() = 0;
685                 } else if (cur.col() != 0) {
686                         cur.idx() -= cur.col();
687                         cur.pos() = 0;
688                 } else if (cur.idx() != 0) {
689                         cur.idx() = 0;
690                         cur.pos() = 0;
691                 } else {
692                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
693                         cur.undispatched();
694                 }
695                 break;
696
697         case LFUN_WORD_FORWARD:
698         case LFUN_WORD_RIGHT:
699         case LFUN_LINE_END:
700                 cur.updateFlags(Update::Decoration | Update::FitCursor);
701         case LFUN_WORD_FORWARD_SELECT:
702         case LFUN_WORD_RIGHT_SELECT:
703         case LFUN_LINE_END_SELECT:
704                 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
705                                 cmd.action == LFUN_WORD_RIGHT_SELECT ||
706                                 cmd.action == LFUN_LINE_END_SELECT);
707                 cur.macroModeClose();
708                 cur.clearTargetX();
709                 if (cur.pos() != cur.lastpos()) {
710                         cur.pos() = cur.lastpos();
711                 } else if (ncols() && (cur.col() != cur.lastcol())) {
712                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
713                         cur.pos() = cur.lastpos();
714                 } else if (cur.idx() != cur.lastidx()) {
715                         cur.idx() = cur.lastidx();
716                         cur.pos() = cur.lastpos();
717                 } else {
718                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
719                         cur.undispatched();
720                 }
721                 break;
722
723         case LFUN_CELL_FORWARD:
724                 cur.updateFlags(Update::Decoration | Update::FitCursor);
725                 cur.inset().idxNext(cur);
726                 break;
727
728         case LFUN_CELL_BACKWARD:
729                 cur.updateFlags(Update::Decoration | Update::FitCursor);
730                 cur.inset().idxPrev(cur);
731                 break;
732
733         case LFUN_WORD_DELETE_BACKWARD:
734         case LFUN_CHAR_DELETE_BACKWARD:
735                 if (cur.pos() == 0)
736                         // May affect external cell:
737                         cur.recordUndoInset();
738                 else
739                         cur.recordUndoSelection();
740                 // if the inset can not be removed from within, delete it
741                 if (!cur.backspace()) {
742                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
743                         cur.innerText()->dispatch(cur, cmd);
744                 }
745                 break;
746
747         case LFUN_WORD_DELETE_FORWARD:
748         case LFUN_CHAR_DELETE_FORWARD:
749                 if (cur.pos() == cur.lastpos())
750                         // May affect external cell:
751                         cur.recordUndoInset();
752                 else
753                         cur.recordUndoSelection();
754                 // if the inset can not be removed from within, delete it
755                 if (!cur.erase()) {
756                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
757                         cur.innerText()->dispatch(cur, cmd);
758                 }
759                 break;
760
761         case LFUN_ESCAPE:
762                 if (cur.selection())
763                         cur.clearSelection();
764                 else  {
765                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
766                         cur.undispatched();
767                 }
768                 break;
769
770         // 'Locks' the math inset. A 'locked' math inset behaves as a unit
771         // that is traversed by a single <CursorLeft>/<CursorRight>.
772         case LFUN_INSET_TOGGLE:
773                 cur.recordUndo();
774                 lock(!lock());
775                 cur.popForward();
776                 break;
777
778         case LFUN_SELF_INSERT:
779                 if (cmd.argument().size() != 1) {
780                         cur.recordUndoSelection();
781                         docstring const arg = cmd.argument();
782                         if (!interpretString(cur, arg))
783                                 cur.insert(arg);
784                         break;
785                 }
786                 // Don't record undo steps if we are in macro mode and
787                 // cmd.argument is the next character of the macro name.
788                 // Otherwise we'll get an invalid cursor if we undo after
789                 // the macro was finished and the macro is a known command,
790                 // e.g. sqrt. Cursor::macroModeClose replaces in this case
791                 // the InsetMathUnknown with name "frac" by an empty
792                 // InsetMathFrac -> a pos value > 0 is invalid.
793                 // A side effect is that an undo before the macro is finished
794                 // undoes the complete macro, not only the last character.
795                 if (!cur.inMacroMode())
796                         cur.recordUndoSelection();
797
798                 // spacial handling of space. If we insert an inset
799                 // via macro mode, we want to put the cursor inside it
800                 // if relevant. Think typing "\frac<space>".
801                 if (cmd.argument()[0] == ' '
802                     && cur.inMacroMode() && cur.macroName() != "\\"
803                     && cur.macroModeClose()) {
804                         MathAtom const atom = cur.prevAtom();
805                         if (atom->asNestInset() && atom->isActive()) {
806                                 cur.posBackward();
807                                 cur.pushBackward(*cur.nextInset());
808                         }
809                 } else if (!interpretChar(cur, cmd.argument()[0])) {
810                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
811                         cur.undispatched();
812                 }
813                 break;
814
815         //case LFUN_SERVER_GET_XY:
816         //      sprintf(dispatch_buffer, "%d %d",);
817         //      break;
818
819         case LFUN_SERVER_SET_XY: {
820                 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
821                 int x = 0;
822                 int y = 0;
823                 istringstream is(to_utf8(cmd.argument()));
824                 is >> x >> y;
825                 cur.setScreenPos(x, y);
826                 break;
827         }
828
829         // Special casing for superscript in case of LyX handling
830         // dead-keys:
831         case LFUN_ACCENT_CIRCUMFLEX:
832                 if (cmd.argument().empty()) {
833                         // do superscript if LyX handles
834                         // deadkeys
835                         cur.recordUndoSelection();
836                         script(cur, true, grabAndEraseSelection(cur));
837                 }
838                 break;
839
840         case LFUN_ACCENT_UMLAUT:
841         case LFUN_ACCENT_ACUTE:
842         case LFUN_ACCENT_GRAVE:
843         case LFUN_ACCENT_BREVE:
844         case LFUN_ACCENT_DOT:
845         case LFUN_ACCENT_MACRON:
846         case LFUN_ACCENT_CARON:
847         case LFUN_ACCENT_TILDE:
848         case LFUN_ACCENT_CEDILLA:
849         case LFUN_ACCENT_CIRCLE:
850         case LFUN_ACCENT_UNDERDOT:
851         case LFUN_ACCENT_TIE:
852         case LFUN_ACCENT_OGONEK:
853         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
854                 break;
855
856         //  Math fonts
857         case LFUN_FONT_FREE_APPLY:
858         case LFUN_FONT_FREE_UPDATE:
859                 handleFont2(cur, cmd.argument());
860                 break;
861
862         case LFUN_FONT_BOLD:
863                 if (currentMode() == TEXT_MODE)
864                         handleFont(cur, cmd.argument(), "textbf");
865                 else
866                         handleFont(cur, cmd.argument(), "boldsymbol");
867                 break;
868         case LFUN_FONT_SANS:
869                 if (currentMode() == TEXT_MODE)
870                         handleFont(cur, cmd.argument(), "textsf");
871                 else
872                         handleFont(cur, cmd.argument(), "mathsf");
873                 break;
874         case LFUN_FONT_EMPH:
875                 if (currentMode() == TEXT_MODE)
876                         handleFont(cur, cmd.argument(), "emph");
877                 else
878                         handleFont(cur, cmd.argument(), "mathcal");
879                 break;
880         case LFUN_FONT_ROMAN:
881                 if (currentMode() == TEXT_MODE)
882                         handleFont(cur, cmd.argument(), "textrm");
883                 else
884                         handleFont(cur, cmd.argument(), "mathrm");
885                 break;
886         case LFUN_FONT_TYPEWRITER:
887                 if (currentMode() == TEXT_MODE)
888                         handleFont(cur, cmd.argument(), "texttt");
889                 else
890                         handleFont(cur, cmd.argument(), "mathtt");
891                 break;
892         case LFUN_FONT_FRAK:
893                 handleFont(cur, cmd.argument(), "mathfrak");
894                 break;
895         case LFUN_FONT_ITAL:
896                 if (currentMode() == TEXT_MODE)
897                         handleFont(cur, cmd.argument(), "textit");
898                 else
899                         handleFont(cur, cmd.argument(), "mathit");
900                 break;
901         case LFUN_FONT_NOUN:
902                 if (currentMode() == TEXT_MODE)
903                         // FIXME: should be "noun"
904                         handleFont(cur, cmd.argument(), "textsc");
905                 else
906                         handleFont(cur, cmd.argument(), "mathbb");
907                 break;
908         /*
909         case LFUN_FONT_FREE_APPLY:
910                 handleFont(cur, cmd.argument(), "textrm");
911                 break;
912         */
913         case LFUN_FONT_DEFAULT:
914                 handleFont(cur, cmd.argument(), "textnormal");
915                 break;
916
917         case LFUN_MATH_MODE: {
918 #if 1
919                 // ignore math-mode on when already in math mode
920                 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
921                         break;
922                 cur.macroModeClose();
923                 docstring const save_selection = grabAndEraseSelection(cur);
924                 selClearOrDel(cur);
925                 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
926                 cur.plainInsert(MathAtom(new InsetMathBox(from_ascii("mbox"))));
927                 cur.posBackward();
928                 cur.pushBackward(*cur.nextInset());
929                 cur.niceInsert(save_selection);
930 #else
931                 if (currentMode() == Inset::TEXT_MODE) {
932                         cur.niceInsert(MathAtom(new InsetMathHull("simple")));
933                         cur.message(_("create new math text environment ($...$)"));
934                 } else {
935                         handleFont(cur, cmd.argument(), "textrm");
936                         cur.message(_("entered math text mode (textrm)"));
937                 }
938 #endif
939                 break;
940         }
941
942         case LFUN_MATH_SIZE:
943 #if 0
944                 cur.recordUndoSelection();
945                 cur.setSize(arg);
946 #endif
947                 break;
948
949         case LFUN_MATH_MATRIX: {
950                 cur.recordUndo();
951                 unsigned int m = 1;
952                 unsigned int n = 1;
953                 docstring v_align;
954                 docstring h_align;
955                 idocstringstream is(cmd.argument());
956                 is >> m >> n >> v_align >> h_align;
957                 if (m < 1)
958                         m = 1;
959                 if (n < 1)
960                         n = 1;
961                 v_align += 'c';
962                 cur.niceInsert(
963                         MathAtom(new InsetMathArray(from_ascii("array"), m, n, (char)v_align[0], h_align)));
964                 break;
965         }
966
967         case LFUN_MATH_DELIM: {
968                 docstring ls;
969                 docstring rs = split(cmd.argument(), ls, ' ');
970                 // Reasonable default values
971                 if (ls.empty())
972                         ls = '(';
973                 if (rs.empty())
974                         rs = ')';
975                 cur.recordUndo();
976                 cur.handleNest(MathAtom(new InsetMathDelim(ls, rs)));
977                 break;
978         }
979
980         case LFUN_MATH_BIGDELIM: {
981                 docstring const lname  = from_utf8(cmd.getArg(0));
982                 docstring const ldelim = from_utf8(cmd.getArg(1));
983                 docstring const rname  = from_utf8(cmd.getArg(2));
984                 docstring const rdelim = from_utf8(cmd.getArg(3));
985                 latexkeys const * l = in_word_set(lname);
986                 bool const have_l = l && l->inset == "big" &&
987                                     InsetMathBig::isBigInsetDelim(ldelim);
988                 l = in_word_set(rname);
989                 bool const have_r = l && l->inset == "big" &&
990                                     InsetMathBig::isBigInsetDelim(rdelim);
991                 // We mimic LFUN_MATH_DELIM in case we have an empty left
992                 // or right delimiter.
993                 if (have_l || have_r) {
994                         cur.recordUndo();
995                         docstring const selection = grabAndEraseSelection(cur);
996                         selClearOrDel(cur);
997                         if (have_l)
998                                 cur.insert(MathAtom(new InsetMathBig(lname,
999                                                                 ldelim)));
1000                         cur.niceInsert(selection);
1001                         if (have_r)
1002                                 cur.insert(MathAtom(new InsetMathBig(rname,
1003                                                                 rdelim)));
1004                 }
1005                 // Don't call cur.undispatched() if we did nothing, this would
1006                 // lead to infinite recursion via Text::dispatch().
1007                 break;
1008         }
1009
1010         case LFUN_SPACE_INSERT:
1011         case LFUN_MATH_SPACE:
1012                 cur.recordUndoSelection();
1013                 cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
1014                 break;
1015
1016         case LFUN_ERT_INSERT:
1017                 // interpret this as if a backslash was typed
1018                 cur.recordUndo();
1019                 interpretChar(cur, '\\');
1020                 break;
1021
1022         case LFUN_MATH_SUBSCRIPT:
1023                 // interpret this as if a _ was typed
1024                 cur.recordUndoSelection();
1025                 interpretChar(cur, '_');
1026                 break;
1027
1028         case LFUN_MATH_SUPERSCRIPT:
1029                 // interpret this as if a ^ was typed
1030                 cur.recordUndoSelection();
1031                 interpretChar(cur, '^');
1032                 break;
1033                 
1034         case LFUN_MATH_MACRO_FOLD:
1035         case LFUN_MATH_MACRO_UNFOLD: {
1036                 Cursor it = cur;
1037                 bool fold = cmd.action == LFUN_MATH_MACRO_FOLD;
1038                 bool found = findMacroToFoldUnfold(it, fold);
1039                 if (found) {
1040                         MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1041                         cur.recordUndoInset();
1042                         if (fold)
1043                                 macro->fold(cur);
1044                         else
1045                                 macro->unfold(cur);
1046                 }
1047                 break;
1048         }
1049
1050         case LFUN_QUOTE_INSERT:
1051                 // interpret this as if a straight " was typed
1052                 cur.recordUndoSelection();
1053                 interpretChar(cur, '\"');
1054                 break;
1055
1056 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1057 // handling such that "self-insert" works on "arbitrary stuff" too, and
1058 // math-insert only handles special math things like "matrix".
1059         case LFUN_MATH_INSERT: {
1060                 cur.recordUndoSelection();
1061                 if (cmd.argument() == "^" || cmd.argument() == "_") {
1062                         interpretChar(cur, cmd.argument()[0]);
1063                 } else
1064                         cur.niceInsert(cmd.argument());
1065                 break;
1066                 }
1067
1068         case LFUN_DIALOG_SHOW_NEW_INSET: {
1069                 docstring const & name = cmd.argument();
1070                 string data;
1071                 if (name == "ref") {
1072                         InsetMathRef tmp(name);
1073                         data = tmp.createDialogStr(to_utf8(name));
1074                 }
1075                 cur.bv().showDialog(to_utf8(name), data);
1076                 break;
1077         }
1078
1079         case LFUN_INSET_INSERT: {
1080                 MathData ar;
1081                 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1082                         cur.recordUndoSelection();
1083                         cur.insert(ar);
1084                 } else
1085                         cur.undispatched();
1086                 break;
1087         }
1088         case LFUN_INSET_DISSOLVE:
1089                 if (!asHullInset()) {
1090                         cur.recordUndoInset();
1091                         cur.pullArg();
1092                 }
1093                 break;
1094
1095         default:
1096                 InsetMath::doDispatch(cur, cmd);
1097                 break;
1098         }
1099 }
1100
1101
1102 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1103         // look for macro to open/close, but stay in mathed
1104         for (; !it.empty(); it.pop_back()) {
1105                         
1106                 // go backward through the current cell
1107                 Inset * inset = it.nextInset();
1108                 while (inset && inset->asInsetMath()) {
1109                         MathMacro * macro = inset->asInsetMath()->asMacro();
1110                         if (macro) {
1111                                 // found the an macro to open/close?
1112                                 if (macro->folded() != fold)
1113                                         return true;
1114                                 
1115                                 // Wrong folding state.
1116                                 // If this was the first we see in this slice, look further left,
1117                                 // otherwise go up.
1118                                 if (inset != it.nextInset())
1119                                         break;
1120                         }
1121                         
1122                         // go up if this was the left most position
1123                         if (it.pos() == 0)
1124                                 break;
1125                         
1126                         // go left
1127                         it.pos()--;
1128                         inset = it.nextInset();
1129                 }
1130         }
1131         
1132         return false;
1133 }
1134
1135
1136 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1137                 FuncStatus & flag) const
1138 {
1139         // the font related toggles
1140         //string tc = "mathnormal";
1141         bool ret = true;
1142         string const arg = to_utf8(cmd.argument());
1143         switch (cmd.action) {
1144         case LFUN_TABULAR_FEATURE:
1145                 flag.enabled(false);
1146                 break;
1147 #if 0
1148         case LFUN_TABULAR_FEATURE:
1149                 // FIXME: check temporarily disabled
1150                 // valign code
1151                 char align = mathcursor::valign();
1152                 if (align == '\0') {
1153                         enable = false;
1154                         break;
1155                 }
1156                 if (cmd.argument().empty()) {
1157                         flag.clear();
1158                         break;
1159                 }
1160                 if (!contains("tcb", cmd.argument()[0])) {
1161                         enable = false;
1162                         break;
1163                 }
1164                 flag.setOnOff(cmd.argument()[0] == align);
1165                 break;
1166 #endif
1167         /// We have to handle them since 1.4 blocks all unhandled actions
1168         case LFUN_FONT_ITAL:
1169         case LFUN_FONT_BOLD:
1170         case LFUN_FONT_SANS:
1171         case LFUN_FONT_EMPH:
1172         case LFUN_FONT_TYPEWRITER:
1173         case LFUN_FONT_NOUN:
1174         case LFUN_FONT_ROMAN:
1175         case LFUN_FONT_DEFAULT:
1176                 flag.enabled(true);
1177                 break;
1178         case LFUN_MATH_MUTATE:
1179                 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1180                 flag.setOnOff(false);
1181                 break;
1182
1183         // we just need to be in math mode to enable that
1184         case LFUN_MATH_SIZE:
1185         case LFUN_MATH_SPACE:
1186         case LFUN_MATH_LIMITS:
1187         case LFUN_MATH_EXTERN:
1188                 flag.enabled(true);
1189                 break;
1190
1191         case LFUN_FONT_FRAK:
1192                 flag.enabled(currentMode() != TEXT_MODE);
1193                 break;
1194
1195         case LFUN_MATH_INSERT: {
1196                 bool const textarg =
1197                         arg == "\\textbf"   || arg == "\\textsf" ||
1198                         arg == "\\textrm"   || arg == "\\textmd" ||
1199                         arg == "\\textit"   || arg == "\\textsc" ||
1200                         arg == "\\textsl"   || arg == "\\textup" ||
1201                         arg == "\\texttt"   || arg == "\\textbb" ||
1202                         arg == "\\textnormal";
1203                 flag.enabled(currentMode() != TEXT_MODE || textarg);
1204                 break;
1205         }
1206
1207         case LFUN_MATH_MATRIX:
1208                 flag.enabled(currentMode() == MATH_MODE);
1209                 break;
1210
1211         case LFUN_INSET_INSERT: {
1212                 // Don't test createMathInset_fromDialogStr(), since
1213                 // getStatus is not called with a valid reference and the
1214                 // dialog would not be applyable.
1215                 string const name = cmd.getArg(0);
1216                 flag.enabled(name == "ref");
1217                 break;
1218         }
1219
1220         case LFUN_MATH_DELIM:
1221         case LFUN_MATH_BIGDELIM:
1222                 // Don't do this with multi-cell selections
1223                 flag.enabled(cur.selBegin().idx() == cur.selEnd().idx());
1224                 break;
1225                 
1226         case LFUN_MATH_MACRO_FOLD:
1227         case LFUN_MATH_MACRO_UNFOLD: {
1228                 Cursor it = cur;
1229                 bool found = findMacroToFoldUnfold(it, cmd.action == LFUN_MATH_MACRO_FOLD);
1230                 flag.enabled(found);
1231                 break;
1232         }
1233                 
1234         case LFUN_SPECIALCHAR_INSERT:
1235                 // FIXME: These would probably make sense in math-text mode
1236                 flag.enabled(false);
1237                 break;
1238
1239         case LFUN_INSET_DISSOLVE:
1240                 flag.enabled(!asHullInset());
1241                 break;
1242
1243         default:
1244                 ret = false;
1245                 break;
1246         }
1247         return ret;
1248 }
1249
1250
1251 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1252 {
1253         cur.push(*this);
1254         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT || 
1255                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1256         cur.idx() = enter_front ? 0 : cur.lastidx();
1257         cur.pos() = enter_front ? 0 : cur.lastpos();
1258         cur.resetAnchor();
1259         //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1260 }
1261
1262
1263 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1264 {
1265         int idx_min = 0;
1266         int dist_min = 1000000;
1267         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1268                 int const d = cell(i).dist(cur.bv(), x, y);
1269                 if (d < dist_min) {
1270                         dist_min = d;
1271                         idx_min = i;
1272                 }
1273         }
1274         MathData & ar = cell(idx_min);
1275         cur.push(*this);
1276         cur.idx() = idx_min;
1277         cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1278
1279         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1280         if (dist_min == 0) {
1281                 // hit inside cell
1282                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1283                         if (ar[i]->covers(cur.bv(), x, y))
1284                                 return ar[i].nucleus()->editXY(cur, x, y);
1285         }
1286         return this;
1287 }
1288
1289
1290 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1291 {
1292         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1293         BufferView & bv = cur.bv();
1294         bool do_selection = cmd.button() == mouse_button::button1
1295                 && cmd.argument() == "region-select";
1296         bv.mouseSetCursor(cur, do_selection);
1297         if (cmd.button() == mouse_button::button1) {
1298                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1299                 // Update the cursor update flags as needed:
1300                 //
1301                 // Update::Decoration: tells to update the decoration
1302                 //                     (visual box corners that define
1303                 //                     the inset)/
1304                 // Update::FitCursor: adjust the screen to the cursor
1305                 //                    position if needed
1306                 // cur.result().update(): don't overwrite previously set flags.
1307                 cur.updateFlags(Update::Decoration | Update::FitCursor 
1308                                 | cur.result().update());
1309         } else if (cmd.button() == mouse_button::button2) {
1310                 if (cap::selection()) {
1311                         // See comment in Text::dispatch why we do this
1312                         cap::copySelectionToStack();
1313                         cmd = FuncRequest(LFUN_PASTE, "0");
1314                         doDispatch(bv.cursor(), cmd);
1315                 } else {
1316                         MathData ar;
1317                         asArray(theSelection().get(), ar);
1318                         bv.cursor().insert(ar);
1319                 }
1320         }
1321 }
1322
1323
1324 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1325 {
1326         // only select with button 1
1327         if (cmd.button() == mouse_button::button1) {
1328                 Cursor & bvcur = cur.bv().cursor();
1329                 if (bvcur.anchor_.hasPart(cur)) {
1330                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1331                         bvcur.setCursor(cur);
1332                         bvcur.selection() = true;
1333                         //lyxerr << "MOTION " << bvcur << endl;
1334                 } else
1335                         cur.undispatched();
1336         }
1337 }
1338
1339
1340 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1341 {
1342         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1343
1344         if (cmd.button() == mouse_button::button1) {
1345                 if (!cur.selection())
1346                         cur.noUpdate();
1347                 else {
1348                         Cursor & bvcur = cur.bv().cursor();
1349                         bvcur.selection() = true;
1350                 }
1351                 return;
1352         }
1353
1354         cur.undispatched();
1355 }
1356
1357
1358 bool InsetMathNest::interpretChar(Cursor & cur, char_type c)
1359 {
1360         //lyxerr << "interpret 2: '" << c << "'" << endl;
1361         docstring save_selection;
1362         if (c == '^' || c == '_')
1363                 save_selection = grabAndEraseSelection(cur);
1364
1365         cur.clearTargetX();
1366
1367         // handle macroMode
1368         if (cur.inMacroMode()) {
1369                 docstring name = cur.macroName();
1370
1371                 /// are we currently typing '#1' or '#2' or...?
1372                 if (name == "\\#") {
1373                         cur.backspace();
1374                         int n = c - '0';
1375                         if (n >= 1 && n <= 9)
1376                                 cur.insert(new MathMacroArgument(n));
1377                         return true;
1378                 }
1379
1380                 // do not finish macro for known * commands
1381                 MathWordList const & mwl = mathedWordList();
1382                 bool star_macro = c == '*'
1383                         && (mwl.find(name.substr(1) + "*") != mwl.end()
1384                             || cur.buffer().getMacro(name.substr(1) + "*", cur, true));
1385                 if (isAlphaASCII(c) || star_macro) {
1386                         cur.activeMacro()->setName(name + docstring(1, c));
1387                         return true;
1388                 }
1389
1390                 // handle 'special char' macros
1391                 if (name == "\\") {
1392                         // remove the '\\'
1393                         if (c == '\\') {
1394                                 cur.backspace();
1395                                 if (currentMode() == InsetMath::TEXT_MODE)
1396                                         cur.niceInsert(createInsetMath("textbackslash"));
1397                                 else
1398                                         cur.niceInsert(createInsetMath("backslash"));
1399                         } else if (c == '{') {
1400                                 cur.backspace();
1401                                 cur.niceInsert(MathAtom(new InsetMathBrace));
1402                         } else if (c == '%') {
1403                                 cur.backspace();
1404                                 cur.niceInsert(MathAtom(new InsetMathComment));
1405                         } else if (c == '#') {
1406                                 BOOST_ASSERT(cur.activeMacro());
1407                                 cur.activeMacro()->setName(name + docstring(1, c));
1408                         } else {
1409                                 cur.backspace();
1410                                 cur.niceInsert(createInsetMath(docstring(1, c)));
1411                         }
1412                         return true;
1413                 }
1414
1415                 // One character big delimiters. The others are handled in
1416                 // interpretString().
1417                 latexkeys const * l = in_word_set(name.substr(1));
1418                 if (name[0] == '\\' && l && l->inset == "big") {
1419                         docstring delim;
1420                         switch (c) {
1421                         case '{':
1422                                 delim = from_ascii("\\{");
1423                                 break;
1424                         case '}':
1425                                 delim = from_ascii("\\}");
1426                                 break;
1427                         default:
1428                                 delim = docstring(1, c);
1429                                 break;
1430                         }
1431                         if (InsetMathBig::isBigInsetDelim(delim)) {
1432                                 // name + delim ared a valid InsetMathBig.
1433                                 // We can't use cur.macroModeClose() because
1434                                 // it does not handle delim.
1435                                 InsetMathUnknown * p = cur.activeMacro();
1436                                 p->finalize();
1437                                 --cur.pos();
1438                                 cur.cell().erase(cur.pos());
1439                                 cur.plainInsert(MathAtom(
1440                                         new InsetMathBig(name.substr(1), delim)));
1441                                 return true;
1442                         }
1443                 }
1444
1445                 // leave macro mode and try again if necessary
1446                 cur.macroModeClose();
1447                 if (c == '{')
1448                         cur.niceInsert(MathAtom(new InsetMathBrace));
1449                 else if (c != ' ')
1450                         interpretChar(cur, c);
1451                 return true;
1452         }
1453
1454         // This is annoying as one has to press <space> far too often.
1455         // Disable it.
1456
1457 #if 0
1458                 // leave autocorrect mode if necessary
1459                 if (autocorrect() && c == ' ') {
1460                         autocorrect() = false;
1461                         return true;
1462                 }
1463 #endif
1464
1465         // just clear selection on pressing the space bar
1466         if (cur.selection() && c == ' ') {
1467                 cur.selection() = false;
1468                 return true;
1469         }
1470
1471         if (c == '\\') {
1472                 //lyxerr << "starting with macro" << endl;
1473                 bool reduced = cap::reduceSelectionToOneCell(cur);
1474                 if (reduced || !cur.selection()) {
1475                         docstring const safe = cap::grabAndEraseSelection(cur);
1476                         cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1477                 }
1478                 return true;
1479         }
1480
1481         selClearOrDel(cur);
1482
1483         if (c == '\n') {
1484                 if (currentMode() == InsetMath::TEXT_MODE)
1485                         cur.insert(c);
1486                 return true;
1487         }
1488
1489         if (c == ' ') {
1490                 if (currentMode() == InsetMath::TEXT_MODE) {
1491                         // insert spaces in text mode,
1492                         // but suppress direct insertion of two spaces in a row
1493                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1494                         // it is better than nothing...
1495                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1496                                 cur.insert(c);
1497                                 // FIXME: we have to enable full redraw here because of the
1498                                 // visual box corners that define the inset. If we know for
1499                                 // sure that we stay within the same cell we can optimize for
1500                                 // that using:
1501                                 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1502                         }
1503                         return true;
1504                 }
1505                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1506                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1507                         // FIXME: we have to enable full redraw here because of the
1508                         // visual box corners that define the inset. If we know for
1509                         // sure that we stay within the same cell we can optimize for
1510                         // that using:
1511                         //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1512                         return true;
1513                 }
1514
1515                 if (cur.popForward()) {
1516                         // FIXME: we have to enable full redraw here because of the
1517                         // visual box corners that define the inset. If we know for
1518                         // sure that we stay within the same cell we can optimize for
1519                         // that using:
1520                         //cur.updateFlags(Update::FitCursor);
1521                         return true;
1522                 }
1523
1524                 // if we are at the very end, leave the formula
1525                 return cur.pos() != cur.lastpos();
1526         }
1527
1528         // These shouldn't work in text mode:
1529         if (currentMode() != InsetMath::TEXT_MODE) {
1530                 if (c == '_') {
1531                         script(cur, false, save_selection);
1532                         return true;
1533                 }
1534                 if (c == '^') {
1535                         script(cur, true, save_selection);
1536                         return true;
1537                 }
1538                 if (c == '~') {
1539                         cur.niceInsert(createInsetMath("sim"));
1540                         return true;
1541                 }
1542         }
1543
1544         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1545             c == '%' || c == '_' || c == '^') {
1546                 cur.niceInsert(createInsetMath(docstring(1, c)));
1547                 return true;
1548         }
1549
1550
1551         // try auto-correction
1552         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1553         //      return true;
1554
1555         // no special circumstances, so insert the character without any fuss
1556         cur.insert(c);
1557         cur.autocorrect() = true;
1558         return true;
1559 }
1560
1561
1562 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1563 {
1564         // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1565         // possible
1566         if (!cur.empty() && cur.pos() > 0 &&
1567             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1568                 if (InsetMathBig::isBigInsetDelim(str)) {
1569                         docstring prev = asString(cur.cell()[cur.pos() - 1]);
1570                         if (prev[0] == '\\') {
1571                                 prev = prev.substr(1);
1572                                 latexkeys const * l = in_word_set(prev);
1573                                 if (l && l->inset == "big") {
1574                                         cur.cell()[cur.pos() - 1] =
1575                                                 MathAtom(new InsetMathBig(prev, str));
1576                                         return true;
1577                                 }
1578                         }
1579                 }
1580         }
1581         return false;
1582 }
1583
1584
1585 bool InsetMathNest::script(Cursor & cur, bool up,
1586                 docstring const & save_selection)
1587 {
1588         // Hack to get \^ and \_ working
1589         //lyxerr << "handling script: up: " << up << endl;
1590         if (cur.inMacroMode() && cur.macroName() == "\\") {
1591                 if (up)
1592                         cur.niceInsert(createInsetMath("mathcircumflex"));
1593                 else
1594                         interpretChar(cur, '_');
1595                 return true;
1596         }
1597
1598         cur.macroModeClose();
1599         if (asScriptInset() && cur.idx() == 0) {
1600                 // we are in a nucleus of a script inset, move to _our_ script
1601                 InsetMathScript * inset = asScriptInset();
1602                 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1603                 inset->ensure(up);
1604                 cur.idx() = inset->idxOfScript(up);
1605                 cur.pos() = 0;
1606         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1607                 --cur.pos();
1608                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1609                 cur.push(*inset);
1610                 inset->ensure(up);
1611                 cur.idx() = inset->idxOfScript(up);
1612                 cur.pos() = cur.lastpos();
1613         } else {
1614                 // convert the thing to our left to a scriptinset or create a new
1615                 // one if in the very first position of the array
1616                 if (cur.pos() == 0) {
1617                         //lyxerr << "new scriptinset" << endl;
1618                         cur.insert(new InsetMathScript(up));
1619                 } else {
1620                         //lyxerr << "converting prev atom " << endl;
1621                         cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1622                 }
1623                 --cur.pos();
1624                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1625                 // See comment in MathParser.cpp for special handling of {}-bases
1626
1627                 cur.push(*inset);
1628                 cur.idx() = 1;
1629                 cur.pos() = 0;
1630         }
1631         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1632         cur.niceInsert(save_selection);
1633         cur.resetAnchor();
1634         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1635         return true;
1636 }
1637
1638
1639 bool InsetMathNest::completionSupported(Cursor const & cur) const
1640 {
1641         return cur.inMacroMode();
1642 }
1643
1644
1645 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1646 {
1647         return cur.inMacroMode();
1648 }
1649
1650
1651 bool InsetMathNest::automaticInlineCompletion() const
1652 {
1653         return lyxrc.completion_inline_math;
1654 }
1655
1656
1657 bool InsetMathNest::automaticPopupCompletion() const
1658 {
1659         return lyxrc.completion_popup_math;
1660 }
1661
1662
1663 Inset::CompletionList const *
1664 InsetMathNest::createCompletionList(Cursor const & cur) const
1665 {
1666         if (!cur.inMacroMode())
1667                 return 0;
1668         
1669         return new MathCompletionList(cur);
1670 }
1671
1672
1673 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
1674 {
1675         if (!cur.inMacroMode())
1676                 return docstring();
1677         
1678         return cur.activeMacro()->name();
1679 }
1680
1681
1682 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
1683                                      bool finished)
1684 {
1685         if (!cur.inMacroMode())
1686                 return false;
1687
1688         // append completion to active macro
1689         InsetMathUnknown * inset = cur.activeMacro();
1690         inset->setName(inset->name() + s);
1691
1692         // finish macro
1693         if (finished) {
1694 #if 0
1695                 // FIXME: this creates duplicates in the completion popup
1696                 // which looks ugly. Moreover the changes the list lengths
1697                 // which seems to
1698                 confuse the popup as well.
1699                 MathCompletionList::addToFavorites(inset->name());
1700 #endif
1701                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
1702         }
1703
1704         return true;
1705 }
1706
1707
1708 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y, 
1709                                         Dimension & dim) const
1710 {
1711         Inset const * inset = cur.activeMacro();
1712         if (!inset)
1713                 return;
1714
1715         // get inset dimensions
1716         dim = cur.bv().coordCache().insets().dim(inset);
1717         // FIXME: these 3 are no accurate, but should depend on the font.
1718         // Now the popup jumps down if you enter a char with descent > 0.
1719         dim.des += 3;
1720         dim.asc += 3;
1721
1722         // and position
1723         Point xy
1724         = cur.bv().coordCache().insets().xy(inset);
1725         x = xy.x_;
1726         y = xy.y_;
1727 }
1728
1729
1730 bool InsetMathNest::cursorMathForward(Cursor & cur)
1731 {
1732         if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
1733                 cur.pushBackward(*cur.nextAtom().nucleus());
1734                 cur.inset().idxFirst(cur);
1735                 return true;
1736         } 
1737         if (cur.posForward() || idxForward(cur) || cur.selection())
1738                 return true;
1739         // try to pop forwards --- but don't pop out of math! leave that to
1740         // the FINISH lfuns
1741         int s = cur.depth() - 2;
1742         if (s >= 0 && cur[s].inset().asInsetMath())
1743                 return cur.popForward();
1744         return false;
1745 }
1746
1747
1748 bool InsetMathNest::cursorMathBackward(Cursor & cur)
1749 {
1750         if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
1751                 cur.posBackward();
1752                 cur.push(*cur.nextAtom().nucleus());
1753                 cur.inset().idxLast(cur);
1754                 return true;
1755         } 
1756         if (cur.posBackward() || idxBackward(cur) || cur.selection())
1757                 return true;
1758         // try to pop backwards --- but don't pop out of math! leave that to 
1759         // the FINISH lfuns
1760         int s = cur.depth() - 2;
1761         if (s >= 0 && cur[s].inset().asInsetMath())
1762                 return cur.popBackward();
1763         return false;
1764 }
1765
1766
1767 ////////////////////////////////////////////////////////////////////
1768
1769 MathCompletionList::MathCompletionList(Cursor const & cur)
1770 {
1771         // fill it with macros from the buffer
1772         MacroNameSet macros;
1773         cur.buffer().listMacroNames(macros);
1774         MacroNameSet::const_iterator it;
1775         for (it = macros.begin(); it != macros.end(); ++it) {
1776                 if (cur.buffer().getMacro(*it, cur, false))
1777                         locals.push_back("\\" + *it);
1778         }
1779         sort(locals.begin(), locals.end());
1780
1781         if (globals.size() > 0)
1782                 return;
1783
1784         // fill in global macros
1785         macros.clear();
1786         MacroTable::globalMacros().getMacroNames(macros);
1787         lyxerr << "Globals completion macros: ";
1788         for (it = macros.begin(); it != macros.end(); ++it) {
1789                 lyxerr << "\\" + *it << " ";
1790                 globals.push_back("\\" + *it);
1791         }
1792         lyxerr << std::endl;
1793
1794         // fill in global commands
1795         globals.push_back(from_ascii("\\boxed"));
1796         globals.push_back(from_ascii("\\fbox"));
1797         globals.push_back(from_ascii("\\framebox"));
1798         globals.push_back(from_ascii("\\makebox"));
1799         globals.push_back(from_ascii("\\kern"));
1800         globals.push_back(from_ascii("\\xrightarrow"));
1801         globals.push_back(from_ascii("\\xleftarrow"));
1802         globals.push_back(from_ascii("\\split"));
1803         globals.push_back(from_ascii("\\gathered"));
1804         globals.push_back(from_ascii("\\aligned"));
1805         globals.push_back(from_ascii("\\alignedat"));
1806         globals.push_back(from_ascii("\\cases"));
1807         globals.push_back(from_ascii("\\substack"));
1808         globals.push_back(from_ascii("\\subarray"));
1809         globals.push_back(from_ascii("\\array"));
1810         globals.push_back(from_ascii("\\sqrt"));
1811         globals.push_back(from_ascii("\\root"));
1812         globals.push_back(from_ascii("\\tabular"));
1813         globals.push_back(from_ascii("\\stackrel"));
1814         globals.push_back(from_ascii("\\binom"));
1815         globals.push_back(from_ascii("\\choose"));
1816         globals.push_back(from_ascii("\\choose"));
1817         globals.push_back(from_ascii("\\frac"));
1818         globals.push_back(from_ascii("\\over"));
1819         globals.push_back(from_ascii("\\nicefrac"));
1820         globals.push_back(from_ascii("\\unitfrac"));
1821         globals.push_back(from_ascii("\\unitfracthree"));
1822         globals.push_back(from_ascii("\\unitone"));
1823         globals.push_back(from_ascii("\\unittwo"));
1824         globals.push_back(from_ascii("\\infer"));
1825         globals.push_back(from_ascii("\\atop"));
1826         globals.push_back(from_ascii("\\lefteqn"));
1827         globals.push_back(from_ascii("\\boldsymbol"));
1828         globals.push_back(from_ascii("\\bm"));
1829         globals.push_back(from_ascii("\\color"));
1830         globals.push_back(from_ascii("\\normalcolor"));
1831         globals.push_back(from_ascii("\\textcolor"));
1832         globals.push_back(from_ascii("\\dfrac"));
1833         globals.push_back(from_ascii("\\tfrac"));
1834         globals.push_back(from_ascii("\\dbinom"));
1835         globals.push_back(from_ascii("\\tbinom"));
1836         globals.push_back(from_ascii("\\hphantom"));
1837         globals.push_back(from_ascii("\\phantom"));
1838         globals.push_back(from_ascii("\\vphantom"));
1839         MathWordList const & words = mathedWordList();
1840         MathWordList::const_iterator it2;
1841         lyxerr << "Globals completion commands: ";
1842         for (it2 = words.begin(); it2 != words.end(); ++it2) {
1843                 globals.push_back("\\" + (*it2).first);
1844                 lyxerr << "\\" + (*it2).first << " ";
1845         }
1846         lyxerr << std::endl;
1847         sort(globals.begin(), globals.end());
1848 }
1849
1850
1851 MathCompletionList::~MathCompletionList()
1852 {
1853 }
1854
1855
1856 size_type MathCompletionList::size() const
1857 {
1858         return locals.size() + globals.size();
1859 }
1860
1861
1862 docstring const & MathCompletionList::data(size_t idx) const
1863 {
1864         size_t lsize = locals.size();
1865         if (idx >= lsize)
1866                 return globals[idx - lsize];
1867         else
1868                 return locals[idx];
1869 }
1870
1871
1872 std::string MathCompletionList::icon(size_t idx) const 
1873 {
1874         // get the latex command
1875         docstring cmd;
1876         size_t lsize = locals.size();
1877         if (idx >= lsize)
1878                 cmd = globals[idx - lsize];
1879         else
1880                 cmd = locals[idx];
1881         
1882         // get the icon resource name by stripping the backslash
1883         return "images/math/" + to_utf8(cmd.substr(1)) + ".png";
1884 }
1885
1886 std::vector<docstring> MathCompletionList::globals;
1887
1888 } // namespace lyx