]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathGrid.C
make it compile again (hopefully)
[lyx.git] / src / mathed / InsetMathGrid.C
1 /**
2  * \file InsetMathGrid.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 "InsetMathGrid.h"
14 #include "MathData.h"
15 #include "MathMLStream.h"
16 #include "MathStream.h"
17
18 #include "BufferView.h"
19 #include "CutAndPaste.h"
20 #include "FuncStatus.h"
21 #include "LColor.h"
22 #include "cursor.h"
23 #include "debug.h"
24 #include "funcrequest.h"
25 #include "gettext.h"
26 #include "undo.h"
27
28 #include "frontends/Painter.h"
29
30 #include "insets/mailinset.h"
31
32 #include "support/lstrings.h"
33
34 #include <sstream>
35
36 using lyx::support::bformat;
37
38 using std::endl;
39 using std::max;
40 using std::min;
41 using std::swap;
42
43 using std::string;
44 using std::auto_ptr;
45 using std::istream;
46 using std::istringstream;
47 using std::vector;
48
49
50 class GridInsetMailer : public MailInset {
51 public:
52         GridInsetMailer(InsetMathGrid & inset) : inset_(inset) {}
53         ///
54         virtual string const & name() const
55         {
56                 static string const theName = "tabular";
57                 return theName;
58         }
59         ///
60         virtual string const inset2string(Buffer const &) const
61         {
62                 lyx::odocstringstream data;
63                 //data << name() << " active_cell " << inset.getActCell() << '\n';
64                 data << lyx::from_utf8(name()) << " active_cell " << 0 << '\n';
65                 WriteStream ws(data);
66                 inset_.write(ws);
67                 return lyx::to_utf8(data.str());
68         }
69
70 protected:
71         InsetBase & inset() const { return inset_; }
72         InsetMathGrid & inset_;
73 };
74
75
76 void mathed_parse_normal(InsetMathGrid &, string const & argument);
77
78 namespace {
79
80 string verboseHLine(int n)
81 {
82         string res;
83         for (int i = 0; i < n; ++i)
84                 res += "\\hline";
85         if (n)
86                 res += ' ';
87         return res;
88 }
89
90
91 int extractInt(istream & is)
92 {
93         int num = 1;
94         is >> num;
95         return (num == 0) ? 1 : num;
96 }
97
98 }
99
100
101 //////////////////////////////////////////////////////////////
102
103
104 InsetMathGrid::CellInfo::CellInfo()
105         : dummy_(false)
106 {}
107
108
109
110
111 //////////////////////////////////////////////////////////////
112
113
114 InsetMathGrid::RowInfo::RowInfo()
115         : lines_(0), skip_(0)
116 {}
117
118
119
120 int InsetMathGrid::RowInfo::skipPixels() const
121 {
122         return crskip_.inBP();
123 }
124
125
126
127 //////////////////////////////////////////////////////////////
128
129
130 InsetMathGrid::ColInfo::ColInfo()
131         : align_('c'), lines_(0)
132 {}
133
134
135 //////////////////////////////////////////////////////////////
136
137
138 InsetMathGrid::InsetMathGrid(char v, string const & h)
139         : InsetMathNest(guessColumns(h)),
140           rowinfo_(2),
141           colinfo_(guessColumns(h) + 1),
142           cellinfo_(1 * guessColumns(h))
143 {
144         setDefaults();
145         valign(v);
146         halign(h);
147         //lyxerr << "created grid with " << ncols() << " columns" << endl;
148 }
149
150
151 InsetMathGrid::InsetMathGrid()
152         : InsetMathNest(1),
153           rowinfo_(1 + 1),
154                 colinfo_(1 + 1),
155                 cellinfo_(1),
156                 v_align_('c')
157 {
158         setDefaults();
159 }
160
161
162 InsetMathGrid::InsetMathGrid(col_type m, row_type n)
163         : InsetMathNest(m * n),
164           rowinfo_(n + 1),
165                 colinfo_(m + 1),
166                 cellinfo_(m * n),
167                 v_align_('c')
168 {
169         setDefaults();
170 }
171
172
173 InsetMathGrid::InsetMathGrid(col_type m, row_type n, char v, string const & h)
174         : InsetMathNest(m * n),
175           rowinfo_(n + 1),
176           colinfo_(m + 1),
177                 cellinfo_(m * n),
178                 v_align_(v)
179 {
180         setDefaults();
181         valign(v);
182         halign(h);
183 }
184
185
186 InsetMathGrid::~InsetMathGrid()
187 {
188         GridInsetMailer mailer(*this);
189         mailer.hideDialog();
190 }
191
192
193 auto_ptr<InsetBase> InsetMathGrid::doClone() const
194 {
195         return auto_ptr<InsetBase>(new InsetMathGrid(*this));
196 }
197
198
199 InsetMath::idx_type InsetMathGrid::index(row_type row, col_type col) const
200 {
201         return col + ncols() * row;
202 }
203
204
205 void InsetMathGrid::setDefaults()
206 {
207         if (ncols() <= 0)
208                 lyxerr << "positive number of columns expected" << endl;
209         //if (nrows() <= 0)
210         //      lyxerr << "positive number of rows expected" << endl;
211         for (col_type col = 0; col < ncols(); ++col) {
212                 colinfo_[col].align_ = defaultColAlign(col);
213                 colinfo_[col].skip_  = defaultColSpace(col);
214         }
215 }
216
217
218 void InsetMathGrid::halign(string const & hh)
219 {
220         col_type col = 0;
221         for (string::const_iterator it = hh.begin(); it != hh.end(); ++it) {
222                 char c = *it;
223                 if (c == '|') {
224                         colinfo_[col].lines_++;
225                 } else if (col >= ncols()) {
226                         // Only '|' is allowed in the last dummy column
227                         break;
228                 } else if (c == 'c' || c == 'l' || c == 'r') {
229                         colinfo_[col].align_ = c;
230                         ++col;
231                         colinfo_[col].lines_ = 0;
232                 } else {
233                         lyxerr << "unknown column separator: '" << c << "'" << endl;
234                 }
235         }
236
237 /*
238         col_type n = hh.size();
239         if (n > ncols())
240                 n = ncols();
241         for (col_type col = 0; col < n; ++col)
242                 colinfo_[col].align_ = hh[col];
243 */
244 }
245
246
247 InsetMathGrid::col_type InsetMathGrid::guessColumns(string const & hh) const
248 {
249         col_type col = 0;
250         for (string::const_iterator it = hh.begin(); it != hh.end(); ++it)
251                 if (*it == 'c' || *it == 'l' || *it == 'r')
252                         ++col;
253         // let's have at least one column, even if we did not recognize its
254         // alignment
255         if (col == 0)
256                 col = 1;
257         return col;
258 }
259
260
261 void InsetMathGrid::halign(char h, col_type col)
262 {
263         colinfo_[col].align_ = h;
264 }
265
266
267 char InsetMathGrid::halign(col_type col) const
268 {
269         return colinfo_[col].align_;
270 }
271
272
273 string InsetMathGrid::halign() const
274 {
275         string res;
276         for (col_type col = 0; col < ncols(); ++col) {
277                 res += string(colinfo_[col].lines_, '|');
278                 res += colinfo_[col].align_;
279         }
280         return res + string(colinfo_[ncols()].lines_, '|');
281 }
282
283
284 void InsetMathGrid::valign(char c)
285 {
286         v_align_ = c;
287 }
288
289
290 char InsetMathGrid::valign() const
291 {
292         return v_align_;
293 }
294
295
296 InsetMathGrid::col_type InsetMathGrid::ncols() const
297 {
298         return colinfo_.size() - 1;
299 }
300
301
302 InsetMathGrid::row_type InsetMathGrid::nrows() const
303 {
304         return rowinfo_.size() - 1;
305 }
306
307
308 InsetMathGrid::col_type InsetMathGrid::col(idx_type idx) const
309 {
310         return idx % ncols();
311 }
312
313
314 InsetMathGrid::row_type InsetMathGrid::row(idx_type idx) const
315 {
316         return idx / ncols();
317 }
318
319
320 void InsetMathGrid::vcrskip(LyXLength const & crskip, row_type row)
321 {
322         rowinfo_[row].crskip_ = crskip;
323 }
324
325
326 LyXLength InsetMathGrid::vcrskip(row_type row) const
327 {
328         return rowinfo_[row].crskip_;
329 }
330
331
332 void InsetMathGrid::metrics(MetricsInfo & mi) const
333 {
334         // let the cells adjust themselves
335         InsetMathNest::metrics(mi);
336
337         // compute absolute sizes of vertical structure
338         for (row_type row = 0; row < nrows(); ++row) {
339                 int asc  = 0;
340                 int desc = 0;
341                 for (col_type col = 0; col < ncols(); ++col) {
342                         MathArray const & c = cell(index(row, col));
343                         asc  = max(asc,  c.ascent());
344                         desc = max(desc, c.descent());
345                 }
346                 rowinfo_[row].ascent_  = asc;
347                 rowinfo_[row].descent_ = desc;
348         }
349         rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
350         rowinfo_[nrows()].ascent_  = 0;
351         rowinfo_[nrows()].descent_ = 0;
352
353         // compute vertical offsets
354         rowinfo_[0].offset_ = 0;
355         for (row_type row = 1; row <= nrows(); ++row) {
356                 rowinfo_[row].offset_  =
357                         rowinfo_[row - 1].offset_  +
358                         rowinfo_[row - 1].descent_ +
359                         rowinfo_[row - 1].skipPixels() +
360                         rowsep() +
361                         rowinfo_[row].lines_ * hlinesep() +
362                         rowinfo_[row].ascent_;
363         }
364
365         // adjust vertical offset
366         int h = 0;
367         switch (v_align_) {
368                 case 't':
369                         h = 0;
370                         break;
371                 case 'b':
372                         h = rowinfo_[nrows() - 1].offset_;
373                         break;
374                 default:
375                         h = rowinfo_[nrows() - 1].offset_ / 2;
376         }
377         for (row_type row = 0; row <= nrows(); ++row)
378                 rowinfo_[row].offset_ -= h;
379
380
381         // compute absolute sizes of horizontal structure
382         for (col_type col = 0; col < ncols(); ++col) {
383                 int wid = 0;
384                 for (row_type row = 0; row < nrows(); ++row)
385                         wid = max(wid, cell(index(row, col)).width());
386                 colinfo_[col].width_ = wid;
387         }
388         colinfo_[ncols()].width_  = 0;
389
390         // compute horizontal offsets
391         colinfo_[0].offset_ = border();
392         for (col_type col = 1; col <= ncols(); ++col) {
393                 colinfo_[col].offset_ =
394                         colinfo_[col - 1].offset_ +
395                         colinfo_[col - 1].width_ +
396                         colinfo_[col - 1].skip_ +
397                         colsep() +
398                         colinfo_[col].lines_ * vlinesep();
399         }
400
401
402         dim_.wid   =   colinfo_[ncols() - 1].offset_
403                        + colinfo_[ncols() - 1].width_
404                  + vlinesep() * colinfo_[ncols()].lines_
405                        + border();
406
407         dim_.asc  = - rowinfo_[0].offset_
408                        + rowinfo_[0].ascent_
409                  + hlinesep() * rowinfo_[0].lines_
410                        + border();
411
412         dim_.des =   rowinfo_[nrows() - 1].offset_
413                        + rowinfo_[nrows() - 1].descent_
414                  + hlinesep() * rowinfo_[nrows()].lines_
415                        + border();
416
417
418 /*
419         // Increase ws_[i] for 'R' columns (except the first one)
420         for (int i = 1; i < nc_; ++i)
421                 if (align_[i] == 'R')
422                         ws_[i] += 10 * df_width;
423         // Increase ws_[i] for 'C' column
424         if (align_[0] == 'C')
425                 if (ws_[0] < 7 * workwidth / 8)
426                         ws_[0] = 7 * workwidth / 8;
427
428         // Adjust local tabs
429         width = colsep();
430         for (cxrow = row_.begin(); cxrow; ++cxrow) {
431                 int rg = COLSEP;
432                 int lf = 0;
433                 for (int i = 0; i < nc_; ++i) {
434                         bool isvoid = false;
435                         if (cxrow->getTab(i) <= 0) {
436                                 cxrow->setTab(i, df_width);
437                                 isvoid = true;
438                         }
439                         switch (align_[i]) {
440                         case 'l':
441                                 lf = 0;
442                                 break;
443                         case 'c':
444                                 lf = (ws_[i] - cxrow->getTab(i))/2;
445                                 break;
446                         case 'r':
447                         case 'R':
448                                 lf = ws_[i] - cxrow->getTab(i);
449                                 break;
450                         case 'C':
451                                 if (cxrow == row_.begin())
452                                         lf = 0;
453                                 else if (cxrow.is_last())
454                                         lf = ws_[i] - cxrow->getTab(i);
455                                 else
456                                         lf = (ws_[i] - cxrow->getTab(i))/2;
457                                 break;
458                         }
459                         int const ww = (isvoid) ? lf : lf + cxrow->getTab(i);
460                         cxrow->setTab(i, lf + rg);
461                         rg = ws_[i] - ww + colsep();
462                         if (cxrow == row_.begin())
463                                 width += ws_[i] + colsep();
464                 }
465                 cxrow->setBaseline(cxrow->getBaseline() - ascent);
466         }
467 */
468         metricsMarkers2(dim_);
469 }
470
471
472 void InsetMathGrid::metrics(MetricsInfo & mi, Dimension & dim) const
473 {
474         metrics(mi);
475         dim = dim_;
476 }
477
478
479 void InsetMathGrid::draw(PainterInfo & pi, int x, int y) const
480 {
481         drawWithMargin(pi, x, y, 0, 0);
482 }
483
484 void InsetMathGrid::drawWithMargin(PainterInfo & pi, int x, int y,
485         int lmargin, int rmargin) const
486 {
487         for (idx_type idx = 0; idx < nargs(); ++idx)
488                 cell(idx).draw(pi, x + lmargin + cellXOffset(idx),
489                         y + cellYOffset(idx));
490
491         for (row_type row = 0; row <= nrows(); ++row)
492                 for (unsigned int i = 0; i < rowinfo_[row].lines_; ++i) {
493                         int yy = y + rowinfo_[row].offset_ - rowinfo_[row].ascent_
494                                 - i * hlinesep() - hlinesep()/2 - rowsep()/2;
495                         pi.pain.line(x + lmargin + 1, yy,
496                                      x + dim_.width() - rmargin - 1, yy,
497                                      LColor::foreground);
498                 }
499
500         for (col_type col = 0; col <= ncols(); ++col)
501                 for (unsigned int i = 0; i < colinfo_[col].lines_; ++i) {
502                         int xx = x + lmargin + colinfo_[col].offset_
503                                 - i * vlinesep() - vlinesep()/2 - colsep()/2;
504                         pi.pain.line(xx, y - dim_.ascent() + 1,
505                                      xx, y + dim_.descent() - 1,
506                                      LColor::foreground);
507                 }
508         drawMarkers2(pi, x, y);
509 }
510
511
512 void InsetMathGrid::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
513 {
514         // let the cells adjust themselves
515         //InsetMathNest::metrics(mi);
516         for (idx_type i = 0; i < nargs(); ++i)
517                 cell(i).metricsT(mi, dim);
518
519         // compute absolute sizes of vertical structure
520         for (row_type row = 0; row < nrows(); ++row) {
521                 int asc  = 0;
522                 int desc = 0;
523                 for (col_type col = 0; col < ncols(); ++col) {
524                         MathArray const & c = cell(index(row, col));
525                         asc  = max(asc,  c.ascent());
526                         desc = max(desc, c.descent());
527                 }
528                 rowinfo_[row].ascent_  = asc;
529                 rowinfo_[row].descent_ = desc;
530         }
531         //rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
532         rowinfo_[nrows()].ascent_  = 0;
533         rowinfo_[nrows()].descent_ = 0;
534
535         // compute vertical offsets
536         rowinfo_[0].offset_ = 0;
537         for (row_type row = 1; row <= nrows(); ++row) {
538                 rowinfo_[row].offset_  =
539                         rowinfo_[row - 1].offset_  +
540                         rowinfo_[row - 1].descent_ +
541                         //rowinfo_[row - 1].skipPixels() +
542                         1 + //rowsep() +
543                         //rowinfo_[row].lines_ * hlinesep() +
544                         rowinfo_[row].ascent_;
545         }
546
547         // adjust vertical offset
548         int h = 0;
549         switch (v_align_) {
550                 case 't':
551                         h = 0;
552                         break;
553                 case 'b':
554                         h = rowinfo_[nrows() - 1].offset_;
555                         break;
556                 default:
557                         h = rowinfo_[nrows() - 1].offset_ / 2;
558         }
559         for (row_type row = 0; row <= nrows(); ++row)
560                 rowinfo_[row].offset_ -= h;
561
562
563         // compute absolute sizes of horizontal structure
564         for (col_type col = 0; col < ncols(); ++col) {
565                 int wid = 0;
566                 for (row_type row = 0; row < nrows(); ++row)
567                         wid = max(wid, cell(index(row, col)).width());
568                 colinfo_[col].width_ = wid;
569         }
570         colinfo_[ncols()].width_  = 0;
571
572         // compute horizontal offsets
573         colinfo_[0].offset_ = border();
574         for (col_type col = 1; col <= ncols(); ++col) {
575                 colinfo_[col].offset_ =
576                         colinfo_[col - 1].offset_ +
577                         colinfo_[col - 1].width_ +
578                         colinfo_[col - 1].skip_ +
579                         1 ; //colsep() +
580                         //colinfo_[col].lines_ * vlinesep();
581         }
582
583
584         dim.wid  =  colinfo_[ncols() - 1].offset_
585                        + colinfo_[ncols() - 1].width_
586                  //+ vlinesep() * colinfo_[ncols()].lines_
587                        + 2;
588
589         dim.asc  = -rowinfo_[0].offset_
590                        + rowinfo_[0].ascent_
591                  //+ hlinesep() * rowinfo_[0].lines_
592                        + 1;
593
594         dim.des  =  rowinfo_[nrows() - 1].offset_
595                        + rowinfo_[nrows() - 1].descent_
596                  //+ hlinesep() * rowinfo_[nrows()].lines_
597                        + 1;
598 }
599
600
601 void InsetMathGrid::drawT(TextPainter & pain, int x, int y) const
602 {
603         for (idx_type idx = 0; idx < nargs(); ++idx)
604                 cell(idx).drawT(pain, x + cellXOffset(idx), y + cellYOffset(idx));
605 }
606
607
608 string InsetMathGrid::eolString(row_type row, bool emptyline, bool fragile) const
609 {
610         string eol;
611
612         if (!rowinfo_[row].crskip_.zero())
613                 eol += '[' + rowinfo_[row].crskip_.asLatexString() + ']';
614
615         // make sure an upcoming '[' does not break anything
616         if (row + 1 < nrows()) {
617                 MathArray const & c = cell(index(row + 1, 0));
618                 if (c.size() && c.front()->getChar() == '[')
619                         //eol += "[0pt]";
620                         eol += "{}";
621         }
622
623         // only add \\ if necessary
624         if (eol.empty() && row + 1 == nrows() && (nrows() == 1 || !emptyline))
625                 return string();
626
627         return (fragile ? "\\protect\\\\" : "\\\\") + eol;
628 }
629
630
631 string InsetMathGrid::eocString(col_type col, col_type lastcol) const
632 {
633         if (col + 1 == lastcol)
634                 return string();
635         return " & ";
636 }
637
638
639 void InsetMathGrid::addRow(row_type row)
640 {
641         rowinfo_.insert(rowinfo_.begin() + row + 1, RowInfo());
642         cells_.insert
643                 (cells_.begin() + (row + 1) * ncols(), ncols(), MathArray());
644         cellinfo_.insert
645                 (cellinfo_.begin() + (row + 1) * ncols(), ncols(), CellInfo());
646 }
647
648
649 void InsetMathGrid::appendRow()
650 {
651         rowinfo_.push_back(RowInfo());
652         //cells_.insert(cells_.end(), ncols(), MathArray());
653         for (col_type col = 0; col < ncols(); ++col) {
654                 cells_.push_back(cells_type::value_type());
655                 cellinfo_.push_back(CellInfo());
656         }
657 }
658
659
660 void InsetMathGrid::delRow(row_type row)
661 {
662         if (nrows() == 1)
663                 return;
664
665         cells_type::iterator it = cells_.begin() + row * ncols();
666         cells_.erase(it, it + ncols());
667
668         vector<CellInfo>::iterator jt = cellinfo_.begin() + row * ncols();
669         cellinfo_.erase(jt, jt + ncols());
670
671         rowinfo_.erase(rowinfo_.begin() + row);
672 }
673
674
675 void InsetMathGrid::copyRow(row_type row)
676 {
677         addRow(row);
678         for (col_type col = 0; col < ncols(); ++col)
679                 cells_[(row + 1) * ncols() + col] = cells_[row * ncols() + col];
680 }
681
682
683 void InsetMathGrid::swapRow(row_type row)
684 {
685         if (nrows() == 1)
686                 return;
687         if (row + 1 == nrows())
688                 --row;
689         for (col_type col = 0; col < ncols(); ++col)
690                 swap(cells_[row * ncols() + col], cells_[(row + 1) * ncols() + col]);
691 }
692
693
694 void InsetMathGrid::addCol(col_type newcol)
695 {
696         const col_type nc = ncols();
697         const row_type nr = nrows();
698         cells_type new_cells((nc + 1) * nr);
699         vector<CellInfo> new_cellinfo((nc + 1) * nr);
700
701         for (row_type row = 0; row < nr; ++row)
702                 for (col_type col = 0; col < nc; ++col) {
703                         new_cells[row * (nc + 1) + col + (col > newcol)]
704                                 = cells_[row * nc + col];
705                         new_cellinfo[row * (nc + 1) + col + (col > newcol)]
706                                 = cellinfo_[row * nc + col];
707                 }
708         swap(cells_, new_cells);
709         swap(cellinfo_, new_cellinfo);
710
711         ColInfo inf;
712         inf.skip_  = defaultColSpace(newcol);
713         inf.align_ = defaultColAlign(newcol);
714         colinfo_.insert(colinfo_.begin() + newcol, inf);
715 }
716
717
718 void InsetMathGrid::delCol(col_type col)
719 {
720         if (ncols() == 1)
721                 return;
722
723         cells_type tmpcells;
724         vector<CellInfo> tmpcellinfo;
725         for (col_type i = 0; i < nargs(); ++i)
726                 if (i % ncols() != col) {
727                         tmpcells.push_back(cells_[i]);
728                         tmpcellinfo.push_back(cellinfo_[i]);
729                 }
730         swap(cells_, tmpcells);
731         swap(cellinfo_, tmpcellinfo);
732
733         colinfo_.erase(colinfo_.begin() + col);
734 }
735
736
737 void InsetMathGrid::copyCol(col_type col)
738 {
739         addCol(col);
740         for (row_type row = 0; row < nrows(); ++row)
741                 cells_[row * ncols() + col + 1] = cells_[row * ncols() + col];
742 }
743
744
745 void InsetMathGrid::swapCol(col_type col)
746 {
747         if (ncols() == 1)
748                 return;
749         if (col + 1 == ncols())
750                 --col;
751         for (row_type row = 0; row < nrows(); ++row)
752                 swap(cells_[row * ncols() + col], cells_[row * ncols() + col + 1]);
753 }
754
755
756 int InsetMathGrid::cellXOffset(idx_type idx) const
757 {
758         col_type c = col(idx);
759         int x = colinfo_[c].offset_;
760         char align = colinfo_[c].align_;
761         if (align == 'r' || align == 'R')
762                 x += colinfo_[c].width_ - cell(idx).width();
763         if (align == 'c' || align == 'C')
764                 x += (colinfo_[c].width_ - cell(idx).width()) / 2;
765         return x;
766 }
767
768
769 int InsetMathGrid::cellYOffset(idx_type idx) const
770 {
771         return rowinfo_[row(idx)].offset_;
772 }
773
774
775 bool InsetMathGrid::idxUpDown(LCursor & cur, bool up) const
776 {
777         if (up) {
778                 if (cur.row() == 0)
779                         return false;
780                 cur.idx() -= ncols();
781         } else {
782                 if (cur.row() + 1 >= nrows())
783                         return false;
784                 cur.idx() += ncols();
785         }
786         cur.pos() = cur.cell().x2pos(cur.x_target() - cur.cell().xo(cur.bv()));
787         return true;
788 }
789
790
791 bool InsetMathGrid::idxLeft(LCursor & cur) const
792 {
793         // leave matrix if on the left hand edge
794         if (cur.col() == 0)
795                 return false;
796         --cur.idx();
797         cur.pos() = cur.lastpos();
798         return true;
799 }
800
801
802 bool InsetMathGrid::idxRight(LCursor & cur) const
803 {
804         // leave matrix if on the right hand edge
805         if (cur.col() + 1 == ncols())
806                 return false;
807         ++cur.idx();
808         cur.pos() = 0;
809         return true;
810 }
811
812
813 bool InsetMathGrid::idxFirst(LCursor & cur) const
814 {
815         switch (v_align_) {
816                 case 't':
817                         cur.idx() = 0;
818                         break;
819                 case 'b':
820                         cur.idx() = (nrows() - 1) * ncols();
821                         break;
822                 default:
823                         cur.idx() = ((nrows() - 1) / 2) * ncols();
824         }
825         cur.pos() = 0;
826         return true;
827 }
828
829
830 bool InsetMathGrid::idxLast(LCursor & cur) const
831 {
832         switch (v_align_) {
833                 case 't':
834                         cur.idx() = ncols() - 1;
835                         break;
836                 case 'b':
837                         cur.idx() = nargs() - 1;
838                         break;
839                 default:
840                         cur.idx() = ((nrows() - 1) / 2 + 1) * ncols() - 1;
841         }
842         cur.pos() = cur.lastpos();
843         return true;
844 }
845
846
847 bool InsetMathGrid::idxDelete(idx_type & idx)
848 {
849         // nothing to do if we have just one row
850         if (nrows() == 1)
851                 return false;
852
853         // nothing to do if we are in the middle of the last row of the inset
854         if (idx + ncols() > nargs())
855                 return false;
856
857         // try to delete entire sequence of ncols() empty cells if possible
858         for (idx_type i = idx; i < idx + ncols(); ++i)
859                 if (cell(i).size())
860                         return false;
861
862         // move cells if necessary
863         for (idx_type i = index(row(idx), 0); i < idx; ++i)
864                 swap(cell(i), cell(i + ncols()));
865
866         delRow(row(idx));
867
868         if (idx >= nargs())
869                 idx = nargs() - 1;
870
871         // undo effect of Ctrl-Tab (i.e. pull next cell)
872         //if (idx + 1 != nargs())
873         //      cell(idx).swap(cell(idx + 1));
874
875         // we handled the event..
876         return true;
877 }
878
879
880 // reimplement old behaviour when pressing Delete in the last position
881 // of a cell
882 void InsetMathGrid::idxGlue(idx_type idx)
883 {
884         col_type c = col(idx);
885         if (c + 1 == ncols()) {
886                 if (row(idx) + 1 != nrows()) {
887                         for (col_type cc = 0; cc < ncols(); ++cc)
888                                 cell(idx).append(cell(idx + cc + 1));
889                         delRow(row(idx) + 1);
890                 }
891         } else {
892                 cell(idx).append(cell(idx + 1));
893                 for (col_type cc = c + 2; cc < ncols(); ++cc)
894                         cell(idx - c + cc - 1) = cell(idx - c + cc);
895                 cell(idx - c + ncols() - 1).clear();
896         }
897 }
898
899
900 InsetMathGrid::RowInfo const & InsetMathGrid::rowinfo(row_type row) const
901 {
902         return rowinfo_[row];
903 }
904
905
906 InsetMathGrid::RowInfo & InsetMathGrid::rowinfo(row_type row)
907 {
908         return rowinfo_[row];
909 }
910
911
912 bool InsetMathGrid::idxBetween(idx_type idx, idx_type from, idx_type to) const
913 {
914         row_type const ri = row(idx);
915         row_type const r1 = min(row(from), row(to));
916         row_type const r2 = max(row(from), row(to));
917         col_type const ci = col(idx);
918         col_type const c1 = min(col(from), col(to));
919         col_type const c2 = max(col(from), col(to));
920         return r1 <= ri && ri <= r2 && c1 <= ci && ci <= c2;
921 }
922
923
924
925 void InsetMathGrid::normalize(NormalStream & os) const
926 {
927         os << "[grid ";
928         for (row_type row = 0; row < nrows(); ++row) {
929                 os << "[row ";
930                 for (col_type col = 0; col < ncols(); ++col)
931                         os << "[cell " << cell(index(row, col)) << ']';
932                 os << ']';
933         }
934         os << ']';
935 }
936
937
938 void InsetMathGrid::mathmlize(MathMLStream & os) const
939 {
940         os << MTag("mtable");
941         for (row_type row = 0; row < nrows(); ++row) {
942                 os << MTag("mtr");
943                 for (col_type col = 0; col < ncols(); ++col)
944                         os << cell(index(row, col));
945                 os << ETag("mtr");
946         }
947         os << ETag("mtable");
948 }
949
950
951 void InsetMathGrid::write(WriteStream & os) const
952 {
953         string eol;
954         for (row_type row = 0; row < nrows(); ++row) {
955                 os << verboseHLine(rowinfo_[row].lines_);
956                 // don't write & and empty cells at end of line
957                 col_type lastcol = 0;
958                 bool emptyline = true;
959                 for (col_type col = 0; col < ncols(); ++col)
960                         if (!cell(index(row, col)).empty()) {
961                                 lastcol = col + 1;
962                                 emptyline = false;
963                         }
964                 for (col_type col = 0; col < lastcol; ++col)
965                         os << cell(index(row, col)) << eocString(col, lastcol);
966                 eol = eolString(row, emptyline, os.fragile());
967                 os << eol;
968                 // append newline only if line wasn't completely empty
969                 // and this was not the last line in the grid
970                 if (!emptyline && row + 1 < nrows())
971                         os << "\n";
972         }
973         string const s = verboseHLine(rowinfo_[nrows()].lines_);
974         if (!s.empty()) {
975                 if (eol.empty()) {
976                         if (os.fragile())
977                                 os << "\\protect";
978                         os << "\\\\";
979                 }
980                 os << s;
981         }
982 }
983
984
985 int InsetMathGrid::colsep() const
986 {
987         return 6;
988 }
989
990
991 int InsetMathGrid::rowsep() const
992 {
993         return 6;
994 }
995
996
997 int InsetMathGrid::hlinesep() const
998 {
999         return 3;
1000 }
1001
1002
1003 int InsetMathGrid::vlinesep() const
1004 {
1005         return 3;
1006 }
1007
1008
1009 int InsetMathGrid::border() const
1010 {
1011         return 1;
1012 }
1013
1014
1015 void InsetMathGrid::splitCell(LCursor & cur)
1016 {
1017         if (cur.idx() == cur.lastidx())
1018                 return;
1019         MathArray ar = cur.cell();
1020         ar.erase(0, cur.pos());
1021         cur.cell().erase(cur.pos(), cur.lastpos());
1022         ++cur.idx();
1023         cur.pos() = 0;
1024         cur.cell().insert(0, ar);
1025 }
1026
1027
1028 void InsetMathGrid::doDispatch(LCursor & cur, FuncRequest & cmd)
1029 {
1030         //lyxerr << "*** InsetMathGrid: request: " << cmd << endl;
1031         switch (cmd.action) {
1032
1033         case LFUN_MOUSE_RELEASE:
1034                 //if (cmd.button() == mouse_button::button3) {
1035                 //      GridInsetMailer(*this).showDialog();
1036                 //      return DispatchResult(true, true);
1037                 //}
1038                 InsetMathNest::doDispatch(cur, cmd);
1039                 break;
1040
1041         case LFUN_INSET_DIALOG_UPDATE:
1042                 GridInsetMailer(*this).updateDialog(&cur.bv());
1043                 break;
1044
1045         // insert file functions
1046         case LFUN_LINE_DELETE:
1047                 // FIXME: We use recordUndoInset when a change reflects more
1048                 // than one cell, because recordUndo does not work for
1049                 // multiple cells. Unfortunately this puts the cursor in front
1050                 // of the inset after undo. This is (especilally for large
1051                 // grids) annoying.
1052                 recordUndoInset(cur);
1053                 //autocorrect_ = false;
1054                 //macroModeClose();
1055                 //if (selection_) {
1056                 //      selDel();
1057                 //      break;
1058                 //}
1059                 if (nrows() > 1)
1060                         delRow(cur.row());
1061                 if (cur.idx() > cur.lastidx())
1062                         cur.idx() = cur.lastidx();
1063                 if (cur.pos() > cur.lastpos())
1064                         cur.pos() = cur.lastpos();
1065                 break;
1066
1067         case LFUN_CELL_SPLIT:
1068                 recordUndo(cur);
1069                 splitCell(cur);
1070                 break;
1071
1072         case LFUN_CELL_BACKWARD:
1073                 // See below.
1074                 cur.selection() = false;
1075                 if (!idxPrev(cur)) {
1076                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
1077                         cur.undispatched();
1078                 }
1079                 break;
1080
1081         case LFUN_CELL_FORWARD:
1082                 // Can't handle selection by additional 'shift' as this is
1083                 // hard bound to LFUN_CELL_BACKWARD
1084                 cur.selection() = false;
1085                 if (!idxNext(cur)) {
1086                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
1087                         cur.undispatched();
1088                 }
1089                 break;
1090
1091         case LFUN_BREAK_LINE: {
1092                 recordUndoInset(cur);
1093                 row_type const r = cur.row();
1094                 addRow(r);
1095
1096                 // split line
1097                 for (col_type c = col(cur.idx()) + 1; c < ncols(); ++c)
1098                         swap(cell(index(r, c)), cell(index(r + 1, c)));
1099
1100                 // split cell
1101                 splitCell(cur);
1102                 swap(cell(cur.idx()), cell(cur.idx() + ncols() - 1));
1103                 if (cur.idx() > 0)
1104                         --cur.idx();
1105                 cur.pos() = cur.lastpos();
1106
1107                 //mathcursor->normalize();
1108                 //cmd = FuncRequest(LFUN_FINISHED_LEFT);
1109                 break;
1110         }
1111
1112         case LFUN_TABULAR_FEATURE: {
1113                 recordUndoInset(cur);
1114                 //lyxerr << "handling tabular-feature " << lyx::to_utf8(cmd.argument()) << endl;
1115                 istringstream is(lyx::to_utf8(cmd.argument()));
1116                 string s;
1117                 is >> s;
1118                 if (s == "valign-top")
1119                         valign('t');
1120                 else if (s == "valign-middle")
1121                         valign('c');
1122                 else if (s == "valign-bottom")
1123                         valign('b');
1124                 else if (s == "align-left")
1125                         halign('l', cur.col());
1126                 else if (s == "align-right")
1127                         halign('r', cur.col());
1128                 else if (s == "align-center")
1129                         halign('c', cur.col());
1130                 else if (s == "append-row")
1131                         for (int i = 0, n = extractInt(is); i < n; ++i)
1132                                 addRow(cur.row());
1133                 else if (s == "delete-row") {
1134                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1135                                 delRow(cur.row());
1136                                 if (cur.idx() >= nargs())
1137                                         cur.idx() -= ncols();
1138                         }
1139                         cur.pos() = 0; // trick, see below
1140                 }
1141                 else if (s == "copy-row") {
1142                         // Here (as later) we save the cursor col/row
1143                         // in order to restore it after operation.
1144                         row_type const r = cur.row();
1145                         col_type const c = cur.col();
1146                         for (int i = 0, n = extractInt(is); i < n; ++i)
1147                                 copyRow(cur.row());
1148                         cur.idx() = index(r, c);
1149                 }
1150                 else if (s == "swap-row") {
1151                         swapRow(cur.row());
1152                         // Trick to suppress same-idx-means-different-cell
1153                         // assertion crash:
1154                         cur.pos() = 0;
1155                 }
1156                 else if (s == "add-hline-above")
1157                         rowinfo_[cur.row()].lines_++;
1158                 else if (s == "add-hline-below")
1159                         rowinfo_[cur.row()+1].lines_++;
1160                 else if (s == "delete-hline-above")
1161                         rowinfo_[cur.row()].lines_--;
1162                 else if (s == "delete-hline-below")
1163                         rowinfo_[cur.row()+1].lines_--;
1164                 else if (s == "append-column") {
1165                         row_type const r = cur.row();
1166                         col_type const c = cur.col();
1167                         for (int i = 0, n = extractInt(is); i < n; ++i)
1168                                 addCol(cur.col());
1169                         cur.idx() = index(r, c);
1170                 }
1171                 else if (s == "delete-column") {
1172                         row_type const r = cur.row();
1173                         col_type const c = cur.col();
1174                         for (int i = 0, n = extractInt(is); i < n; ++i)
1175                                 delCol(col(cur.idx()));
1176                         cur.idx() = index(r, min(c, cur.ncols() - 1));
1177                         cur.pos() = 0; // trick, see above
1178                 }
1179                 else if (s == "copy-column") {
1180                         row_type const r = cur.row();
1181                         col_type const c = cur.col();
1182                         copyCol(cur.col());
1183                         cur.idx() = index(r, c);
1184                 }
1185                 else if (s == "swap-column") {
1186                         swapCol(cur.col());
1187                         cur.pos() = 0; // trick, see above
1188                 }
1189                 else if (s == "add-vline-left")
1190                         colinfo_[cur.col()].lines_++;
1191                 else if (s == "add-vline-right")
1192                         colinfo_[cur.col()+1].lines_++;
1193                 else if (s == "delete-vline-left")
1194                         colinfo_[cur.col()].lines_--;
1195                 else if (s == "delete-vline-right")
1196                         colinfo_[cur.col()+1].lines_--;
1197                 else {
1198                         cur.undispatched();
1199                         break;
1200                 }
1201                 lyxerr << "returning FINISHED_LEFT" << endl;
1202                 break;
1203         }
1204
1205         case LFUN_PASTE: {
1206                 cur.message(_("Paste"));
1207                 lyx::cap::replaceSelection(cur);
1208                 istringstream is(lyx::to_utf8(cmd.argument()));
1209                 int n = 0;
1210                 is >> n;
1211                 InsetMathGrid grid(1, 1);
1212                 // FIXME UNICODE
1213                 mathed_parse_normal(grid,
1214                         lyx::to_utf8(lyx::cap::getSelection(cur.buffer(), n)));
1215                 if (grid.nargs() == 1) {
1216                         // single cell/part of cell
1217                         recordUndo(cur);
1218                         cur.cell().insert(cur.pos(), grid.cell(0));
1219                         cur.pos() += grid.cell(0).size();
1220                 } else {
1221                         // multiple cells
1222                         recordUndoInset(cur);
1223                         col_type const numcols =
1224                                 min(grid.ncols(), ncols() - col(cur.idx()));
1225                         row_type const numrows =
1226                                 min(grid.nrows(), nrows() - cur.row());
1227                         for (row_type r = 0; r < numrows; ++r) {
1228                                 for (col_type c = 0; c < numcols; ++c) {
1229                                         idx_type i = index(r + cur.row(), c + col(cur.idx()));
1230                                         cell(i).insert(0, grid.cell(grid.index(r, c)));
1231                                 }
1232                                 // append the left over horizontal cells to the last column
1233                                 idx_type i = index(r + cur.row(), ncols() - 1);
1234                                 for (InsetMath::col_type c = numcols; c < grid.ncols(); ++c)
1235                                         cell(i).append(grid.cell(grid.index(r, c)));
1236                         }
1237                         // append the left over vertical cells to the last _cell_
1238                         idx_type i = nargs() - 1;
1239                         for (row_type r = numrows; r < grid.nrows(); ++r)
1240                                 for (col_type c = 0; c < grid.ncols(); ++c)
1241                                         cell(i).append(grid.cell(grid.index(r, c)));
1242                 }
1243                 cur.clearSelection(); // bug 393
1244                 cur.bv().switchKeyMap();
1245                 finishUndo();
1246                 break;
1247         }
1248
1249         case LFUN_LINE_BEGIN_SELECT:
1250         case LFUN_LINE_BEGIN:
1251         case LFUN_WORD_BACKWARD_SELECT:
1252         case LFUN_WORD_BACKWARD:
1253                 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
1254                                 cmd.action == LFUN_LINE_BEGIN_SELECT);
1255                 cur.macroModeClose();
1256                 if (cur.pos() != 0) {
1257                         cur.pos() = 0;
1258                 } else if (cur.idx() % cur.ncols() != 0) {
1259                         cur.idx() -= cur.idx() % cur.ncols();
1260                         cur.pos() = 0;
1261                 } else if (cur.idx() != 0) {
1262                         cur.idx() = 0;
1263                         cur.pos() = 0;
1264                 } else {
1265                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
1266                         cur.undispatched();
1267                 }
1268                 break;
1269
1270         case LFUN_WORD_FORWARD_SELECT:
1271         case LFUN_WORD_FORWARD:
1272         case LFUN_LINE_END_SELECT:
1273         case LFUN_LINE_END:
1274                 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
1275                                 cmd.action == LFUN_LINE_END_SELECT);
1276                 cur.macroModeClose();
1277                 cur.clearTargetX();
1278                 if (cur.pos() != cur.lastpos()) {
1279                         cur.pos() = cur.lastpos();
1280                 } else if ((cur.idx() + 1) % cur.ncols() != 0) {
1281                         cur.idx() += cur.ncols() - 1 - cur.idx() % cur.ncols();
1282                         cur.pos() = cur.lastpos();
1283                 } else if (cur.idx() != cur.lastidx()) {
1284                         cur.idx() = cur.lastidx();
1285                         cur.pos() = cur.lastpos();
1286                 } else {
1287                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
1288                         cur.undispatched();
1289                 }
1290                 break;
1291
1292         default:
1293                 InsetMathNest::doDispatch(cur, cmd);
1294         }
1295 }
1296
1297
1298 bool InsetMathGrid::getStatus(LCursor & cur, FuncRequest const & cmd,
1299                 FuncStatus & status) const
1300 {
1301         switch (cmd.action) {
1302         case LFUN_TABULAR_FEATURE: {
1303                 string const s = lyx::to_utf8(cmd.argument());
1304                 if (nrows() <= 1 && (s == "delete-row" || s == "swap-row")) {
1305                         status.enabled(false);
1306                         status.message(lyx::from_utf8(N_("Only one row")));
1307                         return true;
1308                 }
1309                 if (ncols() <= 1 &&
1310                     (s == "delete-column" || s == "swap-column")) {
1311                         status.enabled(false);
1312                         status.message(lyx::from_utf8(N_("Only one column")));
1313                         return true;
1314                 }
1315                 if ((rowinfo_[cur.row()].lines_ == 0 &&
1316                      s == "delete-hline-above") ||
1317                     (rowinfo_[cur.row() + 1].lines_ == 0 &&
1318                      s == "delete-hline-below")) {
1319                         status.enabled(false);
1320                         status.message(lyx::from_utf8(N_("No hline to delete")));
1321                         return true;
1322                 }
1323
1324                 if ((colinfo_[cur.col()].lines_ == 0 &&
1325                      s == "delete-vline-left") ||
1326                     (colinfo_[cur.col() + 1].lines_ == 0 &&
1327                      s == "delete-vline-right")) {
1328                         status.enabled(false);
1329                         status.message(lyx::from_utf8(N_("No vline to delete")));
1330                         return true;
1331                 }
1332                 if (s == "valign-top" || s == "valign-middle" ||
1333                     s == "valign-bottom" || s == "align-left" ||
1334                     s == "align-right" || s == "align-center" ||
1335                     s == "append-row" || s == "delete-row" ||
1336                     s == "copy-row" || s == "swap-row" ||
1337                     s == "add-hline-above" || s == "add-hline-below" ||
1338                     s == "delete-hline-above" || s == "delete-hline-below" ||
1339                     s == "append-column" || s == "delete-column" ||
1340                     s == "copy-column" || s == "swap-column" ||
1341                     s == "add-vline-left" || s == "add-vline-right" ||
1342                     s == "delete-vline-left" || s == "delete-vline-right")
1343                         status.enabled(true);
1344                 else {
1345                         status.enabled(false);
1346                         status.message(bformat(
1347                                 lyx::from_utf8(N_("Unknown tabular feature '%1$s'")), lyx::from_ascii(s)));
1348                 }
1349
1350                 status.setOnOff(s == "align-left"    && halign(cur.col()) == 'l'
1351                            || s == "align-right"   && halign(cur.col()) == 'r'
1352                            || s == "align-center"  && halign(cur.col()) == 'c'
1353                            || s == "valign-top"    && valign() == 't'
1354                            || s == "valign-bottom" && valign() == 'b'
1355                            || s == "valign-middle" && valign() == 'm');
1356
1357 #if 0
1358                 // FIXME: What did this code do?
1359                 // Please check whether it is still needed!
1360                 // should be more precise
1361                 if (v_align_ == '\0') {
1362                         status.enable(true);
1363                         break;
1364                 }
1365                 if (cmd.argument().empty()) {
1366                         status.enable(false);
1367                         break;
1368                 }
1369                 if (!lyx::support::contains("tcb", cmd.argument()[0])) {
1370                         status.enable(false);
1371                         break;
1372                 }
1373                 status.setOnOff(cmd.argument()[0] == v_align_);
1374                 status.enabled(true);
1375 #endif
1376                 return true;
1377         }
1378
1379         case LFUN_CELL_SPLIT:
1380                 status.enabled(true);
1381                 return true;
1382
1383         case LFUN_CELL_BACKWARD:
1384         case LFUN_CELL_FORWARD:
1385                 status.enabled(true);
1386                 return true;
1387
1388         default:
1389                 return InsetMathNest::getStatus(cur, cmd, status);
1390         }
1391 }