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