]> git.lyx.org Git - lyx.git/blob - src/mathed/math_nestinset.C
8f3f8cfb6c44392c9739a83f01c67ca5234c03f5
[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                 cur.selHandle(cmd.action == LFUN_UPSEL);
500                 if (!cur.up())
501                         cmd = FuncRequest(LFUN_FINISHED_UP);
502                 // fixes bug 1598. Please check!
503                 cur.normalize();
504                 break;
505
506         case LFUN_DOWNSEL:
507         case LFUN_DOWN:
508                 cur.selHandle(cmd.action == LFUN_DOWNSEL);
509                 if (!cur.down())
510                         cmd = FuncRequest(LFUN_FINISHED_DOWN);
511                 // fixes bug 1598. Please check!
512                 cur.normalize();
513                 break;
514
515         case LFUN_MOUSE_DOUBLE:
516         case LFUN_MOUSE_TRIPLE:
517         case LFUN_WORDSEL:
518                 cur.pos() = 0;
519                 cur.idx() = 0;
520                 cur.resetAnchor();
521                 cur.selection() = true;
522                 cur.pos() = cur.lastpos();
523                 cur.idx() = cur.lastidx();
524                 break;
525
526         case LFUN_UP_PARAGRAPHSEL:
527         case LFUN_UP_PARAGRAPH:
528         case LFUN_DOWN_PARAGRAPHSEL:
529         case LFUN_DOWN_PARAGRAPH:
530                 break;
531
532         case LFUN_HOMESEL:
533         case LFUN_HOME:
534         case LFUN_WORDLEFTSEL:
535         case LFUN_WORDLEFT:
536                 cur.selHandle(cmd.action == LFUN_WORDLEFTSEL || cmd.action == LFUN_HOMESEL);
537                 cur.macroModeClose();
538                 if (cur.pos() != 0) {
539                         cur.pos() = 0;
540                 } else if (cur.col() != 0) {
541                         cur.idx() -= cur.col();
542                         cur.pos() = 0;
543                 } else if (cur.idx() != 0) {
544                         cur.idx() = 0;
545                         cur.pos() = 0;
546                 } else {
547                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
548                 }
549                 break;
550
551         case LFUN_WORDRIGHTSEL:
552         case LFUN_WORDRIGHT:
553         case LFUN_ENDSEL:
554         case LFUN_END:
555                 cur.selHandle(cmd.action == LFUN_WORDRIGHTSEL || cmd.action == LFUN_ENDSEL);
556                 cur.macroModeClose();
557                 cur.clearTargetX();
558                 if (cur.pos() != cur.lastpos()) {
559                         cur.pos() = cur.lastpos();
560                 } else if (ncols() && (cur.col() != cur.lastcol())) {
561                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
562                         cur.pos() = cur.lastpos();
563                 } else if (cur.idx() != cur.lastidx()) {
564                         cur.idx() = cur.lastidx();
565                         cur.pos() = cur.lastpos();
566                 } else {
567                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
568                 }
569                 break;
570
571         case LFUN_PRIORSEL:
572         case LFUN_PRIOR:
573                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
574                 break;
575
576         case LFUN_NEXTSEL:
577         case LFUN_NEXT:
578                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
579                 break;
580
581         case LFUN_CELL_FORWARD:
582                 cur.inset().idxNext(cur);
583                 break;
584
585         case LFUN_CELL_BACKWARD:
586                 cur.inset().idxPrev(cur);
587                 break;
588
589         case LFUN_DELETE_WORD_BACKWARD:
590         case LFUN_BACKSPACE:
591                 recordUndo(cur, Undo::ATOMIC);
592                 cur.backspace();
593                 break;
594
595         case LFUN_DELETE_WORD_FORWARD:
596         case LFUN_DELETE:
597                 recordUndo(cur);
598                 cur.erase();
599                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
600                 break;
601
602         case LFUN_ESCAPE:
603                 if (cur.selection())
604                         cur.clearSelection();
605                 else
606                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
607                 break;
608
609         case LFUN_INSET_TOGGLE:
610                 recordUndo(cur);
611                 //lockToggle();
612                 if (cur.pos() != cur.lastpos()) {
613                         // toggle previous inset ...
614                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
615                 } else if (cur.popLeft() && cur.pos() != cur.lastpos()) {
616                         // ... or enclosing inset if we are in the last inset position
617                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
618                         ++cur.pos();
619                 }
620                 break;
621
622         case LFUN_SELFINSERT:
623                 recordUndo(cur);
624                 if (cmd.argument.size() != 1) {
625                         cur.insert(cmd.argument);
626                         break;
627                 }
628                 if (!interpret(cur, cmd.argument[0]))
629                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
630                 break;
631
632         //case LFUN_GETXY:
633         //      sprintf(dispatch_buffer, "%d %d",);
634         //      break;
635
636         case LFUN_SETXY: {
637                 lyxerr << "LFUN_SETXY broken!" << endl;
638                 int x = 0;
639                 int y = 0;
640                 istringstream is(cmd.argument);
641                 is >> x >> y;
642                 cur.setScreenPos(x, y);
643                 break;
644         }
645
646         // Special casing for superscript in case of LyX handling
647         // dead-keys:
648         case LFUN_CIRCUMFLEX:
649                 if (cmd.argument.empty()) {
650                         // do superscript if LyX handles
651                         // deadkeys
652                         recordUndo(cur, Undo::ATOMIC);
653                         script(cur, true);
654                 }
655                 break;
656
657         case LFUN_UMLAUT:
658         case LFUN_ACUTE:
659         case LFUN_GRAVE:
660         case LFUN_BREVE:
661         case LFUN_DOT:
662         case LFUN_MACRON:
663         case LFUN_CARON:
664         case LFUN_TILDE:
665         case LFUN_CEDILLA:
666         case LFUN_CIRCLE:
667         case LFUN_UNDERDOT:
668         case LFUN_TIE:
669         case LFUN_OGONEK:
670         case LFUN_HUNG_UMLAUT:
671                 break;
672
673         //  Math fonts
674         case LFUN_FREEFONT_APPLY:
675         case LFUN_FREEFONT_UPDATE:
676                 handleFont2(cur, cmd.argument);
677                 break;
678
679         case LFUN_BOLD:
680                 handleFont(cur, cmd.argument, "mathbf");
681                 break;
682         case LFUN_SANS:
683                 handleFont(cur, cmd.argument, "mathsf");
684                 break;
685         case LFUN_EMPH:
686                 handleFont(cur, cmd.argument, "mathcal");
687                 break;
688         case LFUN_ROMAN:
689                 handleFont(cur, cmd.argument, "mathrm");
690                 break;
691         case LFUN_CODE:
692                 handleFont(cur, cmd.argument, "texttt");
693                 break;
694         case LFUN_FRAK:
695                 handleFont(cur, cmd.argument, "mathfrak");
696                 break;
697         case LFUN_ITAL:
698                 handleFont(cur, cmd.argument, "mathit");
699                 break;
700         case LFUN_NOUN:
701                 handleFont(cur, cmd.argument, "mathbb");
702                 break;
703         //case LFUN_FREEFONT_APPLY:
704                 handleFont(cur, cmd.argument, "textrm");
705                 break;
706         case LFUN_DEFAULT:
707                 handleFont(cur, cmd.argument, "textnormal");
708                 break;
709
710         case LFUN_MATH_MODE:
711 #if 1
712                 // ignore math-mode on when already in math mode
713                 if (currentMode() == InsetBase::MATH_MODE && cmd.argument == "on")
714                         break;
715                 cur.macroModeClose();
716                 selClearOrDel(cur);
717                 //cur.plainInsert(MathAtom(new MathMBoxInset(cur.bv())));
718                 cur.plainInsert(MathAtom(new MathBoxInset("mbox")));
719                 cur.posLeft();
720                 cur.pushLeft(*cur.nextInset());
721 #else
722                 if (currentMode() == InsetBase::TEXT_MODE) {
723                         cur.niceInsert(MathAtom(new MathHullInset("simple")));
724                         cur.message(_("create new math text environment ($...$)"));
725                 } else {
726                         handleFont(cur, cmd.argument, "textrm");
727                         cur.message(_("entered math text mode (textrm)"));
728                 }
729 #endif
730                 break;
731
732         case LFUN_MATH_SIZE:
733 #if 0
734                 recordUndo(cur);
735                 cur.setSize(arg);
736 #endif
737                 break;
738
739         case LFUN_INSERT_MATRIX: {
740                 recordUndo(cur, Undo::ATOMIC);
741                 unsigned int m = 1;
742                 unsigned int n = 1;
743                 string v_align;
744                 string h_align;
745                 istringstream is(cmd.argument);
746                 is >> m >> n >> v_align >> h_align;
747                 if (m < 1)
748                         m = 1;
749                 if (n < 1)
750                         n = 1;
751                 v_align += 'c';
752                 cur.niceInsert(
753                         MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
754                 break;
755         }
756
757         case LFUN_MATH_DELIM: {
758                 lyxerr << "MathNestInset::LFUN_MATH_DELIM" << endl;
759                 string ls;
760                 string rs = lyx::support::split(cmd.argument, ls, ' ');
761                 // Reasonable default values
762                 if (ls.empty())
763                         ls = '(';
764                 if (rs.empty())
765                         rs = ')';
766                 recordUndo(cur, Undo::ATOMIC);
767                 cur.handleNest(MathAtom(new MathDelimInset(ls, rs)));
768                 break;
769         }
770
771         case LFUN_SPACE_INSERT:
772         case LFUN_MATH_SPACE:
773                 recordUndo(cur, Undo::ATOMIC);
774                 cur.insert(MathAtom(new MathSpaceInset(",")));
775                 break;
776
777         case LFUN_INSET_ERT:
778                 // interpret this as if a backslash was typed
779                 recordUndo(cur, Undo::ATOMIC);
780                 interpret(cur, '\\');
781                 break;
782
783         case LFUN_SUBSCRIPT:
784                 // interpret this as if a _ was typed
785                 recordUndo(cur, Undo::ATOMIC);
786                 interpret(cur, '_');
787                 break;
788
789         case LFUN_SUPERSCRIPT:
790                 // interpret this as if a ^ was typed
791                 recordUndo(cur, Undo::ATOMIC);
792                 interpret(cur, '^');
793                 break;
794
795 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
796 // handling such that "self-insert" works on "arbitrary stuff" too, and
797 // math-insert only handles special math things like "matrix".
798         case LFUN_INSERT_MATH: {
799                 recordUndo(cur, Undo::ATOMIC);
800                 MathArray ar;
801                 asArray(cmd.argument, ar);
802                 if (ar.size() == 1 && (ar[0].nucleus()->asNestInset())) {
803                         cur.handleNest(ar[0]);
804                 } else
805                         cur.niceInsert(cmd.argument);
806                 break;
807                 }
808
809         case LFUN_DIALOG_SHOW_NEW_INSET: {
810                 string const & name = cmd.argument;
811                 string data;
812 #if 0
813                 if (name == "ref") {
814                         RefInset tmp(name);
815                         data = tmp.createDialogStr(name);
816                 }
817 #endif
818                 cur.bv().owner()->getDialogs().show(name, data, 0);
819                 break;
820         }
821
822         case LFUN_INSET_APPLY: {
823                 string const name = cmd.getArg(0);
824                 InsetBase * base = cur.bv().owner()->getDialogs().getOpenInset(name);
825
826                 if (base) {
827                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument);
828                         base->dispatch(cur, fr);
829                         break;
830                 }
831                 MathArray ar;
832                 if (createMathInset_fromDialogStr(cmd.argument, ar)) {
833                         cur.insert(ar);
834                         break;
835                 }
836                 cur.undispatched();
837                 break;
838         }
839
840         default:
841                 MathDimInset::doDispatch(cur, cmd);
842                 break;
843         }
844 }
845
846
847 bool MathNestInset::getStatus(LCursor & /*cur*/, FuncRequest const & cmd,
848                 FuncStatus & flag) const
849 {
850         // the font related toggles
851         //string tc = "mathnormal";
852         bool ret = true;
853         switch (cmd.action) {
854 #if 0
855         case LFUN_TABULAR_FEATURE:
856                 // FIXME: check temporarily disabled
857                 // valign code
858                 char align = mathcursor::valign();
859                 if (align == '\0') {
860                         enable = false;
861                         break;
862                 }
863                 if (cmd.argument.empty()) {
864                         flag.clear();
865                         break;
866                 }
867                 if (!contains("tcb", cmd.argument[0])) {
868                         enable = false;
869                         break;
870                 }
871                 flag.setOnOff(cmd.argument[0] == align);
872                 break;
873         case LFUN_BOLD:
874                 flag.setOnOff(tc == "mathbf");
875                 break;
876         case LFUN_SANS:
877                 flag.setOnOff(tc == "mathsf");
878                 break;
879         case LFUN_EMPH:
880                 flag.setOnOff(tc == "mathcal");
881                 break;
882         case LFUN_ROMAN:
883                 flag.setOnOff(tc == "mathrm");
884                 break;
885         case LFUN_CODE:
886                 flag.setOnOff(tc == "mathtt");
887                 break;
888         case LFUN_NOUN:
889                 flag.setOnOff(tc == "mathbb");
890                 break;
891         case LFUN_DEFAULT:
892                 flag.setOnOff(tc == "mathnormal");
893                 break;
894 #endif
895         case LFUN_MATH_MUTATE:
896                 //flag.setOnOff(mathcursor::formula()->hullType() == cmd.argument);
897                 flag.setOnOff(false);
898                 break;
899
900         // we just need to be in math mode to enable that
901         case LFUN_MATH_SIZE:
902         case LFUN_MATH_SPACE:
903         case LFUN_MATH_LIMITS:
904         case LFUN_MATH_NONUMBER:
905         case LFUN_MATH_NUMBER:
906         case LFUN_MATH_EXTERN:
907                 flag.enabled(true);
908                 break;
909
910         default:
911                 ret = false;
912                 break;
913         }
914         return ret;
915 }
916
917
918 void MathNestInset::edit(LCursor & cur, bool left)
919 {
920         cur.push(*this);
921         cur.idx() = left ? 0 : cur.lastidx();
922         cur.pos() = left ? 0 : cur.lastpos();
923         cur.resetAnchor();
924         lyxerr << "MathNestInset::edit, cur:\n" << cur << endl;
925 }
926
927
928 InsetBase * MathNestInset::editXY(LCursor & cur, int x, int y) const
929 {
930         int idx_min = 0;
931         int dist_min = 1000000;
932         for (idx_type i = 0; i < nargs(); ++i) {
933                 int d = cell(i).dist(x, y);
934                 if (d < dist_min) {
935                         dist_min = d;
936                         idx_min = i;
937                 }
938         }
939         MathArray const & ar = cell(idx_min);
940         cur.push(const_cast<MathNestInset&>(*this));
941         cur.idx() = idx_min;
942         cur.pos() = ar.x2pos(x - ar.xo());
943         lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
944         if (dist_min == 0) {
945                 // hit inside cell
946                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
947                         if (ar[i]->covers(x, y))
948                                 return ar[i].nucleus()->editXY(cur, x, y);
949         }
950         return const_cast<MathNestInset*>(this);
951 }
952
953
954 void MathNestInset::lfunMousePress(LCursor & cur, FuncRequest & cmd)
955 {
956         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
957         if (cmd.button() == mouse_button::button1) {
958                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
959                 cur.resetAnchor();
960                 cur.bv().cursor() = cur;
961         }
962
963         if (cmd.button() == mouse_button::button2) {
964                 cur.dispatch(FuncRequest(LFUN_PASTESELECTION));
965         }
966 }
967
968
969 void MathNestInset::lfunMouseMotion(LCursor & cur, FuncRequest & cmd)
970 {
971         // only select with button 1
972         if (cmd.button() == mouse_button::button1) {
973                 LCursor & bvcur = cur.bv().cursor();
974                 if (bvcur.anchor_.hasPart(cur)) {
975                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
976                         bvcur.setCursor(cur);
977                         bvcur.selection() = true;
978                         //lyxerr << "MOTION " << bvcur << endl;
979                 }
980                 else {
981                         cur.undispatched();
982                 }
983         }
984 }
985
986
987 void MathNestInset::lfunMouseRelease(LCursor & cur, FuncRequest & cmd)
988 {
989         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
990
991         if (cmd.button() == mouse_button::button1) {
992                 //cur.bv().stuffClipboard(cur.grabSelection());
993                 return;
994         }
995
996         if (cmd.button() == mouse_button::button2) {
997                 MathArray ar;
998                 asArray(cur.bv().getClipboard(), ar);
999                 cur.clearSelection();
1000                 cur.setScreenPos(cmd.x, cmd.y);
1001                 cur.insert(ar);
1002                 cur.bv().update();
1003                 return;
1004         }
1005
1006         if (cmd.button() == mouse_button::button3) {
1007                 // try to dispatch to enclosed insets first
1008                 cur.bv().owner()->getDialogs().show("mathpanel");
1009                 return;
1010         }
1011
1012         cur.undispatched();
1013 }
1014
1015
1016 bool MathNestInset::interpret(LCursor & cur, char c)
1017 {
1018         lyxerr << "interpret 2: '" << c << "'" << endl;
1019         cur.clearTargetX();
1020
1021         // handle macroMode
1022         if (cur.inMacroMode()) {
1023                 string name = cur.macroName();
1024
1025                 /// are we currently typing '#1' or '#2' or...?
1026                 if (name == "\\#") {
1027                         cur.backspace();
1028                         int n = c - '0';
1029                         if (n >= 1 && n <= 9)
1030                                 cur.insert(new MathMacroArgument(n));
1031                         return true;
1032                 }
1033
1034                 if (isalpha(c)) {
1035                         cur.activeMacro()->setName(name + c);
1036                         return true;
1037                 }
1038
1039                 // handle 'special char' macros
1040                 if (name == "\\") {
1041                         // remove the '\\'
1042                         if (c == '\\') {
1043                                 cur.backspace();
1044                                 if (currentMode() == MathInset::TEXT_MODE)
1045                                         cur.niceInsert(createMathInset("textbackslash"));
1046                                 else
1047                                         cur.niceInsert(createMathInset("backslash"));
1048                         } else if (c == '{') {
1049                                 cur.backspace();
1050                                 cur.niceInsert(MathAtom(new MathBraceInset));
1051                         } else if (c == '%') {
1052                                 cur.backspace();
1053                                 cur.niceInsert(MathAtom(new MathCommentInset));
1054                         } else if (c == '#') {
1055                                 BOOST_ASSERT(cur.activeMacro());
1056                                 cur.activeMacro()->setName(name + c);
1057                         } else {
1058                                 cur.backspace();
1059                                 cur.niceInsert(createMathInset(string(1, c)));
1060                         }
1061                         return true;
1062                 }
1063
1064                 // leave macro mode and try again if necessary
1065                 cur.macroModeClose();
1066                 if (c == '{')
1067                         cur.niceInsert(MathAtom(new MathBraceInset));
1068                 else if (c != ' ')
1069                         interpret(cur, c);
1070                 return true;
1071         }
1072
1073         // This is annoying as one has to press <space> far too often.
1074         // Disable it.
1075
1076 #if 0
1077                 // leave autocorrect mode if necessary
1078                 if (autocorrect() && c == ' ') {
1079                         autocorrect() = false;
1080                         return true;
1081                 }
1082 #endif
1083
1084         // just clear selection on pressing the space bar
1085         if (cur.selection() && c == ' ') {
1086                 cur.selection() = false;
1087                 return true;
1088         }
1089
1090         selClearOrDel(cur);
1091
1092         if (c == '\\') {
1093                 //lyxerr << "starting with macro" << endl;
1094                 cur.insert(MathAtom(new MathUnknownInset("\\", false)));
1095                 return true;
1096         }
1097
1098         if (c == '\n') {
1099                 if (currentMode() == MathInset::TEXT_MODE)
1100                         cur.insert(c);
1101                 return true;
1102         }
1103
1104         if (c == ' ') {
1105                 if (currentMode() == MathInset::TEXT_MODE) {
1106                         // insert spaces in text mode,
1107                         // but suppress direct insertion of two spaces in a row
1108                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1109                         // it is better than nothing...
1110                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ')
1111                                 cur.insert(c);
1112                         return true;
1113                 }
1114                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1115                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1116                         return true;
1117                 }
1118                 if (cur.popRight())
1119                         return true;
1120                 // if are at the very end, leave the formula
1121                 return cur.pos() != cur.lastpos();
1122         }
1123
1124         if (c == '_') {
1125                 script(cur, false);
1126                 return true;
1127         }
1128
1129         if (c == '^') {
1130                 script(cur, true);
1131                 return true;
1132         }
1133
1134         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' || c == '%') {
1135                 cur.niceInsert(createMathInset(string(1, c)));
1136                 return true;
1137         }
1138
1139         if (c == '~') {
1140                 cur.niceInsert(createMathInset("sim"));
1141                 return true;
1142         }
1143
1144         // try auto-correction
1145         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1146         //      return true;
1147
1148         // no special circumstances, so insert the character without any fuss
1149         cur.insert(c);
1150         cur.autocorrect() = true;
1151         return true;
1152 }
1153
1154
1155 bool MathNestInset::script(LCursor & cur, bool up)
1156 {
1157         // Hack to get \^ and \_ working
1158         lyxerr << "handling script: up: " << up << endl;
1159         if (cur.inMacroMode() && cur.macroName() == "\\") {
1160                 if (up)
1161                         cur.niceInsert(createMathInset("mathcircumflex"));
1162                 else
1163                         interpret(cur, '_');
1164                 return true;
1165         }
1166
1167         cur.macroModeClose();
1168         string safe = grabAndEraseSelection(cur);
1169         if (asScriptInset() && cur.idx() == 0) {
1170                 // we are in a nucleus of a script inset, move to _our_ script
1171                 MathScriptInset * inset = asScriptInset();
1172                 lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1173                 inset->ensure(up);
1174                 cur.idx() = inset->idxOfScript(up);
1175                 cur.pos() = 0;
1176         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1177                 --cur.pos();
1178                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1179                 cur.push(*inset);
1180                 cur.idx() = inset->idxOfScript(up);
1181                 cur.pos() = cur.lastpos();
1182         } else {
1183                 // convert the thing to our left to a scriptinset or create a new
1184                 // one if in the very first position of the array
1185                 if (cur.pos() == 0) {
1186                         lyxerr << "new scriptinset" << endl;
1187                         cur.insert(new MathScriptInset(up));
1188                 } else {
1189                         lyxerr << "converting prev atom " << endl;
1190                         cur.prevAtom() = MathAtom(new MathScriptInset(cur.prevAtom(), up));
1191                 }
1192                 --cur.pos();
1193                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1194                 cur.push(*inset);
1195                 cur.idx() = 1;
1196                 cur.pos() = 0;
1197         }
1198         lyxerr << "pasting 1: safe:\n" << safe << endl;
1199         cur.paste(safe);
1200         cur.resetAnchor();
1201         lyxerr << "pasting 2: safe:\n" << safe << endl;
1202         return true;
1203 }