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