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