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/syscall.h"
93 #include "support/lyxlib.h"
94 #include "support/FileInfo.h"
95 #include "support/lyxmanip.h"
96 #include "support/lyxalgo.h" // for lyx::count
108 #include <sys/types.h>
125 using std::make_pair;
134 using lyx::layout_type;
135 using lyx::textclass_type;
137 // all these externs should eventually be removed.
138 extern BufferList bufferlist;
140 extern LyXAction lyxaction;
144 const int LYX_FORMAT = 220;
148 extern int tex_code_break_column;
151 Buffer::Buffer(string const & file, bool ronly)
152 : paragraph(0), lyx_clean(true), bak_clean(true),
153 unnamed(false), dep_clean(0), read_only(ronly),
154 filename_(file), users(0)
156 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
158 filepath_ = OnlyPath(file);
163 // read_only = ronly;
167 if (read_only || lyxrc.use_tempdir) {
168 tmppath = CreateBufferTmpDir();
177 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
178 // here the buffer should take care that it is
179 // saved properly, before it goes into the void.
181 // make sure that views using this buffer
186 if (!tmppath.empty()) {
187 DestroyBufferTmpDir(tmppath);
190 Paragraph * par = paragraph;
193 tmppar = par->next();
201 string const Buffer::getLatexName(bool no_path) const
203 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
205 return OnlyFilename(name);
211 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
213 string const filename = getLatexName(false);
215 if (filename.empty())
216 return make_pair(Buffer::latexlog, string());
218 string path = OnlyPath(filename);
220 if (lyxrc.use_tempdir || !IsDirWriteable(path))
223 string const fname = AddName(path,
224 OnlyFilename(ChangeExtension(filename,
227 AddName(path, OnlyFilename(
228 ChangeExtension(filename,
229 formats.extension("literate") + ".out")));
231 // If no Latex log or Build log is newer, show Build log
233 FileInfo const f_fi(fname);
234 FileInfo const b_fi(bname);
237 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
238 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
239 return make_pair(Buffer::buildlog, bname);
241 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
242 return make_pair(Buffer::latexlog, fname);
246 void Buffer::setReadonly(bool flag)
248 if (read_only != flag) {
251 users->owner()->getDialogs()->updateBufferDependent(false);
256 /// Update window titles of all users
257 // Should work on a list
258 void Buffer::updateTitles() const
261 users->owner()->updateWindowTitle();
265 /// Reset autosave timer of all users
266 // Should work on a list
267 void Buffer::resetAutosaveTimers() const
270 users->owner()->resetAutosaveTimer();
274 void Buffer::setFileName(string const & newfile)
276 filename_ = MakeAbsPath(newfile);
277 filepath_ = OnlyPath(filename_);
278 setReadonly(IsFileWriteable(filename_) == 0);
283 // We'll remove this later. (Lgb)
286 string last_inset_read;
288 #ifndef NO_COMPABILITY
291 ErtComp() : active(false), in_tabular(false) {
299 std::stack<ErtComp> ert_stack;
303 #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(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 par->params().spaceTop(VSpace(lex.getString()));
1045 } else if (token == "\\added_space_bottom") {
1047 par->params().spaceBottom(VSpace(lex.getString()));
1048 #ifndef NO_COMPABILITY
1049 #ifndef NO_PEXTRA_REALLY
1050 } else if (token == "\\pextra_type") {
1052 par->params().pextraType(lex.getInteger());
1053 } else if (token == "\\pextra_width") {
1055 par->params().pextraWidth(lex.getString());
1056 } else if (token == "\\pextra_widthp") {
1058 par->params().pextraWidthp(lex.getString());
1059 } else if (token == "\\pextra_alignment") {
1061 par->params().pextraAlignment(lex.getInteger());
1062 } else if (token == "\\pextra_hfill") {
1064 par->params().pextraHfill(lex.getInteger());
1065 } else if (token == "\\pextra_start_minipage") {
1067 par->params().pextraStartMinipage(lex.getInteger());
1070 } else if (token == "\\labelwidthstring") {
1072 par->params().labelWidthString(lex.getString());
1073 // do not delete this token, it is still needed!
1074 } else if (token == "\\end_inset") {
1075 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1076 << "Last inset read was: " << last_inset_read
1078 // Simply ignore this. The insets do not have
1080 // But insets should read it, it is a part of
1081 // the inset isn't it? Lgb.
1082 } else if (token == "\\begin_inset") {
1083 #ifndef NO_COMPABILITY
1084 insertErtContents(par, pos, false);
1085 ert_stack.push(ert_comp);
1086 ert_comp = ErtComp();
1088 readInset(lex, par, pos, font);
1089 #ifndef NO_COMPABILITY
1090 ert_comp = ert_stack.top();
1092 insertErtContents(par, pos);
1094 } else if (token == "\\SpecialChar") {
1095 LyXLayout const & layout =
1096 textclasslist.Style(params.textclass,
1099 // Insets don't make sense in a free-spacing context! ---Kayvan
1100 if (layout.free_spacing || par->isFreeSpacing()) {
1103 string next_token = lex.getString();
1104 if (next_token == "\\-") {
1105 par->insertChar(pos, '-', font);
1106 } else if (next_token == "\\protected_separator"
1107 || next_token == "~") {
1108 par->insertChar(pos, ' ', font);
1110 lex.printError("Token `$$Token' "
1112 "paragraph layout!");
1117 Inset * inset = new InsetSpecialChar;
1118 inset->read(this, lex);
1119 par->insertInset(pos, inset, font);
1122 } else if (token == "\\newline") {
1123 #ifndef NO_COMPABILITY
1124 if (!ert_comp.in_tabular && ert_comp.active) {
1125 ert_comp.contents += char(Paragraph::META_NEWLINE);
1127 // Since we cannot know it this is only a regular
1128 // newline or a tabular cell delimter we have to
1129 // handle the ERT here.
1130 insertErtContents(par, pos, false);
1132 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1136 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1139 } else if (token == "\\LyXTable") {
1140 #ifndef NO_COMPABILITY
1141 ert_comp.in_tabular = true;
1143 Inset * inset = new InsetTabular(*this);
1144 inset->read(this, lex);
1145 par->insertInset(pos, inset, font);
1147 } else if (token == "\\hfill") {
1148 par->insertChar(pos, Paragraph::META_HFILL, font);
1150 } else if (token == "\\protected_separator") { // obsolete
1151 // This is a backward compability thingie. (Lgb)
1152 // Remove it later some time...introduced with fileformat
1154 LyXLayout const & layout =
1155 textclasslist.Style(params.textclass,
1158 if (layout.free_spacing || par->isFreeSpacing()) {
1159 par->insertChar(pos, ' ', font);
1161 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1162 par->insertInset(pos, inset, font);
1165 } else if (token == "\\bibitem") { // ale970302
1167 InsetCommandParams p("bibitem", "dummy");
1168 par->bibkey = new InsetBibKey(p);
1170 par->bibkey->read(this, lex);
1171 } else if (token == "\\backslash") {
1172 #ifndef NO_COMPABILITY
1173 if (ert_comp.active) {
1174 ert_comp.contents += "\\";
1177 par->insertChar(pos, '\\', font);
1179 #ifndef NO_COMPABILITY
1182 } else if (token == "\\the_end") {
1183 #ifndef NO_COMPABILITY
1184 // If we still have some ert active here we have to insert
1185 // it so we don't loose it. (Lgb)
1186 insertErtContents(par, pos);
1188 the_end_read = true;
1189 #ifndef NO_COMPABILITY
1190 #ifndef NO_PEXTRA_REALLY
1191 minipar = parBeforeMinipage = 0;
1195 #ifndef NO_COMPABILITY
1196 if (ert_comp.active) {
1197 ert_comp.contents += token;
1200 // This should be insurance for the future: (Asger)
1203 string const s = _("Unknown token: ") + token
1204 + " " + lex.text() + "\n";
1206 InsetError * new_inset = new InsetError(s);
1207 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
1210 #ifndef NO_COMPABILITY
1215 #ifndef NO_COMPABILITY
1216 #ifndef NO_PEXTRA_REALLY
1217 // I wonder if we could use this blanket fix for all the
1218 // checkminipage cases...
1219 // don't forget about ert paragraphs and compatibility read for'em
1220 if (par && (par->size() || !ert_comp.contents.empty())) {
1221 // It is possible that this will check to often,
1222 // but that should not be an correctness issue.
1223 // Only a speed issue.
1224 checkminipage = true;
1227 // now check if we have a minipage paragraph as at this
1228 // point we already read all the necessary data!
1229 // this cannot be done in layout because there we did
1230 // not read yet the paragraph PEXTRA-params (Jug)
1232 // BEGIN pextra_minipage compability
1233 // This should be removed in 1.3.x (Lgb)
1234 // I don't think we should remove this so fast (Jug)
1236 // This compability code is not perfect. In a couple
1237 // of rand cases it fails. When the minipage par is
1238 // the first par in the document, and when there are
1239 // none or only one regular paragraphs after the
1240 // minipage. Currently I am not investing any effort
1241 // in fixing those cases.
1243 //lyxerr << "Call depth: " << call_depth << endl;
1244 if (checkminipage && (call_depth == 1)) {
1245 checkminipage = false;
1246 if (minipar && (minipar != par) &&
1247 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1249 lyxerr << "minipages in a row" << endl;
1250 if (par->params().pextraStartMinipage()) {
1251 lyxerr << "start new minipage" << endl;
1252 // minipages in a row
1253 par->previous()->next(0);
1256 Paragraph * tmp = minipar;
1258 tmp->params().pextraType(0);
1259 tmp->params().pextraWidth(string());
1260 tmp->params().pextraWidthp(string());
1261 tmp->params().pextraAlignment(0);
1262 tmp->params().pextraHfill(false);
1263 tmp->params().pextraStartMinipage(false);
1266 // create a new paragraph to insert the
1267 // minipages in the following case
1268 if (par->params().pextraStartMinipage() &&
1269 !par->params().pextraHfill())
1271 Paragraph * p = new Paragraph;
1273 p->previous(parBeforeMinipage);
1274 parBeforeMinipage->next(p);
1276 p->params().depth(parBeforeMinipage->params().depth());
1277 parBeforeMinipage = p;
1279 InsetMinipage * mini = new InsetMinipage;
1280 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1281 mini->pageWidth(LyXLength(par->params().pextraWidth()));
1282 if (!par->params().pextraWidthp().empty()) {
1283 lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1284 mini->pageWidth(LyXLength((par->params().pextraWidthp())+"%"));
1286 Paragraph * op = mini->firstParagraph();
1287 mini->inset.paragraph(par);
1289 // and free the old ones!
1292 Paragraph * pp = op->next();
1296 // Insert the minipage last in the
1297 // previous paragraph.
1298 if (par->params().pextraHfill()) {
1299 parBeforeMinipage->insertChar
1300 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1302 parBeforeMinipage->insertInset
1303 (parBeforeMinipage->size(), mini);
1307 lyxerr << "new minipage par" << endl;
1308 //nothing to do just continue reading
1311 } else if (minipar && (minipar != par)) {
1312 lyxerr << "last minipage par read" << endl;
1313 // The last paragraph read was not part of a
1314 // minipage but the par linked list is...
1315 // So we need to remove the last par from the
1317 if (par->previous())
1318 par->previous()->next(0);
1319 par->previous(parBeforeMinipage);
1320 parBeforeMinipage->next(par);
1321 Paragraph * tmp = minipar;
1323 tmp->params().pextraType(0);
1324 tmp->params().pextraWidth(string());
1325 tmp->params().pextraWidthp(string());
1326 tmp->params().pextraAlignment(0);
1327 tmp->params().pextraHfill(false);
1328 tmp->params().pextraStartMinipage(false);
1331 depth = parBeforeMinipage->params().depth();
1332 // and set this depth on the par as it has not been set already
1333 par->params().depth(depth);
1334 minipar = parBeforeMinipage = 0;
1335 } else if (!minipar &&
1336 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1338 // par is the first paragraph in a minipage
1339 lyxerr << "begin minipage" << endl;
1340 // To minimize problems for
1341 // the users we will insert
1342 // the first minipage in
1343 // a sequence of minipages
1344 // in its own paragraph.
1345 Paragraph * p = new Paragraph;
1347 p->previous(par->previous());
1349 p->params().depth(depth);
1350 par->params().depth(0);
1352 if (par->previous())
1353 par->previous()->next(p);
1355 parBeforeMinipage = p;
1357 if (!first_par || (first_par == par))
1360 InsetMinipage * mini = new InsetMinipage;
1361 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1362 mini->pageWidth(LyXLength(minipar->params().pextraWidth()));
1363 if (!par->params().pextraWidthp().empty()) {
1364 lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1365 mini->pageWidth(LyXLength((par->params().pextraWidthp())+"%"));
1367 mini->inset.paragraph(minipar);
1369 // Insert the minipage last in the
1370 // previous paragraph.
1371 if (minipar->params().pextraHfill()) {
1372 parBeforeMinipage->insertChar
1373 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1375 parBeforeMinipage->insertInset
1376 (parBeforeMinipage->size(), mini);
1379 // End of pextra_minipage compability
1383 return the_end_read;
1386 // needed to insert the selection
1387 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
1388 LyXFont const & fn,string const & str) const
1390 LyXLayout const & layout = textclasslist.Style(params.textclass,
1394 (void)par->checkInsertChar(font);
1395 // insert the string, don't insert doublespace
1396 bool space_inserted = true;
1397 for(string::const_iterator cit = str.begin();
1398 cit != str.end(); ++cit) {
1400 if (par->size() || layout.keepempty) {
1401 par->breakParagraph(params, pos,
1402 layout.isEnvironment());
1405 space_inserted = true;
1409 // do not insert consecutive spaces if !free_spacing
1410 } else if ((*cit == ' ' || *cit == '\t') &&
1411 space_inserted && !layout.free_spacing &&
1412 !par->isFreeSpacing())
1415 } else if (*cit == '\t') {
1416 if (!layout.free_spacing && !par->isFreeSpacing()) {
1417 // tabs are like spaces here
1418 par->insertChar(pos, ' ', font);
1420 space_inserted = true;
1422 const pos_type nb = 8 - pos % 8;
1423 for (pos_type a = 0; a < nb ; ++a) {
1424 par->insertChar(pos, ' ', font);
1427 space_inserted = true;
1429 } else if (!IsPrintable(*cit)) {
1430 // Ignore unprintables
1433 // just insert the character
1434 par->insertChar(pos, *cit, font);
1436 space_inserted = (*cit == ' ');
1443 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1444 int & pos, LyXFont & font)
1446 // consistency check
1447 if (lex.getString() != "\\begin_inset") {
1448 lyxerr << "Buffer::readInset: Consistency check failed."
1455 string const tmptok = lex.getString();
1456 last_inset_read = tmptok;
1458 // test the different insets
1459 if (tmptok == "LatexCommand") {
1460 InsetCommandParams inscmd;
1463 string const cmdName = inscmd.getCmdName();
1465 // This strange command allows LyX to recognize "natbib" style
1466 // citations: citet, citep, Citet etc.
1467 if (compare_no_case(cmdName, "cite", 4) == 0) {
1468 inset = new InsetCitation(inscmd);
1469 } else if (cmdName == "bibitem") {
1470 lex.printError("Wrong place for bibitem");
1471 inset = new InsetBibKey(inscmd);
1472 } else if (cmdName == "BibTeX") {
1473 inset = new InsetBibtex(inscmd);
1474 } else if (cmdName == "index") {
1475 inset = new InsetIndex(inscmd);
1476 } else if (cmdName == "include") {
1477 inset = new InsetInclude(inscmd, *this);
1478 } else if (cmdName == "label") {
1479 inset = new InsetLabel(inscmd);
1480 } else if (cmdName == "url"
1481 || cmdName == "htmlurl") {
1482 inset = new InsetUrl(inscmd);
1483 } else if (cmdName == "ref"
1484 || cmdName == "pageref"
1485 || cmdName == "vref"
1486 || cmdName == "vpageref"
1487 || cmdName == "prettyref") {
1488 if (!inscmd.getOptions().empty()
1489 || !inscmd.getContents().empty()) {
1490 inset = new InsetRef(inscmd, *this);
1492 } else if (cmdName == "tableofcontents") {
1493 inset = new InsetTOC(inscmd);
1494 } else if (cmdName == "listofalgorithms") {
1495 inset = new InsetFloatList("algorithm");
1496 } else if (cmdName == "listoffigures") {
1497 inset = new InsetFloatList("figure");
1498 } else if (cmdName == "listoftables") {
1499 inset = new InsetFloatList("table");
1500 } else if (cmdName == "printindex") {
1501 inset = new InsetPrintIndex(inscmd);
1502 } else if (cmdName == "lyxparent") {
1503 inset = new InsetParent(inscmd, *this);
1506 bool alreadyread = false;
1507 if (tmptok == "Quotes") {
1508 inset = new InsetQuotes;
1509 } else if (tmptok == "External") {
1510 inset = new InsetExternal;
1511 } else if (tmptok == "FormulaMacro") {
1512 inset = new InsetFormulaMacro;
1513 } else if (tmptok == "Formula") {
1514 inset = new InsetFormula;
1515 } else if (tmptok == "Figure") { // Backward compatibility
1516 // inset = new InsetFig(100, 100, *this);
1517 inset = new InsetGraphics;
1518 } else if (tmptok == "Graphics") {
1519 inset = new InsetGraphics;
1520 } else if (tmptok == "Info") {// backwards compatibility
1521 inset = new InsetNote(this,
1522 lex.getLongString("\\end_inset"),
1525 } else if (tmptok == "Note") {
1526 inset = new InsetNote;
1527 } else if (tmptok == "Include") {
1528 InsetCommandParams p( "Include" );
1529 inset = new InsetInclude(p, *this);
1530 } else if (tmptok == "ERT") {
1531 inset = new InsetERT;
1532 } else if (tmptok == "Tabular") {
1533 inset = new InsetTabular(*this);
1534 } else if (tmptok == "Text") {
1535 inset = new InsetText;
1536 } else if (tmptok == "Foot") {
1537 inset = new InsetFoot;
1538 } else if (tmptok == "Marginal") {
1539 inset = new InsetMarginal;
1540 } else if (tmptok == "Minipage") {
1541 inset = new InsetMinipage;
1542 } else if (tmptok == "Float") {
1544 string tmptok = lex.getString();
1545 inset = new InsetFloat(tmptok);
1547 } else if (tmptok == "List") {
1548 inset = new InsetList;
1549 } else if (tmptok == "Theorem") {
1550 inset = new InsetList;
1552 } else if (tmptok == "Caption") {
1553 inset = new InsetCaption;
1554 } else if (tmptok == "FloatList") {
1555 inset = new InsetFloatList;
1558 if (inset && !alreadyread) inset->read(this, lex);
1562 par->insertInset(pos, inset, font);
1568 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1572 string const token(lex.getString());
1573 if (token == "\\lyxformat") { // the first token _must_ be...
1575 string tmp_format = lex.getString();
1576 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1577 // if present remove ".," from string.
1578 string::size_type dot = tmp_format.find_first_of(".,");
1579 //lyxerr << " dot found at " << dot << endl;
1580 if (dot != string::npos)
1581 tmp_format.erase(dot, 1);
1582 file_format = strToInt(tmp_format);
1583 if (file_format == LYX_FORMAT) {
1585 } else if (file_format > LYX_FORMAT) {
1587 Alert::alert(_("Warning!"),
1588 _("LyX file format is newer that what"),
1589 _("is supported in this LyX version. Expect some problems."));
1591 } else if (file_format < LYX_FORMAT) {
1593 if (file_format < 200) {
1594 Alert::alert(_("ERROR!"),
1595 _("Old LyX file format found. "
1596 "Use LyX 0.10.x to read this!"));
1600 bool the_end = readLyXformat2(lex, par);
1601 params.setPaperStuff();
1602 // the_end was added in 213
1603 if (file_format < 213)
1607 Alert::alert(_("Warning!"),
1608 _("Reading of document is not complete"),
1609 _("Maybe the document is truncated"));
1612 } else { // "\\lyxformat" not found
1613 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1616 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1621 // Should probably be moved to somewhere else: BufferView? LyXView?
1622 bool Buffer::save() const
1624 // We don't need autosaves in the immediate future. (Asger)
1625 resetAutosaveTimers();
1629 if (lyxrc.make_backup) {
1630 s = fileName() + '~';
1631 if (!lyxrc.backupdir_path.empty())
1632 s = AddName(lyxrc.backupdir_path,
1633 subst(os::slashify_path(s),'/','!'));
1635 // Rename is the wrong way of making a backup,
1636 // this is the correct way.
1637 /* truss cp fil fil2:
1638 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1639 stat("LyXVC.lyx", 0xEFFFF688) = 0
1640 open("LyXVC.lyx", O_RDONLY) = 3
1641 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1642 fstat(4, 0xEFFFF508) = 0
1643 fstat(3, 0xEFFFF508) = 0
1644 read(3, " # T h i s f i l e w".., 8192) = 5579
1645 write(4, " # T h i s f i l e w".., 5579) = 5579
1646 read(3, 0xEFFFD4A0, 8192) = 0
1649 chmod("LyXVC3.lyx", 0100644) = 0
1650 lseek(0, 0, SEEK_CUR) = 46440
1654 // Should probably have some more error checking here.
1655 // Should be cleaned up in 0.13, at least a bit.
1656 // Doing it this way, also makes the inodes stay the same.
1657 // This is still not a very good solution, in particular we
1658 // might loose the owner of the backup.
1659 FileInfo finfo(fileName());
1660 if (finfo.exist()) {
1661 mode_t fmode = finfo.getMode();
1662 struct utimbuf times = {
1663 finfo.getAccessTime(),
1664 finfo.getModificationTime() };
1666 ifstream ifs(fileName().c_str());
1667 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1672 ::chmod(s.c_str(), fmode);
1674 if (::utime(s.c_str(), ×)) {
1675 lyxerr << "utime error." << endl;
1678 lyxerr << "LyX was not able to make "
1679 "backup copy. Beware." << endl;
1684 if (writeFile(fileName(), false)) {
1686 removeAutosaveFile(fileName());
1688 // Saving failed, so backup is not backup
1689 if (lyxrc.make_backup) {
1690 lyx::rename(s, fileName());
1698 // Returns false if unsuccesful
1699 bool Buffer::writeFile(string const & fname, bool flag) const
1701 // if flag is false writeFile will not create any GUI
1702 // warnings, only cerr.
1703 // Needed for autosave in background or panic save (Matthias 120496)
1705 if (read_only && (fname == fileName())) {
1706 // Here we should come with a question if we should
1707 // perform the write anyway.
1709 lyxerr << _("Error! Document is read-only: ")
1712 Alert::alert(_("Error! Document is read-only: "),
1717 FileInfo finfo(fname);
1718 if (finfo.exist() && !finfo.writable()) {
1719 // Here we should come with a question if we should
1720 // try to do the save anyway. (i.e. do a chmod first)
1722 lyxerr << _("Error! Cannot write file: ")
1725 Alert::err_alert(_("Error! Cannot write file: "),
1730 ofstream ofs(fname.c_str());
1733 lyxerr << _("Error! Cannot open file: ")
1736 Alert::err_alert(_("Error! Cannot open file: "),
1742 // Use the standard "C" locale for file output.
1743 ofs.imbue(std::locale::classic());
1746 // The top of the file should not be written by params.
1748 // write out a comment in the top of the file
1749 ofs << '#' << lyx_docversion
1750 << " created this file. For more info see http://www.lyx.org/\n"
1751 << "\\lyxformat " << LYX_FORMAT << "\n";
1753 // now write out the buffer paramters.
1754 params.writeFile(ofs);
1756 Paragraph::depth_type depth = 0;
1758 // this will write out all the paragraphs
1759 // using recursive descent.
1760 paragraph->writeFile(this, ofs, params, depth);
1762 // Write marker that shows file is complete
1763 ofs << "\n\\the_end" << endl;
1767 // how to check if close went ok?
1768 // Following is an attempt... (BE 20001011)
1770 // good() returns false if any error occured, including some
1771 // formatting error.
1772 // bad() returns true if something bad happened in the buffer,
1773 // which should include file system full errors.
1780 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1782 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1792 string const Buffer::asciiParagraph(Paragraph const * par,
1793 unsigned int linelen,
1794 bool noparbreak) const
1796 ostringstream buffer;
1798 Paragraph::depth_type depth = 0;
1800 Paragraph::depth_type ltype_depth = 0;
1801 string::size_type currlinelen = 0;
1802 bool ref_printed = false;
1803 // if (!par->previous()) {
1805 // begins or ends a deeper area ?
1806 if (depth != par->params().depth()) {
1807 if (par->params().depth() > depth) {
1808 while (par->params().depth() > depth) {
1812 while (par->params().depth() < depth) {
1818 depth = par->params().depth();
1821 // First write the layout
1822 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1823 if (tmp == "Itemize") {
1825 ltype_depth = depth + 1;
1826 } else if (tmp == "Enumerate") {
1828 ltype_depth = depth + 1;
1829 } else if (contains(tmp, "ection")) {
1831 ltype_depth = depth + 1;
1832 } else if (contains(tmp, "aragraph")) {
1834 ltype_depth = depth + 1;
1835 } else if (tmp == "Description") {
1837 ltype_depth = depth + 1;
1838 } else if (tmp == "Abstract") {
1841 } else if (tmp == "Bibliography") {
1849 /* maybe some vertical spaces */
1851 /* the labelwidthstring used in lists */
1855 /* some pagebreaks? */
1859 /* what about the alignment */
1861 // lyxerr << "Should this ever happen?" << endl;
1864 // linelen <= 0 is special and means we don't have pargraph breaks
1868 for (Paragraph::depth_type j = 0; j < depth; ++j)
1870 currlinelen = depth * 2;
1872 // we should probably change to the paragraph language in the
1873 // gettext here (if possible) so that strings are outputted in
1874 // the correct language! (20012712 Jug)
1878 case 4: // (Sub)Paragraph
1879 case 5: // Description
1883 buffer << _("Abstract") << "\n\n";
1885 buffer << _("Abstract: ");
1887 case 7: // Bibliography
1890 buffer << _("References") << "\n\n";
1892 buffer << _("References: ");
1897 buffer << par->params().labelString() << " ";
1901 string s = buffer.str();
1902 if (s.rfind('\n') != string::npos) {
1904 s = rsplit(buffer.str().c_str(), dummy, '\n');
1906 currlinelen = s.length();
1908 for (Paragraph::depth_type j = 0; j < depth; ++j)
1910 currlinelen = depth * 2;
1911 if (ltype_depth > depth) {
1912 for (Paragraph::depth_type j = ltype_depth;
1917 currlinelen += (ltype_depth-depth)*2;
1920 // this is to change the linebreak to do it by word a bit more intelligent
1921 // hopefully! (only in the case where we have a max linelenght!) (Jug)
1922 for (pos_type i = 0; i < par->size(); ++i) {
1923 char c = par->getUChar(params, i);
1925 case Paragraph::META_INSET:
1927 Inset const * inset = par->getInset(i);
1930 buffer << word.str();
1933 if (inset->ascii(this, buffer, linelen)) {
1934 // to be sure it breaks paragraph
1935 currlinelen += linelen;
1941 rsplit(buffer.str().c_str(),
1943 currlinelen = s.length();
1950 case Paragraph::META_NEWLINE:
1952 buffer << word.str() << "\n";
1954 for (Paragraph::depth_type j = 0;
1957 currlinelen = depth * 2;
1958 if (ltype_depth > depth) {
1959 for (Paragraph::depth_type j = ltype_depth;
1962 currlinelen += (ltype_depth - depth) * 2;
1967 case Paragraph::META_HFILL:
1968 buffer << word.str() << "\t";
1969 currlinelen += word.str().length() + 1;
1975 buffer << word.str() << ' ';
1976 currlinelen += word.str().length() + 1;
1982 lyxerr[Debug::INFO] <<
1983 "writeAsciiFile: NULL char in structure." << endl;
1985 if ((linelen > 0) &&
1986 (currlinelen+word.str().length()) > linelen)
1989 for (Paragraph::depth_type j = 0; j < depth; ++j)
1991 currlinelen = depth * 2;
1992 if (ltype_depth > depth) {
1993 for (Paragraph::depth_type j = ltype_depth;
1998 currlinelen += (ltype_depth-depth)*2;
2005 buffer << word.str();
2006 return buffer.str().c_str();
2010 void Buffer::writeFileAscii(string const & fname, int linelen)
2012 ofstream ofs(fname.c_str());
2014 Alert::err_alert(_("Error: Cannot write file:"), fname);
2017 writeFileAscii(ofs, linelen);
2021 void Buffer::writeFileAscii(ostream & ofs, int linelen)
2023 Paragraph * par = paragraph;
2025 ofs << asciiParagraph(par, linelen, par->previous() == 0);
2035 void Buffer::makeLaTeXFile(string const & fname,
2036 string const & original_path,
2037 bool nice, bool only_body)
2039 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
2041 niceFile = nice; // this will be used by Insetincludes.
2043 tex_code_break_column = lyxrc.ascii_linelen;
2045 LyXTextClass const & tclass =
2046 textclasslist.TextClass(params.textclass);
2048 ofstream ofs(fname.c_str());
2050 Alert::err_alert(_("Error: Cannot open file: "), fname);
2054 // validate the buffer.
2055 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
2056 LaTeXFeatures features(params, tclass.numLayouts());
2058 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
2061 // The starting paragraph of the coming rows is the
2062 // first paragraph of the document. (Asger)
2063 texrow.start(paragraph, 0);
2065 if (!only_body && nice) {
2066 ofs << "%% " << lyx_docversion << " created this file. "
2067 "For more info, see http://www.lyx.org/.\n"
2068 "%% Do not edit unless you really know what "
2073 lyxerr[Debug::INFO] << "lyx header finished" << endl;
2074 // There are a few differences between nice LaTeX and usual files:
2075 // usual is \batchmode and has a
2076 // special input@path to allow the including of figures
2077 // with either \input or \includegraphics (what figinsets do).
2078 // batchmode is not set if there is a tex_code_break_column.
2079 // In this case somebody is interested in the generated LaTeX,
2080 // so this is OK. input@path is set when the actual parameter
2081 // original_path is set. This is done for usual tex-file, but not
2082 // for nice-latex-file. (Matthias 250696)
2085 // code for usual, NOT nice-latex-file
2086 ofs << "\\batchmode\n"; // changed
2087 // from \nonstopmode
2090 if (!original_path.empty()) {
2091 ofs << "\\makeatletter\n"
2092 << "\\def\\input@path{{"
2093 << os::external_path(original_path) << "/}}\n"
2094 << "\\makeatother\n";
2100 ofs << "\\documentclass";
2102 ostringstream options; // the document class options.
2104 if (tokenPos(tclass.opt_fontsize(),
2105 '|', params.fontsize) >= 0) {
2106 // only write if existing in list (and not default)
2107 options << params.fontsize << "pt,";
2111 if (!params.use_geometry &&
2112 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2113 switch (params.papersize) {
2114 case BufferParams::PAPER_A4PAPER:
2115 options << "a4paper,";
2117 case BufferParams::PAPER_USLETTER:
2118 options << "letterpaper,";
2120 case BufferParams::PAPER_A5PAPER:
2121 options << "a5paper,";
2123 case BufferParams::PAPER_B5PAPER:
2124 options << "b5paper,";
2126 case BufferParams::PAPER_EXECUTIVEPAPER:
2127 options << "executivepaper,";
2129 case BufferParams::PAPER_LEGALPAPER:
2130 options << "legalpaper,";
2136 if (params.sides != tclass.sides()) {
2137 switch (params.sides) {
2138 case LyXTextClass::OneSide:
2139 options << "oneside,";
2141 case LyXTextClass::TwoSides:
2142 options << "twoside,";
2148 if (params.columns != tclass.columns()) {
2149 if (params.columns == 2)
2150 options << "twocolumn,";
2152 options << "onecolumn,";
2155 if (!params.use_geometry
2156 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2157 options << "landscape,";
2159 // language should be a parameter to \documentclass
2161 ostringstream language_options;
2162 if (params.language->babel() == "hebrew"
2163 && default_language->babel() != "hebrew")
2164 // This seems necessary
2165 features.useLanguage(default_language);
2167 if (lyxrc.language_use_babel ||
2168 params.language->lang() != lyxrc.default_language ||
2169 !features.hasLanguages()) {
2171 language_options << features.getLanguages();
2172 language_options << params.language->babel();
2173 if (lyxrc.language_global_options)
2174 options << language_options.str() << ',';
2177 // the user-defined options
2178 if (!params.options.empty()) {
2179 options << params.options << ',';
2182 string strOptions(options.str().c_str());
2183 if (!strOptions.empty()){
2184 strOptions = strip(strOptions, ',');
2185 ofs << '[' << strOptions << ']';
2189 << textclasslist.LatexnameOfClass(params.textclass)
2192 // end of \documentclass defs
2194 // font selection must be done before loading fontenc.sty
2195 // The ae package is not needed when using OT1 font encoding.
2196 if (params.fonts != "default" &&
2197 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2198 ofs << "\\usepackage{" << params.fonts << "}\n";
2200 if (params.fonts == "ae") {
2201 ofs << "\\usepackage{aecompl}\n";
2205 // this one is not per buffer
2206 if (lyxrc.fontenc != "default") {
2207 ofs << "\\usepackage[" << lyxrc.fontenc
2212 if (params.inputenc == "auto") {
2213 string const doc_encoding =
2214 params.language->encoding()->LatexName();
2216 // Create a list with all the input encodings used
2218 set<string> encodings = features.getEncodingSet(doc_encoding);
2220 ofs << "\\usepackage[";
2221 std::copy(encodings.begin(), encodings.end(),
2222 std::ostream_iterator<string>(ofs, ","));
2223 ofs << doc_encoding << "]{inputenc}\n";
2225 } else if (params.inputenc != "default") {
2226 ofs << "\\usepackage[" << params.inputenc
2231 // At the very beginning the text parameters.
2232 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2233 switch (params.paperpackage) {
2234 case BufferParams::PACKAGE_A4:
2235 ofs << "\\usepackage{a4}\n";
2238 case BufferParams::PACKAGE_A4WIDE:
2239 ofs << "\\usepackage{a4wide}\n";
2242 case BufferParams::PACKAGE_WIDEMARGINSA4:
2243 ofs << "\\usepackage[widemargins]{a4}\n";
2248 if (params.use_geometry) {
2249 ofs << "\\usepackage{geometry}\n";
2251 ofs << "\\geometry{verbose";
2252 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2253 ofs << ",landscape";
2254 switch (params.papersize2) {
2255 case BufferParams::VM_PAPER_CUSTOM:
2256 if (!params.paperwidth.empty())
2257 ofs << ",paperwidth="
2258 << params.paperwidth;
2259 if (!params.paperheight.empty())
2260 ofs << ",paperheight="
2261 << params.paperheight;
2263 case BufferParams::VM_PAPER_USLETTER:
2264 ofs << ",letterpaper";
2266 case BufferParams::VM_PAPER_USLEGAL:
2267 ofs << ",legalpaper";
2269 case BufferParams::VM_PAPER_USEXECUTIVE:
2270 ofs << ",executivepaper";
2272 case BufferParams::VM_PAPER_A3:
2275 case BufferParams::VM_PAPER_A4:
2278 case BufferParams::VM_PAPER_A5:
2281 case BufferParams::VM_PAPER_B3:
2284 case BufferParams::VM_PAPER_B4:
2287 case BufferParams::VM_PAPER_B5:
2291 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2292 switch (lyxrc.default_papersize) {
2293 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2294 case BufferParams::PAPER_USLETTER:
2295 ofs << ",letterpaper";
2297 case BufferParams::PAPER_LEGALPAPER:
2298 ofs << ",legalpaper";
2300 case BufferParams::PAPER_EXECUTIVEPAPER:
2301 ofs << ",executivepaper";
2303 case BufferParams::PAPER_A3PAPER:
2306 case BufferParams::PAPER_A4PAPER:
2309 case BufferParams::PAPER_A5PAPER:
2312 case BufferParams::PAPER_B5PAPER:
2317 if (!params.topmargin.empty())
2318 ofs << ",tmargin=" << params.topmargin;
2319 if (!params.bottommargin.empty())
2320 ofs << ",bmargin=" << params.bottommargin;
2321 if (!params.leftmargin.empty())
2322 ofs << ",lmargin=" << params.leftmargin;
2323 if (!params.rightmargin.empty())
2324 ofs << ",rmargin=" << params.rightmargin;
2325 if (!params.headheight.empty())
2326 ofs << ",headheight=" << params.headheight;
2327 if (!params.headsep.empty())
2328 ofs << ",headsep=" << params.headsep;
2329 if (!params.footskip.empty())
2330 ofs << ",footskip=" << params.footskip;
2335 if (tokenPos(tclass.opt_pagestyle(),
2336 '|', params.pagestyle) >= 0) {
2337 if (params.pagestyle == "fancy") {
2338 ofs << "\\usepackage{fancyhdr}\n";
2341 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2345 if (params.secnumdepth != tclass.secnumdepth()) {
2346 ofs << "\\setcounter{secnumdepth}{"
2347 << params.secnumdepth
2351 if (params.tocdepth != tclass.tocdepth()) {
2352 ofs << "\\setcounter{tocdepth}{"
2358 if (params.paragraph_separation) {
2359 switch (params.defskip.kind()) {
2360 case VSpace::SMALLSKIP:
2361 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2363 case VSpace::MEDSKIP:
2364 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2366 case VSpace::BIGSKIP:
2367 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2369 case VSpace::LENGTH:
2370 ofs << "\\setlength\\parskip{"
2371 << params.defskip.length().asLatexString()
2374 default: // should never happen // Then delete it.
2375 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2380 ofs << "\\setlength\\parindent{0pt}\n";
2384 // Now insert the LyX specific LaTeX commands...
2386 // The optional packages;
2387 string preamble(features.getPackages());
2389 // this might be useful...
2390 preamble += "\n\\makeatletter\n";
2392 // Some macros LyX will need
2393 string tmppreamble(features.getMacros());
2395 if (!tmppreamble.empty()) {
2396 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2397 "LyX specific LaTeX commands.\n"
2398 + tmppreamble + '\n';
2401 // the text class specific preamble
2402 tmppreamble = features.getTClassPreamble();
2403 if (!tmppreamble.empty()) {
2404 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2405 "Textclass specific LaTeX commands.\n"
2406 + tmppreamble + '\n';
2409 /* the user-defined preamble */
2410 if (!params.preamble.empty()) {
2411 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2412 "User specified LaTeX commands.\n"
2413 + params.preamble + '\n';
2416 preamble += "\\makeatother\n";
2418 // Itemize bullet settings need to be last in case the user
2419 // defines their own bullets that use a package included
2420 // in the user-defined preamble -- ARRae
2421 // Actually it has to be done much later than that
2422 // since some packages like frenchb make modifications
2423 // at \begin{document} time -- JMarc
2425 for (int i = 0; i < 4; ++i) {
2426 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2427 if (bullets_def.empty())
2428 bullets_def="\\AtBeginDocument{\n";
2429 bullets_def += " \\renewcommand{\\labelitemi";
2431 // `i' is one less than the item to modify
2438 bullets_def += "ii";
2444 bullets_def += "}{" +
2445 params.user_defined_bullets[i].getText()
2450 if (!bullets_def.empty())
2451 preamble += bullets_def + "}\n\n";
2454 int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2455 for (int j = 0; j != nlines; ++j) {
2461 // We try to load babel late, in case it interferes
2462 // with other packages.
2464 string tmp = lyxrc.language_package;
2465 if (!lyxrc.language_global_options
2466 && tmp == "\\usepackage{babel}")
2467 tmp = string("\\usepackage[") +
2468 language_options.str().c_str() +
2475 ofs << "\\begin{document}\n";
2478 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2480 if (!lyxrc.language_auto_begin) {
2481 ofs << subst(lyxrc.language_command_begin, "$$lang",
2482 params.language->babel())
2487 latexParagraphs(ofs, paragraph, 0, texrow);
2489 // add this just in case after all the paragraphs
2493 if (!lyxrc.language_auto_end) {
2494 ofs << subst(lyxrc.language_command_end, "$$lang",
2495 params.language->babel())
2501 ofs << "\\end{document}\n";
2504 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2506 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2510 // Just to be sure. (Asger)
2513 // tex_code_break_column's value is used to decide
2514 // if we are in batchmode or not (within mathed_write()
2515 // in math_write.C) so we must set it to a non-zero
2516 // value when we leave otherwise we save incorrect .lyx files.
2517 tex_code_break_column = lyxrc.ascii_linelen;
2521 lyxerr << "File was not closed properly." << endl;
2524 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2525 lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2530 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2532 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2533 Paragraph * endpar, TexRow & texrow) const
2535 bool was_title = false;
2536 bool already_title = false;
2539 while (par != endpar) {
2540 Inset * in = par->inInset();
2541 // well we have to check if we are in an inset with unlimited
2542 // lenght (all in one row) if that is true then we don't allow
2543 // any special options in the paragraph and also we don't allow
2544 // any environment other then "Standard" to be valid!
2545 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2546 LyXLayout const & layout =
2547 textclasslist.Style(params.textclass, par->layout);
2549 if (layout.intitle) {
2550 if (already_title) {
2551 lyxerr <<"Error in latexParagraphs: You"
2552 " should not mix title layouts"
2553 " with normal ones." << endl;
2556 } else if (was_title && !already_title) {
2557 ofs << "\\maketitle\n";
2559 already_title = true;
2563 if (layout.isEnvironment()) {
2564 par = par->TeXEnvironment(this, params, ofs, texrow);
2566 par = par->TeXOnePar(this, params, ofs, texrow, false);
2569 par = par->TeXOnePar(this, params, ofs, texrow, false);
2572 // It might be that we only have a title in this document
2573 if (was_title && !already_title) {
2574 ofs << "\\maketitle\n";
2580 bool Buffer::isLatex() const
2582 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2586 bool Buffer::isLinuxDoc() const
2588 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2592 bool Buffer::isLiterate() const
2594 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2598 bool Buffer::isDocBook() const
2600 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2604 bool Buffer::isSGML() const
2606 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2607 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2611 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2612 string const & latexname) const
2614 if (!latexname.empty() && latexname != "!-- --")
2615 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2616 os << string(depth, ' ') << "<" << latexname << ">\n";
2620 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2621 string const & latexname) const
2623 if (!latexname.empty() && latexname != "!-- --")
2624 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2625 os << string(depth, ' ') << "</" << latexname << ">\n";
2629 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2631 ofstream ofs(fname.c_str());
2634 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2638 niceFile = nice; // this will be used by included files.
2640 LyXTextClass const & tclass =
2641 textclasslist.TextClass(params.textclass);
2643 LaTeXFeatures features(params, tclass.numLayouts());
2648 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2651 ofs << "<!doctype linuxdoc system";
2653 string preamble = params.preamble;
2654 preamble += features.getIncludedFiles(fname);
2655 preamble += features.getLyXSGMLEntities();
2657 if (!preamble.empty()) {
2658 ofs << " [ " << preamble << " ]";
2662 if (params.options.empty())
2663 sgmlOpenTag(ofs, 0, top_element);
2665 string top = top_element;
2667 top += params.options;
2668 sgmlOpenTag(ofs, 0, top);
2672 ofs << "<!-- " << lyx_docversion
2673 << " created this file. For more info see http://www.lyx.org/"
2676 Paragraph::depth_type depth = 0; // paragraph depth
2677 Paragraph * par = paragraph;
2679 vector<string> environment_stack(5);
2682 LyXLayout const & style =
2683 textclasslist.Style(params.textclass,
2686 // treat <toc> as a special case for compatibility with old code
2687 if (par->isInset(0)) {
2688 Inset * inset = par->getInset(0);
2689 Inset::Code lyx_code = inset->lyxCode();
2690 if (lyx_code == Inset::TOC_CODE){
2691 string const temp = "toc";
2692 sgmlOpenTag(ofs, depth, temp);
2699 // environment tag closing
2700 for (; depth > par->params().depth(); --depth) {
2701 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2702 environment_stack[depth].erase();
2705 // write opening SGML tags
2706 switch (style.latextype) {
2707 case LATEX_PARAGRAPH:
2708 if (depth == par->params().depth()
2709 && !environment_stack[depth].empty()) {
2710 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2711 environment_stack[depth].erase();
2717 sgmlOpenTag(ofs, depth, style.latexname());
2723 _("Error : Wrong depth for"
2724 " LatexType Command.\n"));
2726 if (!environment_stack[depth].empty()){
2727 sgmlCloseTag(ofs, depth,
2728 environment_stack[depth]);
2732 environment_stack[depth].erase();
2733 sgmlOpenTag(ofs, depth, style.latexname());
2736 case LATEX_ENVIRONMENT:
2737 case LATEX_ITEM_ENVIRONMENT:
2738 if (depth == par->params().depth()
2739 && environment_stack[depth] != style.latexname()) {
2740 sgmlCloseTag(ofs, depth,
2741 environment_stack[depth]);
2742 environment_stack[depth].erase();
2744 if (depth < par->params().depth()) {
2745 depth = par->params().depth();
2746 environment_stack[depth].erase();
2748 if (environment_stack[depth] != style.latexname()) {
2750 sgmlOpenTag(ofs, depth, "p");
2752 sgmlOpenTag(ofs, depth, style.latexname());
2754 if (environment_stack.size() == depth + 1)
2755 environment_stack.push_back("!-- --");
2756 environment_stack[depth] = style.latexname();
2759 if (style.latexparam() == "CDATA")
2762 if (style.latextype == LATEX_ENVIRONMENT) break;
2764 if (style.labeltype == LABEL_MANUAL)
2769 sgmlOpenTag(ofs, depth + 1, item_name);
2772 sgmlOpenTag(ofs, depth, style.latexname());
2776 simpleLinuxDocOnePar(ofs, par, depth);
2781 // write closing SGML tags
2782 switch (style.latextype) {
2785 case LATEX_ENVIRONMENT:
2786 case LATEX_ITEM_ENVIRONMENT:
2787 if (style.latexparam() == "CDATA")
2791 sgmlCloseTag(ofs, depth, style.latexname());
2797 for (int i=depth; i >= 0; --i)
2798 sgmlCloseTag(ofs, depth, environment_stack[i]);
2802 sgmlCloseTag(ofs, 0, top_element);
2806 // How to check for successful close
2810 // checks, if newcol chars should be put into this line
2811 // writes newline, if necessary.
2814 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2815 string::size_type newcol)
2818 if (colcount > lyxrc.ascii_linelen) {
2820 colcount = newcol; // assume write after this call
2835 string tag_name(PAR_TAG const & pt) {
2837 case NONE: return "!-- --";
2838 case TT: return "tt";
2839 case SF: return "sf";
2840 case BF: return "bf";
2841 case IT: return "it";
2842 case SL: return "sl";
2843 case EM: return "em";
2850 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2852 p1 = static_cast<PAR_TAG>(p1 | p2);
2857 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2859 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2865 // Handle internal paragraph parsing -- layout already processed.
2866 void Buffer::simpleLinuxDocOnePar(ostream & os,
2868 Paragraph::depth_type /*depth*/)
2870 LyXLayout const & style = textclasslist.Style(params.textclass,
2872 string::size_type char_line_count = 5; // Heuristic choice ;-)
2874 // gets paragraph main font
2877 if (style.labeltype == LABEL_MANUAL) {
2878 font_old = style.labelfont;
2881 font_old = style.font;
2885 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2886 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2887 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2890 stack<PAR_TAG> tag_state;
2891 // parsing main loop
2892 for (pos_type i = 0; i < par->size(); ++i) {
2894 PAR_TAG tag_close = NONE;
2895 list < PAR_TAG > tag_open;
2897 LyXFont const font = par->getFont(params, i);
2899 if (font_old.family() != font.family()) {
2900 switch (family_type) {
2901 case LyXFont::SANS_FAMILY:
2904 case LyXFont::TYPEWRITER_FAMILY:
2911 family_type = font.family();
2913 switch (family_type) {
2914 case LyXFont::SANS_FAMILY:
2915 tag_open.push_back(SF);
2917 case LyXFont::TYPEWRITER_FAMILY:
2918 tag_open.push_back(TT);
2925 if (font_old.series() != font.series()) {
2926 switch (series_type) {
2927 case LyXFont::BOLD_SERIES:
2934 series_type = font.series();
2936 switch (series_type) {
2937 case LyXFont::BOLD_SERIES:
2938 tag_open.push_back(BF);
2946 if (font_old.shape() != font.shape()) {
2947 switch (shape_type) {
2948 case LyXFont::ITALIC_SHAPE:
2951 case LyXFont::SLANTED_SHAPE:
2958 shape_type = font.shape();
2960 switch (shape_type) {
2961 case LyXFont::ITALIC_SHAPE:
2962 tag_open.push_back(IT);
2964 case LyXFont::SLANTED_SHAPE:
2965 tag_open.push_back(SL);
2972 if (font_old.emph() != font.emph()) {
2973 if (font.emph() == LyXFont::ON) {
2974 tag_open.push_back(EM);
2983 list < PAR_TAG > temp;
2984 while (!tag_state.empty() && tag_close ) {
2985 PAR_TAG k = tag_state.top();
2987 os << "</" << tag_name(k) << ">";
2994 for(list< PAR_TAG >::const_iterator j = temp.begin();
2995 j != temp.end(); ++j) {
2997 os << "<" << tag_name(*j) << ">";
3000 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
3001 j != tag_open.end(); ++j) {
3003 os << "<" << tag_name(*j) << ">";
3006 char c = par->getChar(i);
3008 if (c == Paragraph::META_INSET) {
3009 Inset * inset = par->getInset(i);
3010 inset->linuxdoc(this, os);
3015 if (style.latexparam() == "CDATA") {
3016 // "TeX"-Mode on == > SGML-Mode on.
3022 if (par->sgmlConvertChar(c, sgml_string)
3023 && !style.free_spacing && !par->isFreeSpacing())
3025 // in freespacing mode, spaces are
3026 // non-breaking characters
3027 if (desc_on) {// if char is ' ' then...
3030 sgmlLineBreak(os, char_line_count, 6);
3034 sgmlLineBreak(os, char_line_count, 1);
3039 char_line_count += sgml_string.length();
3045 while (!tag_state.empty()) {
3046 os << "</" << tag_name(tag_state.top()) << ">";
3050 // resets description flag correctly
3052 // <tag> not closed...
3053 sgmlLineBreak(os, char_line_count, 6);
3059 // Print an error message.
3060 void Buffer::sgmlError(Paragraph * par, int pos,
3061 string const & message) const
3063 // insert an error marker in text
3064 InsetError * new_inset = new InsetError(message);
3065 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
3070 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3072 ofstream ofs(fname.c_str());
3074 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3078 Paragraph * par = paragraph;
3080 niceFile = nice; // this will be used by Insetincludes.
3082 LyXTextClass const & tclass =
3083 textclasslist.TextClass(params.textclass);
3085 LaTeXFeatures features(params, tclass.numLayouts());
3090 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3093 ofs << "<!DOCTYPE " << top_element
3094 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3096 string preamble = params.preamble;
3097 preamble += features.getIncludedFiles(fname);
3098 preamble += features.getLyXSGMLEntities();
3100 if (!preamble.empty()) {
3101 ofs << "\n [ " << preamble << " ]";
3106 string top = top_element;
3108 top += params.language->code();
3111 if (!params.options.empty()) {
3113 top += params.options;
3115 sgmlOpenTag(ofs, 0, top);
3117 ofs << "<!-- DocBook file was created by " << lyx_docversion
3118 << "\n See http://www.lyx.org/ for more information -->\n";
3120 vector<string> environment_stack(10);
3121 vector<string> environment_inner(10);
3122 vector<string> command_stack(10);
3124 bool command_flag = false;
3125 Paragraph::depth_type command_depth = 0;
3126 Paragraph::depth_type command_base = 0;
3127 Paragraph::depth_type cmd_depth = 0;
3128 Paragraph::depth_type depth = 0; // paragraph depth
3131 string command_name;
3137 int desc_on = 0; // description mode
3139 LyXLayout const & style =
3140 textclasslist.Style(params.textclass,
3143 // environment tag closing
3144 for (; depth > par->params().depth(); --depth) {
3145 if (environment_inner[depth] != "!-- --") {
3146 item_name = "listitem";
3147 sgmlCloseTag(ofs, command_depth + depth,
3149 if (environment_inner[depth] == "varlistentry")
3150 sgmlCloseTag(ofs, depth+command_depth,
3151 environment_inner[depth]);
3153 sgmlCloseTag(ofs, depth + command_depth,
3154 environment_stack[depth]);
3155 environment_stack[depth].erase();
3156 environment_inner[depth].erase();
3159 if (depth == par->params().depth()
3160 && environment_stack[depth] != style.latexname()
3161 && !environment_stack[depth].empty()) {
3162 if (environment_inner[depth] != "!-- --") {
3163 item_name= "listitem";
3164 sgmlCloseTag(ofs, command_depth+depth,
3166 if (environment_inner[depth] == "varlistentry")
3168 depth + command_depth,
3169 environment_inner[depth]);
3172 sgmlCloseTag(ofs, depth + command_depth,
3173 environment_stack[depth]);
3175 environment_stack[depth].erase();
3176 environment_inner[depth].erase();
3179 // Write opening SGML tags.
3180 switch (style.latextype) {
3181 case LATEX_PARAGRAPH:
3182 sgmlOpenTag(ofs, depth + command_depth,
3189 _("Error : Wrong depth for "
3190 "LatexType Command.\n"));
3192 command_name = style.latexname();
3194 sgmlparam = style.latexparam();
3195 c_params = split(sgmlparam, c_depth,'|');
3197 cmd_depth = lyx::atoi(c_depth);
3200 if (cmd_depth < command_base) {
3201 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3202 sgmlCloseTag(ofs, j, command_stack[j]);
3203 command_depth = command_base = cmd_depth;
3204 } else if (cmd_depth <= command_depth) {
3205 for (int j = command_depth; j >= int(cmd_depth); --j)
3206 sgmlCloseTag(ofs, j, command_stack[j]);
3207 command_depth = cmd_depth;
3209 command_depth = cmd_depth;
3211 command_depth = command_base = cmd_depth;
3212 command_flag = true;
3214 if (command_stack.size() == command_depth + 1)
3215 command_stack.push_back(string());
3216 command_stack[command_depth] = command_name;
3218 // treat label as a special case for
3219 // more WYSIWYM handling.
3220 // This is a hack while paragraphs can't have
3221 // attributes, like id in this case.
3222 if (par->isInset(0)) {
3223 Inset * inset = par->getInset(0);
3224 Inset::Code lyx_code = inset->lyxCode();
3225 if (lyx_code == Inset::LABEL_CODE){
3226 command_name += " id=\"";
3227 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3228 command_name += "\"";
3233 sgmlOpenTag(ofs, depth + command_depth, command_name);
3234 if (c_params.empty())
3235 item_name = "title";
3237 item_name = c_params;
3238 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3241 case LATEX_ENVIRONMENT:
3242 case LATEX_ITEM_ENVIRONMENT:
3243 if (depth < par->params().depth()) {
3244 depth = par->params().depth();
3245 environment_stack[depth].erase();
3248 if (environment_stack[depth] != style.latexname()) {
3249 if(environment_stack.size() == depth + 1) {
3250 environment_stack.push_back("!-- --");
3251 environment_inner.push_back("!-- --");
3253 environment_stack[depth] = style.latexname();
3254 environment_inner[depth] = "!-- --";
3255 sgmlOpenTag(ofs, depth + command_depth,
3256 environment_stack[depth]);
3258 if (environment_inner[depth] != "!-- --") {
3259 item_name= "listitem";
3261 command_depth + depth,
3263 if (environment_inner[depth] == "varlistentry")
3265 depth + command_depth,
3266 environment_inner[depth]);
3270 if (style.latextype == LATEX_ENVIRONMENT) {
3271 if (!style.latexparam().empty()) {
3272 if(style.latexparam() == "CDATA")
3275 sgmlOpenTag(ofs, depth + command_depth,
3276 style.latexparam());
3281 desc_on = (style.labeltype == LABEL_MANUAL);
3284 environment_inner[depth]= "varlistentry";
3286 environment_inner[depth]= "listitem";
3288 sgmlOpenTag(ofs, depth + 1 + command_depth,
3289 environment_inner[depth]);
3293 sgmlOpenTag(ofs, depth + 1 + command_depth,
3297 sgmlOpenTag(ofs, depth + 1 + command_depth,
3302 sgmlOpenTag(ofs, depth + command_depth,
3307 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3311 // write closing SGML tags
3312 switch (style.latextype) {
3314 if (c_params.empty())
3318 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3320 case LATEX_ENVIRONMENT:
3321 if (!style.latexparam().empty()) {
3322 if(style.latexparam() == "CDATA")
3325 sgmlCloseTag(ofs, depth + command_depth,
3326 style.latexparam());
3329 case LATEX_ITEM_ENVIRONMENT:
3330 if (desc_on == 1) break;
3332 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3334 case LATEX_PARAGRAPH:
3335 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3338 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3344 for (int d = depth; d >= 0; --d) {
3345 if (!environment_stack[depth].empty()) {
3346 if (environment_inner[depth] != "!-- --") {
3347 item_name = "listitem";
3348 sgmlCloseTag(ofs, command_depth + depth,
3350 if (environment_inner[depth] == "varlistentry")
3351 sgmlCloseTag(ofs, depth + command_depth,
3352 environment_inner[depth]);
3355 sgmlCloseTag(ofs, depth + command_depth,
3356 environment_stack[depth]);
3360 for (int j = command_depth; j >= 0 ; --j)
3361 if (!command_stack[j].empty())
3362 sgmlCloseTag(ofs, j, command_stack[j]);
3365 sgmlCloseTag(ofs, 0, top_element);
3368 // How to check for successful close
3372 void Buffer::simpleDocBookOnePar(ostream & os,
3373 Paragraph * par, int & desc_on,
3374 Paragraph::depth_type depth) const
3376 bool emph_flag = false;
3378 LyXLayout const & style = textclasslist.Style(params.textclass,
3381 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3383 int char_line_count = depth;
3384 //if (!style.free_spacing)
3385 // os << string(depth,' ');
3387 // parsing main loop
3388 for (pos_type i = 0; i < par->size(); ++i) {
3389 LyXFont font = par->getFont(params, i);
3391 // handle <emphasis> tag
3392 if (font_old.emph() != font.emph()) {
3393 if (font.emph() == LyXFont::ON) {
3397 os << "</emphasis>";
3403 if ( par->isInset(i) ) {
3404 Inset * inset = par->getInset(i);
3405 // don't print the inset in position 0 if desc_on == 3 (label)
3406 if ( i || desc_on != 3)
3407 inset->docbook(this, os);
3409 char c = par->getChar(i);
3411 par->sgmlConvertChar(c, sgml_string);
3413 if (style.pass_thru) {
3415 } else if(style.free_spacing || par->isFreeSpacing() || c != ' ') {
3417 } else if (desc_on ==1) {
3419 os << "\n</term><listitem><para>";
3429 os << "</emphasis>";
3432 // resets description flag correctly
3434 // <term> not closed...
3437 if(style.free_spacing) os << '\n';
3441 // This should be enabled when the Chktex class is implemented. (Asger)
3442 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3443 // Other flags: -wall -v0 -x
3444 int Buffer::runChktex()
3446 if (!users->text) return 0;
3448 users->owner()->prohibitInput();
3450 // get LaTeX-Filename
3451 string const name = getLatexName();
3452 string path = filePath();
3454 string const org_path = path;
3455 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3459 Path p(path); // path to LaTeX file
3460 users->owner()->message(_("Running chktex..."));
3462 // Remove all error insets
3463 bool const removedErrorInsets = users->removeAutoInsets();
3465 // Generate the LaTeX file if neccessary
3466 makeLaTeXFile(name, org_path, false);
3469 Chktex chktex(lyxrc.chktex_command, name, filePath());
3470 int res = chktex.run(terr); // run chktex
3473 Alert::alert(_("chktex did not work!"),
3474 _("Could not run with file:"), name);
3475 } else if (res > 0) {
3476 // Insert all errors as errors boxes
3477 users->insertErrors(terr);
3480 // if we removed error insets before we ran chktex or if we inserted
3481 // error insets after we ran chktex, this must be run:
3482 if (removedErrorInsets || res){
3486 users->owner()->allowInput();
3492 void Buffer::validate(LaTeXFeatures & features) const
3494 Paragraph * par = paragraph;
3495 LyXTextClass const & tclass =
3496 textclasslist.TextClass(params.textclass);
3498 // AMS Style is at document level
3499 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3500 features.require("amsmath");
3503 // We don't use "lyxerr.debug" because of speed. (Asger)
3504 if (lyxerr.debugging(Debug::LATEX))
3505 lyxerr << "Paragraph: " << par << endl;
3507 // Now just follow the list of paragraphs and run
3508 // validate on each of them.
3509 par->validate(features);
3511 // and then the next paragraph
3515 // the bullet shapes are buffer level not paragraph level
3516 // so they are tested here
3517 for (int i = 0; i < 4; ++i) {
3518 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3519 int const font = params.user_defined_bullets[i].getFont();
3521 int const c = params
3522 .user_defined_bullets[i]
3529 features.require("latexsym");
3531 } else if (font == 1) {
3532 features.require("amssymb");
3533 } else if ((font >= 2 && font <= 5)) {
3534 features.require("pifont");
3539 if (lyxerr.debugging(Debug::LATEX)) {
3540 features.showStruct();
3545 // This function should be in Buffer because it's a buffer's property (ale)
3546 string const Buffer::getIncludeonlyList(char delim)
3549 for (inset_iterator it = inset_iterator_begin();
3550 it != inset_iterator_end(); ++it) {
3551 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3552 InsetInclude * insetinc =
3553 static_cast<InsetInclude *>(*it);
3554 if (insetinc->isIncludeOnly()) {
3557 lst += insetinc->getRelFileBaseName();
3561 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3566 vector<string> const Buffer::getLabelList()
3568 /// if this is a child document and the parent is already loaded
3569 /// Use the parent's list instead [ale990407]
3570 if (!params.parentname.empty()
3571 && bufferlist.exists(params.parentname)) {
3572 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3574 return tmp->getLabelList();
3577 vector<string> label_list;
3578 for (inset_iterator it = inset_iterator_begin();
3579 it != inset_iterator_end(); ++it) {
3580 vector<string> const l = (*it)->getLabelList();
3581 label_list.insert(label_list.end(), l.begin(), l.end());
3587 Buffer::Lists const Buffer::getLists() const
3590 Paragraph * par = paragraph;
3593 std::pair<bool, textclass_type> const tmp =
3594 textclasslist.NumberOfLayout(params.textclass, "Caption");
3595 bool const found = tmp.first;
3596 textclass_type const cap = tmp.second;
3599 // This is the prefered way to to this, but boost::tie can break
3603 boost::tie(found, cap) = textclasslist
3604 .NumberOfLayout(params.textclass, "Caption");
3608 char const labeltype =
3609 textclasslist.Style(params.textclass,
3610 par->getLayout()).labeltype;
3612 if (labeltype >= LABEL_COUNTER_CHAPTER
3613 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3614 // insert this into the table of contents
3615 SingleList & item = l["TOC"];
3618 textclasslist.TextClass(params.textclass).maxcounter());
3619 item.push_back(TocItem(par, depth, par->asString(this, true)));
3621 // For each paragrph, traverse its insets and look for
3625 Paragraph::inset_iterator it =
3626 par->inset_iterator_begin();
3627 Paragraph::inset_iterator end =
3628 par->inset_iterator_end();
3630 for (; it != end; ++it) {
3631 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3633 static_cast<InsetFloat*>(*it);
3635 string const type = il->type();
3637 // Now find the caption in the float...
3638 // We now tranverse the paragraphs of
3640 Paragraph * tmp = il->inset.paragraph();
3642 if (tmp->layout == cap) {
3643 SingleList & item = l[type];
3645 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3646 item.push_back(TocItem(tmp, 0 , str));
3653 lyxerr << "caption not found" << endl;
3662 // This is also a buffer property (ale)
3663 vector<pair<string, string> > const Buffer::getBibkeyList()
3665 /// if this is a child document and the parent is already loaded
3666 /// Use the parent's list instead [ale990412]
3667 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3668 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3670 return tmp->getBibkeyList();
3673 vector<pair<string, string> > keys;
3674 Paragraph * par = paragraph;
3677 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3678 par->asString(this, false)));
3682 // Might be either using bibtex or a child has bibliography
3684 for (inset_iterator it = inset_iterator_begin();
3685 it != inset_iterator_end(); ++it) {
3686 // Search for Bibtex or Include inset
3687 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3688 vector<pair<string,string> > tmp =
3689 static_cast<InsetBibtex*>(*it)->getKeys(this);
3690 keys.insert(keys.end(), tmp.begin(), tmp.end());
3691 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3692 vector<pair<string,string> > const tmp =
3693 static_cast<InsetInclude*>(*it)->getKeys();
3694 keys.insert(keys.end(), tmp.begin(), tmp.end());
3703 bool Buffer::isDepClean(string const & name) const
3705 DEPCLEAN * item = dep_clean;
3706 while (item && item->master != name)
3708 if (!item) return true;
3713 void Buffer::markDepClean(string const & name)
3716 dep_clean = new DEPCLEAN;
3717 dep_clean->clean = true;
3718 dep_clean->master = name;
3719 dep_clean->next = 0;
3721 DEPCLEAN * item = dep_clean;
3722 while (item && item->master != name)
3727 item = new DEPCLEAN;
3729 item->master = name;
3736 bool Buffer::dispatch(string const & command)
3738 // Split command string into command and argument
3740 string line = frontStrip(command);
3741 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3743 return dispatch(lyxaction.LookupFunc(cmd), arg);
3747 bool Buffer::dispatch(int action, string const & argument)
3749 bool dispatched = true;
3752 Exporter::Export(this, argument, false);
3762 void Buffer::resizeInsets(BufferView * bv)
3764 /// then remove all LyXText in text-insets
3765 Paragraph * par = paragraph;
3766 for (; par; par = par->next()) {
3767 par->resizeInsetsLyXText(bv);
3772 void Buffer::redraw()
3779 void Buffer::changeLanguage(Language const * from, Language const * to)
3782 ParIterator end = par_iterator_end();
3783 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3784 (*it)->changeLanguage(params, from, to);
3788 bool Buffer::isMultiLingual()
3790 ParIterator end = par_iterator_end();
3791 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3792 if ((*it)->isMultiLingual(params))
3799 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
3802 it = par->InsetIterator(pos);
3803 if (it == par->inset_iterator_end()) {
3810 void Buffer::inset_iterator::setParagraph()
3813 it = par->inset_iterator_begin();
3814 if (it != par->inset_iterator_end())
3819 // We maintain an invariant that whenever par = 0 then it = 0
3823 Inset * Buffer::getInsetFromID(int id_arg) const
3825 for (inset_iterator it = inset_const_iterator_begin();
3826 it != inset_const_iterator_end(); ++it)
3828 if ((*it)->id() == id_arg)
3830 Inset * in = (*it)->getInsetFromID(id_arg);
3838 Paragraph * Buffer::getParFromID(int id) const
3840 if (id < 0) return 0;
3841 Paragraph * par = paragraph;
3843 if (par->id() == id) {
3846 Paragraph * tmp = par->getParFromID(id);
3856 ParIterator Buffer::par_iterator_begin()
3858 return ParIterator(paragraph);
3862 ParIterator Buffer::par_iterator_end()
3864 return ParIterator();