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