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