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