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