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