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