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