1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2001 The LyX Team.
9 * This file is Copyright 1996-2001
12 * ======================================================
18 #pragma implementation
22 #include "bufferlist.h"
24 #include "lyx_gui_misc.h"
25 #include "LyXAction.h"
28 #include "tex-strings.h"
30 #include "bufferview_funcs.h"
37 #include "LaTeXFeatures.h"
44 #include "converter.h"
45 #include "BufferView.h"
46 #include "ParagraphParameters.h"
47 #include "iterators.h"
48 #include "lyxtextclasslist.h"
50 #include "mathed/formulamacro.h"
51 #include "mathed/formula.h"
53 #include "insets/inset.h"
54 #include "insets/inseterror.h"
55 #include "insets/insetlabel.h"
56 #include "insets/insetref.h"
57 #include "insets/inseturl.h"
58 #include "insets/insetnote.h"
59 #include "insets/insetquotes.h"
60 #include "insets/insetlatexaccent.h"
61 #include "insets/insetbib.h"
62 #include "insets/insetcite.h"
63 #include "insets/insetexternal.h"
64 #include "insets/insetindex.h"
65 #include "insets/insetinclude.h"
66 #include "insets/insettoc.h"
67 #include "insets/insetparent.h"
68 #include "insets/insetspecialchar.h"
69 #include "insets/figinset.h"
70 #include "insets/insettext.h"
71 #include "insets/insetert.h"
72 #include "insets/insetgraphics.h"
73 #include "insets/insetfoot.h"
74 #include "insets/insetmarginal.h"
75 #include "insets/insetminipage.h"
76 #include "insets/insetfloat.h"
77 #include "insets/insettabular.h"
79 #include "insets/insettheorem.h"
80 #include "insets/insetlist.h"
82 #include "insets/insetcaption.h"
83 #include "insets/insetfloatlist.h"
85 #include "frontends/Dialogs.h"
86 #include "frontends/Alert.h"
88 #include "support/textutils.h"
89 #include "support/filetools.h"
90 #include "support/path.h"
91 #include "support/os.h"
92 #include "support/lyxlib.h"
93 #include "support/FileInfo.h"
94 #include "support/lyxmanip.h"
95 #include "support/lyxalgo.h" // for lyx::count
107 #include <sys/types.h>
124 using std::make_pair;
133 using lyx::layout_type;
134 using lyx::textclass_type;
136 // all these externs should eventually be removed.
137 extern BufferList bufferlist;
139 extern LyXAction lyxaction;
143 const int LYX_FORMAT = 220;
147 extern int tex_code_break_column;
150 Buffer::Buffer(string const & file, bool ronly)
151 : paragraph(0), lyx_clean(true), bak_clean(true),
152 unnamed(false), dep_clean(0), read_only(ronly),
153 filename_(file), users(0)
155 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
157 filepath_ = OnlyPath(file);
162 // read_only = ronly;
166 if (read_only || lyxrc.use_tempdir) {
167 tmppath = CreateBufferTmpDir();
176 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
177 // here the buffer should take care that it is
178 // saved properly, before it goes into the void.
180 // make sure that views using this buffer
185 if (!tmppath.empty()) {
186 DestroyBufferTmpDir(tmppath);
189 Paragraph * par = paragraph;
192 tmppar = par->next();
200 string const Buffer::getLatexName(bool no_path) const
202 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
204 return OnlyFilename(name);
210 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
212 string const filename = getLatexName(false);
214 if (filename.empty())
215 return make_pair(Buffer::latexlog, string());
217 string path = OnlyPath(filename);
219 if (lyxrc.use_tempdir || !IsDirWriteable(path))
222 string const fname = AddName(path,
223 OnlyFilename(ChangeExtension(filename,
226 AddName(path, OnlyFilename(
227 ChangeExtension(filename,
228 formats.extension("literate") + ".out")));
230 // If no Latex log or Build log is newer, show Build log
232 FileInfo const f_fi(fname);
233 FileInfo const b_fi(bname);
236 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
237 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
238 return make_pair(Buffer::buildlog, bname);
240 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
241 return make_pair(Buffer::latexlog, fname);
245 void Buffer::setReadonly(bool flag)
247 if (read_only != flag) {
250 users->owner()->getDialogs()->updateBufferDependent(false);
255 /// Update window titles of all users
256 // Should work on a list
257 void Buffer::updateTitles() const
260 users->owner()->updateWindowTitle();
264 /// Reset autosave timer of all users
265 // Should work on a list
266 void Buffer::resetAutosaveTimers() const
269 users->owner()->resetAutosaveTimer();
273 void Buffer::setFileName(string const & newfile)
275 filename_ = MakeAbsPath(newfile);
276 filepath_ = OnlyPath(filename_);
277 setReadonly(IsFileWriteable(filename_) == 0);
282 // We'll remove this later. (Lgb)
285 string last_inset_read;
287 #ifndef NO_COMPABILITY
290 ErtComp() : active(false), in_tabular(false) {
298 std::stack<ErtComp> ert_stack;
303 #warning And _why_ is this here? (Lgb)
311 // candidate for move to BufferView
312 // (at least some parts in the beginning of the func)
315 // changed to be public and have one parameter
316 // if par = 0 normal behavior
317 // else insert behavior
318 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
319 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
323 #ifndef NO_COMPABILITY
324 ert_comp.contents.erase();
325 ert_comp.active = false;
326 ert_comp.in_tabular = false;
329 Paragraph::depth_type depth = 0;
330 bool the_end_read = false;
332 Paragraph * first_par = 0;
333 LyXFont font(LyXFont::ALL_INHERIT, params.language);
334 if (file_format < 216 && params.language->lang() == "hebrew")
335 font.setLanguage(default_language);
340 // We are inserting into an existing document
341 users->text->breakParagraph(users);
342 first_par = users->text->ownerParagraph();
345 // We don't want to adopt the parameters from the
346 // document we insert, so we skip until the text begins:
349 string const pretoken = lex.getString();
350 if (pretoken == "\\layout") {
351 lex.pushToken(pretoken);
359 string const token = lex.getString();
361 if (token.empty()) continue;
363 lyxerr[Debug::PARSER] << "Handling token: `"
364 << token << "'" << endl;
367 parseSingleLyXformat2Token(lex, par, first_par,
375 paragraph = first_par;
377 if (unknown_layouts > 0) {
378 string s = _("Couldn't set the layout for ");
379 if (unknown_layouts == 1) {
380 s += _("one paragraph");
382 s += tostr(unknown_layouts);
383 s += _(" paragraphs");
385 Alert::alert(_("Textclass Loading Error!"), s,
386 _("When reading " + fileName()));
389 if (unknown_tokens > 0) {
390 string s = _("Encountered ");
391 if (unknown_tokens == 1) {
392 s += _("one unknown token");
394 s += tostr(unknown_tokens);
395 s += _(" unknown tokens");
397 Alert::alert(_("Textclass Loading Error!"), s,
398 _("When reading " + fileName()));
405 #ifndef NO_COMPABILITY
406 void Buffer::insertErtContents(Paragraph * par, int & pos, bool set_inactive)
408 if (!ert_comp.contents.empty()) {
409 lyxerr[Debug::INSETS] << "ERT contents:\n'"
410 << ert_comp.contents << "'" << endl;
411 Inset * inset = new InsetERT(params.language, ert_comp.contents, true);
412 par->insertInset(pos++, inset, ert_comp.font);
413 ert_comp.contents.erase();
416 ert_comp.active = false;
423 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
424 Paragraph *& first_par,
425 string const & token, int & pos,
426 Paragraph::depth_type & depth,
430 bool the_end_read = false;
431 #ifndef NO_COMPABILITY
432 #ifndef NO_PEXTRA_REALLY
433 // This is super temporary but is needed to get the compability
434 // mode for minipages work correctly together with new tabulars.
435 static int call_depth;
437 bool checkminipage = false;
438 static Paragraph * minipar;
439 static Paragraph * parBeforeMinipage;
442 if (token[0] != '\\') {
443 #ifndef NO_COMPABILITY
444 if (ert_comp.active) {
445 ert_comp.contents += token;
448 for (string::const_iterator cit = token.begin();
449 cit != token.end(); ++cit) {
450 par->insertChar(pos, (*cit), font);
453 #ifndef NO_COMPABILITY
456 } else if (token == "\\i") {
457 Inset * inset = new InsetLatexAccent;
458 inset->read(this, lex);
459 par->insertInset(pos, inset, font);
461 } else if (token == "\\layout") {
462 #ifndef NO_COMPABILITY
463 ert_comp.in_tabular = false;
465 insertErtContents(par, pos);
468 string const layoutname = lex.getString();
469 //lyxerr << "Looking for layout '"
470 // << layoutname << "'!" << endl;
472 pair<bool, layout_type> pp
473 = textclasslist.NumberOfLayout(params.textclass, layoutname);
475 //lyxerr << "Result: " << pp.first << "/" << pp.second << endl;
477 #ifndef NO_COMPABILITY
478 if (compare_no_case(layoutname, "latex") == 0) {
479 ert_comp.active = true;
480 ert_comp.font = font;
484 // The is the compability reading of layout caption.
485 // It can be removed in LyX version 1.3.0. (Lgb)
486 if (compare_no_case(layoutname, "caption") == 0) {
487 // We expect that the par we are now working on is
488 // really inside a InsetText inside a InsetFloat.
489 // We also know that captions can only be
490 // one paragraph. (Lgb)
492 // We should now read until the next "\layout"
494 // This is probably not good enough, what if the
495 // caption is the last par in the document (Lgb)
496 istream & ist = lex.getStream();
502 if (prefixIs(line, "\\layout")) {
506 if (prefixIs(line, "\\begin_inset"))
508 if (prefixIs(line, "\\end_inset")) {
519 // Now we should have the whole layout in ss
520 // we should now be able to give this to the
522 ss << "\\end_inset\n";
524 // This seems like a bug in stringstream.
525 // We really should be able to use ss
527 istringstream is(ss.str());
529 tmplex.setStream(is);
530 Inset * inset = new InsetCaption;
531 inset->Read(this, tmplex);
532 par->InsertInset(pos, inset, font);
539 par = new Paragraph(par);
543 par->layout = pp.second;
544 #ifndef NO_COMPABILITY
545 } else if (ert_comp.active) {
550 // use default layout "Standard" (0)
551 //lyxerr << "Layout '" << layoutname
552 // << "' was not found!" << endl;
556 string const s = _("Layout had to be changed from\n")
557 + layoutname + _(" to ")
558 + textclasslist.NameOfLayout(params.textclass, par->layout);
559 InsetError * new_inset = new InsetError(s);
560 par->insertInset(0, new_inset,
561 LyXFont(LyXFont::ALL_INHERIT,
564 // Test whether the layout is obsolete.
565 LyXLayout const & layout =
566 textclasslist.Style(params.textclass,
568 if (!layout.obsoleted_by().empty())
569 par->layout = textclasslist
570 .NumberOfLayout(params.textclass,
571 layout.obsoleted_by())
573 par->params().depth(depth);
574 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
575 if (file_format < 216
576 && params.language->lang() == "hebrew")
577 font.setLanguage(default_language);
582 #ifndef NO_COMPABILITY
583 } else if (token == "\\begin_float") {
584 insertErtContents(par, pos);
585 //insertErtContents(par, pos, false);
586 //ert_stack.push(ert_comp);
587 //ert_comp = ErtComp();
589 // This is the compability reader. It can be removed in
590 // LyX version 1.3.0. (Lgb)
592 string const tmptok = lex.getString();
593 //lyxerr << "old float: " << tmptok << endl;
596 stringstream old_float;
598 if (tmptok == "footnote") {
599 inset = new InsetFoot;
600 old_float << "collapsed true\n";
601 } else if (tmptok == "margin") {
602 inset = new InsetMarginal;
603 old_float << "collapsed true\n";
604 } else if (tmptok == "fig") {
605 inset = new InsetFloat("figure");
606 old_float << "placement htbp\n"
608 << "collapsed false\n";
609 } else if (tmptok == "tab") {
610 inset = new InsetFloat("table");
611 old_float << "placement htbp\n"
613 << "collapsed false\n";
614 } else if (tmptok == "alg") {
615 inset = new InsetFloat("algorithm");
616 old_float << "placement htbp\n"
618 << "collapsed false\n";
619 } else if (tmptok == "wide-fig") {
620 inset = new InsetFloat("figure");
621 //InsetFloat * tmp = new InsetFloat("figure");
624 old_float << "placement htbp\n"
626 << "collapsed false\n";
627 } else if (tmptok == "wide-tab") {
628 inset = new InsetFloat("table");
629 //InsetFloat * tmp = new InsetFloat("table");
632 old_float << "placement htbp\n"
634 << "collapsed false\n";
638 #ifndef NO_PEXTRA_REALLY
641 return false; // no end read yet
644 // Here we need to check for \end_deeper and handle that
645 // before we do the footnote parsing.
646 // This _is_ a hack! (Lgb)
649 string const tmp = lex.getString();
650 if (tmp == "\\end_deeper") {
651 //lyxerr << "\\end_deeper caught!" << endl;
653 lex.printError("\\end_deeper: "
654 "depth is already null");
659 old_float << tmp << ' ';
664 old_float << lex.getLongString("\\end_float")
665 << "\n\\end_inset\n";
666 //lyxerr << "Float Body:\n" << old_float.str() << endl;
667 // That this does not work seems like a bug
668 // in stringstream. (Lgb)
669 istringstream istr(old_float.str());
671 nylex.setStream(istr);
672 inset->read(this, nylex);
673 par->insertInset(pos, inset, font);
675 insertErtContents(par, pos);
677 } else if (token == "\\begin_deeper") {
679 } else if (token == "\\end_deeper") {
681 lex.printError("\\end_deeper: "
682 "depth is already null");
686 } else if (token == "\\begin_preamble") {
687 params.readPreamble(lex);
688 } else if (token == "\\textclass") {
690 pair<bool, textclass_type> pp =
691 textclasslist.NumberOfClass(lex.getString());
693 params.textclass = pp.second;
695 Alert::alert(string(_("Textclass error")),
696 string(_("The document uses an unknown textclass \"")) +
697 lex.getString() + string("\"."),
698 string(_("LyX will not be able to produce output correctly.")));
699 params.textclass = 0;
701 if (!textclasslist.Load(params.textclass)) {
702 // if the textclass wasn't loaded properly
703 // we need to either substitute another
704 // or stop loading the file.
705 // I can substitute but I don't see how I can
706 // stop loading... ideas?? ARRae980418
707 Alert::alert(_("Textclass Loading Error!"),
708 string(_("Can't load textclass ")) +
709 textclasslist.NameOfClass(params.textclass),
710 _("-- substituting default"));
711 params.textclass = 0;
713 } else if (token == "\\options") {
715 params.options = lex.getString();
716 } else if (token == "\\language") {
717 params.readLanguage(lex);
718 } else if (token == "\\fontencoding") {
720 } else if (token == "\\inputencoding") {
722 params.inputenc = lex.getString();
723 } else if (token == "\\graphics") {
724 params.readGraphicsDriver(lex);
725 } else if (token == "\\fontscheme") {
727 params.fonts = lex.getString();
728 } else if (token == "\\noindent") {
729 par->params().noindent(true);
730 } else if (token == "\\fill_top") {
731 par->params().spaceTop(VSpace(VSpace::VFILL));
732 } else if (token == "\\fill_bottom") {
733 par->params().spaceBottom(VSpace(VSpace::VFILL));
734 } else if (token == "\\line_top") {
735 par->params().lineTop(true);
736 } else if (token == "\\line_bottom") {
737 par->params().lineBottom(true);
738 } else if (token == "\\pagebreak_top") {
739 par->params().pagebreakTop(true);
740 } else if (token == "\\pagebreak_bottom") {
741 par->params().pagebreakBottom(true);
742 } else if (token == "\\start_of_appendix") {
743 par->params().startOfAppendix(true);
744 } else if (token == "\\paragraph_separation") {
745 int tmpret = lex.findToken(string_paragraph_separation);
748 if (tmpret != LYX_LAYOUT_DEFAULT)
749 params.paragraph_separation =
750 static_cast<BufferParams::PARSEP>(tmpret);
751 } else if (token == "\\defskip") {
753 params.defskip = VSpace(lex.getString());
754 #ifndef NO_COMPABILITY
755 } else if (token == "\\epsfig") { // obsolete
756 // Indeed it is obsolete, but we HAVE to be backwards
757 // compatible until 0.14, because otherwise all figures
758 // in existing documents are irretrivably lost. (Asger)
759 params.readGraphicsDriver(lex);
761 } else if (token == "\\quotes_language") {
762 int tmpret = lex.findToken(string_quotes_language);
765 if (tmpret != LYX_LAYOUT_DEFAULT) {
766 InsetQuotes::quote_language tmpl =
767 InsetQuotes::EnglishQ;
770 tmpl = InsetQuotes::EnglishQ;
773 tmpl = InsetQuotes::SwedishQ;
776 tmpl = InsetQuotes::GermanQ;
779 tmpl = InsetQuotes::PolishQ;
782 tmpl = InsetQuotes::FrenchQ;
785 tmpl = InsetQuotes::DanishQ;
788 params.quotes_language = tmpl;
790 } else if (token == "\\quotes_times") {
792 switch (lex.getInteger()) {
794 params.quotes_times = InsetQuotes::SingleQ;
797 params.quotes_times = InsetQuotes::DoubleQ;
800 } else if (token == "\\papersize") {
801 int tmpret = lex.findToken(string_papersize);
805 params.papersize2 = tmpret;
806 } else if (token == "\\paperpackage") {
807 int tmpret = lex.findToken(string_paperpackages);
810 params.paperpackage = BufferParams::PACKAGE_NONE;
812 params.paperpackage = tmpret;
813 } else if (token == "\\use_geometry") {
815 params.use_geometry = lex.getInteger();
816 } else if (token == "\\use_amsmath") {
818 params.use_amsmath = lex.getInteger();
819 } else if (token == "\\use_natbib") {
821 params.use_natbib = lex.getInteger();
822 } else if (token == "\\use_numerical_citations") {
824 params.use_numerical_citations = lex.getInteger();
825 } else if (token == "\\paperorientation") {
826 int tmpret = lex.findToken(string_orientation);
829 if (tmpret != LYX_LAYOUT_DEFAULT)
830 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
831 } else if (token == "\\paperwidth") {
833 params.paperwidth = lex.getString();
834 } else if (token == "\\paperheight") {
836 params.paperheight = lex.getString();
837 } else if (token == "\\leftmargin") {
839 params.leftmargin = lex.getString();
840 } else if (token == "\\topmargin") {
842 params.topmargin = lex.getString();
843 } else if (token == "\\rightmargin") {
845 params.rightmargin = lex.getString();
846 } else if (token == "\\bottommargin") {
848 params.bottommargin = lex.getString();
849 } else if (token == "\\headheight") {
851 params.headheight = lex.getString();
852 } else if (token == "\\headsep") {
854 params.headsep = lex.getString();
855 } else if (token == "\\footskip") {
857 params.footskip = lex.getString();
858 } else if (token == "\\paperfontsize") {
860 params.fontsize = strip(lex.getString());
861 } else if (token == "\\papercolumns") {
863 params.columns = lex.getInteger();
864 } else if (token == "\\papersides") {
866 switch (lex.getInteger()) {
868 case 1: params.sides = LyXTextClass::OneSide; break;
869 case 2: params.sides = LyXTextClass::TwoSides; break;
871 } else if (token == "\\paperpagestyle") {
873 params.pagestyle = strip(lex.getString());
874 } else if (token == "\\bullet") {
876 int const index = lex.getInteger();
878 int temp_int = lex.getInteger();
879 params.user_defined_bullets[index].setFont(temp_int);
880 params.temp_bullets[index].setFont(temp_int);
882 temp_int = lex.getInteger();
883 params.user_defined_bullets[index].setCharacter(temp_int);
884 params.temp_bullets[index].setCharacter(temp_int);
886 temp_int = lex.getInteger();
887 params.user_defined_bullets[index].setSize(temp_int);
888 params.temp_bullets[index].setSize(temp_int);
890 string const temp_str = lex.getString();
891 if (temp_str != "\\end_bullet") {
892 // this element isn't really necessary for
893 // parsing but is easier for humans
894 // to understand bullets. Put it back and
895 // set a debug message?
896 lex.printError("\\end_bullet expected, got" + temp_str);
897 //how can I put it back?
899 } else if (token == "\\bulletLaTeX") {
900 // The bullet class should be able to read this.
902 int const index = lex.getInteger();
904 string temp_str = lex.getString();
906 while (temp_str != "\\end_bullet") {
907 // this loop structure is needed when user
908 // enters an empty string since the first
909 // thing returned will be the \\end_bullet
911 // if the LaTeX entry has spaces. Each element
912 // therefore needs to be read in turn
915 temp_str = lex.getString();
918 params.user_defined_bullets[index].setText(sum_str);
919 params.temp_bullets[index].setText(sum_str);
920 } else if (token == "\\secnumdepth") {
922 params.secnumdepth = lex.getInteger();
923 } else if (token == "\\tocdepth") {
925 params.tocdepth = lex.getInteger();
926 } else if (token == "\\spacing") {
928 string const tmp = strip(lex.getString());
929 Spacing::Space tmp_space = Spacing::Default;
931 if (tmp == "single") {
932 tmp_space = Spacing::Single;
933 } else if (tmp == "onehalf") {
934 tmp_space = Spacing::Onehalf;
935 } else if (tmp == "double") {
936 tmp_space = Spacing::Double;
937 } else if (tmp == "other") {
939 tmp_space = Spacing::Other;
940 tmp_val = lex.getFloat();
942 lex.printError("Unknown spacing token: '$$Token'");
944 // Small hack so that files written with klyx will be
947 par->params().spacing(Spacing(tmp_space, tmp_val));
949 params.spacing.set(tmp_space, tmp_val);
951 } else if (token == "\\paragraph_spacing") {
953 string const tmp = strip(lex.getString());
954 if (tmp == "single") {
955 par->params().spacing(Spacing(Spacing::Single));
956 } else if (tmp == "onehalf") {
957 par->params().spacing(Spacing(Spacing::Onehalf));
958 } else if (tmp == "double") {
959 par->params().spacing(Spacing(Spacing::Double));
960 } else if (tmp == "other") {
962 par->params().spacing(Spacing(Spacing::Other,
965 lex.printError("Unknown spacing token: '$$Token'");
967 } else if (token == "\\float_placement") {
969 params.float_placement = lex.getString();
970 } else if (token == "\\family") {
972 font.setLyXFamily(lex.getString());
973 } else if (token == "\\series") {
975 font.setLyXSeries(lex.getString());
976 } else if (token == "\\shape") {
978 font.setLyXShape(lex.getString());
979 } else if (token == "\\size") {
981 font.setLyXSize(lex.getString());
982 #ifndef NO_COMPABILITY
983 } else if (token == "\\latex") {
985 string const tok = lex.getString();
986 if (tok == "no_latex") {
988 insertErtContents(par, pos);
989 } else if (tok == "latex") {
990 ert_comp.active = true;
991 ert_comp.font = font;
992 } else if (tok == "default") {
994 insertErtContents(par, pos);
996 lex.printError("Unknown LaTeX font flag "
1000 } else if (token == "\\lang") {
1002 string const tok = lex.getString();
1003 Language const * lang = languages.getLanguage(tok);
1005 font.setLanguage(lang);
1007 font.setLanguage(params.language);
1008 lex.printError("Unknown language `$$Token'");
1010 } else if (token == "\\numeric") {
1012 font.setNumber(font.setLyXMisc(lex.getString()));
1013 } else if (token == "\\emph") {
1015 font.setEmph(font.setLyXMisc(lex.getString()));
1016 } else if (token == "\\bar") {
1018 string const tok = lex.getString();
1019 // This is dirty, but gone with LyX3. (Asger)
1021 font.setUnderbar(LyXFont::ON);
1022 else if (tok == "no")
1023 font.setUnderbar(LyXFont::OFF);
1024 else if (tok == "default")
1025 font.setUnderbar(LyXFont::INHERIT);
1027 lex.printError("Unknown bar font flag "
1029 } else if (token == "\\noun") {
1031 font.setNoun(font.setLyXMisc(lex.getString()));
1032 } else if (token == "\\color") {
1034 font.setLyXColor(lex.getString());
1035 } else if (token == "\\align") {
1036 int tmpret = lex.findToken(string_align);
1037 if (tmpret == -1) ++tmpret;
1038 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1039 int const tmpret2 = int(pow(2.0, tmpret));
1040 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1041 par->params().align(LyXAlignment(tmpret2));
1043 } else if (token == "\\added_space_top") {
1045 VSpace value = VSpace(lex.getString());
1046 if ((value.length().len().value() != 0) ||
1047 (value.kind() != VSpace::LENGTH))
1048 par->params().spaceTop(value);
1049 } else if (token == "\\added_space_bottom") {
1051 VSpace value = VSpace(lex.getString());
1052 if ((value.length().len().value() != 0) ||
1053 (value.kind() != VSpace::LENGTH))
1054 par->params().spaceBottom(value);
1055 #ifndef NO_COMPABILITY
1056 #ifndef NO_PEXTRA_REALLY
1057 } else if (token == "\\pextra_type") {
1059 par->params().pextraType(lex.getInteger());
1060 } else if (token == "\\pextra_width") {
1062 par->params().pextraWidth(lex.getString());
1063 } else if (token == "\\pextra_widthp") {
1065 par->params().pextraWidthp(lex.getString());
1066 } else if (token == "\\pextra_alignment") {
1068 par->params().pextraAlignment(lex.getInteger());
1069 } else if (token == "\\pextra_hfill") {
1071 par->params().pextraHfill(lex.getInteger());
1072 } else if (token == "\\pextra_start_minipage") {
1074 par->params().pextraStartMinipage(lex.getInteger());
1077 } else if (token == "\\labelwidthstring") {
1079 par->params().labelWidthString(lex.getString());
1080 // do not delete this token, it is still needed!
1081 } else if (token == "\\end_inset") {
1082 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1083 << "Last inset read was: " << last_inset_read
1085 // Simply ignore this. The insets do not have
1087 // But insets should read it, it is a part of
1088 // the inset isn't it? Lgb.
1089 } else if (token == "\\begin_inset") {
1090 #ifndef NO_COMPABILITY
1091 insertErtContents(par, pos, false);
1092 ert_stack.push(ert_comp);
1093 ert_comp = ErtComp();
1095 readInset(lex, par, pos, font);
1096 #ifndef NO_COMPABILITY
1097 ert_comp = ert_stack.top();
1099 insertErtContents(par, pos);
1101 } else if (token == "\\SpecialChar") {
1102 LyXLayout const & layout =
1103 textclasslist.Style(params.textclass,
1106 // Insets don't make sense in a free-spacing context! ---Kayvan
1107 if (layout.free_spacing || par->isFreeSpacing()) {
1110 string next_token = lex.getString();
1111 if (next_token == "\\-") {
1112 par->insertChar(pos, '-', font);
1113 } else if (next_token == "\\protected_separator"
1114 || next_token == "~") {
1115 par->insertChar(pos, ' ', font);
1117 lex.printError("Token `$$Token' "
1119 "paragraph layout!");
1124 Inset * inset = new InsetSpecialChar;
1125 inset->read(this, lex);
1126 par->insertInset(pos, inset, font);
1129 } else if (token == "\\newline") {
1130 #ifndef NO_COMPABILITY
1131 if (!ert_comp.in_tabular && ert_comp.active) {
1132 ert_comp.contents += char(Paragraph::META_NEWLINE);
1134 // Since we cannot know it this is only a regular
1135 // newline or a tabular cell delimter we have to
1136 // handle the ERT here.
1137 insertErtContents(par, pos, false);
1139 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1143 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1146 } else if (token == "\\LyXTable") {
1147 #ifndef NO_COMPABILITY
1148 ert_comp.in_tabular = true;
1150 Inset * inset = new InsetTabular(*this);
1151 inset->read(this, lex);
1152 par->insertInset(pos, inset, font);
1154 } else if (token == "\\hfill") {
1155 par->insertChar(pos, Paragraph::META_HFILL, font);
1157 } else if (token == "\\protected_separator") { // obsolete
1158 // This is a backward compability thingie. (Lgb)
1159 // Remove it later some time...introduced with fileformat
1161 LyXLayout const & layout =
1162 textclasslist.Style(params.textclass,
1165 if (layout.free_spacing || par->isFreeSpacing()) {
1166 par->insertChar(pos, ' ', font);
1168 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1169 par->insertInset(pos, inset, font);
1172 } else if (token == "\\bibitem") { // ale970302
1174 InsetCommandParams p("bibitem", "dummy");
1175 par->bibkey = new InsetBibKey(p);
1177 par->bibkey->read(this, lex);
1178 } else if (token == "\\backslash") {
1179 #ifndef NO_COMPABILITY
1180 if (ert_comp.active) {
1181 ert_comp.contents += "\\";
1184 par->insertChar(pos, '\\', font);
1186 #ifndef NO_COMPABILITY
1189 } else if (token == "\\the_end") {
1190 #ifndef NO_COMPABILITY
1191 // If we still have some ert active here we have to insert
1192 // it so we don't loose it. (Lgb)
1193 insertErtContents(par, pos);
1195 the_end_read = true;
1196 #ifndef NO_COMPABILITY
1197 #ifndef NO_PEXTRA_REALLY
1198 minipar = parBeforeMinipage = 0;
1202 #ifndef NO_COMPABILITY
1203 if (ert_comp.active) {
1204 ert_comp.contents += token;
1207 // This should be insurance for the future: (Asger)
1210 string const s = _("Unknown token: ") + token
1211 + " " + lex.text() + "\n";
1213 InsetError * new_inset = new InsetError(s);
1214 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
1217 #ifndef NO_COMPABILITY
1222 #ifndef NO_COMPABILITY
1223 #ifndef NO_PEXTRA_REALLY
1224 // I wonder if we could use this blanket fix for all the
1225 // checkminipage cases...
1226 // don't forget about ert paragraphs and compatibility read for'em
1227 if (par && (par->size() || !ert_comp.contents.empty())) {
1228 // It is possible that this will check to often,
1229 // but that should not be an correctness issue.
1230 // Only a speed issue.
1231 checkminipage = true;
1234 // now check if we have a minipage paragraph as at this
1235 // point we already read all the necessary data!
1236 // this cannot be done in layout because there we did
1237 // not read yet the paragraph PEXTRA-params (Jug)
1239 // BEGIN pextra_minipage compability
1240 // This should be removed in 1.3.x (Lgb)
1241 // I don't think we should remove this so fast (Jug)
1243 // This compability code is not perfect. In a couple
1244 // of rand cases it fails. When the minipage par is
1245 // the first par in the document, and when there are
1246 // none or only one regular paragraphs after the
1247 // minipage. Currently I am not investing any effort
1248 // in fixing those cases.
1250 //lyxerr << "Call depth: " << call_depth << endl;
1251 if (checkminipage && (call_depth == 1)) {
1252 checkminipage = false;
1253 if (minipar && (minipar != par) &&
1254 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1256 lyxerr << "minipages in a row" << endl;
1257 if (par->params().pextraStartMinipage()) {
1258 lyxerr << "start new minipage" << endl;
1259 // minipages in a row
1260 par->previous()->next(0);
1263 Paragraph * tmp = minipar;
1265 tmp->params().pextraType(0);
1266 tmp->params().pextraWidth(string());
1267 tmp->params().pextraWidthp(string());
1268 tmp->params().pextraAlignment(0);
1269 tmp->params().pextraHfill(false);
1270 tmp->params().pextraStartMinipage(false);
1273 // create a new paragraph to insert the
1274 // minipages in the following case
1275 if (par->params().pextraStartMinipage() &&
1276 !par->params().pextraHfill())
1278 Paragraph * p = new Paragraph;
1280 p->previous(parBeforeMinipage);
1281 parBeforeMinipage->next(p);
1283 p->params().depth(parBeforeMinipage->params().depth());
1284 parBeforeMinipage = p;
1286 InsetMinipage * mini = new InsetMinipage;
1287 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1288 mini->pageWidth(LyXLength(par->params().pextraWidth()));
1289 if (!par->params().pextraWidthp().empty()) {
1290 lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1291 mini->pageWidth(LyXLength((par->params().pextraWidthp())+"%"));
1293 Paragraph * op = mini->firstParagraph();
1294 mini->inset.paragraph(par);
1296 // and free the old ones!
1299 Paragraph * pp = op->next();
1303 // Insert the minipage last in the
1304 // previous paragraph.
1305 if (par->params().pextraHfill()) {
1306 parBeforeMinipage->insertChar
1307 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1309 parBeforeMinipage->insertInset
1310 (parBeforeMinipage->size(), mini);
1314 lyxerr << "new minipage par" << endl;
1315 //nothing to do just continue reading
1318 } else if (minipar && (minipar != par)) {
1319 lyxerr << "last minipage par read" << endl;
1320 // The last paragraph read was not part of a
1321 // minipage but the par linked list is...
1322 // So we need to remove the last par from the
1324 if (par->previous())
1325 par->previous()->next(0);
1326 par->previous(parBeforeMinipage);
1327 parBeforeMinipage->next(par);
1328 Paragraph * tmp = minipar;
1330 tmp->params().pextraType(0);
1331 tmp->params().pextraWidth(string());
1332 tmp->params().pextraWidthp(string());
1333 tmp->params().pextraAlignment(0);
1334 tmp->params().pextraHfill(false);
1335 tmp->params().pextraStartMinipage(false);
1338 depth = parBeforeMinipage->params().depth();
1339 // and set this depth on the par as it has not been set already
1340 par->params().depth(depth);
1341 minipar = parBeforeMinipage = 0;
1342 } else if (!minipar &&
1343 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1345 // par is the first paragraph in a minipage
1346 lyxerr << "begin minipage" << endl;
1347 // To minimize problems for
1348 // the users we will insert
1349 // the first minipage in
1350 // a sequence of minipages
1351 // in its own paragraph.
1352 Paragraph * p = new Paragraph;
1354 p->previous(par->previous());
1356 p->params().depth(depth);
1357 par->params().depth(0);
1359 if (par->previous())
1360 par->previous()->next(p);
1362 parBeforeMinipage = p;
1364 if (!first_par || (first_par == par))
1367 InsetMinipage * mini = new InsetMinipage;
1368 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1369 mini->pageWidth(LyXLength(minipar->params().pextraWidth()));
1370 if (!par->params().pextraWidthp().empty()) {
1371 lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1372 mini->pageWidth(LyXLength((par->params().pextraWidthp())+"%"));
1374 mini->inset.paragraph(minipar);
1376 // Insert the minipage last in the
1377 // previous paragraph.
1378 if (minipar->params().pextraHfill()) {
1379 parBeforeMinipage->insertChar
1380 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1382 parBeforeMinipage->insertInset
1383 (parBeforeMinipage->size(), mini);
1386 // End of pextra_minipage compability
1390 return the_end_read;
1393 // needed to insert the selection
1394 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
1395 LyXFont const & fn,string const & str) const
1397 LyXLayout const & layout = textclasslist.Style(params.textclass,
1401 (void)par->checkInsertChar(font);
1402 // insert the string, don't insert doublespace
1403 bool space_inserted = true;
1404 for(string::const_iterator cit = str.begin();
1405 cit != str.end(); ++cit) {
1407 if (par->size() || layout.keepempty) {
1408 par->breakParagraph(params, pos,
1409 layout.isEnvironment());
1412 space_inserted = true;
1416 // do not insert consecutive spaces if !free_spacing
1417 } else if ((*cit == ' ' || *cit == '\t') &&
1418 space_inserted && !layout.free_spacing &&
1419 !par->isFreeSpacing())
1422 } else if (*cit == '\t') {
1423 if (!layout.free_spacing && !par->isFreeSpacing()) {
1424 // tabs are like spaces here
1425 par->insertChar(pos, ' ', font);
1427 space_inserted = true;
1429 const pos_type nb = 8 - pos % 8;
1430 for (pos_type a = 0; a < nb ; ++a) {
1431 par->insertChar(pos, ' ', font);
1434 space_inserted = true;
1436 } else if (!IsPrintable(*cit)) {
1437 // Ignore unprintables
1440 // just insert the character
1441 par->insertChar(pos, *cit, font);
1443 space_inserted = (*cit == ' ');
1450 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1451 int & pos, LyXFont & font)
1453 // consistency check
1454 if (lex.getString() != "\\begin_inset") {
1455 lyxerr << "Buffer::readInset: Consistency check failed."
1462 string const tmptok = lex.getString();
1463 last_inset_read = tmptok;
1465 // test the different insets
1466 if (tmptok == "LatexCommand") {
1467 InsetCommandParams inscmd;
1470 string const cmdName = inscmd.getCmdName();
1472 // This strange command allows LyX to recognize "natbib" style
1473 // citations: citet, citep, Citet etc.
1474 if (compare_no_case(cmdName, "cite", 4) == 0) {
1475 inset = new InsetCitation(inscmd);
1476 } else if (cmdName == "bibitem") {
1477 lex.printError("Wrong place for bibitem");
1478 inset = new InsetBibKey(inscmd);
1479 } else if (cmdName == "BibTeX") {
1480 inset = new InsetBibtex(inscmd);
1481 } else if (cmdName == "index") {
1482 inset = new InsetIndex(inscmd);
1483 } else if (cmdName == "include") {
1484 inset = new InsetInclude(inscmd, *this);
1485 } else if (cmdName == "label") {
1486 inset = new InsetLabel(inscmd);
1487 } else if (cmdName == "url"
1488 || cmdName == "htmlurl") {
1489 inset = new InsetUrl(inscmd);
1490 } else if (cmdName == "ref"
1491 || cmdName == "pageref"
1492 || cmdName == "vref"
1493 || cmdName == "vpageref"
1494 || cmdName == "prettyref") {
1495 if (!inscmd.getOptions().empty()
1496 || !inscmd.getContents().empty()) {
1497 inset = new InsetRef(inscmd, *this);
1499 } else if (cmdName == "tableofcontents") {
1500 inset = new InsetTOC(inscmd);
1501 } else if (cmdName == "listofalgorithms") {
1502 inset = new InsetFloatList("algorithm");
1503 } else if (cmdName == "listoffigures") {
1504 inset = new InsetFloatList("figure");
1505 } else if (cmdName == "listoftables") {
1506 inset = new InsetFloatList("table");
1507 } else if (cmdName == "printindex") {
1508 inset = new InsetPrintIndex(inscmd);
1509 } else if (cmdName == "lyxparent") {
1510 inset = new InsetParent(inscmd, *this);
1513 bool alreadyread = false;
1514 if (tmptok == "Quotes") {
1515 inset = new InsetQuotes;
1516 } else if (tmptok == "External") {
1517 inset = new InsetExternal;
1518 } else if (tmptok == "FormulaMacro") {
1519 inset = new InsetFormulaMacro;
1520 } else if (tmptok == "Formula") {
1521 inset = new InsetFormula;
1522 } else if (tmptok == "Figure") { // Backward compatibility
1523 // inset = new InsetFig(100, 100, *this);
1524 inset = new InsetGraphics;
1525 } else if (tmptok == "Graphics") {
1526 inset = new InsetGraphics;
1527 } else if (tmptok == "Info") {// backwards compatibility
1528 inset = new InsetNote(this,
1529 lex.getLongString("\\end_inset"),
1532 } else if (tmptok == "Note") {
1533 inset = new InsetNote;
1534 } else if (tmptok == "Include") {
1535 InsetCommandParams p("Include");
1536 inset = new InsetInclude(p, *this);
1537 } else if (tmptok == "ERT") {
1538 inset = new InsetERT;
1539 } else if (tmptok == "Tabular") {
1540 inset = new InsetTabular(*this);
1541 } else if (tmptok == "Text") {
1542 inset = new InsetText;
1543 } else if (tmptok == "Foot") {
1544 inset = new InsetFoot;
1545 } else if (tmptok == "Marginal") {
1546 inset = new InsetMarginal;
1547 } else if (tmptok == "Minipage") {
1548 inset = new InsetMinipage;
1549 } else if (tmptok == "Float") {
1551 string tmptok = lex.getString();
1552 inset = new InsetFloat(tmptok);
1554 } else if (tmptok == "List") {
1555 inset = new InsetList;
1556 } else if (tmptok == "Theorem") {
1557 inset = new InsetList;
1559 } else if (tmptok == "Caption") {
1560 inset = new InsetCaption;
1561 } else if (tmptok == "FloatList") {
1562 inset = new InsetFloatList;
1565 if (inset && !alreadyread) inset->read(this, lex);
1569 par->insertInset(pos, inset, font);
1575 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1579 string const token(lex.getString());
1580 if (token == "\\lyxformat") { // the first token _must_ be...
1582 string tmp_format = lex.getString();
1583 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1584 // if present remove ".," from string.
1585 string::size_type dot = tmp_format.find_first_of(".,");
1586 //lyxerr << " dot found at " << dot << endl;
1587 if (dot != string::npos)
1588 tmp_format.erase(dot, 1);
1589 file_format = strToInt(tmp_format);
1590 if (file_format == LYX_FORMAT) {
1592 } else if (file_format > LYX_FORMAT) {
1594 Alert::alert(_("Warning!"),
1595 _("LyX file format is newer that what"),
1596 _("is supported in this LyX version. Expect some problems."));
1598 } else if (file_format < LYX_FORMAT) {
1600 if (file_format < 200) {
1601 Alert::alert(_("ERROR!"),
1602 _("Old LyX file format found. "
1603 "Use LyX 0.10.x to read this!"));
1607 bool the_end = readLyXformat2(lex, par);
1608 params.setPaperStuff();
1609 // the_end was added in 213
1610 if (file_format < 213)
1614 Alert::alert(_("Warning!"),
1615 _("Reading of document is not complete"),
1616 _("Maybe the document is truncated"));
1619 } else { // "\\lyxformat" not found
1620 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1623 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1628 // Should probably be moved to somewhere else: BufferView? LyXView?
1629 bool Buffer::save() const
1631 // We don't need autosaves in the immediate future. (Asger)
1632 resetAutosaveTimers();
1636 if (lyxrc.make_backup) {
1637 s = fileName() + '~';
1638 if (!lyxrc.backupdir_path.empty())
1639 s = AddName(lyxrc.backupdir_path,
1640 subst(os::slashify_path(s),'/','!'));
1642 // Rename is the wrong way of making a backup,
1643 // this is the correct way.
1644 /* truss cp fil fil2:
1645 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1646 stat("LyXVC.lyx", 0xEFFFF688) = 0
1647 open("LyXVC.lyx", O_RDONLY) = 3
1648 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1649 fstat(4, 0xEFFFF508) = 0
1650 fstat(3, 0xEFFFF508) = 0
1651 read(3, " # T h i s f i l e w".., 8192) = 5579
1652 write(4, " # T h i s f i l e w".., 5579) = 5579
1653 read(3, 0xEFFFD4A0, 8192) = 0
1656 chmod("LyXVC3.lyx", 0100644) = 0
1657 lseek(0, 0, SEEK_CUR) = 46440
1661 // Should probably have some more error checking here.
1662 // Should be cleaned up in 0.13, at least a bit.
1663 // Doing it this way, also makes the inodes stay the same.
1664 // This is still not a very good solution, in particular we
1665 // might loose the owner of the backup.
1666 FileInfo finfo(fileName());
1667 if (finfo.exist()) {
1668 mode_t fmode = finfo.getMode();
1669 struct utimbuf times = {
1670 finfo.getAccessTime(),
1671 finfo.getModificationTime() };
1673 ifstream ifs(fileName().c_str());
1674 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1679 ::chmod(s.c_str(), fmode);
1681 if (::utime(s.c_str(), ×)) {
1682 lyxerr << "utime error." << endl;
1685 lyxerr << "LyX was not able to make "
1686 "backup copy. Beware." << endl;
1691 if (writeFile(fileName(), false)) {
1693 removeAutosaveFile(fileName());
1695 // Saving failed, so backup is not backup
1696 if (lyxrc.make_backup) {
1697 lyx::rename(s, fileName());
1705 // Returns false if unsuccesful
1706 bool Buffer::writeFile(string const & fname, bool flag) const
1708 // if flag is false writeFile will not create any GUI
1709 // warnings, only cerr.
1710 // Needed for autosave in background or panic save (Matthias 120496)
1712 if (read_only && (fname == fileName())) {
1713 // Here we should come with a question if we should
1714 // perform the write anyway.
1716 lyxerr << _("Error! Document is read-only: ")
1719 Alert::alert(_("Error! Document is read-only: "),
1724 FileInfo finfo(fname);
1725 if (finfo.exist() && !finfo.writable()) {
1726 // Here we should come with a question if we should
1727 // try to do the save anyway. (i.e. do a chmod first)
1729 lyxerr << _("Error! Cannot write file: ")
1732 Alert::err_alert(_("Error! Cannot write file: "),
1737 ofstream ofs(fname.c_str());
1740 lyxerr << _("Error! Cannot open file: ")
1743 Alert::err_alert(_("Error! Cannot open file: "),
1749 // Use the standard "C" locale for file output.
1750 ofs.imbue(std::locale::classic());
1753 // The top of the file should not be written by params.
1755 // write out a comment in the top of the file
1756 ofs << '#' << lyx_docversion
1757 << " created this file. For more info see http://www.lyx.org/\n"
1758 << "\\lyxformat " << LYX_FORMAT << "\n";
1760 // now write out the buffer paramters.
1761 params.writeFile(ofs);
1763 Paragraph::depth_type depth = 0;
1765 // this will write out all the paragraphs
1766 // using recursive descent.
1767 paragraph->writeFile(this, ofs, params, depth);
1769 // Write marker that shows file is complete
1770 ofs << "\n\\the_end" << endl;
1774 // how to check if close went ok?
1775 // Following is an attempt... (BE 20001011)
1777 // good() returns false if any error occured, including some
1778 // formatting error.
1779 // bad() returns true if something bad happened in the buffer,
1780 // which should include file system full errors.
1787 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1789 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1799 string const Buffer::asciiParagraph(Paragraph const * par,
1800 unsigned int linelen,
1801 bool noparbreak) const
1803 ostringstream buffer;
1805 Paragraph::depth_type depth = 0;
1807 Paragraph::depth_type ltype_depth = 0;
1808 string::size_type currlinelen = 0;
1809 bool ref_printed = false;
1810 // if (!par->previous()) {
1812 // begins or ends a deeper area ?
1813 if (depth != par->params().depth()) {
1814 if (par->params().depth() > depth) {
1815 while (par->params().depth() > depth) {
1819 while (par->params().depth() < depth) {
1825 depth = par->params().depth();
1828 // First write the layout
1829 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1830 if (tmp == "Itemize") {
1832 ltype_depth = depth + 1;
1833 } else if (tmp == "Enumerate") {
1835 ltype_depth = depth + 1;
1836 } else if (contains(tmp, "ection")) {
1838 ltype_depth = depth + 1;
1839 } else if (contains(tmp, "aragraph")) {
1841 ltype_depth = depth + 1;
1842 } else if (tmp == "Description") {
1844 ltype_depth = depth + 1;
1845 } else if (tmp == "Abstract") {
1848 } else if (tmp == "Bibliography") {
1856 /* maybe some vertical spaces */
1858 /* the labelwidthstring used in lists */
1862 /* some pagebreaks? */
1866 /* what about the alignment */
1868 // lyxerr << "Should this ever happen?" << endl;
1871 // linelen <= 0 is special and means we don't have pargraph breaks
1875 for (Paragraph::depth_type j = 0; j < depth; ++j)
1877 currlinelen = depth * 2;
1879 // we should probably change to the paragraph language in the
1880 // gettext here (if possible) so that strings are outputted in
1881 // the correct language! (20012712 Jug)
1885 case 4: // (Sub)Paragraph
1886 case 5: // Description
1890 buffer << _("Abstract") << "\n\n";
1892 buffer << _("Abstract: ");
1894 case 7: // Bibliography
1897 buffer << _("References") << "\n\n";
1899 buffer << _("References: ");
1904 buffer << par->params().labelString() << " ";
1908 string s = buffer.str();
1909 if (s.rfind('\n') != string::npos) {
1911 s = rsplit(buffer.str().c_str(), dummy, '\n');
1913 currlinelen = s.length();
1915 for (Paragraph::depth_type j = 0; j < depth; ++j)
1917 currlinelen = depth * 2;
1918 if (ltype_depth > depth) {
1919 for (Paragraph::depth_type j = ltype_depth;
1924 currlinelen += (ltype_depth-depth)*2;
1927 // this is to change the linebreak to do it by word a bit more intelligent
1928 // hopefully! (only in the case where we have a max linelenght!) (Jug)
1929 for (pos_type i = 0; i < par->size(); ++i) {
1930 char c = par->getUChar(params, i);
1932 case Paragraph::META_INSET:
1934 Inset const * inset = par->getInset(i);
1937 buffer << word.str();
1940 if (inset->ascii(this, buffer, linelen)) {
1941 // to be sure it breaks paragraph
1942 currlinelen += linelen;
1948 rsplit(buffer.str().c_str(),
1950 currlinelen = s.length();
1957 case Paragraph::META_NEWLINE:
1959 buffer << word.str() << "\n";
1961 for (Paragraph::depth_type j = 0;
1964 currlinelen = depth * 2;
1965 if (ltype_depth > depth) {
1966 for (Paragraph::depth_type j = ltype_depth;
1969 currlinelen += (ltype_depth - depth) * 2;
1974 case Paragraph::META_HFILL:
1975 buffer << word.str() << "\t";
1976 currlinelen += word.str().length() + 1;
1982 buffer << word.str() << ' ';
1983 currlinelen += word.str().length() + 1;
1989 lyxerr[Debug::INFO] <<
1990 "writeAsciiFile: NULL char in structure." << endl;
1992 if ((linelen > 0) &&
1993 (currlinelen+word.str().length()) > linelen)
1996 for (Paragraph::depth_type j = 0; j < depth; ++j)
1998 currlinelen = depth * 2;
1999 if (ltype_depth > depth) {
2000 for (Paragraph::depth_type j = ltype_depth;
2005 currlinelen += (ltype_depth-depth)*2;
2012 buffer << word.str();
2013 return buffer.str().c_str();
2017 void Buffer::writeFileAscii(string const & fname, int linelen)
2019 ofstream ofs(fname.c_str());
2021 Alert::err_alert(_("Error: Cannot write file:"), fname);
2024 writeFileAscii(ofs, linelen);
2028 void Buffer::writeFileAscii(ostream & ofs, int linelen)
2030 Paragraph * par = paragraph;
2032 ofs << asciiParagraph(par, linelen, par->previous() == 0);
2042 void Buffer::makeLaTeXFile(string const & fname,
2043 string const & original_path,
2044 bool nice, bool only_body)
2046 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
2048 niceFile = nice; // this will be used by Insetincludes.
2050 tex_code_break_column = lyxrc.ascii_linelen;
2052 LyXTextClass const & tclass =
2053 textclasslist.TextClass(params.textclass);
2055 ofstream ofs(fname.c_str());
2057 Alert::err_alert(_("Error: Cannot open file: "), fname);
2061 // validate the buffer.
2062 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
2063 LaTeXFeatures features(params, tclass.numLayouts());
2065 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
2068 // The starting paragraph of the coming rows is the
2069 // first paragraph of the document. (Asger)
2070 texrow.start(paragraph, 0);
2072 if (!only_body && nice) {
2073 ofs << "%% " << lyx_docversion << " created this file. "
2074 "For more info, see http://www.lyx.org/.\n"
2075 "%% Do not edit unless you really know what "
2080 lyxerr[Debug::INFO] << "lyx header finished" << endl;
2081 // There are a few differences between nice LaTeX and usual files:
2082 // usual is \batchmode and has a
2083 // special input@path to allow the including of figures
2084 // with either \input or \includegraphics (what figinsets do).
2085 // batchmode is not set if there is a tex_code_break_column.
2086 // In this case somebody is interested in the generated LaTeX,
2087 // so this is OK. input@path is set when the actual parameter
2088 // original_path is set. This is done for usual tex-file, but not
2089 // for nice-latex-file. (Matthias 250696)
2092 // code for usual, NOT nice-latex-file
2093 ofs << "\\batchmode\n"; // changed
2094 // from \nonstopmode
2097 if (!original_path.empty()) {
2098 ofs << "\\makeatletter\n"
2099 << "\\def\\input@path{{"
2100 << os::external_path(original_path) << "/}}\n"
2101 << "\\makeatother\n";
2107 ofs << "\\documentclass";
2109 ostringstream options; // the document class options.
2111 if (tokenPos(tclass.opt_fontsize(),
2112 '|', params.fontsize) >= 0) {
2113 // only write if existing in list (and not default)
2114 options << params.fontsize << "pt,";
2118 if (!params.use_geometry &&
2119 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2120 switch (params.papersize) {
2121 case BufferParams::PAPER_A4PAPER:
2122 options << "a4paper,";
2124 case BufferParams::PAPER_USLETTER:
2125 options << "letterpaper,";
2127 case BufferParams::PAPER_A5PAPER:
2128 options << "a5paper,";
2130 case BufferParams::PAPER_B5PAPER:
2131 options << "b5paper,";
2133 case BufferParams::PAPER_EXECUTIVEPAPER:
2134 options << "executivepaper,";
2136 case BufferParams::PAPER_LEGALPAPER:
2137 options << "legalpaper,";
2143 if (params.sides != tclass.sides()) {
2144 switch (params.sides) {
2145 case LyXTextClass::OneSide:
2146 options << "oneside,";
2148 case LyXTextClass::TwoSides:
2149 options << "twoside,";
2155 if (params.columns != tclass.columns()) {
2156 if (params.columns == 2)
2157 options << "twocolumn,";
2159 options << "onecolumn,";
2162 if (!params.use_geometry
2163 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2164 options << "landscape,";
2166 // language should be a parameter to \documentclass
2168 ostringstream language_options;
2169 if (params.language->babel() == "hebrew"
2170 && default_language->babel() != "hebrew")
2171 // This seems necessary
2172 features.useLanguage(default_language);
2174 if (lyxrc.language_use_babel ||
2175 params.language->lang() != lyxrc.default_language ||
2176 !features.hasLanguages()) {
2178 language_options << features.getLanguages();
2179 language_options << params.language->babel();
2180 if (lyxrc.language_global_options)
2181 options << language_options.str() << ',';
2184 // the user-defined options
2185 if (!params.options.empty()) {
2186 options << params.options << ',';
2189 string strOptions(options.str().c_str());
2190 if (!strOptions.empty()) {
2191 strOptions = strip(strOptions, ',');
2192 ofs << '[' << strOptions << ']';
2196 << textclasslist.LatexnameOfClass(params.textclass)
2199 // end of \documentclass defs
2201 // font selection must be done before loading fontenc.sty
2202 // The ae package is not needed when using OT1 font encoding.
2203 if (params.fonts != "default" &&
2204 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2205 ofs << "\\usepackage{" << params.fonts << "}\n";
2207 if (params.fonts == "ae") {
2208 ofs << "\\usepackage{aecompl}\n";
2212 // this one is not per buffer
2213 if (lyxrc.fontenc != "default") {
2214 ofs << "\\usepackage[" << lyxrc.fontenc
2219 if (params.inputenc == "auto") {
2220 string const doc_encoding =
2221 params.language->encoding()->LatexName();
2223 // Create a list with all the input encodings used
2225 set<string> encodings = features.getEncodingSet(doc_encoding);
2227 ofs << "\\usepackage[";
2228 std::copy(encodings.begin(), encodings.end(),
2229 std::ostream_iterator<string>(ofs, ","));
2230 ofs << doc_encoding << "]{inputenc}\n";
2232 } else if (params.inputenc != "default") {
2233 ofs << "\\usepackage[" << params.inputenc
2238 // At the very beginning the text parameters.
2239 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2240 switch (params.paperpackage) {
2241 case BufferParams::PACKAGE_A4:
2242 ofs << "\\usepackage{a4}\n";
2245 case BufferParams::PACKAGE_A4WIDE:
2246 ofs << "\\usepackage{a4wide}\n";
2249 case BufferParams::PACKAGE_WIDEMARGINSA4:
2250 ofs << "\\usepackage[widemargins]{a4}\n";
2255 if (params.use_geometry) {
2256 ofs << "\\usepackage{geometry}\n";
2258 ofs << "\\geometry{verbose";
2259 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2260 ofs << ",landscape";
2261 switch (params.papersize2) {
2262 case BufferParams::VM_PAPER_CUSTOM:
2263 if (!params.paperwidth.empty())
2264 ofs << ",paperwidth="
2265 << params.paperwidth;
2266 if (!params.paperheight.empty())
2267 ofs << ",paperheight="
2268 << params.paperheight;
2270 case BufferParams::VM_PAPER_USLETTER:
2271 ofs << ",letterpaper";
2273 case BufferParams::VM_PAPER_USLEGAL:
2274 ofs << ",legalpaper";
2276 case BufferParams::VM_PAPER_USEXECUTIVE:
2277 ofs << ",executivepaper";
2279 case BufferParams::VM_PAPER_A3:
2282 case BufferParams::VM_PAPER_A4:
2285 case BufferParams::VM_PAPER_A5:
2288 case BufferParams::VM_PAPER_B3:
2291 case BufferParams::VM_PAPER_B4:
2294 case BufferParams::VM_PAPER_B5:
2298 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2299 switch (lyxrc.default_papersize) {
2300 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2301 case BufferParams::PAPER_USLETTER:
2302 ofs << ",letterpaper";
2304 case BufferParams::PAPER_LEGALPAPER:
2305 ofs << ",legalpaper";
2307 case BufferParams::PAPER_EXECUTIVEPAPER:
2308 ofs << ",executivepaper";
2310 case BufferParams::PAPER_A3PAPER:
2313 case BufferParams::PAPER_A4PAPER:
2316 case BufferParams::PAPER_A5PAPER:
2319 case BufferParams::PAPER_B5PAPER:
2324 if (!params.topmargin.empty())
2325 ofs << ",tmargin=" << params.topmargin;
2326 if (!params.bottommargin.empty())
2327 ofs << ",bmargin=" << params.bottommargin;
2328 if (!params.leftmargin.empty())
2329 ofs << ",lmargin=" << params.leftmargin;
2330 if (!params.rightmargin.empty())
2331 ofs << ",rmargin=" << params.rightmargin;
2332 if (!params.headheight.empty())
2333 ofs << ",headheight=" << params.headheight;
2334 if (!params.headsep.empty())
2335 ofs << ",headsep=" << params.headsep;
2336 if (!params.footskip.empty())
2337 ofs << ",footskip=" << params.footskip;
2342 if (tokenPos(tclass.opt_pagestyle(),
2343 '|', params.pagestyle) >= 0) {
2344 if (params.pagestyle == "fancy") {
2345 ofs << "\\usepackage{fancyhdr}\n";
2348 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2352 if (params.secnumdepth != tclass.secnumdepth()) {
2353 ofs << "\\setcounter{secnumdepth}{"
2354 << params.secnumdepth
2358 if (params.tocdepth != tclass.tocdepth()) {
2359 ofs << "\\setcounter{tocdepth}{"
2365 if (params.paragraph_separation) {
2366 switch (params.defskip.kind()) {
2367 case VSpace::SMALLSKIP:
2368 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2370 case VSpace::MEDSKIP:
2371 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2373 case VSpace::BIGSKIP:
2374 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2376 case VSpace::LENGTH:
2377 ofs << "\\setlength\\parskip{"
2378 << params.defskip.length().asLatexString()
2381 default: // should never happen // Then delete it.
2382 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2387 ofs << "\\setlength\\parindent{0pt}\n";
2391 // Now insert the LyX specific LaTeX commands...
2393 // The optional packages;
2394 string preamble(features.getPackages());
2396 // this might be useful...
2397 preamble += "\n\\makeatletter\n";
2399 // Some macros LyX will need
2400 string tmppreamble(features.getMacros());
2402 if (!tmppreamble.empty()) {
2403 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2404 "LyX specific LaTeX commands.\n"
2405 + tmppreamble + '\n';
2408 // the text class specific preamble
2409 tmppreamble = features.getTClassPreamble();
2410 if (!tmppreamble.empty()) {
2411 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2412 "Textclass specific LaTeX commands.\n"
2413 + tmppreamble + '\n';
2416 /* the user-defined preamble */
2417 if (!params.preamble.empty()) {
2418 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2419 "User specified LaTeX commands.\n"
2420 + params.preamble + '\n';
2423 preamble += "\\makeatother\n";
2425 // Itemize bullet settings need to be last in case the user
2426 // defines their own bullets that use a package included
2427 // in the user-defined preamble -- ARRae
2428 // Actually it has to be done much later than that
2429 // since some packages like frenchb make modifications
2430 // at \begin{document} time -- JMarc
2432 for (int i = 0; i < 4; ++i) {
2433 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2434 if (bullets_def.empty())
2435 bullets_def="\\AtBeginDocument{\n";
2436 bullets_def += " \\renewcommand{\\labelitemi";
2438 // `i' is one less than the item to modify
2445 bullets_def += "ii";
2451 bullets_def += "}{" +
2452 params.user_defined_bullets[i].getText()
2457 if (!bullets_def.empty())
2458 preamble += bullets_def + "}\n\n";
2461 int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2462 for (int j = 0; j != nlines; ++j) {
2468 // We try to load babel late, in case it interferes
2469 // with other packages.
2471 string tmp = lyxrc.language_package;
2472 if (!lyxrc.language_global_options
2473 && tmp == "\\usepackage{babel}")
2474 tmp = string("\\usepackage[") +
2475 language_options.str().c_str() +
2482 ofs << "\\begin{document}\n";
2485 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2487 if (!lyxrc.language_auto_begin) {
2488 ofs << subst(lyxrc.language_command_begin, "$$lang",
2489 params.language->babel())
2494 latexParagraphs(ofs, paragraph, 0, texrow);
2496 // add this just in case after all the paragraphs
2500 if (!lyxrc.language_auto_end) {
2501 ofs << subst(lyxrc.language_command_end, "$$lang",
2502 params.language->babel())
2508 ofs << "\\end{document}\n";
2511 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2513 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2517 // Just to be sure. (Asger)
2520 // tex_code_break_column's value is used to decide
2521 // if we are in batchmode or not (within mathed_write()
2522 // in math_write.C) so we must set it to a non-zero
2523 // value when we leave otherwise we save incorrect .lyx files.
2524 tex_code_break_column = lyxrc.ascii_linelen;
2528 lyxerr << "File was not closed properly." << endl;
2531 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2532 lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2537 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2539 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2540 Paragraph * endpar, TexRow & texrow) const
2542 bool was_title = false;
2543 bool already_title = false;
2546 while (par != endpar) {
2547 Inset * in = par->inInset();
2548 // well we have to check if we are in an inset with unlimited
2549 // lenght (all in one row) if that is true then we don't allow
2550 // any special options in the paragraph and also we don't allow
2551 // any environment other then "Standard" to be valid!
2552 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2553 LyXLayout const & layout =
2554 textclasslist.Style(params.textclass, par->layout);
2556 if (layout.intitle) {
2557 if (already_title) {
2558 lyxerr <<"Error in latexParagraphs: You"
2559 " should not mix title layouts"
2560 " with normal ones." << endl;
2563 } else if (was_title && !already_title) {
2564 ofs << "\\maketitle\n";
2566 already_title = true;
2570 if (layout.isEnvironment()) {
2571 par = par->TeXEnvironment(this, params, ofs, texrow);
2573 par = par->TeXOnePar(this, params, ofs, texrow, false);
2576 par = par->TeXOnePar(this, params, ofs, texrow, false);
2579 // It might be that we only have a title in this document
2580 if (was_title && !already_title) {
2581 ofs << "\\maketitle\n";
2587 bool Buffer::isLatex() const
2589 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2593 bool Buffer::isLinuxDoc() const
2595 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2599 bool Buffer::isLiterate() const
2601 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2605 bool Buffer::isDocBook() const
2607 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2611 bool Buffer::isSGML() const
2613 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2614 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2618 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2619 string const & latexname) const
2621 if (!latexname.empty() && latexname != "!-- --")
2622 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2623 os << string(depth, ' ') << "<" << latexname << ">\n";
2627 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2628 string const & latexname) const
2630 if (!latexname.empty() && latexname != "!-- --")
2631 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2632 os << string(depth, ' ') << "</" << latexname << ">\n";
2636 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2638 ofstream ofs(fname.c_str());
2641 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2645 niceFile = nice; // this will be used by included files.
2647 LyXTextClass const & tclass =
2648 textclasslist.TextClass(params.textclass);
2650 LaTeXFeatures features(params, tclass.numLayouts());
2655 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2658 ofs << "<!doctype linuxdoc system";
2660 string preamble = params.preamble;
2661 preamble += features.getIncludedFiles(fname);
2662 preamble += features.getLyXSGMLEntities();
2664 if (!preamble.empty()) {
2665 ofs << " [ " << preamble << " ]";
2669 if (params.options.empty())
2670 sgmlOpenTag(ofs, 0, top_element);
2672 string top = top_element;
2674 top += params.options;
2675 sgmlOpenTag(ofs, 0, top);
2679 ofs << "<!-- " << lyx_docversion
2680 << " created this file. For more info see http://www.lyx.org/"
2683 Paragraph::depth_type depth = 0; // paragraph depth
2684 Paragraph * par = paragraph;
2686 vector<string> environment_stack(5);
2689 LyXLayout const & style =
2690 textclasslist.Style(params.textclass,
2693 // treat <toc> as a special case for compatibility with old code
2694 if (par->isInset(0)) {
2695 Inset * inset = par->getInset(0);
2696 Inset::Code lyx_code = inset->lyxCode();
2697 if (lyx_code == Inset::TOC_CODE) {
2698 string const temp = "toc";
2699 sgmlOpenTag(ofs, depth, temp);
2706 // environment tag closing
2707 for (; depth > par->params().depth(); --depth) {
2708 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2709 environment_stack[depth].erase();
2712 // write opening SGML tags
2713 switch (style.latextype) {
2714 case LATEX_PARAGRAPH:
2715 if (depth == par->params().depth()
2716 && !environment_stack[depth].empty()) {
2717 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2718 environment_stack[depth].erase();
2724 sgmlOpenTag(ofs, depth, style.latexname());
2730 _("Error : Wrong depth for"
2731 " LatexType Command.\n"));
2733 if (!environment_stack[depth].empty()) {
2734 sgmlCloseTag(ofs, depth,
2735 environment_stack[depth]);
2739 environment_stack[depth].erase();
2740 sgmlOpenTag(ofs, depth, style.latexname());
2743 case LATEX_ENVIRONMENT:
2744 case LATEX_ITEM_ENVIRONMENT:
2745 if (depth == par->params().depth()
2746 && environment_stack[depth] != style.latexname()) {
2747 sgmlCloseTag(ofs, depth,
2748 environment_stack[depth]);
2749 environment_stack[depth].erase();
2751 if (depth < par->params().depth()) {
2752 depth = par->params().depth();
2753 environment_stack[depth].erase();
2755 if (environment_stack[depth] != style.latexname()) {
2757 sgmlOpenTag(ofs, depth, "p");
2759 sgmlOpenTag(ofs, depth, style.latexname());
2761 if (environment_stack.size() == depth + 1)
2762 environment_stack.push_back("!-- --");
2763 environment_stack[depth] = style.latexname();
2766 if (style.latexparam() == "CDATA")
2769 if (style.latextype == LATEX_ENVIRONMENT) break;
2771 if (style.labeltype == LABEL_MANUAL)
2776 sgmlOpenTag(ofs, depth + 1, item_name);
2779 sgmlOpenTag(ofs, depth, style.latexname());
2783 simpleLinuxDocOnePar(ofs, par, depth);
2788 // write closing SGML tags
2789 switch (style.latextype) {
2792 case LATEX_ENVIRONMENT:
2793 case LATEX_ITEM_ENVIRONMENT:
2794 if (style.latexparam() == "CDATA")
2798 sgmlCloseTag(ofs, depth, style.latexname());
2804 for (int i=depth; i >= 0; --i)
2805 sgmlCloseTag(ofs, depth, environment_stack[i]);
2809 sgmlCloseTag(ofs, 0, top_element);
2813 // How to check for successful close
2817 // checks, if newcol chars should be put into this line
2818 // writes newline, if necessary.
2821 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2822 string::size_type newcol)
2825 if (colcount > lyxrc.ascii_linelen) {
2827 colcount = newcol; // assume write after this call
2842 string tag_name(PAR_TAG const & pt) {
2844 case NONE: return "!-- --";
2845 case TT: return "tt";
2846 case SF: return "sf";
2847 case BF: return "bf";
2848 case IT: return "it";
2849 case SL: return "sl";
2850 case EM: return "em";
2857 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2859 p1 = static_cast<PAR_TAG>(p1 | p2);
2864 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2866 p1 = static_cast<PAR_TAG>(p1 & ~p2);
2872 // Handle internal paragraph parsing -- layout already processed.
2873 void Buffer::simpleLinuxDocOnePar(ostream & os,
2875 Paragraph::depth_type /*depth*/)
2877 LyXLayout const & style = textclasslist.Style(params.textclass,
2879 string::size_type char_line_count = 5; // Heuristic choice ;-)
2881 // gets paragraph main font
2884 if (style.labeltype == LABEL_MANUAL) {
2885 font_old = style.labelfont;
2888 font_old = style.font;
2892 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2893 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2894 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2897 stack<PAR_TAG> tag_state;
2898 // parsing main loop
2899 for (pos_type i = 0; i < par->size(); ++i) {
2901 PAR_TAG tag_close = NONE;
2902 list < PAR_TAG > tag_open;
2904 LyXFont const font = par->getFont(params, i);
2906 if (font_old.family() != font.family()) {
2907 switch (family_type) {
2908 case LyXFont::SANS_FAMILY:
2911 case LyXFont::TYPEWRITER_FAMILY:
2918 family_type = font.family();
2920 switch (family_type) {
2921 case LyXFont::SANS_FAMILY:
2922 tag_open.push_back(SF);
2924 case LyXFont::TYPEWRITER_FAMILY:
2925 tag_open.push_back(TT);
2932 if (font_old.series() != font.series()) {
2933 switch (series_type) {
2934 case LyXFont::BOLD_SERIES:
2941 series_type = font.series();
2943 switch (series_type) {
2944 case LyXFont::BOLD_SERIES:
2945 tag_open.push_back(BF);
2953 if (font_old.shape() != font.shape()) {
2954 switch (shape_type) {
2955 case LyXFont::ITALIC_SHAPE:
2958 case LyXFont::SLANTED_SHAPE:
2965 shape_type = font.shape();
2967 switch (shape_type) {
2968 case LyXFont::ITALIC_SHAPE:
2969 tag_open.push_back(IT);
2971 case LyXFont::SLANTED_SHAPE:
2972 tag_open.push_back(SL);
2979 if (font_old.emph() != font.emph()) {
2980 if (font.emph() == LyXFont::ON) {
2981 tag_open.push_back(EM);
2990 list < PAR_TAG > temp;
2991 while (!tag_state.empty() && tag_close) {
2992 PAR_TAG k = tag_state.top();
2994 os << "</" << tag_name(k) << ">";
3001 for(list< PAR_TAG >::const_iterator j = temp.begin();
3002 j != temp.end(); ++j) {
3004 os << "<" << tag_name(*j) << ">";
3007 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
3008 j != tag_open.end(); ++j) {
3010 os << "<" << tag_name(*j) << ">";
3013 char c = par->getChar(i);
3015 if (c == Paragraph::META_INSET) {
3016 Inset * inset = par->getInset(i);
3017 inset->linuxdoc(this, os);
3022 if (style.latexparam() == "CDATA") {
3023 // "TeX"-Mode on == > SGML-Mode on.
3029 if (par->sgmlConvertChar(c, sgml_string)
3030 && !style.free_spacing && !par->isFreeSpacing())
3032 // in freespacing mode, spaces are
3033 // non-breaking characters
3034 if (desc_on) {// if char is ' ' then...
3037 sgmlLineBreak(os, char_line_count, 6);
3041 sgmlLineBreak(os, char_line_count, 1);
3046 char_line_count += sgml_string.length();
3052 while (!tag_state.empty()) {
3053 os << "</" << tag_name(tag_state.top()) << ">";
3057 // resets description flag correctly
3059 // <tag> not closed...
3060 sgmlLineBreak(os, char_line_count, 6);
3066 // Print an error message.
3067 void Buffer::sgmlError(Paragraph * par, int pos,
3068 string const & message) const
3070 // insert an error marker in text
3071 InsetError * new_inset = new InsetError(message);
3072 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
3077 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3079 ofstream ofs(fname.c_str());
3081 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3085 Paragraph * par = paragraph;
3087 niceFile = nice; // this will be used by Insetincludes.
3089 LyXTextClass const & tclass =
3090 textclasslist.TextClass(params.textclass);
3092 LaTeXFeatures features(params, tclass.numLayouts());
3097 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3100 ofs << "<!DOCTYPE " << top_element
3101 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3103 string preamble = params.preamble;
3104 preamble += features.getIncludedFiles(fname);
3105 preamble += features.getLyXSGMLEntities();
3107 if (!preamble.empty()) {
3108 ofs << "\n [ " << preamble << " ]";
3113 string top = top_element;
3115 top += params.language->code();
3118 if (!params.options.empty()) {
3120 top += params.options;
3122 sgmlOpenTag(ofs, 0, top);
3124 ofs << "<!-- DocBook file was created by " << lyx_docversion
3125 << "\n See http://www.lyx.org/ for more information -->\n";
3127 vector<string> environment_stack(10);
3128 vector<string> environment_inner(10);
3129 vector<string> command_stack(10);
3131 bool command_flag = false;
3132 Paragraph::depth_type command_depth = 0;
3133 Paragraph::depth_type command_base = 0;
3134 Paragraph::depth_type cmd_depth = 0;
3135 Paragraph::depth_type depth = 0; // paragraph depth
3138 string command_name;
3144 int desc_on = 0; // description mode
3146 LyXLayout const & style =
3147 textclasslist.Style(params.textclass,
3150 // environment tag closing
3151 for (; depth > par->params().depth(); --depth) {
3152 if (environment_inner[depth] != "!-- --") {
3153 item_name = "listitem";
3154 sgmlCloseTag(ofs, command_depth + depth,
3156 if (environment_inner[depth] == "varlistentry")
3157 sgmlCloseTag(ofs, depth+command_depth,
3158 environment_inner[depth]);
3160 sgmlCloseTag(ofs, depth + command_depth,
3161 environment_stack[depth]);
3162 environment_stack[depth].erase();
3163 environment_inner[depth].erase();
3166 if (depth == par->params().depth()
3167 && environment_stack[depth] != style.latexname()
3168 && !environment_stack[depth].empty()) {
3169 if (environment_inner[depth] != "!-- --") {
3170 item_name= "listitem";
3171 sgmlCloseTag(ofs, command_depth+depth,
3173 if (environment_inner[depth] == "varlistentry")
3175 depth + command_depth,
3176 environment_inner[depth]);
3179 sgmlCloseTag(ofs, depth + command_depth,
3180 environment_stack[depth]);
3182 environment_stack[depth].erase();
3183 environment_inner[depth].erase();
3186 // Write opening SGML tags.
3187 switch (style.latextype) {
3188 case LATEX_PARAGRAPH:
3189 sgmlOpenTag(ofs, depth + command_depth,
3196 _("Error : Wrong depth for "
3197 "LatexType Command.\n"));
3199 command_name = style.latexname();
3201 sgmlparam = style.latexparam();
3202 c_params = split(sgmlparam, c_depth,'|');
3204 cmd_depth = lyx::atoi(c_depth);
3207 if (cmd_depth < command_base) {
3208 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3209 sgmlCloseTag(ofs, j, command_stack[j]);
3210 command_depth = command_base = cmd_depth;
3211 } else if (cmd_depth <= command_depth) {
3212 for (int j = command_depth; j >= int(cmd_depth); --j)
3213 sgmlCloseTag(ofs, j, command_stack[j]);
3214 command_depth = cmd_depth;
3216 command_depth = cmd_depth;
3218 command_depth = command_base = cmd_depth;
3219 command_flag = true;
3221 if (command_stack.size() == command_depth + 1)
3222 command_stack.push_back(string());
3223 command_stack[command_depth] = command_name;
3225 // treat label as a special case for
3226 // more WYSIWYM handling.
3227 // This is a hack while paragraphs can't have
3228 // attributes, like id in this case.
3229 if (par->isInset(0)) {
3230 Inset * inset = par->getInset(0);
3231 Inset::Code lyx_code = inset->lyxCode();
3232 if (lyx_code == Inset::LABEL_CODE) {
3233 command_name += " id=\"";
3234 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3235 command_name += "\"";
3240 sgmlOpenTag(ofs, depth + command_depth, command_name);
3241 if (c_params.empty())
3242 item_name = "title";
3244 item_name = c_params;
3245 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3248 case LATEX_ENVIRONMENT:
3249 case LATEX_ITEM_ENVIRONMENT:
3250 if (depth < par->params().depth()) {
3251 depth = par->params().depth();
3252 environment_stack[depth].erase();
3255 if (environment_stack[depth] != style.latexname()) {
3256 if (environment_stack.size() == depth + 1) {
3257 environment_stack.push_back("!-- --");
3258 environment_inner.push_back("!-- --");
3260 environment_stack[depth] = style.latexname();
3261 environment_inner[depth] = "!-- --";
3262 sgmlOpenTag(ofs, depth + command_depth,
3263 environment_stack[depth]);
3265 if (environment_inner[depth] != "!-- --") {
3266 item_name= "listitem";
3268 command_depth + depth,
3270 if (environment_inner[depth] == "varlistentry")
3272 depth + command_depth,
3273 environment_inner[depth]);
3277 if (style.latextype == LATEX_ENVIRONMENT) {
3278 if (!style.latexparam().empty()) {
3279 if (style.latexparam() == "CDATA")
3282 sgmlOpenTag(ofs, depth + command_depth,
3283 style.latexparam());
3288 desc_on = (style.labeltype == LABEL_MANUAL);
3291 environment_inner[depth]= "varlistentry";
3293 environment_inner[depth]= "listitem";
3295 sgmlOpenTag(ofs, depth + 1 + command_depth,
3296 environment_inner[depth]);
3300 sgmlOpenTag(ofs, depth + 1 + command_depth,
3304 sgmlOpenTag(ofs, depth + 1 + command_depth,
3309 sgmlOpenTag(ofs, depth + command_depth,
3314 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3318 // write closing SGML tags
3319 switch (style.latextype) {
3321 if (c_params.empty())
3325 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3327 case LATEX_ENVIRONMENT:
3328 if (!style.latexparam().empty()) {
3329 if (style.latexparam() == "CDATA")
3332 sgmlCloseTag(ofs, depth + command_depth,
3333 style.latexparam());
3336 case LATEX_ITEM_ENVIRONMENT:
3337 if (desc_on == 1) break;
3339 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3341 case LATEX_PARAGRAPH:
3342 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3345 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3351 for (int d = depth; d >= 0; --d) {
3352 if (!environment_stack[depth].empty()) {
3353 if (environment_inner[depth] != "!-- --") {
3354 item_name = "listitem";
3355 sgmlCloseTag(ofs, command_depth + depth,
3357 if (environment_inner[depth] == "varlistentry")
3358 sgmlCloseTag(ofs, depth + command_depth,
3359 environment_inner[depth]);
3362 sgmlCloseTag(ofs, depth + command_depth,
3363 environment_stack[depth]);
3367 for (int j = command_depth; j >= 0 ; --j)
3368 if (!command_stack[j].empty())
3369 sgmlCloseTag(ofs, j, command_stack[j]);
3372 sgmlCloseTag(ofs, 0, top_element);
3375 // How to check for successful close
3379 void Buffer::simpleDocBookOnePar(ostream & os,
3380 Paragraph * par, int & desc_on,
3381 Paragraph::depth_type depth) const
3383 bool emph_flag = false;
3385 LyXLayout const & style = textclasslist.Style(params.textclass,
3388 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3390 int char_line_count = depth;
3391 //if (!style.free_spacing)
3392 // os << string(depth,' ');
3394 // parsing main loop
3395 for (pos_type i = 0; i < par->size(); ++i) {
3396 LyXFont font = par->getFont(params, i);
3398 // handle <emphasis> tag
3399 if (font_old.emph() != font.emph()) {
3400 if (font.emph() == LyXFont::ON) {
3404 os << "</emphasis>";
3410 if (par->isInset(i)) {
3411 Inset * inset = par->getInset(i);
3412 // don't print the inset in position 0 if desc_on == 3 (label)
3413 if ( i || desc_on != 3) {
3414 if(style.latexparam() == "CDATA")
3416 inset->docbook(this, os);
3417 if(style.latexparam() == "CDATA")
3421 char c = par->getChar(i);
3423 par->sgmlConvertChar(c, sgml_string);
3425 if (style.pass_thru) {
3427 } else if (style.free_spacing || par->isFreeSpacing() || c != ' ') {
3429 } else if (desc_on ==1) {
3431 os << "\n</term><listitem><para>";
3441 os << "</emphasis>";
3444 // resets description flag correctly
3446 // <term> not closed...
3449 if (style.free_spacing) os << '\n';
3453 // This should be enabled when the Chktex class is implemented. (Asger)
3454 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3455 // Other flags: -wall -v0 -x
3456 int Buffer::runChktex()
3458 if (!users->text) return 0;
3460 users->owner()->prohibitInput();
3462 // get LaTeX-Filename
3463 string const name = getLatexName();
3464 string path = filePath();
3466 string const org_path = path;
3467 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3471 Path p(path); // path to LaTeX file
3472 users->owner()->message(_("Running chktex..."));
3474 // Remove all error insets
3475 bool const removedErrorInsets = users->removeAutoInsets();
3477 // Generate the LaTeX file if neccessary
3478 makeLaTeXFile(name, org_path, false);
3481 Chktex chktex(lyxrc.chktex_command, name, filePath());
3482 int res = chktex.run(terr); // run chktex
3485 Alert::alert(_("chktex did not work!"),
3486 _("Could not run with file:"), name);
3487 } else if (res > 0) {
3488 // Insert all errors as errors boxes
3489 users->insertErrors(terr);
3492 // if we removed error insets before we ran chktex or if we inserted
3493 // error insets after we ran chktex, this must be run:
3494 if (removedErrorInsets || res) {
3498 users->owner()->allowInput();
3504 void Buffer::validate(LaTeXFeatures & features) const
3506 Paragraph * par = paragraph;
3507 LyXTextClass const & tclass =
3508 textclasslist.TextClass(params.textclass);
3510 // AMS Style is at document level
3511 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3512 features.require("amsmath");
3515 // We don't use "lyxerr.debug" because of speed. (Asger)
3516 if (lyxerr.debugging(Debug::LATEX))
3517 lyxerr << "Paragraph: " << par << endl;
3519 // Now just follow the list of paragraphs and run
3520 // validate on each of them.
3521 par->validate(features);
3523 // and then the next paragraph
3527 // the bullet shapes are buffer level not paragraph level
3528 // so they are tested here
3529 for (int i = 0; i < 4; ++i) {
3530 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3531 int const font = params.user_defined_bullets[i].getFont();
3533 int const c = params
3534 .user_defined_bullets[i]
3541 features.require("latexsym");
3543 } else if (font == 1) {
3544 features.require("amssymb");
3545 } else if ((font >= 2 && font <= 5)) {
3546 features.require("pifont");
3551 if (lyxerr.debugging(Debug::LATEX)) {
3552 features.showStruct();
3557 // This function should be in Buffer because it's a buffer's property (ale)
3558 string const Buffer::getIncludeonlyList(char delim)
3561 for (inset_iterator it = inset_iterator_begin();
3562 it != inset_iterator_end(); ++it) {
3563 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3564 InsetInclude * insetinc =
3565 static_cast<InsetInclude *>(*it);
3566 if (insetinc->isIncludeOnly()) {
3569 lst += insetinc->getRelFileBaseName();
3573 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3578 vector<string> const Buffer::getLabelList()
3580 /// if this is a child document and the parent is already loaded
3581 /// Use the parent's list instead [ale990407]
3582 if (!params.parentname.empty()
3583 && bufferlist.exists(params.parentname)) {
3584 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3586 return tmp->getLabelList();
3589 vector<string> label_list;
3590 for (inset_iterator it = inset_iterator_begin();
3591 it != inset_iterator_end(); ++it) {
3592 vector<string> const l = (*it)->getLabelList();
3593 label_list.insert(label_list.end(), l.begin(), l.end());
3599 Buffer::Lists const Buffer::getLists() const
3602 Paragraph * par = paragraph;
3605 std::pair<bool, textclass_type> const tmp =
3606 textclasslist.NumberOfLayout(params.textclass, "Caption");
3607 bool const found = tmp.first;
3608 textclass_type const cap = tmp.second;
3611 // This is the prefered way to to this, but boost::tie can break
3615 boost::tie(found, cap) = textclasslist
3616 .NumberOfLayout(params.textclass, "Caption");
3620 char const labeltype =
3621 textclasslist.Style(params.textclass,
3622 par->getLayout()).labeltype;
3624 if (labeltype >= LABEL_COUNTER_CHAPTER
3625 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3626 // insert this into the table of contents
3627 SingleList & item = l["TOC"];
3630 textclasslist.TextClass(params.textclass).maxcounter());
3631 item.push_back(TocItem(par, depth, par->asString(this, true)));
3633 // For each paragrph, traverse its insets and look for
3637 Paragraph::inset_iterator it =
3638 par->inset_iterator_begin();
3639 Paragraph::inset_iterator end =
3640 par->inset_iterator_end();
3642 for (; it != end; ++it) {
3643 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3645 static_cast<InsetFloat*>(*it);
3647 string const type = il->type();
3649 // Now find the caption in the float...
3650 // We now tranverse the paragraphs of
3652 Paragraph * tmp = il->inset.paragraph();
3654 if (tmp->layout == cap) {
3655 SingleList & item = l[type];
3657 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3658 item.push_back(TocItem(tmp, 0 , str));
3665 lyxerr << "caption not found" << endl;
3674 // This is also a buffer property (ale)
3675 vector<pair<string, string> > const Buffer::getBibkeyList()
3677 /// if this is a child document and the parent is already loaded
3678 /// Use the parent's list instead [ale990412]
3679 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3680 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3682 return tmp->getBibkeyList();
3685 vector<pair<string, string> > keys;
3686 Paragraph * par = paragraph;
3689 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3690 par->asString(this, false)));
3694 // Might be either using bibtex or a child has bibliography
3696 for (inset_iterator it = inset_iterator_begin();
3697 it != inset_iterator_end(); ++it) {
3698 // Search for Bibtex or Include inset
3699 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3700 vector<pair<string,string> > tmp =
3701 static_cast<InsetBibtex*>(*it)->getKeys(this);
3702 keys.insert(keys.end(), tmp.begin(), tmp.end());
3703 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3704 vector<pair<string,string> > const tmp =
3705 static_cast<InsetInclude*>(*it)->getKeys();
3706 keys.insert(keys.end(), tmp.begin(), tmp.end());
3715 bool Buffer::isDepClean(string const & name) const
3717 DEPCLEAN * item = dep_clean;
3718 while (item && item->master != name)
3720 if (!item) return true;
3725 void Buffer::markDepClean(string const & name)
3728 dep_clean = new DEPCLEAN;
3729 dep_clean->clean = true;
3730 dep_clean->master = name;
3731 dep_clean->next = 0;
3733 DEPCLEAN * item = dep_clean;
3734 while (item && item->master != name)
3739 item = new DEPCLEAN;
3741 item->master = name;
3748 bool Buffer::dispatch(string const & command)
3750 // Split command string into command and argument
3752 string line = frontStrip(command);
3753 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3755 return dispatch(lyxaction.LookupFunc(cmd), arg);
3759 bool Buffer::dispatch(int action, string const & argument)
3761 bool dispatched = true;
3764 Exporter::Export(this, argument, false);
3774 void Buffer::resizeInsets(BufferView * bv)
3776 /// then remove all LyXText in text-insets
3777 Paragraph * par = paragraph;
3778 for (; par; par = par->next()) {
3779 par->resizeInsetsLyXText(bv);
3784 void Buffer::redraw()
3791 void Buffer::changeLanguage(Language const * from, Language const * to)
3794 ParIterator end = par_iterator_end();
3795 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3796 (*it)->changeLanguage(params, from, to);
3800 bool Buffer::isMultiLingual()
3802 ParIterator end = par_iterator_end();
3803 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3804 if ((*it)->isMultiLingual(params))
3811 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
3814 it = par->InsetIterator(pos);
3815 if (it == par->inset_iterator_end()) {
3822 void Buffer::inset_iterator::setParagraph()
3825 it = par->inset_iterator_begin();
3826 if (it != par->inset_iterator_end())
3831 // We maintain an invariant that whenever par = 0 then it = 0
3835 Inset * Buffer::getInsetFromID(int id_arg) const
3837 for (inset_iterator it = inset_const_iterator_begin();
3838 it != inset_const_iterator_end(); ++it)
3840 if ((*it)->id() == id_arg)
3842 Inset * in = (*it)->getInsetFromID(id_arg);
3850 Paragraph * Buffer::getParFromID(int id) const
3852 if (id < 0) return 0;
3853 Paragraph * par = paragraph;
3855 if (par->id() == id) {
3858 Paragraph * tmp = par->getParFromID(id);
3868 ParIterator Buffer::par_iterator_begin()
3870 return ParIterator(paragraph);
3874 ParIterator Buffer::par_iterator_end()
3876 return ParIterator();