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