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