]> git.lyx.org Git - lyx.git/blob - src/mathed/math_nestinset.C
fix two crashes related to dEPM. Some crashes remain
[lyx.git] / src / mathed / math_nestinset.C
1 /**
2  * \file math_nestinset.C
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 "math_nestinset.h"
14
15 #include "math_arrayinset.h"
16 #include "math_boxinset.h"
17 #include "math_braceinset.h"
18 #include "math_colorinset.h"
19 #include "math_commentinset.h"
20 #include "math_data.h"
21 #include "math_deliminset.h"
22 #include "math_factory.h"
23 #include "math_hullinset.h"
24 #include "math_mathmlstream.h"
25 #include "math_macroarg.h"
26 //#include "math_mboxinset.h"
27 #include "math_parser.h"
28 #include "math_scriptinset.h"
29 #include "math_spaceinset.h"
30 #include "math_symbolinset.h"
31 #include "math_support.h"
32 #include "math_unknowninset.h"
33
34 #include "BufferView.h"
35 #include "CutAndPaste.h"
36 #include "FuncStatus.h"
37 #include "LColor.h"
38 #include "bufferview_funcs.h"
39 #include "coordcache.h"
40 #include "cursor.h"
41 #include "debug.h"
42 #include "dispatchresult.h"
43 #include "funcrequest.h"
44 #include "gettext.h"
45 #include "outputparams.h"
46 #include "undo.h"
47
48 #include "support/lstrings.h"
49
50 #include "frontends/Dialogs.h"
51 #include "frontends/LyXView.h"
52 #include "frontends/Painter.h"
53
54 #include <sstream>
55
56 using lyx::cap::copySelection;
57 using lyx::cap::grabAndEraseSelection;
58 using lyx::cap::cutSelection;
59 using lyx::cap::pasteSelection;
60 using lyx::cap::replaceSelection;
61 using lyx::cap::selClearOrDel;
62
63 using std::endl;
64 using std::string;
65 using std::istringstream;
66
67
68 MathNestInset::MathNestInset(idx_type nargs)
69         : cells_(nargs), lock_(false)
70 {}
71
72
73 MathInset::idx_type MathNestInset::nargs() const
74 {
75         return cells_.size();
76 }
77
78
79 MathArray & MathNestInset::cell(idx_type i)
80 {
81         return cells_[i];
82 }
83
84
85 MathArray const & MathNestInset::cell(idx_type i) const
86 {
87         return cells_[i];
88 }
89
90
91 void MathNestInset::cursorPos(CursorSlice const & sl, bool /*boundary*/,
92         int & x, int & y) const
93 {
94 // FIXME: This is a hack. Ideally, the coord cache should not store
95 // absolute positions, but relative ones. This would mean to call
96 // setXY() not in MathArray::draw(), but in the parent insets' draw()
97 // with the correctly adjusted x,y values. But this means that we'd have
98 // to touch all (math)inset's draw() methods. Right now, we'll store
99 // absolute value, and make them here relative, only to make them
100 // absolute again when actually drawing the cursor. What a mess.
101         BOOST_ASSERT(ptr_cmp(&sl.inset(), this));
102         MathArray const & ar = sl.cell();
103         if (!theCoords.getArrays().has(&ar)) {
104                 // this can (semi-)legally happen if we just created this cell
105                 // and it never has been drawn before. So don't ASSERT.
106                 //lyxerr << "no cached data for array " << &ar << endl;
107                 x = 0;
108                 y = 0;
109                 return;
110         }
111         Point const pt = theCoords.getArrays().xy(&ar);
112         if (!theCoords.getInsets().has(this)) {
113                 // same as above
114                 //lyxerr << "no cached data for inset " << this << endl;
115                 x = 0;
116                 y = 0;
117                 return;
118         }
119         Point const pt2 = theCoords.getInsets().xy(this);
120         //lyxerr << "retrieving position cache for MathArray "
121         //      << pt.x_ << ' ' << pt.y_ << std::endl;
122         x = pt.x_ - pt2.x_ + ar.pos2x(sl.pos());
123         y = pt.y_ - pt2.y_;
124 //      lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
125 //              << " asc: " << ascent() << "  des: " << descent()
126 //              << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
127         // move cursor visually into empty cells ("blue rectangles");
128         if (ar.empty())
129                 x += 2;
130 }
131
132
133 void MathNestInset::metrics(MetricsInfo const & mi) const
134 {
135         MetricsInfo m = mi;
136         for (idx_type i = 0, n = nargs(); i != n; ++i)
137                 cell(i).metrics(m);
138 }
139
140
141 bool MathNestInset::idxNext(LCursor & cur) const
142 {
143         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
144         if (cur.idx() == cur.lastidx())
145                 return false;
146         ++cur.idx();
147         cur.pos() = 0;
148         return true;
149 }
150
151
152 bool MathNestInset::idxRight(LCursor & cur) const
153 {
154         return idxNext(cur);
155 }
156
157
158 bool MathNestInset::idxPrev(LCursor & cur) const
159 {
160         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
161         if (cur.idx() == 0)
162                 return false;
163         --cur.idx();
164         cur.pos() = cur.lastpos();
165         return true;
166 }
167
168
169 bool MathNestInset::idxLeft(LCursor & cur) const
170 {
171         return idxPrev(cur);
172 }
173
174
175 bool MathNestInset::idxFirst(LCursor & cur) const
176 {
177         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
178         if (nargs() == 0)
179                 return false;
180         cur.idx() = 0;
181         cur.pos() = 0;
182         return true;
183 }
184
185
186 bool MathNestInset::idxLast(LCursor & cur) const
187 {
188         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
189         if (nargs() == 0)
190                 return false;
191         cur.idx() = cur.lastidx();
192         cur.pos() = cur.lastpos();
193         return true;
194 }
195
196
197 void MathNestInset::dump() const
198 {
199         WriteStream os(lyxerr);
200         os << "---------------------------------------------\n";
201         write(os);
202         os << "\n";
203         for (idx_type i = 0, n = nargs(); i != n; ++i)
204                 os << cell(i) << "\n";
205         os << "---------------------------------------------\n";
206 }
207
208
209 void MathNestInset::draw(PainterInfo & pi, int x, int y) const
210 {
211 #if 0
212         if (lock_)
213                 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
214                                         LColor::mathlockbg);
215 #endif
216         setPosCache(pi, x, y);
217 }
218
219
220 void MathNestInset::drawSelection(PainterInfo & pi, int x, int y) const
221 {
222         // FIXME: hack to get position cache warm
223         draw(pi, x, y);
224
225         // this should use the x/y values given, not the cached values
226         LCursor & cur = pi.base.bv->cursor();
227         if (!cur.selection())
228                 return;
229         if (!ptr_cmp(&cur.inset(), this))
230                 return;
231
232         CursorSlice s1 = cur.selBegin();
233         CursorSlice s2 = cur.selEnd();
234         //lyxerr << "MathNestInset::drawing selection: "
235         //      << " s1: " << s1 << " s2: " << s2 << endl;
236         if (s1.idx() == s2.idx()) {
237                 MathArray const & c = cell(s1.idx());
238                 int x1 = c.xo() + c.pos2x(s1.pos());
239                 int y1 = c.yo() - c.ascent();
240                 int x2 = c.xo() + c.pos2x(s2.pos());
241                 int y2 = c.yo() + c.descent();
242                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
243         //lyxerr << "MathNestInset::drawing selection 3: "
244         //      << " x1: " << x1 << " x2: " << x2
245         //      << " y1: " << y1 << " y2: " << y2 << endl;
246         } else {
247                 for (idx_type i = 0; i < nargs(); ++i) {
248                         if (idxBetween(i, s1.idx(), s2.idx())) {
249                                 MathArray const & c = cell(i);
250                                 int x1 = c.xo();
251                                 int y1 = c.yo() - c.ascent();
252                                 int x2 = c.xo() + c.width();
253                                 int y2 = c.yo() + c.descent();
254                                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
255                         }
256                 }
257         }
258 }
259
260
261 void MathNestInset::validate(LaTeXFeatures & features) const
262 {
263         for (idx_type i = 0; i < nargs(); ++i)
264                 cell(i).validate(features);
265 }
266
267
268 void MathNestInset::replace(ReplaceData & rep)
269 {
270         for (idx_type i = 0; i < nargs(); ++i)
271                 cell(i).replace(rep);
272 }
273
274
275 bool MathNestInset::contains(MathArray const & ar) const
276 {
277         for (idx_type i = 0; i < nargs(); ++i)
278                 if (cell(i).contains(ar))
279                         return true;
280         return false;
281 }
282
283
284 bool MathNestInset::lock() const
285 {
286         return lock_;
287 }
288
289
290 void MathNestInset::lock(bool l)
291 {
292         lock_ = l;
293 }
294
295
296 bool MathNestInset::isActive() const
297 {
298         return nargs() > 0;
299 }
300
301
302 MathArray MathNestInset::glue() const
303 {
304         MathArray ar;
305         for (size_t i = 0; i < nargs(); ++i)
306                 ar.append(cell(i));
307         return ar;
308 }
309
310
311 void MathNestInset::write(WriteStream & os) const
312 {
313         os << '\\' << name().c_str();
314         for (size_t i = 0; i < nargs(); ++i)
315                 os << '{' << cell(i) << '}';
316         if (nargs() == 0)
317                 os.pendingSpace(true);
318         if (lock_ && !os.latex()) {
319                 os << "\\lyxlock";
320                 os.pendingSpace(true);
321         }
322 }
323
324
325 void MathNestInset::normalize(NormalStream & os) const
326 {
327         os << '[' << name().c_str();
328         for (size_t i = 0; i < nargs(); ++i)
329                 os << ' ' << cell(i);
330         os << ']';
331 }
332
333
334 int MathNestInset::latex(Buffer const &, std::ostream & os,
335                         OutputParams const & runparams) const
336 {
337         WriteStream wi(os, runparams.moving_arg, true);
338         write(wi);
339         return wi.line();
340 }
341
342
343 void MathNestInset::notifyCursorLeaves(LCursor & /*cur*/)
344 {
345 #ifdef WITH_WARNINGS
346 #warning look here
347 #endif
348 #if 0
349         MathArray & ar = cur.cell();
350         // remove base-only "scripts"
351         for (pos_type i = 0; i + 1 < ar.size(); ++i) {
352                 MathScriptInset * p = operator[](i).nucleus()->asScriptInset();
353                 if (p && p->nargs() == 1) {
354                         MathArray ar = p->nuc();
355                         erase(i);
356                         insert(i, ar);
357                         cur.adjust(i, ar.size() - 1);
358                 }
359         }
360
361         // glue adjacent font insets of the same kind
362         for (pos_type i = 0; i + 1 < size(); ++i) {
363                 MathFontInset * p = operator[](i).nucleus()->asFontInset();
364                 MathFontInset const * q = operator[](i + 1)->asFontInset();
365                 if (p && q && p->name() == q->name()) {
366                         p->cell(0).append(q->cell(0));
367                         erase(i + 1);
368                         cur.adjust(i, -1);
369                 }
370         }
371 #endif
372 }
373
374
375 void MathNestInset::handleFont
376         (LCursor & cur, string const & arg, string const & font)
377 {
378         // this whole function is a hack and won't work for incremental font
379         // changes...
380         recordUndo(cur, Undo::ATOMIC);
381
382         if (cur.inset().asMathInset()->name() == font)
383                 cur.handleFont(font);
384         else {
385                 cur.handleNest(createMathInset(font));
386                 cur.insert(arg);
387         }
388 }
389
390
391 void MathNestInset::handleFont2(LCursor & cur, string const & arg)
392 {
393         recordUndo(cur, Undo::ATOMIC);
394         LyXFont font;
395         bool b;
396         bv_funcs::string2font(arg, font, b);
397         if (font.color() != LColor::inherit) {
398                 MathAtom at = MathAtom(new MathColorInset(true, font.color()));
399                 cur.handleNest(at, 0);
400         }
401 }
402
403
404 void MathNestInset::doDispatch(LCursor & cur, FuncRequest & cmd)
405 {
406         //lyxerr << "MathNestInset: request: " << cmd << std::endl;
407         //CursorSlice sl = cur.current();
408
409         switch (cmd.action) {
410
411         case LFUN_PASTE: {
412                 recordUndo(cur);
413                 cur.message(_("Paste"));
414                 replaceSelection(cur);
415                 size_t n = 0;
416                 istringstream is(cmd.argument);
417                 is >> n;
418                 string const selection = lyx::cap::getSelection(cur.buffer(), n);
419                 cur.niceInsert(selection);
420                 cur.clearSelection(); // bug 393
421                 cur.bv().switchKeyMap();
422                 finishUndo();
423                 break;
424         }
425
426         case LFUN_CUT:
427                 recordUndo(cur);
428                 cutSelection(cur, true, true);
429                 cur.message(_("Cut"));
430                 // Prevent stale position >= size crash
431                 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
432                 cur.normalize();
433                 break;
434
435         case LFUN_COPY:
436                 copySelection(cur);
437                 cur.message(_("Copy"));
438                 break;
439
440         case LFUN_MOUSE_PRESS:
441                 lfunMousePress(cur, cmd);
442                 break;
443
444         case LFUN_MOUSE_MOTION:
445                 lfunMouseMotion(cur, cmd);
446                 break;
447
448         case LFUN_MOUSE_RELEASE:
449                 lfunMouseRelease(cur, cmd);
450                 break;
451
452         case LFUN_FINISHED_LEFT:
453                 cur.bv().cursor() = cur;
454                 break;
455
456         case LFUN_FINISHED_RIGHT:
457                 ++cur.pos();
458                 cur.bv().cursor() = cur;
459                 break;
460
461         case LFUN_FINISHED_UP:
462                 cur.bv().cursor() = cur;
463                 break;
464
465         case LFUN_FINISHED_DOWN:
466                 ++cur.pos();
467                 cur.bv().cursor() = cur;
468                 break;
469
470         case LFUN_RIGHTSEL:
471         case LFUN_RIGHT:
472                 cur.selHandle(cmd.action == LFUN_RIGHTSEL);
473                 cur.autocorrect() = false;
474                 cur.clearTargetX();
475                 cur.macroModeClose();
476                 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
477                         cur.pushLeft(*cur.nextAtom().nucleus());
478                         cur.inset().idxFirst(cur);
479                 } else if (cur.posRight() || idxRight(cur)
480                         || cur.popRight() || cur.selection())
481                         ;
482                 else {
483                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
484                         cur.undispatched();
485                 }
486                 break;
487
488         case LFUN_LEFTSEL:
489         case LFUN_LEFT:
490                 cur.selHandle(cmd.action == LFUN_LEFTSEL);
491                 cur.autocorrect() = false;
492                 cur.clearTargetX();
493                 cur.macroModeClose();
494                 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
495                         cur.posLeft();
496                         cur.push(*cur.nextAtom().nucleus());
497                         cur.inset().idxLast(cur);
498                 } else if (cur.posLeft() || idxLeft(cur)
499                         || cur.popLeft() || cur.selection())
500                         ;
501                 else {
502                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
503                         cur.undispatched();
504                 }
505                 break;
506
507         case LFUN_UPSEL:
508         case LFUN_UP:
509                 // FIXME Tried to use clearTargetX and macroModeClose, crashed on cur.up()
510                 if (cur.inMacroMode()) {
511                         // Make Helge happy
512                         cur.macroModeClose();
513                         break;
514                 }
515                 cur.selHandle(cmd.action == LFUN_UPSEL);
516                 if (!cur.up()) {
517                         cmd = FuncRequest(LFUN_FINISHED_UP);
518                         cur.undispatched();
519                 }
520                 // fixes bug 1598. Please check!
521                 cur.normalize();
522                 break;
523
524         case LFUN_DOWNSEL:
525         case LFUN_DOWN:
526                 if (cur.inMacroMode()) {
527                         cur.macroModeClose();
528                         break;
529                 }
530                 cur.selHandle(cmd.action == LFUN_DOWNSEL);
531                 if (!cur.down()) {
532                         cmd = FuncRequest(LFUN_FINISHED_DOWN);
533                         cur.undispatched();
534                 }
535                 // fixes bug 1598. Please check!
536                 cur.normalize();
537                 break;
538
539         case LFUN_MOUSE_DOUBLE:
540         case LFUN_MOUSE_TRIPLE:
541         case LFUN_WORDSEL:
542                 cur.pos() = 0;
543                 cur.idx() = 0;
544                 cur.resetAnchor();
545                 cur.selection() = true;
546                 cur.pos() = cur.lastpos();
547                 cur.idx() = cur.lastidx();
548                 break;
549
550         case LFUN_UP_PARAGRAPHSEL:
551         case LFUN_UP_PARAGRAPH:
552         case LFUN_DOWN_PARAGRAPHSEL:
553         case LFUN_DOWN_PARAGRAPH:
554                 break;
555
556         case LFUN_HOMESEL:
557         case LFUN_HOME:
558         case LFUN_WORDLEFTSEL:
559         case LFUN_WORDLEFT:
560                 cur.selHandle(cmd.action == LFUN_WORDLEFTSEL || cmd.action == LFUN_HOMESEL);
561                 cur.macroModeClose();
562                 if (cur.pos() != 0) {
563                         cur.pos() = 0;
564                 } else if (cur.col() != 0) {
565                         cur.idx() -= cur.col();
566                         cur.pos() = 0;
567                 } else if (cur.idx() != 0) {
568                         cur.idx() = 0;
569                         cur.pos() = 0;
570                 } else {
571                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
572                         cur.undispatched();
573                 }
574                 break;
575
576         case LFUN_WORDRIGHTSEL:
577         case LFUN_WORDRIGHT:
578         case LFUN_ENDSEL:
579         case LFUN_END:
580                 cur.selHandle(cmd.action == LFUN_WORDRIGHTSEL || cmd.action == LFUN_ENDSEL);
581                 cur.macroModeClose();
582                 cur.clearTargetX();
583                 if (cur.pos() != cur.lastpos()) {
584                         cur.pos() = cur.lastpos();
585                 } else if (ncols() && (cur.col() != cur.lastcol())) {
586                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
587                         cur.pos() = cur.lastpos();
588                 } else if (cur.idx() != cur.lastidx()) {
589                         cur.idx() = cur.lastidx();
590                         cur.pos() = cur.lastpos();
591                 } else {
592                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
593                         cur.undispatched();
594                 }
595                 break;
596
597         case LFUN_PRIORSEL:
598         case LFUN_PRIOR:
599                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
600                 cur.undispatched();
601                 break;
602
603         case LFUN_NEXTSEL:
604         case LFUN_NEXT:
605                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
606                 cur.undispatched();
607                 break;
608
609         case LFUN_CELL_FORWARD:
610                 cur.inset().idxNext(cur);
611                 break;
612
613         case LFUN_CELL_BACKWARD:
614                 cur.inset().idxPrev(cur);
615                 break;
616
617         case LFUN_DELETE_WORD_BACKWARD:
618         case LFUN_BACKSPACE:
619                 if (cur.pos() == 0)
620                         // delete whole cell
621                         recordUndoInset(cur, Undo::ATOMIC);
622                 else
623                         recordUndo(cur, Undo::ATOMIC);
624                 cur.backspace();
625                 break;
626
627         case LFUN_DELETE_WORD_FORWARD:
628         case LFUN_DELETE:
629                 recordUndo(cur);
630                 cur.erase();
631                 break;
632
633         case LFUN_ESCAPE:
634                 if (cur.selection())
635                         cur.clearSelection();
636                 else  {
637                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
638                         cur.undispatched();
639                 }
640                 break;
641
642         case LFUN_INSET_TOGGLE:
643                 recordUndo(cur);
644                 //lockToggle();
645                 if (cur.pos() != cur.lastpos()) {
646                         // toggle previous inset ...
647                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
648                 } else if (cur.popLeft() && cur.pos() != cur.lastpos()) {
649                         // ... or enclosing inset if we are in the last inset position
650                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
651                         ++cur.pos();
652                 }
653                 break;
654
655         case LFUN_SELFINSERT:
656                 if (cmd.argument.size() != 1) {
657                         recordUndo(cur);
658                         cur.insert(cmd.argument);
659                         break;
660                 }
661                 // Don't record undo steps if we are in macro mode and
662                 // cmd.argument is the next character of the macro name.
663                 // Otherwise we'll get an invalid cursor if we undo after
664                 // the macro was finished and the macro is a known command,
665                 // e.g. sqrt. LCursor::macroModeClose replaces in this case
666                 // the MathUnknownInset with name "frac" by an empty
667                 // MathFracInset -> a pos value > 0 is invalid.
668                 // A side effect is that an undo before the macro is finished
669                 // undoes the complete macro, not only the last character.
670                 if (!cur.inMacroMode())
671                         recordUndo(cur);
672                 if (!interpret(cur, cmd.argument[0])) {
673                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
674                         cur.undispatched();
675                 }
676                 break;
677
678         //case LFUN_GETXY:
679         //      sprintf(dispatch_buffer, "%d %d",);
680         //      break;
681
682         case LFUN_SETXY: {
683                 lyxerr << "LFUN_SETXY broken!" << endl;
684                 int x = 0;
685                 int y = 0;
686                 istringstream is(cmd.argument);
687                 is >> x >> y;
688                 cur.setScreenPos(x, y);
689                 break;
690         }
691
692         // Special casing for superscript in case of LyX handling
693         // dead-keys:
694         case LFUN_CIRCUMFLEX:
695                 if (cmd.argument.empty()) {
696                         // do superscript if LyX handles
697                         // deadkeys
698                         recordUndo(cur, Undo::ATOMIC);
699                         script(cur, true);
700                 }
701                 break;
702
703         case LFUN_UMLAUT:
704         case LFUN_ACUTE:
705         case LFUN_GRAVE:
706         case LFUN_BREVE:
707         case LFUN_DOT:
708         case LFUN_MACRON:
709         case LFUN_CARON:
710         case LFUN_TILDE:
711         case LFUN_CEDILLA:
712         case LFUN_CIRCLE:
713         case LFUN_UNDERDOT:
714         case LFUN_TIE:
715         case LFUN_OGONEK:
716         case LFUN_HUNG_UMLAUT:
717                 break;
718
719         //  Math fonts
720         case LFUN_FREEFONT_APPLY:
721         case LFUN_FREEFONT_UPDATE:
722                 handleFont2(cur, cmd.argument);
723                 break;
724
725         case LFUN_BOLD:
726                 if (currentMode() == TEXT_MODE)
727                         handleFont(cur, cmd.argument, "textbf");
728                 else
729                         handleFont(cur, cmd.argument, "mathbf");
730                 break;
731         case LFUN_SANS:
732                 if (currentMode() == TEXT_MODE)
733                         handleFont(cur, cmd.argument, "textsf");
734                 else
735                         handleFont(cur, cmd.argument, "mathsf");
736                 break;
737         case LFUN_EMPH:
738                 if (currentMode() == TEXT_MODE)
739                         handleFont(cur, cmd.argument, "emph");
740                 else
741                         handleFont(cur, cmd.argument, "mathcal");
742                 break;
743         case LFUN_ROMAN:
744                 if (currentMode() == TEXT_MODE)
745                         handleFont(cur, cmd.argument, "textrm");
746                 else
747                         handleFont(cur, cmd.argument, "mathrm");
748                 break;
749         case LFUN_CODE:
750                 if (currentMode() == TEXT_MODE)
751                         handleFont(cur, cmd.argument, "texttt");
752                 else
753                         handleFont(cur, cmd.argument, "mathtt");
754                 break;
755         case LFUN_FRAK:
756                 handleFont(cur, cmd.argument, "mathfrak");
757                 break;
758         case LFUN_ITAL:
759                 if (currentMode() == TEXT_MODE)
760                         handleFont(cur, cmd.argument, "textit");
761                 else
762                         handleFont(cur, cmd.argument, "mathit");
763                 break;
764         case LFUN_NOUN:
765                 if (currentMode() == TEXT_MODE)
766                         // FIXME: should be "noun"
767                         handleFont(cur, cmd.argument, "textsc");
768                 else
769                         handleFont(cur, cmd.argument, "mathbb");
770                 break;
771         //case LFUN_FREEFONT_APPLY:
772                 handleFont(cur, cmd.argument, "textrm");
773                 break;
774         case LFUN_DEFAULT:
775                 handleFont(cur, cmd.argument, "textnormal");
776                 break;
777
778         case LFUN_MATH_MODE:
779 #if 1
780                 // ignore math-mode on when already in math mode
781                 if (currentMode() == InsetBase::MATH_MODE && cmd.argument == "on")
782                         break;
783                 cur.macroModeClose();
784                 selClearOrDel(cur);
785                 //cur.plainInsert(MathAtom(new MathMBoxInset(cur.bv())));
786                 cur.plainInsert(MathAtom(new MathBoxInset("mbox")));
787                 cur.posLeft();
788                 cur.pushLeft(*cur.nextInset());
789 #else
790                 if (currentMode() == InsetBase::TEXT_MODE) {
791                         cur.niceInsert(MathAtom(new MathHullInset("simple")));
792                         cur.message(_("create new math text environment ($...$)"));
793                 } else {
794                         handleFont(cur, cmd.argument, "textrm");
795                         cur.message(_("entered math text mode (textrm)"));
796                 }
797 #endif
798                 break;
799
800         case LFUN_MATH_SIZE:
801 #if 0
802                 recordUndo(cur);
803                 cur.setSize(arg);
804 #endif
805                 break;
806
807         case LFUN_INSERT_MATRIX: {
808                 recordUndo(cur, Undo::ATOMIC);
809                 unsigned int m = 1;
810                 unsigned int n = 1;
811                 string v_align;
812                 string h_align;
813                 istringstream is(cmd.argument);
814                 is >> m >> n >> v_align >> h_align;
815                 if (m < 1)
816                         m = 1;
817                 if (n < 1)
818                         n = 1;
819                 v_align += 'c';
820                 cur.niceInsert(
821                         MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
822                 break;
823         }
824
825         case LFUN_MATH_DELIM: {
826                 lyxerr << "MathNestInset::LFUN_MATH_DELIM" << endl;
827                 string ls;
828                 string rs = lyx::support::split(cmd.argument, ls, ' ');
829                 // Reasonable default values
830                 if (ls.empty())
831                         ls = '(';
832                 if (rs.empty())
833                         rs = ')';
834                 recordUndo(cur, Undo::ATOMIC);
835                 // Don't do this with multi-cell selections
836                 if (cur.selBegin().idx() == cur.selEnd().idx())
837                         cur.handleNest(MathAtom(new MathDelimInset(ls, rs)));
838                 break;
839         }
840
841         case LFUN_SPACE_INSERT:
842         case LFUN_MATH_SPACE:
843                 recordUndo(cur, Undo::ATOMIC);
844                 cur.insert(MathAtom(new MathSpaceInset(",")));
845                 break;
846
847         case LFUN_INSET_ERT:
848                 // interpret this as if a backslash was typed
849                 recordUndo(cur, Undo::ATOMIC);
850                 interpret(cur, '\\');
851                 break;
852
853         case LFUN_SUBSCRIPT:
854                 // interpret this as if a _ was typed
855                 recordUndo(cur, Undo::ATOMIC);
856                 interpret(cur, '_');
857                 break;
858
859         case LFUN_SUPERSCRIPT:
860                 // interpret this as if a ^ was typed
861                 recordUndo(cur, Undo::ATOMIC);
862                 interpret(cur, '^');
863                 break;
864
865 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
866 // handling such that "self-insert" works on "arbitrary stuff" too, and
867 // math-insert only handles special math things like "matrix".
868         case LFUN_INSERT_MATH: {
869                 recordUndo(cur, Undo::ATOMIC);
870                 MathArray ar;
871                 asArray(cmd.argument, ar);
872                 int cell(0);
873                 if (cmd.argument == "\\root")
874                         cell = 1;
875                 // math macros are nest insets and may have 0 cells.
876                 // handleNest would crash in this case.
877                 if (ar.size() == 1 && (ar[0].nucleus()->asNestInset()) &&
878                     ar[0].nucleus()->nargs() > cell) {
879                         cur.handleNest(ar[0], cell);
880                 } else
881                         cur.niceInsert(cmd.argument);
882                 break;
883                 }
884
885         case LFUN_DIALOG_SHOW_NEW_INSET: {
886                 string const & name = cmd.argument;
887                 string data;
888 #if 0
889                 if (name == "ref") {
890                         RefInset tmp(name);
891                         data = tmp.createDialogStr(name);
892                 }
893 #endif
894                 cur.bv().owner()->getDialogs().show(name, data, 0);
895                 break;
896         }
897
898         case LFUN_INSET_APPLY: {
899                 string const name = cmd.getArg(0);
900                 InsetBase * base = cur.bv().owner()->getDialogs().getOpenInset(name);
901
902                 if (base) {
903                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument);
904                         base->dispatch(cur, fr);
905                         break;
906                 }
907                 MathArray ar;
908                 if (createMathInset_fromDialogStr(cmd.argument, ar)) {
909                         cur.insert(ar);
910                         break;
911                 }
912                 cur.undispatched();
913                 break;
914         }
915
916         default:
917                 MathDimInset::doDispatch(cur, cmd);
918                 break;
919         }
920 }
921
922
923 bool MathNestInset::getStatus(LCursor & /*cur*/, FuncRequest const & cmd,
924                 FuncStatus & flag) const
925 {
926         // the font related toggles
927         //string tc = "mathnormal";
928         bool ret = true;
929         string const arg = cmd.argument;
930         switch (cmd.action) {
931         case LFUN_TABULAR_FEATURE:
932                 flag.enabled(false);
933                 break;
934 #if 0
935         case LFUN_TABULAR_FEATURE:
936                 // FIXME: check temporarily disabled
937                 // valign code
938                 char align = mathcursor::valign();
939                 if (align == '\0') {
940                         enable = false;
941                         break;
942                 }
943                 if (cmd.argument.empty()) {
944                         flag.clear();
945                         break;
946                 }
947                 if (!contains("tcb", cmd.argument[0])) {
948                         enable = false;
949                         break;
950                 }
951                 flag.setOnOff(cmd.argument[0] == align);
952                 break;
953 #endif
954         /// We have to handle them since 1.4 blocks all unhandled actions
955         case LFUN_ITAL:
956         case LFUN_BOLD:
957         case LFUN_SANS:
958         case LFUN_EMPH:
959         case LFUN_CODE:
960         case LFUN_NOUN:
961         case LFUN_ROMAN:
962         case LFUN_DEFAULT:
963                 flag.enabled(true);
964                 break;
965         case LFUN_MATH_MUTATE:
966                 //flag.setOnOff(mathcursor::formula()->hullType() == cmd.argument);
967                 flag.setOnOff(false);
968                 break;
969
970         // we just need to be in math mode to enable that
971         case LFUN_MATH_SIZE:
972         case LFUN_MATH_SPACE:
973         case LFUN_MATH_LIMITS:
974         case LFUN_MATH_NONUMBER:
975         case LFUN_MATH_NUMBER:
976         case LFUN_MATH_EXTERN:
977                 flag.enabled(true);
978                 break;
979
980         case LFUN_FRAK:
981                 flag.enabled(currentMode() != TEXT_MODE);
982                 break;
983
984         case LFUN_INSERT_MATH: {
985                 bool const textarg =
986                         arg == "\\textbf"   || arg == "\\textsf" ||
987                         arg == "\\textrm"   || arg == "\\textmd" ||
988                         arg == "\\textit"   || arg == "\\textsc" ||
989                         arg == "\\textsl"   || arg == "\\textup" ||
990                         arg == "\\texttt"   || arg == "\\textbb" ||
991                         arg == "\\textnormal";
992                 flag.enabled(currentMode() != TEXT_MODE || textarg);
993                 break;
994         }
995
996         case LFUN_INSERT_MATRIX:
997                 flag.enabled(currentMode() == MATH_MODE);
998                 break;
999         default:
1000                 ret = false;
1001                 break;
1002         }
1003         return ret;
1004 }
1005
1006
1007 void MathNestInset::edit(LCursor & cur, bool left)
1008 {
1009         cur.push(*this);
1010         cur.idx() = left ? 0 : cur.lastidx();
1011         cur.pos() = left ? 0 : cur.lastpos();
1012         cur.resetAnchor();
1013         //lyxerr << "MathNestInset::edit, cur:\n" << cur << endl;
1014 }
1015
1016
1017 InsetBase * MathNestInset::editXY(LCursor & cur, int x, int y)
1018 {
1019         int idx_min = 0;
1020         int dist_min = 1000000;
1021         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1022                 int const d = cell(i).dist(x, y);
1023                 if (d < dist_min) {
1024                         dist_min = d;
1025                         idx_min = i;
1026                 }
1027         }
1028         MathArray & ar = cell(idx_min);
1029         cur.push(*this);
1030         cur.idx() = idx_min;
1031         cur.pos() = ar.x2pos(x - ar.xo());
1032         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1033         if (dist_min == 0) {
1034                 // hit inside cell
1035                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1036                         if (ar[i]->covers(x, y))
1037                                 return ar[i].nucleus()->editXY(cur, x, y);
1038         }
1039         return this;
1040 }
1041
1042
1043 void MathNestInset::lfunMousePress(LCursor & cur, FuncRequest & cmd)
1044 {
1045         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1046         if (cmd.button() == mouse_button::button1) {
1047                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1048                 cur.resetAnchor();
1049                 cur.bv().cursor() = cur;
1050         }
1051
1052         if (cmd.button() == mouse_button::button2) {
1053                 cur.dispatch(FuncRequest(LFUN_PASTESELECTION));
1054         }
1055 }
1056
1057
1058 void MathNestInset::lfunMouseMotion(LCursor & cur, FuncRequest & cmd)
1059 {
1060         // only select with button 1
1061         if (cmd.button() == mouse_button::button1) {
1062                 LCursor & bvcur = cur.bv().cursor();
1063                 if (bvcur.anchor_.hasPart(cur)) {
1064                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1065                         bvcur.setCursor(cur);
1066                         bvcur.selection() = true;
1067                         //lyxerr << "MOTION " << bvcur << endl;
1068                 }
1069                 else {
1070                         cur.undispatched();
1071                 }
1072         }
1073 }
1074
1075
1076 void MathNestInset::lfunMouseRelease(LCursor & cur, FuncRequest & cmd)
1077 {
1078         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1079
1080         if (cmd.button() == mouse_button::button1) {
1081                 //cur.bv().stuffClipboard(cur.grabSelection());
1082                 return;
1083         }
1084
1085         if (cmd.button() == mouse_button::button2) {
1086                 MathArray ar;
1087                 asArray(cur.bv().getClipboard(), ar);
1088                 cur.clearSelection();
1089                 cur.setScreenPos(cmd.x, cmd.y);
1090                 cur.insert(ar);
1091                 cur.bv().update();
1092                 return;
1093         }
1094
1095         if (cmd.button() == mouse_button::button3) {
1096                 // try to dispatch to enclosed insets first
1097                 cur.bv().owner()->getDialogs().show("mathpanel");
1098                 return;
1099         }
1100
1101         cur.undispatched();
1102 }
1103
1104
1105 bool MathNestInset::interpret(LCursor & cur, char c)
1106 {
1107         //lyxerr << "interpret 2: '" << c << "'" << endl;
1108         cur.clearTargetX();
1109
1110         // handle macroMode
1111         if (cur.inMacroMode()) {
1112                 string name = cur.macroName();
1113
1114                 /// are we currently typing '#1' or '#2' or...?
1115                 if (name == "\\#") {
1116                         cur.backspace();
1117                         int n = c - '0';
1118                         if (n >= 1 && n <= 9)
1119                                 cur.insert(new MathMacroArgument(n));
1120                         return true;
1121                 }
1122
1123                 if (isalpha(c)) {
1124                         cur.activeMacro()->setName(name + c);
1125                         return true;
1126                 }
1127
1128                 // handle 'special char' macros
1129                 if (name == "\\") {
1130                         // remove the '\\'
1131                         if (c == '\\') {
1132                                 cur.backspace();
1133                                 if (currentMode() == MathInset::TEXT_MODE)
1134                                         cur.niceInsert(createMathInset("textbackslash"));
1135                                 else
1136                                         cur.niceInsert(createMathInset("backslash"));
1137                         } else if (c == '{') {
1138                                 cur.backspace();
1139                                 cur.niceInsert(MathAtom(new MathBraceInset));
1140                         } else if (c == '%') {
1141                                 cur.backspace();
1142                                 cur.niceInsert(MathAtom(new MathCommentInset));
1143                         } else if (c == '#') {
1144                                 BOOST_ASSERT(cur.activeMacro());
1145                                 cur.activeMacro()->setName(name + c);
1146                         } else {
1147                                 cur.backspace();
1148                                 cur.niceInsert(createMathInset(string(1, c)));
1149                         }
1150                         return true;
1151                 }
1152
1153                 // leave macro mode and try again if necessary
1154                 cur.macroModeClose();
1155                 if (c == '{')
1156                         cur.niceInsert(MathAtom(new MathBraceInset));
1157                 else if (c != ' ')
1158                         interpret(cur, c);
1159                 return true;
1160         }
1161
1162         // This is annoying as one has to press <space> far too often.
1163         // Disable it.
1164
1165 #if 0
1166                 // leave autocorrect mode if necessary
1167                 if (autocorrect() && c == ' ') {
1168                         autocorrect() = false;
1169                         return true;
1170                 }
1171 #endif
1172
1173         // just clear selection on pressing the space bar
1174         if (cur.selection() && c == ' ') {
1175                 cur.selection() = false;
1176                 return true;
1177         }
1178
1179         selClearOrDel(cur);
1180
1181         if (c == '\\') {
1182                 //lyxerr << "starting with macro" << endl;
1183                 cur.insert(MathAtom(new MathUnknownInset("\\", false)));
1184                 return true;
1185         }
1186
1187         if (c == '\n') {
1188                 if (currentMode() == MathInset::TEXT_MODE)
1189                         cur.insert(c);
1190                 return true;
1191         }
1192
1193         if (c == ' ') {
1194                 if (currentMode() == MathInset::TEXT_MODE) {
1195                         // insert spaces in text mode,
1196                         // but suppress direct insertion of two spaces in a row
1197                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1198                         // it is better than nothing...
1199                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ')
1200                                 cur.insert(c);
1201                         return true;
1202                 }
1203                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1204                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1205                         return true;
1206                 }
1207                 if (cur.popRight())
1208                         return true;
1209                 // if are at the very end, leave the formula
1210                 return cur.pos() != cur.lastpos();
1211         }
1212
1213         // These shouldn't work in text mode:
1214         if (currentMode() != MathInset::TEXT_MODE) {
1215                 if (c == '_') {
1216                         script(cur, false);
1217                         return true;
1218                 }
1219                 if (c == '^') {
1220                         script(cur, true);
1221                         return true;
1222                 }
1223                 if (c == '~') {
1224                         cur.niceInsert(createMathInset("sim"));
1225                         return true;
1226                 }
1227         }
1228
1229         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' || c == '%'
1230       || c == '_' || c == '^') {
1231                 cur.niceInsert(createMathInset(string(1, c)));
1232                 return true;
1233         }
1234
1235
1236         // try auto-correction
1237         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1238         //      return true;
1239
1240         // no special circumstances, so insert the character without any fuss
1241         cur.insert(c);
1242         cur.autocorrect() = true;
1243         return true;
1244 }
1245
1246
1247 bool MathNestInset::script(LCursor & cur, bool up)
1248 {
1249         // Hack to get \^ and \_ working
1250         lyxerr << "handling script: up: " << up << endl;
1251         if (cur.inMacroMode() && cur.macroName() == "\\") {
1252                 if (up)
1253                         cur.niceInsert(createMathInset("mathcircumflex"));
1254                 else
1255                         interpret(cur, '_');
1256                 return true;
1257         }
1258
1259         cur.macroModeClose();
1260         string safe = grabAndEraseSelection(cur);
1261         if (asScriptInset() && cur.idx() == 0) {
1262                 // we are in a nucleus of a script inset, move to _our_ script
1263                 MathScriptInset * inset = asScriptInset();
1264                 lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1265                 inset->ensure(up);
1266                 cur.idx() = inset->idxOfScript(up);
1267                 cur.pos() = 0;
1268         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1269                 --cur.pos();
1270                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1271                 cur.push(*inset);
1272                 cur.idx() = inset->idxOfScript(up);
1273                 cur.pos() = cur.lastpos();
1274         } else {
1275                 // convert the thing to our left to a scriptinset or create a new
1276                 // one if in the very first position of the array
1277                 if (cur.pos() == 0) {
1278                         //lyxerr << "new scriptinset" << endl;
1279                         cur.insert(new MathScriptInset(up));
1280                 } else {
1281                         //lyxerr << "converting prev atom " << endl;
1282                         cur.prevAtom() = MathAtom(new MathScriptInset(cur.prevAtom(), up));
1283                 }
1284                 --cur.pos();
1285                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1286                 cur.push(*inset);
1287                 cur.idx() = 1;
1288                 cur.pos() = 0;
1289         }
1290         //lyxerr << "pasting 1: safe:\n" << safe << endl;
1291         cur.paste(safe);
1292         cur.resetAnchor();
1293         //lyxerr << "pasting 2: safe:\n" << safe << endl;
1294         return true;
1295 }