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