]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathNest.cpp
Do not remove character at start of paragraph when cutting
[lyx.git] / src / mathed / InsetMathNest.cpp
1 /**
2  * \file InsetMathNest.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetMathNest.h"
14
15 #include "InsetMathArray.h"
16 #include "InsetMathAMSArray.h"
17 #include "InsetMathBig.h"
18 #include "InsetMathBox.h"
19 #include "InsetMathBrace.h"
20 #include "InsetMathChar.h"
21 #include "InsetMathColor.h"
22 #include "InsetMathComment.h"
23 #include "InsetMathDelim.h"
24 #include "InsetMathEnsureMath.h"
25 #include "InsetMathHull.h"
26 #include "InsetMathRef.h"
27 #include "InsetMathScript.h"
28 #include "InsetMathSpace.h"
29 #include "InsetMathSymbol.h"
30 #include "InsetMathUnknown.h"
31 #include "MathAutoCorrect.h"
32 #include "MathCompletionList.h"
33 #include "MathData.h"
34 #include "MathFactory.h"
35 #include "InsetMathMacro.h"
36 #include "InsetMathMacroArgument.h"
37 #include "MathParser.h"
38 #include "MathStream.h"
39 #include "MathSupport.h"
40
41 #include "Buffer.h"
42 #include "BufferParams.h"
43 #include "BufferView.h"
44 #include "CoordCache.h"
45 #include "Cursor.h"
46 #include "CutAndPaste.h"
47 #include "DispatchResult.h"
48 #include "Encoding.h"
49 #include "FuncRequest.h"
50 #include "FuncStatus.h"
51 #include "LaTeXFeatures.h"
52 #include "LyX.h"
53 #include "LyXRC.h"
54 #include "MetricsInfo.h"
55 #include "OutputParams.h"
56 #include "TexRow.h"
57 #include "Text.h"
58
59 #include "frontends/Application.h"
60 #include "frontends/Clipboard.h"
61 #include "frontends/Painter.h"
62 #include "frontends/Selection.h"
63
64 #include "support/debug.h"
65 #include "support/docstream.h"
66 #include "support/gettext.h"
67 #include "support/lassert.h"
68 #include "support/lstrings.h"
69 #include "support/textutils.h"
70
71 #include <algorithm>
72 #include <sstream>
73
74 using namespace std;
75 using namespace lyx::support;
76
77 namespace lyx {
78
79 using cap::copySelection;
80 using cap::grabAndEraseSelection;
81 using cap::cutSelection;
82 using cap::replaceSelection;
83 using cap::selClearOrDel;
84
85
86 InsetMathNest::InsetMathNest(Buffer * buf, idx_type nargs)
87         : InsetMath(buf), cells_(nargs), lock_(false)
88 {
89         setBuffer(*buf);
90 }
91
92
93 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
94         : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_)
95 {}
96
97
98 InsetMathNest::~InsetMathNest()
99 {
100         map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
101         map<BufferView const *, bool>::iterator end = mouse_hover_.end();
102         for (; it != end; ++it)
103                 if (it->second)
104                         it->first->clearLastInset(this);
105 }
106
107
108 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
109 {
110         cells_ = inset.cells_;
111         lock_ = inset.lock_;
112         mouse_hover_.clear();
113         InsetMath::operator=(inset);
114         return *this;
115 }
116
117
118 void InsetMathNest::setBuffer(Buffer & buffer)
119 {
120         InsetMath::setBuffer(buffer);
121         for (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() = firstIdx();
239         cur.pos() = 0;
240         return true;
241 }
242
243
244 bool InsetMathNest::idxLast(Cursor & cur) const
245 {
246         LASSERT(&cur.inset() == this, return false);
247         if (nargs() == 0)
248                 return false;
249         cur.idx() = lastIdx();
250         cur.pos() = cur.lastpos();
251         return true;
252 }
253
254
255 void InsetMathNest::dump() const
256 {
257         odocstringstream oss;
258         otexrowstream ots(oss);
259         WriteStream os(ots);
260         os << "---------------------------------------------\n";
261         write(os);
262         os << "\n";
263         for (idx_type i = 0, n = nargs(); i != n; ++i)
264                 os << cell(i) << "\n";
265         os << "---------------------------------------------\n";
266         lyxerr << to_utf8(oss.str());
267 }
268
269
270 void InsetMathNest::draw(PainterInfo &, int, int) const
271 {
272 #if 0
273         if (lock_)
274                 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
275                                         Color_mathlockbg);
276 #endif
277 }
278
279
280 void InsetMathNest::validate(LaTeXFeatures & features) const
281 {
282         for (idx_type i = 0; i < nargs(); ++i)
283                 cell(i).validate(features);
284 }
285
286
287 void InsetMathNest::replace(ReplaceData & rep)
288 {
289         for (idx_type i = 0; i < nargs(); ++i)
290                 cell(i).replace(rep);
291 }
292
293
294 bool InsetMathNest::contains(MathData const & ar) const
295 {
296         for (idx_type i = 0; i < nargs(); ++i)
297                 if (cell(i).contains(ar))
298                         return true;
299         return false;
300 }
301
302
303 bool InsetMathNest::lock() const
304 {
305         return lock_;
306 }
307
308
309 void InsetMathNest::lock(bool l)
310 {
311         lock_ = l;
312 }
313
314
315 bool InsetMathNest::isActive() const
316 {
317         return nargs() > 0;
318 }
319
320
321 MathData InsetMathNest::glue() const
322 {
323         MathData ar;
324         for (size_t i = 0; i < nargs(); ++i)
325                 ar.append(cell(i));
326         return ar;
327 }
328
329
330 void InsetMathNest::write(WriteStream & os) const
331 {
332         MathEnsurer ensurer(os, currentMode() == MATH_MODE);
333         ModeSpecifier specifier(os, currentMode(), lockedMode());
334         docstring const latex_name = name();
335         os << '\\' << latex_name;
336         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);
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.bv().mouseSetCursor(cur);
739                 cur.pos() = cur.lastpos();
740                 cur.bv().mouseSetCursor(cur, true);
741                 break;
742
743         case LFUN_MOUSE_TRIPLE:
744                 cur.idx() = 0;
745                 cur.pos() = 0;
746                 cur.bv().mouseSetCursor(cur);
747                 cur.idx() = cur.lastidx();
748                 cur.pos() = cur.lastpos();
749                 cur.bv().mouseSetCursor(cur, true);
750                 break;
751
752         case LFUN_LINE_BEGIN:
753                 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
754                 // fall through
755         case LFUN_LINE_BEGIN_SELECT:
756                 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
757                                 act == LFUN_WORD_LEFT_SELECT ||
758                                 act == LFUN_LINE_BEGIN_SELECT);
759                 cur.macroModeClose();
760                 if (cur.pos() != 0) {
761                         cur.pos() = 0;
762                 } else if (cur.col() != 0) {
763                         cur.idx() -= cur.col();
764                         cur.pos() = 0;
765                 } else if (cur.idx() != 0) {
766                         cur.idx() = 0;
767                         cur.pos() = 0;
768                 } else {
769                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
770                         cur.undispatched();
771                 }
772                 break;
773
774         case LFUN_LINE_END:
775                 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
776                 // fall through
777         case LFUN_LINE_END_SELECT:
778                 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
779                                 act == LFUN_WORD_RIGHT_SELECT ||
780                                 act == LFUN_LINE_END_SELECT);
781                 cur.macroModeClose();
782                 cur.clearTargetX();
783                 if (cur.pos() != cur.lastpos()) {
784                         cur.pos() = cur.lastpos();
785                 } else if (ncols() && (cur.col() != cur.lastcol())) {
786                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
787                         cur.pos() = cur.lastpos();
788                 } else if (cur.idx() != cur.lastidx()) {
789                         cur.idx() = cur.lastidx();
790                         cur.pos() = cur.lastpos();
791                 } else {
792                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
793                         cur.undispatched();
794                 }
795                 break;
796
797         case LFUN_CELL_FORWARD:
798                 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
799                 cur.inset().idxNext(cur);
800                 break;
801
802         case LFUN_CELL_BACKWARD:
803                 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
804                 cur.inset().idxPrev(cur);
805                 break;
806
807         case LFUN_WORD_DELETE_BACKWARD:
808         case LFUN_CHAR_DELETE_BACKWARD:
809                 if (cur.pos() == 0)
810                         // May affect external cell:
811                         cur.recordUndoInset();
812                 else if (!cur.inMacroMode())
813                         cur.recordUndoSelection();
814                 // if the inset can not be removed from within, delete it
815                 if (!cur.backspace(cmd.getArg(0) == "force")) {
816                         FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
817                         cur.innerText()->dispatch(cur, newcmd);
818                 }
819                 break;
820
821         case LFUN_WORD_DELETE_FORWARD:
822         case LFUN_CHAR_DELETE_FORWARD:
823                 if (cur.pos() == cur.lastpos())
824                         // May affect external cell:
825                         cur.recordUndoInset();
826                 else
827                         cur.recordUndoSelection();
828                 // if the inset can not be removed from within, delete it
829                 if (!cur.erase(cmd.getArg(0) == "force")) {
830                         FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
831                         cur.innerText()->dispatch(cur, newcmd);
832                 }
833                 break;
834
835         case LFUN_ESCAPE:
836                 if (cur.selection())
837                         cur.clearSelection();
838                 else  {
839                         if (cur.inMacroMode())
840                                 cur.macroModeClose(true);
841                         else {
842                                 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
843                                 cur.undispatched();
844                         }
845                 }
846                 break;
847
848         // 'Locks' the math inset. A 'locked' math inset behaves as a unit
849         // that is traversed by a single <CursorLeft>/<CursorRight>.
850         case LFUN_INSET_TOGGLE:
851                 cur.recordUndo();
852                 lock(!lock());
853                 cur.popForward();
854                 break;
855
856         case LFUN_SELF_INSERT:
857                 // special case first for big delimiters
858                 if (cmd.argument().size() != 1 && interpretString(cur, cmd.argument()))
859                         break;
860
861                 for (char_type c : cmd.argument()) {
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                         // special 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 (c == ' '
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, c)) {
887                                 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
888                                 cur.undispatched();
889                                 // FIXME: can we avoid skipping the end of the string?
890                                 break;
891                         }
892                 }
893                 break;
894
895         //case LFUN_SERVER_GET_XY:
896         //      break;
897
898         case LFUN_SERVER_SET_XY: {
899                 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
900                 int x = 0;
901                 int y = 0;
902                 istringstream is(to_utf8(cmd.argument()));
903                 is >> x >> y;
904                 cur.setTargetX(x);
905                 break;
906         }
907
908         // Special casing for superscript in case of LyX handling
909         // dead-keys:
910         case LFUN_ACCENT_CIRCUMFLEX:
911                 if (cmd.argument().empty()) {
912                         // do superscript if LyX handles
913                         // deadkeys
914                         cur.recordUndoSelection();
915                         script(cur, true, grabAndEraseSelection(cur));
916                 }
917                 break;
918
919         case LFUN_ACCENT_UMLAUT:
920         case LFUN_ACCENT_ACUTE:
921         case LFUN_ACCENT_GRAVE:
922         case LFUN_ACCENT_BREVE:
923         case LFUN_ACCENT_DOT:
924         case LFUN_ACCENT_MACRON:
925         case LFUN_ACCENT_CARON:
926         case LFUN_ACCENT_TILDE:
927         case LFUN_ACCENT_CEDILLA:
928         case LFUN_ACCENT_CIRCLE:
929         case LFUN_ACCENT_UNDERDOT:
930         case LFUN_ACCENT_TIE:
931         case LFUN_ACCENT_OGONEK:
932         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
933                 break;
934
935         //  Math fonts
936         case LFUN_TEXTSTYLE_APPLY:
937         case LFUN_TEXTSTYLE_UPDATE:
938                 handleFont2(cur, cmd.argument());
939                 break;
940
941         case LFUN_FONT_BOLD:
942                 if (currentMode() != MATH_MODE)
943                         handleFont(cur, cmd.argument(), "textbf");
944                 else
945                         handleFont(cur, cmd.argument(), "mathbf");
946                 break;
947         case LFUN_FONT_BOLDSYMBOL:
948                 if (currentMode() != MATH_MODE)
949                         handleFont(cur, cmd.argument(), "textbf");
950                 else
951                         handleFont(cur, cmd.argument(), "boldsymbol");
952                 break;
953         case LFUN_FONT_SANS:
954                 if (currentMode() != MATH_MODE)
955                         handleFont(cur, cmd.argument(), "textsf");
956                 else
957                         handleFont(cur, cmd.argument(), "mathsf");
958                 break;
959         case LFUN_FONT_EMPH:
960                 if (currentMode() != MATH_MODE)
961                         handleFont(cur, cmd.argument(), "emph");
962                 else
963                         handleFont(cur, cmd.argument(), "mathcal");
964                 break;
965         case LFUN_FONT_ROMAN:
966                 if (currentMode() != MATH_MODE)
967                         handleFont(cur, cmd.argument(), "textrm");
968                 else
969                         handleFont(cur, cmd.argument(), "mathrm");
970                 break;
971         case LFUN_FONT_TYPEWRITER:
972                 if (currentMode() != MATH_MODE)
973                         handleFont(cur, cmd.argument(), "texttt");
974                 else
975                         handleFont(cur, cmd.argument(), "mathtt");
976                 break;
977         case LFUN_FONT_FRAK:
978                 handleFont(cur, cmd.argument(), "mathfrak");
979                 break;
980         case LFUN_FONT_ITAL:
981                 if (currentMode() != MATH_MODE)
982                         handleFont(cur, cmd.argument(), "textit");
983                 else
984                         handleFont(cur, cmd.argument(), "mathit");
985                 break;
986         case LFUN_FONT_NOUN:
987                 if (currentMode() != MATH_MODE)
988                         // FIXME: should be "noun"
989                         handleFont(cur, cmd.argument(), "textsc");
990                 else
991                         handleFont(cur, cmd.argument(), "mathbb");
992                 break;
993         case LFUN_FONT_DEFAULT:
994                 handleFont(cur, cmd.argument(), "textnormal");
995                 break;
996         case LFUN_FONT_UNDERLINE:
997                 cur.recordUndo();
998                 cur.handleNest(createInsetMath("underline", cur.buffer()));
999                 break;
1000
1001         case LFUN_MATH_MODE: {
1002 #if 1
1003                 // ignore math-mode on when already in math mode
1004                 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1005                         break;
1006                 cur.recordUndoSelection();
1007                 cur.macroModeClose();
1008                 docstring const save_selection = grabAndEraseSelection(cur);
1009                 selClearOrDel(cur);
1010                 if (currentMode() != Inset::MATH_MODE)
1011                         cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1012                 else
1013                         cur.plainInsert(createInsetMath("text", buffer_));
1014                 cur.posBackward();
1015                 cur.pushBackward(*cur.nextInset());
1016                 cur.niceInsert(save_selection);
1017                 cur.forceBufferUpdate();
1018 #else
1019                 if (currentMode() == Inset::TEXT_MODE) {
1020                         cur.recordUndoSelection();
1021                         cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1022                         cur.message(_("create new math text environment ($...$)"));
1023                 } else {
1024                         handleFont(cur, cmd.argument(), "textrm");
1025                         cur.message(_("entered math text mode (textrm)"));
1026                 }
1027 #endif
1028                 break;
1029         }
1030
1031         case LFUN_REGEXP_MODE: {
1032                 InsetMath * im = cur.inset().asInsetMath();
1033                 if (im) {
1034                         InsetMathHull * i = im->asHullInset();
1035                         if (i && i->getType() == hullRegexp) {
1036                                 cur.message(_("Already in regular expression mode"));
1037                                 break;
1038                         }
1039                 }
1040                 cur.macroModeClose();
1041                 docstring const save_selection = grabAndEraseSelection(cur);
1042                 selClearOrDel(cur);
1043                 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1044                 cur.posBackward();
1045                 cur.pushBackward(*cur.nextInset());
1046                 cur.niceInsert(save_selection);
1047                 cur.message(_("Regular expression editor mode"));
1048                 break;
1049         }
1050
1051         case LFUN_MATH_FONT_STYLE: {
1052                 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1053                 doDispatch(cur, fr);
1054                 break;
1055         }
1056
1057         case LFUN_MATH_SIZE: {
1058                 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1059                 doDispatch(cur, fr);
1060                 break;
1061         }
1062
1063         case LFUN_MATH_MATRIX: {
1064                 cur.recordUndo();
1065                 unsigned int m = 1;
1066                 unsigned int n = 1;
1067                 docstring v_align;
1068                 docstring h_align;
1069                 idocstringstream is(cmd.argument());
1070                 is >> m >> n >> v_align >> h_align;
1071                 if (m < 1)
1072                         m = 1;
1073                 if (n < 1)
1074                         n = 1;
1075                 v_align += 'c';
1076                 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1077                         from_ascii("array"), m, n, (char)v_align[0], h_align)));
1078                 break;
1079         }
1080
1081         case LFUN_MATH_AMS_MATRIX: {
1082                 cur.recordUndo();
1083                 unsigned int m = 1;
1084                 unsigned int n = 1;
1085                 docstring name = from_ascii("matrix");
1086                 idocstringstream is(cmd.argument());
1087                 is >> m >> n >> name;
1088                 if (m < 1)
1089                         m = 1;
1090                 if (n < 1)
1091                         n = 1;
1092                 // check if we have a valid decoration
1093                 if (name != "pmatrix" && name != "bmatrix"
1094                         && name != "Bmatrix" && name != "vmatrix"
1095                         && name != "Vmatrix" && name != "matrix")
1096                         name = from_ascii("matrix");
1097
1098                 cur.niceInsert(
1099                         MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1100                 break;
1101         }
1102
1103         case LFUN_MATH_DELIM: {
1104                 docstring ls;
1105                 docstring rs = split(cmd.argument(), ls, ' ');
1106                 // Reasonable default values
1107                 if (ls.empty())
1108                         ls = '(';
1109                 if (rs.empty())
1110                         rs = ')';
1111                 cur.recordUndo();
1112                 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1113                 break;
1114         }
1115
1116         case LFUN_MATH_BIGDELIM: {
1117                 docstring const lname  = from_utf8(cmd.getArg(0));
1118                 docstring const ldelim = from_utf8(cmd.getArg(1));
1119                 docstring const rname  = from_utf8(cmd.getArg(2));
1120                 docstring const rdelim = from_utf8(cmd.getArg(3));
1121                 latexkeys const * l = in_word_set(lname);
1122                 bool const have_l = l && l->inset == "big" &&
1123                                     InsetMathBig::isBigInsetDelim(ldelim);
1124                 l = in_word_set(rname);
1125                 bool const have_r = l && l->inset == "big" &&
1126                                     InsetMathBig::isBigInsetDelim(rdelim);
1127                 // We mimic LFUN_MATH_DELIM in case we have an empty left
1128                 // or right delimiter.
1129                 if (have_l || have_r) {
1130                         cur.recordUndo();
1131                         docstring const selection = grabAndEraseSelection(cur);
1132                         selClearOrDel(cur);
1133                         if (have_l)
1134                                 cur.insert(MathAtom(new InsetMathBig(lname,
1135                                                                 ldelim)));
1136                         // first insert the right delimiter and then go back
1137                         // and re-insert the selection (bug 7088)
1138                         if (have_r) {
1139                                 cur.insert(MathAtom(new InsetMathBig(rname,
1140                                                                 rdelim)));
1141                                 cur.posBackward();
1142                         }
1143                         cur.niceInsert(selection);
1144                 }
1145                 // Don't call cur.undispatched() if we did nothing, this would
1146                 // lead to infinite recursion via Text::dispatch().
1147                 break;
1148         }
1149
1150         case LFUN_SPACE_INSERT: {
1151                 cur.recordUndoSelection();
1152                 string const name = cmd.getArg(0);
1153                 if (name == "normal")
1154                         cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1155                 else if (name == "protected")
1156                         cur.insert(MathAtom(new InsetMathSpace("~", "")));
1157                 else if (name == "thin" || name == "med" || name == "thick")
1158                         cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1159                 else if (name == "hfill*")
1160                         cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1161                 else if (name == "quad" || name == "qquad" ||
1162                          name == "enspace" || name == "enskip" ||
1163                          name == "negthinspace" || name == "negmedspace" ||
1164                          name == "negthickspace" || name == "hfill")
1165                         cur.insert(MathAtom(new InsetMathSpace(name, "")));
1166                 else if (name == "hspace" || name == "hspace*") {
1167                         string const len = cmd.getArg(1);
1168                         if (len.empty() || !isValidLength(len)) {
1169                                 lyxerr << "LyX function 'space-insert " << name << "' "
1170                                           "needs a valid length argument." << endl;
1171                                 break;
1172                         }
1173                         cur.insert(MathAtom(new InsetMathSpace(name, len)));
1174                 } else
1175                         cur.insert(MathAtom(new InsetMathSpace));
1176                 break;
1177         }
1178
1179         case LFUN_MATH_SPACE:
1180                 cur.recordUndoSelection();
1181                 if (cmd.argument().empty())
1182                         cur.insert(MathAtom(new InsetMathSpace));
1183                 else {
1184                         string const name = cmd.getArg(0);
1185                         string const len = cmd.getArg(1);
1186                         cur.insert(MathAtom(new InsetMathSpace(name, len)));
1187                 }
1188                 break;
1189
1190         case LFUN_ERT_INSERT:
1191                 // interpret this as if a backslash was typed
1192                 cur.recordUndo();
1193                 interpretChar(cur, '\\');
1194                 break;
1195
1196         case LFUN_MATH_SUBSCRIPT:
1197                 // interpret this as if a _ was typed
1198                 cur.recordUndoSelection();
1199                 interpretChar(cur, '_');
1200                 break;
1201
1202         case LFUN_MATH_SUPERSCRIPT:
1203                 // interpret this as if a ^ was typed
1204                 cur.recordUndoSelection();
1205                 interpretChar(cur, '^');
1206                 break;
1207
1208         case LFUN_MATH_MACRO_FOLD:
1209         case LFUN_MATH_MACRO_UNFOLD: {
1210                 Cursor it = cur;
1211                 bool fold = act == LFUN_MATH_MACRO_FOLD;
1212                 bool found = findMacroToFoldUnfold(it, fold);
1213                 if (found) {
1214                         InsetMathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1215                         cur.recordUndoInset();
1216                         if (fold)
1217                                 macro->fold(cur);
1218                         else
1219                                 macro->unfold(cur);
1220                 }
1221                 break;
1222         }
1223
1224         case LFUN_QUOTE_INSERT:
1225                 // interpret this as if a straight " was typed
1226                 cur.recordUndoSelection();
1227                 interpretChar(cur, '\"');
1228                 break;
1229
1230 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1231 // handling such that "self-insert" works on "arbitrary stuff" too, and
1232 // math-insert only handles special math things like "matrix".
1233         case LFUN_MATH_INSERT: {
1234                 cur.recordUndoSelection();
1235                 if (cmd.argument() == "^" || cmd.argument() == "_")
1236                         interpretChar(cur, cmd.argument()[0]);
1237                 else {
1238                         MathData ar;
1239                         asArray(cmd.argument(), ar);
1240                         if (cur.selection() && ar.size() == 1
1241                             && ar[0]->asNestInset()
1242                             && ar[0]->asNestInset()->nargs() > 1)
1243                                 handleNest(cur, ar[0]);
1244                         else
1245                                 cur.niceInsert(cmd.argument());
1246                 }
1247                 break;
1248         }
1249
1250         case LFUN_DIALOG_SHOW_NEW_INSET: {
1251                 docstring const & name = cmd.argument();
1252                 string data;
1253                 if (name == "ref") {
1254                         InsetMathRef tmp(buffer_, name);
1255                         data = tmp.createDialogStr();
1256                         cur.bv().showDialog(to_utf8(name), data);
1257                 } else if (name == "mathspace") {
1258                         cur.bv().showDialog(to_utf8(name));
1259                 }
1260                 break;
1261         }
1262
1263         case LFUN_INSET_INSERT: {
1264                 MathData ar;
1265                 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1266                         cur.recordUndoSelection();
1267                         cur.insert(ar);
1268                         cur.forceBufferUpdate();
1269                 } else
1270                         cur.undispatched();
1271                 break;
1272         }
1273         case LFUN_INSET_DISSOLVE:
1274                 if (!asHullInset()) {
1275                         cur.recordUndoInset();
1276                         cur.pullArg();
1277                 }
1278                 break;
1279
1280         default:
1281                 InsetMath::doDispatch(cur, cmd);
1282                 break;
1283         }
1284 }
1285
1286
1287 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1288         // look for macro to open/close, but stay in mathed
1289         for (; !it.empty(); it.pop_back()) {
1290
1291                 // go backward through the current cell
1292                 Inset * inset = it.nextInset();
1293                 while (inset && inset->asInsetMath()) {
1294                         InsetMathMacro * macro = inset->asInsetMath()->asMacro();
1295                         if (macro) {
1296                                 // found the an macro to open/close?
1297                                 if (macro->folded() != fold)
1298                                         return true;
1299
1300                                 // Wrong folding state.
1301                                 // If this was the first we see in this slice, look further left,
1302                                 // otherwise go up.
1303                                 if (inset != it.nextInset())
1304                                         break;
1305                         }
1306
1307                         // go up if this was the left most position
1308                         if (it.pos() == 0)
1309                                 break;
1310
1311                         // go left
1312                         it.pos()--;
1313                         inset = it.nextInset();
1314                 }
1315         }
1316
1317         return false;
1318 }
1319
1320
1321 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1322                 FuncStatus & flag) const
1323 {
1324         // the font related toggles
1325         //string tc = "mathnormal";
1326         bool ret = true;
1327         string const arg = to_utf8(cmd.argument());
1328         switch (cmd.action()) {
1329         case LFUN_INSET_MODIFY:
1330                 flag.setEnabled(false);
1331                 break;
1332 #if 0
1333         case LFUN_INSET_MODIFY:
1334                 // FIXME: check temporarily disabled
1335                 // valign code
1336                 char align = mathcursor::valign();
1337                 if (align == '\0') {
1338                         enable = false;
1339                         break;
1340                 }
1341                 if (cmd.argument().empty()) {
1342                         flag.clear();
1343                         break;
1344                 }
1345                 if (!contains("tcb", cmd.argument()[0])) {
1346                         enable = false;
1347                         break;
1348                 }
1349                 flag.setOnOff(cmd.argument()[0] == align);
1350                 break;
1351 #endif
1352         /// We have to handle them since 1.4 blocks all unhandled actions
1353         case LFUN_FONT_ITAL:
1354         case LFUN_FONT_BOLD:
1355         case LFUN_FONT_BOLDSYMBOL:
1356         case LFUN_FONT_SANS:
1357         case LFUN_FONT_EMPH:
1358         case LFUN_FONT_TYPEWRITER:
1359         case LFUN_FONT_NOUN:
1360         case LFUN_FONT_ROMAN:
1361         case LFUN_FONT_DEFAULT:
1362                 flag.setEnabled(true);
1363                 break;
1364
1365         // we just need to be in math mode to enable that
1366         case LFUN_MATH_SIZE:
1367         case LFUN_MATH_SPACE:
1368         case LFUN_MATH_EXTERN:
1369                 flag.setEnabled(true);
1370                 break;
1371
1372         case LFUN_FONT_UNDERLINE:
1373         case LFUN_FONT_FRAK:
1374                 flag.setEnabled(currentMode() != TEXT_MODE);
1375                 break;
1376
1377         case LFUN_MATH_FONT_STYLE: {
1378                 bool const textarg =
1379                         arg == "textbf"   || arg == "textsf" ||
1380                         arg == "textrm"   || arg == "textmd" ||
1381                         arg == "textit"   || arg == "textsc" ||
1382                         arg == "textsl"   || arg == "textup" ||
1383                         arg == "texttt"   || arg == "textbb" ||
1384                         arg == "textnormal";
1385                 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1386                 break;
1387         }
1388
1389         case LFUN_MATH_MODE:
1390                 // forbid "math-mode on" in math mode to prevent irritating
1391                 // behaviour of menu entries (bug 6709)
1392                 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1393                 break;
1394
1395         case LFUN_MATH_INSERT:
1396                 flag.setEnabled(currentMode() != TEXT_MODE);
1397                 break;
1398
1399         case LFUN_MATH_AMS_MATRIX:
1400         case LFUN_MATH_MATRIX:
1401                 flag.setEnabled(currentMode() == MATH_MODE);
1402                 break;
1403
1404         case LFUN_INSET_INSERT: {
1405                 // Don't test createMathInset_fromDialogStr(), since
1406                 // getStatus is not called with a valid reference and the
1407                 // dialog would not be applyable.
1408                 string const name = cmd.getArg(0);
1409                 flag.setEnabled(name == "ref" || name == "mathspace");
1410                 break;
1411         }
1412
1413         case LFUN_DIALOG_SHOW_NEW_INSET: {
1414                 docstring const & name = cmd.argument();
1415                 if (name == "space")
1416                         flag.setEnabled(false);
1417                 break;
1418         }
1419
1420
1421         case LFUN_MATH_DELIM:
1422         case LFUN_MATH_BIGDELIM:
1423                 // Don't do this with multi-cell selections
1424                 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1425                 break;
1426
1427         case LFUN_MATH_MACRO_FOLD:
1428         case LFUN_MATH_MACRO_UNFOLD: {
1429                 Cursor it = cur;
1430                 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1431                 flag.setEnabled(found);
1432                 break;
1433         }
1434
1435         case LFUN_SPECIALCHAR_INSERT:
1436         case LFUN_SCRIPT_INSERT:
1437                 // FIXME: These would probably make sense in math-text mode
1438                 flag.setEnabled(false);
1439                 break;
1440
1441         case LFUN_CAPTION_INSERT:
1442                 flag.setEnabled(false);
1443                 break;
1444
1445         case LFUN_SPACE_INSERT: {
1446                 docstring const & name = cmd.argument();
1447                 if (name == "visible")
1448                         flag.setEnabled(false);
1449                 break;
1450         }
1451
1452         case LFUN_INSET_DISSOLVE:
1453                 flag.setEnabled(!asHullInset());
1454                 break;
1455
1456         case LFUN_PASTE: {
1457                 docstring const & name = cmd.argument();
1458                 if (name == "html" || name == "latex")
1459                         flag.setEnabled(false);
1460                 break;
1461         }
1462
1463         default:
1464                 ret = false;
1465                 break;
1466         }
1467         return ret;
1468 }
1469
1470
1471 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1472 {
1473         cur.push(*this);
1474         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1475                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1476         enter_front ? idxFirst(cur) : idxLast(cur);
1477         cur.resetAnchor();
1478         //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1479 }
1480
1481
1482 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1483 {
1484         int idx_min = -1;
1485         int dist_min = 1000000;
1486         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1487                 int const d = cell(i).dist(cur.bv(), x, y);
1488                 if (d < dist_min) {
1489                         dist_min = d;
1490                         idx_min = i;
1491                 }
1492         }
1493         if (idx_min == -1)
1494                 return this;
1495
1496         MathData & ar = cell(idx_min);
1497         cur.push(*this);
1498         cur.idx() = idx_min;
1499         cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1500
1501         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1502         if (dist_min == 0) {
1503                 // hit inside cell
1504                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1505                         if (ar[i]->covers(cur.bv(), x, y))
1506                                 return ar[i].nucleus()->editXY(cur, x, y);
1507         }
1508         return this;
1509 }
1510
1511
1512 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1513 {
1514         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1515         BufferView & bv = cur.bv();
1516         if (cmd.button() == mouse_button::button3) {
1517                 // Don't do anything if we right-click a
1518                 // selection, a context menu will popup.
1519                 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1520                       && cur < bv.cursor().selectionEnd()) {
1521                         cur.noScreenUpdate();
1522                         return;
1523                 }
1524         }
1525
1526         // set cursor after the inset if x is nearer to that position (bug 9748)
1527         cur.moveToClosestEdge(cmd.x(), true);
1528
1529         bool do_selection = cmd.button() == mouse_button::button1
1530                 && cmd.modifier() == ShiftModifier;
1531         bv.mouseSetCursor(cur, do_selection);
1532         if (cmd.button() == mouse_button::button1) {
1533                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1534                 // Update the cursor update flags as needed:
1535                 //
1536                 // Update::Decoration: tells to update the decoration
1537                 //                     (visual box corners that define
1538                 //                     the inset)/
1539                 // Update::FitCursor: adjust the screen to the cursor
1540                 //                    position if needed
1541                 // cur.result().update(): don't overwrite previously set flags.
1542                 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1543                                 | cur.result().screenUpdate());
1544         } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1545                 if (cap::selection()) {
1546                         // See comment in Text::dispatch why we do this
1547                         cap::copySelectionToStack();
1548                         cmd = FuncRequest(LFUN_PASTE, "0");
1549                         doDispatch(bv.cursor(), cmd);
1550                 } else {
1551                         MathData ar;
1552                         asArray(theSelection().get(), ar);
1553                         bv.cursor().insert(ar);
1554                 }
1555         }
1556 }
1557
1558
1559 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1560 {
1561         // only select with button 1
1562         if (cmd.button() != mouse_button::button1)
1563                 return;
1564
1565         Cursor & bvcur = cur.bv().cursor();
1566
1567         // ignore motions deeper nested than the real anchor
1568         if (!bvcur.realAnchor().hasPart(cur)) {
1569                 cur.undispatched();
1570                 return;
1571         }
1572
1573         // set cursor after the inset if x is nearer to that position (bug 9748)
1574         cur.moveToClosestEdge(cmd.x());
1575
1576         CursorSlice old = bvcur.top();
1577
1578         // We continue with our existing selection or start a new one, so don't
1579         // reset the anchor.
1580         bvcur.setCursor(cur);
1581         // Did we actually move?
1582         if (cur.top() == old)
1583                 // We didn't move one iota, so no need to change selection status
1584                 // or update the screen.
1585                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1586         else
1587                 bvcur.setSelection();
1588 }
1589
1590
1591 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1592 {
1593         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1594
1595         if (cmd.button() == mouse_button::button1) {
1596                 if (!cur.selection())
1597                         cur.noScreenUpdate();
1598                 else {
1599                         Cursor & bvcur = cur.bv().cursor();
1600                         bvcur.selection(true);
1601                 }
1602                 return;
1603         }
1604
1605         cur.undispatched();
1606 }
1607
1608
1609 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1610 {
1611         //lyxerr << "interpret 2: '" << c << "'" << endl;
1612         docstring save_selection;
1613         if (c == '^' || c == '_')
1614                 save_selection = grabAndEraseSelection(cur);
1615
1616         cur.clearTargetX();
1617         Buffer * buf = cur.buffer();
1618
1619         // handle macroMode
1620         if (cur.inMacroMode()) {
1621                 docstring name = cur.macroName();
1622
1623                 /// are we currently typing '#1' or '#2' or...?
1624                 if (name == "\\#") {
1625                         cur.backspace();
1626                         int n = c - '0';
1627                         if (n >= 1 && n <= 9)
1628                                 cur.insert(new InsetMathMacroArgument(n));
1629                         return true;
1630                 }
1631
1632                 // do not finish macro for known * commands
1633                 bool star_macro = c == '*'
1634                         && (in_word_set(name.substr(1) + '*')
1635                             || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1636                 if (isAlphaASCII(c) || star_macro) {
1637                         cur.activeMacro()->setName(name + docstring(1, c));
1638                         return true;
1639                 }
1640
1641                 // handle 'special char' macros
1642                 if (name == "\\") {
1643                         // remove the '\\'
1644                         if (c == '\\') {
1645                                 cur.backspace();
1646                                 if (currentMode() != InsetMath::MATH_MODE)
1647                                         cur.niceInsert(createInsetMath("textbackslash", buf));
1648                                 else
1649                                         cur.niceInsert(createInsetMath("backslash", buf));
1650                         } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1651                                 cur.backspace();
1652                                 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1653                         } else if (c == '{' || c == '%') {
1654                                 //using the saved selection as argument
1655                                 InsetMathUnknown * p = cur.activeMacro();
1656                                 p->finalize();
1657                                 MathData sel(cur.buffer());
1658                                 asArray(p->selection(), sel);
1659                                 cur.backspace();
1660                                 if (c == '{')
1661                                         cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1662                                 else
1663                                         cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1664                         } else if (c == '#') {
1665                                 LASSERT(cur.activeMacro(), return false);
1666                                 cur.activeMacro()->setName(name + docstring(1, c));
1667                         } else {
1668                                 cur.backspace();
1669                                 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1670                         }
1671                         return true;
1672                 }
1673
1674                 // One character big delimiters. The others are handled in
1675                 // interpretString().
1676                 latexkeys const * l = in_word_set(name.substr(1));
1677                 if (name[0] == '\\' && l && l->inset == "big") {
1678                         docstring delim;
1679                         switch (c) {
1680                         case '{':
1681                                 delim = from_ascii("\\{");
1682                                 break;
1683                         case '}':
1684                                 delim = from_ascii("\\}");
1685                                 break;
1686                         default:
1687                                 delim = docstring(1, c);
1688                                 break;
1689                         }
1690                         if (InsetMathBig::isBigInsetDelim(delim)) {
1691                                 // name + delim ared a valid InsetMathBig.
1692                                 // We can't use cur.macroModeClose() because
1693                                 // it does not handle delim.
1694                                 InsetMathUnknown * p = cur.activeMacro();
1695                                 p->finalize();
1696                                 --cur.pos();
1697                                 cur.cell().erase(cur.pos());
1698                                 cur.plainInsert(MathAtom(
1699                                         new InsetMathBig(name.substr(1), delim)));
1700                                 return true;
1701                         }
1702                 } else if (name == "\\smash" && c == '[') {
1703                         // We can't use cur.macroModeClose() because
1704                         // it would create an InsetMathPhantom
1705                         InsetMathUnknown * p = cur.activeMacro();
1706                         p->finalize();
1707                         interpretChar(cur, c);
1708                         return true;
1709                 }
1710
1711                 // leave macro mode and try again if necessary
1712                 if (cur.macroModeClose()) {
1713                         MathAtom const atom = cur.prevAtom();
1714                         if (atom->asNestInset() && atom->isActive()) {
1715                                 cur.posBackward();
1716                                 cur.nextInset()->edit(cur, true);
1717                         }
1718                 }
1719                 if (c == '{')
1720                         cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1721                 else if (c != ' ')
1722                         interpretChar(cur, c);
1723                 return true;
1724         }
1725
1726
1727         // leave autocorrect mode if necessary
1728         if (lyxrc.autocorrection_math && c == ' ' && cur.autocorrect()) {
1729                 cur.autocorrect() = false;
1730                 cur.message(_("Autocorrect Off ('!' to enter)"));
1731                 return true;
1732         }
1733         if (lyxrc.autocorrection_math && c == '!' && !cur.autocorrect()) {
1734                 cur.autocorrect() = true;
1735                 cur.message(_("Autocorrect On (<space> to exit)"));
1736                 return true;
1737         }
1738
1739         // just clear selection on pressing the space bar
1740         if (cur.selection() && c == ' ') {
1741                 cur.selection(false);
1742                 return true;
1743         }
1744
1745         if (c == '\\') {
1746                 //lyxerr << "starting with macro" << endl;
1747                 bool reduced = cap::reduceSelectionToOneCell(cur);
1748                 if (reduced || !cur.selection()) {
1749                         cur.recordUndoInset();
1750                         docstring const safe = cap::grabAndEraseSelection(cur);
1751                         if (!cur.inRegexped())
1752                                 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1753                         else
1754                                 cur.niceInsert(createInsetMath("backslash", buf));
1755                 }
1756                 return true;
1757         }
1758
1759         selClearOrDel(cur);
1760
1761         if (c == '\n') {
1762                 if (currentMode() != InsetMath::MATH_MODE)
1763                         cur.insert(c);
1764                 return true;
1765         }
1766
1767         if (c == ' ') {
1768                 if (currentMode() != InsetMath::MATH_MODE) {
1769                         // insert spaces in text or undecided mode,
1770                         // but suppress direct insertion of two spaces in a row
1771                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1772                         // it is better than nothing...
1773                         if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1774                                 cur.insert(c);
1775                                 // FIXME: we have to enable full redraw here because of the
1776                                 // visual box corners that define the inset. If we know for
1777                                 // sure that we stay within the same cell we can optimize for
1778                                 // that using:
1779                                 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1780                         }
1781                         return true;
1782                 }
1783                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1784                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1785                         // FIXME: we have to enable full redraw here because of the
1786                         // visual box corners that define the inset. If we know for
1787                         // sure that we stay within the same cell we can optimize for
1788                         // that using:
1789                         //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1790                         return true;
1791                 }
1792
1793                 if (cur.popForward()) {
1794                         // FIXME: we have to enable full redraw here because of the
1795                         // visual box corners that define the inset. If we know for
1796                         // sure that we stay within the same cell we can optimize for
1797                         // that using:
1798                         //cur.screenUpdateFlags(Update::FitCursor);
1799                         return true;
1800                 }
1801
1802                 // if we are at the very end, leave the formula
1803                 return cur.pos() != cur.lastpos();
1804         }
1805
1806         // These should be treated differently when not in text mode:
1807         if (cur.inRegexped()) {
1808                 switch (c) {
1809                 case '^':
1810                         cur.niceInsert(createInsetMath("mathcircumflex", buf));
1811                         break;
1812                 case '{':
1813                 case '}':
1814                 case '#':
1815                 case '%':
1816                 case '_':
1817                         cur.niceInsert(createInsetMath(docstring(1, c), buf));
1818                         break;
1819                 case '~':
1820                         cur.niceInsert(createInsetMath("sim", buf));
1821                         break;
1822                 default:
1823                         cur.insert(c);
1824                 }
1825                 return true;
1826         } else if (currentMode() != InsetMath::TEXT_MODE) {
1827                 if (c == '_') {
1828                         script(cur, false, save_selection);
1829                         return true;
1830                 }
1831                 if (c == '^') {
1832                         script(cur, true, save_selection);
1833                         return true;
1834                 }
1835                 if (c == '~') {
1836                         cur.niceInsert(createInsetMath("sim", buf));
1837                         return true;
1838                 }
1839                 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1840                         MathAtom at = createInsetMath("text", buf);
1841                         at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1842                         cur.niceInsert(at);
1843                         cur.posForward();
1844                         return true;
1845                 }
1846         } else {
1847                 if (c == '^') {
1848                         cur.niceInsert(createInsetMath("textasciicircum", buf));
1849                         return true;
1850                 }
1851                 if (c == '~') {
1852                         cur.niceInsert(createInsetMath("textasciitilde", buf));
1853                         return true;
1854                 }
1855         }
1856
1857         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1858             c == '%' || c == '_') {
1859                 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1860                 return true;
1861         }
1862
1863
1864         // try auto-correction
1865         if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0
1866                   && math_autocorrect(cur.prevAtom(), c))
1867                 return true;
1868
1869         // no special circumstances, so insert the character without any fuss
1870         cur.insert(c);
1871         if (lyxrc.autocorrection_math) {
1872                 if (!cur.autocorrect())
1873                         cur.message(_("Autocorrect Off ('!' to enter)"));
1874                 else
1875                         cur.message(_("Autocorrect On (<space> to exit)"));
1876         }
1877         return true;
1878 }
1879
1880
1881 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1882 {
1883         // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1884         // possible
1885         if (!cur.empty() && cur.pos() > 0 &&
1886             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1887                 if (InsetMathBig::isBigInsetDelim(str)) {
1888                         docstring prev = asString(cur.cell()[cur.pos() - 1]);
1889                         if (prev[0] == '\\') {
1890                                 prev = prev.substr(1);
1891                                 latexkeys const * l = in_word_set(prev);
1892                                 if (l && l->inset == "big") {
1893                                         cur.recordUndoSelection();
1894                                         cur.cell()[cur.pos() - 1] =
1895                                                 MathAtom(new InsetMathBig(prev, str));
1896                                         return true;
1897                                 }
1898                         }
1899                 }
1900         }
1901         return false;
1902 }
1903
1904
1905 bool InsetMathNest::script(Cursor & cur, bool up)
1906 {
1907         return script(cur, up, docstring());
1908 }
1909
1910
1911 bool InsetMathNest::script(Cursor & cur, bool up,
1912                 docstring const & save_selection)
1913 {
1914         // Hack to get \^ and \_ working
1915         //lyxerr << "handling script: up: " << up << endl;
1916         if (cur.inMacroMode() && cur.macroName() == "\\") {
1917                 if (up)
1918                         cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1919                 else
1920                         interpretChar(cur, '_');
1921                 return true;
1922         }
1923
1924         cur.macroModeClose();
1925         if (asScriptInset() && cur.idx() == 0) {
1926                 // we are in a nucleus of a script inset, move to _our_ script
1927                 InsetMathScript * inset = asScriptInset();
1928                 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1929                 inset->ensure(up);
1930                 cur.idx() = inset->idxOfScript(up);
1931                 cur.pos() = 0;
1932         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1933                 --cur.pos();
1934                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1935                 cur.push(*inset);
1936                 inset->ensure(up);
1937                 cur.idx() = inset->idxOfScript(up);
1938                 cur.pos() = cur.lastpos();
1939         } else {
1940                 // convert the thing to our left to a scriptinset or create a new
1941                 // one if in the very first position of the array
1942                 if (cur.pos() == 0) {
1943                         //lyxerr << "new scriptinset" << endl;
1944                         cur.insert(new InsetMathScript(buffer_, up));
1945                 } else {
1946                         //lyxerr << "converting prev atom " << endl;
1947                         cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1948                 }
1949                 --cur.pos();
1950                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1951                 // See comment in MathParser.cpp for special handling of {}-bases
1952
1953                 cur.push(*inset);
1954                 cur.idx() = 1;
1955                 cur.pos() = 0;
1956         }
1957         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1958         cur.niceInsert(save_selection);
1959         cur.resetAnchor();
1960         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1961         return true;
1962 }
1963
1964
1965 bool InsetMathNest::completionSupported(Cursor const & cur) const
1966 {
1967         return cur.inMacroMode();
1968 }
1969
1970
1971 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1972 {
1973         return cur.inMacroMode();
1974 }
1975
1976
1977 bool InsetMathNest::automaticInlineCompletion() const
1978 {
1979         return lyxrc.completion_inline_math;
1980 }
1981
1982
1983 bool InsetMathNest::automaticPopupCompletion() const
1984 {
1985         return lyxrc.completion_popup_math;
1986 }
1987
1988
1989 CompletionList const *
1990 InsetMathNest::createCompletionList(Cursor const & cur) const
1991 {
1992         if (!cur.inMacroMode())
1993                 return 0;
1994
1995         return new MathCompletionList(cur);
1996 }
1997
1998
1999 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2000 {
2001         if (!cur.inMacroMode())
2002                 return docstring();
2003
2004         return cur.activeMacro()->name();
2005 }
2006
2007
2008 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2009                                      bool finished)
2010 {
2011         if (!cur.inMacroMode())
2012                 return false;
2013
2014         // append completion to active macro
2015         InsetMathUnknown * inset = cur.activeMacro();
2016         inset->setName(inset->name() + s);
2017
2018         // finish macro
2019         if (finished) {
2020 #if 0
2021                 // FIXME: this creates duplicates in the completion popup
2022                 // which looks ugly. Moreover the changes the list lengths
2023                 // which seems to confuse the popup as well.
2024                 MathCompletionList::addToFavorites(inset->name());
2025 #endif
2026                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2027         }
2028
2029         return true;
2030 }
2031
2032
2033 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2034                                         Dimension & dim) const
2035 {
2036         Inset const * inset = cur.activeMacro();
2037         if (!inset)
2038                 return;
2039
2040         // get inset dimensions
2041         dim = cur.bv().coordCache().insets().dim(inset);
2042         // FIXME: these 3 are no accurate, but should depend on the font.
2043         // Now the popup jumps down if you enter a char with descent > 0.
2044         dim.des += 3;
2045         dim.asc += 3;
2046
2047         // and position
2048         Point xy = cur.bv().coordCache().insets().xy(inset);
2049         x = xy.x_;
2050         y = xy.y_;
2051 }
2052
2053
2054 ////////////////////////////////////////////////////////////////////
2055
2056 MathCompletionList::MathCompletionList(Cursor const & cur)
2057 {
2058         // fill it with macros from the buffer
2059         MacroNameSet macros;
2060         cur.buffer()->listMacroNames(macros);
2061         MacroNameSet::const_iterator it;
2062         for (it = macros.begin(); it != macros.end(); ++it) {
2063                 if (cur.buffer()->getMacro(*it, cur, false))
2064                         locals.push_back("\\" + *it);
2065         }
2066         sort(locals.begin(), locals.end());
2067
2068         if (!globals.empty())
2069                 return;
2070
2071         // fill in global macros
2072         macros.clear();
2073         MacroTable::globalMacros().getMacroNames(macros, false);
2074         //lyxerr << "Globals completion macros: ";
2075         for (it = macros.begin(); it != macros.end(); ++it) {
2076                 //lyxerr << "\\" + *it << " ";
2077                 globals.push_back("\\" + *it);
2078         }
2079         //lyxerr << std::endl;
2080
2081         // fill in global commands
2082         globals.push_back(from_ascii("\\boxed"));
2083         globals.push_back(from_ascii("\\fbox"));
2084         globals.push_back(from_ascii("\\framebox"));
2085         globals.push_back(from_ascii("\\makebox"));
2086         globals.push_back(from_ascii("\\kern"));
2087         globals.push_back(from_ascii("\\xhookrightarrow"));
2088         globals.push_back(from_ascii("\\xhookleftarrow"));
2089         globals.push_back(from_ascii("\\xrightarrow"));
2090         globals.push_back(from_ascii("\\xRightarrow"));
2091         globals.push_back(from_ascii("\\xrightharpoondown"));
2092         globals.push_back(from_ascii("\\xrightharpoonup"));
2093         globals.push_back(from_ascii("\\xrightleftharpoons"));
2094         globals.push_back(from_ascii("\\xleftarrow"));
2095         globals.push_back(from_ascii("\\xLeftarrow"));
2096         globals.push_back(from_ascii("\\xleftharpoondown"));
2097         globals.push_back(from_ascii("\\xleftharpoonup"));
2098         globals.push_back(from_ascii("\\xleftrightarrow"));
2099         globals.push_back(from_ascii("\\xLeftrightarrow"));
2100         globals.push_back(from_ascii("\\xleftrightharpoons"));
2101         globals.push_back(from_ascii("\\xmapsto"));
2102         globals.push_back(from_ascii("\\split"));
2103         globals.push_back(from_ascii("\\gathered"));
2104         globals.push_back(from_ascii("\\aligned"));
2105         globals.push_back(from_ascii("\\alignedat"));
2106         globals.push_back(from_ascii("\\cases"));
2107         globals.push_back(from_ascii("\\substack"));
2108         globals.push_back(from_ascii("\\xymatrix"));
2109         globals.push_back(from_ascii("\\Diagram"));
2110         globals.push_back(from_ascii("\\subarray"));
2111         globals.push_back(from_ascii("\\array"));
2112         globals.push_back(from_ascii("\\sqrt"));
2113         globals.push_back(from_ascii("\\root"));
2114         globals.push_back(from_ascii("\\tabular"));
2115         globals.push_back(from_ascii("\\sideset"));
2116         globals.push_back(from_ascii("\\stackrel"));
2117         globals.push_back(from_ascii("\\stackrelthree"));
2118         globals.push_back(from_ascii("\\binom"));
2119         globals.push_back(from_ascii("\\choose"));
2120         globals.push_back(from_ascii("\\brace"));
2121         globals.push_back(from_ascii("\\brack"));
2122         globals.push_back(from_ascii("\\frac"));
2123         globals.push_back(from_ascii("\\over"));
2124         globals.push_back(from_ascii("\\nicefrac"));
2125         globals.push_back(from_ascii("\\unitfrac"));
2126         globals.push_back(from_ascii("\\unitfracthree"));
2127         globals.push_back(from_ascii("\\unitone"));
2128         globals.push_back(from_ascii("\\unittwo"));
2129         globals.push_back(from_ascii("\\infer"));
2130         globals.push_back(from_ascii("\\atop"));
2131         globals.push_back(from_ascii("\\lefteqn"));
2132         globals.push_back(from_ascii("\\boldsymbol"));
2133         globals.push_back(from_ascii("\\bm"));
2134         globals.push_back(from_ascii("\\color"));
2135         globals.push_back(from_ascii("\\normalcolor"));
2136         globals.push_back(from_ascii("\\textcolor"));
2137         globals.push_back(from_ascii("\\cfrac"));
2138         globals.push_back(from_ascii("\\cfracleft"));
2139         globals.push_back(from_ascii("\\cfracright"));
2140         globals.push_back(from_ascii("\\dfrac"));
2141         globals.push_back(from_ascii("\\tfrac"));
2142         globals.push_back(from_ascii("\\dbinom"));
2143         globals.push_back(from_ascii("\\tbinom"));
2144         globals.push_back(from_ascii("\\hphantom"));
2145         globals.push_back(from_ascii("\\phantom"));
2146         globals.push_back(from_ascii("\\vphantom"));
2147         globals.push_back(from_ascii("\\cancel"));
2148         globals.push_back(from_ascii("\\bcancel"));
2149         globals.push_back(from_ascii("\\xcancel"));
2150         globals.push_back(from_ascii("\\cancelto"));
2151         globals.push_back(from_ascii("\\smash"));
2152         globals.push_back(from_ascii("\\mathclap"));
2153         globals.push_back(from_ascii("\\mathllap"));
2154         globals.push_back(from_ascii("\\mathrlap"));
2155         globals.push_back(from_ascii("\\ensuremath"));
2156         MathWordList const & words = mathedWordList();
2157         MathWordList::const_iterator it2;
2158         //lyxerr << "Globals completion commands: ";
2159         for (it2 = words.begin(); it2 != words.end(); ++it2) {
2160                 if (it2->second.inset != "macro" && !it2->second.hidden) {
2161                         // macros are already read from MacroTable::globalMacros()
2162                         globals.push_back('\\' + it2->first);
2163                         //lyxerr << '\\' + it2->first << ' ';
2164                 }
2165         }
2166         //lyxerr << std::endl;
2167         sort(globals.begin(), globals.end());
2168 }
2169
2170
2171 MathCompletionList::~MathCompletionList()
2172 {
2173 }
2174
2175
2176 size_type MathCompletionList::size() const
2177 {
2178         return locals.size() + globals.size();
2179 }
2180
2181
2182 docstring const & MathCompletionList::data(size_t idx) const
2183 {
2184         size_t lsize = locals.size();
2185         if (idx >= lsize)
2186                 return globals[idx - lsize];
2187         else
2188                 return locals[idx];
2189 }
2190
2191
2192 std::string MathCompletionList::icon(size_t idx) const
2193 {
2194         // get the latex command
2195         docstring cmd;
2196         size_t lsize = locals.size();
2197         if (idx >= lsize)
2198                 cmd = globals[idx - lsize];
2199         else
2200                 cmd = locals[idx];
2201
2202         // get the icon resource name by stripping the backslash
2203         docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2204         if (icon_name.empty())
2205                 return std::string();
2206         return "images/math/" + to_utf8(icon_name);
2207 }
2208
2209 std::vector<docstring> MathCompletionList::globals;
2210
2211 } // namespace lyx