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/insettext.h"
70 #include "insets/insetert.h"
71 #include "insets/insetgraphics.h"
72 #include "insets/insetfoot.h"
73 #include "insets/insetmarginal.h"
74 #include "insets/insetminipage.h"
75 #include "insets/insetfloat.h"
76 #include "insets/insettabular.h"
78 #include "insets/insettheorem.h"
79 #include "insets/insetlist.h"
81 #include "insets/insetcaption.h"
82 #include "insets/insetfloatlist.h"
84 #include "frontends/Dialogs.h"
85 #include "frontends/Alert.h"
87 #include "support/textutils.h"
88 #include "support/filetools.h"
89 #include "support/path.h"
90 #include "support/os.h"
91 #include "support/lyxlib.h"
92 #include "support/FileInfo.h"
93 #include "support/lyxmanip.h"
94 #include "support/lyxalgo.h" // for lyx::count
106 #include <sys/types.h>
123 using std::make_pair;
132 using lyx::layout_type;
133 using lyx::textclass_type;
135 // all these externs should eventually be removed.
136 extern BufferList bufferlist;
138 extern LyXAction lyxaction;
142 const int LYX_FORMAT = 220;
146 extern int tex_code_break_column;
149 Buffer::Buffer(string const & file, bool ronly)
150 : paragraph(0), lyx_clean(true), bak_clean(true),
151 unnamed(false), dep_clean(0), read_only(ronly),
152 filename_(file), users(0)
154 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
156 filepath_ = OnlyPath(file);
161 // read_only = ronly;
165 if (read_only || lyxrc.use_tempdir) {
166 tmppath = CreateBufferTmpDir();
175 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
176 // here the buffer should take care that it is
177 // saved properly, before it goes into the void.
179 // make sure that views using this buffer
184 if (!tmppath.empty()) {
185 DestroyBufferTmpDir(tmppath);
188 Paragraph * par = paragraph;
191 tmppar = par->next();
199 string const Buffer::getLatexName(bool no_path) const
201 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
203 return OnlyFilename(name);
209 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
211 string const filename = getLatexName(false);
213 if (filename.empty())
214 return make_pair(Buffer::latexlog, string());
216 string path = OnlyPath(filename);
218 if (lyxrc.use_tempdir || !IsDirWriteable(path))
221 string const fname = AddName(path,
222 OnlyFilename(ChangeExtension(filename,
225 AddName(path, OnlyFilename(
226 ChangeExtension(filename,
227 formats.extension("literate") + ".out")));
229 // If no Latex log or Build log is newer, show Build log
231 FileInfo const f_fi(fname);
232 FileInfo const b_fi(bname);
235 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
236 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
237 return make_pair(Buffer::buildlog, bname);
239 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
240 return make_pair(Buffer::latexlog, fname);
244 void Buffer::setReadonly(bool flag)
246 if (read_only != flag) {
249 users->owner()->getDialogs()->updateBufferDependent(false);
254 /// Update window titles of all users
255 // Should work on a list
256 void Buffer::updateTitles() const
259 users->owner()->updateWindowTitle();
263 /// Reset autosave timer of all users
264 // Should work on a list
265 void Buffer::resetAutosaveTimers() const
268 users->owner()->resetAutosaveTimer();
272 void Buffer::setFileName(string const & newfile)
274 filename_ = MakeAbsPath(newfile);
275 filepath_ = OnlyPath(filename_);
276 setReadonly(IsFileWriteable(filename_) == 0);
281 // We'll remove this later. (Lgb)
284 string last_inset_read;
286 #ifndef NO_COMPABILITY
289 ErtComp() : active(false), in_tabular(false) {
297 std::stack<ErtComp> ert_stack;
302 #warning And _why_ is this here? (Lgb)
310 // candidate for move to BufferView
311 // (at least some parts in the beginning of the func)
314 // changed to be public and have one parameter
315 // if par = 0 normal behavior
316 // else insert behavior
317 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
318 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
322 #ifndef NO_COMPABILITY
323 ert_comp.contents.erase();
324 ert_comp.active = false;
325 ert_comp.in_tabular = false;
328 Paragraph::depth_type depth = 0;
329 bool the_end_read = false;
331 Paragraph * first_par = 0;
332 LyXFont font(LyXFont::ALL_INHERIT, params.language);
333 if (file_format < 216 && params.language->lang() == "hebrew")
334 font.setLanguage(default_language);
339 // We are inserting into an existing document
340 users->text->breakParagraph(users);
341 first_par = users->text->ownerParagraph();
344 // We don't want to adopt the parameters from the
345 // document we insert, so we skip until the text begins:
348 string const pretoken = lex.getString();
349 if (pretoken == "\\layout") {
350 lex.pushToken(pretoken);
358 string const token = lex.getString();
360 if (token.empty()) continue;
362 lyxerr[Debug::PARSER] << "Handling token: `"
363 << token << "'" << endl;
366 parseSingleLyXformat2Token(lex, par, first_par,
374 paragraph = first_par;
376 if (unknown_layouts > 0) {
377 string s = _("Couldn't set the layout for ");
378 if (unknown_layouts == 1) {
379 s += _("one paragraph");
381 s += tostr(unknown_layouts);
382 s += _(" paragraphs");
384 Alert::alert(_("Textclass Loading Error!"), s,
385 _("When reading " + fileName()));
388 if (unknown_tokens > 0) {
389 string s = _("Encountered ");
390 if (unknown_tokens == 1) {
391 s += _("one unknown token");
393 s += tostr(unknown_tokens);
394 s += _(" unknown tokens");
396 Alert::alert(_("Textclass Loading Error!"), s,
397 _("When reading " + fileName()));
404 #ifndef NO_COMPABILITY
405 void Buffer::insertErtContents(Paragraph * par, int & pos, bool set_inactive)
407 if (!ert_comp.contents.empty()) {
408 lyxerr[Debug::INSETS] << "ERT contents:\n'"
409 << ert_comp.contents << "'" << endl;
410 Inset * inset = new InsetERT(params.language, ert_comp.contents, true);
411 par->insertInset(pos++, inset, ert_comp.font);
412 ert_comp.contents.erase();
415 ert_comp.active = false;
422 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
423 Paragraph *& first_par,
424 string const & token, int & pos,
425 Paragraph::depth_type & depth,
429 bool the_end_read = false;
430 #ifndef NO_COMPABILITY
431 #ifndef NO_PEXTRA_REALLY
432 // This is super temporary but is needed to get the compability
433 // mode for minipages work correctly together with new tabulars.
434 static int call_depth;
436 bool checkminipage = false;
437 static Paragraph * minipar;
438 static Paragraph * parBeforeMinipage;
441 if (token[0] != '\\') {
442 #ifndef NO_COMPABILITY
443 if (ert_comp.active) {
444 ert_comp.contents += token;
447 for (string::const_iterator cit = token.begin();
448 cit != token.end(); ++cit) {
449 par->insertChar(pos, (*cit), font);
452 #ifndef NO_COMPABILITY
455 } else if (token == "\\i") {
456 Inset * inset = new InsetLatexAccent;
457 inset->read(this, lex);
458 par->insertInset(pos, inset, font);
460 } else if (token == "\\layout") {
461 #ifndef NO_COMPABILITY
462 ert_comp.in_tabular = false;
464 insertErtContents(par, pos);
467 string const layoutname = lex.getString();
468 //lyxerr << "Looking for layout '"
469 // << layoutname << "'!" << endl;
471 pair<bool, layout_type> pp
472 = textclasslist.NumberOfLayout(params.textclass, layoutname);
474 //lyxerr << "Result: " << pp.first << "/" << pp.second << endl;
476 #ifndef NO_COMPABILITY
477 if (compare_no_case(layoutname, "latex") == 0) {
478 ert_comp.active = true;
479 ert_comp.font = font;
483 // The is the compability reading of layout caption.
484 // It can be removed in LyX version 1.3.0. (Lgb)
485 if (compare_no_case(layoutname, "caption") == 0) {
486 // We expect that the par we are now working on is
487 // really inside a InsetText inside a InsetFloat.
488 // We also know that captions can only be
489 // one paragraph. (Lgb)
491 // We should now read until the next "\layout"
493 // This is probably not good enough, what if the
494 // caption is the last par in the document (Lgb)
495 istream & ist = lex.getStream();
501 if (prefixIs(line, "\\layout")) {
505 if (prefixIs(line, "\\begin_inset"))
507 if (prefixIs(line, "\\end_inset")) {
518 // Now we should have the whole layout in ss
519 // we should now be able to give this to the
521 ss << "\\end_inset\n";
523 // This seems like a bug in stringstream.
524 // We really should be able to use ss
526 istringstream is(ss.str());
528 tmplex.setStream(is);
529 Inset * inset = new InsetCaption;
530 inset->Read(this, tmplex);
531 par->InsertInset(pos, inset, font);
538 par = new Paragraph(par);
542 par->layout = pp.second;
543 #ifndef NO_COMPABILITY
544 } else if (ert_comp.active) {
549 // use default layout "Standard" (0)
550 //lyxerr << "Layout '" << layoutname
551 // << "' was not found!" << endl;
555 string const s = _("Layout had to be changed from\n")
556 + layoutname + _(" to ")
557 + textclasslist.NameOfLayout(params.textclass, par->layout);
558 InsetError * new_inset = new InsetError(s);
559 par->insertInset(0, new_inset,
560 LyXFont(LyXFont::ALL_INHERIT,
563 // Test whether the layout is obsolete.
564 LyXLayout const & layout =
565 textclasslist.Style(params.textclass,
567 if (!layout.obsoleted_by().empty())
568 par->layout = textclasslist
569 .NumberOfLayout(params.textclass,
570 layout.obsoleted_by())
572 par->params().depth(depth);
573 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
574 if (file_format < 216
575 && params.language->lang() == "hebrew")
576 font.setLanguage(default_language);
581 #ifndef NO_COMPABILITY
582 } else if (token == "\\begin_float") {
583 insertErtContents(par, pos);
584 //insertErtContents(par, pos, false);
585 //ert_stack.push(ert_comp);
586 //ert_comp = ErtComp();
588 // This is the compability reader. It can be removed in
589 // LyX version 1.3.0. (Lgb)
591 string const tmptok = lex.getString();
592 //lyxerr << "old float: " << tmptok << endl;
595 stringstream old_float;
597 if (tmptok == "footnote") {
598 inset = new InsetFoot;
599 old_float << "collapsed true\n";
600 } else if (tmptok == "margin") {
601 inset = new InsetMarginal;
602 old_float << "collapsed true\n";
603 } else if (tmptok == "fig") {
604 inset = new InsetFloat("figure");
605 old_float << "placement htbp\n"
607 << "collapsed false\n";
608 } else if (tmptok == "tab") {
609 inset = new InsetFloat("table");
610 old_float << "placement htbp\n"
612 << "collapsed false\n";
613 } else if (tmptok == "alg") {
614 inset = new InsetFloat("algorithm");
615 old_float << "placement htbp\n"
617 << "collapsed false\n";
618 } else if (tmptok == "wide-fig") {
619 inset = new InsetFloat("figure");
620 //InsetFloat * tmp = new InsetFloat("figure");
623 old_float << "placement htbp\n"
625 << "collapsed false\n";
626 } else if (tmptok == "wide-tab") {
627 inset = new InsetFloat("table");
628 //InsetFloat * tmp = new InsetFloat("table");
631 old_float << "placement htbp\n"
633 << "collapsed false\n";
637 #ifndef NO_PEXTRA_REALLY
640 return false; // no end read yet
643 // Here we need to check for \end_deeper and handle that
644 // before we do the footnote parsing.
645 // This _is_ a hack! (Lgb)
648 string const tmp = lex.getString();
649 if (tmp == "\\end_deeper") {
650 //lyxerr << "\\end_deeper caught!" << endl;
652 lex.printError("\\end_deeper: "
653 "depth is already null");
658 old_float << tmp << ' ';
663 old_float << lex.getLongString("\\end_float")
664 << "\n\\end_inset\n";
665 //lyxerr << "Float Body:\n" << old_float.str() << endl;
666 // That this does not work seems like a bug
667 // in stringstream. (Lgb)
668 istringstream istr(old_float.str());
670 nylex.setStream(istr);
671 inset->read(this, nylex);
672 par->insertInset(pos, inset, font);
674 insertErtContents(par, pos);
676 } else if (token == "\\begin_deeper") {
678 } else if (token == "\\end_deeper") {
680 lex.printError("\\end_deeper: "
681 "depth is already null");
685 } else if (token == "\\begin_preamble") {
686 params.readPreamble(lex);
687 } else if (token == "\\textclass") {
689 pair<bool, textclass_type> pp =
690 textclasslist.NumberOfClass(lex.getString());
692 params.textclass = pp.second;
694 Alert::alert(string(_("Textclass error")),
695 string(_("The document uses an unknown textclass \"")) +
696 lex.getString() + string("\"."),
697 string(_("LyX will not be able to produce output correctly.")));
698 params.textclass = 0;
700 if (!textclasslist.Load(params.textclass)) {
701 // if the textclass wasn't loaded properly
702 // we need to either substitute another
703 // or stop loading the file.
704 // I can substitute but I don't see how I can
705 // stop loading... ideas?? ARRae980418
706 Alert::alert(_("Textclass Loading Error!"),
707 string(_("Can't load textclass ")) +
708 textclasslist.NameOfClass(params.textclass),
709 _("-- substituting default"));
710 params.textclass = 0;
712 } else if (token == "\\options") {
714 params.options = lex.getString();
715 } else if (token == "\\language") {
716 params.readLanguage(lex);
717 } else if (token == "\\fontencoding") {
719 } else if (token == "\\inputencoding") {
721 params.inputenc = lex.getString();
722 } else if (token == "\\graphics") {
723 params.readGraphicsDriver(lex);
724 } else if (token == "\\fontscheme") {
726 params.fonts = lex.getString();
727 } else if (token == "\\noindent") {
728 par->params().noindent(true);
729 } else if (token == "\\fill_top") {
730 par->params().spaceTop(VSpace(VSpace::VFILL));
731 } else if (token == "\\fill_bottom") {
732 par->params().spaceBottom(VSpace(VSpace::VFILL));
733 } else if (token == "\\line_top") {
734 par->params().lineTop(true);
735 } else if (token == "\\line_bottom") {
736 par->params().lineBottom(true);
737 } else if (token == "\\pagebreak_top") {
738 par->params().pagebreakTop(true);
739 } else if (token == "\\pagebreak_bottom") {
740 par->params().pagebreakBottom(true);
741 } else if (token == "\\start_of_appendix") {
742 par->params().startOfAppendix(true);
743 } else if (token == "\\paragraph_separation") {
744 int tmpret = lex.findToken(string_paragraph_separation);
747 if (tmpret != LYX_LAYOUT_DEFAULT)
748 params.paragraph_separation =
749 static_cast<BufferParams::PARSEP>(tmpret);
750 } else if (token == "\\defskip") {
752 params.defskip = VSpace(lex.getString());
753 #ifndef NO_COMPABILITY
754 } else if (token == "\\epsfig") { // obsolete
755 // Indeed it is obsolete, but we HAVE to be backwards
756 // compatible until 0.14, because otherwise all figures
757 // in existing documents are irretrivably lost. (Asger)
758 params.readGraphicsDriver(lex);
760 } else if (token == "\\quotes_language") {
761 int tmpret = lex.findToken(string_quotes_language);
764 if (tmpret != LYX_LAYOUT_DEFAULT) {
765 InsetQuotes::quote_language tmpl =
766 InsetQuotes::EnglishQ;
769 tmpl = InsetQuotes::EnglishQ;
772 tmpl = InsetQuotes::SwedishQ;
775 tmpl = InsetQuotes::GermanQ;
778 tmpl = InsetQuotes::PolishQ;
781 tmpl = InsetQuotes::FrenchQ;
784 tmpl = InsetQuotes::DanishQ;
787 params.quotes_language = tmpl;
789 } else if (token == "\\quotes_times") {
791 switch (lex.getInteger()) {
793 params.quotes_times = InsetQuotes::SingleQ;
796 params.quotes_times = InsetQuotes::DoubleQ;
799 } else if (token == "\\papersize") {
800 int tmpret = lex.findToken(string_papersize);
804 params.papersize2 = tmpret;
805 } else if (token == "\\paperpackage") {
806 int tmpret = lex.findToken(string_paperpackages);
809 params.paperpackage = BufferParams::PACKAGE_NONE;
811 params.paperpackage = tmpret;
812 } else if (token == "\\use_geometry") {
814 params.use_geometry = lex.getInteger();
815 } else if (token == "\\use_amsmath") {
817 params.use_amsmath = lex.getInteger();
818 } else if (token == "\\use_natbib") {
820 params.use_natbib = lex.getInteger();
821 } else if (token == "\\use_numerical_citations") {
823 params.use_numerical_citations = lex.getInteger();
824 } else if (token == "\\paperorientation") {
825 int tmpret = lex.findToken(string_orientation);
828 if (tmpret != LYX_LAYOUT_DEFAULT)
829 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
830 } else if (token == "\\paperwidth") {
832 params.paperwidth = lex.getString();
833 } else if (token == "\\paperheight") {
835 params.paperheight = lex.getString();
836 } else if (token == "\\leftmargin") {
838 params.leftmargin = lex.getString();
839 } else if (token == "\\topmargin") {
841 params.topmargin = lex.getString();
842 } else if (token == "\\rightmargin") {
844 params.rightmargin = lex.getString();
845 } else if (token == "\\bottommargin") {
847 params.bottommargin = lex.getString();
848 } else if (token == "\\headheight") {
850 params.headheight = lex.getString();
851 } else if (token == "\\headsep") {
853 params.headsep = lex.getString();
854 } else if (token == "\\footskip") {
856 params.footskip = lex.getString();
857 } else if (token == "\\paperfontsize") {
859 params.fontsize = strip(lex.getString());
860 } else if (token == "\\papercolumns") {
862 params.columns = lex.getInteger();
863 } else if (token == "\\papersides") {
865 switch (lex.getInteger()) {
867 case 1: params.sides = LyXTextClass::OneSide; break;
868 case 2: params.sides = LyXTextClass::TwoSides; break;
870 } else if (token == "\\paperpagestyle") {
872 params.pagestyle = strip(lex.getString());
873 } else if (token == "\\bullet") {
875 int const index = lex.getInteger();
877 int temp_int = lex.getInteger();
878 params.user_defined_bullets[index].setFont(temp_int);
879 params.temp_bullets[index].setFont(temp_int);
881 temp_int = lex.getInteger();
882 params.user_defined_bullets[index].setCharacter(temp_int);
883 params.temp_bullets[index].setCharacter(temp_int);
885 temp_int = lex.getInteger();
886 params.user_defined_bullets[index].setSize(temp_int);
887 params.temp_bullets[index].setSize(temp_int);
889 string const temp_str = lex.getString();
890 if (temp_str != "\\end_bullet") {
891 // this element isn't really necessary for
892 // parsing but is easier for humans
893 // to understand bullets. Put it back and
894 // set a debug message?
895 lex.printError("\\end_bullet expected, got" + temp_str);
896 //how can I put it back?
898 } else if (token == "\\bulletLaTeX") {
899 // The bullet class should be able to read this.
901 int const index = lex.getInteger();
903 string temp_str = lex.getString();
905 while (temp_str != "\\end_bullet") {
906 // this loop structure is needed when user
907 // enters an empty string since the first
908 // thing returned will be the \\end_bullet
910 // if the LaTeX entry has spaces. Each element
911 // therefore needs to be read in turn
914 temp_str = lex.getString();
917 params.user_defined_bullets[index].setText(sum_str);
918 params.temp_bullets[index].setText(sum_str);
919 } else if (token == "\\secnumdepth") {
921 params.secnumdepth = lex.getInteger();
922 } else if (token == "\\tocdepth") {
924 params.tocdepth = lex.getInteger();
925 } else if (token == "\\spacing") {
927 string const tmp = strip(lex.getString());
928 Spacing::Space tmp_space = Spacing::Default;
930 if (tmp == "single") {
931 tmp_space = Spacing::Single;
932 } else if (tmp == "onehalf") {
933 tmp_space = Spacing::Onehalf;
934 } else if (tmp == "double") {
935 tmp_space = Spacing::Double;
936 } else if (tmp == "other") {
938 tmp_space = Spacing::Other;
939 tmp_val = lex.getFloat();
941 lex.printError("Unknown spacing token: '$$Token'");
943 // Small hack so that files written with klyx will be
946 par->params().spacing(Spacing(tmp_space, tmp_val));
948 params.spacing.set(tmp_space, tmp_val);
950 } else if (token == "\\paragraph_spacing") {
952 string const tmp = strip(lex.getString());
953 if (tmp == "single") {
954 par->params().spacing(Spacing(Spacing::Single));
955 } else if (tmp == "onehalf") {
956 par->params().spacing(Spacing(Spacing::Onehalf));
957 } else if (tmp == "double") {
958 par->params().spacing(Spacing(Spacing::Double));
959 } else if (tmp == "other") {
961 par->params().spacing(Spacing(Spacing::Other,
964 lex.printError("Unknown spacing token: '$$Token'");
966 } else if (token == "\\float_placement") {
968 params.float_placement = lex.getString();
969 } else if (token == "\\family") {
971 font.setLyXFamily(lex.getString());
972 } else if (token == "\\series") {
974 font.setLyXSeries(lex.getString());
975 } else if (token == "\\shape") {
977 font.setLyXShape(lex.getString());
978 } else if (token == "\\size") {
980 font.setLyXSize(lex.getString());
981 #ifndef NO_COMPABILITY
982 } else if (token == "\\latex") {
984 string const tok = lex.getString();
985 if (tok == "no_latex") {
987 insertErtContents(par, pos);
988 } else if (tok == "latex") {
989 ert_comp.active = true;
990 ert_comp.font = font;
991 } else if (tok == "default") {
993 insertErtContents(par, pos);
995 lex.printError("Unknown LaTeX font flag "
999 } else if (token == "\\lang") {
1001 string const tok = lex.getString();
1002 Language const * lang = languages.getLanguage(tok);
1004 font.setLanguage(lang);
1006 font.setLanguage(params.language);
1007 lex.printError("Unknown language `$$Token'");
1009 } else if (token == "\\numeric") {
1011 font.setNumber(font.setLyXMisc(lex.getString()));
1012 } else if (token == "\\emph") {
1014 font.setEmph(font.setLyXMisc(lex.getString()));
1015 } else if (token == "\\bar") {
1017 string const tok = lex.getString();
1018 // This is dirty, but gone with LyX3. (Asger)
1020 font.setUnderbar(LyXFont::ON);
1021 else if (tok == "no")
1022 font.setUnderbar(LyXFont::OFF);
1023 else if (tok == "default")
1024 font.setUnderbar(LyXFont::INHERIT);
1026 lex.printError("Unknown bar font flag "
1028 } else if (token == "\\noun") {
1030 font.setNoun(font.setLyXMisc(lex.getString()));
1031 } else if (token == "\\color") {
1033 font.setLyXColor(lex.getString());
1034 } else if (token == "\\align") {
1035 int tmpret = lex.findToken(string_align);
1036 if (tmpret == -1) ++tmpret;
1037 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1038 int const tmpret2 = int(pow(2.0, tmpret));
1039 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1040 par->params().align(LyXAlignment(tmpret2));
1042 } else if (token == "\\added_space_top") {
1044 VSpace value = VSpace(lex.getString());
1045 if ((value.length().len().value() != 0) ||
1046 (value.kind() != VSpace::LENGTH))
1047 par->params().spaceTop(value);
1048 } else if (token == "\\added_space_bottom") {
1050 VSpace value = VSpace(lex.getString());
1051 if ((value.length().len().value() != 0) ||
1052 (value.kind() != VSpace::LENGTH))
1053 par->params().spaceBottom(value);
1054 #ifndef NO_COMPABILITY
1055 #ifndef NO_PEXTRA_REALLY
1056 } else if (token == "\\pextra_type") {
1058 par->params().pextraType(lex.getInteger());
1059 } else if (token == "\\pextra_width") {
1061 par->params().pextraWidth(lex.getString());
1062 } else if (token == "\\pextra_widthp") {
1064 par->params().pextraWidthp(lex.getString());
1065 } else if (token == "\\pextra_alignment") {
1067 par->params().pextraAlignment(lex.getInteger());
1068 } else if (token == "\\pextra_hfill") {
1070 par->params().pextraHfill(lex.getInteger());
1071 } else if (token == "\\pextra_start_minipage") {
1073 par->params().pextraStartMinipage(lex.getInteger());
1076 } else if (token == "\\labelwidthstring") {
1078 par->params().labelWidthString(lex.getString());
1079 // do not delete this token, it is still needed!
1080 } else if (token == "\\end_inset") {
1081 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1082 << "Last inset read was: " << last_inset_read
1084 // Simply ignore this. The insets do not have
1086 // But insets should read it, it is a part of
1087 // the inset isn't it? Lgb.
1088 } else if (token == "\\begin_inset") {
1089 #ifndef NO_COMPABILITY
1090 insertErtContents(par, pos, false);
1091 ert_stack.push(ert_comp);
1092 ert_comp = ErtComp();
1094 readInset(lex, par, pos, font);
1095 #ifndef NO_COMPABILITY
1096 ert_comp = ert_stack.top();
1098 insertErtContents(par, pos);
1100 } else if (token == "\\SpecialChar") {
1101 LyXLayout const & layout =
1102 textclasslist.Style(params.textclass,
1105 // Insets don't make sense in a free-spacing context! ---Kayvan
1106 if (layout.free_spacing || par->isFreeSpacing()) {
1109 string next_token = lex.getString();
1110 if (next_token == "\\-") {
1111 par->insertChar(pos, '-', font);
1112 } else if (next_token == "\\protected_separator"
1113 || next_token == "~") {
1114 par->insertChar(pos, ' ', font);
1116 lex.printError("Token `$$Token' "
1118 "paragraph layout!");
1123 Inset * inset = new InsetSpecialChar;
1124 inset->read(this, lex);
1125 par->insertInset(pos, inset, font);
1128 } else if (token == "\\newline") {
1129 #ifndef NO_COMPABILITY
1130 if (!ert_comp.in_tabular && ert_comp.active) {
1131 ert_comp.contents += char(Paragraph::META_NEWLINE);
1133 // Since we cannot know it this is only a regular
1134 // newline or a tabular cell delimter we have to
1135 // handle the ERT here.
1136 insertErtContents(par, pos, false);
1138 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1142 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1145 } else if (token == "\\LyXTable") {
1146 #ifndef NO_COMPABILITY
1147 ert_comp.in_tabular = true;
1149 Inset * inset = new InsetTabular(*this);
1150 inset->read(this, lex);
1151 par->insertInset(pos, inset, font);
1153 } else if (token == "\\hfill") {
1154 par->insertChar(pos, Paragraph::META_HFILL, font);
1156 } else if (token == "\\protected_separator") { // obsolete
1157 // This is a backward compability thingie. (Lgb)
1158 // Remove it later some time...introduced with fileformat
1160 LyXLayout const & layout =
1161 textclasslist.Style(params.textclass,
1164 if (layout.free_spacing || par->isFreeSpacing()) {
1165 par->insertChar(pos, ' ', font);
1167 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1168 par->insertInset(pos, inset, font);
1171 } else if (token == "\\bibitem") { // ale970302
1173 InsetCommandParams p("bibitem", "dummy");
1174 par->bibkey = new InsetBibKey(p);
1176 par->bibkey->read(this, lex);
1177 } else if (token == "\\backslash") {
1178 #ifndef NO_COMPABILITY
1179 if (ert_comp.active) {
1180 ert_comp.contents += "\\";
1183 par->insertChar(pos, '\\', font);
1185 #ifndef NO_COMPABILITY
1188 } else if (token == "\\the_end") {
1189 #ifndef NO_COMPABILITY
1190 // If we still have some ert active here we have to insert
1191 // it so we don't loose it. (Lgb)
1192 insertErtContents(par, pos);
1194 the_end_read = true;
1195 #ifndef NO_COMPABILITY
1196 #ifndef NO_PEXTRA_REALLY
1197 minipar = parBeforeMinipage = 0;
1201 #ifndef NO_COMPABILITY
1202 if (ert_comp.active) {
1203 ert_comp.contents += token;
1206 // This should be insurance for the future: (Asger)
1209 string const s = _("Unknown token: ") + token
1210 + " " + lex.text() + "\n";
1212 InsetError * new_inset = new InsetError(s);
1213 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
1216 #ifndef NO_COMPABILITY
1221 #ifndef NO_COMPABILITY
1222 #ifndef NO_PEXTRA_REALLY
1223 // I wonder if we could use this blanket fix for all the
1224 // checkminipage cases...
1225 // don't forget about ert paragraphs and compatibility read for'em
1226 if (par && (par->size() || !ert_comp.contents.empty())) {
1227 // It is possible that this will check to often,
1228 // but that should not be an correctness issue.
1229 // Only a speed issue.
1230 checkminipage = true;
1233 // now check if we have a minipage paragraph as at this
1234 // point we already read all the necessary data!
1235 // this cannot be done in layout because there we did
1236 // not read yet the paragraph PEXTRA-params (Jug)
1238 // BEGIN pextra_minipage compability
1239 // This should be removed in 1.3.x (Lgb)
1240 // I don't think we should remove this so fast (Jug)
1242 // This compability code is not perfect. In a couple
1243 // of rand cases it fails. When the minipage par is
1244 // the first par in the document, and when there are
1245 // none or only one regular paragraphs after the
1246 // minipage. Currently I am not investing any effort
1247 // in fixing those cases.
1249 //lyxerr << "Call depth: " << call_depth << endl;
1250 if (checkminipage && (call_depth == 1)) {
1251 checkminipage = false;
1252 if (minipar && (minipar != par) &&
1253 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1255 lyxerr << "minipages in a row" << endl;
1256 if (par->params().pextraStartMinipage()) {
1257 lyxerr << "start new minipage" << endl;
1258 // minipages in a row
1259 par->previous()->next(0);
1262 Paragraph * tmp = minipar;
1264 tmp->params().pextraType(0);
1265 tmp->params().pextraWidth(string());
1266 tmp->params().pextraWidthp(string());
1267 tmp->params().pextraAlignment(0);
1268 tmp->params().pextraHfill(false);
1269 tmp->params().pextraStartMinipage(false);
1272 // create a new paragraph to insert the
1273 // minipages in the following case
1274 if (par->params().pextraStartMinipage() &&
1275 !par->params().pextraHfill())
1277 Paragraph * p = new Paragraph;
1279 p->previous(parBeforeMinipage);
1280 parBeforeMinipage->next(p);
1282 p->params().depth(parBeforeMinipage->params().depth());
1283 parBeforeMinipage = p;
1285 InsetMinipage * mini = new InsetMinipage;
1286 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1287 mini->pageWidth(LyXLength(par->params().pextraWidth()));
1288 if (!par->params().pextraWidthp().empty()) {
1289 lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1290 mini->pageWidth(LyXLength((par->params().pextraWidthp())+"%"));
1292 Paragraph * op = mini->firstParagraph();
1293 mini->inset.paragraph(par);
1295 // and free the old ones!
1298 Paragraph * pp = op->next();
1302 // Insert the minipage last in the
1303 // previous paragraph.
1304 if (par->params().pextraHfill()) {
1305 parBeforeMinipage->insertChar
1306 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1308 parBeforeMinipage->insertInset
1309 (parBeforeMinipage->size(), mini);
1313 lyxerr << "new minipage par" << endl;
1314 //nothing to do just continue reading
1317 } else if (minipar && (minipar != par)) {
1318 lyxerr << "last minipage par read" << endl;
1319 // The last paragraph read was not part of a
1320 // minipage but the par linked list is...
1321 // So we need to remove the last par from the
1323 if (par->previous())
1324 par->previous()->next(0);
1325 par->previous(parBeforeMinipage);
1326 parBeforeMinipage->next(par);
1327 Paragraph * tmp = minipar;
1329 tmp->params().pextraType(0);
1330 tmp->params().pextraWidth(string());
1331 tmp->params().pextraWidthp(string());
1332 tmp->params().pextraAlignment(0);
1333 tmp->params().pextraHfill(false);
1334 tmp->params().pextraStartMinipage(false);
1337 depth = parBeforeMinipage->params().depth();
1338 // and set this depth on the par as it has not been set already
1339 par->params().depth(depth);
1340 minipar = parBeforeMinipage = 0;
1341 } else if (!minipar &&
1342 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1344 // par is the first paragraph in a minipage
1345 lyxerr << "begin minipage" << endl;
1346 // To minimize problems for
1347 // the users we will insert
1348 // the first minipage in
1349 // a sequence of minipages
1350 // in its own paragraph.
1351 Paragraph * p = new Paragraph;
1353 p->previous(par->previous());
1355 p->params().depth(depth);
1356 par->params().depth(0);
1358 if (par->previous())
1359 par->previous()->next(p);
1361 parBeforeMinipage = p;
1363 if (!first_par || (first_par == par))
1366 InsetMinipage * mini = new InsetMinipage;
1367 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1368 mini->pageWidth(LyXLength(minipar->params().pextraWidth()));
1369 if (!par->params().pextraWidthp().empty()) {
1370 lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1371 mini->pageWidth(LyXLength((par->params().pextraWidthp())+"%"));
1373 mini->inset.paragraph(minipar);
1375 // Insert the minipage last in the
1376 // previous paragraph.
1377 if (minipar->params().pextraHfill()) {
1378 parBeforeMinipage->insertChar
1379 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1381 parBeforeMinipage->insertInset
1382 (parBeforeMinipage->size(), mini);
1385 // End of pextra_minipage compability
1389 return the_end_read;
1392 // needed to insert the selection
1393 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
1394 LyXFont const & fn,string const & str) const
1396 LyXLayout const & layout = textclasslist.Style(params.textclass,
1400 (void)par->checkInsertChar(font);
1401 // insert the string, don't insert doublespace
1402 bool space_inserted = true;
1403 for(string::const_iterator cit = str.begin();
1404 cit != str.end(); ++cit) {
1406 if (par->size() || layout.keepempty) {
1407 par->breakParagraph(params, pos,
1408 layout.isEnvironment());
1411 space_inserted = true;
1415 // do not insert consecutive spaces if !free_spacing
1416 } else if ((*cit == ' ' || *cit == '\t') &&
1417 space_inserted && !layout.free_spacing &&
1418 !par->isFreeSpacing())
1421 } else if (*cit == '\t') {
1422 if (!layout.free_spacing && !par->isFreeSpacing()) {
1423 // tabs are like spaces here
1424 par->insertChar(pos, ' ', font);
1426 space_inserted = true;
1428 const pos_type nb = 8 - pos % 8;
1429 for (pos_type a = 0; a < nb ; ++a) {
1430 par->insertChar(pos, ' ', font);
1433 space_inserted = true;
1435 } else if (!IsPrintable(*cit)) {
1436 // Ignore unprintables
1439 // just insert the character
1440 par->insertChar(pos, *cit, font);
1442 space_inserted = (*cit == ' ');
1449 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1450 int & pos, LyXFont & font)
1452 // consistency check
1453 if (lex.getString() != "\\begin_inset") {
1454 lyxerr << "Buffer::readInset: Consistency check failed."
1461 string const tmptok = lex.getString();
1462 last_inset_read = tmptok;
1464 // test the different insets
1465 if (tmptok == "LatexCommand") {
1466 InsetCommandParams inscmd;
1469 string const cmdName = inscmd.getCmdName();
1471 // This strange command allows LyX to recognize "natbib" style
1472 // citations: citet, citep, Citet etc.
1473 if (compare_no_case(cmdName, "cite", 4) == 0) {
1474 inset = new InsetCitation(inscmd);
1475 } else if (cmdName == "bibitem") {
1476 lex.printError("Wrong place for bibitem");
1477 inset = new InsetBibKey(inscmd);
1478 } else if (cmdName == "BibTeX") {
1479 inset = new InsetBibtex(inscmd);
1480 } else if (cmdName == "index") {
1481 inset = new InsetIndex(inscmd);
1482 } else if (cmdName == "include") {
1483 inset = new InsetInclude(inscmd, *this);
1484 } else if (cmdName == "label") {
1485 inset = new InsetLabel(inscmd);
1486 } else if (cmdName == "url"
1487 || cmdName == "htmlurl") {
1488 inset = new InsetUrl(inscmd);
1489 } else if (cmdName == "ref"
1490 || cmdName == "pageref"
1491 || cmdName == "vref"
1492 || cmdName == "vpageref"
1493 || cmdName == "prettyref") {
1494 if (!inscmd.getOptions().empty()
1495 || !inscmd.getContents().empty()) {
1496 inset = new InsetRef(inscmd, *this);
1498 } else if (cmdName == "tableofcontents") {
1499 inset = new InsetTOC(inscmd);
1500 } else if (cmdName == "listofalgorithms") {
1501 inset = new InsetFloatList("algorithm");
1502 } else if (cmdName == "listoffigures") {
1503 inset = new InsetFloatList("figure");
1504 } else if (cmdName == "listoftables") {
1505 inset = new InsetFloatList("table");
1506 } else if (cmdName == "printindex") {
1507 inset = new InsetPrintIndex(inscmd);
1508 } else if (cmdName == "lyxparent") {
1509 inset = new InsetParent(inscmd, *this);
1512 bool alreadyread = false;
1513 if (tmptok == "Quotes") {
1514 inset = new InsetQuotes;
1515 } else if (tmptok == "External") {
1516 inset = new InsetExternal;
1517 } else if (tmptok == "FormulaMacro") {
1518 inset = new InsetFormulaMacro;
1519 } else if (tmptok == "Formula") {
1520 inset = new InsetFormula;
1521 } else if (tmptok == "Figure") { // Backward compatibility
1522 // inset = new InsetFig(100, 100, *this);
1523 inset = new InsetGraphics;
1524 } else if (tmptok == "Graphics") {
1525 inset = new InsetGraphics;
1526 } else if (tmptok == "Info") {// backwards compatibility
1527 inset = new InsetNote(this,
1528 lex.getLongString("\\end_inset"),
1531 } else if (tmptok == "Note") {
1532 inset = new InsetNote;
1533 } else if (tmptok == "Include") {
1534 InsetCommandParams p("Include");
1535 inset = new InsetInclude(p, *this);
1536 } else if (tmptok == "ERT") {
1537 inset = new InsetERT;
1538 } else if (tmptok == "Tabular") {
1539 inset = new InsetTabular(*this);
1540 } else if (tmptok == "Text") {
1541 inset = new InsetText;
1542 } else if (tmptok == "Foot") {
1543 inset = new InsetFoot;
1544 } else if (tmptok == "Marginal") {
1545 inset = new InsetMarginal;
1546 } else if (tmptok == "Minipage") {
1547 inset = new InsetMinipage;
1548 } else if (tmptok == "Float") {
1550 string tmptok = lex.getString();
1551 inset = new InsetFloat(tmptok);
1553 } else if (tmptok == "List") {
1554 inset = new InsetList;
1555 } else if (tmptok == "Theorem") {
1556 inset = new InsetList;
1558 } else if (tmptok == "Caption") {
1559 inset = new InsetCaption;
1560 } else if (tmptok == "FloatList") {
1561 inset = new InsetFloatList;
1564 if (inset && !alreadyread) inset->read(this, lex);
1568 par->insertInset(pos, inset, font);
1574 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1578 string const token(lex.getString());
1579 if (token == "\\lyxformat") { // the first token _must_ be...
1581 string tmp_format = lex.getString();
1582 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1583 // if present remove ".," from string.
1584 string::size_type dot = tmp_format.find_first_of(".,");
1585 //lyxerr << " dot found at " << dot << endl;
1586 if (dot != string::npos)
1587 tmp_format.erase(dot, 1);
1588 file_format = strToInt(tmp_format);
1589 if (file_format == LYX_FORMAT) {
1591 } else if (file_format > LYX_FORMAT) {
1593 Alert::alert(_("Warning!"),
1594 _("LyX file format is newer that what"),
1595 _("is supported in this LyX version. Expect some problems."));
1597 } else if (file_format < LYX_FORMAT) {
1599 if (file_format < 200) {
1600 Alert::alert(_("ERROR!"),
1601 _("Old LyX file format found. "
1602 "Use LyX 0.10.x to read this!"));
1606 bool the_end = readLyXformat2(lex, par);
1607 params.setPaperStuff();
1608 // the_end was added in 213
1609 if (file_format < 213)
1613 Alert::alert(_("Warning!"),
1614 _("Reading of document is not complete"),
1615 _("Maybe the document is truncated"));
1618 } else { // "\\lyxformat" not found
1619 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1622 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1627 // Should probably be moved to somewhere else: BufferView? LyXView?
1628 bool Buffer::save() const
1630 // We don't need autosaves in the immediate future. (Asger)
1631 resetAutosaveTimers();
1635 if (lyxrc.make_backup) {
1636 s = fileName() + '~';
1637 if (!lyxrc.backupdir_path.empty())
1638 s = AddName(lyxrc.backupdir_path,
1639 subst(os::slashify_path(s),'/','!'));
1641 // Rename is the wrong way of making a backup,
1642 // this is the correct way.
1643 /* truss cp fil fil2:
1644 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1645 stat("LyXVC.lyx", 0xEFFFF688) = 0
1646 open("LyXVC.lyx", O_RDONLY) = 3
1647 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1648 fstat(4, 0xEFFFF508) = 0
1649 fstat(3, 0xEFFFF508) = 0
1650 read(3, " # T h i s f i l e w".., 8192) = 5579
1651 write(4, " # T h i s f i l e w".., 5579) = 5579
1652 read(3, 0xEFFFD4A0, 8192) = 0
1655 chmod("LyXVC3.lyx", 0100644) = 0
1656 lseek(0, 0, SEEK_CUR) = 46440
1660 // Should probably have some more error checking here.
1661 // Should be cleaned up in 0.13, at least a bit.
1662 // Doing it this way, also makes the inodes stay the same.
1663 // This is still not a very good solution, in particular we
1664 // might loose the owner of the backup.
1665 FileInfo finfo(fileName());
1666 if (finfo.exist()) {
1667 mode_t fmode = finfo.getMode();
1668 struct utimbuf times = {
1669 finfo.getAccessTime(),
1670 finfo.getModificationTime() };
1672 ifstream ifs(fileName().c_str());
1673 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1678 ::chmod(s.c_str(), fmode);
1680 if (::utime(s.c_str(), ×)) {
1681 lyxerr << "utime error." << endl;
1684 lyxerr << "LyX was not able to make "
1685 "backup copy. Beware." << endl;
1690 if (writeFile(fileName(), false)) {
1692 removeAutosaveFile(fileName());
1694 // Saving failed, so backup is not backup
1695 if (lyxrc.make_backup) {
1696 lyx::rename(s, fileName());
1704 // Returns false if unsuccesful
1705 bool Buffer::writeFile(string const & fname, bool flag) const
1707 // if flag is false writeFile will not create any GUI
1708 // warnings, only cerr.
1709 // Needed for autosave in background or panic save (Matthias 120496)
1711 if (read_only && (fname == fileName())) {
1712 // Here we should come with a question if we should
1713 // perform the write anyway.
1715 lyxerr << _("Error! Document is read-only: ")
1718 Alert::alert(_("Error! Document is read-only: "),
1723 FileInfo finfo(fname);
1724 if (finfo.exist() && !finfo.writable()) {
1725 // Here we should come with a question if we should
1726 // try to do the save anyway. (i.e. do a chmod first)
1728 lyxerr << _("Error! Cannot write file: ")
1731 Alert::err_alert(_("Error! Cannot write file: "),
1736 ofstream ofs(fname.c_str());
1739 lyxerr << _("Error! Cannot open file: ")
1742 Alert::err_alert(_("Error! Cannot open file: "),
1748 // Use the standard "C" locale for file output.
1749 ofs.imbue(std::locale::classic());
1752 // The top of the file should not be written by params.
1754 // write out a comment in the top of the file
1755 ofs << '#' << lyx_docversion
1756 << " created this file. For more info see http://www.lyx.org/\n"
1757 << "\\lyxformat " << LYX_FORMAT << "\n";
1759 // now write out the buffer paramters.
1760 params.writeFile(ofs);
1762 Paragraph::depth_type depth = 0;
1764 // this will write out all the paragraphs
1765 // using recursive descent.
1766 paragraph->writeFile(this, ofs, params, depth);
1768 // Write marker that shows file is complete
1769 ofs << "\n\\the_end" << endl;
1773 // how to check if close went ok?
1774 // Following is an attempt... (BE 20001011)
1776 // good() returns false if any error occured, including some
1777 // formatting error.
1778 // bad() returns true if something bad happened in the buffer,
1779 // which should include file system full errors.
1786 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1788 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1798 string const Buffer::asciiParagraph(Paragraph const * par,
1799 unsigned int linelen,
1800 bool noparbreak) const
1802 ostringstream buffer;
1804 Paragraph::depth_type depth = 0;
1806 Paragraph::depth_type ltype_depth = 0;
1807 string::size_type currlinelen = 0;
1808 bool ref_printed = false;
1809 // if (!par->previous()) {
1811 // begins or ends a deeper area ?
1812 if (depth != par->params().depth()) {
1813 if (par->params().depth() > depth) {
1814 while (par->params().depth() > depth) {
1818 while (par->params().depth() < depth) {
1824 depth = par->params().depth();
1827 // First write the layout
1828 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1829 if (tmp == "Itemize") {
1831 ltype_depth = depth + 1;
1832 } else if (tmp == "Enumerate") {
1834 ltype_depth = depth + 1;
1835 } else if (contains(tmp, "ection")) {
1837 ltype_depth = depth + 1;
1838 } else if (contains(tmp, "aragraph")) {
1840 ltype_depth = depth + 1;
1841 } else if (tmp == "Description") {
1843 ltype_depth = depth + 1;
1844 } else if (tmp == "Abstract") {
1847 } else if (tmp == "Bibliography") {
1855 /* maybe some vertical spaces */
1857 /* the labelwidthstring used in lists */
1861 /* some pagebreaks? */
1865 /* what about the alignment */
1867 // lyxerr << "Should this ever happen?" << endl;
1870 // linelen <= 0 is special and means we don't have pargraph breaks
1874 for (Paragraph::depth_type j = 0; j < depth; ++j)
1876 currlinelen = depth * 2;
1878 // we should probably change to the paragraph language in the
1879 // gettext here (if possible) so that strings are outputted in
1880 // the correct language! (20012712 Jug)
1884 case 4: // (Sub)Paragraph
1885 case 5: // Description
1889 buffer << _("Abstract") << "\n\n";
1891 buffer << _("Abstract: ");
1893 case 7: // Bibliography
1896 buffer << _("References") << "\n\n";
1898 buffer << _("References: ");
1903 buffer << par->params().labelString() << " ";
1907 string s = buffer.str();
1908 if (s.rfind('\n') != string::npos) {
1910 s = rsplit(buffer.str().c_str(), dummy, '\n');
1912 currlinelen = s.length();
1914 for (Paragraph::depth_type j = 0; j < depth; ++j)
1916 currlinelen = depth * 2;
1917 if (ltype_depth > depth) {
1918 for (Paragraph::depth_type j = ltype_depth;
1923 currlinelen += (ltype_depth-depth)*2;
1926 // this is to change the linebreak to do it by word a bit more intelligent
1927 // hopefully! (only in the case where we have a max linelenght!) (Jug)
1928 for (pos_type i = 0; i < par->size(); ++i) {
1929 char c = par->getUChar(params, i);
1931 case Paragraph::META_INSET:
1933 Inset const * inset = par->getInset(i);
1936 buffer << word.str();
1939 if (inset->ascii(this, buffer, linelen)) {
1940 // to be sure it breaks paragraph
1941 currlinelen += linelen;
1947 rsplit(buffer.str().c_str(),
1949 currlinelen = s.length();
1956 case Paragraph::META_NEWLINE:
1958 buffer << word.str() << "\n";
1960 for (Paragraph::depth_type j = 0;
1963 currlinelen = depth * 2;
1964 if (ltype_depth > depth) {
1965 for (Paragraph::depth_type j = ltype_depth;
1968 currlinelen += (ltype_depth - depth) * 2;
1973 case Paragraph::META_HFILL:
1974 buffer << word.str() << "\t";
1975 currlinelen += word.str().length() + 1;
1981 buffer << word.str() << ' ';
1982 currlinelen += word.str().length() + 1;
1988 lyxerr[Debug::INFO] <<
1989 "writeAsciiFile: NULL char in structure." << endl;
1991 if ((linelen > 0) &&
1992 (currlinelen+word.str().length()) > linelen)
1995 for (Paragraph::depth_type j = 0; j < depth; ++j)
1997 currlinelen = depth * 2;
1998 if (ltype_depth > depth) {
1999 for (Paragraph::depth_type j = ltype_depth;
2004 currlinelen += (ltype_depth-depth)*2;
2011 buffer << word.str();
2012 return buffer.str().c_str();
2016 void Buffer::writeFileAscii(string const & fname, int linelen)
2018 ofstream ofs(fname.c_str());
2020 Alert::err_alert(_("Error: Cannot write file:"), fname);
2023 writeFileAscii(ofs, linelen);
2027 void Buffer::writeFileAscii(ostream & ofs, int linelen)
2029 Paragraph * par = paragraph;
2031 ofs << asciiParagraph(par, linelen, par->previous() == 0);
2041 void Buffer::makeLaTeXFile(string const & fname,
2042 string const & original_path,
2043 bool nice, bool only_body)
2045 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
2047 niceFile = nice; // this will be used by Insetincludes.
2049 tex_code_break_column = lyxrc.ascii_linelen;
2051 LyXTextClass const & tclass =
2052 textclasslist.TextClass(params.textclass);
2054 ofstream ofs(fname.c_str());
2056 Alert::err_alert(_("Error: Cannot open file: "), fname);
2060 // validate the buffer.
2061 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
2062 LaTeXFeatures features(params, tclass.numLayouts());
2064 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
2067 // The starting paragraph of the coming rows is the
2068 // first paragraph of the document. (Asger)
2069 texrow.start(paragraph, 0);
2071 if (!only_body && nice) {
2072 ofs << "%% " << lyx_docversion << " created this file. "
2073 "For more info, see http://www.lyx.org/.\n"
2074 "%% Do not edit unless you really know what "
2079 lyxerr[Debug::INFO] << "lyx header finished" << endl;
2080 // There are a few differences between nice LaTeX and usual files:
2081 // usual is \batchmode and has a
2082 // special input@path to allow the including of figures
2083 // with either \input or \includegraphics (what figinsets do).
2084 // batchmode is not set if there is a tex_code_break_column.
2085 // In this case somebody is interested in the generated LaTeX,
2086 // so this is OK. input@path is set when the actual parameter
2087 // original_path is set. This is done for usual tex-file, but not
2088 // for nice-latex-file. (Matthias 250696)
2091 // code for usual, NOT nice-latex-file
2092 ofs << "\\batchmode\n"; // changed
2093 // from \nonstopmode
2096 if (!original_path.empty()) {
2097 ofs << "\\makeatletter\n"
2098 << "\\def\\input@path{{"
2099 << os::external_path(original_path) << "/}}\n"
2100 << "\\makeatother\n";
2106 ofs << "\\documentclass";
2108 ostringstream options; // the document class options.
2110 if (tokenPos(tclass.opt_fontsize(),
2111 '|', params.fontsize) >= 0) {
2112 // only write if existing in list (and not default)
2113 options << params.fontsize << "pt,";
2117 if (!params.use_geometry &&
2118 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2119 switch (params.papersize) {
2120 case BufferParams::PAPER_A4PAPER:
2121 options << "a4paper,";
2123 case BufferParams::PAPER_USLETTER:
2124 options << "letterpaper,";
2126 case BufferParams::PAPER_A5PAPER:
2127 options << "a5paper,";
2129 case BufferParams::PAPER_B5PAPER:
2130 options << "b5paper,";
2132 case BufferParams::PAPER_EXECUTIVEPAPER:
2133 options << "executivepaper,";
2135 case BufferParams::PAPER_LEGALPAPER:
2136 options << "legalpaper,";
2142 if (params.sides != tclass.sides()) {
2143 switch (params.sides) {
2144 case LyXTextClass::OneSide:
2145 options << "oneside,";
2147 case LyXTextClass::TwoSides:
2148 options << "twoside,";
2154 if (params.columns != tclass.columns()) {
2155 if (params.columns == 2)
2156 options << "twocolumn,";
2158 options << "onecolumn,";
2161 if (!params.use_geometry
2162 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2163 options << "landscape,";
2165 // language should be a parameter to \documentclass
2167 ostringstream language_options;
2168 if (params.language->babel() == "hebrew"
2169 && default_language->babel() != "hebrew")
2170 // This seems necessary
2171 features.useLanguage(default_language);
2173 if (lyxrc.language_use_babel ||
2174 params.language->lang() != lyxrc.default_language ||
2175 !features.hasLanguages()) {
2177 language_options << features.getLanguages();
2178 language_options << params.language->babel();
2179 if (lyxrc.language_global_options)
2180 options << language_options.str() << ',';
2183 // the user-defined options
2184 if (!params.options.empty()) {
2185 options << params.options << ',';
2188 string strOptions(options.str().c_str());
2189 if (!strOptions.empty()) {
2190 strOptions = strip(strOptions, ',');
2191 ofs << '[' << strOptions << ']';
2195 << textclasslist.LatexnameOfClass(params.textclass)
2198 // end of \documentclass defs
2200 // font selection must be done before loading fontenc.sty
2201 // The ae package is not needed when using OT1 font encoding.
2202 if (params.fonts != "default" &&
2203 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2204 ofs << "\\usepackage{" << params.fonts << "}\n";
2206 if (params.fonts == "ae") {
2207 ofs << "\\usepackage{aecompl}\n";
2211 // this one is not per buffer
2212 if (lyxrc.fontenc != "default") {
2213 ofs << "\\usepackage[" << lyxrc.fontenc
2218 if (params.inputenc == "auto") {
2219 string const doc_encoding =
2220 params.language->encoding()->LatexName();
2222 // Create a list with all the input encodings used
2224 set<string> encodings = features.getEncodingSet(doc_encoding);
2226 ofs << "\\usepackage[";
2227 std::copy(encodings.begin(), encodings.end(),
2228 std::ostream_iterator<string>(ofs, ","));
2229 ofs << doc_encoding << "]{inputenc}\n";
2231 } else if (params.inputenc != "default") {
2232 ofs << "\\usepackage[" << params.inputenc
2237 // At the very beginning the text parameters.
2238 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2239 switch (params.paperpackage) {
2240 case BufferParams::PACKAGE_A4:
2241 ofs << "\\usepackage{a4}\n";
2244 case BufferParams::PACKAGE_A4WIDE:
2245 ofs << "\\usepackage{a4wide}\n";
2248 case BufferParams::PACKAGE_WIDEMARGINSA4:
2249 ofs << "\\usepackage[widemargins]{a4}\n";
2254 if (params.use_geometry) {
2255 ofs << "\\usepackage{geometry}\n";
2257 ofs << "\\geometry{verbose";
2258 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2259 ofs << ",landscape";
2260 switch (params.papersize2) {
2261 case BufferParams::VM_PAPER_CUSTOM:
2262 if (!params.paperwidth.empty())
2263 ofs << ",paperwidth="
2264 << params.paperwidth;
2265 if (!params.paperheight.empty())
2266 ofs << ",paperheight="
2267 << params.paperheight;
2269 case BufferParams::VM_PAPER_USLETTER:
2270 ofs << ",letterpaper";
2272 case BufferParams::VM_PAPER_USLEGAL:
2273 ofs << ",legalpaper";
2275 case BufferParams::VM_PAPER_USEXECUTIVE:
2276 ofs << ",executivepaper";
2278 case BufferParams::VM_PAPER_A3:
2281 case BufferParams::VM_PAPER_A4:
2284 case BufferParams::VM_PAPER_A5:
2287 case BufferParams::VM_PAPER_B3:
2290 case BufferParams::VM_PAPER_B4:
2293 case BufferParams::VM_PAPER_B5:
2297 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2298 switch (lyxrc.default_papersize) {
2299 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2300 case BufferParams::PAPER_USLETTER:
2301 ofs << ",letterpaper";
2303 case BufferParams::PAPER_LEGALPAPER:
2304 ofs << ",legalpaper";
2306 case BufferParams::PAPER_EXECUTIVEPAPER:
2307 ofs << ",executivepaper";
2309 case BufferParams::PAPER_A3PAPER:
2312 case BufferParams::PAPER_A4PAPER:
2315 case BufferParams::PAPER_A5PAPER:
2318 case BufferParams::PAPER_B5PAPER:
2323 if (!params.topmargin.empty())
2324 ofs << ",tmargin=" << params.topmargin;
2325 if (!params.bottommargin.empty())
2326 ofs << ",bmargin=" << params.bottommargin;
2327 if (!params.leftmargin.empty())
2328 ofs << ",lmargin=" << params.leftmargin;
2329 if (!params.rightmargin.empty())
2330 ofs << ",rmargin=" << params.rightmargin;
2331 if (!params.headheight.empty())
2332 ofs << ",headheight=" << params.headheight;
2333 if (!params.headsep.empty())
2334 ofs << ",headsep=" << params.headsep;
2335 if (!params.footskip.empty())
2336 ofs << ",footskip=" << params.footskip;
2341 if (tokenPos(tclass.opt_pagestyle(),
2342 '|', params.pagestyle) >= 0) {
2343 if (params.pagestyle == "fancy") {
2344 ofs << "\\usepackage{fancyhdr}\n";
2347 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2351 if (params.secnumdepth != tclass.secnumdepth()) {
2352 ofs << "\\setcounter{secnumdepth}{"
2353 << params.secnumdepth
2357 if (params.tocdepth != tclass.tocdepth()) {
2358 ofs << "\\setcounter{tocdepth}{"
2364 if (params.paragraph_separation) {
2365 switch (params.defskip.kind()) {
2366 case VSpace::SMALLSKIP:
2367 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2369 case VSpace::MEDSKIP:
2370 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2372 case VSpace::BIGSKIP:
2373 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2375 case VSpace::LENGTH:
2376 ofs << "\\setlength\\parskip{"
2377 << params.defskip.length().asLatexString()
2380 default: // should never happen // Then delete it.
2381 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2386 ofs << "\\setlength\\parindent{0pt}\n";
2390 // Now insert the LyX specific LaTeX commands...
2392 // The optional packages;
2393 string preamble(features.getPackages());
2395 // this might be useful...
2396 preamble += "\n\\makeatletter\n";
2398 // Some macros LyX will need
2399 string tmppreamble(features.getMacros());
2401 if (!tmppreamble.empty()) {
2402 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2403 "LyX specific LaTeX commands.\n"
2404 + tmppreamble + '\n';
2407 // the text class specific preamble
2408 tmppreamble = features.getTClassPreamble();
2409 if (!tmppreamble.empty()) {
2410 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2411 "Textclass specific LaTeX commands.\n"
2412 + tmppreamble + '\n';
2415 /* the user-defined preamble */
2416 if (!params.preamble.empty()) {
2417 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2418 "User specified LaTeX commands.\n"
2419 + params.preamble + '\n';
2422 preamble += "\\makeatother\n";
2424 // Itemize bullet settings need to be last in case the user
2425 // defines their own bullets that use a package included
2426 // in the user-defined preamble -- ARRae
2427 // Actually it has to be done much later than that
2428 // since some packages like frenchb make modifications
2429 // at \begin{document} time -- JMarc
2431 for (int i = 0; i < 4; ++i) {
2432 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2433 if (bullets_def.empty())
2434 bullets_def="\\AtBeginDocument{\n";
2435 bullets_def += " \\renewcommand{\\labelitemi";
2437 // `i' is one less than the item to modify
2444 bullets_def += "ii";
2450 bullets_def += "}{" +
2451 params.user_defined_bullets[i].getText()
2456 if (!bullets_def.empty())
2457 preamble += bullets_def + "}\n\n";
2460 int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2461 for (int j = 0; j != nlines; ++j) {
2467 // We try to load babel late, in case it interferes
2468 // with other packages.
2470 string tmp = lyxrc.language_package;
2471 if (!lyxrc.language_global_options
2472 && tmp == "\\usepackage{babel}")
2473 tmp = string("\\usepackage[") +
2474 language_options.str().c_str() +
2481 ofs << "\\begin{document}\n";
2484 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2486 if (!lyxrc.language_auto_begin) {
2487 ofs << subst(lyxrc.language_command_begin, "$$lang",
2488 params.language->babel())
2493 latexParagraphs(ofs, paragraph, 0, texrow);
2495 // add this just in case after all the paragraphs
2499 if (!lyxrc.language_auto_end) {
2500 ofs << subst(lyxrc.language_command_end, "$$lang",
2501 params.language->babel())
2507 ofs << "\\end{document}\n";
2510 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2512 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2516 // Just to be sure. (Asger)
2519 // tex_code_break_column's value is used to decide
2520 // if we are in batchmode or not (within mathed_write()
2521 // in math_write.C) so we must set it to a non-zero
2522 // value when we leave otherwise we save incorrect .lyx files.
2523 tex_code_break_column = lyxrc.ascii_linelen;
2527 lyxerr << "File was not closed properly." << endl;
2530 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2531 lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2536 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2538 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2539 Paragraph * endpar, TexRow & texrow) const
2541 bool was_title = false;
2542 bool already_title = false;
2545 while (par != endpar) {
2546 Inset * in = par->inInset();
2547 // well we have to check if we are in an inset with unlimited
2548 // lenght (all in one row) if that is true then we don't allow
2549 // any special options in the paragraph and also we don't allow
2550 // any environment other then "Standard" to be valid!
2551 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2552 LyXLayout const & layout =
2553 textclasslist.Style(params.textclass, par->layout);
2555 if (layout.intitle) {
2556 if (already_title) {
2557 lyxerr <<"Error in latexParagraphs: You"
2558 " should not mix title layouts"
2559 " with normal ones." << endl;
2562 } else if (was_title && !already_title) {
2563 ofs << "\\maketitle\n";
2565 already_title = true;
2569 if (layout.isEnvironment()) {
2570 par = par->TeXEnvironment(this, params, ofs, texrow);
2572 par = par->TeXOnePar(this, params, ofs, texrow, false);
2575 par = par->TeXOnePar(this, params, ofs, texrow, false);
2578 // It might be that we only have a title in this document
2579 if (was_title && !already_title) {
2580 ofs << "\\maketitle\n";
2586 bool Buffer::isLatex() const
2588 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2592 bool Buffer::isLinuxDoc() const
2594 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2598 bool Buffer::isLiterate() const
2600 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2604 bool Buffer::isDocBook() const
2606 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2610 bool Buffer::isSGML() const
2612 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2613 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2617 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2618 string const & latexname) const
2620 if (!latexname.empty() && latexname != "!-- --")
2621 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2622 os << string(depth, ' ') << "<" << latexname << ">\n";
2626 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2627 string const & latexname) const
2629 if (!latexname.empty() && latexname != "!-- --")
2630 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2631 os << string(depth, ' ') << "</" << latexname << ">\n";
2635 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2637 ofstream ofs(fname.c_str());
2640 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2644 niceFile = nice; // this will be used by included files.
2646 LyXTextClass const & tclass =
2647 textclasslist.TextClass(params.textclass);
2649 LaTeXFeatures features(params, tclass.numLayouts());
2654 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2657 ofs << "<!doctype linuxdoc system";
2659 string preamble = params.preamble;
2660 preamble += features.getIncludedFiles(fname);
2661 preamble += features.getLyXSGMLEntities();
2663 if (!preamble.empty()) {
2664 ofs << " [ " << preamble << " ]";
2668 if (params.options.empty())
2669 sgmlOpenTag(ofs, 0, top_element);
2671 string top = top_element;
2673 top += params.options;
2674 sgmlOpenTag(ofs, 0, top);
2678 ofs << "<!-- " << lyx_docversion
2679 << " created this file. For more info see http://www.lyx.org/"
2682 Paragraph::depth_type depth = 0; // paragraph depth
2683 Paragraph * par = paragraph;
2685 vector<string> environment_stack(5);
2688 LyXLayout const & style =
2689 textclasslist.Style(params.textclass,
2692 // treat <toc> as a special case for compatibility with old code
2693 if (par->isInset(0)) {
2694 Inset * inset = par->getInset(0);
2695 Inset::Code lyx_code = inset->lyxCode();
2696 if (lyx_code == Inset::TOC_CODE) {
2697 string const temp = "toc";
2698 sgmlOpenTag(ofs, depth, temp);
2705 // environment tag closing
2706 for (; depth > par->params().depth(); --depth) {
2707 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2708 environment_stack[depth].erase();
2711 // write opening SGML tags
2712 switch (style.latextype) {
2713 case LATEX_PARAGRAPH:
2714 if (depth == par->params().depth()
2715 && !environment_stack[depth].empty()) {
2716 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2717 environment_stack[depth].erase();
2723 sgmlOpenTag(ofs, depth, style.latexname());
2729 _("Error : Wrong depth for"
2730 " LatexType Command.\n"));
2732 if (!environment_stack[depth].empty()) {
2733 sgmlCloseTag(ofs, depth,
2734 environment_stack[depth]);
2738 environment_stack[depth].erase();
2739 sgmlOpenTag(ofs, depth, style.latexname());
2742 case LATEX_ENVIRONMENT:
2743 case LATEX_ITEM_ENVIRONMENT:
2744 if (depth == par->params().depth()
2745 && environment_stack[depth] != style.latexname()) {
2746 sgmlCloseTag(ofs, depth,
2747 environment_stack[depth]);
2748 environment_stack[depth].erase();
2750 if (depth < par->params().depth()) {
2751 depth = par->params().depth();
2752 environment_stack[depth].erase();
2754 if (environment_stack[depth] != style.latexname()) {
2756 sgmlOpenTag(ofs, depth, "p");
2758 sgmlOpenTag(ofs, depth, style.latexname());
2760 if (environment_stack.size() == depth + 1)
2761 environment_stack.push_back("!-- --");
2762 environment_stack[depth] = style.latexname();
2765 if (style.latexparam() == "CDATA")
2768 if (style.latextype == LATEX_ENVIRONMENT) break;
2770 if (style.labeltype == LABEL_MANUAL)
2775 sgmlOpenTag(ofs, depth + 1, item_name);
2778 sgmlOpenTag(ofs, depth, style.latexname());
2782 simpleLinuxDocOnePar(ofs, par, depth);
2787 // write closing SGML tags
2788 switch (style.latextype) {
2791 case LATEX_ENVIRONMENT:
2792 case LATEX_ITEM_ENVIRONMENT:
2793 if (style.latexparam() == "CDATA")
2797 sgmlCloseTag(ofs, depth, style.latexname());
2803 for (int i=depth; i >= 0; --i)
2804 sgmlCloseTag(ofs, depth, environment_stack[i]);
2808 sgmlCloseTag(ofs, 0, top_element);
2812 // How to check for successful close
2816 // checks, if newcol chars should be put into this line
2817 // writes newline, if necessary.
2820 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2821 string::size_type newcol)
2824 if (colcount > lyxrc.ascii_linelen) {
2826 colcount = newcol; // assume write after this call
2841 string tag_name(PAR_TAG const & pt) {
2843 case NONE: return "!-- --";
2844 case TT: return "tt";
2845 case SF: return "sf";
2846 case BF: return "bf";
2847 case IT: return "it";
2848 case SL: return "sl";
2849 case EM: return "em";
2856 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2858 p1 = static_cast<PAR_TAG>(p1 | p2);
2863 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2865 p1 = static_cast<PAR_TAG>(p1 & ~p2);
2871 // Handle internal paragraph parsing -- layout already processed.
2872 void Buffer::simpleLinuxDocOnePar(ostream & os,
2874 Paragraph::depth_type /*depth*/)
2876 LyXLayout const & style = textclasslist.Style(params.textclass,
2878 string::size_type char_line_count = 5; // Heuristic choice ;-)
2880 // gets paragraph main font
2883 if (style.labeltype == LABEL_MANUAL) {
2884 font_old = style.labelfont;
2887 font_old = style.font;
2891 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2892 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2893 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2896 stack<PAR_TAG> tag_state;
2897 // parsing main loop
2898 for (pos_type i = 0; i < par->size(); ++i) {
2900 PAR_TAG tag_close = NONE;
2901 list < PAR_TAG > tag_open;
2903 LyXFont const font = par->getFont(params, i);
2905 if (font_old.family() != font.family()) {
2906 switch (family_type) {
2907 case LyXFont::SANS_FAMILY:
2910 case LyXFont::TYPEWRITER_FAMILY:
2917 family_type = font.family();
2919 switch (family_type) {
2920 case LyXFont::SANS_FAMILY:
2921 tag_open.push_back(SF);
2923 case LyXFont::TYPEWRITER_FAMILY:
2924 tag_open.push_back(TT);
2931 if (font_old.series() != font.series()) {
2932 switch (series_type) {
2933 case LyXFont::BOLD_SERIES:
2940 series_type = font.series();
2942 switch (series_type) {
2943 case LyXFont::BOLD_SERIES:
2944 tag_open.push_back(BF);
2952 if (font_old.shape() != font.shape()) {
2953 switch (shape_type) {
2954 case LyXFont::ITALIC_SHAPE:
2957 case LyXFont::SLANTED_SHAPE:
2964 shape_type = font.shape();
2966 switch (shape_type) {
2967 case LyXFont::ITALIC_SHAPE:
2968 tag_open.push_back(IT);
2970 case LyXFont::SLANTED_SHAPE:
2971 tag_open.push_back(SL);
2978 if (font_old.emph() != font.emph()) {
2979 if (font.emph() == LyXFont::ON) {
2980 tag_open.push_back(EM);
2989 list < PAR_TAG > temp;
2990 while (!tag_state.empty() && tag_close) {
2991 PAR_TAG k = tag_state.top();
2993 os << "</" << tag_name(k) << ">";
3000 for(list< PAR_TAG >::const_iterator j = temp.begin();
3001 j != temp.end(); ++j) {
3003 os << "<" << tag_name(*j) << ">";
3006 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
3007 j != tag_open.end(); ++j) {
3009 os << "<" << tag_name(*j) << ">";
3012 char c = par->getChar(i);
3014 if (c == Paragraph::META_INSET) {
3015 Inset * inset = par->getInset(i);
3016 inset->linuxdoc(this, os);
3021 if (style.latexparam() == "CDATA") {
3022 // "TeX"-Mode on == > SGML-Mode on.
3028 if (par->sgmlConvertChar(c, sgml_string)
3029 && !style.free_spacing && !par->isFreeSpacing())
3031 // in freespacing mode, spaces are
3032 // non-breaking characters
3033 if (desc_on) {// if char is ' ' then...
3036 sgmlLineBreak(os, char_line_count, 6);
3040 sgmlLineBreak(os, char_line_count, 1);
3045 char_line_count += sgml_string.length();
3051 while (!tag_state.empty()) {
3052 os << "</" << tag_name(tag_state.top()) << ">";
3056 // resets description flag correctly
3058 // <tag> not closed...
3059 sgmlLineBreak(os, char_line_count, 6);
3065 // Print an error message.
3066 void Buffer::sgmlError(Paragraph * par, int pos,
3067 string const & message) const
3069 // insert an error marker in text
3070 InsetError * new_inset = new InsetError(message);
3071 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
3076 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3078 ofstream ofs(fname.c_str());
3080 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3084 Paragraph * par = paragraph;
3086 niceFile = nice; // this will be used by Insetincludes.
3088 LyXTextClass const & tclass =
3089 textclasslist.TextClass(params.textclass);
3091 LaTeXFeatures features(params, tclass.numLayouts());
3096 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3099 ofs << "<!DOCTYPE " << top_element
3100 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3102 string preamble = params.preamble;
3103 preamble += features.getIncludedFiles(fname);
3104 preamble += features.getLyXSGMLEntities();
3106 if (!preamble.empty()) {
3107 ofs << "\n [ " << preamble << " ]";
3112 string top = top_element;
3114 top += params.language->code();
3117 if (!params.options.empty()) {
3119 top += params.options;
3121 sgmlOpenTag(ofs, 0, top);
3123 ofs << "<!-- DocBook file was created by " << lyx_docversion
3124 << "\n See http://www.lyx.org/ for more information -->\n";
3126 vector<string> environment_stack(10);
3127 vector<string> environment_inner(10);
3128 vector<string> command_stack(10);
3130 bool command_flag = false;
3131 Paragraph::depth_type command_depth = 0;
3132 Paragraph::depth_type command_base = 0;
3133 Paragraph::depth_type cmd_depth = 0;
3134 Paragraph::depth_type depth = 0; // paragraph depth
3137 string command_name;
3143 int desc_on = 0; // description mode
3145 LyXLayout const & style =
3146 textclasslist.Style(params.textclass,
3149 // environment tag closing
3150 for (; depth > par->params().depth(); --depth) {
3151 if (environment_inner[depth] != "!-- --") {
3152 item_name = "listitem";
3153 sgmlCloseTag(ofs, command_depth + depth,
3155 if (environment_inner[depth] == "varlistentry")
3156 sgmlCloseTag(ofs, depth+command_depth,
3157 environment_inner[depth]);
3159 sgmlCloseTag(ofs, depth + command_depth,
3160 environment_stack[depth]);
3161 environment_stack[depth].erase();
3162 environment_inner[depth].erase();
3165 if (depth == par->params().depth()
3166 && environment_stack[depth] != style.latexname()
3167 && !environment_stack[depth].empty()) {
3168 if (environment_inner[depth] != "!-- --") {
3169 item_name= "listitem";
3170 sgmlCloseTag(ofs, command_depth+depth,
3172 if (environment_inner[depth] == "varlistentry")
3174 depth + command_depth,
3175 environment_inner[depth]);
3178 sgmlCloseTag(ofs, depth + command_depth,
3179 environment_stack[depth]);
3181 environment_stack[depth].erase();
3182 environment_inner[depth].erase();
3185 // Write opening SGML tags.
3186 switch (style.latextype) {
3187 case LATEX_PARAGRAPH:
3188 sgmlOpenTag(ofs, depth + command_depth,
3195 _("Error : Wrong depth for "
3196 "LatexType Command.\n"));
3198 command_name = style.latexname();
3200 sgmlparam = style.latexparam();
3201 c_params = split(sgmlparam, c_depth,'|');
3203 cmd_depth = lyx::atoi(c_depth);
3206 if (cmd_depth < command_base) {
3207 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3208 sgmlCloseTag(ofs, j, command_stack[j]);
3209 command_depth = command_base = cmd_depth;
3210 } else if (cmd_depth <= command_depth) {
3211 for (int j = command_depth; j >= int(cmd_depth); --j)
3212 sgmlCloseTag(ofs, j, command_stack[j]);
3213 command_depth = cmd_depth;
3215 command_depth = cmd_depth;
3217 command_depth = command_base = cmd_depth;
3218 command_flag = true;
3220 if (command_stack.size() == command_depth + 1)
3221 command_stack.push_back(string());
3222 command_stack[command_depth] = command_name;
3224 // treat label as a special case for
3225 // more WYSIWYM handling.
3226 // This is a hack while paragraphs can't have
3227 // attributes, like id in this case.
3228 if (par->isInset(0)) {
3229 Inset * inset = par->getInset(0);
3230 Inset::Code lyx_code = inset->lyxCode();
3231 if (lyx_code == Inset::LABEL_CODE) {
3232 command_name += " id=\"";
3233 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3234 command_name += "\"";
3239 sgmlOpenTag(ofs, depth + command_depth, command_name);
3240 if (c_params.empty())
3241 item_name = "title";
3243 item_name = c_params;
3244 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3247 case LATEX_ENVIRONMENT:
3248 case LATEX_ITEM_ENVIRONMENT:
3249 if (depth < par->params().depth()) {
3250 depth = par->params().depth();
3251 environment_stack[depth].erase();
3254 if (environment_stack[depth] != style.latexname()) {
3255 if (environment_stack.size() == depth + 1) {
3256 environment_stack.push_back("!-- --");
3257 environment_inner.push_back("!-- --");
3259 environment_stack[depth] = style.latexname();
3260 environment_inner[depth] = "!-- --";
3261 sgmlOpenTag(ofs, depth + command_depth,
3262 environment_stack[depth]);
3264 if (environment_inner[depth] != "!-- --") {
3265 item_name= "listitem";
3267 command_depth + depth,
3269 if (environment_inner[depth] == "varlistentry")
3271 depth + command_depth,
3272 environment_inner[depth]);
3276 if (style.latextype == LATEX_ENVIRONMENT) {
3277 if (!style.latexparam().empty()) {
3278 if (style.latexparam() == "CDATA")
3281 sgmlOpenTag(ofs, depth + command_depth,
3282 style.latexparam());
3287 desc_on = (style.labeltype == LABEL_MANUAL);
3290 environment_inner[depth]= "varlistentry";
3292 environment_inner[depth]= "listitem";
3294 sgmlOpenTag(ofs, depth + 1 + command_depth,
3295 environment_inner[depth]);
3299 sgmlOpenTag(ofs, depth + 1 + command_depth,
3303 sgmlOpenTag(ofs, depth + 1 + command_depth,
3308 sgmlOpenTag(ofs, depth + command_depth,
3313 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3317 // write closing SGML tags
3318 switch (style.latextype) {
3320 if (c_params.empty())
3324 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3326 case LATEX_ENVIRONMENT:
3327 if (!style.latexparam().empty()) {
3328 if (style.latexparam() == "CDATA")
3331 sgmlCloseTag(ofs, depth + command_depth,
3332 style.latexparam());
3335 case LATEX_ITEM_ENVIRONMENT:
3336 if (desc_on == 1) break;
3338 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3340 case LATEX_PARAGRAPH:
3341 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3344 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3350 for (int d = depth; d >= 0; --d) {
3351 if (!environment_stack[depth].empty()) {
3352 if (environment_inner[depth] != "!-- --") {
3353 item_name = "listitem";
3354 sgmlCloseTag(ofs, command_depth + depth,
3356 if (environment_inner[depth] == "varlistentry")
3357 sgmlCloseTag(ofs, depth + command_depth,
3358 environment_inner[depth]);
3361 sgmlCloseTag(ofs, depth + command_depth,
3362 environment_stack[depth]);
3366 for (int j = command_depth; j >= 0 ; --j)
3367 if (!command_stack[j].empty())
3368 sgmlCloseTag(ofs, j, command_stack[j]);
3371 sgmlCloseTag(ofs, 0, top_element);
3374 // How to check for successful close
3378 void Buffer::simpleDocBookOnePar(ostream & os,
3379 Paragraph * par, int & desc_on,
3380 Paragraph::depth_type depth) const
3382 bool emph_flag = false;
3384 LyXLayout const & style = textclasslist.Style(params.textclass,
3387 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3389 int char_line_count = depth;
3390 //if (!style.free_spacing)
3391 // os << string(depth,' ');
3393 // parsing main loop
3394 for (pos_type i = 0; i < par->size(); ++i) {
3395 LyXFont font = par->getFont(params, i);
3397 // handle <emphasis> tag
3398 if (font_old.emph() != font.emph()) {
3399 if (font.emph() == LyXFont::ON) {
3403 os << "</emphasis>";
3409 if (par->isInset(i)) {
3410 Inset * inset = par->getInset(i);
3411 // don't print the inset in position 0 if desc_on == 3 (label)
3412 if ( i || desc_on != 3) {
3413 if(style.latexparam() == "CDATA")
3415 inset->docbook(this, os);
3416 if(style.latexparam() == "CDATA")
3420 char c = par->getChar(i);
3422 par->sgmlConvertChar(c, sgml_string);
3424 if (style.pass_thru) {
3426 } else if (style.free_spacing || par->isFreeSpacing() || c != ' ') {
3428 } else if (desc_on ==1) {
3430 os << "\n</term><listitem><para>";
3440 os << "</emphasis>";
3443 // resets description flag correctly
3445 // <term> not closed...
3448 if (style.free_spacing) os << '\n';
3452 // This should be enabled when the Chktex class is implemented. (Asger)
3453 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3454 // Other flags: -wall -v0 -x
3455 int Buffer::runChktex()
3457 if (!users->text) return 0;
3459 users->owner()->prohibitInput();
3461 // get LaTeX-Filename
3462 string const name = getLatexName();
3463 string path = filePath();
3465 string const org_path = path;
3466 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3470 Path p(path); // path to LaTeX file
3471 users->owner()->message(_("Running chktex..."));
3473 // Remove all error insets
3474 bool const removedErrorInsets = users->removeAutoInsets();
3476 // Generate the LaTeX file if neccessary
3477 makeLaTeXFile(name, org_path, false);
3480 Chktex chktex(lyxrc.chktex_command, name, filePath());
3481 int res = chktex.run(terr); // run chktex
3484 Alert::alert(_("chktex did not work!"),
3485 _("Could not run with file:"), name);
3486 } else if (res > 0) {
3487 // Insert all errors as errors boxes
3488 users->insertErrors(terr);
3491 // if we removed error insets before we ran chktex or if we inserted
3492 // error insets after we ran chktex, this must be run:
3493 if (removedErrorInsets || res) {
3497 users->owner()->allowInput();
3503 void Buffer::validate(LaTeXFeatures & features) const
3505 Paragraph * par = paragraph;
3506 LyXTextClass const & tclass =
3507 textclasslist.TextClass(params.textclass);
3509 // AMS Style is at document level
3510 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3511 features.require("amsmath");
3514 // We don't use "lyxerr.debug" because of speed. (Asger)
3515 if (lyxerr.debugging(Debug::LATEX))
3516 lyxerr << "Paragraph: " << par << endl;
3518 // Now just follow the list of paragraphs and run
3519 // validate on each of them.
3520 par->validate(features);
3522 // and then the next paragraph
3526 // the bullet shapes are buffer level not paragraph level
3527 // so they are tested here
3528 for (int i = 0; i < 4; ++i) {
3529 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3530 int const font = params.user_defined_bullets[i].getFont();
3532 int const c = params
3533 .user_defined_bullets[i]
3540 features.require("latexsym");
3542 } else if (font == 1) {
3543 features.require("amssymb");
3544 } else if ((font >= 2 && font <= 5)) {
3545 features.require("pifont");
3550 if (lyxerr.debugging(Debug::LATEX)) {
3551 features.showStruct();
3556 // This function should be in Buffer because it's a buffer's property (ale)
3557 string const Buffer::getIncludeonlyList(char delim)
3560 for (inset_iterator it = inset_iterator_begin();
3561 it != inset_iterator_end(); ++it) {
3562 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3563 InsetInclude * insetinc =
3564 static_cast<InsetInclude *>(*it);
3565 if (insetinc->isIncludeOnly()) {
3568 lst += insetinc->getRelFileBaseName();
3572 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3577 vector<string> const Buffer::getLabelList()
3579 /// if this is a child document and the parent is already loaded
3580 /// Use the parent's list instead [ale990407]
3581 if (!params.parentname.empty()
3582 && bufferlist.exists(params.parentname)) {
3583 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3585 return tmp->getLabelList();
3588 vector<string> label_list;
3589 for (inset_iterator it = inset_iterator_begin();
3590 it != inset_iterator_end(); ++it) {
3591 vector<string> const l = (*it)->getLabelList();
3592 label_list.insert(label_list.end(), l.begin(), l.end());
3598 Buffer::Lists const Buffer::getLists() const
3601 Paragraph * par = paragraph;
3604 std::pair<bool, textclass_type> const tmp =
3605 textclasslist.NumberOfLayout(params.textclass, "Caption");
3606 bool const found = tmp.first;
3607 textclass_type const cap = tmp.second;
3610 // This is the prefered way to to this, but boost::tie can break
3614 boost::tie(found, cap) = textclasslist
3615 .NumberOfLayout(params.textclass, "Caption");
3619 char const labeltype =
3620 textclasslist.Style(params.textclass,
3621 par->getLayout()).labeltype;
3623 if (labeltype >= LABEL_COUNTER_CHAPTER
3624 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3625 // insert this into the table of contents
3626 SingleList & item = l["TOC"];
3629 textclasslist.TextClass(params.textclass).maxcounter());
3630 item.push_back(TocItem(par, depth, par->asString(this, true)));
3632 // For each paragrph, traverse its insets and look for
3636 Paragraph::inset_iterator it =
3637 par->inset_iterator_begin();
3638 Paragraph::inset_iterator end =
3639 par->inset_iterator_end();
3641 for (; it != end; ++it) {
3642 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3644 static_cast<InsetFloat*>(*it);
3646 string const type = il->type();
3648 // Now find the caption in the float...
3649 // We now tranverse the paragraphs of
3651 Paragraph * tmp = il->inset.paragraph();
3653 if (tmp->layout == cap) {
3654 SingleList & item = l[type];
3656 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3657 item.push_back(TocItem(tmp, 0 , str));
3664 lyxerr << "caption not found" << endl;
3673 // This is also a buffer property (ale)
3674 vector<pair<string, string> > const Buffer::getBibkeyList()
3676 /// if this is a child document and the parent is already loaded
3677 /// Use the parent's list instead [ale990412]
3678 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3679 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3681 return tmp->getBibkeyList();
3684 vector<pair<string, string> > keys;
3685 Paragraph * par = paragraph;
3688 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3689 par->asString(this, false)));
3693 // Might be either using bibtex or a child has bibliography
3695 for (inset_iterator it = inset_iterator_begin();
3696 it != inset_iterator_end(); ++it) {
3697 // Search for Bibtex or Include inset
3698 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3699 vector<pair<string,string> > tmp =
3700 static_cast<InsetBibtex*>(*it)->getKeys(this);
3701 keys.insert(keys.end(), tmp.begin(), tmp.end());
3702 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3703 vector<pair<string,string> > const tmp =
3704 static_cast<InsetInclude*>(*it)->getKeys();
3705 keys.insert(keys.end(), tmp.begin(), tmp.end());
3714 bool Buffer::isDepClean(string const & name) const
3716 DEPCLEAN * item = dep_clean;
3717 while (item && item->master != name)
3719 if (!item) return true;
3724 void Buffer::markDepClean(string const & name)
3727 dep_clean = new DEPCLEAN;
3728 dep_clean->clean = true;
3729 dep_clean->master = name;
3730 dep_clean->next = 0;
3732 DEPCLEAN * item = dep_clean;
3733 while (item && item->master != name)
3738 item = new DEPCLEAN;
3740 item->master = name;
3747 bool Buffer::dispatch(string const & command)
3749 // Split command string into command and argument
3751 string line = frontStrip(command);
3752 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3754 return dispatch(lyxaction.LookupFunc(cmd), arg);
3758 bool Buffer::dispatch(int action, string const & argument)
3760 bool dispatched = true;
3763 Exporter::Export(this, argument, false);
3773 void Buffer::resizeInsets(BufferView * bv)
3775 /// then remove all LyXText in text-insets
3776 Paragraph * par = paragraph;
3777 for (; par; par = par->next()) {
3778 par->resizeInsetsLyXText(bv);
3783 void Buffer::redraw()
3790 void Buffer::changeLanguage(Language const * from, Language const * to)
3793 ParIterator end = par_iterator_end();
3794 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3795 (*it)->changeLanguage(params, from, to);
3799 bool Buffer::isMultiLingual()
3801 ParIterator end = par_iterator_end();
3802 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3803 if ((*it)->isMultiLingual(params))
3810 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
3813 it = par->InsetIterator(pos);
3814 if (it == par->inset_iterator_end()) {
3821 void Buffer::inset_iterator::setParagraph()
3824 it = par->inset_iterator_begin();
3825 if (it != par->inset_iterator_end())
3830 // We maintain an invariant that whenever par = 0 then it = 0
3834 Inset * Buffer::getInsetFromID(int id_arg) const
3836 for (inset_iterator it = inset_const_iterator_begin();
3837 it != inset_const_iterator_end(); ++it)
3839 if ((*it)->id() == id_arg)
3841 Inset * in = (*it)->getInsetFromID(id_arg);
3849 Paragraph * Buffer::getParFromID(int id) const
3851 if (id < 0) return 0;
3852 Paragraph * par = paragraph;
3854 if (par->id() == id) {
3857 Paragraph * tmp = par->getParFromID(id);
3867 ParIterator Buffer::par_iterator_begin()
3869 return ParIterator(paragraph);
3873 ParIterator Buffer::par_iterator_end()
3875 return ParIterator();