]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathGrid.cpp
... and RELEASE-NOTES
[lyx.git] / src / mathed / InsetMathGrid.cpp
1 /**
2  * \file InsetMathGrid.cpp
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 #include <algorithm>
13
14 #include "InsetMathGrid.h"
15
16 #include "InsetMathUnknown.h"
17 #include "MathData.h"
18 #include "MathParser.h"
19 #include "MathStream.h"
20 #include "MetricsInfo.h"
21
22 #include "Buffer.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "LaTeXFeatures.h"
30 #include "TexRow.h"
31
32 #include "frontends/Clipboard.h"
33 #include "frontends/Painter.h"
34
35 #include "support/debug.h"
36 #include "support/docstream.h"
37 #include "support/gettext.h"
38 #include "support/lstrings.h"
39 #include "support/lassert.h"
40
41 #include <sstream>
42
43 using namespace std;
44 using namespace lyx::support;
45
46
47
48 namespace lyx {
49
50 static docstring verboseHLine(int n)
51 {
52         docstring res;
53         for (int i = 0; i < n; ++i)
54                 res += "\\hline";
55         if (n)
56                 res += ' ';
57         return res;
58 }
59
60
61 static int extractInt(istream & is)
62 {
63         int num = 1;
64         is >> num;
65         return (num == 0) ? 1 : num;
66 }
67
68
69 static void resetGrid(InsetMathGrid & grid)
70 {
71         while (grid.ncols() > 1)
72                 grid.delCol(grid.ncols() - 1);
73         while (grid.nrows() > 1)
74                 grid.delRow(grid.nrows() - 1);
75         grid.cell(0).erase(0, grid.cell(0).size());
76         grid.setDefaults();
77 }
78
79
80
81 //////////////////////////////////////////////////////////////
82
83
84 InsetMathGrid::CellInfo::CellInfo()
85         : multi_(CELL_NORMAL)
86 {}
87
88
89
90 //////////////////////////////////////////////////////////////
91
92
93 InsetMathGrid::RowInfo::RowInfo()
94         : descent_(0), ascent_(0), offset_(0), lines_(0), skip_(0),
95           allow_newpage_(true)
96 {}
97
98
99
100 int InsetMathGrid::RowInfo::skipPixels(MetricsInfo const & mi) const
101 {
102         return crskip_.inPixels(mi.base);
103 }
104
105
106
107 //////////////////////////////////////////////////////////////
108
109
110 InsetMathGrid::ColInfo::ColInfo()
111         : align_('c'), width_(0), offset_(0), lines_(0), skip_(0)
112 {}
113
114
115 //////////////////////////////////////////////////////////////
116
117
118 InsetMathGrid::InsetMathGrid(Buffer * buf)
119         : InsetMathNest(buf, 1),
120           rowinfo_(1 + 1),
121                 colinfo_(1 + 1),
122                 cellinfo_(1),
123                 v_align_('c')
124 {
125         setDefaults();
126 }
127
128
129 InsetMathGrid::InsetMathGrid(Buffer * buf, col_type m, row_type n)
130         : InsetMathNest(buf, m * n),
131           rowinfo_(n + 1),
132                 colinfo_(m + 1),
133                 cellinfo_(m * n),
134                 v_align_('c')
135 {
136         setDefaults();
137 }
138
139
140 InsetMathGrid::InsetMathGrid(Buffer * buf, col_type m, row_type n, char v,
141         docstring const & h)
142         : InsetMathNest(buf, m * n),
143           rowinfo_(n + 1),
144           colinfo_(m + 1),
145                 cellinfo_(m * n),
146                 v_align_(v)
147 {
148         setDefaults();
149         setVerticalAlignment(v);
150         setHorizontalAlignments(h);
151 }
152
153
154 Inset * InsetMathGrid::clone() const
155 {
156         return new InsetMathGrid(*this);
157 }
158
159
160 InsetMath::idx_type InsetMathGrid::index(row_type row, col_type col) const
161 {
162         return col + ncols() * row;
163 }
164
165
166 void InsetMathGrid::setDefaults()
167 {
168         if (ncols() <= 0)
169                 lyxerr << "positive number of columns expected" << endl;
170         //if (nrows() <= 0)
171         //      lyxerr << "positive number of rows expected" << endl;
172         for (col_type col = 0; col < ncols(); ++col) {
173                 colinfo_[col].align_ = defaultColAlign(col);
174                 colinfo_[col].skip_  = defaultColSpace(col);
175                 colinfo_[col].special_.clear();
176         }
177         for (idx_type idx = 0; idx < nargs(); ++idx)
178                 cellinfo_[idx].multi_ = CELL_NORMAL;
179 }
180
181
182 bool InsetMathGrid::interpretString(Cursor & cur, docstring const & str)
183 {
184         if (str == "\\hline") {
185                 FuncRequest fr = FuncRequest(LFUN_TABULAR_FEATURE, "add-hline-above");
186                 FuncStatus status;
187                 if (getStatus(cur, fr, status)) {
188                         if (status.enabled()) {
189                                 rowinfo_[cur.row()].lines_++;
190                                 return true;
191                         }
192                 }
193         }
194         return InsetMathNest::interpretString(cur, str);
195 }
196
197
198 void InsetMathGrid::setHorizontalAlignments(docstring const & hh)
199 {
200         col_type col = 0;
201         for (docstring::const_iterator it = hh.begin(); it != hh.end(); ++it) {
202                 char_type c = *it;
203                 if (c == '|') {
204                         colinfo_[col].lines_++;
205                 } else if ((c == 'p' || c == 'm' || c == 'b'||
206                             c == '!' || c == '@' || c == '>' || c == '<') &&
207                            it + 1 != hh.end() && *(it + 1) == '{') {
208                         // @{decl.} and p{width} are standard LaTeX, the
209                         // others are extensions by array.sty
210                         bool const newcolumn = c == 'p' || c == 'm' || c == 'b';
211                         if (newcolumn) {
212                                 // this declares a new column
213                                 if (col >= ncols())
214                                         // Only intercolumn stuff is allowed
215                                         // in the last dummy column
216                                         break;
217                                 colinfo_[col].align_ = 'l';
218                         } else {
219                                 // this is intercolumn stuff
220                                 if (colinfo_[col].special_.empty())
221                                         // Overtake possible lines
222                                         colinfo_[col].special_ = docstring(colinfo_[col].lines_, '|');
223                         }
224                         int brace_open = 0;
225                         int brace_close = 0;
226                         while (it != hh.end()) {
227                                 c = *it;
228                                 colinfo_[col].special_ += c;
229                                 if (c == '{')
230                                         ++brace_open;
231                                 else if (c == '}')
232                                         ++brace_close;
233                                 ++it;
234                                 if (brace_open > 0 && brace_open == brace_close)
235                                         break;
236                         }
237                         --it;
238                         if (newcolumn) {
239                                 colinfo_[col].lines_ = count(
240                                         colinfo_[col].special_.begin(),
241                                         colinfo_[col].special_.end(), '|');
242                                 LYXERR(Debug::MATHED, "special column separator: `"
243                                         << to_utf8(colinfo_[col].special_) << '\'');
244                                 ++col;
245                                 colinfo_[col].lines_ = 0;
246                                 colinfo_[col].special_.clear();
247                         }
248                 } else if (col >= ncols()) {
249                         // Only intercolumn stuff is allowed in the last
250                         // dummy column
251                         break;
252                 } else if (c == 'c' || c == 'l' || c == 'r') {
253                         colinfo_[col].align_ = static_cast<char>(c);
254                         if (!colinfo_[col].special_.empty()) {
255                                 colinfo_[col].special_ += c;
256                                 colinfo_[col].lines_ = count(
257                                                 colinfo_[col].special_.begin(),
258                                                 colinfo_[col].special_.end(), '|');
259                                 LYXERR(Debug::MATHED, "special column separator: `"
260                                         << to_utf8(colinfo_[col].special_) << '\'');
261                         }
262                         ++col;
263                         colinfo_[col].lines_ = 0;
264                         colinfo_[col].special_.clear();
265                 } else {
266                         lyxerr << "unknown column separator: '" << c << "'" << endl;
267                 }
268         }
269
270 /*
271         col_type n = hh.size();
272         if (n > ncols())
273                 n = ncols();
274         for (col_type col = 0; col < n; ++col)
275                 colinfo_[col].align_ = hh[col];
276 */
277 }
278
279
280 InsetMathGrid::col_type InsetMathGrid::guessColumns(docstring const & hh)
281 {
282         col_type col = 0;
283         for (docstring::const_iterator it = hh.begin(); it != hh.end(); ++it)
284                 if (*it == 'c' || *it == 'l' || *it == 'r'||
285                     *it == 'p' || *it == 'm' || *it == 'b')
286                         ++col;
287         // let's have at least one column, even if we did not recognize its
288         // alignment
289         if (col == 0)
290                 col = 1;
291         return col;
292 }
293
294
295 void InsetMathGrid::setHorizontalAlignment(char h, col_type col)
296 {
297         colinfo_[col].align_ = h;
298         if (!colinfo_[col].special_.empty()) {
299                 char_type & c = colinfo_[col].special_[colinfo_[col].special_.size() - 1];
300                 if (c == 'l' || c == 'c' || c == 'r')
301                         c = h;
302         }
303         // FIXME: Change alignment of p, m and b columns, too
304 }
305
306
307 char InsetMathGrid::horizontalAlignment(col_type col) const
308 {
309         return colinfo_[col].align_;
310 }
311
312
313 docstring InsetMathGrid::horizontalAlignments() const
314 {
315         docstring res;
316         for (col_type col = 0; col < ncols(); ++col) {
317                 if (colinfo_[col].special_.empty()) {
318                         res += docstring(colinfo_[col].lines_, '|');
319                         res += colinfo_[col].align_;
320                 } else
321                         res += colinfo_[col].special_;
322         }
323         if (colinfo_[ncols()].special_.empty())
324                 return res + docstring(colinfo_[ncols()].lines_, '|');
325         return res + colinfo_[ncols()].special_;
326 }
327
328
329 void InsetMathGrid::setVerticalAlignment(char c)
330 {
331         v_align_ = c;
332 }
333
334
335 char InsetMathGrid::verticalAlignment() const
336 {
337         return v_align_;
338 }
339
340
341 InsetMathGrid::col_type InsetMathGrid::ncols() const
342 {
343         return colinfo_.size() - 1;
344 }
345
346
347 InsetMathGrid::row_type InsetMathGrid::nrows() const
348 {
349         return rowinfo_.size() - 1;
350 }
351
352
353 InsetMathGrid::col_type InsetMathGrid::col(idx_type idx) const
354 {
355         return idx % ncols();
356 }
357
358
359 InsetMathGrid::row_type InsetMathGrid::row(idx_type idx) const
360 {
361         return idx / ncols();
362 }
363
364
365 InsetMathGrid::col_type InsetMathGrid::ncellcols(idx_type idx) const
366 {
367         col_type cols = 1;
368         if (cellinfo_[idx].multi_ == CELL_NORMAL)
369                 return cols;
370         // If the cell at idx is already CELL_PART_OF_MULTICOLUMN we return
371         // the number of remaining columns, not the ones of the complete
372         // multicolumn cell. This makes it possible to always go to the next
373         // cell with idx + ncellcols(idx) - 1.
374         row_type const r = row(idx);
375         while (idx+cols < nargs() && row(idx+cols) == r &&
376                cellinfo_[idx+cols].multi_ == CELL_PART_OF_MULTICOLUMN)
377                 cols++;
378         return cols;
379 }
380
381
382 void InsetMathGrid::vcrskip(Length const & crskip, row_type row)
383 {
384         rowinfo_[row].crskip_ = crskip;
385 }
386
387
388 Length InsetMathGrid::vcrskip(row_type row) const
389 {
390         return rowinfo_[row].crskip_;
391 }
392
393
394 void InsetMathGrid::metrics(MetricsInfo & mi, Dimension & dim) const
395 {
396         // let the cells adjust themselves
397         for (idx_type i = 0; i < nargs(); ++i) {
398                 if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
399                         Dimension dimc;
400                         cell(i).metrics(mi, dimc);
401                 }
402         }
403
404         BufferView & bv = *mi.base.bv;
405
406         // compute absolute sizes of vertical structure
407         for (row_type row = 0; row < nrows(); ++row) {
408                 int asc  = 0;
409                 int desc = 0;
410                 for (col_type col = 0; col < ncols(); ++col) {
411                         idx_type const i = index(row, col);
412                         if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
413                                 Dimension const & dimc = cell(i).dimension(bv);
414                                 asc  = max(asc,  dimc.asc);
415                                 desc = max(desc, dimc.des);
416                         }
417                 }
418                 rowinfo_[row].ascent_  = asc;
419                 rowinfo_[row].descent_ = desc;
420         }
421         rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
422         rowinfo_[nrows()].ascent_  = 0;
423         rowinfo_[nrows()].descent_ = 0;
424
425         // compute vertical offsets
426         rowinfo_[0].offset_ = 0;
427         for (row_type row = 1; row <= nrows(); ++row) {
428                 rowinfo_[row].offset_ =
429                         rowinfo_[row - 1].offset_ +
430                         rowinfo_[row - 1].descent_ +
431                         rowinfo_[row - 1].skipPixels(mi) +
432                         rowsep() +
433                         rowinfo_[row].lines_ * hlinesep() +
434                         rowinfo_[row].ascent_;
435         }
436
437         // adjust vertical offset
438         int h = 0;
439         switch (v_align_) {
440                 case 't':
441                         h = 0;
442                         break;
443                 case 'b':
444                         h = rowinfo_[nrows() - 1].offset_;
445                         break;
446                 default:
447                         h = rowinfo_[nrows() - 1].offset_ / 2;
448         }
449         for (row_type row = 0; row <= nrows(); ++row)
450                 rowinfo_[row].offset_ -= h;
451
452
453         // multicolumn cell widths, as a map from first column to width in a
454         // vector of last columns.
455         // This is only used if the grid has more than one row, since for
456         // one-row grids multicolumn cells do not need special handling
457         vector<map<col_type, int> > mcolwidths(ncols());
458
459         // compute absolute sizes of horizontal structure
460         for (col_type col = 0; col < ncols(); ++col) {
461                 int wid = 0;
462                 for (row_type row = 0; row < nrows(); ++row) {
463                         idx_type const i = index(row, col);
464                         if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
465                                 int const w = cell(i).dimension(bv).wid;
466                                 col_type const cols = ncellcols(i);
467                                 if (cols > 1 && nrows() > 1) {
468                                         col_type last = col+cols-1;
469                                         LASSERT(last < ncols(), last = ncols()-1);
470                                         map<col_type, int>::iterator it =
471                                                 mcolwidths[last].find(col);
472                                         if (it == mcolwidths[last].end())
473                                                 mcolwidths[last][col] = w;
474                                         else
475                                                 it->second = max(it->second, w);
476                                 } else
477                                         wid = max(wid, w);
478                         }
479                 }
480                 colinfo_[col].width_ = wid;
481         }
482         colinfo_[ncols()].width_  = 0;
483
484         // compute horizontal offsets
485         colinfo_[0].offset_ = border();
486         for (col_type col = 1; col <= ncols(); ++col) {
487                 colinfo_[col].offset_ =
488                         colinfo_[col - 1].offset_ +
489                         colinfo_[col - 1].width_ +
490                         displayColSpace(col - 1) +
491                         colsep() +
492                         colinfo_[col].lines_ * vlinesep();
493         }
494
495         // increase column widths for multicolumn cells if needed
496         // FIXME: multicolumn lines are not yet considered
497         for (col_type last = 0; last < ncols(); ++last) {
498                 map<col_type, int> const & widths = mcolwidths[last];
499                 // We increase the width of the last column of the multicol
500                 // cell (some sort of left alignment). Since we iterate through
501                 // the last and the first columns from left to right, we ensure
502                 // that increased widths of previous columns are correctly
503                 // taken into account for later columns, thus preventing
504                 // unneeded width increasing.
505                 for (map<col_type, int>::const_iterator it = widths.begin();
506                      it != widths.end(); ++it) {
507                         int const wid = it->second;
508                         col_type const first = it->first;
509                         int const nextoffset =
510                                 colinfo_[first].offset_ +
511                                 wid +
512                                 displayColSpace(last) +
513                                 colsep() +
514                                 colinfo_[last+1].lines_ * vlinesep();
515                         int const dx = nextoffset - colinfo_[last+1].offset_;
516                         if (dx > 0) {
517                                 colinfo_[last].width_ += dx;
518                                 for (col_type col = last + 1; col <= ncols(); ++col)
519                                         colinfo_[col].offset_ += dx;
520                         }
521                 }
522         }
523
524
525         dim.wid = colinfo_[ncols() - 1].offset_
526                 + colinfo_[ncols() - 1].width_
527                 + vlinesep() * colinfo_[ncols()].lines_
528                 + border();
529
530         dim.asc = - rowinfo_[0].offset_
531                 + rowinfo_[0].ascent_
532                 + hlinesep() * rowinfo_[0].lines_
533                 + border();
534
535         dim.des = rowinfo_[nrows() - 1].offset_
536                 + rowinfo_[nrows() - 1].descent_
537                 + hlinesep() * rowinfo_[nrows()].lines_
538                 + border();
539
540
541 /*
542         // Increase ws_[i] for 'R' columns (except the first one)
543         for (int i = 1; i < nc_; ++i)
544                 if (align_[i] == 'R')
545                         ws_[i] += 10 * df_width;
546         // Increase ws_[i] for 'C' column
547         if (align_[0] == 'C')
548                 if (ws_[0] < 7 * workwidth / 8)
549                         ws_[0] = 7 * workwidth / 8;
550
551         // Adjust local tabs
552         width = colsep();
553         for (cxrow = row_.begin(); cxrow; ++cxrow) {
554                 int rg = COLSEP;
555                 int lf = 0;
556                 for (int i = 0; i < nc_; ++i) {
557                         bool isvoid = false;
558                         if (cxrow->getTab(i) <= 0) {
559                                 cxrow->setTab(i, df_width);
560                                 isvoid = true;
561                         }
562                         switch (align_[i]) {
563                         case 'l':
564                                 lf = 0;
565                                 break;
566                         case 'c':
567                                 lf = (ws_[i] - cxrow->getTab(i))/2;
568                                 break;
569                         case 'r':
570                         case 'R':
571                                 lf = ws_[i] - cxrow->getTab(i);
572                                 break;
573                         case 'C':
574                                 if (cxrow == row_.begin())
575                                         lf = 0;
576                                 else if (cxrow.is_last())
577                                         lf = ws_[i] - cxrow->getTab(i);
578                                 else
579                                         lf = (ws_[i] - cxrow->getTab(i))/2;
580                                 break;
581                         }
582                         int const ww = (isvoid) ? lf : lf + cxrow->getTab(i);
583                         cxrow->setTab(i, lf + rg);
584                         rg = ws_[i] - ww + colsep();
585                         if (cxrow == row_.begin())
586                                 width += ws_[i] + colsep();
587                 }
588                 cxrow->setBaseline(cxrow->getBaseline() - ascent);
589         }
590 */
591         metricsMarkers2(dim);
592         // Cache the inset dimension.
593         setDimCache(mi, dim);
594 }
595
596
597 void InsetMathGrid::draw(PainterInfo & pi, int x, int y) const
598 {
599         drawWithMargin(pi, x, y, 1, 1);
600 }
601
602
603 void InsetMathGrid::drawWithMargin(PainterInfo & pi, int x, int y,
604         int lmargin, int rmargin) const
605 {
606         Dimension const dim = dimension(*pi.base.bv);
607         BufferView const & bv = *pi.base.bv;
608
609         for (idx_type idx = 0; idx < nargs(); ++idx) {
610                 if (cellinfo_[idx].multi_ != CELL_PART_OF_MULTICOLUMN) {
611                         cell(idx).draw(pi,
612                                 x + lmargin + cellXOffset(bv, idx),
613                                 y + cellYOffset(idx));
614
615                         // draw inner lines cell by cell because of possible multicolumns
616                         // FIXME: multicolumn lines are not yet considered
617                         row_type const r = row(idx);
618                         col_type const c = col(idx);
619                         if (r > 0 && r < nrows()) {
620                                 for (unsigned int i = 0; i < rowinfo_[r].lines_; ++i) {
621                                         int const yy = y + rowinfo_[r].offset_
622                                                 - rowinfo_[r].ascent_
623                                                 - i * hlinesep()
624                                                 - hlinesep()/2 - rowsep()/2;
625                                         int const xx1 = x + lmargin + colinfo_[c].offset_;
626                                         int const xx2 = (c + 1 == ncols()) ?
627                                                 // last column
628                                                 xx1 + colinfo_[c].width_ :
629                                                 // first columns
630                                                 x + lmargin + colinfo_[c+1].offset_;
631                                         pi.pain.line(xx1, yy, xx2, yy, Color_foreground);
632                                 }
633                         }
634                         if (c > 0 && c < ncols()) {
635                                 for (unsigned int i = 0; i < colinfo_[c].lines_; ++i) {
636                                         int const xx = x + lmargin
637                                                 + colinfo_[c].offset_
638                                                 - i * vlinesep()
639                                                 - vlinesep()/2 - colsep()/2;
640                                         int top_offset;
641                                         // prevRowHasLine needs to be changed if multicolumn lines are supported
642                                         bool const prevRowHasLine(r > 0);
643                                         if (prevRowHasLine)
644                                                 // start from offset of previous row to create a continous line
645                                                 top_offset = rowinfo_[r - 1].offset_ + rowinfo_[r - 1].descent_;
646                                         else
647                                                 top_offset = rowinfo_[r].offset_- rowinfo_[r].ascent_;
648                                         pi.pain.line(xx, y + top_offset,
649                                                 xx, y + rowinfo_[r].offset_ + rowinfo_[r].descent_,
650                                                 Color_foreground);
651                                 }
652                         }
653                 }
654         }
655
656         // draw outer lines in one go
657         for (row_type row = 0; row <= nrows(); row += nrows())
658                 for (unsigned int i = 0; i < rowinfo_[row].lines_; ++i) {
659                         int yy = y + rowinfo_[row].offset_ - rowinfo_[row].ascent_
660                                 - i * hlinesep() - hlinesep()/2 - rowsep()/2;
661                         pi.pain.line(x + lmargin + 1, yy,
662                                      x + dim.width() - rmargin - 1, yy,
663                                      Color_foreground);
664                 }
665
666         for (col_type col = 0; col <= ncols(); col += ncols())
667                 for (unsigned int i = 0; i < colinfo_[col].lines_; ++i) {
668                         int xx = x + lmargin + colinfo_[col].offset_
669                                 - i * vlinesep() - vlinesep()/2 - colsep()/2;
670                         pi.pain.line(xx, y - dim.ascent() + 1,
671                                      xx, y + dim.descent() - 1,
672                                      Color_foreground);
673                 }
674         drawMarkers2(pi, x, y);
675 }
676
677
678 void InsetMathGrid::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
679 {
680         // let the cells adjust themselves
681         for (idx_type i = 0; i < nargs(); ++i)
682                 if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN)
683                         cell(i).metricsT(mi, dim);
684
685         // compute absolute sizes of vertical structure
686         for (row_type row = 0; row < nrows(); ++row) {
687                 int asc  = 0;
688                 int desc = 0;
689                 for (col_type col = 0; col < ncols(); ++col) {
690                         idx_type const i = index(row, col);
691                         if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
692                                 //MathData const & c = cell(i);
693                                 // FIXME: BROKEN!
694                                 Dimension dimc;
695                                 asc  = max(asc,  dimc.ascent());
696                                 desc = max(desc, dimc.descent());
697                         }
698                 }
699                 rowinfo_[row].ascent_  = asc;
700                 rowinfo_[row].descent_ = desc;
701         }
702         //rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
703         rowinfo_[nrows()].ascent_  = 0;
704         rowinfo_[nrows()].descent_ = 0;
705
706         // compute vertical offsets
707         rowinfo_[0].offset_ = 0;
708         for (row_type row = 1; row <= nrows(); ++row) {
709                 rowinfo_[row].offset_  =
710                         rowinfo_[row - 1].offset_  +
711                         rowinfo_[row - 1].descent_ +
712                         //rowinfo_[row - 1].skipPixels(mi) +
713                         1 + //rowsep() +
714                         //rowinfo_[row].lines_ * hlinesep() +
715                         rowinfo_[row].ascent_;
716         }
717
718         // adjust vertical offset
719         int h = 0;
720         switch (v_align_) {
721                 case 't':
722                         h = 0;
723                         break;
724                 case 'b':
725                         h = rowinfo_[nrows() - 1].offset_;
726                         break;
727                 default:
728                         h = rowinfo_[nrows() - 1].offset_ / 2;
729         }
730         for (row_type row = 0; row <= nrows(); ++row)
731                 rowinfo_[row].offset_ -= h;
732
733
734         // compute absolute sizes of horizontal structure
735         for (col_type col = 0; col < ncols(); ++col) {
736                 int wid = 0;
737                 for (row_type row = 0; row < nrows(); ++row) {
738                         // FIXME: BROKEN!
739                         //idx_type const i = index(row, col);
740                         //if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN)
741                         //      wid = max(wid, cell(i).width());
742                 }
743                 colinfo_[col].width_ = wid;
744         }
745         colinfo_[ncols()].width_  = 0;
746
747         // compute horizontal offsets
748         colinfo_[0].offset_ = border();
749         for (col_type col = 1; col <= ncols(); ++col) {
750                 colinfo_[col].offset_ =
751                         colinfo_[col - 1].offset_ +
752                         colinfo_[col - 1].width_ +
753                         displayColSpace(col - 1) +
754                         1 ; //colsep() +
755                         //colinfo_[col].lines_ * vlinesep();
756         }
757
758
759         dim.wid  =  colinfo_[ncols() - 1].offset_
760                        + colinfo_[ncols() - 1].width_
761                  //+ vlinesep() * colinfo_[ncols()].lines_
762                        + 2;
763
764         dim.asc  = -rowinfo_[0].offset_
765                        + rowinfo_[0].ascent_
766                  //+ hlinesep() * rowinfo_[0].lines_
767                        + 1;
768
769         dim.des  =  rowinfo_[nrows() - 1].offset_
770                        + rowinfo_[nrows() - 1].descent_
771                  //+ hlinesep() * rowinfo_[nrows()].lines_
772                        + 1;
773 }
774
775
776 void InsetMathGrid::drawT(TextPainter & /*pain*/, int /*x*/, int /*y*/) const
777 {
778 //      for (idx_type idx = 0; idx < nargs(); ++idx)
779 //              if (cellinfo_[idx].multi_ != CELL_PART_OF_MULTICOLUMN)
780 //                      cell(idx).drawT(pain, x + cellXOffset(idx), y + cellYOffset(idx));
781 }
782
783
784 void InsetMathGrid::updateBuffer(ParIterator const & it, UpdateType utype)
785 {
786         // pass down
787         for (idx_type idx = 0; idx < nargs(); ++idx)
788                 if (cellinfo_[idx].multi_ != CELL_PART_OF_MULTICOLUMN)
789                         cell(idx).updateBuffer(it, utype);
790 }
791
792
793 docstring InsetMathGrid::eolString(row_type row, bool fragile,
794                 bool /*latex*/, bool last_eoln) const
795 {
796         docstring eol;
797
798         if (!rowinfo_[row].crskip_.zero())
799                 eol += '[' + from_utf8(rowinfo_[row].crskip_.asLatexString()) + ']';
800         else if(!rowinfo_[row].allow_newpage_)
801                 eol += '*';
802
803         // make sure an upcoming '[' does not break anything
804         if (row + 1 < nrows()) {
805                 MathData const & c = cell(index(row + 1, 0));
806                 if (!c.empty() && c.front()->getChar() == '[')
807                         //eol += "[0pt]";
808                         eol += "{}";
809         }
810
811         // only add \\ if necessary
812         if (eol.empty() && row + 1 == nrows() && (nrows() == 1 || !last_eoln))
813                 return docstring();
814
815         return (fragile ? "\\protect\\\\" : "\\\\") + eol;
816 }
817
818
819 docstring InsetMathGrid::eocString(col_type col, col_type lastcol) const
820 {
821         if (col + 1 == lastcol)
822                 return docstring();
823         return from_ascii(" & ");
824 }
825
826
827 void InsetMathGrid::addRow(row_type row)
828 {
829         rowinfo_.insert(rowinfo_.begin() + row + 1, RowInfo());
830         cells_.insert
831                 (cells_.begin() + (row + 1) * ncols(), ncols(), MathData());
832         cellinfo_.insert
833                 (cellinfo_.begin() + (row + 1) * ncols(), ncols(), CellInfo());
834 }
835
836
837 void InsetMathGrid::delRow(row_type row)
838 {
839         if (nrows() == 1)
840                 return;
841
842         cells_type::iterator it = cells_.begin() + row * ncols();
843         cells_.erase(it, it + ncols());
844
845         vector<CellInfo>::iterator jt = cellinfo_.begin() + row * ncols();
846         cellinfo_.erase(jt, jt + ncols());
847
848         rowinfo_.erase(rowinfo_.begin() + row);
849 }
850
851
852 void InsetMathGrid::copyRow(row_type row)
853 {
854         addRow(row);
855         for (col_type col = 0; col < ncols(); ++col)
856                 cells_[(row + 1) * ncols() + col] = cells_[row * ncols() + col];
857 }
858
859
860 void InsetMathGrid::swapRow(row_type row)
861 {
862         if (nrows() == 1)
863                 return;
864         if (row + 1 == nrows())
865                 --row;
866         for (col_type col = 0; col < ncols(); ++col)
867                 swap(cells_[row * ncols() + col], cells_[(row + 1) * ncols() + col]);
868 }
869
870
871 void InsetMathGrid::addCol(col_type newcol)
872 {
873         const col_type nc = ncols();
874         const row_type nr = nrows();
875         cells_type new_cells((nc + 1) * nr);
876         vector<CellInfo> new_cellinfo((nc + 1) * nr);
877
878         for (row_type row = 0; row < nr; ++row)
879                 for (col_type col = 0; col < nc; ++col) {
880                         new_cells[row * (nc + 1) + col + (col >= newcol)]
881                                 = cells_[row * nc + col];
882                         new_cellinfo[row * (nc + 1) + col + (col >= newcol)]
883                                 = cellinfo_[row * nc + col];
884                 }
885         swap(cells_, new_cells);
886         swap(cellinfo_, new_cellinfo);
887
888         ColInfo inf;
889         inf.skip_  = defaultColSpace(newcol);
890         inf.align_ = defaultColAlign(newcol);
891         colinfo_.insert(colinfo_.begin() + newcol, inf);
892 }
893
894
895 void InsetMathGrid::delCol(col_type col)
896 {
897         if (ncols() == 1)
898                 return;
899
900         cells_type tmpcells;
901         vector<CellInfo> tmpcellinfo;
902         for (col_type i = 0; i < nargs(); ++i)
903                 if (i % ncols() != col) {
904                         tmpcells.push_back(cells_[i]);
905                         tmpcellinfo.push_back(cellinfo_[i]);
906                 }
907         swap(cells_, tmpcells);
908         swap(cellinfo_, tmpcellinfo);
909
910         colinfo_.erase(colinfo_.begin() + col);
911 }
912
913
914 void InsetMathGrid::copyCol(col_type col)
915 {
916         addCol(col+1);
917         for (row_type row = 0; row < nrows(); ++row)
918                 cells_[row * ncols() + col + 1] = cells_[row * ncols() + col];
919 }
920
921
922 void InsetMathGrid::swapCol(col_type col)
923 {
924         if (ncols() == 1)
925                 return;
926         if (col + 1 == ncols())
927                 --col;
928         for (row_type row = 0; row < nrows(); ++row)
929                 swap(cells_[row * ncols() + col], cells_[row * ncols() + col + 1]);
930 }
931
932
933 int InsetMathGrid::cellXOffset(BufferView const & bv, idx_type idx) const
934 {
935         if (cellinfo_[idx].multi_ == CELL_PART_OF_MULTICOLUMN)
936                 return 0;
937         col_type c = col(idx);
938         int x = colinfo_[c].offset_;
939         char align = displayColAlign(idx);
940         Dimension const & celldim = cell(idx).dimension(bv);
941         if (align == 'r' || align == 'R')
942                 x += cellWidth(idx) - celldim.wid;
943         if (align == 'c' || align == 'C')
944                 x += (cellWidth(idx) - celldim.wid) / 2;
945         return x;
946 }
947
948
949 int InsetMathGrid::cellYOffset(idx_type idx) const
950 {
951         return rowinfo_[row(idx)].offset_;
952 }
953
954
955 int InsetMathGrid::cellWidth(idx_type idx) const
956 {
957         switch (cellinfo_[idx].multi_) {
958         case CELL_NORMAL:
959                 return colinfo_[col(idx)].width_;
960         case CELL_BEGIN_OF_MULTICOLUMN: {
961                 col_type c1 = col(idx);
962                 col_type c2 = c1 + ncellcols(idx);
963                 return colinfo_[c2].offset_
964                         - colinfo_[c1].offset_
965                         - displayColSpace(c2)
966                         - colsep()
967                         - colinfo_[c2].lines_ * vlinesep();
968         }
969         case CELL_PART_OF_MULTICOLUMN:
970                 return 0;
971         }
972         return 0;
973 }
974
975
976 bool InsetMathGrid::idxUpDown(Cursor & cur, bool up) const
977 {
978         if (up) {
979                 if (cur.row() == 0)
980                         return false;
981                 cur.idx() -= ncols();
982         } else {
983                 if (cur.row() + 1 >= nrows())
984                         return false;
985                 cur.idx() += ncols();
986         }
987         // If we are in a multicolumn cell, move to the "real" cell
988         while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
989                 LASSERT(cur.idx() > 0, return false);
990                 --cur.idx();
991         }
992         cur.pos() = cur.cell().x2pos(&cur.bv(), cur.x_target() - cur.cell().xo(cur.bv()));
993         return true;
994 }
995
996
997 bool InsetMathGrid::idxBackward(Cursor & cur) const
998 {
999         // leave matrix if at the front edge
1000         if (cur.col() == 0)
1001                 return false;
1002         --cur.idx();
1003         // If we are in a multicolumn cell, move to the "real" cell
1004         while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
1005                 LASSERT(cur.idx() > 0, return false);
1006                 --cur.idx();
1007         }
1008         cur.pos() = cur.lastpos();
1009         return true;
1010 }
1011
1012
1013 bool InsetMathGrid::idxForward(Cursor & cur) const
1014 {
1015         // leave matrix if at the back edge
1016         if (cur.col() + 1 == ncols())
1017                 return false;
1018         ++cur.idx();
1019         // If we are in a multicolumn cell, move to the next cell
1020         while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
1021                 // leave matrix if at the back edge
1022                 if (cur.col() + 1 == ncols())
1023                         return false;
1024                 ++cur.idx();
1025         }
1026         cur.pos() = 0;
1027         return true;
1028 }
1029
1030
1031 bool InsetMathGrid::idxFirst(Cursor & cur) const
1032 {
1033         switch (v_align_) {
1034                 case 't':
1035                         cur.idx() = 0;
1036                         break;
1037                 case 'b':
1038                         cur.idx() = (nrows() - 1) * ncols();
1039                         break;
1040                 default:
1041                         cur.idx() = ((nrows() - 1) / 2) * ncols();
1042         }
1043         // If we are in a multicolumn cell, move to the "real" cell
1044         while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
1045                 LASSERT(cur.idx() > 0, return false);
1046                 --cur.idx();
1047         }
1048         cur.pos() = 0;
1049         return true;
1050 }
1051
1052
1053 bool InsetMathGrid::idxLast(Cursor & cur) const
1054 {
1055         switch (v_align_) {
1056                 case 't':
1057                         cur.idx() = ncols() - 1;
1058                         break;
1059                 case 'b':
1060                         cur.idx() = nargs() - 1;
1061                         break;
1062                 default:
1063                         cur.idx() = ((nrows() - 1) / 2 + 1) * ncols() - 1;
1064         }
1065         // If we are in a multicolumn cell, move to the "real" cell
1066         while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
1067                 LASSERT(cur.idx() > 0, return false);
1068                 --cur.idx();
1069         }
1070         cur.pos() = cur.lastpos();
1071         return true;
1072 }
1073
1074
1075 bool InsetMathGrid::idxDelete(idx_type & idx)
1076 {
1077         // nothing to do if we have just one row
1078         if (nrows() == 1)
1079                 return false;
1080
1081         // nothing to do if we are in the middle of the last row of the inset
1082         if (idx + ncols() > nargs())
1083                 return false;
1084
1085         // try to delete entire sequence of ncols() empty cells if possible
1086         for (idx_type i = idx; i < idx + ncols(); ++i)
1087                 if (!cell(i).empty())
1088                         return false;
1089
1090         // move cells if necessary
1091         for (idx_type i = index(row(idx), 0); i < idx; ++i)
1092                 swap(cell(i), cell(i + ncols()));
1093
1094         delRow(row(idx));
1095
1096         if (idx >= nargs())
1097                 idx = nargs() - 1;
1098
1099         // undo effect of Ctrl-Tab (i.e. pull next cell)
1100         //if (idx + 1 != nargs())
1101         //      cell(idx).swap(cell(idx + 1));
1102
1103         // we handled the event..
1104         return true;
1105 }
1106
1107
1108 // reimplement old behaviour when pressing Delete in the last position
1109 // of a cell
1110 void InsetMathGrid::idxGlue(idx_type idx)
1111 {
1112         col_type c = col(idx);
1113         if (c + 1 == ncols()) {
1114                 if (row(idx) + 1 != nrows()) {
1115                         for (col_type cc = 0; cc < ncols(); ++cc)
1116                                 cell(idx).append(cell(idx + cc + 1));
1117                         delRow(row(idx) + 1);
1118                 }
1119         } else {
1120                 idx_type idx_next = idx + 1;
1121                 while (idx_next < nargs() &&
1122                        cellinfo_[idx_next].multi_ == CELL_PART_OF_MULTICOLUMN)
1123                         ++idx_next;
1124                 if (idx_next < nargs())
1125                         cell(idx).append(cell(idx_next));
1126                 col_type oldcol = c + 1;
1127                 for (col_type cc = c + 2; cc < ncols(); ++cc)
1128                         cell(idx - oldcol + cc) = cell(idx - oldcol + 1 + cc);
1129                 cell(idx - c + ncols() - 1).clear();
1130         }
1131 }
1132
1133
1134 InsetMathGrid::RowInfo const & InsetMathGrid::rowinfo(row_type row) const
1135 {
1136         return rowinfo_[row];
1137 }
1138
1139
1140 InsetMathGrid::RowInfo & InsetMathGrid::rowinfo(row_type row)
1141 {
1142         return rowinfo_[row];
1143 }
1144
1145
1146 bool InsetMathGrid::idxBetween(idx_type idx, idx_type from, idx_type to) const
1147 {
1148         row_type const ri = row(idx);
1149         row_type const r1 = min(row(from), row(to));
1150         row_type const r2 = max(row(from), row(to));
1151         col_type const ci = col(idx);
1152         col_type const c1 = min(col(from), col(to));
1153         col_type const c2 = max(col(from), col(to));
1154         return r1 <= ri && ri <= r2 && c1 <= ci && ci <= c2;
1155 }
1156
1157
1158 void InsetMathGrid::normalize(NormalStream & os) const
1159 {
1160         os << "[grid ";
1161         for (row_type row = 0; row < nrows(); ++row) {
1162                 os << "[row ";
1163                 for (col_type col = 0; col < ncols(); ++col) {
1164                         idx_type const i = index(row, col);
1165                         switch (cellinfo_[i].multi_) {
1166                         case CELL_NORMAL:
1167                                 os << "[cell " << cell(i) << ']';
1168                                 break;
1169                         case CELL_BEGIN_OF_MULTICOLUMN:
1170                                 os << "[cell colspan="
1171                                    << static_cast<int>(ncellcols(i)) << ' '
1172                                    << cell(i) << ']';
1173                                 break;
1174                         case CELL_PART_OF_MULTICOLUMN:
1175                                 break;
1176                         }
1177                 }
1178                 os << ']';
1179         }
1180         os << ']';
1181 }
1182
1183
1184 void InsetMathGrid::mathmlize(MathStream & os) const
1185 {
1186         bool const havetable = nrows() > 1 || ncols() > 1;
1187         if (havetable)
1188                 os << MTag("mtable");
1189         char const * const celltag = havetable ? "mtd" : "mrow";
1190         for (row_type row = 0; row < nrows(); ++row) {
1191                 if (havetable)
1192                         os << MTag("mtr");
1193                 for (col_type col = 0; col < ncols(); ++col) {
1194                         idx_type const i = index(row, col);
1195                         if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
1196                                 col_type const cellcols = ncellcols(i);
1197                                 ostringstream attr;
1198                                 if (havetable && cellcols > 1)
1199                                         attr << "colspan='" << cellcols << '\'';
1200                                 os << MTag(celltag, attr.str());
1201                                 os << cell(index(row, col));
1202                                 os << ETag(celltag);
1203                         }
1204                 }
1205                 if (havetable)
1206                         os << ETag("mtr");
1207         }
1208         if (havetable)
1209                 os << ETag("mtable");
1210 }
1211
1212
1213 // FIXME XHTML
1214 // We need to do something about alignment here.
1215 void InsetMathGrid::htmlize(HtmlStream & os, string attrib) const
1216 {
1217         bool const havetable = nrows() > 1 || ncols() > 1;
1218         if (!havetable) {
1219                 os << cell(index(0, 0));
1220                 return;
1221         }
1222         os << MTag("table", attrib);
1223         for (row_type row = 0; row < nrows(); ++row) {
1224                 os << MTag("tr");
1225                 for (col_type col = 0; col < ncols(); ++col) {
1226                         idx_type const i = index(row, col);
1227                         if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
1228                                 col_type const cellcols = ncellcols(i);
1229                                 ostringstream attr;
1230                                 if (cellcols > 1)
1231                                         attr << "colspan='" << cellcols << '\'';
1232                                 os << MTag("td", attr.str());
1233                                 os << cell(index(row, col));
1234                                 os << ETag("td");
1235                         }
1236                 }
1237                 os << ETag("tr");
1238         }
1239         os << ETag("table");
1240 }
1241
1242
1243 void InsetMathGrid::htmlize(HtmlStream & os) const
1244 {
1245         htmlize(os, "class='mathtable'");
1246 }
1247
1248
1249 void InsetMathGrid::validate(LaTeXFeatures & features) const
1250 {
1251         if (features.runparams().math_flavor == OutputParams::MathAsHTML
1252             && (nrows() > 1 || ncols() > 1)) {
1253                 // CSS taken from InsetMathCases
1254                 features.addCSSSnippet(
1255                         "table.mathtable{display: inline-block; text-align: center; border: none;"
1256                         "border-left: thin solid black; vertical-align: middle; padding-left: 0.5ex;}\n"
1257                         "table.mathtable td {text-align: left; border: none;}");
1258         }
1259         InsetMathNest::validate(features);
1260 }
1261
1262
1263 void InsetMathGrid::write(WriteStream & os) const
1264 {
1265         write(os, 0, 0, nrows(), ncols());
1266 }
1267
1268 void InsetMathGrid::write(WriteStream & os,
1269                           row_type beg_row, col_type beg_col,
1270                           row_type end_row, col_type end_col) const
1271 {
1272         MathEnsurer ensurer(os, false);
1273         docstring eol;
1274         for (row_type row = beg_row; row < end_row; ++row) {
1275                 os << verboseHLine(rowinfo_[row].lines_);
1276                 // don't write & and empty cells at end of line,
1277                 // unless there are vertical lines
1278                 col_type lastcol = 0;
1279                 bool emptyline = true;
1280                 bool last_eoln = true;
1281                 for (col_type col = beg_col; col < end_col; ++col) {
1282                         idx_type const idx = index(row, col);
1283                         bool const empty_cell = cell(idx).empty();
1284                         if (!empty_cell || cellinfo_[idx].multi_ != CELL_NORMAL)
1285                                 last_eoln = false;
1286                         if (!empty_cell || cellinfo_[idx].multi_ != CELL_NORMAL ||
1287                             colinfo_[col + 1].lines_) {
1288                                 lastcol = col + 1;
1289                                 emptyline = false;
1290                         }
1291                 }
1292                 for (col_type col = beg_col; col < end_col;) {
1293                         int nccols = 1;
1294                         idx_type const idx = index(row, col);
1295                         RowEntry entry = TexRow::mathEntry(id(),idx);
1296                         os.texrow().start(entry);
1297                         if (col >= lastcol) {
1298                                 ++col;
1299                                 continue;
1300                         }
1301                         Changer dummy = os.changeRowEntry(entry);
1302                         if (cellinfo_[idx].multi_ == CELL_BEGIN_OF_MULTICOLUMN) {
1303                                 size_t s = col + 1;
1304                                 while (s < ncols() &&
1305                                        cellinfo_[index(row, s)].multi_ == CELL_PART_OF_MULTICOLUMN)
1306                                         s++;
1307                                 nccols = s - col;
1308                                 os << "\\multicolumn{" << nccols
1309                                    << "}{" << cellinfo_[idx].align_
1310                                    << "}{";
1311                         }
1312                         os << cell(idx);
1313                         if (os.pendingBrace())
1314                                 ModeSpecifier specifier(os, TEXT_MODE);
1315                         if (cellinfo_[idx].multi_ == CELL_BEGIN_OF_MULTICOLUMN)
1316                                 os << '}';
1317                         os << eocString(col + nccols - 1, lastcol);
1318                         col += nccols;
1319                 }
1320                 eol = eolString(row, os.fragile(), os.latex(), last_eoln);
1321                 os << eol;
1322                 // append newline only if line wasn't completely empty
1323                 // and the formula is not written on a single line
1324                 bool const empty = emptyline && eol.empty();
1325                 if (!empty && nrows() > 1)
1326                         os << "\n";
1327         }
1328         // @TODO use end_row instead of nrows() ?
1329         docstring const s = verboseHLine(rowinfo_[nrows()].lines_);
1330         if (!s.empty()) {
1331                 if (eol.empty()) {
1332                         if (os.fragile())
1333                                 os << "\\protect";
1334                         os << "\\\\";
1335                 }
1336                 os << s;
1337         }
1338 }
1339
1340
1341 int InsetMathGrid::colsep() const
1342 {
1343         return 6;
1344 }
1345
1346
1347 int InsetMathGrid::rowsep() const
1348 {
1349         return 6;
1350 }
1351
1352
1353 int InsetMathGrid::hlinesep() const
1354 {
1355         return 3;
1356 }
1357
1358
1359 int InsetMathGrid::vlinesep() const
1360 {
1361         return 3;
1362 }
1363
1364
1365 int InsetMathGrid::border() const
1366 {
1367         return 1;
1368 }
1369
1370
1371 void InsetMathGrid::splitCell(Cursor & cur)
1372 {
1373         if (cur.idx() == cur.lastidx())
1374                 return;
1375         MathData ar = cur.cell();
1376         ar.erase(0, cur.pos());
1377         cur.cell().erase(cur.pos(), cur.lastpos());
1378         ++cur.idx();
1379         while (cur.idx() << nargs() &&
1380                cellinfo_[cur.idx()].multi_ == CELL_BEGIN_OF_MULTICOLUMN)
1381                 ++cur.idx();
1382         cur.pos() = 0;
1383         cur.cell().insert(0, ar);
1384 }
1385
1386
1387 char InsetMathGrid::displayColAlign(idx_type idx) const
1388 {
1389         if (cellinfo_[idx].multi_ == CELL_BEGIN_OF_MULTICOLUMN) {
1390                 // align_ may also contain lines like "||r|", so this is
1391                 // not complete, but we catch at least the simple cases.
1392                 if (cellinfo_[idx].align_ == "c")
1393                         return 'c';
1394                 if (cellinfo_[idx].align_ == "l")
1395                         return 'l';
1396                 if (cellinfo_[idx].align_ == "r")
1397                         return 'r';
1398         }
1399         return colinfo_[col(idx)].align_;
1400 }
1401
1402
1403 int InsetMathGrid::displayColSpace(col_type col) const
1404 {
1405         return colinfo_[col].skip_;
1406 }
1407
1408 void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
1409 {
1410         //lyxerr << "*** InsetMathGrid: request: " << cmd << endl;
1411
1412         Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
1413
1414         FuncCode const act = cmd.action();
1415         switch (act) {
1416
1417         // insert file functions
1418         case LFUN_LINE_DELETE_FORWARD:
1419                 cur.recordUndoInset();
1420                 //autocorrect_ = false;
1421                 //macroModeClose();
1422                 //if (selection_) {
1423                 //      selDel();
1424                 //      break;
1425                 //}
1426                 if (nrows() > 1)
1427                         delRow(cur.row());
1428                 if (cur.idx() > cur.lastidx())
1429                         cur.idx() = cur.lastidx();
1430                 if (cur.pos() > cur.lastpos())
1431                         cur.pos() = cur.lastpos();
1432                 break;
1433
1434         case LFUN_CELL_SPLIT:
1435                 cur.recordUndo();
1436                 splitCell(cur);
1437                 break;
1438
1439         case LFUN_CELL_BACKWARD:
1440                 // See below.
1441                 cur.selection(false);
1442                 if (!idxPrev(cur)) {
1443                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1444                         cur.undispatched();
1445                 }
1446                 break;
1447
1448         case LFUN_CELL_FORWARD:
1449                 // Can't handle selection by additional 'shift' as this is
1450                 // hard bound to LFUN_CELL_BACKWARD
1451                 cur.selection(false);
1452                 if (!idxNext(cur)) {
1453                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1454                         cur.undispatched();
1455                 }
1456                 break;
1457
1458         case LFUN_NEWLINE_INSERT: {
1459                 cur.recordUndoInset();
1460                 row_type const r = cur.row();
1461                 addRow(r);
1462
1463                 // split line
1464                 for (col_type c = col(cur.idx()) + 1; c < ncols(); ++c)
1465                         swap(cell(index(r, c)), cell(index(r + 1, c)));
1466
1467                 // split cell
1468                 splitCell(cur);
1469                 if (ncols() > 1)
1470                         swap(cell(cur.idx()), cell(cur.idx() + ncols() - 1));
1471                 if (cur.idx() > 0)
1472                         --cur.idx();
1473                 cur.pos() = cur.lastpos();
1474                 cur.forceBufferUpdate();
1475                 //mathcursor->normalize();
1476                 //cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1477                 break;
1478         }
1479
1480         case LFUN_TABULAR_FEATURE: {
1481                 cur.recordUndoInset();
1482                 //lyxerr << "handling tabular-feature " << to_utf8(cmd.argument()) << endl;
1483                 istringstream is(to_utf8(cmd.argument()));
1484                 string s;
1485                 is >> s;
1486                 if (s == "valign-top")
1487                         setVerticalAlignment('t');
1488                 else if (s == "valign-middle")
1489                         setVerticalAlignment('c');
1490                 else if (s == "valign-bottom")
1491                         setVerticalAlignment('b');
1492                 else if (s == "align-left")
1493                         setHorizontalAlignment('l', cur.col());
1494                 else if (s == "align-right")
1495                         setHorizontalAlignment('r', cur.col());
1496                 else if (s == "align-center")
1497                         setHorizontalAlignment('c', cur.col());
1498                 else if (s == "append-row")
1499                         for (int i = 0, n = extractInt(is); i < n; ++i)
1500                                 addRow(cur.row());
1501                 else if (s == "delete-row") {
1502                         cur.clearSelection(); // bug 4323
1503                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1504                                 delRow(cur.row());
1505                                 if (cur.idx() >= nargs())
1506                                         cur.idx() -= ncols();
1507                         }
1508                         cur.pos() = 0; // trick, see below
1509                 }
1510                 else if (s == "copy-row") {
1511                         // Here (as later) we save the cursor col/row
1512                         // in order to restore it after operation.
1513                         row_type const r = cur.row();
1514                         col_type const c = cur.col();
1515                         for (int i = 0, n = extractInt(is); i < n; ++i)
1516                                 copyRow(cur.row());
1517                         cur.idx() = index(r, c);
1518                 }
1519                 else if (s == "swap-row") {
1520                         swapRow(cur.row());
1521                         // Trick to suppress same-idx-means-different-cell
1522                         // assertion crash:
1523                         cur.pos() = 0;
1524                 }
1525                 else if (s == "add-hline-above")
1526                         rowinfo_[cur.row()].lines_++;
1527                 else if (s == "add-hline-below")
1528                         rowinfo_[cur.row()+1].lines_++;
1529                 else if (s == "delete-hline-above")
1530                         rowinfo_[cur.row()].lines_--;
1531                 else if (s == "delete-hline-below")
1532                         rowinfo_[cur.row()+1].lines_--;
1533                 else if (s == "append-column") {
1534                         row_type const r = cur.row();
1535                         col_type const c = cur.col();
1536                         for (int i = 0, n = extractInt(is); i < n; ++i)
1537                                 addCol(cur.col() + 1);
1538                         cur.idx() = index(r, c);
1539                 }
1540                 else if (s == "delete-column") {
1541                         cur.clearSelection(); // bug 4323
1542                         row_type const r = cur.row();
1543                         col_type const c = cur.col();
1544                         for (int i = 0, n = extractInt(is); i < n; ++i)
1545                                 delCol(col(cur.idx()));
1546                         cur.idx() = index(r, min(c, cur.ncols() - 1));
1547                         cur.pos() = 0; // trick, see above
1548                 }
1549                 else if (s == "copy-column") {
1550                         row_type const r = cur.row();
1551                         col_type const c = cur.col();
1552                         copyCol(cur.col());
1553                         cur.idx() = index(r, c);
1554                 }
1555                 else if (s == "swap-column") {
1556                         swapCol(cur.col());
1557                         cur.pos() = 0; // trick, see above
1558                 }
1559                 else if (s == "add-vline-left") {
1560                         colinfo_[cur.col()].lines_++;
1561                         if (!colinfo_[cur.col()].special_.empty())
1562                                 colinfo_[cur.col()].special_ += '|';
1563                 }
1564                 else if (s == "add-vline-right") {
1565                         colinfo_[cur.col()+1].lines_++;
1566                         if (!colinfo_[cur.col()+1].special_.empty())
1567                                 colinfo_[cur.col()+1].special_.insert(0, 1, '|');
1568                 }
1569                 else if (s == "delete-vline-left") {
1570                         colinfo_[cur.col()].lines_--;
1571                         docstring & special = colinfo_[cur.col()].special_;
1572                         if (!special.empty()) {
1573                                 docstring::size_type i = special.rfind('|');
1574                                 LASSERT(i != docstring::npos, break);
1575                                 special.erase(i, 1);
1576                         }
1577                 }
1578                 else if (s == "delete-vline-right") {
1579                         colinfo_[cur.col()+1].lines_--;
1580                         docstring & special = colinfo_[cur.col()+1].special_;
1581                         if (!special.empty()) {
1582                                 docstring::size_type i = special.find('|');
1583                                 LASSERT(i != docstring::npos, break);
1584                                 special.erase(i, 1);
1585                         }
1586                 }
1587                 else {
1588                         cur.undispatched();
1589                         break;
1590                 }
1591                 // perhaps this should be FINISHED_BACKWARD -- just for clarity?
1592                 //lyxerr << "returning FINISHED_LEFT" << endl;
1593                 break;
1594         }
1595
1596         case LFUN_CLIPBOARD_PASTE:
1597                 parseflg |= Parse::VERBATIM;
1598                 // fall through
1599         case LFUN_PASTE: {
1600                 if (cur.currentMode() <= TEXT_MODE)
1601                         parseflg |= Parse::TEXTMODE;
1602                 cur.message(_("Paste"));
1603                 cap::replaceSelection(cur);
1604                 docstring topaste;
1605                 if (cmd.argument().empty() && !theClipboard().isInternal())
1606                         topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
1607                 else {
1608                         idocstringstream is(cmd.argument());
1609                         int n = 0;
1610                         is >> n;
1611                         topaste = cap::selection(n, buffer().params().documentClassPtr());
1612                 }
1613                 InsetMathGrid grid(buffer_, 1, 1);
1614                 if (!topaste.empty())
1615                         if ((topaste.size() == 1 && isAscii(topaste))
1616                             || !mathed_parse_normal(grid, topaste, parseflg)) {
1617                                 resetGrid(grid);
1618                                 mathed_parse_normal(grid, topaste, parseflg | Parse::VERBATIM);
1619                         }
1620
1621                 bool hline_enabled = false;
1622                 FuncRequest fr = FuncRequest(LFUN_TABULAR_FEATURE, "add-hline-above");
1623                 FuncStatus status;
1624                 if (getStatus(cur, fr, status))
1625                         hline_enabled = status.enabled();
1626                 if (grid.nargs() == 1) {
1627                         // single cell/part of cell
1628                         cur.recordUndoInset();
1629                         cur.cell().insert(cur.pos(), grid.cell(0));
1630                         cur.pos() += grid.cell(0).size();
1631                         if (hline_enabled)
1632                                 rowinfo_[cur.row()].lines_ += grid.rowinfo_[0].lines_;
1633                         else {
1634                                 for (unsigned int l = 0; l < grid.rowinfo_[0].lines_; ++l) {
1635                                          cur.cell().insert(0,
1636                                                 MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
1637                                          cur.pos()++;
1638                                 }
1639                         }
1640                 } else {
1641                         // multiple cells
1642                         cur.recordUndoInset();
1643                         col_type const numcols =
1644                                 min(grid.ncols(), ncols() - col(cur.idx()));
1645                         row_type const numrows =
1646                                 min(grid.nrows(), nrows() - cur.row());
1647                         for (row_type r = 0; r < numrows; ++r) {
1648                                 for (col_type c = 0; c < numcols; ++c) {
1649                                         idx_type i = index(r + cur.row(), c + col(cur.idx()));
1650                                         cell(i).insert(0, grid.cell(grid.index(r, c)));
1651                                 }
1652                                 if (hline_enabled)
1653                                         rowinfo_[r].lines_ += grid.rowinfo_[r].lines_;
1654                                 else {
1655                                         for (unsigned int l = 0; l < grid.rowinfo_[r].lines_; ++l) {
1656                                                 idx_type i = index(r + cur.row(), 0);
1657                                                 cell(i).insert(0,
1658                                                         MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
1659                                         }
1660                                 }
1661                                 // append the left over horizontal cells to the last column
1662                                 idx_type i = index(r + cur.row(), ncols() - 1);
1663                                 for (InsetMath::col_type c = numcols; c < grid.ncols(); ++c)
1664                                         cell(i).append(grid.cell(grid.index(r, c)));
1665                         }
1666                         // append the left over vertical cells to the last _cell_
1667                         idx_type i = nargs() - 1;
1668                         for (row_type r = numrows; r < grid.nrows(); ++r) {
1669                                 for (col_type c = 0; c < grid.ncols(); ++c)
1670                                         cell(i).append(grid.cell(grid.index(r, c)));
1671                                 if (hline_enabled)
1672                                         rowinfo_[r].lines_ += grid.rowinfo_[r].lines_;
1673                                 else {
1674                                         for (unsigned int l = 0; l < grid.rowinfo_[r].lines_; ++l) {
1675                                                 cell(i).insert(0,
1676                                                         MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
1677                                         }
1678                                 }
1679                         }
1680                 }
1681                 cur.clearSelection(); // bug 393
1682                 // FIXME audit setBuffer calls
1683                 cur.inset().setBuffer(*buffer_);
1684                 cur.forceBufferUpdate();
1685                 cur.finishUndo();
1686                 break;
1687         }
1688
1689         case LFUN_LINE_BEGIN:
1690         case LFUN_WORD_BACKWARD:
1691         case LFUN_WORD_LEFT:
1692                 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
1693                 // fall through
1694         case LFUN_LINE_BEGIN_SELECT:
1695         case LFUN_WORD_BACKWARD_SELECT:
1696         case LFUN_WORD_LEFT_SELECT:
1697                 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
1698                                 act == LFUN_WORD_LEFT_SELECT ||
1699                                 act == LFUN_LINE_BEGIN_SELECT);
1700                 cur.macroModeClose();
1701                 if (cur.pos() != 0) {
1702                         cur.pos() = 0;
1703                 } else if (cur.idx() % cur.ncols() != 0) {
1704                         cur.idx() -= cur.idx() % cur.ncols();
1705                         cur.pos() = 0;
1706                 } else if (cur.idx() != 0) {
1707                         cur.idx() = 0;
1708                         cur.pos() = 0;
1709                 } else {
1710                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1711                         cur.undispatched();
1712                 }
1713                 break;
1714
1715         case LFUN_WORD_FORWARD:
1716         case LFUN_WORD_RIGHT:
1717         case LFUN_LINE_END:
1718                 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
1719                 // fall through
1720         case LFUN_WORD_FORWARD_SELECT:
1721         case LFUN_WORD_RIGHT_SELECT:
1722         case LFUN_LINE_END_SELECT:
1723                 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
1724                                 act == LFUN_WORD_RIGHT_SELECT ||
1725                                 act == LFUN_LINE_END_SELECT);
1726                 cur.macroModeClose();
1727                 cur.clearTargetX();
1728                 if (cur.pos() != cur.lastpos()) {
1729                         cur.pos() = cur.lastpos();
1730                 } else if ((cur.idx() + 1) % cur.ncols() != 0) {
1731                         cur.idx() += cur.ncols() - 1 - cur.idx() % cur.ncols();
1732                         cur.pos() = cur.lastpos();
1733                 } else if (cur.idx() != cur.lastidx()) {
1734                         cur.idx() = cur.lastidx();
1735                         cur.pos() = cur.lastpos();
1736                 } else {
1737                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1738                         cur.undispatched();
1739                 }
1740                 break;
1741
1742         default:
1743                 InsetMathNest::doDispatch(cur, cmd);
1744         }
1745 }
1746
1747
1748 bool InsetMathGrid::getStatus(Cursor & cur, FuncRequest const & cmd,
1749                 FuncStatus & status) const
1750 {
1751         switch (cmd.action()) {
1752         case LFUN_TABULAR_FEATURE: {
1753                 string s = cmd.getArg(0);
1754                 if (&cur.inset() != this) {
1755                         // Table actions requires that the cursor is _inside_ the
1756                         // table.
1757                         status.setEnabled(false);
1758                         status.message(from_utf8(N_("Cursor not in table")));
1759                         return true;
1760                 }
1761                 if (nrows() <= 1 && (s == "delete-row" || s == "swap-row")) {
1762                         status.setEnabled(false);
1763                         status.message(from_utf8(N_("Only one row")));
1764                         return true;
1765                 }
1766                 if (ncols() <= 1 &&
1767                     (s == "delete-column" || s == "swap-column")) {
1768                         status.setEnabled(false);
1769                         status.message(from_utf8(N_("Only one column")));
1770                         return true;
1771                 }
1772                 if ((rowinfo_[cur.row()].lines_ == 0 &&
1773                      s == "delete-hline-above") ||
1774                     (rowinfo_[cur.row() + 1].lines_ == 0 &&
1775                      s == "delete-hline-below")) {
1776                         status.setEnabled(false);
1777                         status.message(from_utf8(N_("No hline to delete")));
1778                         return true;
1779                 }
1780
1781                 if ((colinfo_[cur.col()].lines_ == 0 &&
1782                      s == "delete-vline-left") ||
1783                     (colinfo_[cur.col() + 1].lines_ == 0 &&
1784                      s == "delete-vline-right")) {
1785                         status.setEnabled(false);
1786                         status.message(from_utf8(N_("No vline to delete")));
1787                         return true;
1788                 }
1789                 if (s == "valign-top" || s == "valign-middle" ||
1790                     s == "valign-bottom" || s == "align-left" ||
1791                     s == "align-right" || s == "align-center") {
1792                         status.setEnabled(true);
1793                         char const ha = horizontalAlignment(cur.col());
1794                         char const va = verticalAlignment();
1795                         status.setOnOff((s == "align-left" && ha == 'l')
1796                                         || (s == "align-right"   && ha == 'r')
1797                                         || (s == "align-center"  && ha == 'c')
1798                                         || (s == "valign-top"    && va == 't')
1799                                         || (s == "valign-bottom" && va == 'b')
1800                                         || (s == "valign-middle" && va == 'c'));
1801                         return true;
1802                 }
1803                 if (s == "append-row" || s == "delete-row" ||
1804                     s == "copy-row" || s == "swap-row" ||
1805                     s == "add-hline-above" || s == "add-hline-below" ||
1806                     s == "delete-hline-above" || s == "delete-hline-below" ||
1807                     s == "append-column" || s == "delete-column" ||
1808                     s == "copy-column" || s == "swap-column" ||
1809                     s == "add-vline-left" || s == "add-vline-right" ||
1810                     s == "delete-vline-left" || s == "delete-vline-right") {
1811                         status.setEnabled(true);
1812                 } else {
1813                         status.setEnabled(false);
1814                         status.message(bformat(
1815                             from_utf8(N_("Unknown tabular feature '%1$s'")),
1816                             from_utf8(s)));
1817                 }
1818
1819 #if 0
1820                 // FIXME: What did this code do?
1821                 // Please check whether it is still needed!
1822                 // should be more precise
1823                 if (v_align_ == '\0') {
1824                         status.enable(true);
1825                         break;
1826                 }
1827                 if (cmd.argument().empty()) {
1828                         status.enable(false);
1829                         break;
1830                 }
1831                 if (!contains("tcb", cmd.argument()[0])) {
1832                         status.enable(false);
1833                         break;
1834                 }
1835                 status.setOnOff(cmd.argument()[0] == v_align_);
1836                 status.setEnabled(true);
1837 #endif
1838                 return true;
1839         }
1840
1841         case LFUN_CELL_SPLIT:
1842                 status.setEnabled(cur.idx() != cur.lastidx());
1843                 return true;
1844
1845         case LFUN_CELL_BACKWARD:
1846         case LFUN_CELL_FORWARD:
1847                 status.setEnabled(true);
1848                 return true;
1849
1850         default:
1851                 break;
1852         }
1853         return InsetMathNest::getStatus(cur, cmd, status);
1854 }
1855
1856
1857 // static
1858 char InsetMathGrid::colAlign(HullType type, col_type col)
1859 {
1860         switch (type) {
1861         case hullEqnArray:
1862                 return "rcl"[col % 3];
1863
1864         case hullMultline:
1865         case hullGather:
1866                 return 'c';
1867
1868         case hullAlign:
1869         case hullAlignAt:
1870         case hullXAlignAt:
1871         case hullXXAlignAt:
1872         case hullFlAlign:
1873                 return "rl"[col & 1];
1874
1875         case hullUnknown:
1876         case hullNone:
1877         case hullSimple:
1878         case hullEquation:
1879         case hullRegexp:
1880                 return 'c';
1881         }
1882         // avoid warning
1883         return 'c';
1884 }
1885
1886
1887 //static
1888 int InsetMathGrid::colSpace(HullType type, col_type col)
1889 {
1890         int alignInterSpace = 0;
1891         switch (type) {
1892         case hullUnknown:
1893         case hullNone:
1894         case hullSimple:
1895         case hullEquation:
1896         case hullMultline:
1897         case hullGather:
1898         case hullRegexp:
1899                 return 0;
1900
1901         case hullEqnArray:
1902                 return 5;
1903
1904         case hullAlign:
1905                 alignInterSpace = 20;
1906                 break;
1907         case hullAlignAt:
1908                 alignInterSpace = 0;
1909                 break;
1910         case hullXAlignAt:
1911                 alignInterSpace = 40;
1912                 break;
1913         case hullXXAlignAt:
1914         case hullFlAlign:
1915                 alignInterSpace = 60;
1916                 break;
1917         }
1918         return (col % 2) ? alignInterSpace : 0;
1919 }
1920
1921
1922 } // namespace lyx