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