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