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