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