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