]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
- make line-lovers happy (fix bug 4677)
[lyx.git] / src / insets / InsetTabular.cpp
1 /**
2  * \file InsetTabular.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Matthias Ettrich
8  * \author José Matos
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Jürgen Vigna
14  *
15  * Full author contact details are available in file CREDITS.
16  */
17
18 #include <config.h>
19
20 #include "InsetTabular.h"
21
22 #include "buffer_funcs.h"
23 #include "Buffer.h"
24 #include "BufferParams.h"
25 #include "BufferView.h"
26 #include "CoordCache.h"
27 #include "Counters.h"
28 #include "Cursor.h"
29 #include "CutAndPaste.h"
30 #include "DispatchResult.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "Language.h"
34 #include "LaTeXFeatures.h"
35 #include "Lexer.h"
36 #include "LyXFunc.h"
37 #include "LyXRC.h"
38 #include "MetricsInfo.h"
39 #include "OutputParams.h"
40 #include "paragraph_funcs.h"
41 #include "Paragraph.h"
42 #include "ParagraphParameters.h"
43 #include "ParIterator.h"
44 #include "TextClass.h"
45 #include "TextMetrics.h"
46
47 #include "frontends/Application.h"
48 #include "frontends/alert.h"
49 #include "frontends/Clipboard.h"
50 #include "frontends/Painter.h"
51 #include "frontends/Selection.h"
52
53 #include "support/assert.h"
54 #include "support/convert.h"
55 #include "support/debug.h"
56 #include "support/docstream.h"
57 #include "support/FileName.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
60
61 #include <boost/scoped_ptr.hpp>
62
63 #include <sstream>
64 #include <iostream>
65 #include <limits>
66 #include <cstring>
67
68 using namespace std;
69 using namespace lyx::support;
70
71 using boost::shared_ptr;
72 using boost::dynamic_pointer_cast;
73
74
75 namespace lyx {
76
77 using cap::dirtyTabularStack;
78 using cap::tabularStackDirty;
79
80 using graphics::PreviewLoader;
81
82 using frontend::Painter;
83 using frontend::Clipboard;
84
85 namespace Alert = frontend::Alert;
86
87
88 namespace {
89
90 int const ADD_TO_HEIGHT = 2; // in cell
91 int const ADD_TO_TABULAR_WIDTH = 6; // horiz space before and after the table
92 int const default_line_space = 10; // ?
93 int const WIDTH_OF_LINE = 5; // space between double lines
94
95
96 ///
97 boost::scoped_ptr<Tabular> paste_tabular;
98
99
100 struct TabularFeature {
101         Tabular::Feature action;
102         string feature;
103 };
104
105
106 TabularFeature tabularFeature[] =
107 {
108         { Tabular::APPEND_ROW, "append-row" },
109         { Tabular::APPEND_COLUMN, "append-column" },
110         { Tabular::DELETE_ROW, "delete-row" },
111         { Tabular::DELETE_COLUMN, "delete-column" },
112         { Tabular::COPY_ROW, "copy-row" },
113         { Tabular::COPY_COLUMN, "copy-column" },
114         { Tabular::TOGGLE_LINE_TOP, "toggle-line-top" },
115         { Tabular::TOGGLE_LINE_BOTTOM, "toggle-line-bottom" },
116         { Tabular::TOGGLE_LINE_LEFT, "toggle-line-left" },
117         { Tabular::TOGGLE_LINE_RIGHT, "toggle-line-right" },
118         { Tabular::ALIGN_LEFT, "align-left" },
119         { Tabular::ALIGN_RIGHT, "align-right" },
120         { Tabular::ALIGN_CENTER, "align-center" },
121         { Tabular::ALIGN_BLOCK, "align-block" },
122         { Tabular::VALIGN_TOP, "valign-top" },
123         { Tabular::VALIGN_BOTTOM, "valign-bottom" },
124         { Tabular::VALIGN_MIDDLE, "valign-middle" },
125         { Tabular::M_ALIGN_LEFT, "m-align-left" },
126         { Tabular::M_ALIGN_RIGHT, "m-align-right" },
127         { Tabular::M_ALIGN_CENTER, "m-align-center" },
128         { Tabular::M_VALIGN_TOP, "m-valign-top" },
129         { Tabular::M_VALIGN_BOTTOM, "m-valign-bottom" },
130         { Tabular::M_VALIGN_MIDDLE, "m-valign-middle" },
131         { Tabular::MULTICOLUMN, "multicolumn" },
132         { Tabular::SET_ALL_LINES, "set-all-lines" },
133         { Tabular::UNSET_ALL_LINES, "unset-all-lines" },
134         { Tabular::SET_LONGTABULAR, "set-longtabular" },
135         { Tabular::UNSET_LONGTABULAR, "unset-longtabular" },
136         { Tabular::SET_PWIDTH, "set-pwidth" },
137         { Tabular::SET_MPWIDTH, "set-mpwidth" },
138         { Tabular::SET_ROTATE_TABULAR, "set-rotate-tabular" },
139         { Tabular::UNSET_ROTATE_TABULAR, "unset-rotate-tabular" },
140         { Tabular::TOGGLE_ROTATE_TABULAR, "toggle-rotate-tabular" },
141         { Tabular::SET_ROTATE_CELL, "set-rotate-cell" },
142         { Tabular::UNSET_ROTATE_CELL, "unset-rotate-cell" },
143         { Tabular::TOGGLE_ROTATE_CELL, "toggle-rotate-cell" },
144         { Tabular::SET_USEBOX, "set-usebox" },
145         { Tabular::SET_LTHEAD, "set-lthead" },
146         { Tabular::UNSET_LTHEAD, "unset-lthead" },
147         { Tabular::SET_LTFIRSTHEAD, "set-ltfirsthead" },
148         { Tabular::UNSET_LTFIRSTHEAD, "unset-ltfirsthead" },
149         { Tabular::SET_LTFOOT, "set-ltfoot" },
150         { Tabular::UNSET_LTFOOT, "unset-ltfoot" },
151         { Tabular::SET_LTLASTFOOT, "set-ltlastfoot" },
152         { Tabular::UNSET_LTLASTFOOT, "unset-ltlastfoot" },
153         { Tabular::SET_LTNEWPAGE, "set-ltnewpage" },
154         { Tabular::SET_SPECIAL_COLUMN, "set-special-column" },
155         { Tabular::SET_SPECIAL_MULTI, "set-special-multi" },
156         { Tabular::SET_BOOKTABS, "set-booktabs" },
157         { Tabular::UNSET_BOOKTABS, "unset-booktabs" },
158         { Tabular::SET_TOP_SPACE, "set-top-space" },
159         { Tabular::SET_BOTTOM_SPACE, "set-bottom-space" },
160         { Tabular::SET_INTERLINE_SPACE, "set-interline-space" },
161         { Tabular::SET_BORDER_LINES, "set-border-lines" },
162         { Tabular::LAST_ACTION, "" }
163 };
164
165
166 class FeatureEqual : public unary_function<TabularFeature, bool> {
167 public:
168         FeatureEqual(Tabular::Feature feature)
169                 : feature_(feature) {}
170         bool operator()(TabularFeature const & tf) const {
171                 return tf.action == feature_;
172         }
173 private:
174         Tabular::Feature feature_;
175 };
176
177
178 template <class T>
179 string const write_attribute(string const & name, T const & t)
180 {
181         string const s = tostr(t);
182         return s.empty() ? s : " " + name + "=\"" + s + "\"";
183 }
184
185 template <>
186 string const write_attribute(string const & name, string const & t)
187 {
188         return t.empty() ? t : " " + name + "=\"" + t + "\"";
189 }
190
191
192 template <>
193 string const write_attribute(string const & name, docstring const & t)
194 {
195         return t.empty() ? string() : " " + name + "=\"" + to_utf8(t) + "\"";
196 }
197
198
199 template <>
200 string const write_attribute(string const & name, bool const & b)
201 {
202         // we write only true attribute values so we remove a bit of the
203         // file format bloat for tabulars.
204         return b ? write_attribute(name, convert<string>(b)) : string();
205 }
206
207
208 template <>
209 string const write_attribute(string const & name, int const & i)
210 {
211         // we write only true attribute values so we remove a bit of the
212         // file format bloat for tabulars.
213         return i ? write_attribute(name, convert<string>(i)) : string();
214 }
215
216
217 template <>
218 string const write_attribute(string const & name, Tabular::idx_type const & i)
219 {
220         // we write only true attribute values so we remove a bit of the
221         // file format bloat for tabulars.
222         return i ? write_attribute(name, convert<string>(i)) : string();
223 }
224
225
226 template <>
227 string const write_attribute(string const & name, Length const & value)
228 {
229         // we write only the value if we really have one same reson as above.
230         return value.zero() ? string() : write_attribute(name, value.asString());
231 }
232
233
234 string const tostr(LyXAlignment const & num)
235 {
236         switch (num) {
237         case LYX_ALIGN_NONE:
238                 return "none";
239         case LYX_ALIGN_BLOCK:
240                 return "block";
241         case LYX_ALIGN_LEFT:
242                 return "left";
243         case LYX_ALIGN_CENTER:
244                 return "center";
245         case LYX_ALIGN_RIGHT:
246                 return "right";
247         case LYX_ALIGN_LAYOUT:
248                 return "layout";
249         case LYX_ALIGN_SPECIAL:
250                 return "special";
251         }
252         return string();
253 }
254
255
256 string const tostr(Tabular::VAlignment const & num)
257 {
258         switch (num) {
259         case Tabular::LYX_VALIGN_TOP:
260                 return "top";
261         case Tabular::LYX_VALIGN_MIDDLE:
262                 return "middle";
263         case Tabular::LYX_VALIGN_BOTTOM:
264                 return "bottom";
265         }
266         return string();
267 }
268
269
270 string const tostr(Tabular::BoxType const & num)
271 {
272         switch (num) {
273         case Tabular::BOX_NONE:
274                 return "none";
275         case Tabular::BOX_PARBOX:
276                 return "parbox";
277         case Tabular::BOX_MINIPAGE:
278                 return "minipage";
279         }
280         return string();
281 }
282
283
284 // I would have liked a fromstr template a lot better. (Lgb)
285 bool string2type(string const str, LyXAlignment & num)
286 {
287         if (str == "none")
288                 num = LYX_ALIGN_NONE;
289         else if (str == "block")
290                 num = LYX_ALIGN_BLOCK;
291         else if (str == "left")
292                 num = LYX_ALIGN_LEFT;
293         else if (str == "center")
294                 num = LYX_ALIGN_CENTER;
295         else if (str == "right")
296                 num = LYX_ALIGN_RIGHT;
297         else
298                 return false;
299         return true;
300 }
301
302
303 bool string2type(string const str, Tabular::VAlignment & num)
304 {
305         if (str == "top")
306                 num = Tabular::LYX_VALIGN_TOP;
307         else if (str == "middle" )
308                 num = Tabular::LYX_VALIGN_MIDDLE;
309         else if (str == "bottom")
310                 num = Tabular::LYX_VALIGN_BOTTOM;
311         else
312                 return false;
313         return true;
314 }
315
316
317 bool string2type(string const str, Tabular::BoxType & num)
318 {
319         if (str == "none")
320                 num = Tabular::BOX_NONE;
321         else if (str == "parbox")
322                 num = Tabular::BOX_PARBOX;
323         else if (str == "minipage")
324                 num = Tabular::BOX_MINIPAGE;
325         else
326                 return false;
327         return true;
328 }
329
330
331 bool string2type(string const str, bool & num)
332 {
333         if (str == "true")
334                 num = true;
335         else if (str == "false")
336                 num = false;
337         else
338                 return false;
339         return true;
340 }
341
342
343 bool getTokenValue(string const & str, char const * token, string & ret)
344 {
345         ret.erase();
346         size_t token_length = strlen(token);
347         size_t pos = str.find(token);
348
349         if (pos == string::npos || pos + token_length + 1 >= str.length()
350                 || str[pos + token_length] != '=')
351                 return false;
352         pos += token_length + 1;
353         char ch = str[pos];
354         if (ch != '"' && ch != '\'') { // only read till next space
355                 ret += ch;
356                 ch = ' ';
357         }
358         while (pos < str.length() - 1 && str[++pos] != ch)
359                 ret += str[pos];
360
361         return true;
362 }
363
364
365 bool getTokenValue(string const & str, char const * token, docstring & ret)
366 {
367         string tmp;
368         bool const success = getTokenValue(str, token, tmp);
369         ret = from_utf8(tmp);
370         return success;
371 }
372
373
374 bool getTokenValue(string const & str, char const * token, int & num)
375 {
376         string tmp;
377         num = 0;
378         if (!getTokenValue(str, token, tmp))
379                 return false;
380         num = convert<int>(tmp);
381         return true;
382 }
383
384
385 bool getTokenValue(string const & str, char const * token, LyXAlignment & num)
386 {
387         string tmp;
388         return getTokenValue(str, token, tmp) && string2type(tmp, num);
389 }
390
391
392 bool getTokenValue(string const & str, char const * token,
393                                    Tabular::VAlignment & num)
394 {
395         string tmp;
396         return getTokenValue(str, token, tmp) && string2type(tmp, num);
397 }
398
399
400 bool getTokenValue(string const & str, char const * token,
401                                    Tabular::BoxType & num)
402 {
403         string tmp;
404         return getTokenValue(str, token, tmp) && string2type(tmp, num);
405 }
406
407
408 bool getTokenValue(string const & str, char const * token, bool & flag)
409 {
410         // set the flag always to false as this should be the default for bools
411         // not in the file-format.
412         flag = false;
413         string tmp;
414         return getTokenValue(str, token, tmp) && string2type(tmp, flag);
415 }
416
417
418 bool getTokenValue(string const & str, char const * token, Length & len)
419 {
420         // set the length to be zero() as default as this it should be if not
421         // in the file format.
422         len = Length();
423         string tmp;
424         return getTokenValue(str, token, tmp) && isValidLength(tmp, &len);
425 }
426
427
428 bool getTokenValue(string const & str, char const * token, Length & len, bool & flag)
429 {
430         len = Length();
431         flag = false;
432         string tmp;
433         if (!getTokenValue(str, token, tmp))
434                 return false;
435         if (tmp == "default") {
436                 flag = true;
437                 return  true;
438         }
439         return isValidLength(tmp, &len);
440 }
441
442
443 void l_getline(istream & is, string & str)
444 {
445         str.erase();
446         while (str.empty()) {
447                 getline(is, str);
448                 if (!str.empty() && str[str.length() - 1] == '\r')
449                         str.erase(str.length() - 1);
450         }
451 }
452
453 } // namespace
454
455
456 string const featureAsString(Tabular::Feature feature)
457 {
458         TabularFeature * end = tabularFeature +
459                 sizeof(tabularFeature) / sizeof(TabularFeature);
460         TabularFeature * it = find_if(tabularFeature, end,
461                                            FeatureEqual(feature));
462         return (it == end) ? string() : it->feature;
463 }
464
465
466
467 /////////////////////////////////////////////////////////////////////
468 //
469 // Tabular
470 //
471 /////////////////////////////////////////////////////////////////////
472
473
474 Tabular::CellData::CellData(Buffer const & buf, Tabular const & table)
475         : cellno(0),
476           width(0),
477           multicolumn(Tabular::CELL_NORMAL),
478           alignment(LYX_ALIGN_CENTER),
479           valignment(LYX_VALIGN_TOP),
480           top_line(false),
481           bottom_line(false),
482           left_line(false),
483           right_line(false),
484           usebox(BOX_NONE),
485           rotate(false),
486           inset(new InsetTableCell(buf, this, &table))
487 {
488         inset->setBuffer(const_cast<Buffer &>(buf));
489         inset->paragraphs().back().setLayout(buf.params().documentClass().emptyLayout());
490 }
491
492
493 Tabular::CellData::CellData(CellData const & cs)
494         : cellno(cs.cellno),
495           width(cs.width),
496           multicolumn(cs.multicolumn),
497           alignment(cs.alignment),
498           valignment(cs.valignment),
499           top_line(cs.top_line),
500           bottom_line(cs.bottom_line),
501           left_line(cs.left_line),
502           right_line(cs.right_line),
503           usebox(cs.usebox),
504           rotate(cs.rotate),
505           align_special(cs.align_special),
506           p_width(cs.p_width),
507           inset(dynamic_cast<InsetTableCell *>(cs.inset->clone()))
508 {
509         inset->setCellData(this);
510 }
511
512
513 Tabular::CellData & Tabular::CellData::operator=(CellData cs)
514 {
515         swap(cs);
516         return *this;
517 }
518
519
520 void Tabular::CellData::swap(CellData & rhs)
521 {
522         std::swap(cellno, rhs.cellno);
523         std::swap(width, rhs.width);
524         std::swap(multicolumn, rhs.multicolumn);
525         std::swap(alignment, rhs.alignment);
526         std::swap(valignment, rhs.valignment);
527         std::swap(top_line, rhs.top_line);
528         std::swap(bottom_line, rhs.bottom_line);
529         std::swap(left_line, rhs.left_line);
530         std::swap(right_line, rhs.right_line);
531         std::swap(usebox, rhs.usebox);
532         std::swap(rotate, rhs.rotate);
533         std::swap(align_special, rhs.align_special);
534         p_width.swap(rhs.p_width);
535         inset.swap(rhs.inset);
536 }
537
538
539 Tabular::RowData::RowData()
540         : ascent(0),
541           descent(0),
542           top_space_default(false),
543           bottom_space_default(false),
544           interline_space_default(false),
545           endhead(false),
546           endfirsthead(false),
547           endfoot(false),
548           endlastfoot(false),
549           newpage(false)
550 {}
551
552
553 Tabular::ColumnData::ColumnData()
554         : alignment(LYX_ALIGN_CENTER),
555           valignment(LYX_VALIGN_TOP),
556           width(0)
557 {
558 }
559
560
561 Tabular::ltType::ltType()
562         : topDL(false),
563           bottomDL(false),
564           empty(false)
565 {}
566
567
568 Tabular::Tabular()
569 {
570         // unusable now!
571 }
572
573
574 Tabular::Tabular(Buffer const & buffer, row_type rows_arg, col_type columns_arg)
575 {
576         init(buffer, rows_arg, columns_arg);
577 }
578
579
580 // activates all lines and sets all widths to 0
581 void Tabular::init(Buffer const & buf, row_type rows_arg,
582                       col_type columns_arg)
583 {
584         buffer_ = &buf;
585         row_info = row_vector(rows_arg);
586         column_info = column_vector(columns_arg);
587         cell_info = cell_vvector(rows_arg, cell_vector(columns_arg, CellData(buf, *this)));
588         row_info.reserve(10);
589         column_info.reserve(10);
590         cell_info.reserve(100);
591         updateIndexes();
592         is_long_tabular = false;
593         rotate = false;
594         use_booktabs = false;
595         // set silly default lines
596         for (row_type i = 0; i < rowCount(); ++i)
597                 for (col_type j = 0; j < columnCount(); ++j) {
598                         cell_info[i][j].top_line = true;
599                         cell_info[i][j].left_line = true;
600                         cell_info[i][j].bottom_line = i == 0 || i == rowCount() - 1;
601                         cell_info[i][j].right_line = j == columnCount() - 1;
602                 }
603 }
604
605
606 void Tabular::appendRow(idx_type const cell)
607 {
608         BufferParams const & bp = buffer().params();
609         row_type const row = cellRow(cell);
610
611         row_vector::iterator rit = row_info.begin() + row;
612         row_info.insert(rit, RowData());
613         // now set the values of the row before
614         row_info[row] = row_info[row + 1];
615
616         row_type const nrows = rowCount();
617         col_type const ncols = columnCount();
618
619         cell_vvector old(nrows - 1);
620         for (row_type i = 0; i < nrows - 1; ++i)
621                 swap(cell_info[i], old[i]);
622
623         cell_info = cell_vvector(nrows, cell_vector(ncols, CellData(buffer(), *this)));
624
625         for (row_type i = 0; i <= row; ++i)
626                 swap(cell_info[i], old[i]);
627         for (row_type i = row + 2; i < nrows; ++i)
628                 swap(cell_info[i], old[i - 1]);
629
630         updateIndexes();
631         for (col_type c = 0; c < ncols; ++c) {
632                 // inherit line settings
633                 idx_type const i = cellIndex(row + 1, c);
634                 idx_type const j = cellIndex(row, c);
635                 setLeftLine(i, leftLine(j));
636                 setRightLine(i, rightLine(j));
637                 setTopLine(i, topLine(j));
638                 if (topLine(j) && bottomLine(j)) {
639                         setBottomLine(i, true);
640                         setBottomLine(j, false);
641                 }
642                 // mark track changes
643                 if (bp.trackChanges)
644                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
645         }
646 }
647
648
649 void Tabular::deleteRow(row_type const row)
650 {
651         // Not allowed to delete last row
652         if (rowCount() == 1)
653                 return;
654
655         row_info.erase(row_info.begin() + row);
656         cell_info.erase(cell_info.begin() + row);
657         updateIndexes();
658 }
659
660
661 void Tabular::copyRow(row_type const row)
662 {
663         row_info.insert(row_info.begin() + row, row_info[row]);
664         cell_info.insert(cell_info.begin() + row, cell_info[row]);
665
666         if (buffer().params().trackChanges)
667                 for (col_type j = 0; j < columnCount(); ++j)
668                         cell_info[row + 1][j].inset->setChange(Change(Change::INSERTED));
669
670         updateIndexes();
671 }
672
673
674 void Tabular::appendColumn(idx_type const cell)
675 {
676         col_type const c = cellColumn(cell);
677         column_vector::iterator cit = column_info.begin() + c + 1;
678         column_info.insert(cit, ColumnData());
679         row_type const nrows = rowCount();
680         //col_type const ncols = columnCount();
681         // set the column values of the column before
682         column_info[c + 1] = column_info[c];
683
684         for (row_type r = 0; r < nrows; ++r) {
685                 cell_info[r].insert(cell_info[r].begin() + c + 1, 
686                         CellData(buffer(), *this));
687                 if (cell_info[r][c].multicolumn == CELL_BEGIN_OF_MULTICOLUMN)
688                         cell_info[r][c + 1].multicolumn = CELL_PART_OF_MULTICOLUMN;
689                 else
690                         cell_info[r][c + 1].multicolumn = cell_info[r][c].multicolumn;
691         }
692         updateIndexes();
693         for (row_type r = 0; r < nrows; ++r) {
694                 // inherit line settings
695                 idx_type const i = cellIndex(r, c + 1);
696                 idx_type const j = cellIndex(r, c);
697                 setBottomLine(i, bottomLine(j));
698                 setTopLine(i, topLine(j));
699                 setLeftLine(i, leftLine(j));
700                 if (rightLine(j) && rightLine(j)) {
701                         setRightLine(i, true);
702                         setRightLine(j, false);
703                 }
704                 //
705                 cellInfo(i).inset->clear();
706                 if (buffer().params().trackChanges)
707                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
708         }
709 }
710
711
712 void Tabular::deleteColumn(col_type const column)
713 {
714         // Not allowed to delete last column
715         if (columnCount() == 1)
716                 return;
717
718         column_info.erase(column_info.begin() + column);
719         for (row_type i = 0; i < rowCount(); ++i) {
720                 // Care about multicolumn cells
721                 if (column + 1 < columnCount() &&
722                     cell_info[i][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN &&
723                     cell_info[i][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN) {
724                         cell_info[i][column + 1].multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
725                 }
726                 cell_info[i].erase(cell_info[i].begin() + column);
727         }
728         updateIndexes();
729 }
730
731
732 void Tabular::copyColumn(col_type const column)
733 {
734         BufferParams const & bp = buffer().params();
735         column_info.insert(column_info.begin() + column, column_info[column]);
736
737         for (row_type i = 0; i < rowCount(); ++i)
738                 cell_info[i].insert(cell_info[i].begin() + column, cell_info[i][column]);
739
740         if (bp.trackChanges)
741                 for (row_type i = 0; i < rowCount(); ++i)
742                         cell_info[i][column + 1].inset->setChange(Change(Change::INSERTED));
743         updateIndexes();
744 }
745
746
747 void Tabular::updateIndexes()
748 {
749         col_type ncols = columnCount();
750         row_type nrows = rowCount();
751         numberofcells = 0;
752         for (row_type row = 0; row < nrows; ++row)
753                 for (col_type column = 0; column < ncols; ++column) {
754                         if (!isPartOfMultiColumn(row, column))
755                                 ++numberofcells;
756                         cell_info[row][column].cellno = numberofcells - 1;
757                 }
758
759         rowofcell.resize(numberofcells);
760         columnofcell.resize(numberofcells);
761         idx_type i = 0;
762         for (row_type row = 0; row < nrows; ++row)
763                 for (col_type column = 0; column < ncols; ++column) {
764                         if (isPartOfMultiColumn(row, column))
765                                 continue;
766                         rowofcell[i] = row;
767                         columnofcell[i] = column;
768                         ++i;
769                 }
770 }
771
772
773 Tabular::idx_type Tabular::cellCount() const
774 {
775         return numberofcells;
776 }
777
778
779 Tabular::idx_type Tabular::numberOfCellsInRow(idx_type const cell) const
780 {
781         row_type const row = cellRow(cell);
782         idx_type result = 0;
783         for (col_type i = 0; i < columnCount(); ++i)
784                 if (cell_info[row][i].multicolumn != Tabular::CELL_PART_OF_MULTICOLUMN)
785                         ++result;
786         return result;
787 }
788
789
790 bool Tabular::topLine(idx_type const cell) const
791 {
792         return cellInfo(cell).top_line;
793 }
794
795
796 bool Tabular::bottomLine(idx_type const cell) const
797 {
798         return cellInfo(cell).bottom_line;
799 }
800
801
802 bool Tabular::leftLine(idx_type cell) const
803 {
804         if (use_booktabs)
805                 return false;
806         return cellInfo(cell).left_line;
807 }
808
809
810 bool Tabular::rightLine(idx_type cell) const
811 {
812         if (use_booktabs)
813                 return false;
814         return cellInfo(cell).right_line;
815 }
816
817
818 bool Tabular::topAlreadyDrawn(idx_type cell) const
819 {
820         row_type row = cellRow(cell);
821         if (row == 0)
822                 return false;
823         idx_type i = cellIndex(row - 1, cellColumn(cell));
824         return !rowTopLine(row) && bottomLine(i);
825 }
826
827
828 bool Tabular::leftAlreadyDrawn(idx_type cell) const
829 {
830         col_type col = cellColumn(cell);
831         if (col == 0)
832                 return false;
833         idx_type i = cellIndex(cellRow(cell), col - 1);
834         return rightLine(i) && !leftLine(cell);
835 }
836
837
838 bool Tabular::isLastRow(idx_type cell) const
839 {
840         return cellRow(cell) == rowCount() - 1;
841 }
842
843
844 int Tabular::getAdditionalHeight(row_type row) const
845 {
846         if (!row || row >= rowCount())
847                 return 0;
848
849         int const interline_space = row_info[row - 1].interline_space_default ?
850                 default_line_space :
851                 row_info[row - 1].interline_space.inPixels(width());
852         if (rowTopLine(row) && rowBottomLine(row - 1))
853                 return interline_space + WIDTH_OF_LINE;
854         return interline_space;
855 }
856
857
858 int Tabular::getAdditionalWidth(idx_type cell) const
859 {
860         col_type const nextcol = cellColumn(cell) + columnSpan(cell);
861         if (rightLine(cell) 
862                 && nextcol < columnCount() && leftLine(cellIndex(cellRow(cell), nextcol)))
863                 return WIDTH_OF_LINE;
864         return 0;
865 }
866
867
868 int Tabular::columnWidth(idx_type cell) const
869 {
870         int w = 0;
871         col_type const span = columnSpan(cell);
872         col_type const col = cellColumn(cell);
873         for(col_type c = col; c < col + span ; ++c)
874                 w += column_info[c].width;
875         return w;
876 }
877
878
879 bool Tabular::updateColumnWidths()
880 {
881         col_type const ncols = columnCount();
882         row_type const nrows = rowCount();
883         bool update = false;
884         // for each col get max of single col cells
885         for(col_type c = 0; c < ncols; ++c) {
886                 int new_width = 0;
887                 for(row_type r = 0; r < nrows; ++r) {
888                         idx_type const i = cellIndex(r, c);
889                         if (columnSpan(i) == 1)
890                                 new_width = max(new_width, cellInfo(i).width);
891                 }
892
893                 if (column_info[c].width != new_width) {
894                         column_info[c].width = new_width;
895                         update = true;
896                 }
897         }
898         // update col widths to fit merged cells
899         for(col_type c = 0; c < ncols; ++c)
900                 for(row_type r = 0; r < nrows; ++r) {
901                         idx_type const i = cellIndex(r, c);
902                         int const span = columnSpan(i);
903                         if (span == 1 || c > cellColumn(i))
904                                 continue;
905
906                         int old_width = 0;
907                         for(col_type j = c; j < c + span ; ++j)
908                                 old_width += column_info[j].width;
909
910                         if (cellInfo(i).width > old_width) {
911                                 column_info[c + span - 1].width += cellInfo(i).width - old_width;
912                                 update = true;
913                         }
914                 }
915
916         return update;
917 }
918
919
920 int Tabular::width() const
921 {
922         col_type const ncols = columnCount();
923         int width = 0;
924         for (col_type i = 0; i < ncols; ++i)
925                 width += column_info[i].width;
926         return width;
927 }
928
929
930 void Tabular::setCellWidth(idx_type cell, int new_width)
931 {
932         cellInfo(cell).width = new_width + 2 * WIDTH_OF_LINE 
933                 + getAdditionalWidth(cell);
934 }
935
936
937 void Tabular::setAlignment(idx_type cell, LyXAlignment align,
938                               bool onlycolumn)
939 {
940         if (!isMultiColumn(cell) || onlycolumn)
941                 column_info[cellColumn(cell)].alignment = align;
942         if (!onlycolumn)
943                 cellInfo(cell).alignment = align;
944 }
945
946
947 void Tabular::setVAlignment(idx_type cell, VAlignment align,
948                                bool onlycolumn)
949 {
950         if (!isMultiColumn(cell) || onlycolumn)
951                 column_info[cellColumn(cell)].valignment = align;
952         if (!onlycolumn)
953                 cellInfo(cell).valignment = align;
954 }
955
956
957 namespace {
958
959 /**
960  * Allow line and paragraph breaks for fixed width cells or disallow them,
961  * merge cell paragraphs and reset layout to standard for variable width
962  * cells.
963  */
964 void toggleFixedWidth(Cursor & cur, InsetTableCell * inset, bool fixedWidth)
965 {
966         inset->setAutoBreakRows(fixedWidth);
967         if (fixedWidth)
968                 return;
969
970         // merge all paragraphs to one
971         BufferParams const & bp = cur.bv().buffer().params();
972         while (inset->paragraphs().size() > 1)
973                 mergeParagraph(bp, inset->paragraphs(), 0);
974
975         // reset layout
976         cur.push(*inset);
977         // undo information has already been recorded
978         inset->getText(0)->setLayout(cur.bv().buffer(), 0, cur.lastpit() + 1,
979                         bp.documentClass().emptyLayoutName());
980         cur.pop();
981 }
982
983 }
984
985
986 void Tabular::setColumnPWidth(Cursor & cur, idx_type cell,
987                 Length const & width)
988 {
989         col_type const j = cellColumn(cell);
990
991         column_info[j].p_width = width;
992         for (row_type i = 0; i < rowCount(); ++i) {
993                 idx_type const cell = cellIndex(i, j);
994                 // because of multicolumns
995                 toggleFixedWidth(cur, cellInset(cell).get(),
996                                  !getPWidth(cell).zero());
997         }
998         // cur paragraph can become invalid after paragraphs were merged
999         if (cur.pit() > cur.lastpit())
1000                 cur.pit() = cur.lastpit();
1001         // cur position can become invalid after newlines were removed
1002         if (cur.pos() > cur.lastpos())
1003                 cur.pos() = cur.lastpos();
1004 }
1005
1006
1007 bool Tabular::setMColumnPWidth(Cursor & cur, idx_type cell,
1008                 Length const & width)
1009 {
1010         if (!isMultiColumn(cell))
1011                 return false;
1012
1013         cellInfo(cell).p_width = width;
1014         toggleFixedWidth(cur, cellInset(cell).get(), !width.zero());
1015         // cur paragraph can become invalid after paragraphs were merged
1016         if (cur.pit() > cur.lastpit())
1017                 cur.pit() = cur.lastpit();
1018         // cur position can become invalid after newlines were removed
1019         if (cur.pos() > cur.lastpos())
1020                 cur.pos() = cur.lastpos();
1021         return true;
1022 }
1023
1024
1025 void Tabular::setAlignSpecial(idx_type cell, docstring const & special,
1026                                  Tabular::Feature what)
1027 {
1028         if (what == SET_SPECIAL_MULTI)
1029                 cellInfo(cell).align_special = special;
1030         else
1031                 column_info[cellColumn(cell)].align_special = special;
1032 }
1033
1034
1035 void Tabular::setAllLines(idx_type cell, bool line)
1036 {
1037         setTopLine(cell, line);
1038         setBottomLine(cell, line);
1039         setRightLine(cell, line);
1040         setLeftLine(cell, line);
1041 }
1042
1043
1044 void Tabular::setTopLine(idx_type i, bool line)
1045 {
1046         cellInfo(i).top_line = line;
1047 }
1048
1049
1050 void Tabular::setBottomLine(idx_type i, bool line)
1051 {
1052         cellInfo(i).bottom_line = line;
1053 }
1054
1055
1056 void Tabular::setLeftLine(idx_type cell, bool line)
1057 {
1058         cellInfo(cell).left_line = line;
1059 }
1060
1061
1062 void Tabular::setRightLine(idx_type cell, bool line)
1063 {
1064         cellInfo(cell).right_line = line;
1065 }
1066
1067 bool Tabular::rowTopLine(row_type r) const
1068 {
1069         idx_type i0 = getFirstCellInRow(r);
1070         idx_type i1 = getLastCellInRow(r);
1071         bool all_rows_set = true;
1072         for (idx_type j = i0; all_rows_set && j <= i1; ++j)
1073                 all_rows_set = cellInfo(j).top_line;
1074         return all_rows_set;
1075 }
1076
1077
1078 bool Tabular::rowBottomLine(row_type r) const
1079 {
1080         idx_type i0 = getFirstCellInRow(r);
1081         idx_type i1 = getLastCellInRow(r);
1082         bool all_rows_set = true;
1083         for (idx_type j = i0; all_rows_set && j <= i1; ++j)
1084                 all_rows_set = cellInfo(j).bottom_line;
1085         return all_rows_set;
1086 }
1087
1088
1089 bool Tabular::columnLeftLine(col_type c) const
1090 {
1091         bool all_cols_set = true;
1092         row_type const nrows = rowCount();
1093         for (row_type r = 0; all_cols_set && r < nrows; ++r) {
1094                 idx_type i = cellIndex(r, c);
1095                 if (c == cellColumn(i))
1096                         all_cols_set = cellInfo(i).left_line;
1097         }
1098         return all_cols_set;
1099 }
1100
1101
1102 bool Tabular::columnRightLine(col_type c) const
1103 {
1104         bool all_cols_set = true;
1105         row_type const nrows = rowCount();
1106         for (row_type r = 0; all_cols_set && r < nrows; ++r) {
1107                 idx_type i = cellIndex(r, c);
1108                 if (c == cellColumn(i) + columnSpan(i) - 1)
1109                         all_cols_set = cellInfo(i).right_line;
1110         }
1111         return all_cols_set;
1112 }
1113
1114
1115 LyXAlignment Tabular::getAlignment(idx_type cell, bool onlycolumn) const
1116 {
1117         if (!onlycolumn && isMultiColumn(cell))
1118                 return cellInfo(cell).alignment;
1119         return column_info[cellColumn(cell)].alignment;
1120 }
1121
1122
1123 Tabular::VAlignment
1124 Tabular::getVAlignment(idx_type cell, bool onlycolumn) const
1125 {
1126         if (!onlycolumn && isMultiColumn(cell))
1127                 return cellInfo(cell).valignment;
1128         return column_info[cellColumn(cell)].valignment;
1129 }
1130
1131
1132 Length const Tabular::getPWidth(idx_type cell) const
1133 {
1134         if (isMultiColumn(cell))
1135                 return cellInfo(cell).p_width;
1136         return column_info[cellColumn(cell)].p_width;
1137 }
1138
1139
1140 Length const Tabular::getColumnPWidth(idx_type cell) const
1141 {
1142         return column_info[cellColumn(cell)].p_width;
1143 }
1144
1145
1146 Length const Tabular::getMColumnPWidth(idx_type cell) const
1147 {
1148         if (isMultiColumn(cell))
1149                 return cellInfo(cell).p_width;
1150         return Length();
1151 }
1152
1153
1154 docstring const Tabular::getAlignSpecial(idx_type cell, int what) const
1155 {
1156         if (what == SET_SPECIAL_MULTI)
1157                 return cellInfo(cell).align_special;
1158         return column_info[cellColumn(cell)].align_special;
1159 }
1160
1161
1162 int Tabular::cellWidth(idx_type cell) const
1163 {
1164         return cellInfo(cell).width;
1165 }
1166
1167
1168 int Tabular::getBeginningOfTextInCell(idx_type cell) const
1169 {
1170         int x = 0;
1171
1172         switch (getAlignment(cell)) {
1173         case LYX_ALIGN_CENTER:
1174                 x += (columnWidth(cell) - cellWidth(cell)) / 2;
1175                 break;
1176         case LYX_ALIGN_RIGHT:
1177                 x += columnWidth(cell) - cellWidth(cell);
1178                 // + getAdditionalWidth(cell);
1179                 break;
1180         default:
1181                 // LYX_ALIGN_LEFT: nothing :-)
1182                 break;
1183         }
1184
1185         // the LaTeX Way :-(
1186         x += WIDTH_OF_LINE;
1187         return x;
1188 }
1189
1190
1191 bool Tabular::isFirstCellInRow(idx_type cell) const
1192 {
1193         return cellColumn(cell) == 0;
1194 }
1195
1196
1197 Tabular::idx_type Tabular::getFirstCellInRow(row_type row) const
1198 {
1199         if (row > rowCount() - 1)
1200                 row = rowCount() - 1;
1201         return cell_info[row][0].cellno;
1202 }
1203
1204
1205 bool Tabular::isLastCellInRow(idx_type cell) const
1206 {
1207         return cellRightColumn(cell) == columnCount() - 1;
1208 }
1209
1210
1211 Tabular::idx_type Tabular::getLastCellInRow(row_type row) const
1212 {
1213         if (row > rowCount() - 1)
1214                 row = rowCount() - 1;
1215         return cell_info[row][columnCount() - 1].cellno;
1216 }
1217
1218
1219 Tabular::row_type Tabular::cellRow(idx_type cell) const
1220 {
1221         if (cell >= cellCount())
1222                 return rowCount() - 1;
1223         if (cell == npos)
1224                 return 0;
1225         return rowofcell[cell];
1226 }
1227
1228
1229 Tabular::col_type Tabular::cellColumn(idx_type cell) const
1230 {
1231         if (cell >= cellCount())
1232                 return columnCount() - 1;
1233         if (cell == npos)
1234                 return 0;
1235         return columnofcell[cell];
1236 }
1237
1238
1239 Tabular::col_type Tabular::cellRightColumn(idx_type cell) const
1240 {
1241         row_type const row = cellRow(cell);
1242         col_type column = cellColumn(cell);
1243         while (column < columnCount() - 1 &&
1244                    cell_info[row][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN)
1245                 ++column;
1246         return column;
1247 }
1248
1249
1250 void Tabular::write(ostream & os) const
1251 {
1252         // header line
1253         os << "<lyxtabular"
1254            << write_attribute("version", 3)
1255            << write_attribute("rows", rowCount())
1256            << write_attribute("columns", columnCount())
1257            << ">\n";
1258         // global longtable options
1259         os << "<features"
1260            << write_attribute("rotate", rotate)
1261            << write_attribute("booktabs", use_booktabs)
1262            << write_attribute("islongtable", is_long_tabular)
1263            << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1264            << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1265            << write_attribute("firstHeadEmpty", endfirsthead.empty)
1266            << write_attribute("headTopDL", endhead.topDL)
1267            << write_attribute("headBottomDL", endhead.bottomDL)
1268            << write_attribute("footTopDL", endfoot.topDL)
1269            << write_attribute("footBottomDL", endfoot.bottomDL)
1270            << write_attribute("lastFootTopDL", endlastfoot.topDL)
1271            << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1272            << write_attribute("lastFootEmpty", endlastfoot.empty)
1273            << ">\n";
1274         for (col_type j = 0; j < columnCount(); ++j) {
1275                 os << "<column"
1276                    << write_attribute("alignment", column_info[j].alignment)
1277                    << write_attribute("valignment", column_info[j].valignment)
1278                    << write_attribute("width", column_info[j].p_width.asString())
1279                    << write_attribute("special", column_info[j].align_special)
1280                    << ">\n";
1281         }
1282         for (row_type i = 0; i < rowCount(); ++i) {
1283                 static const string def("default");
1284                 os << "<row";
1285                 if (row_info[i].top_space_default)
1286                         os << write_attribute("topspace", def);
1287                 else
1288                         os << write_attribute("topspace", row_info[i].top_space);
1289                 if (row_info[i].bottom_space_default)
1290                         os << write_attribute("bottomspace", def);
1291                 else
1292                         os << write_attribute("bottomspace", row_info[i].bottom_space);
1293                 if (row_info[i].interline_space_default)
1294                         os << write_attribute("interlinespace", def);
1295                 else
1296                         os << write_attribute("interlinespace", row_info[i].interline_space);
1297                 os << write_attribute("endhead", row_info[i].endhead)
1298                    << write_attribute("endfirsthead", row_info[i].endfirsthead)
1299                    << write_attribute("endfoot", row_info[i].endfoot)
1300                    << write_attribute("endlastfoot", row_info[i].endlastfoot)
1301                    << write_attribute("newpage", row_info[i].newpage)
1302                    << ">\n";
1303                 for (col_type j = 0; j < columnCount(); ++j) {
1304                         os << "<cell"
1305                            << write_attribute("multicolumn", cell_info[i][j].multicolumn)
1306                            << write_attribute("alignment", cell_info[i][j].alignment)
1307                            << write_attribute("valignment", cell_info[i][j].valignment)
1308                            << write_attribute("topline", cell_info[i][j].top_line)
1309                            << write_attribute("bottomline", cell_info[i][j].bottom_line)
1310                            << write_attribute("leftline", cell_info[i][j].left_line)
1311                            << write_attribute("rightline", cell_info[i][j].right_line)
1312                            << write_attribute("rotate", cell_info[i][j].rotate)
1313                            << write_attribute("usebox", cell_info[i][j].usebox)
1314                            << write_attribute("width", cell_info[i][j].p_width)
1315                            << write_attribute("special", cell_info[i][j].align_special)
1316                            << ">\n";
1317                         os << "\\begin_inset ";
1318                         cell_info[i][j].inset->write(os);
1319                         os << "\n\\end_inset\n"
1320                            << "</cell>\n";
1321                 }
1322                 os << "</row>\n";
1323         }
1324         os << "</lyxtabular>\n";
1325 }
1326
1327
1328 void Tabular::read(Lexer & lex)
1329 {
1330         string line;
1331         istream & is = lex.getStream();
1332
1333         l_getline(is, line);
1334         if (!prefixIs(line, "<lyxtabular ") && !prefixIs(line, "<Tabular ")) {
1335                 LASSERT(false, /**/);
1336                 return;
1337         }
1338
1339         int version;
1340         if (!getTokenValue(line, "version", version))
1341                 return;
1342         LASSERT(version >= 2, /**/);
1343
1344         int rows_arg;
1345         if (!getTokenValue(line, "rows", rows_arg))
1346                 return;
1347         int columns_arg;
1348         if (!getTokenValue(line, "columns", columns_arg))
1349                 return;
1350         init(buffer(), rows_arg, columns_arg);
1351         l_getline(is, line);
1352         if (!prefixIs(line, "<features")) {
1353                 lyxerr << "Wrong tabular format (expected <features ...> got"
1354                        << line << ')' << endl;
1355                 return;
1356         }
1357         getTokenValue(line, "rotate", rotate);
1358         getTokenValue(line, "booktabs", use_booktabs);
1359         getTokenValue(line, "islongtable", is_long_tabular);
1360         getTokenValue(line, "firstHeadTopDL", endfirsthead.topDL);
1361         getTokenValue(line, "firstHeadBottomDL", endfirsthead.bottomDL);
1362         getTokenValue(line, "firstHeadEmpty", endfirsthead.empty);
1363         getTokenValue(line, "headTopDL", endhead.topDL);
1364         getTokenValue(line, "headBottomDL", endhead.bottomDL);
1365         getTokenValue(line, "footTopDL", endfoot.topDL);
1366         getTokenValue(line, "footBottomDL", endfoot.bottomDL);
1367         getTokenValue(line, "lastFootTopDL", endlastfoot.topDL);
1368         getTokenValue(line, "lastFootBottomDL", endlastfoot.bottomDL);
1369         getTokenValue(line, "lastFootEmpty", endlastfoot.empty);
1370
1371         for (col_type j = 0; j < columnCount(); ++j) {
1372                 l_getline(is,line);
1373                 if (!prefixIs(line,"<column")) {
1374                         lyxerr << "Wrong tabular format (expected <column ...> got"
1375                                << line << ')' << endl;
1376                         return;
1377                 }
1378                 getTokenValue(line, "alignment", column_info[j].alignment);
1379                 getTokenValue(line, "valignment", column_info[j].valignment);
1380                 getTokenValue(line, "width", column_info[j].p_width);
1381                 getTokenValue(line, "special", column_info[j].align_special);
1382         }
1383
1384         for (row_type i = 0; i < rowCount(); ++i) {
1385                 l_getline(is, line);
1386                 if (!prefixIs(line, "<row")) {
1387                         lyxerr << "Wrong tabular format (expected <row ...> got"
1388                                << line << ')' << endl;
1389                         return;
1390                 }
1391                 getTokenValue(line, "topspace", row_info[i].top_space,
1392                               row_info[i].top_space_default);
1393                 getTokenValue(line, "bottomspace", row_info[i].bottom_space,
1394                               row_info[i].bottom_space_default);
1395                 getTokenValue(line, "interlinespace", row_info[i].interline_space,
1396                               row_info[i].interline_space_default);
1397                 getTokenValue(line, "endfirsthead", row_info[i].endfirsthead);
1398                 getTokenValue(line, "endhead", row_info[i].endhead);
1399                 getTokenValue(line, "endfoot", row_info[i].endfoot);
1400                 getTokenValue(line, "endlastfoot", row_info[i].endlastfoot);
1401                 getTokenValue(line, "newpage", row_info[i].newpage);
1402                 for (col_type j = 0; j < columnCount(); ++j) {
1403                         l_getline(is, line);
1404                         if (!prefixIs(line, "<cell")) {
1405                                 lyxerr << "Wrong tabular format (expected <cell ...> got"
1406                                        << line << ')' << endl;
1407                                 return;
1408                         }
1409                         getTokenValue(line, "multicolumn", cell_info[i][j].multicolumn);
1410                         getTokenValue(line, "alignment", cell_info[i][j].alignment);
1411                         getTokenValue(line, "valignment", cell_info[i][j].valignment);
1412                         getTokenValue(line, "topline", cell_info[i][j].top_line);
1413                         getTokenValue(line, "bottomline", cell_info[i][j].bottom_line);
1414                         getTokenValue(line, "leftline", cell_info[i][j].left_line);
1415                         getTokenValue(line, "rightline", cell_info[i][j].right_line);
1416                         getTokenValue(line, "rotate", cell_info[i][j].rotate);
1417                         getTokenValue(line, "usebox", cell_info[i][j].usebox);
1418                         getTokenValue(line, "width", cell_info[i][j].p_width);
1419                         getTokenValue(line, "special", cell_info[i][j].align_special);
1420                         l_getline(is, line);
1421                         if (prefixIs(line, "\\begin_inset")) {
1422                                 cell_info[i][j].inset->read(lex);
1423                                 l_getline(is, line);
1424                         }
1425                         if (!prefixIs(line, "</cell>")) {
1426                                 lyxerr << "Wrong tabular format (expected </cell> got"
1427                                        << line << ')' << endl;
1428                                 return;
1429                         }
1430                 }
1431                 l_getline(is, line);
1432                 if (!prefixIs(line, "</row>")) {
1433                         lyxerr << "Wrong tabular format (expected </row> got"
1434                                << line << ')' << endl;
1435                         return;
1436                 }
1437         }
1438         while (!prefixIs(line, "</lyxtabular>")) {
1439                 l_getline(is, line);
1440         }
1441         updateIndexes();
1442 }
1443
1444
1445 bool Tabular::isMultiColumn(idx_type cell) const
1446 {
1447         return cellInfo(cell).multicolumn != CELL_NORMAL;
1448 }
1449
1450
1451 bool Tabular::isMultiColumnReal(idx_type cell) const
1452 {
1453         return cellColumn(cell) != cellRightColumn(cell) &&
1454                         cellInfo(cell).multicolumn != CELL_NORMAL;
1455 }
1456
1457
1458 Tabular::CellData & Tabular::cellInfo(idx_type cell) const
1459 {
1460         return cell_info[cellRow(cell)][cellColumn(cell)];
1461 }
1462
1463
1464 void Tabular::setMultiColumn(idx_type cell, idx_type number)
1465 {
1466         CellData & cs = cellInfo(cell);
1467         cs.multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
1468         cs.alignment = column_info[cellColumn(cell)].alignment;
1469         setRightLine(cell, rightLine(cell + number - 1));
1470         for (idx_type i = 1; i < number; ++i) {
1471                 CellData & cs1 = cellInfo(cell + i);
1472                 cs1.multicolumn = CELL_PART_OF_MULTICOLUMN;
1473                 cs.inset->appendParagraphs(cs1.inset->paragraphs());
1474                 cs1.inset->clear();
1475         }
1476         updateIndexes();
1477 }
1478
1479
1480 Tabular::idx_type Tabular::columnSpan(idx_type cell) const
1481 {
1482         row_type const row = cellRow(cell);
1483         col_type const ncols = columnCount();
1484         idx_type result = 1;
1485         col_type column = cellColumn(cell) + 1;
1486         while (column < ncols && isPartOfMultiColumn(row, column)) {
1487                 ++result;
1488                 ++column;
1489         }
1490         return result;
1491 }
1492
1493
1494 Tabular::idx_type Tabular::unsetMultiColumn(idx_type cell)
1495 {
1496         row_type const row = cellRow(cell);
1497         col_type column = cellColumn(cell);
1498
1499         idx_type result = 0;
1500
1501         if (cell_info[row][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN) {
1502                 cell_info[row][column].multicolumn = CELL_NORMAL;
1503                 ++column;
1504                 while (column < columnCount() &&
1505                            cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN)
1506                 {
1507                         cell_info[row][column].multicolumn = CELL_NORMAL;
1508                         ++column;
1509                         ++result;
1510                 }
1511         }
1512         updateIndexes();
1513         return result;
1514 }
1515
1516
1517 void Tabular::setBookTabs(bool what)
1518 {
1519         use_booktabs = what;
1520 }
1521
1522
1523 bool Tabular::useBookTabs() const
1524 {
1525         return use_booktabs;
1526 }
1527
1528
1529 void Tabular::setLongTabular(bool what)
1530 {
1531         is_long_tabular = what;
1532 }
1533
1534
1535 bool Tabular::isLongTabular() const
1536 {
1537         return is_long_tabular;
1538 }
1539
1540
1541 void Tabular::setRotateTabular(bool flag)
1542 {
1543         rotate = flag;
1544 }
1545
1546
1547 bool Tabular::getRotateTabular() const
1548 {
1549         return rotate;
1550 }
1551
1552
1553 void Tabular::setRotateCell(idx_type cell, bool flag)
1554 {
1555         cellInfo(cell).rotate = flag;
1556 }
1557
1558
1559 bool Tabular::getRotateCell(idx_type cell) const
1560 {
1561         return cellInfo(cell).rotate;
1562 }
1563
1564
1565 bool Tabular::needRotating() const
1566 {
1567         if (rotate)
1568                 return true;
1569         for (row_type i = 0; i < rowCount(); ++i)
1570                 for (col_type j = 0; j < columnCount(); ++j)
1571                         if (cell_info[i][j].rotate)
1572                                 return true;
1573         return false;
1574 }
1575
1576
1577 bool Tabular::isLastCell(idx_type cell) const
1578 {
1579         if (cell + 1 < cellCount())
1580                 return false;
1581         return true;
1582 }
1583
1584
1585 Tabular::idx_type Tabular::cellAbove(idx_type cell) const
1586 {
1587         if (cellRow(cell) > 0)
1588                 return cell_info[cellRow(cell)-1][cellColumn(cell)].cellno;
1589         return cell;
1590 }
1591
1592
1593 Tabular::idx_type Tabular::cellBelow(idx_type cell) const
1594 {
1595         if (cellRow(cell) + 1 < rowCount())
1596                 return cell_info[cellRow(cell)+1][cellColumn(cell)].cellno;
1597         return cell;
1598 }
1599
1600
1601 Tabular::idx_type Tabular::cellIndex(row_type row,
1602                                                col_type column) const
1603 {
1604         BOOST_ASSERT(column != npos && column < columnCount() &&
1605                      row    != npos && row    < rowCount());
1606         return cell_info[row][column].cellno;
1607 }
1608
1609
1610 void Tabular::setUsebox(idx_type cell, BoxType type)
1611 {
1612         cellInfo(cell).usebox = type;
1613 }
1614
1615
1616 Tabular::BoxType Tabular::getUsebox(idx_type cell) const
1617 {
1618         if (column_info[cellColumn(cell)].p_width.zero() &&
1619                 !(isMultiColumn(cell) && !cellInfo(cell).p_width.zero()))
1620                 return BOX_NONE;
1621         if (cellInfo(cell).usebox > 1)
1622                 return cellInfo(cell).usebox;
1623         return useParbox(cell);
1624 }
1625
1626
1627 ///
1628 //  This are functions used for the longtable support
1629 ///
1630 void Tabular::setLTHead(row_type row, bool flag, ltType const & hd,
1631                            bool first)
1632 {
1633         if (first) {
1634                 endfirsthead = hd;
1635                 if (hd.set)
1636                         row_info[row].endfirsthead = flag;
1637         } else {
1638                 endhead = hd;
1639                 if (hd.set)
1640                         row_info[row].endhead = flag;
1641         }
1642 }
1643
1644
1645 bool Tabular::getRowOfLTHead(row_type row, ltType & hd) const
1646 {
1647         hd = endhead;
1648         hd.set = haveLTHead();
1649         return row_info[row].endhead;
1650 }
1651
1652
1653 bool Tabular::getRowOfLTFirstHead(row_type row, ltType & hd) const
1654 {
1655         hd = endfirsthead;
1656         hd.set = haveLTFirstHead();
1657         return row_info[row].endfirsthead;
1658 }
1659
1660
1661 void Tabular::setLTFoot(row_type row, bool flag, ltType const & fd,
1662                            bool last)
1663 {
1664         if (last) {
1665                 endlastfoot = fd;
1666                 if (fd.set)
1667                         row_info[row].endlastfoot = flag;
1668         } else {
1669                 endfoot = fd;
1670                 if (fd.set)
1671                         row_info[row].endfoot = flag;
1672         }
1673 }
1674
1675
1676 bool Tabular::getRowOfLTFoot(row_type row, ltType & fd) const
1677 {
1678         fd = endfoot;
1679         fd.set = haveLTFoot();
1680         return row_info[row].endfoot;
1681 }
1682
1683
1684 bool Tabular::getRowOfLTLastFoot(row_type row, ltType & fd) const
1685 {
1686         fd = endlastfoot;
1687         fd.set = haveLTLastFoot();
1688         return row_info[row].endlastfoot;
1689 }
1690
1691
1692 void Tabular::setLTNewPage(row_type row, bool what)
1693 {
1694         row_info[row].newpage = what;
1695 }
1696
1697
1698 bool Tabular::getLTNewPage(row_type row) const
1699 {
1700         return row_info[row].newpage;
1701 }
1702
1703
1704 bool Tabular::haveLTHead() const
1705 {
1706         for (row_type i = 0; i < rowCount(); ++i)
1707                 if (row_info[i].endhead)
1708                         return true;
1709         return false;
1710 }
1711
1712
1713 bool Tabular::haveLTFirstHead() const
1714 {
1715         if (endfirsthead.empty)
1716                 return false;
1717         for (row_type i = 0; i < rowCount(); ++i)
1718                 if (row_info[i].endfirsthead)
1719                         return true;
1720         return false;
1721 }
1722
1723
1724 bool Tabular::haveLTFoot() const
1725 {
1726         for (row_type i = 0; i < rowCount(); ++i)
1727                 if (row_info[i].endfoot)
1728                         return true;
1729         return false;
1730 }
1731
1732
1733 bool Tabular::haveLTLastFoot() const
1734 {
1735         if (endlastfoot.empty)
1736                 return false;
1737         for (row_type i = 0; i < rowCount(); ++i)
1738                 if (row_info[i].endlastfoot)
1739                         return true;
1740         return false;
1741 }
1742
1743
1744 // end longtable support functions
1745
1746 void Tabular::setRowAscent(row_type row, int height)
1747 {
1748         if (row >= rowCount() || row_info[row].ascent == height)
1749                 return;
1750         row_info[row].ascent = height;
1751 }
1752
1753
1754 void Tabular::setRowDescent(row_type row, int height)
1755 {
1756         if (row >= rowCount() || row_info[row].descent == height)
1757                 return;
1758         row_info[row].descent = height;
1759 }
1760
1761
1762 int Tabular::rowAscent(row_type row) const
1763 {
1764         if (row >= rowCount())
1765                 return 0;
1766         return row_info[row].ascent;
1767 }
1768
1769
1770 int Tabular::rowDescent(row_type row) const
1771 {
1772         LASSERT(row < rowCount(), /**/);
1773         return row_info[row].descent;
1774 }
1775
1776
1777 int Tabular::height() const
1778 {
1779         int height = 0;
1780         for (row_type row = 0; row < rowCount(); ++row)
1781                 height += rowAscent(row) + rowDescent(row) +
1782                         getAdditionalHeight(row);
1783         return height;
1784 }
1785
1786
1787 bool Tabular::isPartOfMultiColumn(row_type row, col_type column) const
1788 {
1789         LASSERT(row < rowCount(), /**/);
1790         LASSERT(column < columnCount(), /**/);
1791         return cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN;
1792 }
1793
1794
1795 int Tabular::TeXTopHLine(odocstream & os, row_type row) const
1796 {
1797         // FIXME: assert or return 0 as in TeXBottomHLine()?
1798         LASSERT(row != npos, /**/);
1799         LASSERT(row < rowCount(), /**/);
1800
1801         idx_type const fcell = getFirstCellInRow(row);
1802         idx_type const n = numberOfCellsInRow(fcell) + fcell;
1803         idx_type tmp = 0;
1804
1805         for (idx_type i = fcell; i < n; ++i) {
1806                 if (topLine(i))
1807                         ++tmp;
1808         }
1809         if (use_booktabs && row == 0) {
1810                 if (topLine(fcell))
1811                         os << "\\toprule ";
1812         } else if (tmp == n - fcell) {
1813                 os << (use_booktabs ? "\\midrule " : "\\hline ");
1814         } else if (tmp) {
1815                 for (idx_type i = fcell; i < n; ++i) {
1816                         if (topLine(i)) {
1817                                 os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
1818                                    << cellColumn(i) + 1
1819                                    << '-'
1820                                    << cellRightColumn(i) + 1
1821                                    << "} ";
1822                         }
1823                 }
1824         } else {
1825                 return 0;
1826         }
1827         os << "\n";
1828         return 1;
1829 }
1830
1831
1832 int Tabular::TeXBottomHLine(odocstream & os, row_type row) const
1833 {
1834         // FIXME: return 0 or assert as in TeXTopHLine()?
1835         if (row == npos || row >= rowCount())
1836                 return 0;
1837
1838         idx_type const fcell = getFirstCellInRow(row);
1839         idx_type const n = numberOfCellsInRow(fcell) + fcell;
1840         idx_type tmp = 0;
1841
1842         for (idx_type i = fcell; i < n; ++i) {
1843                 if (bottomLine(i))
1844                         ++tmp;
1845         }
1846         if (use_booktabs && row == rowCount() - 1) {
1847                 if (bottomLine(fcell))
1848                         os << "\\bottomrule";
1849         } else if (tmp == n - fcell) {
1850                 os << (use_booktabs ? "\\midrule" : "\\hline");
1851         } else if (tmp) {
1852                 for (idx_type i = fcell; i < n; ++i) {
1853                         if (bottomLine(i)) {
1854                                 os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
1855                                    << cellColumn(i) + 1
1856                                    << '-'
1857                                    << cellRightColumn(i) + 1
1858                                    << "} ";
1859                         }
1860                 }
1861         } else {
1862                 return 0;
1863         }
1864         os << "\n";
1865         return 1;
1866 }
1867
1868
1869 int Tabular::TeXCellPreamble(odocstream & os, idx_type cell, bool & ismulticol) const
1870 {
1871         int ret = 0;
1872
1873         Tabular::VAlignment valign =  getVAlignment(cell, !isMultiColumn(cell));
1874         LyXAlignment align = getAlignment(cell, !isMultiColumn(cell));
1875         // figure out how to set the lines
1876         // we always set double lines to the right of the cell
1877         row_type const r = cellRow(cell);
1878         col_type const c = cellColumn(cell);
1879         col_type const nextcol = c + columnSpan(cell);
1880         bool prevcellright = c > 0 && rightLine(cellIndex(r, c - 1));
1881         bool forceleft = ismulticol && !prevcellright && leftLine(cell);
1882         bool nextcolleft = nextcol < columnCount() && columnLeftLine(nextcol);
1883         bool coldouble = columnRightLine(c) && nextcolleft;
1884         bool nextcellleft = nextcol < columnCount() 
1885                 && leftLine(cellIndex(r, nextcol));
1886         bool celldouble = rightLine(cell) && nextcellleft;
1887         bool doubleright = celldouble && (isMultiColumn(cell) || !coldouble);
1888         ismulticol = isMultiColumn(cell) 
1889                 || (leftLine(cell) && !columnLeftLine(c))
1890                 || (rightLine(cell) && !columnRightLine(c))
1891                 || (!celldouble && coldouble) || doubleright || forceleft;
1892         if (ismulticol) {
1893                 os << "\\multicolumn{" << columnSpan(cell) << "}{";
1894                 if (leftLine(cell) || forceleft)
1895                         os << '|';
1896                 if (!cellInfo(cell).align_special.empty()) {
1897                         os << cellInfo(cell).align_special;
1898                 } else {
1899                         if (!getPWidth(cell).zero()) {
1900                                 switch (valign) {
1901                                 case LYX_VALIGN_TOP:
1902                                         os << 'p';
1903                                         break;
1904                                 case LYX_VALIGN_MIDDLE:
1905                                         os << 'm';
1906                                         break;
1907                                 case LYX_VALIGN_BOTTOM:
1908                                         os << 'b';
1909                                         break;
1910                                 }
1911                                 os << '{'
1912                                    << from_ascii(getPWidth(cell).asLatexString())
1913                                    << '}';
1914                         } else {
1915                                 switch (align) {
1916                                 case LYX_ALIGN_LEFT:
1917                                         os << 'l';
1918                                         break;
1919                                 case LYX_ALIGN_RIGHT:
1920                                         os << 'r';
1921                                         break;
1922                                 default:
1923                                         os << 'c';
1924                                         break;
1925                                 }
1926                         } // end if else !getPWidth
1927                 } // end if else !cellinfo_of_cell
1928                 if (rightLine(cell))
1929                         os << '|';
1930                 if (doubleright)
1931                         // add extra vertical line if we want a double one
1932                         os << '|';
1933                 os << "}{";
1934                 }
1935         if (getRotateCell(cell)) {
1936                 os << "\\begin{sideways}\n";
1937                 ++ret;
1938         }
1939         if (getUsebox(cell) == BOX_PARBOX) {
1940                 os << "\\parbox[";
1941                 switch (valign) {
1942                 case LYX_VALIGN_TOP:
1943                         os << 't';
1944                         break;
1945                 case LYX_VALIGN_MIDDLE:
1946                         os << 'c';
1947                         break;
1948                 case LYX_VALIGN_BOTTOM:
1949                         os << 'b';
1950                         break;
1951                 }
1952                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
1953                    << "}{";
1954         } else if (getUsebox(cell) == BOX_MINIPAGE) {
1955                 os << "\\begin{minipage}[";
1956                 switch (valign) {
1957                 case LYX_VALIGN_TOP:
1958                         os << 't';
1959                         break;
1960                 case LYX_VALIGN_MIDDLE:
1961                         os << 'm';
1962                         break;
1963                 case LYX_VALIGN_BOTTOM:
1964                         os << 'b';
1965                         break;
1966                 }
1967                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
1968                    << "}\n";
1969                 ++ret;
1970         }
1971         return ret;
1972 }
1973
1974
1975 int Tabular::TeXCellPostamble(odocstream & os, idx_type cell, bool ismulticol) const
1976 {
1977         int ret = 0;
1978
1979         // usual cells
1980         if (getUsebox(cell) == BOX_PARBOX)
1981                 os << '}';
1982         else if (getUsebox(cell) == BOX_MINIPAGE) {
1983                 os << "%\n\\end{minipage}";
1984                 ret += 2;
1985         }
1986         if (getRotateCell(cell)) {
1987                 os << "%\n\\end{sideways}";
1988                 ++ret;
1989         }
1990         if (ismulticol) {
1991                 os << '}';
1992         }
1993         return ret;
1994 }
1995
1996
1997 int Tabular::TeXLongtableHeaderFooter(odocstream & os,
1998                                          OutputParams const & runparams) const
1999 {
2000         if (!is_long_tabular)
2001                 return 0;
2002
2003         int ret = 0;
2004         // output header info
2005         if (haveLTHead()) {
2006                 if (endhead.topDL) {
2007                         os << "\\hline\n";
2008                         ++ret;
2009                 }
2010                 for (row_type i = 0; i < rowCount(); ++i) {
2011                         if (row_info[i].endhead) {
2012                                 ret += TeXRow(os, i, runparams);
2013                         }
2014                 }
2015                 if (endhead.bottomDL) {
2016                         os << "\\hline\n";
2017                         ++ret;
2018                 }
2019                 os << "\\endhead\n";
2020                 ++ret;
2021                 if (endfirsthead.empty) {
2022                         os << "\\endfirsthead\n";
2023                         ++ret;
2024                 }
2025         }
2026         // output firstheader info
2027         if (haveLTFirstHead()) {
2028                 if (endfirsthead.topDL) {
2029                         os << "\\hline\n";
2030                         ++ret;
2031                 }
2032                 for (row_type i = 0; i < rowCount(); ++i) {
2033                         if (row_info[i].endfirsthead) {
2034                                 ret += TeXRow(os, i, runparams);
2035                         }
2036                 }
2037                 if (endfirsthead.bottomDL) {
2038                         os << "\\hline\n";
2039                         ++ret;
2040                 }
2041                 os << "\\endfirsthead\n";
2042                 ++ret;
2043         }
2044         // output footer info
2045         if (haveLTFoot()) {
2046                 if (endfoot.topDL) {
2047                         os << "\\hline\n";
2048                         ++ret;
2049                 }
2050                 for (row_type i = 0; i < rowCount(); ++i) {
2051                         if (row_info[i].endfoot) {
2052                                 ret += TeXRow(os, i, runparams);
2053                         }
2054                 }
2055                 if (endfoot.bottomDL) {
2056                         os << "\\hline\n";
2057                         ++ret;
2058                 }
2059                 os << "\\endfoot\n";
2060                 ++ret;
2061                 if (endlastfoot.empty) {
2062                         os << "\\endlastfoot\n";
2063                         ++ret;
2064                 }
2065         }
2066         // output lastfooter info
2067         if (haveLTLastFoot()) {
2068                 if (endlastfoot.topDL) {
2069                         os << "\\hline\n";
2070                         ++ret;
2071                 }
2072                 for (row_type i = 0; i < rowCount(); ++i) {
2073                         if (row_info[i].endlastfoot) {
2074                                 ret += TeXRow(os, i, runparams);
2075                         }
2076                 }
2077                 if (endlastfoot.bottomDL) {
2078                         os << "\\hline\n";
2079                         ++ret;
2080                 }
2081                 os << "\\endlastfoot\n";
2082                 ++ret;
2083         }
2084         return ret;
2085 }
2086
2087
2088 bool Tabular::isValidRow(row_type row) const
2089 {
2090         if (!is_long_tabular)
2091                 return true;
2092         return !row_info[row].endhead && !row_info[row].endfirsthead &&
2093                         !row_info[row].endfoot && !row_info[row].endlastfoot;
2094 }
2095
2096
2097 int Tabular::TeXRow(odocstream & os, row_type i,
2098                        OutputParams const & runparams) const
2099 {
2100         idx_type cell = cellIndex(i, 0);
2101         int ret = TeXTopHLine(os, i);
2102         if (row_info[i].top_space_default) {
2103                 if (use_booktabs)
2104                         os << "\\addlinespace\n";
2105                 else
2106                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2107                 ++ret;
2108         } else if(!row_info[i].top_space.zero()) {
2109                 if (use_booktabs)
2110                         os << "\\addlinespace["
2111                            << from_ascii(row_info[i].top_space.asLatexString())
2112                            << "]\n";
2113                 else {
2114                         os << "\\noalign{\\vskip"
2115                            << from_ascii(row_info[i].top_space.asLatexString())
2116                            << "}\n";
2117                 }
2118                 ++ret;
2119         }
2120         bool ismulticol = false;
2121         for (col_type j = 0; j < columnCount(); ++j) {
2122                 if (isPartOfMultiColumn(i, j))
2123                         continue;
2124                 ret += TeXCellPreamble(os, cell, ismulticol);
2125                 shared_ptr<InsetTableCell> inset = cellInset(cell);
2126
2127                 Paragraph const & par = inset->paragraphs().front();
2128                 bool rtl = par.isRTL(buffer().params())
2129                         && !par.empty()
2130                         && getPWidth(cell).zero();
2131
2132                 if (rtl) {
2133                         if (par.getParLanguage(buffer().params())->lang() ==
2134                         "farsi")
2135                                 os << "\\textFR{";
2136                         else if (par.getParLanguage(buffer().params())->lang() == "arabic_arabi")
2137                                 os << "\\textAR{";
2138                         // currently, remaning RTL languages are arabic_arabtex and hebrew
2139                         else
2140                                 os << "\\R{";
2141                 }
2142                 ret += inset->latex(os, runparams);
2143                 if (rtl)
2144                         os << '}';
2145
2146                 ret += TeXCellPostamble(os, cell, ismulticol);
2147                 if (!isLastCellInRow(cell)) { // not last cell in row
2148                         os << " & ";
2149                 }
2150                 ++cell;
2151         }
2152         os << "\\tabularnewline";
2153         if (row_info[i].bottom_space_default) {
2154                 if (use_booktabs)
2155                         os << "\\addlinespace";
2156                 else
2157                         os << "[\\doublerulesep]";
2158         } else if (!row_info[i].bottom_space.zero()) {
2159                 if (use_booktabs)
2160                         os << "\\addlinespace";
2161                 os << '['
2162                    << from_ascii(row_info[i].bottom_space.asLatexString())
2163                    << ']';
2164         }
2165         os << '\n';
2166         ++ret;
2167         ret += TeXBottomHLine(os, i);
2168         if (row_info[i].interline_space_default) {
2169                 if (use_booktabs)
2170                         os << "\\addlinespace\n";
2171                 else
2172                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2173                 ++ret;
2174         } else if (!row_info[i].interline_space.zero()) {
2175                 if (use_booktabs)
2176                         os << "\\addlinespace["
2177                            << from_ascii(row_info[i].interline_space.asLatexString())
2178                            << "]\n";
2179                 else
2180                         os << "\\noalign{\\vskip"
2181                            << from_ascii(row_info[i].interline_space.asLatexString())
2182                            << "}\n";
2183                 ++ret;
2184         }
2185         return ret;
2186 }
2187
2188
2189 int Tabular::latex(odocstream & os, OutputParams const & runparams) const
2190 {
2191         int ret = 0;
2192
2193         //+---------------------------------------------------------------------
2194         //+                      first the opening preamble                    +
2195         //+---------------------------------------------------------------------
2196
2197         if (rotate) {
2198                 os << "\\begin{sideways}\n";
2199                 ++ret;
2200         }
2201         if (is_long_tabular)
2202                 os << "\\begin{longtable}{";
2203         else
2204                 os << "\\begin{tabular}{";
2205
2206         for (col_type i = 0; i < columnCount(); ++i) {
2207                 if (!use_booktabs && columnLeftLine(i))
2208                         os << '|';
2209                 if (!column_info[i].align_special.empty()) {
2210                         os << column_info[i].align_special;
2211                 } else {
2212                         if (!column_info[i].p_width.zero()) {
2213                                 switch (column_info[i].alignment) {
2214                                 case LYX_ALIGN_LEFT:
2215                                         os << ">{\\raggedright}";
2216                                         break;
2217                                 case LYX_ALIGN_RIGHT:
2218                                         os << ">{\\raggedleft}";
2219                                         break;
2220                                 case LYX_ALIGN_CENTER:
2221                                         os << ">{\\centering}";
2222                                         break;
2223                                 case LYX_ALIGN_NONE:
2224                                 case LYX_ALIGN_BLOCK:
2225                                 case LYX_ALIGN_LAYOUT:
2226                                 case LYX_ALIGN_SPECIAL:
2227                                         break;
2228                                 }
2229
2230                                 switch (column_info[i].valignment) {
2231                                 case LYX_VALIGN_TOP:
2232                                         os << 'p';
2233                                         break;
2234                                 case LYX_VALIGN_MIDDLE:
2235                                         os << 'm';
2236                                         break;
2237                                 case LYX_VALIGN_BOTTOM:
2238                                         os << 'b';
2239                                         break;
2240                         }
2241                                 os << '{'
2242                                    << from_ascii(column_info[i].p_width.asLatexString())
2243                                    << '}';
2244                         } else {
2245                                 switch (column_info[i].alignment) {
2246                                 case LYX_ALIGN_LEFT:
2247                                         os << 'l';
2248                                         break;
2249                                 case LYX_ALIGN_RIGHT:
2250                                         os << 'r';
2251                                         break;
2252                                 default:
2253                                         os << 'c';
2254                                         break;
2255                                 }
2256                         } // end if else !column_info[i].p_width
2257                 } // end if else !column_info[i].align_special
2258                 if (!use_booktabs && columnRightLine(i))
2259                         os << '|';
2260         }
2261         os << "}\n";
2262         ++ret;
2263
2264         ret += TeXLongtableHeaderFooter(os, runparams);
2265
2266         //+---------------------------------------------------------------------
2267         //+                      the single row and columns (cells)            +
2268         //+---------------------------------------------------------------------
2269
2270         for (row_type i = 0; i < rowCount(); ++i) {
2271                 if (isValidRow(i)) {
2272                         ret += TeXRow(os, i, runparams);
2273                         if (is_long_tabular && row_info[i].newpage) {
2274                                 os << "\\newpage\n";
2275                                 ++ret;
2276                         }
2277                 }
2278         }
2279
2280         //+---------------------------------------------------------------------
2281         //+                      the closing of the tabular                    +
2282         //+---------------------------------------------------------------------
2283
2284         if (is_long_tabular)
2285                 os << "\\end{longtable}";
2286         else
2287                 os << "\\end{tabular}";
2288         if (rotate) {
2289                 os << "\n\\end{sideways}";
2290                 ++ret;
2291         }
2292
2293         return ret;
2294 }
2295
2296
2297 int Tabular::docbookRow(odocstream & os, row_type row,
2298                            OutputParams const & runparams) const
2299 {
2300         int ret = 0;
2301         idx_type cell = getFirstCellInRow(row);
2302
2303         os << "<row>\n";
2304         for (col_type j = 0; j < columnCount(); ++j) {
2305                 if (isPartOfMultiColumn(row, j))
2306                         continue;
2307
2308                 os << "<entry align=\"";
2309                 switch (getAlignment(cell)) {
2310                 case LYX_ALIGN_LEFT:
2311                         os << "left";
2312                         break;
2313                 case LYX_ALIGN_RIGHT:
2314                         os << "right";
2315                         break;
2316                 default:
2317                         os << "center";
2318                         break;
2319                 }
2320
2321                 os << "\" valign=\"";
2322                 switch (getVAlignment(cell)) {
2323                 case LYX_VALIGN_TOP:
2324                         os << "top";
2325                         break;
2326                 case LYX_VALIGN_BOTTOM:
2327                         os << "bottom";
2328                         break;
2329                 case LYX_VALIGN_MIDDLE:
2330                         os << "middle";
2331                 }
2332                 os << '"';
2333
2334                 if (isMultiColumn(cell)) {
2335                         os << " namest=\"col" << j << "\" ";
2336                         os << "nameend=\"col" << j + columnSpan(cell) - 1<< '"';
2337                 }
2338
2339                 os << '>';
2340                 ret += cellInset(cell)->docbook(os, runparams);
2341                 os << "</entry>\n";
2342                 ++cell;
2343         }
2344         os << "</row>\n";
2345         return ret;
2346 }
2347
2348
2349 int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
2350 {
2351         int ret = 0;
2352
2353         //+---------------------------------------------------------------------
2354         //+                      first the opening preamble                    +
2355         //+---------------------------------------------------------------------
2356
2357         os << "<tgroup cols=\"" << columnCount()
2358            << "\" colsep=\"1\" rowsep=\"1\">\n";
2359
2360         for (col_type i = 0; i < columnCount(); ++i) {
2361                 os << "<colspec colname=\"col" << i << "\" align=\"";
2362                 switch (column_info[i].alignment) {
2363                 case LYX_ALIGN_LEFT:
2364                         os << "left";
2365                         break;
2366                 case LYX_ALIGN_RIGHT:
2367                         os << "right";
2368                         break;
2369                 default:
2370                         os << "center";
2371                         break;
2372                 }
2373                 os << '"';
2374                 if (runparams.flavor == OutputParams::XML)
2375                         os << '/';
2376                 os << ">\n";
2377                 ++ret;
2378         }
2379
2380         //+---------------------------------------------------------------------
2381         //+                      Long Tabular case                             +
2382         //+---------------------------------------------------------------------
2383
2384         // output header info
2385         if (haveLTHead() || haveLTFirstHead()) {
2386                 os << "<thead>\n";
2387                 ++ret;
2388                 for (row_type i = 0; i < rowCount(); ++i) {
2389                         if (row_info[i].endhead || row_info[i].endfirsthead) {
2390                                 ret += docbookRow(os, i, runparams);
2391                         }
2392                 }
2393                 os << "</thead>\n";
2394                 ++ret;
2395         }
2396         // output footer info
2397         if (haveLTFoot() || haveLTLastFoot()) {
2398                 os << "<tfoot>\n";
2399                 ++ret;
2400                 for (row_type i = 0; i < rowCount(); ++i) {
2401                         if (row_info[i].endfoot || row_info[i].endlastfoot) {
2402                                 ret += docbookRow(os, i, runparams);
2403                         }
2404                 }
2405                 os << "</tfoot>\n";
2406                 ++ret;
2407         }
2408
2409         //+---------------------------------------------------------------------
2410         //+                      the single row and columns (cells)            +
2411         //+---------------------------------------------------------------------
2412
2413         os << "<tbody>\n";
2414         ++ret;
2415         for (row_type i = 0; i < rowCount(); ++i) {
2416                 if (isValidRow(i)) {
2417                         ret += docbookRow(os, i, runparams);
2418                 }
2419         }
2420         os << "</tbody>\n";
2421         ++ret;
2422         //+---------------------------------------------------------------------
2423         //+                      the closing of the tabular                    +
2424         //+---------------------------------------------------------------------
2425
2426         os << "</tgroup>";
2427         ++ret;
2428
2429         return ret;
2430 }
2431
2432
2433 bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
2434                                    vector<unsigned int> const & clen) const
2435 {
2436         idx_type const fcell = getFirstCellInRow(row);
2437         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2438         idx_type tmp = 0;
2439
2440         for (idx_type i = fcell; i < n; ++i) {
2441                 if (topLine(i)) {
2442                         ++tmp;
2443                         break;
2444                 }
2445         }
2446         if (!tmp)
2447                 return false;
2448
2449         char_type ch;
2450         for (idx_type i = fcell; i < n; ++i) {
2451                 if (topLine(i)) {
2452                         if (leftLine(i))
2453                                 os << "+-";
2454                         else
2455                                 os << "--";
2456                         ch = '-';
2457                 } else {
2458                         os << "  ";
2459                         ch = ' ';
2460                 }
2461                 col_type column = cellColumn(i);
2462                 int len = clen[column];
2463                 while (column < columnCount() - 1
2464                        && isPartOfMultiColumn(row, ++column))
2465                         len += clen[column] + 4;
2466                 os << docstring(len, ch);
2467                 if (topLine(i)) {
2468                         if (rightLine(i))
2469                                 os << "-+";
2470                         else
2471                                 os << "--";
2472                 } else {
2473                         os << "  ";
2474                 }
2475         }
2476         os << endl;
2477         return true;
2478 }
2479
2480
2481 bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
2482                                       vector<unsigned int> const & clen) const
2483 {
2484         idx_type const fcell = getFirstCellInRow(row);
2485         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2486         idx_type tmp = 0;
2487
2488         for (idx_type i = fcell; i < n; ++i) {
2489                 if (bottomLine(i)) {
2490                         ++tmp;
2491                         break;
2492                 }
2493         }
2494         if (!tmp)
2495                 return false;
2496
2497         char_type ch;
2498         for (idx_type i = fcell; i < n; ++i) {
2499                 if (bottomLine(i)) {
2500                         if (leftLine(i))
2501                                 os << "+-";
2502                         else
2503                                 os << "--";
2504                         ch = '-';
2505                 } else {
2506                         os << "  ";
2507                         ch = ' ';
2508                 }
2509                 col_type column = cellColumn(i);
2510                 int len = clen[column];
2511                 while (column < columnCount() -1
2512                        && isPartOfMultiColumn(row, ++column))
2513                         len += clen[column] + 4;
2514                 os << docstring(len, ch);
2515                 if (bottomLine(i)) {
2516                         if (rightLine(i))
2517                                 os << "-+";
2518                         else
2519                                 os << "--";
2520                 } else {
2521                         os << "  ";
2522                 }
2523         }
2524         os << endl;
2525         return true;
2526 }
2527
2528
2529 void Tabular::plaintextPrintCell(odocstream & os,
2530                                OutputParams const & runparams,
2531                                idx_type cell, row_type row, col_type column,
2532                                vector<unsigned int> const & clen,
2533                                bool onlydata) const
2534 {
2535         odocstringstream sstr;
2536         cellInset(cell)->plaintext(sstr, runparams);
2537
2538         if (onlydata) {
2539                 os << sstr.str();
2540                 return;
2541         }
2542
2543         if (leftLine(cell))
2544                 os << "| ";
2545         else
2546                 os << "  ";
2547
2548         unsigned int len1 = sstr.str().length();
2549         unsigned int len2 = clen[column];
2550         while (column < columnCount() -1
2551                && isPartOfMultiColumn(row, ++column))
2552                 len2 += clen[column] + 4;
2553         len2 -= len1;
2554
2555         switch (getAlignment(cell)) {
2556         default:
2557         case LYX_ALIGN_LEFT:
2558                 len1 = 0;
2559                 break;
2560         case LYX_ALIGN_RIGHT:
2561                 len1 = len2;
2562                 len2 = 0;
2563                 break;
2564         case LYX_ALIGN_CENTER:
2565                 len1 = len2 / 2;
2566                 len2 -= len1;
2567                 break;
2568         }
2569
2570         os << docstring(len1, ' ') << sstr.str()
2571            << docstring(len2, ' ');
2572
2573         if (rightLine(cell))
2574                 os << " |";
2575         else
2576                 os << "  ";
2577 }
2578
2579
2580 void Tabular::plaintext(odocstream & os,
2581                            OutputParams const & runparams, int const depth,
2582                            bool onlydata, char_type delim) const
2583 {
2584         // first calculate the width of the single columns
2585         vector<unsigned int> clen(columnCount());
2586
2587         if (!onlydata) {
2588                 // first all non (real) multicolumn cells!
2589                 for (col_type j = 0; j < columnCount(); ++j) {
2590                         clen[j] = 0;
2591                         for (row_type i = 0; i < rowCount(); ++i) {
2592                                 idx_type cell = cellIndex(i, j);
2593                                 if (isMultiColumnReal(cell))
2594                                         continue;
2595                                 odocstringstream sstr;
2596                                 cellInset(cell)->plaintext(sstr, runparams);
2597                                 if (clen[j] < sstr.str().length())
2598                                         clen[j] = sstr.str().length();
2599                         }
2600                 }
2601                 // then all (real) multicolumn cells!
2602                 for (col_type j = 0; j < columnCount(); ++j) {
2603                         for (row_type i = 0; i < rowCount(); ++i) {
2604                                 idx_type cell = cellIndex(i, j);
2605                                 if (!isMultiColumnReal(cell) || isPartOfMultiColumn(i, j))
2606                                         continue;
2607                                 odocstringstream sstr;
2608                                 cellInset(cell)->plaintext(sstr, runparams);
2609                                 int len = int(sstr.str().length());
2610                                 idx_type const n = columnSpan(cell);
2611                                 for (col_type k = j; len > 0 && k < j + n - 1; ++k)
2612                                         len -= clen[k];
2613                                 if (len > int(clen[j + n - 1]))
2614                                         clen[j + n - 1] = len;
2615                         }
2616                 }
2617         }
2618         idx_type cell = 0;
2619         for (row_type i = 0; i < rowCount(); ++i) {
2620                 if (!onlydata && plaintextTopHLine(os, i, clen))
2621                         os << docstring(depth * 2, ' ');
2622                 for (col_type j = 0; j < columnCount(); ++j) {
2623                         if (isPartOfMultiColumn(i, j))
2624                                 continue;
2625                         if (onlydata && j > 0)
2626                                 // we don't use operator<< for single UCS4 character.
2627                                 // see explanation in docstream.h
2628                                 os.put(delim);
2629                         plaintextPrintCell(os, runparams, cell, i, j, clen, onlydata);
2630                         ++cell;
2631                 }
2632                 os << endl;
2633                 if (!onlydata) {
2634                         os << docstring(depth * 2, ' ');
2635                         if (plaintextBottomHLine(os, i, clen))
2636                                 os << docstring(depth * 2, ' ');
2637                 }
2638         }
2639 }
2640
2641
2642 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell) const
2643 {
2644         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
2645 }
2646
2647
2648 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row,
2649                                                col_type column) const
2650 {
2651         return cell_info[row][column].inset;
2652 }
2653
2654
2655 void Tabular::setCellInset(row_type row, col_type column,
2656                               shared_ptr<InsetTableCell> ins) const
2657 {
2658         CellData & cd = cell_info[row][column];
2659         cd.inset = ins;
2660         // reset the InsetTableCell's pointers
2661         ins->setCellData(&cd);
2662         ins->setTabular(this);
2663 }
2664
2665
2666 Tabular::idx_type
2667 Tabular::cellFromInset(Inset const * inset) const
2668 {
2669         // is this inset part of the tabular?
2670         if (!inset) {
2671                 lyxerr << "Error: this is not a cell of the tabular!" << endl;
2672                 LASSERT(false, /**/);
2673         }
2674
2675         for (idx_type cell = 0, n = cellCount(); cell < n; ++cell)
2676                 if (cellInset(cell).get() == inset) {
2677                         LYXERR(Debug::INSETTEXT, "Tabular::cellFromInset: "
2678                                 << "cell=" << cell);
2679                         return cell;
2680                 }
2681
2682         // We should have found a cell at this point
2683         lyxerr << "Tabular::cellFromInset: Cell of inset "
2684                 << inset << " not found!" << endl;
2685         LASSERT(false, /**/);
2686         // shut up compiler
2687         return 0;
2688 }
2689
2690
2691 void Tabular::validate(LaTeXFeatures & features) const
2692 {
2693         features.require("NeedTabularnewline");
2694         if (useBookTabs())
2695                 features.require("booktabs");
2696         if (isLongTabular())
2697                 features.require("longtable");
2698         if (needRotating())
2699                 features.require("rotating");
2700         for (idx_type cell = 0; cell < cellCount(); ++cell) {
2701                 if (getVAlignment(cell) != LYX_VALIGN_TOP ||
2702                      (!getPWidth(cell).zero() && !isMultiColumn(cell)))
2703                         features.require("array");
2704                 cellInset(cell)->validate(features);
2705         }
2706 }
2707
2708
2709 Tabular::BoxType Tabular::useParbox(idx_type cell) const
2710 {
2711         ParagraphList const & parlist = cellInset(cell)->paragraphs();
2712         ParagraphList::const_iterator cit = parlist.begin();
2713         ParagraphList::const_iterator end = parlist.end();
2714
2715         for (; cit != end; ++cit)
2716                 for (int i = 0; i < cit->size(); ++i)
2717                         if (cit->isNewline(i))
2718                                 return BOX_PARBOX;
2719
2720         return BOX_NONE;
2721 }
2722
2723
2724 /////////////////////////////////////////////////////////////////////
2725 //
2726 // InsetTableCell
2727 //
2728 /////////////////////////////////////////////////////////////////////
2729
2730 InsetTableCell::InsetTableCell(Buffer const & buf,
2731         Tabular::CellData const * cell, Tabular const * table)
2732         : InsetText(buf), cell_data_(cell), table_(table)
2733 {}
2734
2735
2736 bool InsetTableCell::forceEmptyLayout(idx_type) const
2737 {
2738         LASSERT(table_, /**/);
2739         LASSERT(cell_data_, /**/);
2740         return table_->getPWidth(cell_data_->cellno).zero();
2741 }
2742
2743 bool InsetTableCell::allowParagraphCustomization(idx_type) const
2744 {
2745         LASSERT(table_, /**/);
2746         LASSERT(cell_data_, /**/);
2747         return !table_->getPWidth(cell_data_->cellno).zero();
2748 }
2749
2750 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
2751         FuncStatus & status) const
2752 {
2753         bool enabled;
2754         switch (cmd.action) {
2755         case LFUN_LAYOUT:
2756                 enabled = !forceEmptyLayout();
2757                 break;
2758         case LFUN_LAYOUT_PARAGRAPH:
2759                 enabled = allowParagraphCustomization();
2760                 break;
2761         default:
2762                 return InsetText::getStatus(cur, cmd, status);
2763         }
2764         status.enabled(enabled);
2765         return true;
2766 }
2767
2768 /////////////////////////////////////////////////////////////////////
2769 //
2770 // InsetTabular
2771 //
2772 /////////////////////////////////////////////////////////////////////
2773
2774 InsetTabular::InsetTabular(Buffer const & buf, row_type rows,
2775                            col_type columns)
2776         : tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
2777         rowselect_(false), colselect_(false)
2778 {
2779         setBuffer(const_cast<Buffer &>(buf)); // FIXME: remove later
2780 }
2781
2782
2783 InsetTabular::InsetTabular(InsetTabular const & tab)
2784         : Inset(tab), tabular(tab.tabular),  scx_(0)
2785 {
2786         setBuffer(const_cast<Buffer &>(tab.buffer())); // FIXME: remove later
2787 }
2788
2789
2790 InsetTabular::~InsetTabular()
2791 {
2792         hideDialogs("tabular", this);
2793 }
2794
2795
2796 bool InsetTabular::insetAllowed(InsetCode code) const
2797 {
2798         if (code == MATHMACRO_CODE)
2799                 return false;
2800
2801         return true;
2802 }
2803
2804
2805 void InsetTabular::write(ostream & os) const
2806 {
2807         os << "Tabular" << endl;
2808         tabular.write(os);
2809 }
2810
2811
2812 docstring InsetTabular::contextMenu(BufferView const &, int, int) const
2813 {
2814         // FIXME: depending on the selection state, we could offer a different menu.
2815         return from_ascii("context-tabular");
2816 }
2817
2818
2819 void InsetTabular::read(Lexer & lex)
2820 {
2821         //bool const old_format = (lex.getString() == "\\LyXTable");
2822
2823         tabular.read(lex);
2824
2825         //if (old_format)
2826         //      return;
2827
2828         lex.next();
2829         string token = lex.getString();
2830         while (lex && token != "\\end_inset") {
2831                 lex.next();
2832                 token = lex.getString();
2833         }
2834         if (!lex)
2835                 lex.printError("Missing \\end_inset at this point. ");
2836 }
2837
2838
2839 int InsetTabular::rowFromY(Cursor & cur, int y) const
2840 {
2841         // top y coordinate of tabular
2842         int h = yo(cur.bv()) - tabular.rowAscent(0);
2843         size_t nrows = tabular.rowCount();
2844         row_type r = 0;
2845         for (; r < nrows && y > h; ++r) {
2846                 h += tabular.rowAscent(r);
2847                 h += tabular.rowDescent(r);
2848                 h += tabular.getAdditionalHeight(r);
2849         }
2850         return r - 1;
2851 }
2852
2853
2854 int InsetTabular::columnFromX(Cursor & cur, int x) const
2855 {
2856         // left x coordinate of tabular
2857         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
2858         size_t ncols = tabular.columnCount();
2859         col_type c = 0;
2860         for (; c < ncols && x > w; ++c)
2861                 w += tabular.columnWidth(c);
2862         return c - 1;
2863 }
2864
2865
2866 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
2867 {
2868         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
2869         //      mi.base.textwidth << "\n";
2870         if (!mi.base.bv) {
2871                 LYXERR0("need bv");
2872                 LASSERT(false, /**/);
2873         }
2874
2875         row_type i = 0;
2876         for (idx_type cell = 0; i < tabular.rowCount(); ++i) {
2877                 int maxAsc = 0;
2878                 int maxDesc = 0;
2879                 for (col_type j = 0; j < tabular.columnCount(); ++j) {
2880                         if (tabular.isPartOfMultiColumn(i, j))
2881                                 // Multicolumn cell, but not first one
2882                                 continue;
2883                         Dimension dim;
2884                         MetricsInfo m = mi;
2885                         Length p_width;
2886                         if (tabular.cell_info[i][j].multicolumn ==
2887                                 Tabular::CELL_BEGIN_OF_MULTICOLUMN)
2888                                 p_width = tabular.cellInfo(cell).p_width;
2889                         else
2890                                 p_width = tabular.column_info[j].p_width;
2891                         if (!p_width.zero())
2892                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
2893                         tabular.cellInset(cell)->metrics(m, dim);
2894                         if (!p_width.zero())
2895                                 dim.wid = m.base.textwidth;
2896                         tabular.setCellWidth(cell, dim.wid);
2897                         maxAsc  = max(maxAsc, dim.asc);
2898                         maxDesc = max(maxDesc, dim.des);
2899                         ++cell;
2900                 }
2901                 int const top_space = tabular.row_info[i].top_space_default ?
2902                         default_line_space :
2903                         tabular.row_info[i].top_space.inPixels(mi.base.textwidth);
2904                 tabular.setRowAscent(i, maxAsc + ADD_TO_HEIGHT + top_space);
2905                 int const bottom_space = tabular.row_info[i].bottom_space_default ?
2906                         default_line_space :
2907                         tabular.row_info[i].bottom_space.inPixels(mi.base.textwidth);
2908                 tabular.setRowDescent(i, maxDesc + ADD_TO_HEIGHT + bottom_space);
2909         }
2910         tabular.updateColumnWidths();
2911         dim.asc = tabular.rowAscent(0);
2912         dim.des = tabular.height() - dim.asc;
2913         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
2914 }
2915
2916
2917 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
2918 {
2919         //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
2920         BufferView * bv = pi.base.bv;
2921
2922         // FIXME: As the full backrgound is painted in drawSelection(),
2923         // we have no choice but to do a full repaint for the Text cells.
2924         pi.full_repaint = true;
2925
2926         resetPos(bv->cursor());
2927
2928         x += scx_;
2929         x += ADD_TO_TABULAR_WIDTH;
2930
2931         bool const original_drawing_state = pi.pain.isDrawingEnabled();
2932
2933         idx_type idx = 0;
2934         first_visible_cell = Tabular::npos;
2935         for (row_type i = 0; i < tabular.rowCount(); ++i) {
2936                 int nx = x;
2937                 int const a = tabular.rowAscent(i);
2938                 int const d = tabular.rowDescent(i);
2939                 idx = tabular.cellIndex(i, 0);
2940                 for (col_type j = 0; j < tabular.columnCount(); ++j) {
2941                         if (tabular.isPartOfMultiColumn(i, j))
2942                                 continue;
2943                         if (first_visible_cell == Tabular::npos)
2944                                 first_visible_cell = idx;
2945
2946                         int const cx = nx + tabular.getBeginningOfTextInCell(idx);
2947                         // Cache the Inset position.
2948                         bv->coordCache().insets().add(cell(idx).get(), cx, y);
2949                         if (nx + tabular.columnWidth(idx) < 0
2950                             || nx > bv->workWidth()
2951                             || y + d < 0
2952                             || y - a > bv->workHeight()) {
2953                                 pi.pain.setDrawingEnabled(false);
2954                                 cell(idx)->draw(pi, cx, y);
2955                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
2956                                 pi.pain.setDrawingEnabled(original_drawing_state);
2957                         } else {
2958                                 cell(idx)->draw(pi, cx, y);
2959                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
2960                         }
2961                         nx += tabular.columnWidth(idx);
2962                         ++idx;
2963                 }
2964
2965                 if (i + 1 < tabular.rowCount())
2966                         y += d + tabular.rowAscent(i + 1) +
2967                                 tabular.getAdditionalHeight(i + 1);
2968         }
2969 }
2970
2971
2972 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
2973 {
2974         Cursor & cur = pi.base.bv->cursor();
2975
2976         x += scx_ + ADD_TO_TABULAR_WIDTH;
2977
2978         // FIXME: it is wrong to completely paint the background
2979         // if we want to do single row painting.
2980
2981         // Paint background of current tabular
2982         int const w = tabular.width();
2983         int const h = tabular.height();
2984         int yy = y - tabular.rowAscent(0);
2985         pi.pain.fillRectangle(x, yy, w, h, backgroundColor());
2986
2987         if (!cur.selection())
2988                 return;
2989         if (&cur.inset() != this)
2990                 return;
2991
2992         //resetPos(cur);
2993
2994
2995         if (tablemode(cur)) {
2996                 row_type rs, re;
2997                 col_type cs, ce;
2998                 getSelection(cur, rs, re, cs, ce);
2999                 y -= tabular.rowAscent(0);
3000                 for (row_type j = 0; j < tabular.rowCount(); ++j) {
3001                         int const a = tabular.rowAscent(j);
3002                         int const h = a + tabular.rowDescent(j);
3003                         int xx = x;
3004                         y += tabular.getAdditionalHeight(j);
3005                         for (col_type i = 0; i < tabular.columnCount(); ++i) {
3006                                 if (tabular.isPartOfMultiColumn(j, i))
3007                                         continue;
3008                                 idx_type const cell =
3009                                         tabular.cellIndex(j, i);
3010                                 int const w = tabular.columnWidth(cell);
3011                                 if (i >= cs && i <= ce && j >= rs && j <= re)
3012                                         pi.pain.fillRectangle(xx, y, w, h,
3013                                                               Color_selection);
3014                                 xx += w;
3015                         }
3016                         y += h;
3017                 }
3018
3019         } else {
3020                 x += cellXPos(cur.idx());
3021                 x += tabular.getBeginningOfTextInCell(cur.idx());
3022                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3023         }
3024 }
3025
3026
3027 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
3028                                  row_type row, idx_type cell, bool erased) const
3029 {
3030         int x2 = x + tabular.columnWidth(cell);
3031         bool on_off = false;
3032         ColorCode col = Color_tabularline;
3033         ColorCode onoffcol = Color_tabularonoffline;
3034
3035         if (erased) {
3036                 col = Color_deletedtext;
3037                 onoffcol = Color_deletedtext;
3038         }
3039
3040         if (!tabular.topAlreadyDrawn(cell)) {
3041                 on_off = !tabular.topLine(cell);
3042                 pain.line(x, y - tabular.rowAscent(row),
3043                           x2, y -  tabular.rowAscent(row),
3044                           on_off ? onoffcol : col,
3045                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3046         }
3047         on_off = !tabular.bottomLine(cell);
3048         pain.line(x, y + tabular.rowDescent(row),
3049                   x2, y + tabular.rowDescent(row),
3050                   on_off ? onoffcol : col,
3051                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3052         if (!tabular.leftAlreadyDrawn(cell)) {
3053                 on_off = !tabular.leftLine(cell);
3054                 pain.line(x, y -  tabular.rowAscent(row),
3055                           x, y +  tabular.rowDescent(row),
3056                           on_off ? onoffcol : col,
3057                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3058         }
3059         on_off = !tabular.rightLine(cell);
3060         pain.line(x2 - tabular.getAdditionalWidth(cell),
3061                   y -  tabular.rowAscent(row),
3062                   x2 - tabular.getAdditionalWidth(cell),
3063                   y +  tabular.rowDescent(row),
3064                   on_off ? onoffcol : col,
3065                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3066 }
3067
3068
3069 docstring InsetTabular::editMessage() const
3070 {
3071         return _("Opened table");
3072 }
3073
3074
3075 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3076 {
3077         //lyxerr << "InsetTabular::edit: " << this << endl;
3078         cur.finishUndo();
3079         cur.selection() = false;
3080         cur.push(*this);
3081         if (front) {
3082                 if (isRightToLeft(cur))
3083                         cur.idx() = tabular.getLastCellInRow(0);
3084                 else
3085                         cur.idx() = 0;
3086                 cur.pit() = 0;
3087                 cur.pos() = 0;
3088         } else {
3089                 if (isRightToLeft(cur))
3090                         cur.idx() = tabular.getFirstCellInRow(tabular.rowCount() - 1);
3091                 else
3092                         cur.idx() = tabular.cellCount() - 1;
3093                 cur.pit() = 0;
3094                 cur.pos() = cur.lastpos(); // FIXME crude guess
3095         }
3096         // FIXME: this accesses the position cache before it is initialized
3097         //resetPos(cur);
3098         //cur.bv().fitCursor();
3099 }
3100
3101
3102 void InsetTabular::updateLabels(ParIterator const & it)
3103 {
3104         // In a longtable, tell captions what the current float is
3105         Counters & cnts = buffer().params().documentClass().counters();
3106         string const saveflt = cnts.current_float();
3107         if (tabular.isLongTabular())
3108                 cnts.current_float("table");
3109
3110         ParIterator it2 = it;
3111         it2.forwardPos();
3112         size_t const end = it2.nargs();
3113         for ( ; it2.idx() < end; it2.top().forwardIdx())
3114                 lyx::updateLabels(buffer(), it2);
3115
3116         //reset afterwards
3117         if (tabular.isLongTabular())
3118                 cnts.current_float(saveflt);
3119 }
3120
3121
3122 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3123 {
3124         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3125                              << "\n  cur:" << cur);
3126         CursorSlice sl = cur.top();
3127         Cursor & bvcur = cur.bv().cursor();
3128
3129         switch (cmd.action) {
3130
3131         case LFUN_MOUSE_PRESS: {
3132                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3133                 // select row
3134                 if (cmd.x < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3135                         || cmd.x > xo(cur.bv()) + tabular.width()) {
3136                         row_type r = rowFromY(cur, cmd.y);
3137                         cur.idx() = tabular.getFirstCellInRow(r);
3138                         cur.pos() = 0;
3139                         cur.resetAnchor();
3140                         cur.idx() = tabular.getLastCellInRow(r);
3141                         cur.pos() = cur.lastpos();
3142                         cur.selection() = true;
3143                         bvcur = cur; 
3144                         rowselect_ = true;
3145                         break;
3146                 }
3147                 // select column
3148                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0);
3149                 if (cmd.y < y0 + ADD_TO_TABULAR_WIDTH 
3150                         || cmd.y > y0 + tabular.height()) {
3151                         col_type c = columnFromX(cur, cmd.x);
3152                         cur.idx() = tabular.cellIndex(0, c);
3153                         cur.pos() = 0;
3154                         cur.resetAnchor();
3155                         cur.idx() = tabular.cellIndex(tabular.rowCount() - 1, c);
3156                         cur.pos() = cur.lastpos();
3157                         cur.selection() = true;
3158                         bvcur = cur; 
3159                         colselect_ = true;
3160                         break;
3161                 }
3162                 // do not reset cursor/selection if we have selected
3163                 // some cells (bug 2715).
3164                 if (cmd.button() == mouse_button::button3
3165                     && &bvcur.selBegin().inset() == this 
3166                     && tablemode(bvcur)) 
3167                         ;
3168                 else
3169                         // Let InsetTableCell do it
3170                         cell(cur.idx())->dispatch(cur, cmd);
3171                 break;
3172         }
3173         case LFUN_MOUSE_MOTION:
3174                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3175                 if (cmd.button() == mouse_button::button1) {
3176                         // only accept motions to places not deeper nested than the real anchor
3177                         if (!bvcur.anchor_.hasPart(cur)) {
3178                                 cur.undispatched();
3179                                 break;
3180                         }
3181                         // select (additional) row
3182                         if (rowselect_) {
3183                                 row_type r = rowFromY(cur, cmd.y);
3184                                 cur.idx() = tabular.getLastCellInRow(r);
3185                                 bvcur.setCursor(cur);
3186                                 bvcur.selection() = true;
3187                                 break;
3188                         }
3189                         // select (additional) column
3190                         if (colselect_) {
3191                                 col_type c = columnFromX(cur, cmd.x);
3192                                 cur.idx() = tabular.cellIndex(tabular.rowCount() - 1, c);
3193                                 bvcur.setCursor(cur);
3194                                 bvcur.selection() = true;
3195                                 break;
3196                         }
3197                         // only update if selection changes
3198                         if (bvcur.idx() == cur.idx() &&
3199                                 !(bvcur.anchor_.idx() == cur.idx() && bvcur.pos() != cur.pos()))
3200                                 cur.noUpdate();
3201                         setCursorFromCoordinates(cur, cmd.x, cmd.y);
3202                         bvcur.setCursor(cur);
3203                         bvcur.selection() = true;
3204                 }
3205                 break;
3206
3207         case LFUN_MOUSE_RELEASE:
3208                 rowselect_ = false;
3209                 colselect_ = false;
3210                 break;
3211
3212         case LFUN_CELL_BACKWARD:
3213                 movePrevCell(cur);
3214                 cur.selection() = false;
3215                 break;
3216
3217         case LFUN_CELL_FORWARD:
3218                 moveNextCell(cur);
3219                 cur.selection() = false;
3220                 break;
3221         case LFUN_CHAR_FORWARD_SELECT:
3222         case LFUN_CHAR_FORWARD:
3223         case LFUN_CHAR_BACKWARD_SELECT:
3224         case LFUN_CHAR_BACKWARD:
3225         case LFUN_CHAR_RIGHT_SELECT:
3226         case LFUN_CHAR_RIGHT:
3227         case LFUN_CHAR_LEFT_SELECT:
3228         case LFUN_CHAR_LEFT: {
3229
3230                 // determine whether we move to next or previous cell, where to enter 
3231                 // the new cell from, and which command to "finish" (i.e., exit the
3232                 // inset) with:
3233                 bool next_cell;
3234                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
3235                 FuncCode finish_lfun;
3236
3237                 if (cmd.action == LFUN_CHAR_FORWARD 
3238                                 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
3239                         next_cell = true;
3240                         finish_lfun = LFUN_FINISHED_FORWARD;
3241                 }
3242                 else if (cmd.action == LFUN_CHAR_BACKWARD
3243                                 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
3244                         next_cell = false;
3245                         finish_lfun = LFUN_FINISHED_BACKWARD;
3246                 }
3247                 // LEFT or RIGHT commands --- the interpretation will depend on the 
3248                 // table's direction.
3249                 else {
3250                         bool right = (cmd.action == LFUN_CHAR_RIGHT
3251                                                         || cmd.action == LFUN_CHAR_RIGHT_SELECT);
3252                         next_cell = (isRightToLeft(cur) != right);
3253                         
3254                         if (lyxrc.visual_cursor) {
3255                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
3256                         }
3257
3258                         if (right)
3259                                 finish_lfun = LFUN_FINISHED_RIGHT;
3260                         else
3261                                 finish_lfun = LFUN_FINISHED_LEFT;
3262                 }
3263                 
3264
3265                 // finally, now that we know what we want to do, do it!
3266                 cell(cur.idx())->dispatch(cur, cmd);
3267                 if (!cur.result().dispatched()) {
3268                         // move to next/prev cell, as appropriate
3269                         LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
3270                                 << " cell from: " << int(entry_from));
3271                         if (next_cell)
3272                                 moveNextCell(cur, entry_from);
3273                         else
3274                                 movePrevCell(cur, entry_from);
3275                         // if we're exiting the table, call the appropriate FINISHED lfun
3276                         if (sl == cur.top())
3277                                 cmd = FuncRequest(finish_lfun);
3278                         else
3279                                 cur.dispatched();
3280                 }
3281                 break;
3282
3283         }
3284
3285         case LFUN_DOWN_SELECT:
3286         case LFUN_DOWN:
3287                 cell(cur.idx())->dispatch(cur, cmd);
3288                 cur.dispatched(); // override the cell's decision
3289                 if (sl == cur.top())
3290                         // if our Text didn't do anything to the cursor
3291                         // then we try to put the cursor into the cell below
3292                         // setting also the right targetX.
3293                         if (tabular.cellRow(cur.idx()) != tabular.rowCount() - 1) {
3294                                 cur.idx() = tabular.cellBelow(cur.idx());
3295                                 cur.pit() = 0;
3296                                 TextMetrics const & tm =
3297                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3298                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3299                         }
3300                 if (sl == cur.top()) {
3301                         // we trick it to go to forward after leaving the
3302                         // tabular.
3303                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3304                         cur.undispatched();
3305                 }
3306                 break;
3307
3308         case LFUN_UP_SELECT:
3309         case LFUN_UP:
3310                 cell(cur.idx())->dispatch(cur, cmd);
3311                 cur.dispatched(); // override the cell's decision
3312                 if (sl == cur.top())
3313                         // if our Text didn't do anything to the cursor
3314                         // then we try to put the cursor into the cell above
3315                         // setting also the right targetX.
3316                         if (tabular.cellRow(cur.idx()) != 0) {
3317                                 cur.idx() = tabular.cellAbove(cur.idx());
3318                                 cur.pit() = cur.lastpit();
3319                                 Text const * text = cell(cur.idx())->getText(0);
3320                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3321                                 ParagraphMetrics const & pm =
3322                                         tm.parMetrics(cur.lastpit());
3323                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3324                         }
3325                 if (sl == cur.top()) {
3326                         cmd = FuncRequest(LFUN_UP);
3327                         cur.undispatched();
3328                 }
3329                 break;
3330
3331 //      case LFUN_SCREEN_DOWN: {
3332 //              //if (hasSelection())
3333 //              //      cur.selection() = false;
3334 //              col_type const col = tabular.cellColumn(cur.idx());
3335 //              int const t =   cur.bv().top_y() + cur.bv().height();
3336 //              if (t < yo() + tabular.getHeightOfTabular()) {
3337 //                      cur.bv().scrollDocView(t);
3338 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3339 //              } else {
3340 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3341 //              }
3342 //              cur.par() = 0;
3343 //              cur.pos() = 0;
3344 //              break;
3345 //      }
3346 //
3347 //      case LFUN_SCREEN_UP: {
3348 //              //if (hasSelection())
3349 //              //      cur.selection() = false;
3350 //              col_type const col = tabular.cellColumn(cur.idx());
3351 //              int const t =   cur.bv().top_y() + cur.bv().height();
3352 //              if (yo() < 0) {
3353 //                      cur.bv().scrollDocView(t);
3354 //                      if (yo() > 0)
3355 //                              cur.idx() = col;
3356 //                      else
3357 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3358 //              } else {
3359 //                      cur.idx() = col;
3360 //              }
3361 //              cur.par() = cur.lastpar();
3362 //              cur.pos() = cur.lastpos();
3363 //              break;
3364 //      }
3365
3366         case LFUN_LAYOUT_TABULAR:
3367                 cur.bv().showDialog("tabular", params2string(*this), this);
3368                 break;
3369
3370         case LFUN_INSET_DIALOG_UPDATE:
3371                 cur.bv().updateDialog("tabular", params2string(*this));
3372                 break;
3373
3374         case LFUN_TABULAR_FEATURE:
3375                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3376                         cur.undispatched();
3377                 break;
3378
3379         // insert file functions
3380         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3381         case LFUN_FILE_INSERT_PLAINTEXT: {
3382                 // FIXME UNICODE
3383                 docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
3384                         FileName(to_utf8(cmd.argument())));
3385                 if (tmpstr.empty())
3386                         break;
3387                 cur.recordUndoInset(INSERT_UNDO);
3388                 if (insertPlaintextString(cur.bv(), tmpstr, false)) {
3389                         // content has been replaced,
3390                         // so cursor might be invalid
3391                         cur.pos() = cur.lastpos();
3392                         cur.pit() = cur.lastpit();
3393                         bvcur.setCursor(cur);
3394                 } else
3395                         cur.undispatched();
3396                 break;
3397         }
3398
3399         case LFUN_CUT:
3400                 if (tablemode(cur)) {
3401                         if (copySelection(cur)) {
3402                                 cur.recordUndoInset(DELETE_UNDO);
3403                                 cutSelection(cur);
3404                         }
3405                 }
3406                 else
3407                         cell(cur.idx())->dispatch(cur, cmd);
3408                 break;
3409
3410         case LFUN_CHAR_DELETE_BACKWARD:
3411         case LFUN_CHAR_DELETE_FORWARD:
3412                 if (tablemode(cur)) {
3413                         cur.recordUndoInset(DELETE_UNDO);
3414                         cutSelection(cur);
3415                 }
3416                 else
3417                         cell(cur.idx())->dispatch(cur, cmd);
3418                 break;
3419
3420         case LFUN_COPY:
3421                 if (!cur.selection())
3422                         break;
3423                 if (tablemode(cur)) {
3424                         cur.finishUndo();
3425                         copySelection(cur);
3426                 } else
3427                         cell(cur.idx())->dispatch(cur, cmd);
3428                 break;
3429
3430         case LFUN_CLIPBOARD_PASTE:
3431         case LFUN_PRIMARY_SELECTION_PASTE: {
3432                 docstring const clip = (cmd.action == LFUN_CLIPBOARD_PASTE) ?
3433                         theClipboard().getAsText() :
3434                         theSelection().get();
3435                 if (clip.empty())
3436                         break;
3437                 // pass to InsertPlaintextString, but
3438                 // only if we have multi-cell content
3439                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
3440                         cur.recordUndoInset(INSERT_UNDO);
3441                         if (insertPlaintextString(cur.bv(), clip, false)) {
3442                                 // content has been replaced,
3443                                 // so cursor might be invalid
3444                                 cur.pos() = cur.lastpos();
3445                                 cur.pit() = cur.lastpit();
3446                                 bvcur.setCursor(cur);
3447                                 break;
3448                         }
3449                 }
3450                 // Let the cell handle normal text
3451                 cell(cur.idx())->dispatch(cur, cmd);
3452                 break;
3453         }
3454
3455         case LFUN_PASTE:
3456                 if (tabularStackDirty() && theClipboard().isInternal() ||
3457                     !theClipboard().hasInternal() && theClipboard().hasLyXContents()) {
3458                         cur.recordUndoInset(INSERT_UNDO);
3459                         pasteClipboard(cur);
3460                         break;
3461                 }
3462                 cell(cur.idx())->dispatch(cur, cmd);
3463                 break;
3464
3465         case LFUN_FONT_EMPH:
3466         case LFUN_FONT_BOLD:
3467         case LFUN_FONT_ROMAN:
3468         case LFUN_FONT_NOUN:
3469         case LFUN_FONT_ITAL:
3470         case LFUN_FONT_FRAK:
3471         case LFUN_FONT_TYPEWRITER:
3472         case LFUN_FONT_SANS:
3473         case LFUN_FONT_FREE_APPLY:
3474         case LFUN_FONT_FREE_UPDATE:
3475         case LFUN_FONT_SIZE:
3476         case LFUN_FONT_UNDERLINE:
3477         case LFUN_LANGUAGE:
3478         case LFUN_WORD_CAPITALIZE:
3479         case LFUN_WORD_UPCASE:
3480         case LFUN_WORD_LOWCASE:
3481         case LFUN_CHARS_TRANSPOSE:
3482                 if (tablemode(cur)) {
3483                         row_type rs, re;
3484                         col_type cs, ce;
3485                         getSelection(cur, rs, re, cs, ce);
3486                         Cursor tmpcur = cur;
3487                         for (row_type i = rs; i <= re; ++i) {
3488                                 for (col_type j = cs; j <= ce; ++j) {
3489                                         // cursor follows cell:
3490                                         tmpcur.idx() = tabular.cellIndex(i, j);
3491                                         // select this cell only:
3492                                         tmpcur.pit() = 0;
3493                                         tmpcur.pos() = 0;
3494                                         tmpcur.resetAnchor();
3495                                         tmpcur.pit() = tmpcur.lastpit();
3496                                         tmpcur.pos() = tmpcur.top().lastpos();
3497                                         tmpcur.setCursor(tmpcur);
3498                                         tmpcur.setSelection();
3499                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
3500                                 }
3501                         }
3502                         break;
3503                 } else {
3504                         cell(cur.idx())->dispatch(cur, cmd);
3505                         break;
3506                 }
3507         default:
3508                 // we try to handle this event in the insets dispatch function.
3509                 cell(cur.idx())->dispatch(cur, cmd);
3510                 break;
3511         }
3512 }
3513
3514
3515 // function sets an object as defined in func_status.h:
3516 // states OK, Unknown, Disabled, On, Off.
3517 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
3518         FuncStatus & status) const
3519 {
3520         switch (cmd.action) {
3521         case LFUN_TABULAR_FEATURE: {
3522                 int action = Tabular::LAST_ACTION;
3523                 int i = 0;
3524                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
3525                         string const tmp = tabularFeature[i].feature;
3526                         if (tmp == to_utf8(cmd.argument()).substr(0, tmp.length())) {
3527                                 action = tabularFeature[i].action;
3528                                 break;
3529                         }
3530                 }
3531                 if (action == Tabular::LAST_ACTION) {
3532                         status.clear();
3533                         status.unknown(true);
3534                         return true;
3535                 }
3536
3537                 string const argument
3538                         = ltrim(to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
3539
3540                 row_type sel_row_start = 0;
3541                 row_type sel_row_end = 0;
3542                 col_type sel_col_start = 0;
3543                 col_type sel_col_end = 0;
3544                 Tabular::ltType dummyltt;
3545                 bool flag = true;
3546
3547                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
3548
3549                 switch (action) {
3550                 case Tabular::SET_PWIDTH:
3551                 case Tabular::SET_MPWIDTH:
3552                 case Tabular::SET_SPECIAL_COLUMN:
3553                 case Tabular::SET_SPECIAL_MULTI:
3554                 case Tabular::APPEND_ROW:
3555                 case Tabular::APPEND_COLUMN:
3556                 case Tabular::DELETE_ROW:
3557                 case Tabular::DELETE_COLUMN:
3558                 case Tabular::COPY_ROW:
3559                 case Tabular::COPY_COLUMN:
3560                 case Tabular::SET_ALL_LINES:
3561                 case Tabular::UNSET_ALL_LINES:
3562                 case Tabular::SET_TOP_SPACE:
3563                 case Tabular::SET_BOTTOM_SPACE:
3564                 case Tabular::SET_INTERLINE_SPACE:
3565                 case Tabular::SET_BORDER_LINES:
3566                         status.clear();
3567                         return true;
3568
3569                 case Tabular::MULTICOLUMN:
3570                         status.enabled(sel_row_start == sel_row_end);
3571                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
3572                         break;
3573
3574                 case Tabular::TOGGLE_LINE_TOP:
3575                         status.setOnOff(tabular.topLine(cur.idx()));
3576                         break;
3577
3578                 case Tabular::TOGGLE_LINE_BOTTOM:
3579                         status.setOnOff(tabular.bottomLine(cur.idx()));
3580                         break;
3581
3582                 case Tabular::TOGGLE_LINE_LEFT:
3583                         status.setOnOff(tabular.leftLine(cur.idx()));
3584                         break;
3585
3586                 case Tabular::TOGGLE_LINE_RIGHT:
3587                         status.setOnOff(tabular.rightLine(cur.idx()));
3588                         break;
3589
3590                 case Tabular::M_ALIGN_LEFT:
3591                         flag = false;
3592                 case Tabular::ALIGN_LEFT:
3593                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
3594                         break;
3595
3596                 case Tabular::M_ALIGN_RIGHT:
3597                         flag = false;
3598                 case Tabular::ALIGN_RIGHT:
3599                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
3600                         break;
3601
3602                 case Tabular::M_ALIGN_CENTER:
3603                         flag = false;
3604                 case Tabular::ALIGN_CENTER:
3605                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
3606                         break;
3607
3608                 case Tabular::ALIGN_BLOCK:
3609                         status.enabled(!tabular.getPWidth(cur.idx()).zero());
3610                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
3611                         break;
3612
3613                 case Tabular::M_VALIGN_TOP:
3614                         flag = false;
3615                 case Tabular::VALIGN_TOP:
3616                         status.setOnOff(
3617                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
3618                         break;
3619
3620                 case Tabular::M_VALIGN_BOTTOM:
3621                         flag = false;
3622                 case Tabular::VALIGN_BOTTOM:
3623                         status.setOnOff(
3624                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
3625                         break;
3626
3627                 case Tabular::M_VALIGN_MIDDLE:
3628                         flag = false;
3629                 case Tabular::VALIGN_MIDDLE:
3630                         status.setOnOff(
3631                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
3632                         break;
3633
3634                 case Tabular::SET_LONGTABULAR:
3635                         status.setOnOff(tabular.isLongTabular());
3636                         break;
3637
3638                 case Tabular::UNSET_LONGTABULAR:
3639                         status.setOnOff(!tabular.isLongTabular());
3640                         break;
3641
3642                 case Tabular::TOGGLE_ROTATE_TABULAR:
3643                 case Tabular::SET_ROTATE_TABULAR:
3644                         status.setOnOff(tabular.getRotateTabular());
3645                         break;
3646
3647                 case Tabular::UNSET_ROTATE_TABULAR:
3648                         status.setOnOff(!tabular.getRotateTabular());
3649                         break;
3650
3651                 case Tabular::TOGGLE_ROTATE_CELL:
3652                 case Tabular::SET_ROTATE_CELL:
3653                         status.setOnOff(!oneCellHasRotationState(false,
3654                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3655                         break;
3656
3657                 case Tabular::UNSET_ROTATE_CELL:
3658                         status.setOnOff(!oneCellHasRotationState(true,
3659                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3660                         break;
3661
3662                 case Tabular::SET_USEBOX:
3663                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
3664                         break;
3665
3666                 case Tabular::SET_LTFIRSTHEAD:
3667                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3668                         break;
3669
3670                 case Tabular::UNSET_LTFIRSTHEAD:
3671                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3672                         break;
3673
3674                 case Tabular::SET_LTHEAD:
3675                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3676                         break;
3677
3678                 case Tabular::UNSET_LTHEAD:
3679                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3680                         break;
3681
3682                 case Tabular::SET_LTFOOT:
3683                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3684                         break;
3685
3686                 case Tabular::UNSET_LTFOOT:
3687                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3688                         break;
3689
3690                 case Tabular::SET_LTLASTFOOT:
3691                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3692                         break;
3693
3694                 case Tabular::UNSET_LTLASTFOOT:
3695                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3696                         break;
3697
3698                 case Tabular::SET_LTNEWPAGE:
3699                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
3700                         break;
3701
3702                 case Tabular::SET_BOOKTABS:
3703                         status.setOnOff(tabular.useBookTabs());
3704                         break;
3705
3706                 case Tabular::UNSET_BOOKTABS:
3707                         status.setOnOff(!tabular.useBookTabs());
3708                         break;
3709
3710                 default:
3711                         status.clear();
3712                         status.enabled(false);
3713                         break;
3714                 }
3715                 return true;
3716         }
3717
3718         // These are only enabled inside tabular
3719         case LFUN_CELL_BACKWARD:
3720         case LFUN_CELL_FORWARD:
3721                 status.enabled(true);
3722                 return true;
3723
3724         // disable these with multiple cells selected
3725         case LFUN_INSET_INSERT:
3726         case LFUN_TABULAR_INSERT:
3727         case LFUN_FLEX_INSERT:
3728         case LFUN_FLOAT_INSERT:
3729         case LFUN_FLOAT_WIDE_INSERT:
3730         case LFUN_FOOTNOTE_INSERT:
3731         case LFUN_MARGINALNOTE_INSERT:
3732         case LFUN_MATH_INSERT:
3733         case LFUN_MATH_MODE:
3734         case LFUN_MATH_MUTATE:
3735         case LFUN_MATH_DISPLAY:
3736         case LFUN_NOTE_INSERT:
3737         case LFUN_OPTIONAL_INSERT:
3738         case LFUN_BOX_INSERT:
3739         case LFUN_BRANCH_INSERT:
3740         case LFUN_WRAP_INSERT:
3741         case LFUN_ERT_INSERT: {
3742                 if (tablemode(cur)) {
3743                         status.enabled(false);
3744                         return true;
3745                 } else
3746                         return cell(cur.idx())->getStatus(cur, cmd, status);
3747         }
3748
3749         // disable in non-fixed-width cells
3750         case LFUN_NEWLINE_INSERT:
3751         case LFUN_BREAK_PARAGRAPH:
3752         case LFUN_BREAK_PARAGRAPH_SKIP: {
3753                 if (tabular.getPWidth(cur.idx()).zero()) {
3754                         status.enabled(false);
3755                         return true;
3756                 } else
3757                         return cell(cur.idx())->getStatus(cur, cmd, status);
3758         }
3759
3760         case LFUN_PASTE:
3761                 if (tabularStackDirty() && theClipboard().isInternal()) {
3762                         status.enabled(true);
3763                         return true;
3764                 } else
3765                         return cell(cur.idx())->getStatus(cur, cmd, status);
3766
3767         case LFUN_INSET_MODIFY:
3768                 if (insetCode(cmd.getArg(0)) == TABULAR_CODE) {
3769                         status.enabled(true);
3770                         return true;
3771                 }
3772                 // Fall through
3773
3774         default:
3775                 // we try to handle this event in the insets dispatch function.
3776                 return cell(cur.idx())->getStatus(cur, cmd, status);
3777         }
3778 }
3779
3780
3781 int InsetTabular::latex(odocstream & os, OutputParams const & runparams) const
3782 {
3783         return tabular.latex(os, runparams);
3784 }
3785
3786
3787 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
3788 {
3789         os << '\n'; // output table on a new line
3790         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
3791         tabular.plaintext(os, runparams, dp, false, 0);
3792         return PLAINTEXT_NEWLINE;
3793 }
3794
3795
3796 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
3797 {
3798         int ret = 0;
3799         Inset * master = 0;
3800
3801         // FIXME: Why not pass a proper DocIterator here?
3802 #if 0
3803         // if the table is inside a float it doesn't need the informaltable
3804         // wrapper. Search for it.
3805         for (master = owner(); master; master = master->owner())
3806                 if (master->lyxCode() == FLOAT_CODE)
3807                         break;
3808 #endif
3809
3810         if (!master) {
3811                 os << "<informaltable>";
3812                 ++ret;
3813         }
3814         ret += tabular.docbook(os, runparams);
3815         if (!master) {
3816                 os << "</informaltable>";
3817                 ++ret;
3818         }
3819         return ret;
3820 }
3821
3822
3823 void InsetTabular::validate(LaTeXFeatures & features) const
3824 {
3825         tabular.validate(features);
3826 }
3827
3828
3829 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
3830 {
3831         return tabular.cellInset(idx);
3832 }
3833
3834
3835 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
3836 {
3837         return tabular.cellInset(idx);
3838 }
3839
3840
3841 void InsetTabular::cursorPos(BufferView const & bv,
3842                 CursorSlice const & sl, bool boundary, int & x, int & y) const
3843 {
3844         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
3845
3846         // y offset     correction
3847         int const row = tabular.cellRow(sl.idx());
3848         for (int i = 0; i <= row; ++i) {
3849                 if (i != 0) {
3850                         y += tabular.rowAscent(i);
3851                         y += tabular.getAdditionalHeight(i);
3852                 }
3853                 if (i != row)
3854                         y += tabular.rowDescent(i);
3855         }
3856
3857         // x offset correction
3858         int const col = tabular.cellColumn(sl.idx());
3859         int idx = tabular.cellIndex(row, 0);
3860         for (int j = 0; j < col; ++j) {
3861                 if (tabular.isPartOfMultiColumn(row, j))
3862                         continue;
3863                 x += tabular.columnWidth(idx);
3864                 ++idx;
3865         }
3866         x += tabular.getBeginningOfTextInCell(idx);
3867         x += ADD_TO_TABULAR_WIDTH;
3868         x += scx_;
3869 }
3870
3871
3872 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
3873 {
3874         int xx = 0;
3875         int yy = 0;
3876         Inset const & inset = *tabular.cellInset(cell);
3877         Point o = bv.coordCache().getInsets().xy(&inset);
3878         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
3879         int const xend = xbeg + tabular.columnWidth(cell);
3880         row_type const row = tabular.cellRow(cell);
3881         int const ybeg = o.y_ - tabular.rowAscent(row) -
3882                          tabular.getAdditionalHeight(row);
3883         int const yend = o.y_ + tabular.rowDescent(row);
3884
3885         if (x < xbeg)
3886                 xx = xbeg - x;
3887         else if (x > xend)
3888                 xx = x - xend;
3889
3890         if (y < ybeg)
3891                 yy = ybeg - y;
3892         else if (y > yend)
3893                 yy = y - yend;
3894
3895         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
3896         //       << " ybeg=" << ybeg << " yend=" << yend
3897         //       << " xx=" << xx << " yy=" << yy
3898         //       << " dist=" << xx + yy << endl;
3899         return xx + yy;
3900 }
3901
3902
3903 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
3904 {
3905         //lyxerr << "InsetTabular::editXY: " << this << endl;
3906         cur.selection() = false;
3907         cur.push(*this);
3908         cur.idx() = getNearestCell(cur.bv(), x, y);
3909         resetPos(cur);
3910         return cur.bv().textMetrics(&cell(cur.idx())->text_).editXY(cur, x, y);
3911 }
3912
3913
3914 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
3915 {
3916         cur.idx() = getNearestCell(cur.bv(), x, y);
3917         cur.bv().textMetrics(&cell(cur.idx())->text_).setCursorFromCoordinates(cur, x, y);
3918 }
3919
3920
3921 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
3922 {
3923         idx_type idx_min = 0;
3924         int dist_min = numeric_limits<int>::max();
3925         for (idx_type i = 0, n = nargs(); i != n; ++i) {
3926                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
3927                         int const d = dist(bv, i, x, y);
3928                         if (d < dist_min) {
3929                                 dist_min = d;
3930                                 idx_min = i;
3931                         }
3932                 }
3933         }
3934         return idx_min;
3935 }
3936
3937
3938 int InsetTabular::cellXPos(idx_type const cell) const
3939 {
3940         idx_type c = cell;
3941
3942         for (; !tabular.isFirstCellInRow(c); --c)
3943                 ;
3944         int lx = 0;
3945         for (; c < cell; ++c)
3946                 lx += tabular.columnWidth(c);
3947
3948         return lx;
3949 }
3950
3951
3952 void InsetTabular::resetPos(Cursor & cur) const
3953 {
3954         BufferView & bv = cur.bv();
3955         int const maxwidth = bv.workWidth();
3956
3957         if (&cur.inset() != this) {
3958                 scx_ = 0;
3959         } else {
3960                 int const X1 = 0;
3961                 int const X2 = maxwidth;
3962                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
3963                 int const x1 = xo(cur.bv()) + cellXPos(cur.idx()) + offset;
3964                 int const x2 = x1 + tabular.columnWidth(cur.idx());
3965
3966                 if (x1 < X1)
3967                         scx_ = X1 + 20 - x1;
3968                 else if (x2 > X2)
3969                         scx_ = X2 - 20 - x2;
3970                 else
3971                         scx_ = 0;
3972         }
3973
3974         cur.updateFlags(Update::Force | Update::FitCursor);
3975 }
3976
3977
3978 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
3979 {
3980         if (isRightToLeft(cur)) {
3981                 if (tabular.isFirstCellInRow(cur.idx())) {
3982                         row_type const row = tabular.cellRow(cur.idx());
3983                         if (row == tabular.rowCount() - 1)
3984                                 return;
3985                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
3986                 } else {
3987                         if (cur.idx() == 0)
3988                                 return;
3989                         --cur.idx();
3990                 }
3991         } else {
3992                 if (tabular.isLastCell(cur.idx()))
3993                         return;
3994                 ++cur.idx();
3995         }
3996         cur.pit() = 0;
3997         cur.pos() = 0;
3998         cur.boundary(false);
3999
4000         // in visual mode, place cursor at extreme left or right
4001         
4002         switch(entry_from) {
4003
4004         case ENTRY_DIRECTION_RIGHT:
4005                 cur.posVisToRowExtremity(false /* !left */);
4006                 break;
4007         case ENTRY_DIRECTION_LEFT:
4008                 cur.posVisToRowExtremity(true /* left */);
4009                 break;
4010         case ENTRY_DIRECTION_IGNORE:
4011                 // nothing to do in this case
4012                 break;
4013
4014         }
4015
4016         resetPos(cur);
4017 }
4018
4019
4020 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
4021 {
4022         if (isRightToLeft(cur)) {
4023                 if (tabular.isLastCellInRow(cur.idx())) {
4024                         row_type const row = tabular.cellRow(cur.idx());
4025                         if (row == 0)
4026                                 return;
4027                         cur.idx() = tabular.getFirstCellInRow(row);
4028                         cur.idx() = tabular.cellAbove(cur.idx());
4029                 } else {
4030                         if (tabular.isLastCell(cur.idx()))
4031                                 return;
4032                         ++cur.idx();
4033                 }
4034         } else {
4035                 if (cur.idx() == 0) // first cell
4036                         return;
4037                 --cur.idx();
4038         }
4039         cur.pit() = cur.lastpit();
4040         cur.pos() = cur.lastpos();
4041
4042         // in visual mode, place cursor at extreme left or right
4043         
4044         switch(entry_from) {
4045
4046         case ENTRY_DIRECTION_RIGHT:
4047                 cur.posVisToRowExtremity(false /* !left */);
4048                 break;
4049         case ENTRY_DIRECTION_LEFT:
4050                 cur.posVisToRowExtremity(true /* left */);
4051                 break;
4052         case ENTRY_DIRECTION_IGNORE:
4053                 // nothing to do in this case
4054                 break;
4055
4056         }
4057
4058         // FIXME: this accesses the position cache before it is initialized
4059         //resetPos(cur);
4060 }
4061
4062
4063 bool InsetTabular::tabularFeatures(Cursor & cur, string const & what)
4064 {
4065         Tabular::Feature action = Tabular::LAST_ACTION;
4066
4067         int i = 0;
4068         for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4069                 string const tmp = tabularFeature[i].feature;
4070
4071                 if (tmp == what.substr(0, tmp.length())) {
4072                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
4073                         //tabularFeatures[i].feature.length()))
4074                         action = tabularFeature[i].action;
4075                         break;
4076                 }
4077         }
4078         if (action == Tabular::LAST_ACTION)
4079                 return false;
4080
4081         string const val =
4082                 ltrim(what.substr(tabularFeature[i].feature.length()));
4083         tabularFeatures(cur, action, val);
4084         return true;
4085 }
4086
4087
4088 static void checkLongtableSpecial(Tabular::ltType & ltt,
4089                           string const & special, bool & flag)
4090 {
4091         if (special == "dl_above") {
4092                 ltt.topDL = flag;
4093                 ltt.set = false;
4094         } else if (special == "dl_below") {
4095                 ltt.bottomDL = flag;
4096                 ltt.set = false;
4097         } else if (special == "empty") {
4098                 ltt.empty = flag;
4099                 ltt.set = false;
4100         } else if (flag) {
4101                 ltt.empty = false;
4102                 ltt.set = true;
4103         }
4104 }
4105
4106 bool InsetTabular::oneCellHasRotationState(bool rotated,
4107                 row_type row_start, row_type row_end,
4108                 col_type col_start, col_type col_end) const {
4109
4110         for (row_type i = row_start; i <= row_end; ++i) {
4111                 for (col_type j = col_start; j <= col_end; ++j) {
4112                         if (tabular.getRotateCell(tabular.cellIndex(i, j))
4113                                 == rotated) {
4114                                 return true;
4115                         }
4116                 }
4117         }
4118         return false;
4119 }
4120
4121 void InsetTabular::tabularFeatures(Cursor & cur,
4122         Tabular::Feature feature, string const & value)
4123 {
4124         col_type sel_col_start;
4125         col_type sel_col_end;
4126         row_type sel_row_start;
4127         row_type sel_row_end;
4128         bool setLines = false;
4129         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4130         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4131
4132         switch (feature) {
4133
4134         case Tabular::M_ALIGN_LEFT:
4135         case Tabular::ALIGN_LEFT:
4136                 setAlign = LYX_ALIGN_LEFT;
4137                 break;
4138
4139         case Tabular::M_ALIGN_RIGHT:
4140         case Tabular::ALIGN_RIGHT:
4141                 setAlign = LYX_ALIGN_RIGHT;
4142                 break;
4143
4144         case Tabular::M_ALIGN_CENTER:
4145         case Tabular::ALIGN_CENTER:
4146                 setAlign = LYX_ALIGN_CENTER;
4147                 break;
4148
4149         case Tabular::ALIGN_BLOCK:
4150                 setAlign = LYX_ALIGN_BLOCK;
4151                 break;
4152
4153         case Tabular::M_VALIGN_TOP:
4154         case Tabular::VALIGN_TOP:
4155                 setVAlign = Tabular::LYX_VALIGN_TOP;
4156                 break;
4157
4158         case Tabular::M_VALIGN_BOTTOM:
4159         case Tabular::VALIGN_BOTTOM:
4160                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4161                 break;
4162
4163         case Tabular::M_VALIGN_MIDDLE:
4164         case Tabular::VALIGN_MIDDLE:
4165                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4166                 break;
4167
4168         default:
4169                 break;
4170         }
4171
4172         cur.recordUndoInset(ATOMIC_UNDO);
4173
4174         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4175         row_type const row = tabular.cellRow(cur.idx());
4176         col_type const column = tabular.cellColumn(cur.idx());
4177         bool flag = true;
4178         Tabular::ltType ltt;
4179
4180         switch (feature) {
4181
4182         case Tabular::SET_PWIDTH: {
4183                 Length const len(value);
4184                 tabular.setColumnPWidth(cur, cur.idx(), len);
4185                 if (len.zero()
4186                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4187                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4188                 break;
4189         }
4190
4191         case Tabular::SET_MPWIDTH:
4192                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4193                 break;
4194
4195         case Tabular::SET_SPECIAL_COLUMN:
4196         case Tabular::SET_SPECIAL_MULTI:
4197                 tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4198                 break;
4199
4200         case Tabular::APPEND_ROW:
4201                 // append the row into the tabular
4202                 tabular.appendRow(cur.idx());
4203                 break;
4204
4205         case Tabular::APPEND_COLUMN:
4206                 // append the column into the tabular
4207                 tabular.appendColumn(cur.idx());
4208                 cur.idx() = tabular.cellIndex(row, column);
4209                 break;
4210
4211         case Tabular::DELETE_ROW:
4212                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4213                         tabular.deleteRow(sel_row_start);
4214                 if (sel_row_start >= tabular.rowCount())
4215                         --sel_row_start;
4216                 cur.idx() = tabular.cellIndex(sel_row_start, column);
4217                 cur.pit() = 0;
4218                 cur.pos() = 0;
4219                 cur.selection() = false;
4220                 break;
4221
4222         case Tabular::DELETE_COLUMN:
4223                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
4224                         tabular.deleteColumn(sel_col_start);
4225                 if (sel_col_start >= tabular.columnCount())
4226                         --sel_col_start;
4227                 cur.idx() = tabular.cellIndex(row, sel_col_start);
4228                 cur.pit() = 0;
4229                 cur.pos() = 0;
4230                 cur.selection() = false;
4231                 break;
4232
4233         case Tabular::COPY_ROW:
4234                 tabular.copyRow(row);
4235                 break;
4236
4237         case Tabular::COPY_COLUMN:
4238                 tabular.copyColumn(column);
4239                 cur.idx() = tabular.cellIndex(row, column);
4240                 break;
4241
4242         case Tabular::TOGGLE_LINE_TOP: {
4243                 bool lineSet = !tabular.topLine(cur.idx());
4244                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4245                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4246                                 tabular.setTopLine(tabular.cellIndex(i, j), lineSet);
4247                 break;
4248         }
4249
4250         case Tabular::TOGGLE_LINE_BOTTOM: {
4251                 bool lineSet = !tabular.bottomLine(cur.idx());
4252                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4253                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4254                                 tabular.setBottomLine(tabular.cellIndex(i, j), lineSet);
4255                 break;
4256         }
4257
4258         case Tabular::TOGGLE_LINE_LEFT: {
4259                 bool lineSet = !tabular.leftLine(cur.idx());
4260                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4261                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4262                                 tabular.setLeftLine(tabular.cellIndex(i, j), lineSet);
4263                 break;
4264         }
4265
4266         case Tabular::TOGGLE_LINE_RIGHT: {
4267                 bool lineSet = !tabular.rightLine(cur.idx());
4268                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4269                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4270                                 tabular.setRightLine(tabular.cellIndex(i, j), lineSet);
4271                 break;
4272         }
4273
4274         case Tabular::M_ALIGN_LEFT:
4275         case Tabular::M_ALIGN_RIGHT:
4276         case Tabular::M_ALIGN_CENTER:
4277                 flag = false;
4278         case Tabular::ALIGN_LEFT:
4279         case Tabular::ALIGN_RIGHT:
4280         case Tabular::ALIGN_CENTER:
4281         case Tabular::ALIGN_BLOCK:
4282                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4283                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4284                                 tabular.setAlignment(tabular.cellIndex(i, j), setAlign, flag);
4285                 break;
4286
4287         case Tabular::M_VALIGN_TOP:
4288         case Tabular::M_VALIGN_BOTTOM:
4289         case Tabular::M_VALIGN_MIDDLE:
4290                 flag = false;
4291         case Tabular::VALIGN_TOP:
4292         case Tabular::VALIGN_BOTTOM:
4293         case Tabular::VALIGN_MIDDLE:
4294                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4295                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4296                                 tabular.setVAlignment(tabular.cellIndex(i, j), setVAlign, flag);
4297                 break;
4298
4299         case Tabular::MULTICOLUMN: {
4300                 if (!cur.selection()) {
4301                         // just multicol for one single cell
4302                         // check whether we are completely in a multicol
4303                         if (tabular.isMultiColumn(cur.idx()))
4304                                 tabular.unsetMultiColumn(cur.idx());
4305                         else
4306                                 tabular.setMultiColumn(cur.idx(), 1);
4307                         break;
4308                 }
4309                 // we have a selection so this means we just add all this
4310                 // cells to form a multicolumn cell
4311                 idx_type const s_start = cur.selBegin().idx();
4312                 idx_type const s_end = cur.selEnd().idx();
4313                 tabular.setMultiColumn(s_start, s_end - s_start + 1);
4314                 cur.idx() = s_start;
4315                 cur.pit() = 0;
4316                 cur.pos() = 0;
4317                 cur.selection() = false;
4318                 break;
4319         }
4320
4321         case Tabular::SET_ALL_LINES:
4322                 setLines = true;
4323         case Tabular::UNSET_ALL_LINES:
4324                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4325                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4326                                 tabular.setAllLines(
4327                                         tabular.cellIndex(i,j), setLines);
4328                 break;
4329
4330         case Tabular::SET_BORDER_LINES:
4331                 for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4332                         tabular.setLeftLine(tabular.cellIndex(i, sel_col_start), true);
4333                         tabular.setRightLine(tabular.cellIndex(i, sel_col_end), true);
4334                 }
4335                 for (col_type j = sel_col_start; j <= sel_col_end; ++j) {
4336                         tabular.setTopLine(tabular.cellIndex(sel_row_start, j), true);
4337                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, j), true);
4338                 }
4339                 break;
4340
4341         case Tabular::SET_LONGTABULAR:
4342                 tabular.setLongTabular(true);
4343                 break;
4344
4345         case Tabular::UNSET_LONGTABULAR:
4346                 tabular.setLongTabular(false);
4347                 break;
4348
4349         case Tabular::SET_ROTATE_TABULAR:
4350                 tabular.setRotateTabular(true);
4351                 break;
4352
4353         case Tabular::UNSET_ROTATE_TABULAR:
4354                 tabular.setRotateTabular(false);
4355                 break;
4356
4357         case Tabular::TOGGLE_ROTATE_TABULAR:
4358                 tabular.setRotateTabular(!tabular.getRotateTabular());
4359                 break;
4360
4361         case Tabular::SET_ROTATE_CELL:
4362                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4363                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4364                                 tabular.setRotateCell(
4365                                         tabular.cellIndex(i, j), true);
4366                 break;
4367
4368         case Tabular::UNSET_ROTATE_CELL:
4369                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4370                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4371                                 tabular.setRotateCell(tabular.cellIndex(i, j), false);
4372                 break;
4373
4374         case Tabular::TOGGLE_ROTATE_CELL:
4375                 {
4376                 bool oneNotRotated = oneCellHasRotationState(false,
4377                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4378
4379                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4380                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4381                                 tabular.setRotateCell(tabular.cellIndex(i, j),
4382                                                                           oneNotRotated);
4383                 }
4384                 break;
4385
4386         case Tabular::SET_USEBOX: {
4387                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
4388                 if (val == tabular.getUsebox(cur.idx()))
4389                         val = Tabular::BOX_NONE;
4390                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4391                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4392                                 tabular.setUsebox(tabular.cellIndex(i, j), val);
4393                 break;
4394         }
4395
4396         case Tabular::UNSET_LTFIRSTHEAD:
4397                 flag = false;
4398         case Tabular::SET_LTFIRSTHEAD:
4399                 tabular.getRowOfLTFirstHead(row, ltt);
4400                 checkLongtableSpecial(ltt, value, flag);
4401                 tabular.setLTHead(row, flag, ltt, true);
4402                 break;
4403
4404         case Tabular::UNSET_LTHEAD:
4405                 flag = false;
4406         case Tabular::SET_LTHEAD:
4407                 tabular.getRowOfLTHead(row, ltt);
4408                 checkLongtableSpecial(ltt, value, flag);
4409                 tabular.setLTHead(row, flag, ltt, false);
4410                 break;
4411
4412         case Tabular::UNSET_LTFOOT:
4413                 flag = false;
4414         case Tabular::SET_LTFOOT:
4415                 tabular.getRowOfLTFoot(row, ltt);
4416                 checkLongtableSpecial(ltt, value, flag);
4417                 tabular.setLTFoot(row, flag, ltt, false);
4418                 break;
4419
4420         case Tabular::UNSET_LTLASTFOOT:
4421                 flag = false;
4422         case Tabular::SET_LTLASTFOOT:
4423                 tabular.getRowOfLTLastFoot(row, ltt);
4424                 checkLongtableSpecial(ltt, value, flag);
4425                 tabular.setLTFoot(row, flag, ltt, true);
4426                 break;
4427
4428         case Tabular::SET_LTNEWPAGE:
4429                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
4430                 break;
4431
4432         case Tabular::SET_BOOKTABS:
4433                 tabular.setBookTabs(true);
4434                 break;
4435
4436         case Tabular::UNSET_BOOKTABS:
4437                 tabular.setBookTabs(false);
4438                 break;
4439
4440         case Tabular::SET_TOP_SPACE: {
4441                 Length len;
4442                 if (value == "default")
4443                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4444                                 tabular.row_info[i].top_space_default = true;
4445                 else if (isValidLength(value, &len))
4446                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4447                                 tabular.row_info[i].top_space_default = false;
4448                                 tabular.row_info[i].top_space = len;
4449                         }
4450                 else
4451                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4452                                 tabular.row_info[i].top_space_default = false;
4453                                 tabular.row_info[i].top_space = len;
4454                         }
4455                 break;
4456         }
4457
4458         case Tabular::SET_BOTTOM_SPACE: {
4459                 Length len;
4460                 if (value == "default")
4461                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4462                                 tabular.row_info[i].bottom_space_default = true;
4463                 else if (isValidLength(value, &len))
4464                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4465                                 tabular.row_info[i].bottom_space_default = false;
4466                                 tabular.row_info[i].bottom_space = len;
4467                         }
4468                 else
4469                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4470                                 tabular.row_info[i].bottom_space_default = false;
4471                                 tabular.row_info[i].bottom_space = len;
4472                         }
4473                 break;
4474         }
4475
4476         case Tabular::SET_INTERLINE_SPACE: {
4477                 Length len;
4478                 if (value == "default")
4479                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4480                                 tabular.row_info[i].interline_space_default = true;
4481                 else if (isValidLength(value, &len))
4482                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4483                                 tabular.row_info[i].interline_space_default = false;
4484                                 tabular.row_info[i].interline_space = len;
4485                         }
4486                 else
4487                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4488                                 tabular.row_info[i].interline_space_default = false;
4489                                 tabular.row_info[i].interline_space = len;
4490                         }
4491                 break;
4492         }
4493
4494         // dummy stuff just to avoid warnings
4495         case Tabular::LAST_ACTION:
4496                 break;
4497         }
4498 }
4499
4500
4501 bool InsetTabular::showInsetDialog(BufferView * bv) const
4502 {
4503         bv->showDialog("tabular", params2string(*this),
4504                 const_cast<InsetTabular *>(this));
4505         return true;
4506 }
4507
4508
4509 void InsetTabular::openLayoutDialog(BufferView * bv) const
4510 {
4511         bv->showDialog("tabular", params2string(*this),
4512                 const_cast<InsetTabular *>(this));
4513 }
4514
4515
4516 bool InsetTabular::copySelection(Cursor & cur)
4517 {
4518         if (!cur.selection())
4519                 return false;
4520
4521         row_type rs, re;
4522         col_type cs, ce;
4523         getSelection(cur, rs, re, cs, ce);
4524
4525         paste_tabular.reset(new Tabular(tabular));
4526
4527         for (row_type i = 0; i < rs; ++i)
4528                 paste_tabular->deleteRow(0);
4529
4530         row_type const rows = re - rs + 1;
4531         while (paste_tabular->rowCount() > rows)
4532                 paste_tabular->deleteRow(rows);
4533
4534         for (col_type i = 0; i < cs; ++i)
4535                 paste_tabular->deleteColumn(0);
4536
4537         col_type const columns = ce - cs + 1;
4538         while (paste_tabular->columnCount() > columns)
4539                 paste_tabular->deleteColumn(columns);
4540
4541         // We clear all the InsetTableCell pointers, since they
4542         // might now become invalid and there is no point in having
4543         // them point to temporary things in paste_tabular.
4544         for (row_type i = 0; i < paste_tabular->rowCount(); ++i)
4545                 for (col_type j = 0; j < paste_tabular->columnCount(); ++j) {
4546                         paste_tabular->cellInset(i,j)->setCellData(0);
4547                         paste_tabular->cellInset(i,j)->setTabular(0);
4548                 }
4549
4550         odocstringstream os;
4551         OutputParams const runparams(0);
4552         paste_tabular->plaintext(os, runparams, 0, true, '\t');
4553         // Needed for the "Edit->Paste recent" menu and the system clipboard.
4554         cap::copySelection(cur, os.str());
4555
4556         // mark tabular stack dirty
4557         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
4558         // when we (hopefully) have a one-for-all paste mechanism.
4559         // This must be called after cap::copySelection.
4560         dirtyTabularStack(true);
4561
4562         return true;
4563 }
4564
4565
4566 bool InsetTabular::pasteClipboard(Cursor & cur)
4567 {
4568         if (!paste_tabular)
4569                 return false;
4570         col_type const actcol = tabular.cellColumn(cur.idx());
4571         row_type const actrow = tabular.cellRow(cur.idx());
4572         for (row_type r1 = 0, r2 = actrow;
4573              r1 < paste_tabular->rowCount() && r2 < tabular.rowCount();
4574              ++r1, ++r2) {
4575                 for (col_type c1 = 0, c2 = actcol;
4576                     c1 < paste_tabular->columnCount() && c2 < tabular.columnCount();
4577                     ++c1, ++c2) {
4578                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
4579                             tabular.isPartOfMultiColumn(r2, c2))
4580                                 continue;
4581                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
4582                                 --c2;
4583                                 continue;
4584                         }
4585                         if (tabular.isPartOfMultiColumn(r2, c2)) {
4586                                 --c1;
4587                                 continue;
4588                         }
4589                         shared_ptr<InsetTableCell> inset(
4590                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
4591                         // note that setCellInset will call InsetTableCell::setCellData()
4592                         // and InsetTableCell::setTabular()
4593                         tabular.setCellInset(r2, c2, inset);
4594                         // FIXME: change tracking (MG)
4595                         inset->setChange(Change(cur.buffer().params().trackChanges ?
4596                                                 Change::INSERTED : Change::UNCHANGED));
4597                         cur.pos() = 0;
4598                 }
4599         }
4600         return true;
4601 }
4602
4603
4604 void InsetTabular::cutSelection(Cursor & cur)
4605 {
4606         if (!cur.selection())
4607                 return;
4608
4609         row_type rs, re;
4610         col_type cs, ce;
4611         getSelection(cur, rs, re, cs, ce);
4612         for (row_type i = rs; i <= re; ++i) {
4613                 for (col_type j = cs; j <= ce; ++j) {
4614                         shared_ptr<InsetTableCell> t
4615                                 = cell(tabular.cellIndex(i, j));
4616                         if (cur.buffer().params().trackChanges)
4617                                 // FIXME: Change tracking (MG)
4618                                 t->setChange(Change(Change::DELETED));
4619                         else
4620                                 t->clear();
4621                 }
4622         }
4623
4624         // cursor position might be invalid now
4625         if (cur.pit() > cur.lastpit())
4626                 cur.pit() = cur.lastpit();
4627         if (cur.pos() > cur.lastpos())
4628                 cur.pos() = cur.lastpos();
4629         cur.clearSelection();
4630 }
4631
4632
4633 bool InsetTabular::isRightToLeft(Cursor & cur) const
4634 {
4635         LASSERT(cur.depth() > 1, /**/);
4636         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
4637         pos_type const parentpos = cur[cur.depth() - 2].pos();
4638         return parentpar.getFontSettings(cur.bv().buffer().params(),
4639                                          parentpos).language()->rightToLeft();
4640 }
4641
4642
4643 void InsetTabular::getSelection(Cursor & cur,
4644         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
4645 {
4646         CursorSlice const & beg = cur.selBegin();
4647         CursorSlice const & end = cur.selEnd();
4648         cs = tabular.cellColumn(beg.idx());
4649         ce = tabular.cellColumn(end.idx());
4650         if (cs > ce) {
4651                 ce = cs;
4652                 cs = tabular.cellColumn(end.idx());
4653         } else {
4654                 ce = tabular.cellRightColumn(end.idx());
4655         }
4656
4657         rs = tabular.cellRow(beg.idx());
4658         re = tabular.cellRow(end.idx());
4659         if (rs > re)
4660                 swap(rs, re);
4661 }
4662
4663
4664 Text * InsetTabular::getText(int idx) const
4665 {
4666         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
4667 }
4668
4669
4670 void InsetTabular::setChange(Change const & change)
4671 {
4672         for (idx_type idx = 0; idx < nargs(); ++idx)
4673                 cell(idx)->setChange(change);
4674 }
4675
4676
4677 void InsetTabular::acceptChanges(BufferParams const & bparams)
4678 {
4679         for (idx_type idx = 0; idx < nargs(); ++idx)
4680                 cell(idx)->acceptChanges(bparams);
4681 }
4682
4683
4684 void InsetTabular::rejectChanges(BufferParams const & bparams)
4685 {
4686         for (idx_type idx = 0; idx < nargs(); ++idx)
4687                 cell(idx)->rejectChanges(bparams);
4688 }
4689
4690
4691 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
4692 {
4693         return tabular.getPWidth(cell).zero();
4694 }
4695
4696
4697 bool InsetTabular::forceEmptyLayout(idx_type cell) const
4698 {
4699         return !tabular.getPWidth(cell).zero();
4700 }
4701
4702
4703 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
4704                                      bool usePaste)
4705 {
4706         if (buf.length() <= 0)
4707                 return true;
4708
4709         col_type cols = 1;
4710         row_type rows = 1;
4711         col_type maxCols = 1;
4712         size_t const len = buf.length();
4713         size_t p = 0;
4714
4715         while (p < len &&
4716                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
4717                 switch (buf[p]) {
4718                 case '\t':
4719                         ++cols;
4720                         break;
4721                 case '\n':
4722                         if (p + 1 < len)
4723                                 ++rows;
4724                         maxCols = max(cols, maxCols);
4725                         cols = 1;
4726                         break;
4727                 }
4728                 ++p;
4729         }
4730         maxCols = max(cols, maxCols);
4731         Tabular * loctab;
4732         idx_type cell = 0;
4733         col_type ocol = 0;
4734         row_type row = 0;
4735         if (usePaste) {
4736                 paste_tabular.reset(new Tabular(buffer(), rows, maxCols));
4737                 loctab = paste_tabular.get();
4738                 cols = 0;
4739                 dirtyTabularStack(true);
4740         } else {
4741                 loctab = &tabular;
4742                 cell = bv.cursor().idx();
4743                 ocol = tabular.cellColumn(cell);
4744                 row = tabular.cellRow(cell);
4745         }
4746
4747         size_t op = 0;
4748         idx_type const cells = loctab->cellCount();
4749         p = 0;
4750         cols = ocol;
4751         rows = loctab->rowCount();
4752         col_type const columns = loctab->columnCount();
4753
4754         while (cell < cells && p < len && row < rows &&
4755                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
4756         {
4757                 if (p >= len)
4758                         break;
4759                 switch (buf[p]) {
4760                 case '\t':
4761                         // we can only set this if we are not too far right
4762                         if (cols < columns) {
4763                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
4764                                 Font const font = bv.textMetrics(&inset->text_).
4765                                         displayFont(0, 0);
4766                                 inset->setText(buf.substr(op, p - op), font,
4767                                                buffer().params().trackChanges);
4768                                 ++cols;
4769                                 ++cell;
4770                         }
4771                         break;
4772                 case '\n':
4773                         // we can only set this if we are not too far right
4774                         if (cols < columns) {
4775                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
4776                                 Font const font = bv.textMetrics(&inset->text_).
4777                                         displayFont(0, 0);
4778                                 inset->setText(buf.substr(op, p - op), font,
4779                                                buffer().params().trackChanges);
4780                         }
4781                         cols = ocol;
4782                         ++row;
4783                         if (row < rows)
4784                                 cell = loctab->cellIndex(row, cols);
4785                         break;
4786                 }
4787                 ++p;
4788                 op = p;
4789         }
4790         // check for the last cell if there is no trailing '\n'
4791         if (cell < cells && op < len) {
4792                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
4793                 Font const font = bv.textMetrics(&inset->text_).displayFont(0, 0);
4794                 inset->setText(buf.substr(op, len - op), font,
4795                         buffer().params().trackChanges);
4796         }
4797         return true;
4798 }
4799
4800
4801 void InsetTabular::addPreview(PreviewLoader & loader) const
4802 {
4803         row_type const rows = tabular.rowCount();
4804         col_type const columns = tabular.columnCount();
4805         for (row_type i = 0; i < rows; ++i) {
4806                 for (col_type j = 0; j < columns; ++j)
4807                         tabular.cellInset(i, j)->addPreview(loader);
4808         }
4809 }
4810
4811
4812 bool InsetTabular::tablemode(Cursor & cur) const
4813 {
4814         return cur.selection() && cur.selBegin().idx() != cur.selEnd().idx();
4815 }
4816
4817
4818 bool InsetTabular::completionSupported(Cursor const & cur) const
4819 {
4820         Cursor const & bvCur = cur.bv().cursor();
4821         if (&bvCur.inset() != this)
4822                 return false;
4823         return cur.text()->completionSupported(cur);
4824 }
4825
4826
4827 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
4828 {
4829         return completionSupported(cur);
4830 }
4831
4832
4833 bool InsetTabular::automaticInlineCompletion() const
4834 {
4835         return lyxrc.completion_inline_text;
4836 }
4837
4838
4839 bool InsetTabular::automaticPopupCompletion() const
4840 {
4841         return lyxrc.completion_popup_text;
4842 }
4843
4844
4845 bool InsetTabular::showCompletionCursor() const
4846 {
4847         return lyxrc.completion_cursor_text;
4848 }
4849
4850
4851 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
4852 {
4853         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
4854 }
4855
4856
4857 docstring InsetTabular::completionPrefix(Cursor const & cur) const
4858 {
4859         if (!completionSupported(cur))
4860                 return docstring();
4861         return cur.text()->completionPrefix(cur);
4862 }
4863
4864
4865 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
4866 {
4867         if (!completionSupported(cur))
4868                 return false;
4869
4870         return cur.text()->insertCompletion(cur, s, finished);
4871 }
4872
4873
4874 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
4875                                     Dimension & dim) const
4876 {
4877         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
4878         tm.completionPosAndDim(cur, x, y, dim);
4879 }
4880
4881
4882 void InsetTabular::string2params(string const & in, InsetTabular & inset)
4883 {
4884         istringstream data(in);
4885         Lexer lex;
4886         lex.setStream(data);
4887
4888         if (in.empty())
4889                 return;
4890
4891         string token;
4892         lex >> token;
4893         if (!lex || token != "tabular") {
4894                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
4895                 return;
4896         }
4897
4898         // This is part of the inset proper that is usually swallowed
4899         // by Buffer::readInset
4900         lex >> token;
4901         if (!lex || token != "Tabular") {
4902                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
4903                 return;
4904         }
4905
4906         inset.read(lex);
4907 }
4908
4909
4910 string InsetTabular::params2string(InsetTabular const & inset)
4911 {
4912         ostringstream data;
4913         data << "tabular" << ' ';
4914         inset.write(data);
4915         data << "\\end_inset\n";
4916         return data.str();
4917 }
4918
4919
4920 } // namespace lyx