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