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