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